<?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</title>
	<atom:link href="http://www.factorypattern.com/category/java/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>Method Chaining</title>
		<link>http://www.factorypattern.com/method-chaining/</link>
		<comments>http://www.factorypattern.com/method-chaining/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 00:48:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[architecture]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/?p=64</guid>
		<description><![CDATA[Method chaining is a simple programming technique that can be implemented in almost any programming language. In simple words, it means that a method performs some operations on &#8220;this&#8221; object and then returns it so it can be used further more. It allows us to invoke several methods one after another, on one or different [...]]]></description>
			<content:encoded><![CDATA[<p>Method chaining is a simple programming technique that can be implemented in almost any programming language. In simple words, it means that a method performs some operations on &#8220;this&#8221; object and then returns it so it can be used further more. It allows us to invoke several methods one after another, on one or different objects, usually written in the same line.</p>
<p>For example we can build a rectangle class using using the Method Chaining for setters. You can see the setters are a little bit different than regular setters:</p>
<pre name="code" class="java">class ChainedRectangle
{
    protected int x;
    public ChainedRectangle setX(int x) { this.x = x; return this; }

    protected int y;
    public ChainedRectangle setY(int y) { this.y = y; return this; }

    protected int width;
    public ChainedRectangle setWidth(int width) { this.width = width; return this; }

    protected int height;
    public ChainedRectangle setHeight(int height) { this.height = height; return this; }

    protected String color;
    public ChainedRectangle setColor(String color) { this.color = color; return this; }
}
</pre>
<p>Then if we need to build a rectangle we can write a single line for setting all the required values:</p>
<pre name="code" class="java">new         Rectangle().setX(10).setY(10).setWidth(13).setHeight(15).setColor("red");</pre>
<p>Along with autocomplete option in most of todays IDEs method chaining might provide a suggestive way of doing some actions in less code.<br />
<span id="more-64"></span><br />
For example we can write a simple class to build  sql queries. Then we can invoke in a simple way.</p>
<pre name="code" class="java">public class Query
{
    protected String queryString = "";

    public Query select(String what)
    {
        queryString = "SELECT " + what;
    }

    public Query from(String from)
    {
        queryString = " FROM " + from;
    }

    public Query where(String where)
    {
        queryString = " WHERE " + where;
    }

    public ResultSet Invoke()
    {
        //... database invocation bla bla
        return result;
    }
}</pre>
<p>Then, to build the query we invoke:</p>
<pre name="code" class="java">new Query().select("*").from("table").where("a=b").Invoke();</pre>
<p>One of the problems of the Method Chaining pattern is the fact that it can not ensure the order of the invoked method. In order to do that each method can return a specific interface object which implements only the allowed methods.</p>
<p>For example we define an interface ISelectedQuery with a single method from, IFromQuery with a single method where. ISelectedQuery.from returns and object of type IFromQuery and IFromQuery returns a Query object. All the interfaces are implemented by the Query object. That way the order of invoking the methods is ensured.</p>
<p>Here is how the code looks like:</p>
<pre name="code" class="java">public interface ISelectedQuery
{
    IFromQuery from(String from);
}

public interface IFromQuery
{
    Query where(String where);
}

 public class Query implements ISelectedQuery, IFromQuery
{
    protected String queryString = "";

    public ISelectedQuery select(String what)
    {
        queryString = "SELECT " + what;
        return this;
    }

    public IFromQuery from(String from)
    {
        queryString = " FROM " + from;
        return this;
    }

    public Query where(String where)
    {
        queryString = " WHERE " + where;
        return this;
    }

    public ResultSet Invoke()
    {
        //... database invocation bla bla
        return result;
    }
}</pre>
<p>The above code ensure that only the right methods can be invoked. Further more the syntax autocomplete option from most of today IDEs will show in the drop down only the right method(s).</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/method-chaining/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/method-chaining/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/method-chaining/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Using VBS to set the environment variables</title>
		<link>http://www.factorypattern.com/using-vbs-to-set-the-environment-variables/</link>
		<comments>http://www.factorypattern.com/using-vbs-to-set-the-environment-variables/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 18:22:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[environment variables]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/using-vbs-to-set-the-environment-variables/</guid>
		<description><![CDATA[I use windows and I hate when I have to switch on another computer, or when I have to do any change related to windows especially changing the environment variables. I like to download the tool, framework, &#8230; I use as a zip and then to do minimal operations to install it. The thing I [...]]]></description>
			<content:encoded><![CDATA[<p>I use windows and I hate when I have to switch on another computer, or when I have to do any change related to windows especially changing the environment variables. I like to download the tool, framework, &#8230; I  use as a zip and then to do minimal operations to install it. The thing I hate the most is setting environment variables, and path in that small dialog window. I have all my java applications and frameworks in one single directory so the configuration depends only on the thing I hate most: thats right, environment variables.<br />
<span id="more-34"></span><br />
Now I decided to move them all in one single file, and I&#8217;m using Vbs for that. Don&#8217;t hurry to blame me for that, I&#8217;m a java programmer but in this case is the best solution. If you take a look on wikipedia you&#8217;ll see that &#8220;VBScript is installed by default in every desktop release of the Windows Operating System (OS) since Windows 98&#8243;. That&#8217;s all I need to know about VBScript to make me use it to create the script that will help me to put my java tools on every windows computer I can access, without having to add the env variables manually(muahahahahaa). Unfortunately the computer requires a restart.</p>
<p>Now, lets cut the chat. Here is the script(maven-env.vbs) which sets the environments required by maven2 according to the <a href="http://maven.apache.org/download.html#Installation">instructions</a> and add the bin folder to the class path:</p>
<pre><code>Dim WSHShell
Set WSHShell = WScript.CreateObject("WScript.Shell")

WScript.Echo "The current PATH is:" &amp; chr(10) &amp; chr(10) &amp; Replace(WSHShell.Environment.item("PATH"),";", chr(10))

WScript.Echo "Current values of the variables to be changed or added:" &amp; chr(10) _
	&amp; "M2_HOME=" &amp; WSHShell.Environment.item("M2_HOME") &amp; chr(10) _
	&amp; "M2=" &amp; WSHShell.Environment.item("M2")
	
'maven environment variables are created according to http://maven.apache.org/download.html#Installation
WSHShell.Environment.item("M2_HOME") = "C:\java\apache-maven-2.0.9"
WSHShell.Environment.item("M2") = "%M2_HOME%\bin"
WSHShell.Environment.item("PATH") = WSHShell.Environment.item("path") &amp; ";%M2%"

Set WSHShell = Nothing    
WScript.Quit(0)</code></pre>
<p>I&#8217;m using the first echo line in a separate script to display the path and to display one directory on each line replacing ; with end of line(chr(0) represents end of line). If you want to change registry values you can use:</p>
<pre><code>WSHShell.RegWrite "HKCU\path\key", "value"
WSHShell.RegRead("HKCU\path\key")</code></pre>
<p>If you need to know that script for more advanced operation you can check <a href="http://www.w3schools.com/VBscript/vbscript_ref_functions.asp">VBScript Functions</a></p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/using-vbs-to-set-the-environment-variables/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/using-vbs-to-set-the-environment-variables/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/using-vbs-to-set-the-environment-variables/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Wrapping (evil)checked exceptions in Java</title>
		<link>http://www.factorypattern.com/wrapping-checked-exceptions-java/</link>
		<comments>http://www.factorypattern.com/wrapping-checked-exceptions-java/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 21:44:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java foundation]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/wrapping-evilchecked-exceptions-in-java/</guid>
		<description><![CDATA[What? There are various reasons when we have to wrap java exceptions. Often those reasons are called: Checked Exceptions. According to the definition there are 2 types of exceptions: Checked Exceptions &#8211; Exceptions that are not descending from RuntimeException are called checked exceptions. Checked exceptions must be handled by a try catch mechanism or by [...]]]></description>
			<content:encoded><![CDATA[<p><strong>What?</strong></p>
<p>There are various reasons when we have to wrap java exceptions. Often those reasons are called: <strong>Checked Exceptions</strong>. According to the definition there are 2 types of exceptions:<span id="more-31"></span></p>
<ul>
<li><strong>Checked Exceptions</strong> &#8211; Exceptions that are not descending from RuntimeException are called checked exceptions. Checked exceptions must be handled by a try catch mechanism or by adding the throws declaration to the method. If neither of those is done then the compiler throws an exception. </li>
<li><strong>Unchecked Exceptions</strong> &#8211; The exceptions that are not checked, of course. They are inherited from RuntimeException and no handling is enforced by the compiler. Simply put you don&#8217;t have to check them.</li>
</ul>
<p><strong>But Why?</strong></p>
<p>In practice using checked exceptions will lead to undesired behavior. Here are a few scenarios:</p>
<ul>
<li>
<p>Let&#8217;s assume we have to use a method called <em>getProperty(String key) throws SQLException</em> defined in DBConfig to read a color property from the database and then to display it on screen. We instantiate the config object and then invoke the method. For avoiding a compiler exception we&#8217;ll add a throws SQLException to our method declaration. And then imagine that you have to add another one to the method invoking the method we wrote. The more mothods are involved the more checked exceptions added to the method declaration. It doesn&#8217;t make sense for a method called paintScreen to force you to handle excpetions like SQLException or IOException, doesn&#8217;t it?</p>
</li>
<li>
<p>Now we are going to add an interface named IConfig. We&#8217;ll have the existing class DBConfig and we&#8217;ll create another one FileConfig. The first one will throw SQLException and the second one IOException. If we&#8217;ll have too many checked exceptions we&#8217;ll pollute the interface with exceptions that might depend on implementation, inducing a tight coupling in our classes: the abstraction depends on modules exceptions. Pretty bad, isn&#8217;t it?</p>
</li>
<li>
<p>
Now the bad practice: We&#8217;ll not going to use throws declaration. Not at all, because it generates too many problems. So let&#8217;s just try, catch, printstacktrace and that&#8217;s it. We&#8217;ll see later what to do. This is fast. This practice is again bad, because it just hide the problems. Especially in large applications with many programmers they tend to forget about the caught exceptions and real problems are not discovered. After all remember that exceptions are meant to signal a real abnormal behavior of the application.</p>
</li>
<li>
<p>
There is also another reason that make us wrapping exceptions which is not related to checked or unchecked exceptions. Sometimes we simply want to hide and separate the implementation details from the exposed interface in order to reduce the complexity and to simplify the interface.</p>
</li>
</ul>
<p><strong>Ok, then. But How?</strong></p>
<p>We have 2 simple options:</p>
<ul>
<li>To wrap the exceptions in such a way that the original exception object is not used.and only the message as String is encapsulated in the new exception.</li>
<li>Create another exception that contains references to the thrown exception</li>
</ul>
<p>There is a very thin line between those 2 options and you have to understand it very well. First of all let&#8217;s think about it. The module which invokes the code throwing exceptions will have the wrapped class in the class path? If the response is definitely an yes then go for second point, otherwise choose the first one. </p>
<p>For example a client invokes remotely your api using rmi. The api throws the exception wrapped but the client have only the wrapper exception class in the classpath, not the wrapped one. An exception will be thrown. In cases like this one runtime exception should be created containing a descriptive message and should not wrap the original exception.</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/wrapping-checked-exceptions-java/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/wrapping-checked-exceptions-java/" height="61" width="51" /></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/wrapping-checked-exceptions-java/feed/</wfw:commentRss>
		<slash:comments>3</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>
	</channel>
</rss>

<!-- Dynamic page generated in 1.397 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-02-04 09:42:47 -->

