<?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; guides</title>
	<atom:link href="http://unitstep.net/blog/category/guides/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<lastBuildDate>Mon, 19 Mar 2012 01:49:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Java, Weak References and WeakHashMap</title>
		<link>http://unitstep.net/blog/2011/03/26/java-weak-references-and-weakhashmap/</link>
		<comments>http://unitstep.net/blog/2011/03/26/java-weak-references-and-weakhashmap/#comments</comments>
		<pubDate>Sat, 26 Mar 2011 16:27:19 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[guides]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[references]]></category>
		<category><![CDATA[weakhashmap]]></category>

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

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

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

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

// Now, we if set the key to null, the entry in weakHashMap will eventually
// disappear. Note that the number of times we have to 'kick' the GC
// before the entry disappears may be different on each run depending
// on the JVM load, memory usage, etc.
key = null;
int count = 0;
while(0 != weakHashMap.size())
{
  ++count;
  System.gc();
}
LOGGER.debug("Took " + count + " calls to System.gc() to result in weakHashMap size of : " + weakHashMap.size());</code></pre>
<h2>Finishing up</h2>
<p>In an upcoming article, I plan on covering the other types of references (soft and phantom) as well as the associated <code>Reference</code> classes in Java. I wanted to keep this post brief so that it provided a basic understanding of the situation.</p>
<h4>Changes/Fixes</h4>
<ul>
<li><strong>2011-04-10</strong>: Fixed numerous incorrect usages of the term &#8220;dereference&#8221;. Thanks to <a href="#comment-222992">Ranjit</a> for the explanation.</li>
</ul>
<h3>References</h3>
<ol class="note less">
<li><a href="http://download.oracle.com/javase/6/docs/api/java/lang/ref/package-summary.html">Package java.lang.ref</a></li>
<li><a href="http://download.oracle.com/javase/6/docs/api/java/util/WeakHashMap.html">WeakHashMap</a></li>
<li><a href="http://weblogs.java.net/blog/2006/05/04/understanding-weak-references">Understanding Weak References</a></li>
</ol>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2011/03/26/java-weak-references-and-weakhashmap/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>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[development]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[JavaScript]]></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 in [...]]]></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; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/08/11/evaluation-of-boolean-values-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the Basic Constraints extension in X.509 v3 certificates for intermediate CAs</title>
		<link>http://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/</link>
		<comments>http://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 03:15:36 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[certificates]]></category>
		<category><![CDATA[cryptography]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pki]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[X.509]]></category>
		<category><![CDATA[bouncy castle]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[extensions]]></category>

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

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

...

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

...

