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

<channel>
	<title>unitstep.net &#187; java</title>
	<atom:link href="http://unitstep.net/blog/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<lastBuildDate>Mon, 19 Mar 2012 01:49:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Java&#8217;s Pattern class and regular expressions</title>
		<link>http://unitstep.net/blog/2012/03/18/javas-pattern-class-and-regular-expressions/</link>
		<comments>http://unitstep.net/blog/2012/03/18/javas-pattern-class-and-regular-expressions/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 01:47:20 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[java regex tutorial]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1366</guid>
		<description><![CDATA[One of the easiest things to get tripped up on is the syntax for creating regular expressions (regex) in Java using the Pattern class. The tl;dr version of how to do things is that you must use double-backslashes in the regular expression Strings you use to create a Pattern object; so something like \b would [...]]]></description>
			<content:encoded><![CDATA[<p>One of the easiest things to get tripped up on is the syntax for creating regular expressions (regex) in Java using the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html">Pattern</a> class. The <em>tl;dr</em> version of how to do things is that <strong>you must use double-backslashes in the regular expression Strings you use to create a Pattern object</strong>; so something like <code>\b</code> would have to be written as <code>"\\b"</code>.  Read on for a more thorough explanation.</p>
<h2>Double trouble</h2>
<p>The key point to understanding the tricky syntax is to realize that when you&#8217;re creating a String literal in Java, backslashes are used to form escape sequences as well. Most people are familiar with this concept, when, for example, constructing a String that spans multiple lines:</p>
<pre><code>final String multiline = "A String...\nOn two lines";</code></pre>
<p>When calling <code>Pattern.compile</code>, you pass in a String literal that is the regular expression. However, regular expressions also use the backslash character to begin escape sequences. So, to ensure that the regular expression engine in Pattern gets the correct syntax, you must replace every backslash in your regular expression with two backslashes. This is to prevent Java from interpreting the single backslash as just a String escape sequence.</p>
<p>Or, put another way, if you wanted a String with the contents <code>"\n"</code>, that is a String with a backslash followed by the letter &#8216;n&#8217;, you&#8217;d have to define it as:</p>
<pre><code>final String newLineEscapeSequence = "\\n";</code></pre>
<p>This is the gist of it; we need to pass in the preserved backslashes into the Pattern regular expression engine, so you have to create a literal backslash by using a double-backslash in your String literal. This information is in the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html">Pattern Javadoc</a>, but it&#8217;s sort of buried beneath loads of regular expression syntax. </p>
<p>Keep this in mind when constructing your regular expressions outside of Java in a tool like <a href="http://gskinner.com/RegExr/">RegExr</a>.  These principles also apply when using other classes/methods that use <code>Pattern</code>, such as <code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29">String.split()</a></code> or <code><a href="http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#useDelimiter%28java.util.regex.Pattern%29">Scanner.useDelimiter()</a></code></p>
<h2>An example</h2>
<p>Here&#8217;s a simple example where we try to find the word &#8220;The&#8221; at the beginning of a String, delimited by a word boundary matcher.</p>
<pre><code>public class PatternExample {
  private static final Logger LOGGER =
      Logger.getLogger(PatternExample.class);
  private static final String TEST_STRING =
      "The quick brown fox jumps over the lazy dog";

  public static void main(final String[] args) {
    System.out.println(TEST_STRING);

    final Pattern wordBoundaryWrong = Pattern.compile("^The\b.*");
    Matcher matcher = wordBoundaryWrong.matcher(TEST_STRING);
    LOGGER.debug(matcher.matches()); // false.

    final Pattern wordBoundaryCorrect = Pattern.compile("^The\\b.*");
    matcher = wordBoundaryCorrect.matcher(TEST_STRING);
    LOGGER.debug(matcher.matches()); // true.
  }
}</code></pre>
<p>The key point here is that the word boundary matcher (<code>\b</code>) must be passed in as a String literal of <code>"\\b"</code> so that the backslash is properly interpreted. In the incorrect Pattern, <code>"\b"</code> maps to a <a href="http://docstore.mik.ua/orelly/java-ent/jenut/ch10_05.htm">backspace character literal</a>.</p>
<p>I think the reason this concept is somewhat tricky is that you have to deal with two levels of escaping &#8211; the Java String literal syntax and the Regular Expression syntax.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2012/03/18/javas-pattern-class-and-regular-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Flyweight Pattern: (Mis&#124;ab)used at times.</title>
		<link>http://unitstep.net/blog/2012/01/08/the-flyweight-pattern-misabused-at-times/</link>
		<comments>http://unitstep.net/blog/2012/01/08/the-flyweight-pattern-misabused-at-times/#comments</comments>
		<pubDate>Sun, 08 Jan 2012 23:21:10 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[software development java design-patterns]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1312</guid>
		<description><![CDATA[In my brief career in software development thus far, I have seen a lot of &#8220;WTF&#8221; code, that is, code that deserves to be posted to The Daily WTF. Some of this code was admittedly developed by myself and upon reviewing it a few months after it was written, I secretly wondered what I&#8217;d been [...]]]></description>
			<content:encoded><![CDATA[<p>In my brief career in software development thus far, I have seen a lot of &#8220;WTF&#8221; code, that is, code that deserves to be posted to <a href="http://thedailywtf.com/">The Daily WTF</a>. Some of this code was admittedly developed by myself and upon reviewing it a few months after it was written, I secretly wondered what I&#8217;d been thinking.</p>
<p>This isn&#8217;t going to be an indictment of bad programming; in fact, I think it&#8217;s good if you can look back at your old code and see where it could be improved. Such a process suggests that you are continually <em>self-improving</em>, a skill crucial in software development. Besides, all of us have made a mistake or two at times when we were stressed, tired or just plain not thinking straight.</p>
<p>However, there&#8217;s one mistake that I&#8217;ve seen that I think warrants bringing to light, and that is the misuse of the <em>Flyweight pattern</em>.</p>
<h2>Who wants to be a Flyweight?</h2>
<p>Flyweight is typically used to describe one of the smaller weight classes in boxing or other fighting sports. This &#8220;minimal&#8221; aspect is what is shared with the design pattern of the same name. Simply put, a Flyweight object is one that reduces memory use by sharing common data with other objects.  Despite this plain definition, implementing the Flyweight pattern can be tricky.</p>
<p>Perhaps this is why I have seen examples like this: (<em>Java pseudo-code below; may not compile, but you shouldn&#8217;t use it anyways</em>)</p>
<pre><code>public class WidgetWithManyFields() {
  private Data field1;
  private String field2;
  private int field3;
  // A lot more fields...
  private SomeOtherData fieldN;

  // Getters and setters...
}</code></pre>
<p>Now, obviously the memory footprint of <code>WidgetWithManyFields</code> can be quite large, and since not all aspects of an application will need access to all data fields, it was decided that a &#8220;Flyweight&#8221; was needed:</p>
<pre><code>public class WidgetFlyweight() {
  // Only these fields are needed.
  private Data field1;
  private String field2;

  public WidgetFlyweight() {
    // Default constructor.
  }

  // Constructor to make one from the regular widget class.
  public WidgetFlyweight(WidgetWithManyFields widget) {
    this.field1 = widget.getField1();
    this.field2 = widget.getField2();
  }
  // Getters and setters...
}</code></pre>
<p>This isn&#8217;t really the Flyweight pattern at all. In fact, I don&#8217;t even know if it is a pattern at all. It might be considered something like the Proxy pattern, <em>if</em> the &#8220;Flyweight&#8221; class contained an instance of the regular class. But I don&#8217;t really know.</p>
<h2>So what is a Flyweight?</h2>
<p>Consider the example of a document that can have images embedded in it. There might be multiple copies of the same image present in the document, but each copy would be sized and positioned differently within the document. </p>
<p>In this case, you wouldn&#8217;t want to load and store the data in memory for multiple copies of the same image as that would be wasteful. However, each instance of the image displayed in the document might be formatted or positioned differently. How might this be done?</p>
<p>Firstly, some assumptions:</p>
<ul>
<li>An image is uniquely identified by some resource path.</li>
<li>The underlying image data does not change during the lifetime of the application.</li>
</ul>
<p>With these assumptions, we can define three classes that allow us to implement the Flyweight pattern.</p>
<p>Firstly, an <code>ImageData</code> class that encapsulates the actual image data. There should be only one canonical instance of this class for each unique resource path. Because of this, we can pool these objects for reuse.</p>
<p>However, the <code>ImageData</code> objects won&#8217;t be directly used by other parts of the application. Instead, we create an <code>ImageFlyweight</code> class that is manipulated. Each instance contains a reference to a canonical <code>ImageData</code> object and also stores information about how to format and position the image.</p>
<p>In this way, there can be multiple <code>ImageFlyweight</code> instances that reference the same image and hence the same <code>ImageData</code> instance, but each instance would define separate formatting and positioning details.</p>
<p>Tying everything together is a factory (<code>ImageFlyweightFactory</code>) that maintains the pool and is the access point for getting instances of <code>ImageFlyweight</code>.</p>
<p>Below is the code: (Sorry, it&#8217;s a lot of code to throw at you at once, but I didn&#8217;t feel like breaking it down into separate chunks, and you can just copy &#038; paste it into your favourite IDE for inspection/compilation)</p>
<pre><code>/**
 * Copyright (c) 2012 Peter Chng, http://unitstep.net/
 */
package net.unitstep.examples.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * In order for the Flyweight Pattern to be effective, ImageFlyweight instances
 * should only be obtained via ImageFlyweightFactory.getImageFlyweight().
 *
 * This ensures that for each unique resource path, there is only one instance
 * of the backing ImageData existing in the application.
 *
 * @author Peter Chng
 */
public class ImageFlyweightFactory {
  private Map&lt;String, ImageData&gt; imageDataPool =
      new HashMap&lt;String, ImageData&gt;();

  public ImageFlyweight getImageFlyweight(final String resourcePath) {
    // This will return a new ImageFlyweight object each time; however, the
    // backing ImageData might be shared across multiple ImageFlyweight
    // instances.
    return new ImageFlyweight(this.getImageData(resourcePath));
  }

  private ImageData getImageData(final String resourcePath) {
    ImageData imageData = this.imageDataPool.get(resourcePath);
    if (null == imageData) {
      imageData = new ImageData(resourcePath);
      this.imageDataPool.put(resourcePath, imageData);
    }
    return imageData;
  }

  /**
   * @return the current count of ImageData instances in the pool; only for
   *         testing purposes.
   */
  public int getImageDataPoolCount() {
    return this.imageDataPool.size();
  }

  /**
   * Will contain the data representing an image loaded from some resource, i.e.
   * the file system.
   *
   * This is a private inner class because it should never need to be used
   * externally by callers. It is considered an implementation detail.
   *
   * We assume that the resource path is the uniquely-identifying aspect of an
   * image and that the underlying image resource/data will not change over the
   * lifetime of the application.
   *
   * Thus, only one instance of the ImageData class is needed for each image
   * uniquely identified by its resource path.
   *
   * @author Peter Chng
   */
  private class ImageData {
    private final byte[] data;
    private final String resourcePath;

    public ImageData(final String resourcePath) {
      this.resourcePath = resourcePath;

      // Image data would be loaded here based on the resource path supplied.
      // For brevity, it's not really done.
      this.data = new byte[] {};
    }

    public byte[] getData() {
      // Note: If we really intend to make this class immutable, we should
      // return a defensive copy instead so that callers cannot modify the
      // data stored in this instance.
      return this.data;
    }

    public String getResourcePath() {
      return resourcePath;
    }

    // Note: Not strictly necessary to override equals() and hashCode() for this
    // example, but it's done to indicate we only consider the resource path
    // in determining equality.
    @Override
    public boolean equals(final Object object) {
      if (null == object) {
        return false;
      }
      if (object == this) {
        return true;
      }
      if (object.getClass() != this.getClass()) {
        return false;
      }
      return this.resourcePath.equals(((ImageData) object).getResourcePath());
    }

    @Override
    public int hashCode() {
      return this.resourcePath.hashCode();
    }
  }

  /**
   * The ImageFlyweight object contains a reference to a canonical ImageData
   * object containing the actual image data we wish to render.
   *
   * By making this a static inner class of {@link ImageFlyweightFactory} and
   * the constructor private, instantiation of this class can be controlled and
   * limited to only the {@link ImageFlyweightFactory}. Callers MUST obtain an
   * instance of the ImageFlyweight through the factory and not by direct
   * instantiation.
   *
   * It also contains other properties that will affect the rendering of the
   * image in the application, such as height, width and position.
   *
   * Reusing the same ImageData object across different ImageFlyweight instances
   * allows us to display the same image in different ways within the
   * application, without having to load (or store in memory) the image data
   * multiple times.
   *
   * @author Peter Chng
   */
  public static class ImageFlyweight {
    private final ImageData imageData;

    private int height;
    private int width;
    private int positionX;
    private int positionY;

    private ImageFlyweight(final ImageData imageData) {
      this.imageData = imageData;
    }

    public byte[] getData() {
      return this.imageData.getData();
    }

    // Getters/setters for height, width, positionX, positionY...

    public int getHeight() {
      return height;
    }

    public void setHeight(int height) {
      this.height = height;
    }

    public int getWidth() {
      return width;
    }

    public void setWidth(int width) {
      this.width = width;
    }

    public int getPositionX() {
      return positionX;
    }

    public void setPositionX(int positionX) {
      this.positionX = positionX;
    }

    public int getPositionY() {
      return positionY;
    }

    public void setPositionY(int positionY) {
      this.positionY = positionY;
    }
  }
}</code></pre>
<p>Everything is contained within the <code>ImageFlyweightFactory</code> class, because the <code>ImageData</code> class does not need to be visible to outsiders and callers should not be able to instantiate <code>ImageFlyweight</code> instances on their own.</p>
<p>With this code, we have a simple test harness to verify whether it&#8217;s working:</p>
<pre><code>/**
 * Copyright (c) 2012 Peter Chng, http://unitstep.net/
 */
package net.unitstep.examples.flyweight;

import net.unitstep.examples.flyweight.ImageFlyweightFactory.ImageFlyweight;

import org.apache.log4j.Logger;

/**
 * @author Peter Chng
 */
public class ImageFlyweightTest {

  private static final Logger LOGGER =
      Logger.getLogger(ImageFlyweightTest.class);

  public static void main(final String[] args) {
    final ImageFlyweightFactory factory = new ImageFlyweightFactory();

    final String resourcePath1 = "/path/to/images/someImage.png";
    final String resourcePath2 = "/path/to/images/anotherImage.png";

    final ImageFlyweight image1 = factory.getImageFlyweight(resourcePath1);

    displayImageDataCountInPool(factory);

    final ImageFlyweight image2 = factory.getImageFlyweight(resourcePath2);

    displayImageDataCountInPool(factory);

    // Should not create an new ImageData instance in the pool.
    final ImageFlyweight image3 = factory.getImageFlyweight(resourcePath1);

    displayImageDataCountInPool(factory);
  }

  private static void displayImageDataCountInPool(
      final ImageFlyweightFactory factory) {
    LOGGER.debug("Current number of ImageData instances: "
        + factory.getImageDataPoolCount());
  }
}</code></pre>
<p>Running the code yields the following results:</p>
<pre>
DEBUG ImageFlyweightTest - Current number of ImageData instances: 1
DEBUG ImageFlyweightTest - Current number of ImageData instances: 2
DEBUG ImageFlyweightTest - Current number of ImageData instances: 2
</pre>
<p>The key point is that after the third <code>ImageFlyweight </code> object is created, the count in the <code>ImageData</code> pool does not increase since the same image has already been &#8220;loaded&#8221;.</p>
<h2>Other examples</h2>
<p>Note that Java itself implements something similar to the Flyweight pattern for Strings; this is known as <em>string interning</em> and many other languages support this feature as well.</p>
<p>Basically, because Strings are immutable, Java can store each distinct value in a pool and then reuse these instances when appropriate.  As an example, the following code displays &#8220;EQUAL&#8221;:</p>
<pre><code>String string1 = "A test of the string intern pool.";
String string2 = "A test of the string intern pool.";
// Note that we are comparing object identity, NOT equality.
if (string1 == string2) {
  System.out.println("EQUAL");
} else {
 System.out.println("NOT EQUAL");
}</code></pre>
<p>Note that this doesn&#8217;t work if you directly create a String using the <code>new</code> keyword.</p>
<h2>Conclusion</h2>
<p>I know that this was a fairly contrived example (aren&#8217;t they all?), but I hope it provided the basics of the Flyweight pattern to readers. There are a lot of holes and I don&#8217;t suggest you directly copy this example for production code, but instead learn the skills to effectively develop the pattern on your own.</p>
<p>As always, I welcome questions or comments and especially corrections if I&#8217;ve made a mistake! Thanks for reading!</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2012/01/08/the-flyweight-pattern-misabused-at-times/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java, Weak References and WeakHashMap</title>
		<link>http://unitstep.net/blog/2011/03/26/java-weak-references-and-weakhashmap/</link>
		<comments>http://unitstep.net/blog/2011/03/26/java-weak-references-and-weakhashmap/#comments</comments>
		<pubDate>Sat, 26 Mar 2011 16:27:19 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[guides]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[references]]></category>
		<category><![CDATA[weakhashmap]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1229</guid>
		<description><![CDATA[Most any Java Developer will be familiar with the concepts of references, as in pass-by-reference vs. pass-by-value. (Pointers, now that&#8217;s another thing&#8230;) When calling methods, primitive data types are passed by value, while objects and arrays are passed by reference. This means when you call a method with an object as a parameter, you are [...]]]></description>
			<content:encoded><![CDATA[<p>Most any Java Developer will be familiar with the concepts of <em>references</em>, as in pass-by-reference vs. pass-by-value. (Pointers, now that&#8217;s another thing&#8230;)</p>
<p>When calling methods, primitive data types are passed by value, while objects and arrays are passed by reference. This means when you call a method with an object as a parameter, you are merely providing that method a way to access/manipulate the <em>same</em> object via a reference; no copy is made. Contrast that with primitives: When calling a method that requires them, a copy of that value is put on the call stack before invoking the method.</p>
<p>In that way, references are somewhat like pointers, though they obviously cannot be manipulated by pointer arithmetic.  But what about <strong>weak references</strong>? What are they, and how do they contrast with <em>strong</em> references?</p>
<h2>Weakly understood</h2>
<p>Based on my experience, the concept of weak references, or more generally reachability, is not one that is well-understood in the Java world. At least I did not have a good grasp of them until stumbling upon some sample code one day. It may be that the need to utilize them is outside the confines of most day-to-day programming tasks, as the concept is fairly low-level.  Nonetheless, it&#8217;s an important concept to understand.</p>
<p>Basically, Java specifies five levels of reachability for objects that reflect which state the object is in, in relation to being marked as finalizable, being finalized and being reclaimed.  They are, in order of strongest-to-weakest:</p>
<ol>
<li>Strongly Reachable</li>
<li>Softly Reachable</li>
<li>Weakly Reachable</li>
<li>Phantom Reachable</li>
<li>Unreachable</li>
</ol>
<p>An object&#8217;s normal state, as soon as it has been instantiated and assigned to a variable/field is <em>strongly reachable</em>. Chances are, these are the only types of objects you&#8217;ve worked with.  We&#8217;ll first cover the concept of <em>weakly reachable</em> objects, as I believe it provides a good base for understanding the remainder.</p>
<h2>Cleaning out the trash</h2>
<p>Going by the <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ref/package-summary.html#reachability">API reference</a>, a weakly reachable object is one that can be reached by traversing (i.e. going through) a weak reference. That&#8217;s a succinct definition to be sure, but it just raises the next question: What is a weak reference?</p>
<p>Simply put, if an object can only be reached by traversing a weak reference, the garbage collector <strong>will not attempt to keep the object in memory any more than it would an object with no references to it</strong>, i.e. an object that cannot be accessed. Thus, from the garbage collector&#8217;s point-of-view, a weakly-referenced object will eventually be cleaned from memory the same as an object no references to it.</p>
<p>So, if weakly-referenced objects are treated the same as completely non-referenced ones, what is the purpose of the weak reference? A good example is the <a href="http://download.oracle.com/javase/6/docs/api/java/util/WeakHashMap.html">WeakHashMap</a>, a class provided by Java.</p>
<h2>WeakHashMap</h2>
<p>Unfortunately, <code>WeakHashMap</code> may also be poorly understood, probably as a result of weak references not being well known. WeakHashMap may at times be described as a &#8220;cache&#8221; of sorts, where objects/entries that are not used will be removed to decrease memory usage. This is not how WeakHashMap works at all.</p>
<p>The best way to describe a WeakHashMap is one where the entries (key-to-value mappings) will be removed when it is no longer possible to retrieve them from the map. For example, say you&#8217;ve added an object to the WeakHashMap using a key <em>k1</em>. If you now set <em>k1</em> to null, there should be no way to retrieve the object from the map, since you don&#8217;t have the key object around any more to call <code>get()</code> with.  This behaviour is possible because WeakHashMap only has weak references to the keys, not strong references like the other Map classes.</p>
<p>Note that for the WeakHashMap to work this way, as it was intended, the key objects must only be considered equal if they are actually the same object &#8211; i.e. object identity instead of mere equality. This is the default behaviour for <code>Object.equals()</code> and <code>Object.hashCode()</code>, so if these methods have not been overridden, the object is OK to be used as a key in WeakHashMap. Objects like <code>Integer</code> are not suitable for use in WeakHashMap, because it is possible to create two separate (non-identical) objects that are both equal:</p>
<pre><code>final Integer i1 = new Integer(4);
final Integer i2 = new Integer(4);
LOGGER.debug("i1.equals(i2): " + i1.equals(i2)); // True.
LOGGER.debug("i1 == i2: " + (i1 == i2)); // False.</code></pre>
<p>Another point of importance is that <code>String</code> is not a suitable key for a WeakHashMap as well. In addition to its overriding of <code>equals()</code> and <code>hashCode()</code>, String objects in Java are also interned (i.e. stored) in a pool by the JVM when created.  This means that they may remain strongly referenced even after you have apparently gotten rid of your reference to them.  Because of this, entries that you add to a WeakHashMap using String keys may never get dropped, even after you have apparently lost reference to the keys, since the Strings may remain strongly referenced in the string intern pool.</p>
<p>An example of String interning:</p>
<pre><code>final String s1 = "The only thing we have to fear is fear itself.";
final String s2 = "The only thing we have to fear is fear itself.";
LOGGER.debug("s1.equals(s2): " + s1.equals(s2)); // True.
LOGGER.debug("s1 == s2: " + (s1 == s2)); // May also return true!</code></pre>
<p>String objects are interned for performance reasons, so when you are going to create a new String, Java first checks if there is a String in the pool that is &#8220;equal&#8221; to the one you are creating.  If such a String exists, the existing object is just returned instead of having to instantiate a new object.  This is possible because Strings in Java are immutable, i.e. operations that appear to modify a String (such as concatenation, <code>toUpperCase()</code>, etc.) really return a new String object while preserving the original.</p>
<p>The last usage note is that even though the keys are weakly-referenced by WeakHashMap, the values remain strongly-referenced. Thus, you must take care to not use value objects that strongly reference the keys themselves, as if this happens, the keys/entries will no longer be automatically dropped because a strong reference may always exist to the keys. (This can be avoided by wrapping the value object in a <a href="http://download.oracle.com/javase/6/docs/api/java/lang/ref/WeakReference.html">WeakReference</a>, so that both keys and values are weakly-referenced when in the WeakHashMap)</p>
<h2>Example use of WeakHashMap</h2>
<p>Here is a brief, albeit contrived example of <code>WeakHashMap</code> at work:</p>
<pre><code>// SampleKey is just an object that holds a single int. (Use instead of
// Integer, since Integer overrides equals() and hashcode())
SampleKey key = new SampleKey(42);
SampleObject value = new SampleObject("Sample Value");

final WeakHashMap&lt;SampleKey, SampleObject&gt; weakHashMap = new WeakHashMap&lt;SampleKey, SampleObject&gt;();
weakHashMap.put(key, value);

// At this point, we still have a strong reference to the key. Thus, even
// though the key is weakly-referenced by the WeakHashMap, nothing will
// be automatically removed even if we give a hint to the GC.
System.gc();

LOGGER.debug(weakHashMap.size()); // Will still be '1'.
LOGGER.debug(weakHashMap.get(key)); // Will still be 'Sample Value'.

// Now, we if set the key to null, the entry in weakHashMap will eventually
// disappear. Note that the number of times we have to 'kick' the GC
// before the entry disappears may be different on each run depending
// on the JVM load, memory usage, etc.
key = null;
int count = 0;
while(0 != weakHashMap.size())
{
  ++count;
  System.gc();
}
LOGGER.debug("Took " + count + " calls to System.gc() to result in weakHashMap size of : " + weakHashMap.size());</code></pre>
<h2>Finishing up</h2>
<p>In an upcoming article, I plan on covering the other types of references (soft and phantom) as well as the associated <code>Reference</code> classes in Java. I wanted to keep this post brief so that it provided a basic understanding of the situation.</p>
<h4>Changes/Fixes</h4>
<ul>
<li><strong>2011-04-10</strong>: Fixed numerous incorrect usages of the term &#8220;dereference&#8221;. Thanks to <a href="#comment-222992">Ranjit</a> for the explanation.</li>
</ul>
<h3>References</h3>
<ol class="note less">
<li><a href="http://download.oracle.com/javase/6/docs/api/java/lang/ref/package-summary.html">Package java.lang.ref</a></li>
<li><a href="http://download.oracle.com/javase/6/docs/api/java/util/WeakHashMap.html">WeakHashMap</a></li>
<li><a href="http://weblogs.java.net/blog/2006/05/04/understanding-weak-references">Understanding Weak References</a></li>
</ol>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2011/03/26/java-weak-references-and-weakhashmap/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Sun plans to launch an App Store for Java Desktop applications.</title>
		<link>http://unitstep.net/blog/2009/05/31/sun-plans-to-launch-an-app-store-for-java-desktop-applications/</link>
		<comments>http://unitstep.net/blog/2009/05/31/sun-plans-to-launch-an-app-store-for-java-desktop-applications/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 02:39:07 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[business]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[sun]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=920</guid>
		<description><![CDATA[As reported a little while ago, Sun plans to launch their own app store for Java-based desktop applications. With Apple&#8217;s App Store having passed the one-billion download mark last month and thus proving to be a roaring success, it&#8217;s clear that Sun, like many others, is hoping to imitate and perhaps improve on the effort. [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/sun-java-appstore.jpg" alt="sun-java-appstore" title="sun-java-appstore" width="200" height="143" class="alignnone size-full wp-image-933" /></p>
<p>As reported a little while ago, <a href="http://arstechnica.com/open-source/news/2009/05/sun-hopes-to-cash-in-on-java-install-base-with-new-app-store.ars">Sun plans to launch their own app store</a> for Java-based desktop applications.  With Apple&#8217;s App Store having <a href="http://www.tuaw.com/2009/04/23/the-app-store-hits-one-billion-downloads/">passed the one-billion download mark last month</a> and thus proving to be a roaring success, it&#8217;s clear that Sun, <a href="http://gizmodo.com/5199933/giz-explains-all-the-smartphone-mobile-app-stores">like many others</a>, is hoping to imitate and perhaps improve on the effort.  But does it make sense?</p>
<h2>Mobile vs. Desktop</h2>
<p>Following in the steps of RIM, Google&#8217;s Android, Palm <a href="http://news.cnet.com/8301-1035_3-10249116-94.html">and others</a>, Sun hopes to follow the same pattern of success that Apple has enjoyed with their App Store.  However, things are a bit different here.  All the current App Store competitors have a separate mobile platform with which to compete against Apple.  In general, this business model makes sense because there are few other easy ways to get software onto the devices, so a centralized app store of sorts makes sense.</p>
<p>In Apple&#8217;s case, they intended from the beginning to have the App Store be the <strong>only</strong> way to get software onto their devices.  This closed-model and high level of control, which Apple is known for, is what helped make the App Store so popular.  It was also very easy to use, and provided functionality not available elsewhere.  Other mobile app stores aim to emulate this &#8220;app store tie-in&#8221;, hoping to make their respective app stores the primary place to get new software for your device, thus providing the companies with a steady source of revenue.</p>
<p>On the desktop, thing&#8217;s aren&#8217;t so clear.  For the most part, people are already able to freely and easily download/purchase and install software, either through their web browser or through content delivery systems like <a href="http://store.steampowered.com/about/">Steam</a>.  Sun will have some real competition on their hands because of this, and unless they can create the ecosystem to spawn &#8220;killer apps&#8221;, people won&#8217;t be flocking to it in droves.  Currently, there are just too many options for getting new software onto your desktop, thanks to the openness of the system, and this will be a real problem for Sun when it comes to gaining any significant market share in this area.</p>
<p>Furthermore, <a href="http://arstechnica.com/open-source/news/2009/05/sun-hopes-to-cash-in-on-java-install-base-with-new-app-store.ars">as noted in the article</a>, there haven&#8217;t been very many compelling Java apps, save for Eclipse and Azureus. (I only use the former)  Java on the desktop just hasn&#8217;t been as much of a success as Sun would&#8217;ve hoped for, mainly because Java desktop applications haven&#8217;t had the same consistent look &#038; feel that native OS applications have offered, with some notable exceptions like Eclipse.  While Java has gained much acceptance on the server side, it may have to settle for this before looking to gain significant acceptance on the desktop anytime soon.</p>
<h2>App Store Hype?</h2>
<p>It should be also noted that while the Apple&#8217;s App Store has been a roaring success for the company itself, it seems that it&#8217;s not as much of a success for the vast majority of developers out there.  Like most markets with low-barriers to entry, (blogging for profit, startups, etc.) the distribution of revenue seems to follow a long-tail model, with very few developers making a lot of money, with the rest only making a fraction of that.</p>
<p>This was highlighted by a recent TechCrunch article about the <a href="http://www.techcrunch.com/2009/05/25/the-app-store-hype-gets-a-dose-of-reality/">reality of the App Store</a>, which referenced an <a href="http://www.stromcode.com/2009/05/24/the-incredible-app-store-hype/">original article by an App Store developer</a>.  In that article, the developer revealed that because there were so many apps available for download, it didn&#8217;t take much to get into the top 100 for a given category:</p>
<blockquote cite="http://www.stromcode.com/2009/05/24/the-incredible-app-store-hype/"><p>In order to place #34 on the social networking charts, you need 30-35 downloads a day.  At the standard app store pricing of .99, and after Apple takes its cut, that means your app needs to bring in a little over $20 a day to chart at that position.  And social networking is a popular category.</p></blockquote>
<p>Thus, it would appear that App Store not as profitable for developers as the hype or large success stories would suggest.  You may have a compelling app that is nicely done, but it may only make a marginal amount instead of the six-figure amounts being seen by some of the most successful apps.  If this is the case with even a successful implementation like Apple&#8217;s App Store, how does this bode for Sun, which hasn&#8217;t even proven that their Java app store can enjoy similar success?  Indeed, it appears that they will have a hard time attracting developers to their app store platform.</p>
<p>Mind you, this hasn&#8217;t stopped people from even <a href="http://www.stefanoforenza.com/ubuntu-appstore-in-the-workings/">speculating about an Ubuntu app store</a>, though it&#8217;s hard to see this business model working well with the FOSS model of Ubuntu.  Nevertheless, it wouldn&#8217;t be unrealistic, given that <a href="http://arstechnica.com/open-source/news/2009/05/canonical-developers-aim-to-make-android-apps-run-on-ubuntu.ars">Canonical is trying to make Android apps run on Ubuntu</a>, possibly allow for Android&#8217;s app store to make an entrance to the desktop through this backdoor method.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/05/31/sun-plans-to-launch-an-app-store-for-java-desktop-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Resolving log4j 1.2.15 dependency problems in Maven using exclusions</title>
		<link>http://unitstep.net/blog/2009/05/18/resolving-log4j-1215-dependency-problems-in-maven-using-exclusions/</link>
		<comments>http://unitstep.net/blog/2009/05/18/resolving-log4j-1215-dependency-problems-in-maven-using-exclusions/#comments</comments>
		<pubDate>Mon, 18 May 2009 15:44:35 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[build]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[dependency]]></category>
		<category><![CDATA[exclusion]]></category>
		<category><![CDATA[log4j]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=906</guid>
		<description><![CDATA[If you&#8217;re using Maven to manage your project&#8217;s build and dependencies, you may have encountered some problems when trying to include the latest version of log4j as a dependency. Specifically, log4j 1.2.15 depends on some artifacts that are not available in the central Maven repository due to licensing issues, and thus when you try to [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/maven.jpg" alt="maven" title="maven" width="150" height="37" class="alignnone size-full wp-image-916" /></p>
<p>If you&#8217;re using Maven to manage your project&#8217;s build and dependencies, you may have encountered some problems when trying to include the latest version of log4j as a dependency.  Specifically, <a href="http://mvnrepository.com/artifact/log4j/log4j/1.2.15">log4j 1.2.15</a> depends on some artifacts that are not available in the <a href="http://repo1.maven.org/maven2/">central Maven repository</a> due to <a href="http://www.mail-archive.com/log4j-dev@logging.apache.org/msg07529.html">licensing issues</a>, and thus when you try to build a project that depends on this version of log4j, you may not be able to download the artifacts and your build will fail.</p>
<p>We could download and <a href="http://onemanwenttomow.wordpress.com/2007/12/31/maven2-log4j-and-jmx-dependencies/">install these artifacts to the local repository</a>, if we really needed them.  But in most cases, they&#8217;re not needed and thus you won&#8217;t want your project relying on these artifacts just because some parts of log4j do.  Thus, we need to exclude them.</p>
<h2>The problem: Not really needed</h2>
<p>The issue is going from log4j <a href="http://mvnrepository.com/artifact/log4j/log4j/1.2.14">1.2.14</a> to <a href="http://mvnrepository.com/artifact/log4j/log4j/1.2.15">1.2.15</a>, the developers added some features which required some dependencies on various <code>sun</code> and <code>javax</code> packages.  However in most cases, you won&#8217;t be using this extra functionality, but if you just include log4j 1.2.15, this will cause your project to require those extra artifacts as per the <em>transitive dependency</em> rule.</p>
<p>Because some of these artifacts are not available from the central Maven repository, due to licensing issues, they will not be automatically installed to your local repository.  So, if you attempt to run <code>mvn install</code>, you&#8217;re likely to encounter this sort of error:</p>
<pre><code>[INFO] Unable to find resource 'com.sun.jdmk:jmxtools:jar:1.2.1' in repository central (http://repo1.maven.org/maven2)
[INFO] Unable to find resource 'javax.jms:jms:jar:1.1' in repository central (http://repo1.maven.org/maven2)
[INFO] Unable to find resource 'com.sun.jmx:jmxri:jar:1.2.1' in repository central (http://repo1.maven.org/maven2)
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed to resolve artifact.

Missing:
----------
1) com.sun.jdmk:jmxtools:jar:1.2.1
...
2) javax.jms:jms:jar:1.1
...
3) com.sun.jmx:jmxri:jar:1.2.1
...
----------
3 required artifacts are missing.</code></pre>
<p>And if you&#8217;re using Eclipse, and have used the Maven Eclipse plugin command (<code>mvn eclipse:eclipse</code>) to generate the project settings, you&#8217;ll have the problem of Eclipse not being able to find the artifacts references on the build path, resulting in an error like so:</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/05/maven-log4j-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/maven-log4j-1-300x237.jpg" alt="maven-log4j-1" title="maven-log4j-1" width="300" height="237" class="alignnone size-medium wp-image-911" /></a>
</p>
<p>This causes a big problem as it essentially prevents you from building your project.  You could <a href="http://onemanwenttomow.wordpress.com/2007/12/31/maven2-log4j-and-jmx-dependencies/">download and install these artifacts</a> to your local repository, but since they&#8217;re not really needed, we should <em>exclude</em> them from the dependency list for log4j.</p>
<h2>Excluding dependencies</h2>
<p>Thankfully, Maven make it easy to <a href="http://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html">exclude dependencies</a> from a certain project.  Looking at the <a href="http://mirrors.ibiblio.org/pub/mirrors/maven2/log4j/log4j/1.2.15/log4j-1.2.15.pom">log4j 1.2.15 POM file</a> (you may have to select &#8220;View Source&#8221;), we can see several dependencies that weren&#8217;t there in the previous release.  These are likely to support new features, and aren&#8217;t needed for the most common uses of log4j.  Here are the actual dependencies for log4j 1.2.15:</p>
<pre><code>&lt;dependencies&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;javax.mail&lt;/groupId&gt;
    &lt;artifactId&gt;mail&lt;/artifactId&gt;
    &lt;version&gt;1.4&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;javax.jms&lt;/groupId&gt;
    &lt;artifactId&gt;jms&lt;/artifactId&gt;
    &lt;version&gt;1.1&lt;/version&gt;
  &lt;/dependency&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;com.sun.jdmk&lt;/groupId&gt;
    &lt;artifactId&gt;jmxtools&lt;/artifactId&gt;
    &lt;version&gt;1.2.1&lt;/version&gt;
  &lt;/dependency&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;com.sun.jmx&lt;/groupId&gt;
    &lt;artifactId&gt;jmxri&lt;/artifactId&gt;
    &lt;version&gt;1.2.1&lt;/version&gt;
  &lt;/dependency&gt;
 &lt;dependency&gt;
    &lt;groupId&gt;oro&lt;/groupId&gt;
    &lt;artifactId&gt;oro&lt;/artifactId&gt;
    &lt;version&gt;2.0.8&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;junit&lt;/groupId&gt;
    &lt;artifactId&gt;junit&lt;/artifactId&gt;
    &lt;version&gt;3.8.1&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;
&lt;/dependencies&gt;</code></pre>
<p>We only need to exclude the first four, and not the last two, since they have a scope of test, and won&#8217;t be included anyways.  <strong>To exclude these dependencies, add the log4j 1.2.15 dependency as show below.</strong></p>
<pre><code>&lt;dependency&gt;
  &lt;groupId&gt;log4j&lt;/groupId&gt;
  &lt;artifactId&gt;log4j&lt;/artifactId&gt;
  &lt;version&gt;1.2.15&lt;/version&gt;
  &lt;scope&gt;provided&lt;/scope&gt;
  &lt;exclusions&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;javax.mail&lt;/groupId&gt;
      &lt;artifactId&gt;mail&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;javax.jms&lt;/groupId&gt;
      &lt;artifactId&gt;jms&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;com.sun.jdmk&lt;/groupId&gt;
      &lt;artifactId&gt;jmxtools&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;com.sun.jmx&lt;/groupId&gt;
      &lt;artifactId&gt;jmxri&lt;/artifactId&gt;
    &lt;/exclusion&gt;
  &lt;/exclusions&gt;
&lt;/dependency&gt;</code></pre>
<p>This tells Maven not to add those artifacts to the classpath and so they won&#8217;t be needed to build your project anymore.  Note that you have to explicitly exclude each one, there is no way to exclude <strong>all</strong> of the dependencies for a project, but there is a <a href="http://jira.codehaus.org/browse/MNG-2315">feature request</a> for such an ability. </p>
<p>If you&#8217;re using Eclipse, after running <code>mvn eclipse:clean/mvn eclipse:eclipse</code>, you should have the build path properly setup without any missing artifacts:</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/05/maven-log4j-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/maven-log4j-2-300x264.jpg" alt="maven-log4j-2" title="maven-log4j-2" width="300" height="264" class="alignnone size-medium wp-image-914" /></a>
</p>
<p>Everything should now work!</p>
<h2>Transitive Dependencies and Exclusions</h2>
<p>The issue here is that the log4j 1.2.15 POM file probably should have marked these dependencies as <strong>optional</strong>, which would have had the same effect as having to exclude them on every project that referenced that version of log4j.  What does an <strong>optional</strong> dependency mean?  The <a href="http://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html">Maven website has a pretty good explanation</a>.</p>
<p>Basically, if you have a large project that requires a lot of dependencies, but the &#8220;core&#8221; features only require a subset of those dependencies, you may want to mark the others as &#8220;optional&#8221; so as not to burden any projects that reference yours.  Your project will still need all of the dependencies to build, but other projects that reference yours will only need the optional dependencies if they are using the additional features.  In this case, they&#8217;ll have to explicitly add those dependencies, as the transitive dependency rule won&#8217;t kick in for &#8220;optional&#8221; ones.</p>
<p>Also worthy to note: <strong>exclusions are done on a per-dependency basis</strong>.  This means that the dependencies that we excluded from log4j are <strong>only excluded from the log4j scope</strong>.  This has the effect of <strong>not</strong> globally excluding those dependencies.  So, for example, if we added another dependency that did really require the <code>javax.jms/jms</code> artifact, it would not be prevented from being added.  Furthermore, if we wanted, we could manually add a dependency to our own list for that JMS artifact, and it would show up as normal.</p>
<h4>References</h4>
<ol class="note less">
<li><a href="http://mavenize.blogspot.com/2007/06/exclude-transitive-dependencies.html">Exclude Transitive Dependencies</a></li>
<li><a href="http://techpolesen.blogspot.com/2007/11/maven-and-excluding-transitive.html">Maven and Excluding Transitive Dependencies</a></li>
</ol>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/05/18/resolving-log4j-1215-dependency-problems-in-maven-using-exclusions/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Google App Engine for Java: First thoughts</title>
		<link>http://unitstep.net/blog/2009/04/15/google-app-engine-for-java-first-thoughts/</link>
		<comments>http://unitstep.net/blog/2009/04/15/google-app-engine-for-java-first-thoughts/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 23:29:22 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[app engine]]></category>
		<category><![CDATA[cloud computing]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[web2.0]]></category>
		<category><![CDATA[hosting]]></category>
		<category><![CDATA[web applications]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=866</guid>
		<description><![CDATA[When Google launched App Engine about one year ago, many were excited about their expected move into the cloud computing space, but at the same time, dismayed that it only supported Python, a language seemingly favoured at the Mountain View-headquartered company. However, Google was adamant that they would begin supporting new languages and began taking [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/04/google-app-engine-java.jpg" alt="google-app-engine-java" title="google-app-engine-java" width="175" height="154" class="alignnone size-full wp-image-873" /></p>
<p>When Google <a href="http://www.readwriteweb.com/archives/google_cloud_control.php">launched App Engine about one year ago</a>, many were excited about their expected move into the cloud computing space, but at the same time, dismayed that it only supported Python, a language seemingly favoured at the Mountain View-headquartered company.</p>
<p>However, Google was adamant that they would begin supporting new languages and <a href="http://code.google.com/p/googleappengine/issues/list">began taking requests on their issue tracker</a> for what language to support next.  So, it was no surprise that <a href="http://googleappengine.blogspot.com/2009/04/seriously-this-time-new-language-on-app.html">support for Java was announced last week</a> as part of an <a href="http://code.google.com/appengine/docs/java/overview.html">&#8220;Early Look&#8221;</a> at the feature. </p>
<h2>I qualified for signup!</h2>
<p>The <a href="http://code.google.com/appengine/">Google App Engine page</a> indicated that access would be limited to the first 10,000 developers who signed up, but I was able to get approved for access after signing up over the weekend, even though Java support was launched last Wednesday on April 8th.  Google has since expanded the &#8220;early Look&#8221; <a href="http://googleappengine.blogspot.com/2009/04/early-look-at-java-language-support.html">to accommodate a total of 25,000 developers</a>, so be sure to sign up if you can!</p>
<p>The choice of Java as the next language to support was no big surprise, as indicated by <a href="http://java.dzone.com/news/will-google-app-engine-ever-su">many</a> <a href="http://news.cnet.com/8301-17939_109-10074158-2.html">articles</a> speculating on the matter.</p>
<p>Furthermore, Java is one of the most popular languages out there, both outside and inside Google, making it a logical choice.  This is seen by the numerous Java projects Google has created/supported, such as <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> and <a href="http://code.google.com/p/google-guice/">Google Guice</a>.  Additionally, Java is second to none when it comes to a viable developer ecosystem, which has resulted in great open source projects such as <a href="http://www.jboss.com/">JBoss</a>, the <a href="http://commons.apache.org/">Apache Commons</a> collections, and other libraries/frameworks that have provided great tools to any Java developer, allowing them focus on developing their application instead of worrying about lower-level problems.  There are also a great many websites out there running on J2EE, such as <a href="http://www.linkedin.com/">LinkedIn</a> and numerous corporate websites.</p>
<h2>App Engine as a enabler for free/cheap Java hosting</h2>
<p>However, this hasn&#8217;t translated into the availability of cheap web hosting for J2EE/Java development.  Typically, web hosting for a shared-server solution will be only a few dollars per month if you&#8217;re using a scripting/interpreted language like <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, Python or Perl.  If you want to develop Java web applications though, you&#8217;ll likely have to pay much more due to the complexity and overhead of the hosting provider having to run a Java VM.</p>
<p>As outlined in <a href="http://newfoo.net/2009/04/08/google-app-engine-will-change-java-web-development.html">this somewhat overly optimistic article</a>, Google&#8217;s support for Java in App Engine has the potential to change the game by offering a cheap/low-cost, or in most cases, a free solution to allow developers to begin creating J2EE/Java-based web applications.  This will have the effect of encouraging greater adoption of J2EE as a server-side solution.  In my opinion, the high cost of Java web hosting has indeed hampered its adoption by the community, as compared to alternatives like <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, Python and Ruby.</p>
<h2>Hello, World</h2>
<p>As for me, I&#8217;m currently devoting my free time to experimenting on App Engine using Java.  So far, the <a href="http://code.google.com/appengine/docs/java/runtime.html">documention</a> and <a href="http://code.google.com/appengine/docs/java/gettingstarted/creating.html">tutorial</a> seem to be fairly well-written and easy to follow, and for the most part App Engine is using the standard Java APIs for providing most of their service functionality.  Furthermore, Google has made an <a href="http://code.google.com/appengine/docs/java/tools/eclipse.html">excellent Eclipse plugin</a> for App Engine Java support, which provides not only the SDK, but also a built-in development server/Jetty-based servlet container for local testing, but also the tools necessary to upload your application to Google&#8217;s servers directly from the IDE.  Another reason why <a href="/blog/2008/02/10/eclipse-the-best-and-only-ide-youll-ever-need/">Eclipse is the best IDE</a> out there.</p>
<p>I hope to have something working within a few days, at least to test the service and play around with its capabilities.  Overall, I&#8217;m very impressed!</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/04/15/google-app-engine-for-java-first-thoughts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the Basic Constraints extension in X.509 v3 certificates for intermediate CAs</title>
		<link>http://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/</link>
		<comments>http://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 03:15:36 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[certificates]]></category>
		<category><![CDATA[cryptography]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pki]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[X.509]]></category>
		<category><![CDATA[bouncy castle]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[extensions]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=773</guid>
		<description><![CDATA[It&#8217;s not often that you&#8217;ll be creating your own X.509 certificates for a web server, since any certificates that you create (self-signed or signed by your own CA) will not be trusted by most browsers (IE, Firefox, etc.) since they were not signed by one of the many Certificate Authorities (CAs) that have been automatically [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s not often that you&#8217;ll be creating your own X.509 certificates for a web server, since any certificates that you create (self-signed or signed by your own CA) will not be trusted by most browsers (IE, Firefox, etc.) since they were not signed by one of the many Certificate Authorities (CAs) that have been automatically trusted by the browser.  If you do decide to use one of these certificates on your web server, you&#8217;ll have to navigate through <a href="http://blog.ivanristic.com/2008/04/firefox-3-ssl-i.html">a Byzantine series of screens to &#8220;confirm&#8221; that you trust the server&#8217;s certificate</a>.  (Though this is annoying, it may be ultimately beneficial in today&#8217;s era of phishing and other malicious behaviour.)</p>
<h2>A bit of background</h2>
<p>However, what I want to discuss today relates to <em>certificate chains</em>.  At the top of every certificate chain is a <strong>root CA</strong>, whose certificate is <em>self-signed</em>.  This sort of certificate can be considered a &#8220;God certificate&#8221; because it essentially says, <em>&#8220;Trust me, because I say so&#8221;</em>.  As you can imagine, that&#8217;s not much of an argument for trusting someone, so that is why your browser has a list of <em>default root CAs</em> that it automatically trusts.  </p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-0.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-0-300x207.jpg" alt="basic-constraints-0" title="basic-constraints-0" width="300" height="207" class="alignnone size-medium wp-image-775" /></a><br />
Some default trusted CAs in Firefox.
</p>
<p>These root CAs are owned and operated by companies that are in the business of <em>issuing certificates</em> to other people for use on their servers.  They have been added to the default trusted list of most browsers so that an end user doesn&#8217;t need to manually add all of them; doing so would be a usability nightmare.  Essentially, these root CAs provide a <strong>trust anchor point</strong>, as not only are they trusted, but <em>any certificates they issue will also be automatically trusted by the browser</em>.  Attempting to visit a HTTPS/SSL website that does not have a trusted certificates results in a <a href="http://jeremy.visser.name/2008/01/26/firefox-3-ssl-error/">nasty warning from modern browsers</a>.</p>
<p>Rarely is the root CA certificate directly used for a web server, but instead it is used to <strong>sign or issue other certificates</strong> that are then used on a web server to confirm its identity and provide for secure end-to-end communication.</p>
<p>As you can imagine, operating a CA is an immense responsibility, so that is why these default lists have been setup: Essentially these companies have to vet entities that purchase certificates from them, to make sure they actually own the domain that they are trying to buy a certificate for, otherwise phishing would become too easy!  Even so, these companies sometimes still have <a href="http://www.win.tue.nl/hashclash/rogue-ca/">lapses due to use of outdated technologies and poor security practices</a>, but that is another complicated issue for another day.</p>
<h2>Issuing a certificate &#8211; An example</h2>
<p>The act of <strong>issuing a certificate</strong> essential entails a CA using its public-private key pair to sign the contents of the certificate that is being issued.  This ties the identity information in the certificate to its key pair and provides confirmation that the CA has affirmed the authenticity of the certificate, I.E., that it has truly issued this certificate and that it has not been forged.</p>
<p>Going back to a certificate chains, it was previously mentioned that the root CA certificate is at the top of the chain.  Any certificates it issues are directly below it, so if these certificates are directly used on a web server, then the chain is of length two.  However, certificate chains can be longer.  If a certificate chain is longer than two, then this indicates the presence of an <strong>intermediate CA</strong>.</p>
<p>An intermediate CA is a CA that does not have a self-signed certificate but still has the capability to issue certificates that are trusted.  For an example of the root CA to intermediate CA relationship, we can look at the certificate chain returned from <a href="https://mail.google.com">https://mail.google.com</a>:</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-1-254x300.jpg" alt="basic-constraints-1" title="basic-constraints-1" width="254" height="300" class="alignnone size-medium wp-image-785" /></a><br />
The Root CA certificate from VeriSign, an X.509 v1 certificate.
</p>
<p>Above we see the <em>root CA certificate</em>, a self-signed certificate created/issued by <strong>VeriSign</strong>.  I&#8217;ve highlighted the fact that it is an X.509 <strong>version 1</strong> certificate, which also means it doesn&#8217;t have any <strong>certificate extensions</strong>.  This may not mean much right now, but we&#8217;ll get back to it soon.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-2-254x300.jpg" alt="basic-constraints-2" title="basic-constraints-2" width="254" height="300" class="alignnone size-medium wp-image-787" /></a><br />
The Intermediate CA certificate from Thawte, an X.509 v3 certificate.
</p>
<p>This next shot shows the <em>intermediate CA certificate</em> that was issued by the root CA.  This certificate has been issued to <strong><a href="http://en.wikipedia.org/wiki/Thawte">Thawte</a></strong>, a company coincidentally founded by Mark Shuttleworth, the South African man behind Canonical/Ubuntu.  Thawte was acquired by VeriSign during the dot-com craze for US $575 million.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-3.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-3-254x300.jpg" alt="basic-constraints-3" title="basic-constraints-3" width="254" height="300" class="alignnone size-medium wp-image-788" /></a><br />
The &#8220;Basic Constraints&#8221; extension of the intermediate CA.
</p>
<p>We can clearly see that this certificate is an X.509 <strong>version 3</strong> certificate, meaning it does support certificate extensions.  One of its extensions is a <strong><a href="http://www.alvestrand.no/objectid/2.5.29.19.html">Basic Constraints</a></strong> extension, which has been set to signify that this is indeed a Certificate Authority.  It also specifies one other parameter, which is the maximum number of intermediate CAs allowed <em>beneath</em> this one in the certificate chain hierarchy.  Since this value is set to 0, this means this intermediate CA <strong>cannot</strong> issue any more CA certificates, but instead can only issue <strong>client certificates</strong>.  Any attempt will to use a client certificate from this CA as a CA or signing certificate will fail, when consumed by a conforming client.</p>
<h2>The client certificate</h2>
<p>The last screenshot shows the <strong>client certificate</strong>, which is the last certificate in the chain.  This is the certificate that is used by the server at <code>mail.google.com</code> to secure HTTPS traffic, and as we can see, it is also an X.509 v3 certificate (has extensions) and one of those extensions is the &#8220;Basic Constraints&#8221; extension.  This time it is set to indicate that this is <strong>not</strong> a CA certificate.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-4.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-4-254x300.jpg" alt="basic-constraints-4" title="basic-constraints-4" width="254" height="300" class="alignnone size-medium wp-image-789" /></a><br />
The Basic Constraints of the client certificate, indicating it is <strong>not</strong> a CA certificate.
</p>
<h2>Basic Contraints &#8211; Why it&#8217;s needed</h2>
<p>The &#8220;<strong>Basic Constraints</strong>&#8221; extension is one way for a CA to control the usage of the certificates it issues.  For instance, when the root CA certificate in the example above issued the intermediate CA certificate, it set the Basic Constraints extension to signify that:</p>
<ul>
<li>The issued certificate is for a Certificate Authority, i.e. an intermediate CA.</li>
<li>This certificate <strong>may not</strong> be used to create further CA certificates</li>
</ul>
<p>In turn, the intermediate CA certificate was used to create the client certificate for <code>mail.google.com</code>, and it attached a Basic Constraints extension to signify that this certificate <strong>was not</strong> a CA certificate.  By doing this, it was indicating that this certificate should not be used to sign/create further certificates.</p>
<p>This is necessary because of the how trust relationship works in X.509 PKI.  Someone who trusts the root CA implicitly trusts all the intermediate CAs, and then by extension, all the client certificates issued by those intermediate CAs! (Note how this creates a single point-of-failure at the root CA as well)</p>
<p>If the CA could not control what the certificates it issued were used for, then someone could purchase a VeriSign certificate and use it to sign/create other certificates which would also be trusted by default! Clearly, this is not desirably from a security or financial point of view, if you are VeriSign.  By using extensions such as the Basic Constraints one, the signing CA can enact fine-grained control over how the certificate is used.  If the client certificate was used to sign another certificate, that certificate would be rejected by a browser that conformed to the X.509 v3 specifications.</p>
<h2>The Grey Area</h2>
<p>However, we run into a &#8220;grey area&#8221; of sorts when faced with a certificate that <strong>does not have a Basic Constraints extension</strong>.  In this case, it is not indicated whether this is a CA certificate or not.  How do the browsers respond in this scenario? In this case, it seems to depend on whether the CA is a root CA or an intermediate one.</p>
<p>For root CA certificates, it seems that the Basic Constraints extension is not required in order for the CA certificate to be viewed as valid from the browser&#8217;s point of view.  (I&#8217;ve observed this in Firefox and Internet Explorer)  This most likely stems from the fact that there are root CAs that were created and put into operation well before X.509 v3 extensions were in wide use.  The VeriSign root CA in our example is an X.509 v1 certificate with a starting validity date of 1996-01-28.</p>
<p>However, for intermediate CAs, it seems that the Basic Constraints extension <strong>is required</strong> if you want things to work, at least in Firefox and Internet Explorer.  I encountered this situation when working with a Private Root CA of my own.  I was trying to create an intermediate CA (without any Basic Constraints extension) from this root CA, and was running into problems when using this intermediate CA to create client certificates.  Any of the client certificates from the intermediate CA were being essentially rejected by the browser when attempting to visit the website they were being used for.</p>
<p>Because this was a &#8220;grey area&#8221;, the results were mixed.  In Firefox, the site would load correctly, however when attempting to view the certificate chain (by double-clicking the lock icon in the lower right), only the client certificate could be viewed, not the fully certificate chain.  Internet Explorer would show the full certificate chain but simply failed to load the page.  Neither browser gave any indication as to why things were failing.</p>
<p>However, once I created an Intermediate CA with a Basic Constraints extension set to explicitly signify that this was indeed a CA, everything worked as expected.  I don&#8217;t believe this is well-documented, though this is understandable since most people will not be creating their own Private CAs unless it&#8217;s for a very specialized purpose.</p>
<h2>How to do this using the Bouncy Castle APIs</h2>
<p>I&#8217;ve talked about the <a href="/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/">Bouncy Castle Java APIs</a> before, and they have been an invaluable resource for simplifying the creation of a Private CA and for issuing certificates.</p>
<p>When issuing a certificate it&#8217;s fairly easy to set the Basic Constraints extension to indicate you want the certificate to be a CA certificate.  First, take a look at this <a href="http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation">guide to under the fundamentals of certificate creation</a> with the Bouncy Castle APIs, then look at this code fragment:</p>
<pre><code>private static final int NUM_ALLOWED_INTERMEDIATE_CAS = 0;
...

// Construct the certificate.
final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

...

// Need this extension to signify that this certificate is a CA and
// can issue certificates. (Extension is marked as critical)
certGen.addExtension( X509Extensions.BasicConstraints, true, new BasicConstraints(
  NUM_ALLOWED_INTERMEDIATE_CAS ) );

...

final X509Certificate intermediateCaCert = certGen.generate( signingCaPrivateKey, "SunRsaSign" );</code></pre>
<p>By doing this you ensure that the intermediate CA certificate has the proper Basic Constraints extension to work correctly with modern web browsers.</p>
<h2>Conclusion</h2>
<p>I hope you found this helpful.  Certainly if you&#8217;re here, you&#8217;ve been puzzled over the same issues that I struggled through!</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation">X.509 Public Key Certificate and Certification Request Generation</a></li>
<li><a href="http://www.alvestrand.no/objectid/2.5.29.19.html">OID 2.5.29.19 &#8211; Basic Constraints</a></li>
<li><a href="http://www.oid-info.com/get/2.5.29.19">OID Repository &#8211; basicConstraints(19)</a></li>
</ol>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Java Polymorphism and Overriding Methods</title>
		<link>http://unitstep.net/blog/2009/02/13/java-polymorphism-and-overriding-methods/</link>
		<comments>http://unitstep.net/blog/2009/02/13/java-polymorphism-and-overriding-methods/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 16:18:10 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=600</guid>
		<description><![CDATA[Most Java developers will be familiar with polymorphism &#8211; we&#8217;ve all seen the example of the Dog and Cat classes inheriting from some abstract Animal class and having their say() methods produce different results. But it&#8217;s still worthwhile to look at a few simple examples to reinforce the concepts. First, we define a simple class [...]]]></description>
			<content:encoded><![CDATA[<p>Most Java developers will be familiar with polymorphism &#8211; we&#8217;ve all seen the example of the <code>Dog</code> and <code>Cat</code> classes inheriting from some abstract <em>Animal</em> class and having their <code>say()</code> methods produce different results.  But it&#8217;s still worthwhile to look at a few simple examples to reinforce the concepts.</p>
<p>First, we define a simple class with one instance method and one static method.</p>
<pre><code>public class A
{
  public String getName()
  {
    return "I am A";
  }

  public static String getStaticName()
  {
    return "Statically A!";
  }
}</code></pre>
<p>Then we extend that class with one that has identical method signatures.</p>
<pre><code>public class B extends A
{
  // Note: @Override only makes sense for instance methods.
  // The annotation is not needed but makes for best practices, since if the
  // method DOES NOT override a superclass, a compile-time error will be
  // generated, limiting damage. (@Override was added in Java 1.5)
  @Override
  public String getName()
  {
    return "I am B";
  }

  public String onlyOnB()
  {
    return "Only available on B";
  }

  // Cannot @Override, generates a compile error. Instead, this methods
  // `hides` the one in the super class.
  public static String getStaticName()
  {
    return "Statically B!";
  }

  public static void main( String[] args )
  {
    A a = new A();
    B b = new B();

    A b_as_a = new B();
    A b_as_a_copied_from_reference = b;

    System.out.println(a.getName());
    System.out.println(a.getStaticName() + "\n");

    System.out.println(b.getName());
    System.out.println(b.getStaticName() + "\n");

    System.out.println(b_as_a.getName());
    System.out.println(b_as_a.getStaticName() + "\n");

    System.out.println(b_as_a_copied_from_reference.getName());
    System.out.println(b_as_a_copied_from_reference.getStaticName() + "\n");
  }
}</code></pre>
<p>Sorry for the funky variable names in <code>main()</code>, but camelCase just didn&#8217;t look good.  Anyway, can you guess the output of the program?  It&#8217;s actually quite interesting:</p>
<pre><code>I am A
Statically A!

I am B
Statically B!

I am B
Statically A!

I am B
Statically A!</code></pre>
<p>The first two are fairly straightforward, since for variables <code>a</code> and <code>b</code>, the declared type matches the instantiated type, so there can be no doubt.  But what happens when the declared type does not match the instantiated type, as in the second two examples?</p>
<p>The short answer is this: <strong>When instance methods are invoked, they will always be called on the instantiated type, regardless of the declared type.  When static or class methods are invoked, they will be called on the declared type.</strong></p>
<h2>Declared type vs. instantiated type</h2>
<p>You can think of the declared type as a &#8220;window&#8221; into the actual instantiated type.  This &#8220;window&#8221; provides a view as to what methods are available for invocation and provides these hints to the compiler.  This is why you cannot call a method that exists on an instantiated type unless it has been declared or exists on the declared type.  (The use of interfaces provides the best example of this)</p>
<p>When an <em>instance method</em> is invoked, the JVM will then determine the <em>runtime</em> type of the variable and then call the appropriate method on that object.  This is why for the last two examples, the output was <code>I am B</code>, even though the declared type was <code>A</code>.  This is what allows polymorphism to work in Java.</p>
<p>However, when a <em>static or class method</em> is invoked, it will always be invoked from the <em>declared type</em>, regardless of what the runtime or instance type is.  This is because static methods are <em>per-class</em> rather than <em>per-instance</em> and thus the exact method invoked can be determined at compile time from the declared type.  This is why for the last two examples, the output is from the the method defined on class <code>A</code>, the declared type of the two variables.</p>
<h2>What Sun has to say</h2>
<p><a href="http://java.sun.com/docs/books/tutorial/java/IandI/override.html">Sun&#8217;s own tutorials</a> on these subjects refers to this as <em>hiding</em>; that is, when a subclass static method has the same signature as one in a superclass, it <em>hides</em> it instead of overriding it.  <em>Override</em> is a term reserved for instance methods only, and in fact, marking <code>getStaticName()</code> with the annotation <code>@Override</code> in class <code>B</code> results in a compile-time error.</p>
<p>However, to me, it&#8217;s far simpler to just remember that static methods are always invoked on the <em>declared type</em>, while instance methods will be invoked on the <em>instantiated type</em>.  This provides an easy way to remember how things work in the JVM.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/02/13/java-polymorphism-and-overriding-methods/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Handling mutable fields in Java</title>
		<link>http://unitstep.net/blog/2008/12/14/handling-mutable-fields-in-java/</link>
		<comments>http://unitstep.net/blog/2008/12/14/handling-mutable-fields-in-java/#comments</comments>
		<pubDate>Mon, 15 Dec 2008 02:11:27 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[mutability]]></category>
		<category><![CDATA[objects]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=604</guid>
		<description><![CDATA[In Java, a mutable object is one whose state can be altered after it has been instantiated. An immutable object is one whose state is fixed after instantiation; that is, the data represented by the object cannot be changed in that object. Perhaps the most well-known immutable type is the built in String class; while [...]]]></description>
			<content:encoded><![CDATA[<p>In Java, a <em>mutable</em> object is one whose state can be altered after it has been instantiated.  An <em>immutable</em> object is one whose state is fixed after instantiation; that is, the data represented by the object cannot be changed in that object.  Perhaps the most well-known immutable type is the built in <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html">String</a> class; while there are methods on the String class that seemingly alter its state (such as <code>toUpperCase()</code> and <code>trim()</code>), in actuality these methods return a <em>new</em> String object if changes had to be made.  In this article I&#8217;ll discuss how mutability will affect how you expose private fields in objects.</p>
<h2>Pop Quiz</h2>
<p>Consider the following code fragment.  We create a <code>MapContainer</code> object, and then get the contained map, which is guaranteed to have a certain value associated with the key &#8220;today&#8221;.  We then alter the value associated with this key, using our <em>local reference</em> to returned map.  We then query the <code>MapContainer</code> object and get the contained map again.  What is the value associated with the key &#8220;today&#8221; in this map?</p>
<pre><code>final MapContainer mapContainer = new MapContainer();
final Map&lt;String, String&gt; map = mapContainer.getKeyValuePairs();

final String today = map.get("today");
assert null != today;
System.out.println(today);  // Returns the current date-time.

// Change the value using our local reference.
map.put("today", "tomorrow");

final Map&lt;String, String&gt; mapAgain = mapContainer.getKeyValuePairs();
System.out.println(mapAgain.get("today")); // What is output?</code></pre>
<p>Don&#8217;t waste too much time on this problem, as it&#8217;s a trick question.  The answer actually depends on the implementation of <code>MapContainer</code>.  Depending on how it&#8217;s implemented, the second output could be unchanged from the first <strong>or</strong> be changed to the new value of &#8220;tomorrow&#8221;.</p>
<h2>It&#8217;s all in the getters</h2>
<p>Let&#8217;s take a look at the code for <code>MapContainer</code>.  </p>
<pre><code>import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MapContainer
{
  final private Map&lt;String, String&gt; keyValuePairs;

  public MapContainer()
  {
    this.keyValuePairs = new HashMap&lt;String, String&gt;();
    this.keyValuePairs.put("today", new Date().toString());
  }

  public Map&lt;String, String&gt; getKeyValuePairs()
  {
    return keyValuePairs;
  }
}</code></pre>
<p>We have a simple constructor that initializes the <code>keyValuePairs</code> Map and adds one value for the current date-time.  But the real &#8216;key&#8217; (no pun intended) to solving the problem is looking at the getter for the field.  As you can see, it simply returns a reference to the private field.  <strong>Under this implementation, a caller is able to alter the contents of the private field/Map even though no public &#8220;set&#8221; methods are available</strong>.  Why is this? For two reasons: In Java, objects are passed/returned by reference, and <code>HashMap</code> is a mutable object.  Thus using this implementation, the second output from our original code fragment is &#8220;tomorrow&#8221;, since the caller has altered the contents of the Map through the returned reference.</p>
<p>Furthermore, the original reference returned from the getter is not independent either; if some other code were to call the get method on the <code>MapContainer</code> object and make changes to the Map, those changes would also be reflected in the original returned reference!</p>
<p>How can we &#8220;fix&#8221; this? We simply have to ensure that the getter for the field returns a reference to a <em>copy</em> of the private Map.  This is easy since there is a <a href="http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#HashMap(java.util.Map)">constructor for <code>HashMap</code></a> that accepts an existing Map.  Here&#8217;s the altered code:</p>
<pre><code>import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MapContainer
{
  final private Map&lt;String, String&gt; keyValuePairs;

  public MapContainer()
  {
    this.keyValuePairs = new HashMap&lt;String, String&gt;();
    this.keyValuePairs.put("today", new Date().toString());
  }

  public Map&lt;String, String&gt; getKeyValuePairs()
  {
    <strong>return new HashMap&lt;String, String&gt;(keyValuePairs);</strong>
  }
}</code></pre>
<p>With these changes, the private Map cannot be altered by a caller and thus the second output will remain changed in our first code fragment example.</p>
<h2>To change, or not to change?</h2>
<p>It should be noted that sometimes you <em>may want to allow</em> callers to alter the backing data structure that you return from a get method.  For example, some of the data structures from the <a href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html">Java Collection Framework</a> have getters that return references that can be used to alter the state of the original object.  A good example is the <a href="http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#entrySet()"><code>entrySet()</code></a> method of the <code>HashMap</code> object. </p>
<p>But in my opinion, these examples are the exception rather than the rule.  In general, you do not want to allow callers to be able to alter the state of private fields directly since this violates information-hiding principles.  If there is some change a caller needs to make to your object, it&#8217;s best accomplished through a set method since this allows you to control the changes and prevents unwanted/unexpected situations.  If you do decide to allow callers to directly alter the state of private fields, it&#8217;s best to explicitly document this in the JavaDoc.</p>
<h2>Mutability and safety</h2>
<p>Note that in this example the field used was a <code>HashMap</code> object, which was mutable.  If the field consisted of an immutable object, like a <code>String</code>, you would not have to worry about making a copy before returning it.  This is because if the object is immutable, you do not have to worry about a caller changing its state because this is impossible to do!  This is why immutable objects are much easier to deal with in multithreaded/concurrent environments.</p>
<p>Note that mutability has nothing to do with the <code>final</code> keyword in Java, contrary to <a href="http://mindprod.com/jgloss/mutable.html">this definition</a>.  Simply marking a field as &#8220;<code>final</code>&#8221; will not magically change a mutable object into an immutable one.  As we saw earlier, whether an object is mutable or not depends entirely on its implementation, the details of which should be expressed in the JavaDoc for that class.  The <code>final</code> keyword only ensures that you cannot reassign that field/variable to completely new reference or object; it <strong>does not</strong> ensure that you can&#8217;t change the state of the object already referenced.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/12/14/handling-mutable-fields-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extracting X509 Extensions from a CSR using the Bouncy Castle APIs</title>
		<link>http://unitstep.net/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/</link>
		<comments>http://unitstep.net/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/#comments</comments>
		<pubDate>Tue, 28 Oct 2008 02:01:07 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[certificates]]></category>
		<category><![CDATA[cryptography]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pki]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[X.509]]></category>
		<category><![CDATA[ca]]></category>
		<category><![CDATA[certificate]]></category>
		<category><![CDATA[certificate request]]></category>
		<category><![CDATA[csr]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=407</guid>
		<description><![CDATA[The Bouncy Castle Cryptography Java APIs are an excellent set of APIs that act as a provider for JCE and JCA. Additionally, they take care of the mundane and tedious (some would say overly complicated) details involved in reading and creating the data structures associated with the X.500 and PKCS standards. (The APIs are also [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://bouncycastle.org/">Bouncy Castle Cryptography Java APIs</a> are an excellent set of APIs that act as a provider for JCE and JCA.  Additionally, they take care of the mundane and tedious (some would say overly complicated) details involved in reading and creating the data structures associated with the X.500 and PKCS standards. (The APIs are also available in C#, for .NET developers out there)</p>
<p>One thing they handle well is the concept of certificate extensions.  X.509 v3 certificates introduced the concept of these extensions, which are basically additional (potentially optional) fields containing information not contained in the older original X.509 specifications.  Each extension is specified by an OID (Object Identifier); a good <a href="http://www.alvestrand.no/objectid/2.5.29.html">list of these extensions</a> is available.</p>
<p>While it&#8217;s easy to read these extensions from an existing X.509 v3 certificate using the Bouncy Castle APIs it is a bit more involved to read these extensions from a <a href="http://en.wikipedia.org/wiki/Certificate_signing_request">Certificate Signing Request</a>, or CSR; this is the data structure that is sent to a CA to request a certificate.  The CA then reads the data from this and creates a signed certificate issued to the requester.  In this guide I&#8217;ll present a brief way to extract X.509 <a href="http://www.alvestrand.no/objectid/submissions/1.2.840.113549.1.9.14.html">extensions request</a> from a CSR so that they may be included in the resulting issued certificate.</p>
<h3>Code: The good stuff</h3>
<p>Assuming you have added the Bouncy Castle JARs to your classpath, you should have access to the classes used here.  </p>
<p>You must first have the CSR in the format of a Bouncy Castle data object, namely the <a href="http://www.cs.berkeley.edu/~jonah/bc/org/bouncycastle/jce/PKCS10CertificationRequest.html"><code>PKCS10CertificationRequest</code></a>. If all you have is the PEM-format of the CSR (i.e. Base64-encoded contents delimited by headers like <code>----- BEGIN CERTIFICATE REQUEST -----</code> and <code>----- END CERTIFICATE REQUEST -----</code>) then you will need to convert  this to the proper data structure using something like<br />
<a href="http://juliusdavies.ca/commons-ssl/javadocs/org/apache/commons/ssl/PEMUtil.html">PEMUtil</a> from Commons-SSL like I have done below.  (BC has a <a href="http://www.eecs.berkeley.edu/~jonah/javadoc/org/bouncycastle/jce/provider/PEMUtil.html">PEMUtil</a> class as well, but it appears to be only for internal use)</p>
<pre><code>// NOTE: Commons-SSL doesn't support generics.
final List pemItems = PEMUtil.decode( csrContent.getBytes() );

// Verify list isn't empty - uses Apache Commons Lang.
Validate.isTrue( !pemItems.isEmpty() );

// No support for generics, so have to cast. (Could have cast the entire List)
final PEMItem csrPemFormat = (PEMItem) pemItems.get( 0 );

// Verify the type.
Validate.isTrue( csrPemFormat.pemType.equals( "CERTIFICATE REQUEST" ),
  "This is not a CSR" );

final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
  csrPemFormat.getDerBytes() );</code></pre>
<p>We first decode the PEM (Base64) CSR into <code>List</code> of <a href="http://juliusdavies.ca/commons-ssl/javadocs/org/apache/commons/ssl/PEMItem.html"><code>PEMItem</code></a>s. Note that Commons-SSL doesn&#8217;t support <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html">generics</a>, so you are going to get a cast warning somewhere in the code, no matter what.  When calling <code>getBytes()</code> on the CSR string, you may want to specify the <code>US-ASCII</code> character set, since the no-arg method uses the platform default character set, which might give inconsistent results across different systems when converting from characters to bytes. </p>
<p>We then grab the first entry in the list, checking if it is a CSR.  We can now convert this into the proper data structure by supplying the raw bytes (i.e. the DER-encoded format) to the constructor of <code>PKCS10CertificationRequest</code>.</p>
<p>The method to extract the <a href="http://www.cs.berkeley.edu/~jonah/bc/org/bouncycastle/asn1/x509/X509Extensions.html"><code>X509Extensions</code></a> structure from the <code>PKCS10CertificationRequest</code> is shown below.</p>
<pre><code>   /**
    * Gets the X509 Extensions contained in a CSR (Certificate Signing Request).
    *
    * @param certificateSigningRequest the CSR.
    * @return the X509 Extensions in the request.
    * @throws CertificateException if the extensions could not be found.
    */
   X509Extensions getX509ExtensionsFromCsr(
         final PKCS10CertificationRequest certificateSigningRequest ) throws CertificateException
   {
      final CertificationRequestInfo certificationRequestInfo = certificateSigningRequest
            .getCertificationRequestInfo();

      final ASN1Set attributesAsn1Set = certificationRequestInfo.getAttributes();

      // The `Extension Request` attribute is contained within an ASN.1 Set,
      // usually as the first element.
      X509Extensions certificateRequestExtensions = null;
      for (int i = 0; i &lt; attributesAsn1Set.size(); ++i)
      {
         // There should be only only one attribute in the set. (that is, only
         // the `Extension Request`, but loop through to find it properly)
         final DEREncodable derEncodable = attributesAsn1Set.getObjectAt( i );
         if (derEncodable instanceof DERSequence)
         {
            final Attribute attribute = new Attribute( (DERSequence) attributesAsn1Set
                  .getObjectAt( i ) );

            if (attribute.getAttrType().equals( PKCSObjectIdentifiers.pkcs_9_at_extensionRequest ))
            {
               // The `Extension Request` attribute is present.
               final ASN1Set attributeValues = attribute.getAttrValues();

               // The X509Extensions are contained as a value of the ASN.1 Set.
               // Assume that it is the first value of the set.
               if (attributeValues.size() &gt;= 1)
               {
                  certificateRequestExtensions = new X509Extensions( (ASN1Sequence) attributeValues
                        .getObjectAt( 0 ) );

                  // No need to search any more.
                  break;
               }
            }
         }
      }

      if (null == certificateRequestExtensions)
      {
         throw new CertificateException( "Could not obtain X509 Extensions from the CSR" );
      }

      return certificateRequestExtensions;
   }</code></pre>
<p>Basically, we get the certificate request info from the CSR structure and then extract attributes from it.  Then, we loop through to find the attribute with the <a href="http://www.alvestrand.no/objectid/submissions/1.2.840.113549.1.9.14.html">&#8220;Extension Request&#8221; OID</a>.</p>
<p>After that, I make an assumption that the actual extensions are contained in the first value of the place of the ASN.1 Set that makes up the &#8220;Extensions Request&#8221; structure &#8211; not a big assumption, and in my testing I haven&#8217;t encountered a situation where this wasn&#8217;t the case.  It&#8217;s worthwhile to keep in mind that ASN.1 often prescribes Set or multi-value structures in places where the underlying data can  only be single-valued. </p>
<p>After running through that code, we&#8217;ll have either found the extensions, and be returning them in a <a href="http://www.cs.berkeley.edu/~jonah/bc/org/bouncycastle/asn1/x509/X509Extensions.html"><code>X509Extensions</code></a> structure, or an exception will be thrown.  You could modify the code to return <code>null</code> if that suits your style or purpose better.</p>
<h3>A few more notes</h3>
<p>Once you have the <code>X509Extensions</code> structure you can use the extensions contained within to create/issue a certificate with them.  Check out the <a href="http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation">Bouncy Castle Guide on Certificate Generation</a> for more details.</p>
<p>Note that a CA is <em>not required</em> to use any of the extension requests present in a CSR &#8211; hence the name &#8220;requests&#8221;.  It is entirely up to the CA to decide what extensions are appropriate, along with their values, for the certificates that it issues.  </p>
<h3>Code Review</h3>
<p>The code is a little complicated and could probably benefit from some refactoring.  However, a lot of the complexity derives from the fact that the X.509 and associated standards are quite complex themselves.  This is a reflection on the vision that the designers of X.509 had for the future of the standard.  However, the <a href="http://www.cs.auckland.ac.nz/~pgut001/pubs/x509guide.txt">complexity of X.509</a> is another topic for another article.  </p>
<p>I hope you found this article useful, as while I found lots of information for <a href="http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation">generating CSRs</a>, information on parsing and working with them was a little sparse.  Please feel free to leave your comments below!</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

