<?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>FactoryPattern.com &#187; java snippets</title>
	<atom:link href="http://www.factorypattern.com/category/java-snippets/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.factorypattern.com</link>
	<description>Just another Object Oriented Weblog</description>
	<lastBuildDate>Thu, 26 Jan 2012 20:21: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>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>How to Obtain the IP Address and DNS Details for a domain in java</title>
		<link>http://www.factorypattern.com/how-to-obtain-the-ip-address-and-dns-details-for-a-domain-in-java/</link>
		<comments>http://www.factorypattern.com/how-to-obtain-the-ip-address-and-dns-details-for-a-domain-in-java/#comments</comments>
		<pubDate>Tue, 15 Nov 2011 16:47:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java snippets]]></category>
		<category><![CDATA[dns]]></category>
		<category><![CDATA[dns records]]></category>
		<category><![CDATA[domain]]></category>
		<category><![CDATA[domains]]></category>
		<category><![CDATA[hostname]]></category>
		<category><![CDATA[internet]]></category>
		<category><![CDATA[ip]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/?p=155</guid>
		<description><![CDATA[In the following snippet you can find out how to use the InetAddress class to obtain the ip of the server where a domain is hosted along with the DNS information. Using this class you&#8217;ll obtain only the technical DNS details(name server, SOA &#038; MX records), not the emails or the names of the domain [...]]]></description>
			<content:encoded><![CDATA[<p>In the following snippet you can find out how to use the <a href="http://download.oracle.com/javase/1,5.0/docs/api/java/net/InetAddress.html">InetAddress</a> class to obtain the ip of the server where a domain is hosted along with the DNS information. Using this class you&#8217;ll obtain only the technical DNS details(name server, SOA &#038; MX records), not the emails or the names of the domain owners.<br />
<span id="more-155"></span></p>
<pre name="code" class="java">
	static public void printDomainDetails(String domain)
			throws UnknownHostException, NamingException
	{
		InetAddress netAddress = InetAddress.getByName(domain);
		String ipAddress = netAddress.getHostAddress();

		System.out.println(domain + " / " + ipAddress);

		InitialDirContext initialDirContext = new InitialDirContext();

		// get the DNS records:
		Attributes attributes = initialDirContext.getAttributes(
												"dns:/" + domain);

		// get an enumeration of the attributes:
		NamingEnumeration&lt;? extends Attribute&gt; attributeEnumeration
												 = attributes.getAll();

		System.out.println("DNS Details:");
		while (attributeEnumeration.hasMore())
		{
			Attribute attribute = attributeEnumeration.next();
			System.out.println(attribute.toString());
		}
		attributeEnumeration.close();
	}
</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/how-to-obtain-the-ip-address-and-dns-details-for-a-domain-in-java/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/how-to-obtain-the-ip-address-and-dns-details-for-a-domain-in-java/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-obtain-the-ip-address-and-dns-details-for-a-domain-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Date Time Manipulation In Java</title>
		<link>http://www.factorypattern.com/date-time-manipulation-in-java/</link>
		<comments>http://www.factorypattern.com/date-time-manipulation-in-java/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 15:38:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java foundation]]></category>
		<category><![CDATA[java snippets]]></category>
		<category><![CDATA[Basic]]></category>
		<category><![CDATA[Date]]></category>
		<category><![CDATA[snippets]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/?p=143</guid>
		<description><![CDATA[There are 2 useful classes in java to manipulate dates: java.util.Date and java.util.Calendar. Another useful class to format and parse string dates is java.text.SimpleDateFormat. Get Current Date Date date = new Date(); Calendar calendar = Calendar.getInstance(); Convert from/to Date to/from Calendar Date date = new Date(); Calendar calendar = Calendar.getInstance(); date = calendar.time(); calendar.setTime(date); Format [...]]]></description>
			<content:encoded><![CDATA[<p>There are 2 useful classes in java to manipulate dates: <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/Date.html">java.util.Date</a> and <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html">java.util.Calendar</a>. Another useful class to format and parse string dates is <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html">java.text.SimpleDateFormat</a>.<span id="more-143"></span></p>
<h2>Get Current Date</h2>
<pre name="code" class="java">
Date date = new Date();
Calendar calendar = Calendar.getInstance();
</pre>
<h2>Convert from/to Date to/from Calendar</h2>
<pre name="code" class="java">
Date date = new Date();
Calendar calendar = Calendar.getInstance();

date = calendar.time();
calendar.setTime(date);
</pre>
<h2>Format Date To String</h2>
<pre name="code" class="java">
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateAsString = dateFormat.format(date);
System.out.println(dateAsString);
</pre>
<h2>Parse Date String</h2>
<pre name="code" class="java">
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(dateAsString);
</pre>
<h2>Add/Substact Days to Current Date</h2>
<pre name="code" class="java">
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance(); // get current date as calendar object
calendar.add(Calendar.DATE, 1);	//Add 1 day to calendar date
calendar.add(Calendar.DATE, -2);	//Substract 2 days to calendar date
String dateAsString = dateformat.format(calendar.getTime());
System.out.println(dateAsString);
</pre>
<h2>Add/Substact Years/Months/Days/Hours/Minutes/Seconds to Current Date</h2>
<pre name="code" class="java">
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance(); // get current date as calendar object
calendar.add(Calendar.YEAR, 1);	//Add 1 year to calendar date
calendar.add(Calendar.YEAR, -2);	//Substract 2 years to calendar date
calendar.add(Calendar.MONTH, 1);	//Add 1 month to calendar date
calendar.add(Calendar.MONTH, -2);	//Substract 2 months to calendar date
calendar.add(Calendar.DATE, 1);	//Add 1 day to calendar date
calendar.add(Calendar.DATE, -2);	//Substract 2 days to calendar date
calendar.add(Calendar.HOUR, 1);	//Add 1 day to hourr date
calendar.add(Calendar.HOUR, -2);       //Substract 2 hours to calendar date
calendar.add(Calendar.MINUTE, 1);       //Add 1 minute to calendar date
calendar.add(Calendar.MINUTE, -2);      //Substract 2 minutes to calendar date
calendar.add(Calendar.SECOND, 1);       //Add 1 second to calendar date
calendar.add(Calendar.SECOND, -2);     //Substract 2 seconds to calendar date
String dateAsString = dateformat.format(calendar.getTime());
System.out.println(dateAsString);
</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/date-time-manipulation-in-java/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/date-time-manipulation-in-java/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/date-time-manipulation-in-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How To Use JDBC addBatch Method with MySQL for Improved Performance</title>
		<link>http://www.factorypattern.com/how-to-use-jdbc-addbatch-method-with-mysql-for-improved-performance/</link>
		<comments>http://www.factorypattern.com/how-to-use-jdbc-addbatch-method-with-mysql-for-improved-performance/#comments</comments>
		<pubDate>Fri, 10 Dec 2010 16:42:07 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java snippets]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[addBatch]]></category>
		<category><![CDATA[batch]]></category>
		<category><![CDATA[jdbc]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/?p=119</guid>
		<description><![CDATA[When you have to deal with a large amount of data to be operated on mySQL databases, the performance can be dramatically improved using a few simple tweaks. First of all you have to use Statement.addBatch/executeBatch instead of simple execute methods. For each added batch, the jdbc driver will store in local memory and when [...]]]></description>
			<content:encoded><![CDATA[<p>When you have to deal with a large amount of data to be operated on mySQL databases, the performance can be dramatically improved using a few simple tweaks.</p>
<p>First of all you have to use <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Statement.html">Statement</a>.<a href="http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Statement.html#addBatch(java.lang.String)">addBatch</a>/<a href="http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Statement.html#executeBatch()">executeBatch</a> instead of simple <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Statement.html#execute(java.lang.String)">execute</a> methods. For each added batch, the jdbc driver will store in local memory and when the executeBatch is invoked, all the batches are sent at once to the database. This will result in an huge <a href="https://docs.google.com/viewer?url=http://assets.en.oreilly.com/1/event/21/Connector_J%2520Performance%2520Gems%2520Presentation.pdf">speed improvement</a>.<br />
<span id="more-119"></span><br />
When you deal with such operations you should keep an eye one the memory allocated to the java process. The JDBC driver(<a href="http://www.mysql.com/products/connector/">Connector/J</a>) will use the heap memory to build the batch until is executed. In order to make sure you don&#8217;t run out of memory you have to executeBatch method from time to time.</p>
<p>When you deal with mySQL database you can make and additional speed improvement. This can be applied for the cases when you have to insert values in the database(which is the probably the case because 90% of large amount data operations are imports). </p>
<p>When you configure the JDBC connection with &#8220;rewriteBatchedStatements=true&#8221;, the driver takes the statements in the form <em>&#8220;INSERT INTO foo VALUES (&#8230;)&#8221;</em> and rewrites them as <em>&#8220;INSERT INTO foo VALUES (&#8230;), (&#8230;), (&#8230;)&#8221;</em>. You can see here <a href="http://www.jroller.com/mmatthews/entry/speeding_up_batch_inserts_for">benchmarks which records 10x performance increase</a>. Yu have to make sure you have the latest Connector/J version to to squeeze the best performance out of it(at least 5.1.8).</p>
<pre name="code" class="java">
static protected String INSERT_GAME_SQL =
	"INSERT INTO tablename(name, category, title, description"
	", metascore) VALUES(?, ?, ?, ?, ?)";

public void batchInsert()
			throws SQLException {
	try
	{
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		connection = DriverManager.getConnection(
connectionString + "?rewriteBatchStatements=true",user,passwd);

		connection.setAutoCommit(false);
		PreparedStatement statement = connection.prepareStatement(
INSERT_SQL_STATEMENT);

		for (int i = 0; i < limit; i++)
		{
			statement.setString(1,  "value1");
			statement.setString(2,  "value2");
			statement.setString(3,  "value3");
			statement.setString(4,  "value4");
			statement.setInt(5,  134);

			statement.addBatch();

			if ( i % 1000 == 0) {
				statement.executeBatch();// Execute every 1000 items
			}
		}

		statement.executeBatch();
		connection.commit();
	}
	catch(SQLException e)
	{
		connection.rollback();
		throw e;
	}
	finally
	{
		// if not required anymore:
		//close statement
		//close connection
	}
}
</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/how-to-use-jdbc-addbatch-method-with-mysql-for-improved-performance/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/how-to-use-jdbc-addbatch-method-with-mysql-for-improved-performance/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-use-jdbc-addbatch-method-with-mysql-for-improved-performance/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>How To Download a File in Java</title>
		<link>http://www.factorypattern.com/how-to-download-a-file-in-java/</link>
		<comments>http://www.factorypattern.com/how-to-download-a-file-in-java/#comments</comments>
		<pubDate>Wed, 08 Dec 2010 14:53:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java snippets]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[download]]></category>
		<category><![CDATA[java.io]]></category>
		<category><![CDATA[java.net]]></category>
		<category><![CDATA[snippets]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/?p=117</guid>
		<description><![CDATA[Here is a snippet that shows how to download a file in java. The snippet is tested and works just fine: static public void download(String address, String localFileName) throws MalformedURLException , FileNotFoundException , IOException { URL url = new URL(address); OutputStream out = new BufferedOutputStream( new FileOutputStream(localFileName)); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a snippet that shows how to download a file in java. The snippet is tested and works just fine:</p>
<pre name="code" class="java">

	static public void download(String address, String localFileName)
											throws MalformedURLException
												 , FileNotFoundException
												 , IOException
	{

		URL url = new URL(address);

		OutputStream out = new BufferedOutputStream(
								new FileOutputStream(localFileName));
		URLConnection conn = url.openConnection();
		InputStream in = conn.getInputStream();

		byte[] buffer = new byte[1024];
		int numRead;
		int progress = 0;
		while ((numRead = in.read(buffer)) != -1) {
			out.write(buffer, 0, numRead);
			progress += 1024;
			System.out.print("\r" + (int)(progress / 1000)+ "kb");
		}            

		in.close();
		out.close();
	}
</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/how-to-download-a-file-in-java/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/how-to-download-a-file-in-java/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-download-a-file-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use Post Method using Apache HttpClient 4</title>
		<link>http://www.factorypattern.com/how-to-use-post-method-using-apache-httpclient-4/</link>
		<comments>http://www.factorypattern.com/how-to-use-post-method-using-apache-httpclient-4/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 11:16:22 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java snippets]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[httpclient]]></category>
		<category><![CDATA[httpclient 4]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/?p=107</guid>
		<description><![CDATA[HttpClient is an apache java library that can be used to read pages over http. It can be used mainly for webpages and provide a well defined API that can handle Cookies, Sessions,&#8230; It offers support for both Get and Post methods, so it&#8217;s very useful for writing http java clients that can login and [...]]]></description>
			<content:encoded><![CDATA[<p>HttpClient is an apache java library that can be used to read pages over http. It can be used mainly for webpages and provide a well defined API that can handle Cookies, Sessions,&#8230; It offers support for both Get and Post methods, so it&#8217;s very useful for writing http java clients that can login and perform different actions on webpages.</p>
<p>Starting with the version 4 the classes were drastically changed. Old tutorials don&#8217;t works anymore and the class names and methods were changed to some degree which makes old code pretty useless if you want to switch to a version 4.<br />
<span id="more-107"></span><br />
Here is a small snippet which shows how to invoke a webpage via post method and how to pass post parameters. In real scenarios post parameters can be used to pass login informations. The snippet uses the method to <a href="http://www.factorypattern.com/how-to-convert-inputstream-to-string/">Convert Input Stream To String</a> from the previous post:</p>
<pre name="code" class="java">
package com.factorypattern.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class PostRequestClient {

	public static void main(String[] args) throws Exception {

		// prepare post method
		HttpPost post = new HttpPost(&quot;http://mydomain.com/&quot;);

		// add parameters to the post method
        List &lt;NameValuePair&gt; parameters = new ArrayList &lt;NameValuePair&gt;();
        parameters.add(new BasicNameValuePair(&quot;param1&quot;, &quot;value1&quot;));
        parameters.add(new BasicNameValuePair(&quot;param2&quot;, &quot;value2&quot;)); 

        UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8);
        post.setEntity(sendentity); 

        // create the client and execute the post method
		HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(post);

        // retrieve the output and display it in console
        System.out.print(convertInputStreamToString(response.getEntity().getContent()));
        client.getConnectionManager().shutdown();
	}

	/**
	 * method to convert an InputStream to a string using the BufferedReader.readLine() method
	 * this methods reads the InputStream line by line until the null line is encountered
	 * it appends each line to a StringBuilder object for optimal performance
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static String convertInputStreamToString(InputStream inputStream) throws IOException
	{
		if (inputStream != null)
		{
			StringBuilder stringBuilder = new StringBuilder();
			String line;

			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, &quot;UTF-8&quot;));
				while ((line = reader.readLine()) != null)
				{
					stringBuilder.append(line).append(&quot;\n&quot;);
				}
			}
			finally
			{
				inputStream.close();
			}

			return stringBuilder.toString();
		}
		else
		{
			return null;
		}
	}
}
</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/how-to-use-post-method-using-apache-httpclient-4/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/how-to-use-post-method-using-apache-httpclient-4/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-use-post-method-using-apache-httpclient-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Convert InputStream to String</title>
		<link>http://www.factorypattern.com/how-to-convert-inputstream-to-string/</link>
		<comments>http://www.factorypattern.com/how-to-convert-inputstream-to-string/#comments</comments>
		<pubDate>Thu, 16 Sep 2010 14:04:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java snippets]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/?p=93</guid>
		<description><![CDATA[Sometimes I feel there are too many classes in java to work with streams and files. InputStream is the base class of all the classes in Java IO API. The input stream class is intended to be used to read the data from different sources in chunks. This is useful for large streams that don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes I feel there are too many classes in java to work with streams and files. InputStream is the base class of all the classes in Java IO API. The input stream class is intended to be used to read the data from different sources in chunks. This is useful for large streams that don&#8217;t fit in memory. </p>
<p>Lots of libraries returns objects of type InputStream and sometimes you know the stream small and you just need the data as a simple String. Here is the snippet written as a static method to transfer the data from a InputStream to a String.<br />
<span id="more-93"></span><br />
The method reads the InputStream line by line (using BufferedReader.readLine()) until the null line is encountered. It appends each line to a StringBuilder object for optimal performance and returns it as a String:</p>
<pre name="code" class="java">
	/**
	 * method to convert an InputStream to a string using the BufferedReader.readLine() method
	 * this methods reads the InputStream line by line until the null line is encountered
	 * it appends each line to a StringBuilder object for optimal performance
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static String convertInputStreamToString(InputStream inputStream) throws IOException
	{
		if (inputStream != null)
		{
			StringBuilder stringBuilder = new StringBuilder();
			String line;

			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
				while ((line = reader.readLine()) != null)
				{
					stringBuilder.append(line).append("\n");
				}
			}
			finally
			{
				inputStream.close();
			}

			return stringBuilder.toString();
		}
		else
		{
			return null;
		}
	}
</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/how-to-convert-inputstream-to-string/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/how-to-convert-inputstream-to-string/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-convert-inputstream-to-string/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Storing parameters in web.xml: context-param &amp; init-param</title>
		<link>http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/</link>
		<comments>http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/#comments</comments>
		<pubDate>Mon, 04 Aug 2008 22:48:16 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java snippets]]></category>
		<category><![CDATA[java web apps]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/</guid>
		<description><![CDATA[There are two options to store parameters in web.xml: - context parameters &#8211; available to the entire scope of the web application - init parameters &#8211; available in the context of a servlet or filter in the web application Context Parameters &#60;?xml version="1.0" encoding="UTF-8"?&#62; &#60;web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&#62; &#60;context-param&#62; &#60;description&#62;This is a [...]]]></description>
			<content:encoded><![CDATA[<p>There are two options to store parameters in web.xml:<br />
- <strong>context parameters</strong> &#8211; available to the entire scope of the web application<br />
- <strong>init parameters</strong> &#8211; available in the context of a servlet or filter in the web application</p>
<h2>Context Parameters</h2>
<p><span id="more-30"></span></p>
<pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt;
  &lt;context-param&gt;
    &lt;description&gt;This is a context parameter example&lt;/description&gt;
    &lt;param-name&gt;ContextParam&lt;/param-name&gt;
    &lt;param-value&gt;ContextParam value&lt;/param-value&gt;
  &lt;/context-param&gt;
...
&lt;web-app&gt;</code></pre>
<p>The following code can be be invoked from a servlet or a filter to retrieve the ContextParam value. The parameter can be read successfully from any servlet or filter class.</p>
<pre><code>@Override
	public void init(ServletConfig config) throws ServletException {
		String contextParam = config.getServletContext().getInitParameter("ContextParam");
	}

//or
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String contextParam = this.getServletContext().getInitParameter("ContextParam");
		...
	}
	...
}

String value = this.getServletContext().getInitParameter("ContextParam");</code></pre>
<h2>Init Parameters</h2>
<pre><code>...
&lt;servlet&gt;
    &lt;servlet-name&gt;A Servlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;com.controller.TestServlet&lt;/servlet-class&gt;
    &lt;init-param&gt; 
        &lt;description&gt;This is an init parameter example&lt;/description&gt; 
        &lt;param-name&gt;InitParam&lt;/param-name&gt; 
        &lt;param-value&gt;init param value&lt;/param-value&gt; 
    &lt;/init-param&gt; 
&lt;/servlet&gt;
...</code></pre>
<p>The following code can be be invoked to retrieve the value of InitParam. The parameter can be accessed only from com.controller.TestServlet.</p>
<pre><code>public class DefaultController extends HttpServlet
{
	@Override
	public void init(ServletConfig config) throws ServletException {
		String initParam  = config.getInitParameter("InitParam");
	}

//or
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String initParam = getServletConfig().getInitParameter("InitParam");
		...
	}
	...
}</code></pre>
<h2>Iterating through context-params and init-params</h2>
<p>It&#8217;s possible to iterate through the paramters if required:</p>
<pre><code>public class DefaultController extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Enumeration contextParams = getServletContext().getInitParameterNames();

		Sytem.out.println("context-params: ");
		while (params.hasMoreElements()) {
			String name = (String) params.nextElement();
			Sytem.out.println(name + " = " + config.getInitParameter(name));
		}

		Enumeration initParams = getServletConfig().getInitParameterNames();

		Sytem.out.println("init-params: ");
		while (params.hasMoreElements()) {
			String name = (String) params.nextElement();
			Sytem.out.println(name + " = " + config.getInitParameter(name));
		}

		...
	}
	...
}</code></pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>How to Read/Write Java Properties Files</title>
		<link>http://www.factorypattern.com/how-to-readwrite-java-properties-files/</link>
		<comments>http://www.factorypattern.com/how-to-readwrite-java-properties-files/#comments</comments>
		<pubDate>Wed, 30 Jul 2008 16:18:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[java snippets]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[java properties]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/how-to-readwrite-java-properties-files/</guid>
		<description><![CDATA[Java properties files are just simple text files that are widely used in Java to store different properties which should not be hard coded in java source files. By convention, properties files should have the .properties extension. They have a simple structure, each line defining a key/value pair. It is also possible to define larger [...]]]></description>
			<content:encoded><![CDATA[<p>Java properties files are just simple text files that are widely used in Java to store different properties which should not be hard coded in java source files. By convention, properties files should have the .properties extension. They have a simple structure, each line defining a key/value pair. It is also possible to define larger text values on multiple lines. The main benefit of the properties files is the one that they can be easily edited by hand using any text editor.<br />
<span id="more-27"></span><br />
Java properties files can be stored in </p>
<ul>
<li>in a standard folder, to a known location</li>
<li>in classpath (this way it can be packed in a jar file, made is accessible when the application runs)</li>
</ul>
<p>There are several options to handle the Java properties files:</p>
<h2>To read java properties files from the classpath:</h2>
<p>The properties files can be stored in the classpath. This way they can be put inside jar files and it&#8217;s really useful for web applications when the absolute location of the properties files is not known. When I tested this in an web application it didn&#8217;t work:</p>
<pre><code>Properties properties = new Properties() ;
URL url =  ClassLoader.getSystemResource("test.properties");
properties.load(new FileInputStream(new File(url.getFile())));</code></pre>
<h2>To read java properties files from the classpath in a web application:</h2>
<p>The following example works to load the properties files in a web application. This snippet was tested on Tomcat 5.5. The &#8216;/&#8217; represents the root of the class path. Otherwise the properties file location is considered relatively to &#8220;this&#8221; class (or to MyClass for the second example):</p>
<pre><code>Properties properties = new Properties() ;
properties.load(this.getClass().getResourceAsStream("/seoimproved.properties"));</code></pre>
<p>Similar example to use in a static context:</p>
<pre><code>Properties properties = new Properties() ;
properties.load(MyClass.class.getResourceAsStream("/seoimproved.properties"));</code></pre>
<h2>To read java properties files from a specific location:</h2>
<p>The properties files can be loaded from any location.</p>
<pre><code>Properties properties = new Properties() ;
properties.load(new FileInputStream("C:\\tmp\\test.properties"));</code></pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/how-to-readwrite-java-properties-files/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/how-to-readwrite-java-properties-files/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-readwrite-java-properties-files/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
	</channel>
</rss>

