<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Brucalipto.org &#187; Java</title>
	<atom:link href="http://www.brucalipto.org/category/java/feed" rel="self" type="application/rss+xml" />
	<link>http://www.brucalipto.org</link>
	<description>Tenete la porta aperta...</description>
	<lastBuildDate>Thu, 24 Nov 2011 08:59:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Log4j tutorial</title>
		<link>http://www.brucalipto.org/java/log4j-tutorial</link>
		<comments>http://www.brucalipto.org/java/log4j-tutorial#comments</comments>
		<pubDate>Mon, 14 Feb 2005 08:12:54 +0000</pubDate>
		<dc:creator>apiero</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://localhost/wordpress/java/log4j-tutorial</guid>
		<description><![CDATA[Log4j is a powerful Java API for logging and its worst defect is documentation: yes the javadoc are available but if you are looking for a simple setup or for a first time setup things become difficult. Here is the &#8220;tutorial&#8221; I wish I had at the time I started using log4j. What is log4j? [...]]]></description>
			<content:encoded><![CDATA[<p>Log4j is a powerful Java API for logging and its worst defect is documentation: yes the javadoc are available but if you are looking for a simple setup or for a first time setup things become difficult. Here is the &#8220;tutorial&#8221; I wish I had at the time I started using log4j.<span id="more-19"></span></p>
<h2>What is log4j?</h2>
<p>As you can read in <a href="http://logging.apache.org/log4j/docs/">log4j homepage</a>:</p>
<p class="quoteText">With log4j it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost. Logging behavior can be controlled by editing a configuration file, without touching the application binary.</p>
<p>So log4j is a Java API that let you insert in your code logging facilities that you can control using a specific configuration file: this way, for example, you can turn debugging info on or off simply touching the config file without looking throughout all your code looking for debug statements.<br />
From a user perspective log4j is mainly composed by two objects: <em>loggers</em> and <em>appenders</em>.  Let us have a look about these objects.</p>
<h2>Logger</h2>
<p>Here is the definitions from <code>org.apache.log4j.Logger</code> javadoc:</p>
<p class="quoteText">This is the central class in the log4j package. Most logging operations, except configuration, are done through this class.</p>
<p>As you can understand the logger is the programmer&#8217;s best friend: using the methods of Logger you really do logging.<br />
There are mainly two ways you can get a Logger (both using static methods):</p>
<p class="quoteCode">Logger log = Logger.getLogger(&#8220;myLogger&#8221;);</p>
<p>Loggers are hierarchically organized starting from the <em>root logger</em> that is the parent of all loggers. If you want to get an instance of the <em>root logger</em> you must use:</p>
<p class="quoteCode">Logger rootLog = Logger.getRootLogger();</p>
<p>If you think that using</p>
<p class="quoteCode">Logger log = Logger.getLogger(&#8220;root&#8221;);</p>
<p>is a good idea you are wrong: with these instructions you get a Logger called <em>root</em> that is the son of the real <em>root logger</em>.</p>
<p>Loggers give you different levels of logging:</p>
<ul>
<li>DEBUG: for simple debug informations.</li>
<li>INFO: when you have to log something informative.</li>
<li>WARN: when something not so normal is happening in your code.</li>
<li>ERROR: use this to log error conditions in your code.</li>
<li>FATAL: guess what?</li>
</ul>
<p><a class="zip" href="http://www.brucalipto.org/files/Log4j_01.zip">Here</a> you can find a simple java                         class that show you a Logger instantiation and usage.</p>
<h2>Appender</h2>
<p>The <em>appender</em> is somewhat hidden to programmer&#8217;s view: usually you will never use directly an <em>appender</em> (eg: you will never instantiate it) but it is used by the logger. Simply put the <em>appender</em> is the object that does the dirty work of outputting your own logs: you use a ConsoleAppender if you want your logs to appear on the console, you use a FileAppender if you want to write your                         logs on the disk etc. etc. You can have more than one <em>appender</em> for each <em>logger</em> so you can have output distributed on more places. Last but not least you can set a threshold for every appender making it possible to have different level of &#8216;debug information&#8217; in different places.</p>
<h2>It is configuration time!</h2>
<p>An example is better than many words:</p>
<p class="quoteCode"># Here is the definition of the rootLogger:<br />
# it has to output all logs (DEBUG is the lowest level)<br />
# it has to output using both &#8216;console&#8217; and &#8216;file&#8217; appender<br />
log4j.rootLogger=DEBUG, console, file<br />
# The appender called &#8216;console&#8217; is of type ConsoleAppender<br />
# This appender shows you all info for better debugging<br />
# Its output is formatted using the inserted ConversionPattern<br />
log4j.appender.console=org.apache.log4j.ConsoleAppender<br />
log4j.appender.console.Threshold=DEBUG<br />
log4j.appender.console.layout=org.apache.log4j.PatternLayout<br />
log4j.appender.console.layout.ConversionPattern=%d %5p %c (%F:%L) &#8211; %m%n<br />
# The appender called &#8216;file&#8217; is of type FileAppender<br />
# This appender shows you only messages ABOVE the INFO level<br />
# It writes in file &#8216;test.log&#8217; located in the directory<br />
# stored in &#8216;user.home&#8217; system property.<br />
# Its output is formatted using the inserted ConversionPattern<br />
log4j.appender.file=org.apache.log4j.FileAppender<br />
log4j.appender.file.Threshold=INFO<br />
log4j.appender.file.File=${user.home}/test.log<br />
log4j.appender.file.layout=org.apache.log4j.PatternLayout<br />
log4j.appender.file.layout.ConversionPattern=%d %5p %c (%F:%L) &#8211; %m%n</p>
<p><a class="zip" href="http://www.brucalipto.org/files/Log4j_02.zip">Here</a> you can find a simple archive containing a sources, executables and configuration files you can look at to better understand what I was saying.</p>
<p>See on <a href="#appendixA">&#8216;Appendix A&#8217;</a> about conversion patterns.</p>
<p>See on <a href="#appendixB">&#8216;Appendix B&#8217;</a> about variable expansion.</p>
<p>Now that you have a configuration file you have to tell log4j to use it and you have two possibilities: put it in the classpath calling it <span class="quoteCode">log4j.properties</span> or use <code>org.apache.log4j.PropertyConfigurator</code> to load it through the <code>configure()</code> method as you can find in the archive.</p>
<h2><a title="appendixA" name="appendixA"></a>Appendix A</h2>
<p>Conversion pattern are listed in the javadoc of                         <code>org.apache.log4j.PatternLayout</code> and reported here for                         simplicity:</p>
<table style="background-color: #999999" border="0" cellpadding="8">
<tbody>
<tr>
<td style="background-color: #eeffee" align="center"><strong>c</strong></td>
<td style="background-color: #eeffee">Used to output the category of the logging event. The                             category conversion specifier can be optionally followed by                             <em>precision specifier</em>, that is a decimal constant in                             brackets.If a precision specifier is given, then only the corresponding                             number of right most components of the category name will be                             printed. By default the category name is printed in full.For example, for the category name &#8220;a.b.c&#8221; the pattern                             <strong>%c{2}</strong> will output &#8220;b.c&#8221;.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>C</strong></td>
<td style="background-color: #eeffee">Used to output the fully qualified class name of the caller                             issuing the logging request. This conversion specifier                             can be optionally followed by <em>precision specifier</em>, that                             is a decimal constant in brackets.If a precision specifier is given, then only the corresponding                             number of right most components of the class name will be                             printed. By default the class name is output in fully qualified form.For example, for the class name &#8220;org.apache.xyz.SomeClass&#8221;, the                             pattern <strong>%C{1}</strong> will output &#8220;SomeClass&#8221;.<strong>WARNING</strong> Generating the caller class information is                             slow. Thus, it&#8217;s use should be avoided unless execution speed is                             not an issue.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>d</strong></td>
<td style="background-color: #eeffee">Used to output the date of                             the logging event. The date conversion specifier may be                             followed by a <em>date format specifier</em> enclosed between                             braces. For example, <strong>%d{HH:mm:ss,SSS}</strong> or                              <strong>%d{dd MMM yyyy HH:mm:ss,SSS}</strong>.  If no                             date format specifier is given then ISO8601 format is                             assumed.The date format specifier admits the same syntax as the                             time pattern string of the <a href="http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html"><code>SimpleDateFormat</code></a>. Although part of the standard                             JDK, the performance of <code>SimpleDateFormat</code> is                             quite poor.For better results it is recommended to use the log4j date                             formatters. These can be specified using one of the strings                             &#8220;ABSOLUTE&#8221;, &#8220;DATE&#8221; and &#8220;ISO8601&#8243; for specifying <a href="http://logging.apache.org/log4j/docs/api/org/apache/log4j/helpers/AbsoluteTimeDateFormat.html"><code>AbsoluteTimeDateFormat</code></a>, <a href="http://logging.apache.org/log4j/docs/api/org/apache/log4j/helpers/DateTimeDateFormat.html"><code>DateTimeDateFormat</code></a> and respectively <a href="http://logging.apache.org/log4j/docs/api/org/apache/log4j/helpers/ISO8601DateFormat.html"><code>ISO8601DateFormat</code></a>. For example, <strong>%d{ISO8601}</strong> or                              <strong>%d{ABSOLUTE}</strong>.These dedicated date formatters perform significantly                             better than <a href="http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html"><code>SimpleDateFormat</code></a>.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>F</strong></td>
<td style="background-color: #eeffee">Used to output the file name where the logging request was                             issued.<strong>WARNING</strong> Generating caller location information is                             extremely slow. It&#8217;s use should be avoided unless execution speed                             is not an issue.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>l</strong></td>
<td style="background-color: #eeffee">Used to output location information of the caller which generated                             the logging event.The location information depends on the JVM implementation but                             usually consists of the fully qualified name of the calling                             method followed by the callers source the file name and line                             number between parentheses.The location information can be very useful. However, it&#8217;s                             generation is <em>extremely</em> slow. It&#8217;s use should be avoided                             unless execution speed is not an issue.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>L</strong></td>
<td style="background-color: #eeffee">Used to output the line number from where the logging request                             was issued.<strong>WARNING</strong> Generating caller location information is                             extremely slow. It&#8217;s use should be avoided unless execution speed                             is not an issue.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>m</strong></td>
<td style="background-color: #eeffee">Used to output the application supplied message associated with                             the logging event.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>M</strong></td>
<td style="background-color: #eeffee">Used to output the method name where the logging request was                             issued.<strong>WARNING</strong> Generating caller location information is                             extremely slow. It&#8217;s use should be avoided unless execution speed                             is not an issue.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>n</strong></td>
<td style="background-color: #eeffee">Outputs the platform dependent line separator character or                             characters.This conversion character offers practically the same                             performance as using non-portable line separator strings such as                             &#8220;\n&#8221;, or &#8220;\r\n&#8221;. Thus, it is the preferred way of specifying a                             line separator.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>p</strong></td>
<td style="background-color: #eeffee">Used to output the priority of the logging event.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>r</strong></td>
<td style="background-color: #eeffee">Used to output the number of milliseconds elapsed since the start                             of the application until the creation of the logging event.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>t</strong></td>
<td style="background-color: #eeffee">Used to output the name of the thread that generated the                             logging event.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>x</strong></td>
<td style="background-color: #eeffee">Used to output the NDC (nested diagnostic context) associated                             with the thread that generated the logging event.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>X</strong></td>
<td style="background-color: #eeffee">Used to output the MDC (mapped diagnostic context) associated                             with the thread that generated the logging event. The <strong>X</strong> conversion character <em>must</em> be followed by the key for the                             map placed between braces, as in <strong>%X{clientNumber}</strong> where                             <code>clientNumber</code> is the key. The value in the MDC                             corresponding to the key will be output.See <a href="http://logging.apache.org/log4j/docs/api/org/apache/log4j/MDC.html"><code>MDC</code></a> class for more details.</td>
</tr>
<tr>
<td style="background-color: #eeffee" align="center"><strong>%</strong></td>
<td style="background-color: #eeffee">The sequence %% outputs a single percent sign.</td>
</tr>
</tbody>
</table>
<h2><a title="appendixB" name="appendixB"></a>Appendix B</h2>
<p>Here is what the <code>org.apache.log4j.PropertyConfigurator</code> says about variable expansion:</p>
<p class="quoteText">All option values admit variable substitution. The syntax of variable substitution is similar to that of Unix shells. The string between an opening &#8220;${&#8221; and closing &#8220;}&#8221; is interpreted as a key. The value of the substituted variable can be defined as a system property or in the configuration file itself. The value of the key is first searched in the system properties, and if not found there, it is then searched in the configuration file being parsed. The corresponding value replaces the ${variableName} sequence. For example, if java.home system property is set to /home/xyz, then every occurrence of the sequence ${java.home} will be interpreted as /home/xyz.</p>
<p>One of the nicest feature of                         <code>org.apache.log4j.PropertyConfigurator</code> I found is that you                         can use it to dinamically configure/reconfigure log4j. As stated in the javadoc the <code>configure()</code> method of this                         class can get a <code>java.util.Properties</code> as parameter: you                         can simply load a properties file that looks like the final result                         you want and then you can manipulate it runtime (as                         <code>java.util.Properties</code>) and pass it to                         <code>PropertyConfigurator</code>.                         With this method you can do whatever you want on log4j: create                         loggers/appenders runtime, change log level etc. etc.</p>
<p><a href="mailto:ottuzzi@gmail.com"><img src="http://www.brucalipto.org/wp-content/uploads/2008/02/ottuzzigoogle.png" alt="ottuzzigoogle Log4j tutorial" align="right" title="Log4j tutorial" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.brucalipto.org/java/log4j-tutorial/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Implementazione di un QueueRequestor con timeout.</title>
		<link>http://www.brucalipto.org/java/implementazione-di-un-queuerequestor-con-timeout</link>
		<comments>http://www.brucalipto.org/java/implementazione-di-un-queuerequestor-con-timeout#comments</comments>
		<pubDate>Mon, 26 Apr 2004 15:45:10 +0000</pubDate>
		<dc:creator>apiero</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JMS]]></category>

		<guid isPermaLink="false">http://localhost/wordpress/unclassified/implementazione-di-un-queuerequestor-con-timeout</guid>
		<description><![CDATA[Mi sono trovato nella necessità di dover usare delle code JMS per lo scambio di messaggi tra due applicazioni. L&#8217;idea era che a domanda doveva seguire una risposta in maniera sincrona e le API javax.jms mettono a disposizione per lo scopo l&#8217;oggetto javax.jms.QueueRequestor. Il problema Il problema del QueueRequestor è che non ha un timeout [...]]]></description>
			<content:encoded><![CDATA[<p>Mi sono trovato nella necessità di dover usare delle code JMS per lo scambio di messaggi tra due applicazioni. L&#8217;idea era che a domanda doveva seguire una risposta in maniera sincrona e le API javax.jms mettono a disposizione per lo scopo l&#8217;oggetto <em>javax.jms.QueueRequestor</em>.<span id="more-7"></span></p>
<h2>Il problema</h2>
<p>Il problema del QueueRequestor è che non ha un timeout dopo il quale ritorna in qualsiasi caso: se non si ottiene una risposta                         il QueueRequestor non fa procedere l&#8217;esecuzione e ciò non è bello.</p>
<h2>La soluzione</h2>
<p>Per la soluzione sono stato illuminato da <a href="http://groups.google.com/groups?hl=it&amp;lr=&amp;ie=UTF-8&amp;oe=UTF-8&amp;threadm=3D9D9C2B.A49F993F%40replyinnewsgroup.com&amp;rnum=1&amp;prev=/groups%3Fq%3Dqueuerequestor%2520timeout%2520%26hl%3Dit%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26sa%3DN%26tab%3Dwg">questo</a>                         post sui newsgroup: qui si afferma che il QueueRequestor è nient&#8217;altro che un wrapper di una serie di API pubbliche del package <em>javax.jms</em>.<br />
Ecco una classe d&#8217;esempio che si interfaccia ad una coda JMS Tibco:<br />
import javax.jms.*;<br />
import java.io.Serializable;<br />
import com.tibco.tibjms.TibjmsQueueConnectionFactory;</p>
<p>public class QueueRequestorImpl<br />
{<br />
private final static String QUEUE_PATH = &#8220;tcp://localhost:7222&#8243;;<br />
private final static String QUEUE_NAME = &#8220;testQueue&#8221;;<br />
private final static long   QUEUE_TIMEOUT = 10000;</p>
<p>public static Object connect(Serializable request)<br />
{<br />
QueueConnection queueConnection = null;<br />
QueueSession queueSession = null;<br />
Queue queue = null;<br />
ObjectMessage objmessage = null;</p>
<p>TemporaryQueue tempQueue = null;<br />
QueueSender qSender = null;<br />
QueueReceiver qReceiver = null;</p>
<p>try<br />
{<br />
QueueConnectionFactory queueConnectionFactory = null;<br />
queueConnectionFactory = new TibjmsQueueConnectionFactory(QUEUE_PATH);<br />
queueConnection = queueConnectionFactory.createQueueConnection();<br />
queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);<br />
queue = getQueue(QUEUE_NAME, queueSession);</p>
<p>tempQueue = queueSession.createTemporaryQueue();<br />
qReceiver = queueSession.createReceiver(tempQueue);<br />
qSender = queueSession.createSender(queue);<br />
}<br />
catch (Exception e)<br />
{<br />
return null;<br />
}<br />
finally<br />
{<br />
try<br />
{<br />
if (qReceiver!=null) qReceiver.close();<br />
if (qSender!=null) qSender.close();<br />
if (tempQueue!=null) tempQueue.delete();<br />
if (queueConnection!=null) queueConnection.close();<br />
}catch (Exception e){;}<br />
}<br />
try<br />
{<br />
objmessage = queueSession.createObjectMessage();<br />
objmessage.setJMSReplyTo(tempQueue);<br />
queueConnection.start();<br />
objmessage.setObject(request);</p>
<p>long elapsedTime = System.currentTimeMillis();<br />
qSender.send(objmessage);<br />
Message response = qReceiver.receive(QUEUE_TIMEOUT);<br />
elapsedTime = System.currentTimeMillis() &#8211; elapsedTime;<br />
System.out.println(&#8220;QueueRequestorImpl Response Time: &#8221; + elapsedTime);</p>
<p>if (response!=null)<br />
System.out.println(&#8220;Message RECEIVED.&#8221;);<br />
else<br />
{<br />
System.out.println(&#8220;Message TIMEOUT.&#8221;);<br />
return null;<br />
}</p>
<p>String sendIDString = objmessage.getJMSMessageID();<br />
String respIDString = response.getJMSCorrelationID();<br />
if (!sendIDString.equals(respIDString))<br />
{<br />
String msg = &#8220;&#8216;&#8221;+sendIDString+&#8221;&#8216;!=&#8217;&#8221;+respIDString+&#8221;&#8216;&#8221;;<br />
System.out.println(&#8220;JMSCorrelationID MISMATCH (&#8220;+msg+&#8221;).&#8221;);<br />
return null;<br />
}</p>
<p>return response;<br />
}<br />
catch (Exception e)<br />
{<br />
System.out.println(&#8220;JMSException &#8216;&#8221;+e.getMessage()+&#8221;&#8216;&#8221;);<br />
return null;<br />
}<br />
finally<br />
{<br />
try<br />
{<br />
if (qReceiver!=null) qReceiver.close();<br />
if (qSender!=null) qSender.close();<br />
if (tempQueue!=null) tempQueue.delete();<br />
if (queueConnection!=null) queueConnection.close();<br />
}<br />
catch (Exception e){;}<br />
}<br />
}</p>
<p>public static Queue getQueue(String name, QueueSession session)<br />
{<br />
try<br />
{<br />
return session.createQueue(name);<br />
}<br />
catch(JMSException e)<br />
{<br />
throw new RuntimeException(&#8220;Session closed&#8221;);<br />
}<br />
}<br />
}</p>
<h2>Conclusione</h2>
<p>Come si può vedere il problema è facilmente aggirabile,                         basta solo fare un po&#8217; di googling e cercare nei javadoc.</p>
<p><a href="mailto:ottuzzi@gmail.com"><img src="http://localhost/wordpress/wp-content/uploads/2008/02/ottuzziemail.png" alt="ottuzziemail Implementazione di un QueueRequestor con timeout."  title="Implementazione di un QueueRequestor con timeout." /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.brucalipto.org/java/implementazione-di-un-queuerequestor-con-timeout/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