final X509Certificate intermediateCaCert = certGen.generate( signingCaPrivateKey, "SunRsaSign" );</code></pre>
<p>By doing this you ensure that the intermediate CA certificate has the proper Basic Constraints extension to work correctly with modern web browsers.</p>
<h2>Conclusion</h2>
<p>I hope you found this helpful.  Certainly if you&#8217;re here, you&#8217;ve been puzzled over the same issues that I struggled through!</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation">X.509 Public Key Certificate and Certification Request Generation</a></li>
<li><a href="http://www.alvestrand.no/objectid/2.5.29.19.html">OID 2.5.29.19 &#8211; Basic Constraints</a></li>
<li><a href="http://www.oid-info.com/get/2.5.29.19">OID Repository &#8211; basicConstraints(19)</a></li>
</ol>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>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[debug]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[PHP]]></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 for [...]]]></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; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/01/26/getting-xdebug-to-work-with-apachexampp-to-debug-php/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Extracting X509 Extensions from a CSR using the Bouncy Castle APIs</title>
		<link>http://unitstep.net/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/</link>
		<comments>http://unitstep.net/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/#comments</comments>
		<pubDate>Tue, 28 Oct 2008 02:01:07 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[certificates]]></category>
		<category><![CDATA[cryptography]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pki]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[X.509]]></category>
		<category><![CDATA[ca]]></category>
		<category><![CDATA[certificate]]></category>
		<category><![CDATA[certificate request]]></category>
		<category><![CDATA[csr]]></category>
		<category><![CDATA[guide]]></category>
		<category><![CDATA[tutorial]]></category>

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

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

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

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

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

      final ASN1Set attributesAsn1Set = certificationRequestInfo.getAttributes();

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

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

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

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

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

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

		<guid isPermaLink="false">http://unitstep.net/blog/2008/01/24/javascript-and-inheritance/</guid>
		<description><![CDATA[JavaScript has a complicated history. The name itself seems to indicate a relationship to Java, when in fact, the two languages share little in common except for a common syntax relationship by way of C. Add to this the myriad of browser incompatibilities and numerous examples of bad usage, and you have what is perhaps [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript has a complicated history.  The <a href="http://en.wikipedia.org/wiki/Javascript#History_and_naming">name itself</a> seems to indicate a relationship to Java, when in fact, the two languages share little in common except for a common syntax relationship by way of C.  Add to this the myriad of browser incompatibilities and numerous examples of bad usage, and you have what is perhaps the world&#8217;s least understood popular programming language.  (I had to add the &#8216;popular&#8217; qualifier, since I am sure there are some esoteric languages out there that only a handful of people know)</p>
<p>This is why inheritance in JavaScript is probably one of the least understood concepts.  While languages like Java have well-defined constructs for inheritance, the topic is of less importance with JavaScript.  In many situations, you&#8217;ll never have to deal with these aspects when programming in JavaScript, simply because it isn&#8217;t required for a lot of client side scripts.  However, for larger-scale web applications, applying object-oriented principles to your code may make it easier to design, improve and maintain.</p>
<p>There have been <a href="http://javascript.crockford.com/inheritance.html">many</a> <a href="http://javascript.crockford.com/prototypal.html">articles</a> <a href="http://20bits.com/2007/03/08/the-philosophy-of-javascript/">written</a> about inheritance in JavaScript and how it can and should be done.  You really don&#8217;t need to read mine to gain an understanding.  Rather, I&#8217;m just going to write about what I&#8217;ve learned, the process I went through and the experience I&#8217;ve gained along the way. </p>
<h3>It&#8217;s all new(s) to me</h3>
<p>If you come from a Java background, you&#8217;ll be no stranger to the <code>new</code> keyword.  Using it allows you to instantiate a new instance of an object from its class by calling its constructor.  The keyword also makes a lot of sense, since you&#8217;re creating a &#8216;new&#8217; object.</p>
<p>JavaScript also has a <code>new</code> keyword, but it doesn&#8217;t do quite the same thing as its Java counterpart, though at first the effects might seem similar.  This is one of the main reasons why JavaScript inheritance tends to be poorly understood.  </p>
<p>Consider the following example.</p>
<pre><code>function Foo(name)
{
  this.name = name;
}

var fooObject = new Foo('I am foo');</code></pre>
<p>If you&#8217;re familiar with Java or JavaScript, this example is fairly straightforward.  In the prototype-based JavaScript, <a href="http://en.wikipedia.org/wiki/Javascript#Prototype-based_features">functions can serve as object constructors</a> in somewhat the same manner as a constructor in Java.  However, <code>Foo</code> in the above example is not a class, since classes do not exist in JavaScript.  So, if <code>Foo</code> is not a class, what exactly happens when the statement <code>var fooObject = new Foo('I am foo')</code> is executed?</p>
<h3>Taking a step back</h3>
<p>Before we dive into the details, I&#8217;ll explain the concepts of a prototype-based language as it applies to JavaScript.  I mentioned above that JavaScript does not use classes like Java does.  This basically means that new objects are not created from instantiation of classes, but rather inherit from existing objects.  Thus, there is no &#8220;class hierarchy&#8221; but rather just an object hierarchy.  </p>
<p>In JavaScript, all objects are descended from the built-in <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Object"><code>Object</code></a> type.  This is similar to how all Java classes implicitly have the Object class as a superclass.  In JavaScript, instead of extending classes, you can inherit by manipulating the <code>prototype</code> property on a type; that is, the <code>prototype</code> property on the function you are using to create an object.  Let&#8217;s see some code to straighten things out.</p>
<pre><code>function Foo(name)
{
  this.name = name;
}
<strong>Foo.prototype.getName = function()
{
  alert(this.name);
}</strong>

var fooObject = new Foo('I am foo');
<strong>fooObject.getName(); // Will alert with 'I am foo'</strong></code></pre>
<p>This example is identical to the first one, except for the lines that are emphasized.  Here, I&#8217;ve set the <code>getName</code> property on the <code>prototype</code> property of <code>Foo</code> equal to a reference to a Function object.  This is effectively the same as defining a method for a class, since any object created from that type can call the method <code>getName()</code> on itself to return the proper value.  But what exactly is happening, and what&#8217;s the deal with the <code>prototype</code> property?</p>
<h3>More new(s)</h3>
<p>In JavaScript, the <code>new</code> keyword actually accomplishes a few things.  When you execute an expression such as <code>var fooObject = new Foo('I am foo')</code>, here&#8217;s exactly what happens.</p>
<ol>
<li>
First, a new generic object is created.  This object is the same as if you created the object using the statement <code>new Object()</code>, using JavaScript&#8217;s <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">built in Object type</a>.
</li>
<li>
The constructor function, that is, the function <code>Foo()</code>, is then called with the <code>this</code> keyword set to reference the newly-created object.  The parameters supplied are also passed to the constructor function, in this case, the string &#8220;I am foo&#8221;.  If you&#8217;re familiar with <a href="/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/">context</a>, this is equivalent to:</p>
<pre><code>var fooObject = new Object();
Foo.call(fooObject, 'I am foo');</code></pre>
<p>Thus, the code in <code>Foo()</code> sets a property called <code>name</code> equal to the supplied string.  Up to this point, things are the same as if you had created a new object and then manually set the <code>name</code> property yourself.  The next step is where things change.
</li>
<li>
The last step is where inheritance takes effect.  The constructor function, in addition to executing the specified code above, also sets an internal property called <code>__proto__</code> equal to the value of <code>Foo.prototype</code>.  This is how the new object inherits from the old one.</p>
<p>When you call a property on <code>fooObject</code> now, JavaScript will first check to see if the object has a local value for it.  In this case, the only local property is <code>name</code>. (Besides the internal and implicitly set <code>__proto__</code> property)  However, if it does not exist locally, it will check to see if the property exists under the object referenced by the <code>__proto__</code> property.  In this case, the <code>getName()</code> method exists under here.
</li>
</ol>
<p>Where things get confusing is because of how the <code>new</code> keyword is used.  Perhaps the designers of JavaScript wanted to use a keyword familiar to Java programmers so as to ease the transition to a new language that sounded so similar.  While it accomplishes a similar goal and for the most part you can consider the action to be almost the same, the use of the <code>new</code> keyword conceals the true meaning of prototype-based inheritance in JavaScript.  This ends up causing more confusion when you start digging into code.</p>
<h3>We&#8217;re all the same</h3>
<p>Suppose you created multiple objects from the <code>Foo()</code> constructor, called <code>fooObject1</code>, <code>fooObject2</code> and <code>fooObject3</code>,   In one fell swoop, you could add a new method to all of these objects without having to recreate them.  This is because of the <code>prototype</code> property.  Because each object contains a reference to <code>Foo.prototype</code>, adding a new method here will allow all objects access to it.  For example:</p>
<pre><code>Foo.prototype.yellName = function()
{
  alert(this.name.toUpperCase());
}
var fooObject3 = new Foo('I am Foo 3!');
fooObject3.yellName(); // alerts 'I AM FOO 3!'</code></pre>
<p>This adds another method to all <code>Foo</code>-constructed objects allowing them to &#8220;yell&#8221; their names.</p>
<h3>Extending Types</h3>
<p>I mentioned inheritance above but with just one type definition, the principles weren&#8217;t too clear.  Suppose we decided to extend our <code>Foo</code> &#8220;class&#8221; &#8211; how exactly would this work?  First, you need to define the child type and then set its <code>prototype</code> value to a new object of the parent type.  An example:</p>
<pre><code>function FooChild(childName)
{
  Foo.call(this, 'I am a child of Foo and my name is ' + childName);
}
FooChild.prototype = new Foo('');

var fooChildObject = new FooChild('Barbar');
fooChildObject.getName(); // Will alert with 'I am a child of Foo and my name is Barbar'</code></pre>
<p>Let&#8217;s break down what&#8217;s going on here.</p>
<ol>
<li>
First, we define a new constructor called <code>FooChild</code>.  In it, we <code>call</code> the parent constructor function with the context set to the current object.  This allows the <code>name</code> property to be set on the object during creation since that&#8217;s what the parent does.
</li>
<li>
Then, we set the <code>prototype</code> property equal to a new object that&#8217;s an instance of <code>Foo</code>.  This is what allows all of the child objects to have access to the parent&#8217;s properties, such as the <code>getName()</code> method.  Coming from the Java world, this would be roughly equivalent to the <code>extends</code> keyword, when defining a class that inherits from another.
</li>
</ol>
<h3>A few more details</h3>
<p>JavaScript provides two special operators for dealing with types and objects.  One is called <code>instanceof</code> and the other is <code>typeof</code>.  The latter, <code>typeof</code>, is less useful since it only deals with built-in JavaScript types.</p>
<p>The <code>typeof</code> operator returns the current variable&#8217;s type, but is limited to predefined types.  For example, <code>typeof fooChildObject</code> or <code>typeof fooObject</code> both return a string with the contents of &#8220;object&#8221;.  Thus, differentiating between the two is impossible.  More information can be found <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Operators:Special_Operators:typeof_Operator">at the Mozilla Developer Center</a>.</p>
<p>The <code>instanceof</code> operator is more interesting.  It takes two arguments and tests whether the first is an instance of the second.  (I guess I didn&#8217;t need to explain that) For example:</p>
<pre><code>function Foo(name)
{
  this.name = name;
}
Foo.prototype.getName = function()
{
  alert(this.name);
}

function FooChild(childName)
{
  Foo.call(this, 'I am a child of Foo and my name is ' + childName);
}
FooChild.prototype = new Foo('');

var fooObject = new Foo('I am foo');
var fooChildObject = new FooChild('Barbar');

alert(fooChildObject instanceof Foo); // true
alert(fooObject instanceof Foo); // true
alert(fooChildObject instanceof FooChild); // true
alert(fooObject instanceof FooChild); // false;</code></pre>
<p>In the above code, it is clear that <code>fooChildObject</code> is an instance of <code>FooChild</code>, and <code>fooObject</code>is an instance of <code>Foo</code>.  However, <code>fooChildObject</code> <strong>is also</strong> an instance of <code>Foo</code>, since its type was inherited from it through the <code>prototype</code> property.  However, <code>fooObject</code> <strong>is not</strong> an instance of <code>FooChild</code> since that type is a child of <code>Foo</code>.</p>
<p>I hope I haven&#8217;t said &#8220;foo&#8221; one too many times for you.</p>
<p>More information about <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Property_Inheritance_Revisited:Determining_Instance_Relationships"><code>instanceof</code> is again available</a> from the excellent Mozilla Developer Center.</p>
<h3>Concluding remarks</h3>
<p>I hope this has helped you to understand the nature of JavaScript&#8217;s built-in inheritance features.  I know I found it very convoluted at first, coming from a class-inheritance background.  I read everything I could find on the subject, and I believe it&#8217;s made me a better JavaScript programmer by understanding some of the &#8220;inner workings&#8221; of the language.  I encourage you to check out some of the references I&#8217;ve provided below.</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://javascript.crockford.com/prototypal.html">Prototypal Inheritance in JavaScript</a> &#8211; Douglas Crockford</li>
<li><a href="http://20bits.com/2007/03/08/the-philosophy-of-javascript/">The Philosophy of JavaScript</a> &#8211; Jesse of 20bits</li>
<li><a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Property_Inheritance_Revisited">Prototype Inheritance Revisited</a> &#8211; Mozilla Developer Center</li>
<li><a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:The_Employee_Example">The Employee Example</a> &#8211; Mozilla Developer Center</li>
</ol>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/01/24/javascript-and-inheritance/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Assembla&#8217;s Trac with Eclipse Mylyn XML-RPC access</title>
		<link>http://unitstep.net/blog/2008/01/19/using-assemblas-trac-with-eclipse-mylyn-xml-rpc-access/</link>
		<comments>http://unitstep.net/blog/2008/01/19/using-assemblas-trac-with-eclipse-mylyn-xml-rpc-access/#comments</comments>
		<pubDate>Sun, 20 Jan 2008 02:16:42 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[assembla]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[mylyn]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[trac]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2008/01/19/using-assemblas-trac-with-eclipse-mylyn-xml-rpc-access/</guid>
		<description><![CDATA[I recently found out about Assembla, an awesome service for managing software development projects. It provides free SVN hosting (like other sites such as SourceForge and Google Code) but also provides tools like Trac, a Wiki, Scrum reporting, public or private access and up to 500 MB of disk space. (Additional features/space are available for [...]]]></description>
			<content:encoded><![CDATA[<p>I recently found out about <a href="http://www.assembla.com/">Assembla</a>, an awesome service for managing software development projects.  It provides free SVN hosting (like other sites such as <a href="http://sourceforge.net/">SourceForge</a> and <a href="http://code.google.com/">Google Code</a>) but also provides tools like <a href="http://trac.edgewall.org">Trac</a>, a Wiki, Scrum reporting, public or private access and up to 500 MB of disk space. (Additional features/space are available for a cost)  For many, setting up services like Trac can be <a href="http://natmaster.com/articles/installing_trac.php">notoriously difficult</a>, so with <em>free</em> services like this, it&#8217;s hard to find any nits to pick.  </p>
<p>I won&#8217;t go into too much detail about the <a href="http://www.assembla.com/tour">features</a> since I wanted to talk about integrating the Eclipse plugin Mylyn with a Trac setup on Assembla.  There can be some issues getting things to work so I&#8217;ve outlined what I did to get everything running nicely.</p>
<div class="info">
Assembla has come out with what appears to be <a href="http://www.assembla.com/wiki/show/assemblamylyn/How_To_Use">their own Mylyn connector for Eclipse</a>, which simplifies a lot of the configuration required.  It&#8217;s available at their site along with a <a href="http://www.assembla.com/wiki/show/assemblamylyn/How_To_Use">great tutorial on how to use it</a>.
</div>
<h3>Background: Mylyn</h3>
<p><a href="http://www.eclipse.org/mylyn/">Mylyn</a> is an excellent task-management plugin for the ultimate IDE, Eclipse.  I have been trying it out for a variety of things, since I was trying to find something better than just text files for managing various tasks lists.  However, Mylyn does much <a href="http://www.ibm.com/developerworks/java/library/j-mylyn1/?ca=dgr-eclipse-1">more than just task management</a> as it helps to streamline your work environment with &#8220;context&#8221;.  I haven&#8217;t started using these advanced features though, but what really caught my eye was the integration Mylyn offers with various issue-tracking services such as Bugzilla and the aforementioned Trac.  This is accomplished by various &#8220;connectors&#8221;, with each connector being specific to one of the issue-tracking systems. </p>
<h3>The Problem: <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a>-RPC Integration</h3>
<p>Integration of Mylyn with Trac allows you to view, create and edit tickets in a Trac repository from within Eclipse.  To accomplish this, there are two levels of integration, the first being simple web-based access.  This is the more primitive of the two and has been around for longer.  Basically, items are still edited from a web browser; the only difference is the web browser is spawned within Eclipse.  This isn&#8217;t really ideal and doesn&#8217;t offer a real integration.</p>
<p>The second uses an <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a>-RPC interface to send/receive data and thus offers proper integration with the Eclipse environment.  However, when trying to connect to my Trac setup on Assembla with this choice, I ran into a lot of intermittent 404 (not found) errors.  Basically, synchronization was very flaky and by no means usable.  </p>
<h3>The Fix</h3>
<p>I did some searching and found <a href="http://www.assembla.com/flows/show_comment/cm_YtanJqr3lL8abIlDkbG?parent_id=cm_YtanJqr3lL8abIlDkbG&#038;space_id=c8A2BGQEWr2RUvaaeP0Qfc">this page</a> on the Assembla site where other users had experienced the same problem.  Scrolling through the comments brought me to <a href="http://vitaliel.blogspot.com/2007/08/mylyn-with-assembla-trac-hosting.html">this nice fellow&#8217;s explanation</a> of the problem, where a screencast was provided showing how it had been fixed.</p>
<p>Basically, these are the steps I did to get Mylyn <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a>-RPC integration with Trac working.</p>
<ol>
<li>
<h4>Enable the <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a>-RPC plugin</h4>
<p>Go to your Trac site, then click on Admin.  On the left sidebar go to <strong>General > Plugins</strong>.  There should be a section called <strong>TracXMLRPC</strong>; click to expand it.  You might as well enable RPC access for all of the options provided, though I&#8217;m not sure if this is necessary.  Here&#8217;s a screenshot.</p>
<p class="image">
<a rel="lightbox" href='http://unitstep.net/wordpress/wp-content/uploads/2008/01/assembla-mylyn-trac-01.png' title='Enable the XML-RPC plugin'><img src='http://unitstep.net/wordpress/wp-content/uploads/2008/01/assembla-mylyn-trac-01.png' alt='Enable the XML-RPC plugin' /></a></p>
</li>
<li>
<h4>Enable <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a>-RPC permissions</h4>
<p>After that, you need to enable permissions for <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a>-RPC access.  Go to <strong>General > Permissions</strong> on the sidebar.  In the &#8220;<strong>Grant Permissions</strong>&#8221; area, add a permission for &#8220;<strong>XML_RPC</strong>&#8221; for &#8220;<strong>@editors</strong>&#8220;.  Using &#8220;@managers&#8221; for the subject might also work/be needed if you&#8217;ve setup access for those users.  This is the basically what it should be:</p>
<p class="image">
<a rel="lightbox" href='http://unitstep.net/wordpress/wp-content/uploads/2008/01/assembla-mylyn-trac-02.png' title='Enable XML-RPC permissions'><img src='http://unitstep.net/wordpress/wp-content/uploads/2008/01/assembla-mylyn-trac-02.png' alt='Enable XML-RPC permissions' /></a></p>
</li>
<li>
<h4>Ensure there is at least one ticket in the system</h4>
<p>For some reason, I had weird errors when trying to synchronize/connect to a Trac repository with no tickets.  This was corroborated by <a href="http://vitaliel.blogspot.com/2007/08/mylyn-with-assembla-trac-hosting.html">the fellow who originally found the solution</a> to this problem.  It&#8217;s a minor issue though, just click &#8220;New Ticket&#8221; and create a placeholder.
</li>
<li>
<h4>Add Trac to Mylyn</h4>
<p>This step&#8217;s simply enough; though some suggestions recommended using <code>http://&lt;domain_name_to_assembla_trac&gt;/&lt;space_url_name&gt;/login/xmlrpc</code> as the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>, I simply used <strong><code>http://&lt;domain_name_to_assembla_trac&gt;/&lt;space_url_name&gt;</code></strong> and it worked fine.  Remember to use <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a>-RPC as your access type or you won&#8217;t get proper integration.</p>
<p class="image">
<a rel="lightbox" href='http://unitstep.net/wordpress/wp-content/uploads/2008/01/assembla-mylyn-trac-03.png' title='Setting up Mylyn to work with Trac'><img src='http://unitstep.net/wordpress/wp-content/uploads/2008/01/assembla-mylyn-trac-03.png' alt='Setting up Mylyn to work with Trac' /></a>
</p>
</li>
</ol>
<p>After that, you should be able to properly connect to your Trac repository using the <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a>-RPC option of Mylyn.  Then, you can finally enjoy proper Trac integration in Eclipse!</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/01/19/using-assemblas-trac-with-eclipse-mylyn-xml-rpc-access/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using the &#8220;call&#8221; and &#8220;apply&#8221; methods to change the context of a function in JavaScript</title>
		<link>http://unitstep.net/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/</link>
		<comments>http://unitstep.net/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/#comments</comments>
		<pubDate>Wed, 19 Dec 2007 01:54:04 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[guides]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/</guid>
		<description><![CDATA[In JavaScript, the context that function is executing in is very important. What is context? Basically, the context of a function is what object it is &#8220;attached&#8221; to &#8211; this object will be the reference of the &#8220;this&#8221; keyword within that function. Every function has a context -that is to say, every function is attached [...]]]></description>
			<content:encoded><![CDATA[<p>In JavaScript, the context that function is executing in is very important.  What is context?  Basically, the context of a function is what object it is &#8220;attached&#8221; to &#8211; this object will be the reference of the &#8220;<code>this</code>&#8221; keyword within that function.  Every function has a context -that is to say, every function is attached to an object.  By default it is the <code>window</code> object.</p>
<p>You may have run into this particular aspect of JavaScript when working with event handlers.  For example:</p>
<pre><code>function alertId()
{
  alert (this.id);
}

document.getElementById('someId').onclick = alertId;</code></pre>
<p>This will return the &#8220;id&#8221; attribute of the element that the function has been attached to.  You could attach the same function to multiple objects and each time you called it on a different object, it would return a different value, since the context is different.  (Minor note: using <code>element.attachEvent()</code>, as part of the Microsoft event handler model, <a href="http://www.quirksmode.org/js/events_advanced.html">does not change the context</a> of the function so &#8220;<code>this</code>&#8221; will still refer to the <code>window</code> object)</p>
<p>However, there may be times when you want to change the meaning of <code>this</code> without actually having to attach that a function to an object.  Using the <code>call()</code> and <code>apply()</code> methods of the Function object can allow you to do this.</p>
<h3>Context is everything</h3>
<p>Let&#8217;s backtrack for a moment.  In JavaScript, many (but not all) variables are objects.  This includes the references to all functions as well &#8211; they are also objects.  In the example above, using &#8220;<code>alertId</code>&#8221; (<em>without</em> the parentheses) would refer to the <code>Function</code> object that represents <code>alertId</code>.  As the <code>Function</code> object is a predefined object in JavaScript, it has <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Function">methods and properties associated</a> with it.</p>
<p>Two of these methods are <code>call()</code> and <code>apply()</code>.  Using these methods on a Function object allows you to set the context of that function &#8211; that is, what the &#8220;<code>this</code>&#8221; keyword refers to.  The two only in how arguments are passed to the function whose context is being redefined.  For example <code>apply()</code> takes an array of arguments like this:</p>
<pre><code>function someFunction(arg1, arg2)
{
  this.id = arg1 + arg2;
}

var arrayOfArguments = ['valueOfArg1', 'valueOfArg2'];

someFunction.apply(objectToBeUsedAsThis, arrayOfArguments);</code></pre>
<p>The values in the second-argument array are then used as the arguments to the <code>someFunction()</code> function.  </p>
<p>The <code>call()</code> method is almost the same except it does not take an array of arguments, but rather just an indeterminate number of arguments that are all passed to the function.  For example, the above could also be accomplished with this code:</p>
<pre><code>function someFunction(arg1, arg2)
{
  this.id = arg1 + arg2;
}

someFunction.call(objectToBeUsedAsThis, 'valueOfArg1', 'valueOfArg2');</code></pre>
<p>I prefer to use <code>apply()</code> sometimes since you can directly use the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Function:arguments"><code>arguments</code></a> variable that is local within all functions. (The variable <code>arguments</code> stores all the arguments that were passed to the function when it was called, and so this can be used in a situation with where it is desired to have a function with a variable number of arguments.)</p>
<h3>A useful example</h3>
<p>So far, the examples posed have been fairly trivial.  Let&#8217;s look at a real-world use of <code>call()</code> to illustrate its usefulness.  Remember the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Function:arguments"><code>arguments</code></a> variable?  Basically, you have access to this object variable whenever you&#8217;re inside a function since it stores all the arguments passed to this function.  However, it&#8217;s not exactly an array (although it works like one sometimes) and thus it <em>does not</em> have access to <code>Array</code> methods such as <a href="http://www.devguru.com/Technologies/ecmaScript/quickref/join.html"><code>join()</code></a>.  </p>
<p>We could easily convert it into an array by accessing each property by its index using a loop, but there&#8217;s an easier to way to do this.  Consider the following code:</p>
<pre><code>function someFunction()
{
  var argsArray = Array.prototype.slice.call(arguments, 0);
}</code></pre>
<p>Using this one line, we have successfully converted the <code>arguments</code> into a true Array object and stored the result in the <code>argsArray</code> variable.  How?  First, we access the <a href="http://www.devguru.com/Technologies/ecmaScript/quickref/slice.html"><code>slice()</code></a> method on the <code>Array</code> object through the <code>prototype</code> property and then <code>call()</code> the method telling it to use the <code>arguments</code> object as <code>this</code>.</p>
<p>The <code>slice()</code> method allows us to extract a section of an existing array.  However, by using <code>call()</code> we are able to apply its effects on the <code>arguments</code> object that is similar to, but not exactly an <code>Array</code> object.  The second argument of &#8217;0&#8242; merely indicates that we want to extract not just a part of <code>arguments</code> but all of it.  Since <code>slice()</code> always returns an <code>Array</code> object, we thus get back a true array containing the same data as the <code>arguments</code> object.  And that&#8217;s it!</p>
<p>Note that the above example could be compacted even further.  However, it looks very cryptic and can be confusing. (As if the previous example wasn&#8217;t confusing enough!) </p>
<pre><code>function someFunction()
{
  var argsArray = [].slice.call(arguments);
}</code></pre>
<p>This example works the same as the previous one.  Instead of using <code>Array.prototype</code>, we create a &#8216;dummy&#8217; empty array to get access to the <code>slice()</code> method.  The second argument of &#8217;0&#8242; isn&#8217;t needed, as if it is left out when using <code>slice()</code> the entire contents will be returned.</p>
<h3>Contextual Conclusion</h3>
<p>In short, using these methods to change the scope of a function can allow you to do some neat things with JavaScript that aren&#8217;t possible in some other languages.  However, one should always be mindful to keep code readable and maintainable and to lessen the learning curve for those new to a language. </p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2007/12/18/using-the-call-and-apply-methods-to-change-the-context-of-a-function-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exception handling in JavaScript</title>
		<link>http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/</link>
		<comments>http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/#comments</comments>
		<pubDate>Mon, 26 Nov 2007 01:54:00 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[exceptions]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/</guid>
		<description><![CDATA[Exception handling is a topic that may not be well-understood by some web developers, depending on what languages they have the most experience in. In particular, PHP, one of the most common server-side languages for web development, did not have support for exception handling until version 5. In the four years between the release of [...]]]></description>
			<content:encoded><![CDATA[<p>Exception handling is a topic that may not be well-understood by some web developers, depending on what languages they have the most experience in.  In particular, <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, one of the most common server-side languages for web development, did not have support for exception handling until <a href="http://www.php.net/exceptions">version 5</a>.  In the four years between the release of PHP4 and PHP5, the language became increasingly popular among developers, and as a result, a lot of code was written without exception handling in mind.  The situation did not even improve much with the release of PHP5, since PHP5 was meant to be backwards-compatible with code developed for PHP4.  Three years later, there are still <a href="http://www.gophp5.org/">movements</a> to get developers to transition to a purely-PHP5 model.</p>
<p>Some of this may have transferred over to JavaScript, a language that is already poorly understood and often implemented even worse.  It is often hard to find well-written, maintainable JavaScript code, as it is often left as an afterthought in a project or otherwise not given much consideration, having been delegated to the realm of popup scripts and mouse-overs.  While exception handling may be overkill for a lot of JavaScript applications, many do not even know of JavaScript&#8217;s exception-handling capabilities.  In this article, I&#8217;ll give a brief overview of exception handling and some recommendations on how to use it in JavaScript to improve the readability of code. </p>
<h2>Exceptional conditions</h2>
<p>I won&#8217;t go too in-depth about the <a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html">merits of using exception handling</a> but will instead just give a brief overview.  (While there are some drawbacks, these apply more to the Java language rather than JavaScript)</p>
<p>The main reason for using exceptions is to have a separate channel for communicating errors.  Without this, you must communicate error conditions using the function itself. Consider a function that performs mathematical division:</p>
<pre><code>function divide(dividend, divisor)
{
  var quotient = dividend/divisor;
  return quotient;
}</code></pre>
<p>Division is a fairly simple arithmetic operation, but of the four basic operations it is the only one that has limits on its arguments: the divisor (the term you divide by) cannot be zero, since <a href="http://en.wikipedia.org/wiki/Division_%28mathematics%29">division by zero is undefined.</a>  So, how should you handle cases where the supplied arguments result in division by zero?  (The situation is very likely in an application accepting user input)</p>
<p>Without using exceptions, you have a few options, each of which has its own weaknesses.  Firstly, you could choose not to return <em>anything</em> and just <code>alert()</code> the user of the error.  This isn&#8217;t good since when you call the <code>divide()</code> function, you expect a result, not a warning message.</p>
<p>Secondly, you could choose to return a special &#8220;error code&#8221; indicating that there was a division by zero.  But this creates another problem &#8211; what exactly <em>do</em> you return when something goes wrong?  In this case, the only error case is division by zero &#8211; since JavaScript is a weakly-typed language, you could just return <code>false</code> on this error, but then in the calling code you&#8217;d have to check if <code>divide()</code> equaled <code>false</code> before using it, probably using the <a href="http://www.webreference.com/js/column26/stricteq.html">strict equality operator</a>.  As you can see, things get messy fast. </p>
<p>Alternatively, you could just check the inputs/arguments every time before you called the function.  However this is clumsy, and adds another layer of complexity where something could go wrong.  </p>
<h2>Another way of doing things</h2>
<p>As mentioned before, exception handling adds a side channel of sorts strictly for communicating errors.  By doing this, it allows for the interruption of program flow for the purpose of dealing with the exception or error situation.  Using exceptions, you would re-write the function above like this:</p>
<pre><code>function divide(dividend, divisor)
{
  if (0 == divisor) {
    throw new Error("Bzlorg! Cannot divide by zero.");
  }

  var quotient = dividend/divisor;
  return quotient;
}</code></pre>
<p>Here we are checking if the divisor equals zero &#8211; signifying an invalid input value &#8211; and then throwing an exception if this is the case.  How is this different than returning an error code?</p>
<p>The main difference is in the <em>control flow</em> of the program; using exceptions causes a change in the program flow.  In the above example, if the divisor equals zero, the execution of the function stops there and returns to the calling code with the throw exception.  The subsequent statements calculating the quotient and returning will not be executed.  Here&#8217;s an example of how you&#8217;d call the <code>divide</code> function.</p>
<pre><code>try {
  var dividend = 3;
  var divisor = 0;

  var quotient = divide(dividend, divisor);

  alert("The answer is " + quotient);
}
catch (e) {
  alert(e.message);
}</code></pre>
<p>With exceptions, you enclose code that could throw an exception with a <code>try</code> block.  This signifies to the interpreter (in the case of JavaScript) that you will be executing code (in this case, calling a function) that <em>could</em> throw an exception as a result of some error condition.  Thus you are <code>try</code>ing to do something &#8211; but as in real life, things may go wrong.</p>
<p>In this example, everything works until the line calling <code>divide</code>.  Since <code>divide</code> throws an exception with the input values supplied, flow will be directed to the <code>catch</code> block.  All <code>try</code> blocks must be followed with a <code>catch</code> block, with the variable in the parentheses specifying the variable to hold the thrown exception object.  In the code above, we merely alert the user to the problem &#8211; the message &#8220;Bzlorg! Cannot divide by zero&#8221; is displayed &#8211; in a real program you most likely would want to do handle the error differently depending on the context &#8211; but that&#8217;s a whole different topic.</p>
<p>If, however, you executed the code with valid values and no exceptions were thrown, once the program had got to the end of the <code>try</code> block it would jump over the following <code>catch</code> block and the user would be alerted with the correct answer.  Code within a <code>catch</code> block is <em>only</em> executed in the event that an exception is thrown.</p>
<h3>Differences with Java</h3>
<p>Since Java is an extremely popular language and one that also uses a similar exception handling model, it would be prudent to discuss some of the differences and similarities with it and JavaScript.</p>
<ol>
<li>
<h4><del>No multiple catch blocks with JavaScript</del></h4>
<p><del>This is perhaps the biggest difference.  If you&#8217;re familiar with Java you&#8217;ll know that different exception objects can be thrown during execution (all subclasses of the root/parent <code>Exception</code> class defined by Java), each signifying different error conditions.  You catch each of them separately by using separate catch blocks, each specifying a particular class or parent class.  However, with JavaScript, as you might have noticed from the code above, there can only be one catch block and thus there&#8217;s no need to specify the exception class. </del></p>
<p><del>If, however, you want the granularity of working with different exception classes, you&#8217;ll have to use the <code>instanceof</code> operator within a catch block, like this:</del></p>
<pre><code>try {
  ...
}
catch (e) {
  if (e instanceof RangeError) {
    ...
  }
  else if (e instanceof TypeError) {
    ...
   }
}</code></pre>
<p><del>It&#8217;s not as elegant as having multiple catch blocks, but it&#8217;s one way to deal with multiple exception types.</del></p>
<h4>Correction:</h4>
<p>It appears I was mistaken.  In JavaScript, you can indeed have <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Exception_Handling_Statements:try...catch_Statement#The_catch_Block">multiple catch blocks</a>, as seen in the <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide">Core JavaScript 1.5 Guide</a> from the Mozilla Developer Center.  My initial example above is still valid syntactically, but this way may be more appealing.  An example is as follows:</p>
<pre><code>try {
  ...
}
catch (e if e instanceof RangeError) {
  ...
}
catch (e if e instanceof TypeError) {
  ...
}
catch (e) {
  // General catch-all block.
  ...
}</code></pre>
<p>It just goes to show that when you think you know something, you probably don&#8217;t!  This is part of why I like JavaScript (and by extension, programming); there&#8217;s always more to learn and experience to be gained.</p>
</li>
<li>
<h4>Exception types</h4>
<p>The discussion of exception types brings us to another point &#8211; the different exception types in JavaScript.  JavaScript defines some <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Error">built-in exception</a> types, all based off the parent <code>Error</code> object.  These should suffice for most situations where you&#8217;re checking user input (the most common use), but if you&#8217;re developing a complex application you may want to define your own.  </p>
<p>In that situation, things get a little tricky, especially if you&#8217;re coming from Java.  Despite the outward similarity, JavaScript does not uses classes like Java, but instead uses a <a href="http://en.wikipedia.org/wiki/Prototype-based_programming">prototype-based approach</a> where inheritance comes from existing objects.  In this respect, things can get complicated as there are debates on <a href="http://www.sitepoint.com/blogs/2006/01/17/javascript-inheritance/">what the best way to inherit from objects</a> is and to that degree, a few JavaScript libraries have been written to facilitate the extending of objects in JavaScript.  These points are beyond the scope of this article, but I thought I&#8217;d just point you in the right direction.</p>
<p>Interestingly, you can also <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Exception_Handling_Statements:throw_Statement">throw many different</a> types of expressions, and are not limited to the built-in exception types.  For example, <code>throw false;</code> and <code>throw "Hello World";</code> are valid statements, but in my opinion, it doesn&#8217;t make much sense to throw any type of expression just because you can.  Using the built-in exception types (or defining your own) is a better practice, though throwing just String expressions might be alright in some situations.
</li>
<li>
<h4>Runtime errors</h4>
<p>During execution, you code may trigger runtime errors within JavaScript &#8211; for example, when trying to reference a property on a non-existent object.  These will also result in a new <code>Error</code> object being thrown, even though you did not define this throw in your code.  If this happens within a try block, the exception will subsequently be caught in the following catch block, and if you&#8217;re not expecting this error you may miss it.  (If, for example, you&#8217;re only looking for specific exception object types)</p>
<p>This can create problems with some of the JavaScript debuggers out there like <a href="http://www.getfirebug.com">Firebug</a>.  Since the runtime exception is being caught, Firebug will not be able to catch it (it is prevented from &#8220;filtering&#8221; up), so you may not be able to locate the source of your error if you&#8217;re relying on the debugger.  </p>
<p>My recommendation is thus to ensure your code runs properly under normal conditions.  Only then should you start using exceptions and try-catch statements.  This will ensure that no unexpected runtime exceptions get caught.  (The runtime errors are analogous to the unchecked runtime exceptions of Java in that they are not normally caught)
</li>
</ol>
<h3>Summing it up</h3>
<p>The whole point of using exceptions is not to make your code &#8220;work&#8221; better &#8211; anything that can be accomplished with exceptions can most likely be done without it, with just the same end result.  The point is to make your code more readable, manageable and flexible.  By using exceptions you get rid of having to use cumbersome &#8220;error codes&#8221;, the values of which you may forget later.  You also get more flexibility with how you handle errors.  You need not handle the error right in the function where it occurs &#8211; you can throw an exception to the calling code and handle the error there &#8211; or, alternatively, you could let the exception bubble up to a higher-level and handle all errors there.  It really depends on your needs, but using exceptions allows for this to be implemented more readily.</p>
<p>Though exceptions may seem like overkill for JavaScript and despite the limitations of its exception handling model as compared to that of Java&#8217;s, there are still some benefits to using exceptions, especially for complex JavaScript applications that you may implement to improve the interactivity of your site. </p>
<h4>Changes/Fixes</h4>
<ul>
<li><strong>2007-12-06</strong>: Changed <code>throw new Exception(...)</code> to correct statement of <code>throw new Error(...)</code>.</li>
<li><strong>2008-01-08</strong>: Fixed incorrect assertion of &#8220;No Multiple Catch Blocks&#8221; in JavaScript; added remarks about being able to throw any type of expression.</li>
</ul>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2007/11/25/exception-handling-in-javascript/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Using SpeedFan to automatically control your PC&#8217;s fan speeds</title>
		<link>http://unitstep.net/blog/2007/11/02/using-speedfan-to-automatically-control-your-pcs-fan-speeds/</link>
		<comments>http://unitstep.net/blog/2007/11/02/using-speedfan-to-automatically-control-your-pcs-fan-speeds/#comments</comments>
		<pubDate>Sat, 03 Nov 2007 01:25:26 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[guides]]></category>
		<category><![CDATA[Hardware]]></category>
		<category><![CDATA[speedfan]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2007/11/02/using-speedfan-to-automatically-control-your-pcs-fan-speeds/</guid>
		<description><![CDATA[SpeedFan is a great utility for enthusiasts who&#8217;ve built their own PC. Besides being able to show the temperatures inside your system (from various sensors in the CPU, motherboard and HDDs) and other vitals such as voltages and fan speeds, it can also automate the cooling cycles of your machine. As its namesake implies, SpeedFan [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><a href='/blog/2007/11/02/using-speedfan-to-automatically-control-your-pcs-fan-speeds' title='SpeedFan Guide'><img src='/wordpress/wp-content/uploads/2007/11/speedfan-01.thumbnail.png' alt='SpeedFan Guide' /></a></p>
<p><a href="http://www.almico.com/speedfan.php">SpeedFan</a> is a great utility for enthusiasts who&#8217;ve built their own PC.  Besides being able to show the temperatures inside your system (from various sensors in the CPU, motherboard and HDDs) and other vitals such as voltages and fan speeds, it can also automate the cooling cycles of your machine.  As its namesake implies, SpeedFan is able to automatically control your computer&#8217;s fan speeds based on the temperatures reported by various hardware sensors.  This can allow you to find the right balance between a cool system and a noisy one.   However, it does require some configuration, as I&#8217;ll attempt to show you in the following article.</p>
<h3>It&#8217;s all in the details</h3>
<p>All the material I&#8217;m about to present here is available in the help file for SpeedFan, however, since most people use the Internet for everything, myself included, I thought I&#8217;d summarize the most important points.  SpeedFan has a lot of functionality and it&#8217;s easy to get lost in all of that when all you want is something simple like automatic fan control.  (Some motherboards already support this, but SpeedFan brings this functionality to almost any motherboard that&#8217;s reasonably new)</p>
<p>First and foremost, the fans that you want to control must be plugged into one of your motherboard&#8217;s 3-pin fan headers; they cannot be plugged into 4-pin molex connectors that come straight from your power supply.  This is because SpeedFan controls fan speeds&#8217; by varying the output (using PWM) of the 3-pin fan headers on your motherboard.  If you want to control the speed of your 4-pin fans, you&#8217;ll have to use some sort of fanbus or external fan controller.</p>
<h3>Getting started</h3>
<p>On the main SpeedFan window, you may have noticed a checkbox for &#8220;Automatic fan speed&#8221;.  However, checking it is not enough to properly set it up, though it would be nice if things were this easy!  For now, you can check it, but nothing will happen &#8211; you shouldn&#8217;t notice any change in your fans&#8217; speeds. </p>
<p class="image"><img src='/wordpress/wp-content/uploads/2007/11/speedfan-01.png' alt='Main SpeedFan window' /></p>
<p>Click on &#8220;Configure&#8221; to bring up the options window.  SpeedFan is a fairly powerful program, but that means configuration is required to make it do what you want.  The assumption that SpeedFan uses is that various <strong>temperatures</strong> can be influenced by the various <strong>fan speeds</strong> in your system.  You need to define these relationships.  For example, in my system &#8220;Temp1&#8243; is the CPU temperature. (I haven&#8217;t bothered to rename the labels)  In the screenshot below, I have linked it with &#8220;Speed01&#8243; and &#8220;Speed02&#8243;, which correspond to my CPU&#8217;s fan and a case exhaust fan.</p>
<p class="image"><img src='/wordpress/wp-content/uploads/2007/11/speedfan-02.png' alt='SpeedFan temperatures' /></p>
<p>This tells SpeedFan that it should vary these fan speeds based on the temperature they&#8217;re associated with.  You also need to configure threshold temperatures; there are two, &#8220;Desired&#8221; and &#8220;Warning&#8221;.  The desired temperature tells SpeedFan what it should aim for.  Once the desired temperature is reached, SpeedFan will begin to drop fan speeds down to some minimum you specify; if the temperature is above desired fan speeds will increase by an amount related to how much the temperature is above the desired.  Once the temperature reaches the warning value, fan speeds will be set to maximum. (100%)</p>
<p>We now need to configure each of these fans.  Go to the &#8220;Speeds&#8221; tab (not the &#8220;Fans&#8221; tab) of the configuration and you&#8217;ll see a window like this:</p>
<p class="image"><img src='/wordpress/wp-content/uploads/2007/11/speedfan-03.png' alt='SpeedFan speeds' /></p>
<p>Remember that Speed01 and Speed02 are linked with the Temp1.  Here is where we define the minimum and maximum fan speed values.  When the temperature is at or below desired, the <em>lowest</em> the Speed01 will go is 30%, while the maximum I&#8217;ve specified is 100%.  This range is for temperatures up to the warning value.  When the temperature is at or above warning, the fan speeds linked to it will be set to 100% <strong>regardless of what you&#8217;ve define the maximum to be</strong>.  This is a sort of fail safe to prevent overheating &#8211; better safe and noisy than silent and sorry.  Also important to note is that you must check &#8220;Automatically variated&#8221; <strong>for each fan</strong> you want to automatically control.  (This is separate from the main automatic fan speed checkbox on the main SpeedFan window we saw earlier)</p>
<p>You may need to experiment to find out what are the best values for minimum and maximum fan speeds.  Also, some fans fail to report their rotational speed (RPM) when spinning slower, so you may get a reading of &#8220;0 RPM&#8221; within SpeedFan.  You&#8217;ll need to actually check whether this is the case.</p>
<p>One last thing you may want to configure is how fast SpeedFan will begin to adjust fan speeds when it has to respond to a temperature change.  This is accomplished by setting the &#8220;Delta value&#8221; on the Options tab of configuration:</p>
<p class="image"><img src='/wordpress/wp-content/uploads/2007/11/speedfan-04.png' alt='Delta value for fan speeds' /></p>
<p>This sets the step-size (in percent) for fan speed changes.  With a larger value, SpeedFan will adjust fan speeds more quickly since it will be increasing or decreasing by that amount each time.  Experiment to find what works best.  I&#8217;ve found that with too large a step/delta size, temperatures and fan speeds will oscillate &#8211; basically the fans will speed up too fast, causing the temperatures to drop, which in turn cause the fans to slow down too much, which then causes temperature to rise again, completing the cycle.  If you&#8217;ve taken a course in <a href="http://en.wikipedia.org/wiki/Control_theory">control theory</a> you&#8217;ll realize that this is perhaps the classic example problem in control theory.  (By adjusting the delta value I believe you&#8217;re adjusting the proportional value of the controller &#8211; though I am not sure if SpeedFan implements a full PID controller)</p>
<p>Lastly, you may want to check &#8220;Set fans to 100% on exit&#8221; just in case you accidentally shut down SpeedFan &#8211; this is another protective feature.</p>
<h3>Finishing up</h3>
<p>Click &#8220;OK&#8221; on the configuration page to save your changes, which should bring you back to the main window.  Then, make sure &#8220;Automatic Fan Speed&#8221; is checked here, and your system should now be set up for automatic fan control!  I have been using SpeedFan for a few years and wasn&#8217;t aware of this functionality until recently.  Just goes to show that you can always learn new things!</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2007/11/02/using-speedfan-to-automatically-control-your-pcs-fan-speeds/feed/</wfw:commentRss>
		<slash:comments>94</slash:comments>
		</item>
	</channel>
</rss>

