<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>FactoryPattern.com</title>
	
	<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" />
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/factorypatterncom" /><feedburner:info uri="factorypatterncom" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>How to Obtain the IP Address and DNS Details for a domain in java</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/eg9f45lSGQc/</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><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/eg9f45lSGQc" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://www.factorypattern.com/how-to-obtain-the-ip-address-and-dns-details-for-a-domain-in-java/</feedburner:origLink></item>
		<item>
		<title>Date Time Manipulation In Java</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/EoROIEqscbA/</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><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/EoROIEqscbA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/date-time-manipulation-in-java/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/date-time-manipulation-in-java/</feedburner:origLink></item>
		<item>
		<title>How To Use JDBC addBatch Method with MySQL for Improved Performance</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/2UDBuUa_kys/</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><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/2UDBuUa_kys" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://www.factorypattern.com/how-to-use-jdbc-addbatch-method-with-mysql-for-improved-performance/</feedburner:origLink></item>
		<item>
		<title>How To Download a File in Java</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/ExQHD5-DTd4/</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><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/ExQHD5-DTd4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-download-a-file-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/how-to-download-a-file-in-java/</feedburner:origLink></item>
		<item>
		<title>How to use Post Method using Apache HttpClient 4</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/oNESuoT8dHE/</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><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/oNESuoT8dHE" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://www.factorypattern.com/how-to-use-post-method-using-apache-httpclient-4/</feedburner:origLink></item>
		<item>
		<title>How to Convert InputStream to String</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/pknD0LnNOxE/</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><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/pknD0LnNOxE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-convert-inputstream-to-string/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/how-to-convert-inputstream-to-string/</feedburner:origLink></item>
		<item>
		<title>Method Chaining</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/I8dEwGUyUrI/</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><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/I8dEwGUyUrI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/method-chaining/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/method-chaining/</feedburner:origLink></item>
		<item>
		<title>A few thoughts about memory cache</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/8ik1h7VI27w/</link>
		<comments>http://www.factorypattern.com/a-few-thoughts-about-memory-cache/#comments</comments>
		<pubDate>Tue, 02 Dec 2008 14:11:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[architecture]]></category>
		<category><![CDATA[memory cache]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[scalability]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/?p=44</guid>
		<description><![CDATA[I was starting today to look on different approaches and techniques that are used in scalable web or non web applications. One technique used in many large systems is simply called &#8220;memory cache&#8221;. It means that data are cached in memory so the data will not be queried again. Cache and memory cache exists for [...]]]></description>
			<content:encoded><![CDATA[<p>I was starting today to look on different approaches and techniques that are used in scalable web or non web applications. One technique used in many large systems is simply called &#8220;memory cache&#8221;. It means that data are cached in memory so the data will not be queried again. </p>
<p>Cache and memory cache exists for a long time; even the hardware parts link hard disks cd units have some sort of memory cache. </p>
<p>Why memory cache becomes so important when we talk about web applications? It&#8217;s simple. Because web applications happens to fulfill thousands of requests simultaneously. Or sometimes they have to. It&#8217;s obvious that keeping the data into memory and reuse it the next time you need it it will improve the performance. And it looks very simple. At the first view simple hashmap would do the job, unless&#8230;</p>
<p>There a few facts we need to be consider in real world:</p>
<ul>
<li>What happens when the database is updated?</li>
<li>In most cases a web application create a thread for each http request. The same thing happens in java of php or other languages. The creation of the threads is handled by the web server, web container, and not by the code we write. </li>
<li>The scalable applications run distributed on multiple servers. If one application change the database, the cache system should be informed on all the machines.</li>
</ul>
<p><span id="more-44"></span></p>
<p>The cache cache is very simple. If the data can be retrieved from cache it will be retrieved from cache. If not then it should be retrieved from database and put in cache:</p>
<pre><code>if (data is in cache)
   retrieve data from cache
if (data not in cache)
   retrieve data from database
   add data to cache
use data</code></pre>
<h2>How to handle database updates?</h2>
<p>Even if we have a simple application and we use a simple hashmap as a memory cache we still have to address this issue. When we update a database the cache should be updated with the new data or the old data should be removed from the cache.</p>
<p>Each time we update something in the database we have to remove the updated entities from the cache. We should take a special care because we our changes might affect other entities kept in cache:</p>
<pre><code>update database  
invalidate saved and affected entities from cache</code></pre>
<h2>Memory Cache in Web Applications</h2>
<p>As I said web applications are special applications. For each http request a thread will be created. In order to make sure that everything will work fine we must ensure that:<br />
- All the http request threads will access the same data in cache. There a many ways to achieve it, singletons can be taken into discussion.<br />
- The way the data is accessed is synchronized &#8211; one thread will not read the data while another one is updating it.</p>
<h2>Distributed applications</h2>
<p>The applications where memory cache is required are the applications with many users and usually they run in distributed environments. There are options here:<br />
- each server instance will have its own memory cache. If in one instance an entity is changed the affected entities should be invalidated in the cache on all the other server instances. The server instance changing the database will have to trigger the propagation the changes to other server instances.<br />
- the cache will run as a separate process and all the server instances will use it in common, connecting remotely to read/invalidate cached data.</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/a-few-thoughts-about-memory-cache/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/a-few-thoughts-about-memory-cache/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/8ik1h7VI27w" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/a-few-thoughts-about-memory-cache/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/a-few-thoughts-about-memory-cache/</feedburner:origLink></item>
		<item>
		<title>Guice Servlets Integration</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/rXTeTYoVyek/</link>
		<comments>http://www.factorypattern.com/guice-servlets/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 09:36:33 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[guice]]></category>
		<category><![CDATA[java web apps]]></category>
		<category><![CDATA[servlets]]></category>
		<category><![CDATA[bootstrapping]]></category>
		<category><![CDATA[google guice]]></category>
		<category><![CDATA[web applications]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/guice-servlets-integration/</guid>
		<description><![CDATA[Using Google Guice in web applications can raise some issues. First of all when we talk about web applications we talk about servlets and we talk about managed environments. The creation of servlets in not controlled by us, when we write the application, it is controlled by the web application container. This generates some problems: [...]]]></description>
			<content:encoded><![CDATA[<p>Using Google Guice in web applications can raise some issues. First of all when we talk about web applications we talk about servlets and we talk about managed environments. The creation of servlets in not controlled by us, when we write the application, it is controlled by the web application container. This generates some problems:<br />
- Because we can not control the servlet creation we can not use Guice to inject servlet members in the classic way.<br />
- Bootstrapping: we need a mechanism to bootstrap Guice into the application. The best way is to do it at start up before any http request will be invoked.<br />
<span id="more-37"></span><br />
The key element to bootstrap Google Guice to a java servlet based application is <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html">ServletContext</a>. For each web application there is only one ServletContext instance per JVM. ServletContext is used to manage data which is accessible to all the servlets, and it can be used by the servlets to share data between them. Starting with Servlet 2.3 specification Sun provides a listener mechanism which can be used to instantiate objects at the application start up, outside of any servlet scope in the ServletContext.</p>
<p>This techniques can not be used in distributed environments. If we use it we&#8217;ll have one injector instance on each JVM because on distributed environments for each JVM there is one ServletContext. ServletContext on one JVM is not visible from another JVM, so if we can not use guice scopes distributed on multiple machines.</p>
<h2>Initializing Guice Injector in ServletContext</h2>
<p>As we said there is only one instance of javax.servlet.ServletContext(as long as we don&#8217;t have a distributed application). We can trigger the initialization of the ServletContext using <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html">ServletContextListener</a>. All we have to do is to implement the ServletContextListener.contextInitialized to create the google guice injector, and to set it as an attribute in the ServletContext:</p>
<pre name="code" class="java">package com.exam.web.guice;

import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

public class GuiceServletContextListener implements ServletContextListener {
    public static final String KEY = Injector.class.getName(); 

    public void contextInitialized(ServletContextEvent servletContextEvent)
    {
    	servletContextEvent.getServletContext()
    		.setAttribute(KEY, getInjector(servletContextEvent.getServletContext()));
    } 

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    	servletContextEvent.getServletContext().removeAttribute(KEY);
    } 

    @SuppressWarnings("unchecked")
    private Injector getInjector(ServletContext servletContext) {
        String className = servletContext.getInitParameter("module");
        try {
            Class<? extends Module> module = (Class<? extends Module>) Class.forName(className);
            return Guice.createInjector(module.getConstructor().newInstance());
        }
        catch (ClassNotFoundException e) { throw new RuntimeException(e); }
        catch (NoSuchMethodException e) { throw new RuntimeException(e); }
        catch (InvocationTargetException e) { throw new RuntimeException(e); }
        catch (IllegalAccessException e) { throw new RuntimeException(e); }
        catch (InstantiationException e) { throw new RuntimeException(e); }
    }
}</pre>
<p>Then we have to change the web.xml to define the listener to be used by the web application container:</p>
<pre name="code" class="xml">
<listener>
<listener-class>
            com.exam.web.guice.GuiceServletContextListener
        </listener-class>
    </listener>
</pre>
<h2>Storing module configuration in web.xml</h2>
<p>We use web.xml to define which module to be used by Guice in <context-param> block. When we create the guice injector the parameter is read and used:</p>
<pre name="code" class="php">String className = servletContext.getInitParameter("module");</pre>
<p>The class name is defined like this in web.xml:</p>
<pre name="code" class="XML">
    <context-param> 
<param-name>module</param-name>
<param-value>com.webapplication.bus.HibernateDaoModule</param-value>
        <description>Guice Module to be used for the servlets app</description>
    </context-param>
</pre>
<p>Finally in the servlet we can use this expression to get the injector:<br />
(Injector) servletContext.getAttribute(GuiceServletContextListener.KEY)</p>
<p>We can add an injector field to the servlet and &#8220;inject&#8221; the injector into it when the servlet is initialized(a super servlet class can be created to define this code in only one place):</p>
<pre name="code" class="java">public class MyServlet  extends HttpServlet {

	Injector injector;
        ...

	@Override
	public void init(ServletConfig config) throws ServletException {

        HibernateUtil.Configure(true);  

	    ServletContext servletContext = config.getServletContext();
	    injector = (Injector) servletContext.getAttribute(GuiceServletContextListener.KEY);
	    injector.injectMembers(this);

	    managersRegistry = injector.getInstance(ManagersRegistry.class);

		super.init(config);
	}
}</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/guice-servlets/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/guice-servlets/" height="61" width="51" /></a></div><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/rXTeTYoVyek" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/guice-servlets/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/guice-servlets/</feedburner:origLink></item>
		<item>
		<title>Using VBS to set the environment variables</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/EQ9VVcP5tR8/</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><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/EQ9VVcP5tR8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/using-vbs-to-set-the-environment-variables/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/using-vbs-to-set-the-environment-variables/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 1.444 seconds. --><!-- Cached page generated by WP-Super-Cache on 2012-01-26 13:47:25 -->

