<?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>Sat, 02 Jan 2010 22:08:06 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<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>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[Design Patterns]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[architecture]]></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><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li>No Related Post</li></ul><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>9</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><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li>No Related Post</li></ul><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><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li><a href="http://www.factorypattern.com/google-guice-tutorial/" title="Google Guice Tutorial">Google Guice Tutorial</a></li><li><a href="http://www.factorypattern.com/google-guice-starts-a-new-google-age/" title="Google Guice Starts a New Google Age?">Google Guice Starts a New Google Age?</a></li></ul><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 [...]]]></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><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li>No Related Post</li></ul><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>
		<item>
		<title>Wrapping (evil)checked exceptions in Java</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/KmPWEtOMtpI/</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 adding the [...]]]></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><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li>No Related Post</li></ul><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/KmPWEtOMtpI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/wrapping-checked-exceptions-java/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/wrapping-checked-exceptions-java/</feedburner:origLink></item>
		<item>
		<title>How to Avoid Generics Related Warnings in Eclipse</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/gF9OYr6_WLk/</link>
		<comments>http://www.factorypattern.com/how-to-avoid-generics-related-warnings-in-eclipse/#comments</comments>
		<pubDate>Thu, 07 Aug 2008 20:50:43 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[warnings]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/how-to-avoid/</guid>
		<description><![CDATA[I get tones of exceptions in my code because I tend to use Generics in the old-fashioned way. I have my reasons for that. And I have tons of warnings like those:

HashMap is a raw type. References to generic type HashMap should be parameterized
Type safety: The method put(Object, Object) belongs to the raw type Map. [...]]]></description>
			<content:encoded><![CDATA[<p>I get tones of exceptions in my code because I tend to use Generics in the old-fashioned way. I have my reasons for that. And I have tons of warnings like those:</p>
<ul>
<li>HashMap is a raw type. References to generic type HashMap<K,V> should be parameterized</li>
<li>Type safety: The method put(Object, Object) belongs to the raw type Map. References to generic type Map<K,V> should be parameterized</li>
</ul>
<p><span id="more-32"></span><br />
Just because I use to write code like this in java 1.5:</p>
<pre><code>Map parametersMap = new HashMap();
parametersMap.put(properties.get("input.key"), page);</code></pre>
<p>I decided to say, no I don&#8217;t want to see them again. You can change the Project Properties in eclipse to ignore them: Right Click on the Project > Java Compiler > Errors / Warnings like in the snapshot (notice you can change this setting only for your specific project or for entire workspace):</p>
<p><a href='http://www.factorypattern.com/wp-content/uploads/2008/08/eclipse-warnings.png' title='Skip eclipse warnings generated by generics'><img src='http://www.factorypattern.com/wp-content/uploads/2008/08/eclipse-warnings.png' alt='Skip eclipse warnings generated by generics' /></a></p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/how-to-avoid-generics-related-warnings-in-eclipse/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/how-to-avoid-generics-related-warnings-in-eclipse/" height="61" width="51" /></a></div><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li><a href="http://www.factorypattern.com/installing-eclipse-bazaar-plug-in-and-avoiding-%e2%80%98bzr-xmloutput-plugin-not-found%e2%80%99/" title="Installing Eclipse Bazaar plug-in and avoiding ‘bzr-xmloutput plugin not found’">Installing Eclipse Bazaar plug-in and avoiding ‘bzr-xmloutput plugin not found’</a></li></ul><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/gF9OYr6_WLk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-avoid-generics-related-warnings-in-eclipse/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/how-to-avoid-generics-related-warnings-in-eclipse/</feedburner:origLink></item>
		<item>
		<title>Storing parameters in web.xml: context-param &amp; init-param</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/PQMMr2nK070/</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 context [...]]]></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><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li>No Related Post</li></ul><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/PQMMr2nK070" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/storing-parameters-in-webxml-context-param-init-param/</feedburner:origLink></item>
		<item>
		<title>How to Read/Write Java Properties Files</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/9L4wHoiePy4/</link>
		<comments>http://www.factorypattern.com/how-to-readwrite-java-properties-files/#comments</comments>
		<pubDate>Wed, 30 Jul 2008 16:18:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[java snippets]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[java properties]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/how-to-readwrite-java-properties-files/</guid>
		<description><![CDATA[There are several options to handle the Java properties files:
To read java properties files from the classpath:
The properties files can be stored in the classpath. This way they can be put inside jar files and it&#8217;s really useful for web applications when the absolute location of the properties files is not known. When I tested [...]]]></description>
			<content:encoded><![CDATA[<p>There are several options to handle the Java properties files:</p>
<h2>To read java properties files from the classpath:</h2>
<p>The properties files can be stored in the classpath. This way they can be put inside jar files and it&#8217;s really useful for web applications when the absolute location of the properties files is not known. When I tested this in an web application it didn&#8217;t work:<span id="more-27"></span></p>
<pre><code>Properties properties = new Properties() ;
URL url =  ClassLoader.getSystemResource("test.properties");
properties.load(new FileInputStream(new File(url.getFile())));</code></pre>
<h2>To read java properties files from the classpath in a web application:</h2>
<p>The following example works to load the properties files in a web application. This snippet was tested on Tomcat 5.5. The &#8216;/&#8217; represents the root of the class path. Otherwise the properties file location is considered relatively to &#8220;this&#8221; class (or to MyClass for the second example):</p>
<pre><code>Properties properties = new Properties() ;
properties.load(this.getClass().getResourceAsStream("/seoimproved.properties"));</code></pre>
<p>Similar example to use in a static context:</p>
<pre><code>Properties properties = new Properties() ;
properties.load(MyClass.class.getResourceAsStream("/seoimproved.properties"));</code></pre>
<h2>To read java properties files from a specific location:</h2>
<p>The properties files can be loaded from any location.</p>
<pre><code>Properties properties = new Properties() ;
properties.load(new FileInputStream("C:\\tmp\\test.properties"));</code></pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/how-to-readwrite-java-properties-files/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/how-to-readwrite-java-properties-files/" height="61" width="51" /></a></div><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li><a href="http://www.factorypattern.com/multimap-in-google-collections-library/" title="Multimap in Google Collections Library">Multimap in Google Collections Library</a></li><li><a href="http://www.factorypattern.com/how-to-use-ant/" title="How To Use Ant">How To Use Ant</a></li><li><a href="http://www.factorypattern.com/how-to-write-ant-xml-build-file-generate-jaxb-code-compile-build-jar/" title="How to write an Ant xml build file to Generate JAXB Code and Compile and Build it to a Jar">How to write an Ant xml build file to Generate JAXB Code and Compile and Build it to a Jar</a></li><li><a href="http://www.factorypattern.com/how-to-simulate-multiple-inheritance-in-java/" title="How to Simulate Multiple Inheritance in Java">How to Simulate Multiple Inheritance in Java</a></li></ul><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/9L4wHoiePy4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/how-to-readwrite-java-properties-files/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/how-to-readwrite-java-properties-files/</feedburner:origLink></item>
		<item>
		<title>Using Visitor Patterns on non Visitable Structures</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/GqU2EUU1gN0/</link>
		<comments>http://www.factorypattern.com/using-visitor-patterns-on-non-visitable-structures/#comments</comments>
		<pubDate>Fri, 30 May 2008 07:27:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Object Oriented Design]]></category>
		<category><![CDATA[Visitor Pattern]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/using-visitor-patterns-on-non-visitable-structures/</guid>
		<description><![CDATA[The visitor pattern can be used on structures of objects which implements a specific interface defining a method called accept. In practice, in many cases, the structures are already created and we have to visit structures of already created objects. Changing hierarchies of classes for adding a new method is not a viable solution.
We need [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.oodesign.com/visitor-pattern.html">visitor pattern</a> can be used on structures of objects which implements a specific interface defining a method called accept. In practice, in many cases, the structures are already created and we have to visit structures of already created objects. Changing hierarchies of classes for adding a new method is not a viable solution.</p>
<p>We need somehow to extend the structure of objects for accepting the visitors without changing them. A way of doing it would be to add a wrapper for the hierarchy classes which accepts visitors and duplicates the structure.</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/using-visitor-patterns-on-non-visitable-structures/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/using-visitor-patterns-on-non-visitable-structures/" height="61" width="51" /></a></div><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li><a href="http://www.factorypattern.com/drawbacks-of-marker-interface-design-pattern/" title="Drawbacks of Marker Interface Design Pattern.">Drawbacks of Marker Interface Design Pattern.</a></li><li><a href="http://www.factorypattern.com/factory-pattern/" title="FactoryPattern.com &#8211; on air">FactoryPattern.com &#8211; on air</a></li></ul><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/GqU2EUU1gN0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/using-visitor-patterns-on-non-visitable-structures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/using-visitor-patterns-on-non-visitable-structures/</feedburner:origLink></item>
		<item>
		<title>Installing Eclipse Bazaar plug-in and avoiding ‘bzr-xmloutput plugin not found’</title>
		<link>http://feedproxy.google.com/~r/factorypatterncom/~3/Df2hGr25o9I/</link>
		<comments>http://www.factorypattern.com/installing-eclipse-bazaar-plug-in-and-avoiding-%e2%80%98bzr-xmloutput-plugin-not-found%e2%80%99/#comments</comments>
		<pubDate>Tue, 20 May 2008 13:06:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[bazaar]]></category>
		<category><![CDATA[bzr]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[source control]]></category>
		<category><![CDATA[xmloutput]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/installing-eclipse-bazaar-plug-in-and-avoiding-%e2%80%98bzr-xmloutput-plugin-not-found%e2%80%99/</guid>
		<description><![CDATA[I’ve installed the  eclipse plugin for bazaar. For me Bazaar is installed in C:\Java(don’t ask why I put it there, because I don’t know).

It&#8217;s really simple to install it:

Install the bazaar plugin bzr-xmloutput by unzipping the archive content in c:\&#8230;\Bazaar\plugins\xmloutput\ (wherever your bazaar is installed, the plugin subdirectory should be named xmloutput). For details [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve installed the  eclipse plugin for bazaar. For me Bazaar is installed in C:\Java(don’t ask why I put it there, because I don’t know).<br />
<span id="more-22"></span><br />
It&#8217;s really simple to install it:</p>
<ul>
<li>Install the bazaar plugin <strong><a href="https://launchpad.net/bzr-xmloutput">bzr-xmloutput</a></strong> by unzipping the archive content in c:\&#8230;\Bazaar\plugins\xmloutput\ (wherever your bazaar is installed, the plugin subdirectory should be named xmloutput). For details you can check the plugin readme file.</li>
<li>Install the eclipse bazaar plugin: Go to  Help > Software updates > Find and install > Search for New Features to Install > New Remote Site. Use there the http://bzr-eclipse.sourceforge.net/update-site/ then pres finish and all the required operations to install the eclipse plugin. Restart eclipse and set the bzr.exe location from Window > Preferences > Team > Bazaar(scroll down for the picture). </li>
</ul>
<p>The detailed installing instructions are <a href="http://bazaar-vcs.org/BzrEclipse/Installation">here</a>. If you fail noticing the first step, like I did and don’t install the bzr-xmloutput plugin you’ll get “bzr-xmloutput plugin not found” exception like in the picture:</p>
<p><img src='http://www.factorypattern.com/wp-content/uploads/2008/05/bazaar-bzr-xmloutput-plugin-not-found.jpg' alt='bazaar ecipse plugin: bzr-xmloutput plugin not found' /></p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/installing-eclipse-bazaar-plug-in-and-avoiding-%e2%80%98bzr-xmloutput-plugin-not-found%e2%80%99/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/installing-eclipse-bazaar-plug-in-and-avoiding-%e2%80%98bzr-xmloutput-plugin-not-found%e2%80%99/" height="61" width="51" /></a></div><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li><a href="http://www.factorypattern.com/how-to-avoid-generics-related-warnings-in-eclipse/" title="How to Avoid Generics Related Warnings in Eclipse">How to Avoid Generics Related Warnings in Eclipse</a></li></ul><img src="http://feeds.feedburner.com/~r/factorypatterncom/~4/Df2hGr25o9I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/installing-eclipse-bazaar-plug-in-and-avoiding-%e2%80%98bzr-xmloutput-plugin-not-found%e2%80%99/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.factorypattern.com/installing-eclipse-bazaar-plug-in-and-avoiding-%e2%80%98bzr-xmloutput-plugin-not-found%e2%80%99/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic Page Served (once) in 1.299 seconds --><!-- Cached page served by WP-Cache -->
