

<?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>Cody A. Ray</title>
	<atom:link href="http://codyaray.com/feed" rel="self" type="application/rss+xml" />
	<link>http://codyaray.com</link>
	<description>Design. Technology. Sustainability. Education. Entrepreneurship.</description>
	<lastBuildDate>Tue, 18 Jun 2013 05:59:49 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Greenfoot: Teaching Java to 5th Graders</title>
		<link>http://codyaray.com/2013/06/greenfoot-teaching-java-to-5th-graders</link>
		<comments>http://codyaray.com/2013/06/greenfoot-teaching-java-to-5th-graders#comments</comments>
		<pubDate>Tue, 18 Jun 2013 05:59:49 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[Education]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1784</guid>
		<description><![CDATA[Once upon a time, I would have said that its impossible to teach 5th graders to program in Java. Even the most basic hello world requires exposure to complex concepts: the print statement must be wrapped by a method with very specific modifiers and parameters, which is then wrapped in an class and compiled. Enter [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Once upon a time, I would have said that its impossible to teach 5th graders to program in Java. Even the most basic hello world requires exposure to complex concepts: the print statement must be wrapped by a method with very specific modifiers and parameters, which is then wrapped in an class and compiled. Enter <a href="http://www.greenfoot.org/door">Greenfoot</a>.</p>
<p>When helping to teach a class for the Northwestern CTD weekend program**, I was introduced to Greenfoot for teaching and learning Java. After my first day of class, I was so inspired by the educational possibilities of Greenfoot that I wrote a little <a title="Breakout Clone" href="https://github.com/codyaray/breakout">Breakout clone</a> to show the kids the next day what they could do with Greenfoot.</p>
<p>Rather than using the classic programming education sequence, from hello world to user input, string manipulation, file I/O, and so on, Greenfoot instructors <span id="more-1784"></span>typically start by letting the students play games in Greenfoot. Once the students understand the mechanics of the game, we step back to cover some of the theoretical bits of programming: data types, methods, objects vs classes, and so on. Then we go through the code of the game they played to see how the theory comes together to make the game work. And finally, we help the students to change the games to behave as they wish. Its <a title="&quot;Gamification of Education&quot; on MIT Technology Review" href="http://www.technologyreview.com/view/512311/the-gamification-of-education/">gamification of education</a> at its core.</p>
<p>Structuring the class in this way results in a very different environment. Instead of having to force-feed material to students, they&#8217;re actively engaged. The primary driver of students&#8217; learning is now their intrinsic curiosity and creativity, rather than the fear of tests hovering overhead. Its a way to <a title="Sir Ken Robinson: Escaping Education's Death Valley" href="http://blog.codyaray.com/post/50202785596/sir-ken-robinson-how-to-escape-educations-death">escape education&#8217;s death valley</a> (at least for programming classes).</p>
<p>Now, don&#8217;t take this the wrong way. I still have <em>a lot</em> to learn about teaching Java, particularly to young learners. Covering the theoretical material is still particularly painful, but I believe its because we don&#8217;t know the best way to help students learn it yet. I&#8217;m confident that we can find the right techniques though. For example, I particularly enjoy trying to teach objects vs classes by drawing on the students&#8217; own experience and intuition.</p>
<p>One thing that I&#8217;ve noticed, though, is that teachers aren&#8217;t properly trained for this kind of environment. The students come in with different backgrounds and exposure to programming, learn at different rates, and — driven by their own creativity — all want to make their games do something different. This makes for a hectic and sometimes challenging environment in which to operate.</p>
<p>In such a student-driven learning environment, its backwards to attempt to maintain the same &#8220;command and control&#8221; style of education to which teachers are accustomed. Although I&#8217;ve written about <a title="Teacher Transition: Instructor to Facilitator" href="http://codyaray.com/2011/05/teacher-transition-instructor-to-facilitator">teachers transitioning from lecturers to facilitators</a> before, I don&#8217;t really know the best way to implement it. But I know that its not telling the students to stop exploring, to be scared of editing code/changing anything (in the case of teaching programming), and to sit and listen. In my experience, the excitement of tinkering leads to student inquiry which leads to teacher assistance which leads to more exploring. What a lovely cycle! Now, the question remains, with a student:teacher ratio fixed by budgetary limitations, how can we actually accomplish this? If I ever figure it out, I&#8217;ll let you know. <img src='http://codyaray.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>** For those of you who don&#8217;t know, I&#8217;ve taught off-and-on through Northwestern&#8217;s <a title="Northwestern CTD" href="http://www.ctd.northwestern.edu/">Center for Talent Development</a> since I moved to Chicago. My first job in the Chicagoland area was as a Residential Teaching Assistant for the <a title="Northwestern CTD Summer Program" href="http://www.ctd.northwestern.edu/summer/">Summer Program</a> and since then I&#8217;ved helped through the <a title="Northwestern Accelerated Weekend Experience" href="http://www.ctd.northwestern.edu/sep/program/awe/">Accelerated Weekend Experience</a> (AWE) program.</p>
<p>&nbsp;</p>
<div class="shr-publisher-1784"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/06/greenfoot-teaching-java-to-5th-graders/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cocoapod lint error: [xcodebuild] No such file or directory</title>
		<link>http://codyaray.com/2013/05/cocoapod-lint-error-xcodebuild-no-such-file-or-directory</link>
		<comments>http://codyaray.com/2013/05/cocoapod-lint-error-xcodebuild-no-such-file-or-directory#comments</comments>
		<pubDate>Thu, 30 May 2013 04:23:40 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1818</guid>
		<description><![CDATA[I just started learning how to write my own Cocoapod yesterday. There&#8217;s a great tutorial to get you started. However, I ran into an issue when trying to lint my new spec. It looked like this: $ pod spec lint MyAwesomeLibrary.podspec &#160; -&#62; MyAwesomeLibrary &#40;0.0.1&#41; - ERROR &#124; &#91;iOS&#93; &#91;xcodebuild&#93; 2013-05-29 23:03:08.370 xcodebuild&#91;91499:3f03&#93; error: Error [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>I just started learning how to write my own Cocoapod yesterday. There&#8217;s a <a href="http://theonlylars.com/blog/2013/01/20/cocoapods-creating-a-pod-spec/" title="Cocoapods: Creating a Cocoapod Spec" target="_blank">great tutorial</a> to get you started. However, I ran into an issue when trying to lint my new spec. It looked like this:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="bash" style="font-family:monospace;">$ pod spec lint MyAwesomeLibrary.podspec
&nbsp;
 -<span style="color: #000000; font-weight: bold;">&gt;</span> MyAwesomeLibrary <span style="color: #7a0874; font-weight: bold;">&#40;</span>0.0.1<span style="color: #7a0874; font-weight: bold;">&#41;</span>
    - ERROR <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>iOS<span style="color: #7a0874; font-weight: bold;">&#93;</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>xcodebuild<span style="color: #7a0874; font-weight: bold;">&#93;</span>  <span style="color: #000000;">2013</span>-05-<span style="color: #000000;">29</span> <span style="color: #000000;">23</span>:03:<span style="color: #000000;">08.370</span> xcodebuild<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">91499</span>:3f03<span style="color: #7a0874; font-weight: bold;">&#93;</span> error: Error <span style="color: #007800;">Domain</span>=NSPOSIXErrorDomain <span style="color: #007800;">Code</span>=<span style="color: #000000;">2</span> <span style="color: #ff0000;">&quot;Non-zero exit code 255 returned from shell command: /usr/bin/gcc-4.2 -v -E -dM -arch armv7 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk -x objective-c -c /dev/null 2&gt;&amp;1&quot;</span> <span style="color: #007800;">UserInfo</span>=0x4001c4e60 <span style="color: #7a0874; font-weight: bold;">&#123;</span><span style="color: #007800;">NSLocalizedDescription</span>=Non-zero <span style="color: #7a0874; font-weight: bold;">exit</span> code <span style="color: #000000;">255</span> returned from shell command: <span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span>gcc-<span style="color: #000000;">4.2</span> <span style="color: #660033;">-v</span> <span style="color: #660033;">-E</span> <span style="color: #660033;">-dM</span> <span style="color: #660033;">-arch</span> armv7 <span style="color: #660033;">-isysroot</span> <span style="color: #000000; font-weight: bold;">/</span>Applications<span style="color: #000000; font-weight: bold;">/</span>Xcode.app<span style="color: #000000; font-weight: bold;">/</span>Contents<span style="color: #000000; font-weight: bold;">/</span>Developer<span style="color: #000000; font-weight: bold;">/</span>Platforms<span style="color: #000000; font-weight: bold;">/</span>iPhoneOS.platform<span style="color: #000000; font-weight: bold;">/</span>Developer<span style="color: #000000; font-weight: bold;">/</span>SDKs<span style="color: #000000; font-weight: bold;">/</span>iPhoneOS6.1.sdk <span style="color: #660033;">-x</span> objective-c <span style="color: #660033;">-c</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>null <span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">1</span>, <span style="color: #007800;">NSLocalizedFailureReason</span>=No such <span style="color: #c20cb9; font-weight: bold;">file</span> or directory<span style="color: #7a0874; font-weight: bold;">&#125;</span>
    - ERROR <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>iOS<span style="color: #7a0874; font-weight: bold;">&#93;</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>xcodebuild<span style="color: #7a0874; font-weight: bold;">&#93;</span>  <span style="color: #000000;">2013</span>-05-<span style="color: #000000;">29</span> <span style="color: #000000;">23</span>:03:<span style="color: #000000;">08.457</span> xcodebuild<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">91499</span>:3f03<span style="color: #7a0874; font-weight: bold;">&#93;</span> error: Error <span style="color: #007800;">Domain</span>=NSPOSIXErrorDomain <span style="color: #007800;">Code</span>=<span style="color: #000000;">2</span> <span style="color: #ff0000;">&quot;Non-zero exit code 1 returned from shell command: /usr/bin/gcc-4.2 -v -E -dM -arch armv7s -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk -x objective-c -c /dev/null 2&gt;&amp;1&quot;</span> <span style="color: #007800;">UserInfo</span>=0x4018946a0 <span style="color: #7a0874; font-weight: bold;">&#123;</span><span style="color: #007800;">NSLocalizedDescription</span>=Non-zero <span style="color: #7a0874; font-weight: bold;">exit</span> code <span style="color: #000000;">1</span> returned from shell command: <span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span>gcc-<span style="color: #000000;">4.2</span> <span style="color: #660033;">-v</span> <span style="color: #660033;">-E</span> <span style="color: #660033;">-dM</span> <span style="color: #660033;">-arch</span> armv7s <span style="color: #660033;">-isysroot</span> <span style="color: #000000; font-weight: bold;">/</span>Applications<span style="color: #000000; font-weight: bold;">/</span>Xcode.app<span style="color: #000000; font-weight: bold;">/</span>Contents<span style="color: #000000; font-weight: bold;">/</span>Developer<span style="color: #000000; font-weight: bold;">/</span>Platforms<span style="color: #000000; font-weight: bold;">/</span>iPhoneOS.platform<span style="color: #000000; font-weight: bold;">/</span>Developer<span style="color: #000000; font-weight: bold;">/</span>SDKs<span style="color: #000000; font-weight: bold;">/</span>iPhoneOS6.1.sdk <span style="color: #660033;">-x</span> objective-c <span style="color: #660033;">-c</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>null <span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">1</span>, <span style="color: #007800;">NSLocalizedFailureReason</span>=No such <span style="color: #c20cb9; font-weight: bold;">file</span> or directory<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
Analyzed <span style="color: #000000;">1</span> podspec.
&nbsp;
<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000; font-weight: bold;">!</span><span style="color: #7a0874; font-weight: bold;">&#93;</span> The spec did not pass validation.</pre></td></tr></table></div>

<p><span id="more-1818"></span><br />
When I manually ran the command in the above error message, I saw this error:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #000000; font-weight: bold;">/</span>usr<span style="color: #000000; font-weight: bold;">/</span>bin<span style="color: #000000; font-weight: bold;">/</span>gcc-<span style="color: #000000;">4.2</span> <span style="color: #660033;">-v</span> <span style="color: #660033;">-E</span> <span style="color: #660033;">-dM</span> <span style="color: #660033;">-arch</span> armv7 <span style="color: #660033;">-isysroot</span> <span style="color: #000000; font-weight: bold;">/</span>Applications<span style="color: #000000; font-weight: bold;">/</span>Xcode.app<span style="color: #000000; font-weight: bold;">/</span>Contents<span style="color: #000000; font-weight: bold;">/</span>Developer<span style="color: #000000; font-weight: bold;">/</span>Platforms<span style="color: #000000; font-weight: bold;">/</span>iPhoneOS.platform<span style="color: #000000; font-weight: bold;">/</span>Developer<span style="color: #000000; font-weight: bold;">/</span>SDKs<span style="color: #000000; font-weight: bold;">/</span>iPhoneOS6.1.sdk <span style="color: #660033;">-x</span> objective-c <span style="color: #660033;">-c</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>null <span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">&gt;&amp;</span><span style="color: #000000;">1</span>
gcc-<span style="color: #000000;">4.2</span>: error trying to <span style="color: #7a0874; font-weight: bold;">exec</span> <span style="color: #ff0000;">'/usr/bin/arm-apple-darwin11-gcc-4.2.1'</span>: execvp: No such <span style="color: #c20cb9; font-weight: bold;">file</span> or directory</pre></td></tr></table></div>

<p>I don&#8217;t have the file &#8220;/usr/bin/arm-apple-darwin11-gcc-4.2.1&#8243;. If you see this too, you should check whether you have a preferred C Compiler. This is configured via the <code>CC</code> environment variable. Mine was set to <code>gcc-4.2</code>.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$CC</span>
gcc-<span style="color: #000000;">4.2</span></pre></td></tr></table></div>

<p>To let cocoapods use the default compiler instead, just run the linter as</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">$ CC<span style="color: #339933;">=</span> pod spec lint MyAwesomeLibrary.<span style="color: #006633;">podspec</span>
&nbsp;
 <span style="color: #339933;">-&gt;</span> MyAwesomeLibrary <span style="color: #009900;">&#40;</span>0.0.1<span style="color: #009900;">&#41;</span>
&nbsp;
Analyzed <span style="color: #cc66cc;">1</span> podspec.
&nbsp;
<span style="color: #006633;">MyAwesomeLibrary</span>.<span style="color: #006633;">podspec</span> passed validation.</pre></td></tr></table></div>

<p>Woohoo! It passed!</p>
<div class="shr-publisher-1818"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/05/cocoapod-lint-error-xcodebuild-no-such-file-or-directory/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiple Keystores in Apache Camel/HttpClient</title>
		<link>http://codyaray.com/2013/05/multiple-keystores-in-apache-camelhttpclient</link>
		<comments>http://codyaray.com/2013/05/multiple-keystores-in-apache-camelhttpclient#comments</comments>
		<pubDate>Wed, 08 May 2013 15:26:54 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1781</guid>
		<description><![CDATA[Now that we know how to use multiple SSL keystores in Java, how do we configure Apache HttpClient (embedded in Apache Camel) to use them? This is useful if you want to load additional keystores in addition to the &#8220;factory&#8221; installed ones, for example. There&#8217;s no obvious way to do this using HttpClient or Camel. [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Now that we know how to use <a title="Java SSL with Multiple Keystores" href="http://codyaray.com/2013/04/java-ssl-with-multiple-keystores">multiple SSL keystores in Java</a>, how do we configure Apache HttpClient (embedded in Apache Camel) to use them? This is useful if you want to load additional keystores in addition to the &#8220;factory&#8221; installed ones, for example. There&#8217;s no obvious way to do this using HttpClient or Camel. If you look at any of the <a title="Camel HTTP" href="http://camel.apache.org/http.html">documentation online</a>, you&#8217;ll either see configuration via the JSSE configuration utility, like so:<span id="more-1781"></span></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">KeyStoreParameters ksp <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> KeyStoreParameters<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
ksp.<span style="color: #006633;">setResource</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/users/home/server/keystore.jks&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
ksp.<span style="color: #006633;">setPassword</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;keystorePassword&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
KeyManagersParameters kmp <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> KeyManagersParameters<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
kmp.<span style="color: #006633;">setKeyStore</span><span style="color: #009900;">&#40;</span>ksp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
kmp.<span style="color: #006633;">setKeyPassword</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;keyPassword&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
SSLContextParameters scp <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SSLContextParameters<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
scp.<span style="color: #006633;">setKeyManagers</span><span style="color: #009900;">&#40;</span>kmp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
ProtocolSocketFactory factory <span style="color: #339933;">=</span>
    <span style="color: #000000; font-weight: bold;">new</span> SSLContextParametersSecureProtocolSocketFactory<span style="color: #009900;">&#40;</span>scp<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
Protocol.<span style="color: #006633;">registerProtocol</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;https&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Protocol<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;https&quot;</span>, factory, <span style="color: #cc66cc;">443</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Or you&#8217;ll see direct configuration of Apache HttpClient using <code>HttpClientConfigurer</code> or something like this:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">Protocol authhttps <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Protocol<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;https&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> AuthSSLProtocolSocketFactory<span style="color: #009900;">&#40;</span>
  <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">URL</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;file:my.keystore&quot;</span><span style="color: #009900;">&#41;</span>, <span style="color: #0000ff;">&quot;mypassword&quot;</span>,
  <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">URL</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;file:my.truststore&quot;</span><span style="color: #009900;">&#41;</span>, <span style="color: #0000ff;">&quot;mypassword&quot;</span><span style="color: #009900;">&#41;</span>, <span style="color: #cc66cc;">443</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
Protocol.<span style="color: #006633;">registerProtocol</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;https&quot;</span>, authhttps<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>However, we&#8217;re not reading from the keystore from a file, nor do we only want to use a single keystore. So all of these convenient wrappers that Apache Camel and Apache HttpClient are actually becoming an <em>inconvenience</em> to us.</p>
<p>This becomes even more frustrating when you realize you can&#8217;t even find many classes used in the examples, including the <code>AuthSSLProtocolSocketFactory</code>, on your classpath (because of Camel bundling older versions of HttpClient). Fortunately, if you hunt through the javadocs and sources long enough, you&#8217;ll learn as I did that it always boils down to an <a title="SSLContext javadoc" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/SSLContext.html">SSLContext</a> or, more specifically, an <a title="SSLSocketFactory javadoc" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/SSLSocketFactory.html">SSLSocketFactory</a>.</p>
<p>The protocol must be registered using <a title="Protocol.html#registerProtocol javadoc" href="http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/protocol/Protocol.html#registerProtocol(java.lang.String, org.apache.commons.httpclient.protocol.Protocol)">Protocol.registerProtocol</a>, so we need an instance of a <a title="ProtocolSocketFactory javadoc" href="http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.html">ProtocolSocketFactory</a>. Digging through the source shows that the promising-sounding <a title="SSLProtocolSocketFactory javadoc" href="http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.html">SSLProtocolSocketFactory</a> always uses the <a title="SSLSocketFactory#getDefault javadoc" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/SSLSocketFactory.html#getDefault()">default SSLSocketFactory</a>.  However, it turns out that the Camel-provided <a title="SSLContextParametersSecureProtocolSocketFactory" href="http://camel.apache.org/maven/camel-2.8.0/camel-http/apidocs/org/apache/camel/component/http/SSLContextParametersSecureProtocolSocketFactory.html">SSLContextParametersSecureProtocolSocketFactory</a> can accept a <code>SSLSocketFactory</code> as a constructor argument instead of the <code>SSLContextParameters</code> shown in all the examples. That&#8217;s the key!</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">  @Provides @Singleton
  ProtocolSocketFactory provideSslProtocolSocketFactory<span style="color: #009900;">&#40;</span>SSLContext sslContext<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> SSLContextParametersSecureProtocolSocketFactory<span style="color: #009900;">&#40;</span>sslContext.<span style="color: #006633;">getSocketFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Now we just need to register this factory for use by the HTTPS protocol as in the examples.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">  Protocol.<span style="color: #006633;">registerProtocol</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;https&quot;</span>,
      <span style="color: #000000; font-weight: bold;">new</span> Protocol<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;https&quot;</span>, factory, <span style="color: #cc66cc;">443</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Its simple once we know what we need, but time-consuming to hunt and peck through all the docs and sources to find it. Hopefully this has helped you save some time!</p>
<p><strong>We can now make HTTPS requests through Camel using multiple (custom) keystores.</strong></p>
<p>As a sidenote, compare this with Ning&#8217;s AsyncHttpClient, which exposes a <code>setSSLContext</code> method directly in the <a title="AsyncHttpClientConfig.Builder javadoc" href="http://asynchttpclient.github.io/async-http-client/apidocs/com/ning/http/client/AsyncHttpClientConfig.Builder.html">AsyncHttpClientConfig.Builder()</a>. That&#8217;s almost too easy by comparison. <img src='http://codyaray.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div class="shr-publisher-1781"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/05/multiple-keystores-in-apache-camelhttpclient/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Intro to Streams2: Design Patterns (Part 2)</title>
		<link>http://codyaray.com/2013/04/intro-to-streams2-design-patterns-part-2</link>
		<comments>http://codyaray.com/2013/04/intro-to-streams2-design-patterns-part-2#comments</comments>
		<pubDate>Sun, 28 Apr 2013 01:56:51 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1589</guid>
		<description><![CDATA[This is the last part in the Intro to Streams2 series. If you haven&#8217;t read Part 1 yet, you should. The examples here build on the ones presented there. Part 2 is about design patterns for streams. Design patterns help us write clean code, like this. function publish&#40;data&#41; &#123; data .pipe&#40;config.formatter&#40;&#41;&#41; .pipe&#40;config.connector&#40;&#41;&#41; .on&#40;'error', function&#40;err&#41; &#123; self.emit&#40;'error', err&#41;; &#125;&#41; [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>This is the last part in the Intro to Streams2 series. If you haven&#8217;t <a title="Intro to Streams2: New Node Streams (Part 1)" href="http://codyaray.com/2013/04/intro-to-streams2-new-node-streams-part-1">read Part 1</a> yet, you should. The examples here build on the ones presented there.</p>
<p>Part 2 is about design patterns for streams. Design patterns help us write clean code, like this.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">function</span> publish<span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  data
    .<span style="color: #660066;">pipe</span><span style="color: #009900;">&#40;</span>config.<span style="color: #660066;">formatter</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    .<span style="color: #660066;">pipe</span><span style="color: #009900;">&#40;</span>config.<span style="color: #660066;">connector</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    .<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'error'</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>err<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      self.<span style="color: #660066;">emit</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'error'</span><span style="color: #339933;">,</span> err<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
    .<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'success'</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      self.<span style="color: #660066;">emit</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'success'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p><span id="more-1589"></span>You could imagine that <code>config.formatter()</code> and <code>config.connector()</code> create already-configured objects. Something like this:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;">  <span style="color: #000066; font-weight: bold;">var</span> config <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
    formatter<span style="color: #339933;">:</span> <span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">new</span> CsvFormatter<span style="color: #009900;">&#40;</span>fieldOrder<span style="color: #339933;">,</span> fieldSeparator <span style="color: #339933;">||</span> <span style="color: #3366CC;">','</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
    connector<span style="color: #339933;">:</span> <span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">new</span> FtpConnector<span style="color: #009900;">&#40;</span>host<span style="color: #339933;">,</span> port <span style="color: #339933;">||</span> <span style="color: #CC0000;">21</span><span style="color: #339933;">,</span> user<span style="color: #339933;">,</span> password<span style="color: #339933;">,</span> filename<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Since we might want to change the configuration to return a JSON formatter that connects to Amazon S3 instead, we want all formatting and connector logic to be entirely encapsulated within their services.</p>
<p>Too bad many components won&#8217;t work this way out of the box. So what do we do? Design patterns to the rescue!</p>
<h2>Adapter Pattern</h2>
<p>Piping streams together is fun! Which means that node modules that handle streams but can&#8217;t be inserted in a pipe chain are no fun. How do we fix this? We write wrapper streams that adapt the module to work the way we want.</p>
<p>In this case, the culprit is <a title="node-ftp" href="https://github.com/mscdex/node-ftp">node-ftp</a>. This would be a great FTP module if only you could pipe a file to an FTP server. Instead, you have to call</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;">ftp.<span style="color: #660066;">put</span><span style="color: #009900;">&#40;</span>readableStream<span style="color: #339933;">,</span> filename<span style="color: #339933;">,</span> callback<span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>Let&#8217;s start by rewriting the FTP connector, adapting it so that we can pipe to it.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">var</span> stream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'stream'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
  FTP <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'ftp'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">/*
 * Stream a file to FTP.
 */</span>
<span style="color: #000066; font-weight: bold;">function</span> FtpConnector<span style="color: #009900;">&#40;</span>host<span style="color: #339933;">,</span> port<span style="color: #339933;">,</span> user<span style="color: #339933;">,</span> password<span style="color: #339933;">,</span> filename<span style="color: #339933;">,</span> ftp<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
&nbsp;
  ftp <span style="color: #339933;">=</span> ftp <span style="color: #339933;">||</span> <span style="color: #000066; font-weight: bold;">new</span> FTP<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  stream.<span style="color: #660066;">PassThrough</span>.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>self<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  ftp.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'ready'</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    ftp.<span style="color: #660066;">put</span><span style="color: #009900;">&#40;</span>self<span style="color: #339933;">,</span> filename<span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>err<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      ftp.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>err<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> self.<span style="color: #660066;">emit</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'error'</span><span style="color: #339933;">,</span> err<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000066; font-weight: bold;">return</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
      self.<span style="color: #660066;">emit</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'success'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  ftp.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'error'</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>err<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    self.<span style="color: #660066;">emit</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'error'</span><span style="color: #339933;">,</span> err<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  ftp.<span style="color: #660066;">connect</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> host<span style="color: #339933;">:</span> host<span style="color: #339933;">,</span> port<span style="color: #339933;">:</span> port<span style="color: #339933;">,</span> user<span style="color: #339933;">:</span> user<span style="color: #339933;">,</span> password<span style="color: #339933;">:</span> password <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
util.<span style="color: #660066;">inherits</span><span style="color: #009900;">&#40;</span>FtpConnector<span style="color: #339933;">,</span> stream.<span style="color: #660066;">PassThrough</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>We create the stream as a subclass of a <a title="PassThrough Stream" href="http://nodejs.org/api/stream.html#stream_class_stream_passthrough">PassThrough</a> stream. Then in the constructor we create a new FTP connection and pass <code>self</code> into its <code>put</code> method. This effectively passes all stream input through directly into the FTP upload. Pretty sweet use of the PassThrough stream, if I do say so myself.</p>
<h2>Composite Pattern</h2>
<p>Ok, on to the CSV.</p>
<p>My data source emits Javascript objects, so I need to transform the object into an ordered row for the CSV stringifier. But I don&#8217;t want to add another pipe in the publish chain to do this transformation. What if I want to change the formatter to an XML formatter? (haha) The details of the formatter shouldn&#8217;t be exposed to the publisher. So I&#8217;d like to wrap up multiple transformers/pipes into a single stream module.</p>
<p>Here&#8217;s how we can do this, building on the <a title="Intro to Streams2: New Nodes Streams" href="http://codyaray.com/2013/04/intro-to-streams2-new-node-streams-part-1">CsvPrepStream transformer introduced in Part 1</a>.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">var</span> stream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'stream'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
  CSV <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'csv'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
<span style="color: #006600; font-style: italic;">/*
 * Formats a batch of data as a CSV with fields in the given order.
 */</span>
<span style="color: #000066; font-weight: bold;">function</span> CsvFormatter<span style="color: #009900;">&#40;</span>fields<span style="color: #339933;">,</span> delimiter<span style="color: #339933;">,</span> prepper<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #000066; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
&nbsp;
 prepper <span style="color: #339933;">=</span> prepper <span style="color: #339933;">||</span> <span style="color: #000066; font-weight: bold;">new</span> CsvPrepStream<span style="color: #009900;">&#40;</span>fields<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 stream.<span style="color: #660066;">PassThrough</span>.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>self<span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> objectMode<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 self.<span style="color: #660066;">pipe</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>dest<span style="color: #339933;">,</span> pipeOpts<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #006600; font-style: italic;">/*
    * override pipe to first stream through CsvPrepStream for converting datapoint objects
    * to ordered arrays and then delegate to node-csv to convert each record to a csv row
    */</span>
   <span style="color: #000066; font-weight: bold;">var</span> super_pipe <span style="color: #339933;">=</span> stream.<span style="color: #660066;">PassThrough</span>.<span style="color: #000066; font-weight: bold;">prototype</span>.<span style="color: #660066;">pipe</span><span style="color: #339933;">,</span>
     csv <span style="color: #339933;">=</span> CSV<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">to</span>.<span style="color: #660066;">options</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> delimiter<span style="color: #339933;">:</span>delimiter<span style="color: #339933;">,</span> header<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">,</span> columns<span style="color: #339933;">:</span>fields <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000066; font-weight: bold;">return</span> super_pipe.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>self<span style="color: #339933;">,</span> prepper<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">pipe</span><span style="color: #009900;">&#40;</span>csv<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">pipe</span><span style="color: #009900;">&#40;</span>dest<span style="color: #339933;">,</span> pipeOpts<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
util.<span style="color: #660066;">inherits</span><span style="color: #009900;">&#40;</span>CsvFormatter<span style="color: #339933;">,</span> stream.<span style="color: #660066;">PassThrough</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>We&#8217;ve extended the PassThrough stream like we did with the CsvPrepStream. This time, however, we&#8217;re overriding its pipe method so that it first sends the incoming stream data through the CsvPrepStream, and then through node-csv, before piping it out to its final destination. Note that we&#8217;re letting node-csv write out the header as the first line by passing <code>header: true, columns: fields</code> as its options. So now we have a single stream module (CsvFormatter) that accepts Javascript objects and outputs CSV rows with the fields taken from the objects and put in the requested order.</p>
<h2> Conclusion</h2>
<p>In part 2, we&#8217;ve looked at how classic design patterns can be used to solve problems with node streams. Starting with the idea of a sexy publish function that streams data through a CSV formatter and out to an FTP server, we applied the adaptor pattern and then composer pattern to make this pipe chain possible. And, in the process, we discovered two new uses of the PassThrough stream. Sweet!</p>
<p><strong>What design patterns do you use for streams in node.js?</strong></p>
<div class="shr-publisher-1589"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/04/intro-to-streams2-design-patterns-part-2/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java SSL with Multiple KeyStores</title>
		<link>http://codyaray.com/2013/04/java-ssl-with-multiple-keystores</link>
		<comments>http://codyaray.com/2013/04/java-ssl-with-multiple-keystores#comments</comments>
		<pubDate>Fri, 26 Apr 2013 06:07:40 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1779</guid>
		<description><![CDATA[For communication between internal services at BrightTag, we use self-signed certs on both the client and server. Simple and cheap (free!). Most of the time, these services only communicate over HTTPS with other internal services, so its been fine to use our own keystore; we didn&#8217;t need access to the &#8220;factory&#8221; certificates anyway. However, I [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>For communication between internal services at BrightTag, we use self-signed certs on both the client and server. Simple and cheap (free!). Most of the time, these services only communicate over HTTPS with other internal services, so its been fine to use our own keystore; we didn&#8217;t need access to the &#8220;factory&#8221; certificates anyway. However, I ran into a case last week where I needed to be able to talk to both internal and external services and realized there&#8217;s no simple way to use multiple keystores in Java. We wanted to use both the standard JVM keystore and our custom keystore. The cleanest solution I found was to write my own CompositeKeyManager and CompositeTrustManagers. Creating a new keystore with both the standard JVM certs and our custom certs was also considered, but ultimately we didn&#8217;t want the responsibility of updating the standard certs in a bundled keystore.</p>
<p><span id="more-1779"></span></p>
<p>Let&#8217;s dive right in. HTTP clients need an <a title="SSLContext javadoc" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/SSLContext.html" target="_blank">SSLContext</a> or <a title="SSLSocketFactory javadoc" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/SSLSocketFactory.html" target="_blank">SSLSocketFactory</a> (which can be retrieved from <a title="SSLContext#getSocketFactory" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/SSLContext.html#getSocketFactory()">SSLContext#getSocketFactory</a>). To initialize an SSLContext from your own keystore, you need an array of <a title="KeyManager javadoc" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/KeyManager.html" target="_blank">KeyManagers</a> and an array of <a title="TrustManager javadoc" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/TrustManager.html" target="_blank">TrustManagers</a>. A <a title="KeyManagerFactory" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/KeyManagerFactory.html" target="_blank">KeyManagerFactory</a> and a <a title="TrustManagerFactory javadoc" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/TrustManagerFactory.html" target="_blank">TrustManagerFactory</a> are used to extract the KeyManagers and TrustManagers from your keystore. The standard code looks something like this:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">KeyManagerFactory kmf <span style="color: #339933;">=</span> KeyManagerFactory.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SunX509&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
kmf.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>keyStore, password<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
TrustManagerFactory tmf <span style="color: #339933;">=</span> TrustManagerFactory.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SunX509&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
tmf.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>keyStore<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
SSLContext sslContext <span style="color: #339933;">=</span> SSLContext.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SSL&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
sslContext.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>kmf.<span style="color: #006633;">getKeyManagers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, tmf.<span style="color: #006633;">getTrustManagers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Okay, so I can just merge the KeyManager arrays  from each keystore, right?</strong></p>
<p>Wrong, thanks to the fine-print associated with the  <a title="SSLContext#init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[], java.security.SecureRandom)" href="http://docs.oracle.com/javase/6/docs/api/javax/net/ssl/SSLContext.html#init(javax.net.ssl.KeyManager[], javax.net.ssl.TrustManager[], java.security.SecureRandom)">SSLContext initializer</a>:</p>
<blockquote><p>Only the first instance of a particular key and/or trust manager implementation type in the array is used. (For example, only the first javax.net.ssl.X509KeyManager in the array will be used.</p></blockquote>
<p>In my case, both the JVM and our certs are X509, so this approach doesn&#8217;t work. Given that X509KeyManager is the only KeyManager implementation that ships with the JDK, I suspect this is the case for more or less everybody.</p>
<p><strong>So what to do now?</strong></p>
<p>As always, I turned to stackoverflow for an answer. <a title="Registering multiple keystores in jvm" href="http://stackoverflow.com/questions/1793979/registering-multiple-keystores-in-jvm" target="_blank">This question</a> addresses my problem and provides code showing a custom KeyManager implementation. Thanks to <a title="Raz on StackOverflow" href="http://stackoverflow.com/users/114601/raz" target="_blank">Raz</a> for following up with an answer to his question, and everyone who chimed in to help him.</p>
<p>However, this solution wasn&#8217;t quite satisfactory to me. The MultiStoreKeyManager explicitly checks the custom KeyManager and then falls back to the jvm KeyManager if an operation fails. I actually want to check jvm certs first; the best solution should be able to handle either case. Additionally, the answer fails to provide a working TrustManager, so it doesn&#8217;t completely solve my multiple-keystore-with-SSL problem.</p>
<p>My approach was to apply the composite pattern a little more directly to create a CompositeX509KeyManager and CompositeX509TrustManager. They both take in a list of their delegates in order of preference. This adds support for any number of keystores in an arbitrary order. Whichever keystore (er, KeyManager/TrustManager) comes first in the injected list will be preferred to those coming later. My solutions use Guava because I heart Guava, but you should be able to replace them with another library or your own implementation of the few methods if you prefer.</p>
<p>Without further ado, ladies and gentlemen, I present to you the CompositeX509KeyManager.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.mycompany.ssl</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.net.Socket</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.security.Principal</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.security.PrivateKey</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.security.cert.X509Certificate</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.List</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.annotation.Nullable</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.net.ssl.X509KeyManager</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">com.google.common.collect.ImmutableList</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">com.google.common.collect.Iterables</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Represents an ordered list of {@link X509KeyManager}s with most-preferred managers first.
 *
 * This is necessary because of the fine-print on {@link SSLContext#init}:
 *     Only the first instance of a particular key and/or trust manager implementation type in the
 *     array is used. (For example, only the first javax.net.ssl.X509KeyManager in the array will be used.)
 *
 * @author codyaray
 * @since 4/22/2013
 * @see http://stackoverflow.com/questions/1793979/registering-multiple-keystores-in-jvm
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CompositeX509KeyManager <span style="color: #000000; font-weight: bold;">implements</span> X509KeyManager <span style="color: #009900;">&#123;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">List</span> keyManagers<span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #008000; font-style: italic; font-weight: bold;">/**
   * Creates a new {@link CompositeX509KeyManager}.
   *
   * @param keyManagers the X509 key managers, ordered with the most-preferred managers first.
   */</span>
  <span style="color: #000000; font-weight: bold;">public</span> CompositeX509KeyManager<span style="color: #009900;">&#40;</span><span style="color: #003399;">List</span> keyManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">keyManagers</span> <span style="color: #339933;">=</span> ImmutableList.<span style="color: #006633;">copyOf</span><span style="color: #009900;">&#40;</span>keyManagers<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #008000; font-style: italic; font-weight: bold;">/**
   * Chooses the first non-null client alias returned from the delegate
   * {@link X509TrustManagers}, or {@code null} if there are no matches.
   */</span>
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> @Nullable <span style="color: #003399;">String</span> chooseClientAlias<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> keyType, <span style="color: #003399;">Principal</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> issuers, <span style="color: #003399;">Socket</span> socket<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>X509KeyManager keyManager <span style="color: #339933;">:</span> keyManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #003399;">String</span> alias <span style="color: #339933;">=</span> keyManager.<span style="color: #006633;">chooseClientAlias</span><span style="color: #009900;">&#40;</span>keyType, issuers, socket<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>alias <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> alias<span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #008000; font-style: italic; font-weight: bold;">/**
   * Chooses the first non-null server alias returned from the delegate
   * {@link X509TrustManagers}, or {@code null} if there are no matches.
   */</span>
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> @Nullable <span style="color: #003399;">String</span> chooseServerAlias<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> keyType, <span style="color: #003399;">Principal</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> issuers, <span style="color: #003399;">Socket</span> socket<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>X509KeyManager keyManager <span style="color: #339933;">:</span> keyManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #003399;">String</span> alias <span style="color: #339933;">=</span> keyManager.<span style="color: #006633;">chooseServerAlias</span><span style="color: #009900;">&#40;</span>keyType, issuers, socket<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>alias <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> alias<span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #008000; font-style: italic; font-weight: bold;">/**
   * Returns the first non-null private key associated with the
   * given alias, or {@code null} if the alias can't be found.
   */</span>
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> @Nullable <span style="color: #003399;">PrivateKey</span> getPrivateKey<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> alias<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>X509KeyManager keyManager <span style="color: #339933;">:</span> keyManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #003399;">PrivateKey</span> privateKey <span style="color: #339933;">=</span> keyManager.<span style="color: #006633;">getPrivateKey</span><span style="color: #009900;">&#40;</span>alias<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>privateKey <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> privateKey<span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #008000; font-style: italic; font-weight: bold;">/**
   * Returns the first non-null certificate chain associated with the
   * given alias, or {@code null} if the alias can't be found.
   */</span>
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> @Nullable <span style="color: #003399;">X509Certificate</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> getCertificateChain<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> alias<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>X509KeyManager keyManager <span style="color: #339933;">:</span> keyManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #003399;">X509Certificate</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> chain <span style="color: #339933;">=</span> keyManager.<span style="color: #006633;">getCertificateChain</span><span style="color: #009900;">&#40;</span>alias<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>chain <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;&amp;</span>amp<span style="color: #339933;">;</span> chain.<span style="color: #006633;">length</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> chain<span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #008000; font-style: italic; font-weight: bold;">/**
   * Get all matching aliases for authenticating the client side of a
   * secure socket, or {@code null} if there are no matches.
   */</span>
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> @Nullable <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> getClientAliases<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> keyType, <span style="color: #003399;">Principal</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> issuers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    ImmutableList.<span style="color: #006633;">Builder</span> aliases <span style="color: #339933;">=</span> ImmutableList.<span style="color: #006633;">builder</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>X509KeyManager keyManager <span style="color: #339933;">:</span> keyManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      aliases.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>keyManager.<span style="color: #006633;">getClientAliases</span><span style="color: #009900;">&#40;</span>keyType, issuers<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">return</span> emptyToNull<span style="color: #009900;">&#40;</span>Iterables.<span style="color: #006633;">toArray</span><span style="color: #009900;">&#40;</span>aliases.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, <span style="color: #003399;">String</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #008000; font-style: italic; font-weight: bold;">/**
   * Get all matching aliases for authenticating the server side of a
   * secure socket, or {@code null} if there are no matches.
   */</span>
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> @Nullable <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> getServerAliases<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> keyType, <span style="color: #003399;">Principal</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> issuers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    ImmutableList.<span style="color: #006633;">Builder</span> aliases <span style="color: #339933;">=</span> ImmutableList.<span style="color: #006633;">builder</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>X509KeyManager keyManager <span style="color: #339933;">:</span> keyManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      aliases.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>keyManager.<span style="color: #006633;">getServerAliases</span><span style="color: #009900;">&#40;</span>keyType, issuers<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">return</span> emptyToNull<span style="color: #009900;">&#40;</span>Iterables.<span style="color: #006633;">toArray</span><span style="color: #009900;">&#40;</span>aliases.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, <span style="color: #003399;">String</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> @Nullable  T<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> emptyToNull<span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> arr<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>arr.<span style="color: #006633;">length</span> <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">?</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">:</span> arr<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>And the accompanying CompositeX509TrustManager:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.mycompany.ssl</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.security.cert.CertificateException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.security.cert.X509Certificate</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.List</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.net.ssl.X509TrustManager</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">com.google.common.collect.ImmutableList</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">com.google.common.collect.Iterables</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Represents an ordered list of {@link X509TrustManager}s with additive trust. If any one of the
 * composed managers trusts a certificate chain, then it is trusted by the composite manager.
 *
 * This is necessary because of the fine-print on {@link SSLContext#init}:
 *     Only the first instance of a particular key and/or trust manager implementation type in the
 *     array is used. (For example, only the first javax.net.ssl.X509KeyManager in the array will be used.)
 *
 * @author codyaray
 * @since 4/22/2013
 * @see http://stackoverflow.com/questions/1793979/registering-multiple-keystores-in-jvm
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CompositeX509TrustManager <span style="color: #000000; font-weight: bold;">implements</span> X509TrustManager <span style="color: #009900;">&#123;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">List</span> trustManagers<span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> CompositeX509TrustManager<span style="color: #009900;">&#40;</span><span style="color: #003399;">List</span> trustManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">trustManagers</span> <span style="color: #339933;">=</span> ImmutableList.<span style="color: #006633;">copyOf</span><span style="color: #009900;">&#40;</span>trustManagers<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> checkClientTrusted<span style="color: #009900;">&#40;</span><span style="color: #003399;">X509Certificate</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> chain, <span style="color: #003399;">String</span> authType<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">CertificateException</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>X509TrustManager trustManager <span style="color: #339933;">:</span> trustManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
        trustManager.<span style="color: #006633;">checkClientTrusted</span><span style="color: #009900;">&#40;</span>chain, authType<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// someone trusts them. success!</span>
      <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">CertificateException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// maybe someone else will trust them</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">CertificateException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;None of the TrustManagers trust this certificate chain&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> checkServerTrusted<span style="color: #009900;">&#40;</span><span style="color: #003399;">X509Certificate</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> chain, <span style="color: #003399;">String</span> authType<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">CertificateException</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>X509TrustManager trustManager <span style="color: #339933;">:</span> trustManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
        trustManager.<span style="color: #006633;">checkServerTrusted</span><span style="color: #009900;">&#40;</span>chain, authType<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// someone trusts them. success!</span>
      <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">CertificateException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// maybe someone else will trust them</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">CertificateException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;None of the TrustManagers trust this certificate chain&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  @Override
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">X509Certificate</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> getAcceptedIssuers<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    ImmutableList.<span style="color: #006633;">Builder</span> certificates <span style="color: #339933;">=</span> ImmutableList.<span style="color: #006633;">builder</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>X509TrustManager trustManager <span style="color: #339933;">:</span> trustManagers<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      certificates.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>trustManager.<span style="color: #006633;">getAcceptedIssuers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">return</span> Iterables.<span style="color: #006633;">toArray</span><span style="color: #009900;">&#40;</span>certificates.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, <span style="color: #003399;">X509Certificate</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>For the standard case of one keystore + jvm keystore, you can wire it up like this. I&#8217;m using Guava again, but in a Guicey wrapper this time:</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="java" style="font-family:monospace;">@Provides @Singleton
SSLContext provideSSLContext<span style="color: #009900;">&#40;</span><span style="color: #003399;">KeyStore</span> keystore, <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> password<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003399;">String</span> defaultAlgorithm <span style="color: #339933;">=</span> KeyManagerFactory.<span style="color: #006633;">getDefaultAlgorithm</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  X509KeyManager customKeyManager <span style="color: #339933;">=</span> getKeyManager<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SunX509&quot;</span>, keystore, password<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  X509KeyManager jvmKeyManager <span style="color: #339933;">=</span> getKeyManager<span style="color: #009900;">&#40;</span>defaultAlgorithm, <span style="color: #000066; font-weight: bold;">null</span>, <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  X509TrustManager customTrustManager <span style="color: #339933;">=</span> getTrustManager<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SunX509&quot;</span>, keystore<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  X509TrustManager jvmTrustManager <span style="color: #339933;">=</span> getTrustManager<span style="color: #009900;">&#40;</span>defaultAlgorithm, <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  KeyManager<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> keyManagers <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">new</span> CompositeX509KeyManager<span style="color: #009900;">&#40;</span>ImmutableList.<span style="color: #006633;">of</span><span style="color: #009900;">&#40;</span>jvmKeyManager, customKeyManager<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
  TrustManager<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> trustManagers <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">new</span> CompositeX509TrustManager<span style="color: #009900;">&#40;</span>ImmutableList.<span style="color: #006633;">of</span><span style="color: #009900;">&#40;</span>jvmTrustManager, customTrustManager<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
  SSLContext context <span style="color: #339933;">=</span> SSLContext.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SSL&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  context.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>keyManagers, trustManagers, <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">return</span> context<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">private</span> X509KeyManager getKeyManager<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> algorithm, <span style="color: #003399;">KeyStore</span> keystore, <span style="color: #000066; font-weight: bold;">char</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> password<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  KeyManagerFactory factory <span style="color: #339933;">=</span> KeyManagerFactory.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span>algorithm<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  factory.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>keystore, password<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">return</span> Iterables.<span style="color: #006633;">getFirst</span><span style="color: #009900;">&#40;</span>Iterables.<span style="color: #006633;">filter</span><span style="color: #009900;">&#40;</span>
      <span style="color: #003399;">Arrays</span>.<span style="color: #006633;">asList</span><span style="color: #009900;">&#40;</span>factory.<span style="color: #006633;">getKeyManagers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>, X509KeyManager.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>, <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">private</span> X509TrustManager getTrustManager<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> algorithm, <span style="color: #003399;">KeyStore</span> keystore<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  TrustManagerFactory factory <span style="color: #339933;">=</span> TrustManagerFactory.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span>algorithm<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  factory.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>keystore<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">return</span> Iterables.<span style="color: #006633;">getFirst</span><span style="color: #009900;">&#40;</span>Iterables.<span style="color: #006633;">filter</span><span style="color: #009900;">&#40;</span>
      <span style="color: #003399;">Arrays</span>.<span style="color: #006633;">asList</span><span style="color: #009900;">&#40;</span>factory.<span style="color: #006633;">getTrustManagers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>, X509TrustManager.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>, <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Yep, Java is <em>that</em> verbose. But at least its clean, reusable, flexible, and future-proof.</p>
<p>I think this meets Raz&#8217;s initial request for &#8220;a solution that can dynamically register multiple keystores in addition to the default keystore/certs in jre into jvm.&#8221; What do you think?</p>
<p><em><strong>Do you have a cleaner approach to mixing internal and external certs for SSL in Java?</strong></em></p>
<div class="shr-publisher-1779"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/04/java-ssl-with-multiple-keystores/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Intro to Streams2: New Node Streams (Part 1)</title>
		<link>http://codyaray.com/2013/04/intro-to-streams2-new-node-streams-part-1</link>
		<comments>http://codyaray.com/2013/04/intro-to-streams2-new-node-streams-part-1#comments</comments>
		<pubDate>Thu, 25 Apr 2013 05:28:25 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1713</guid>
		<description><![CDATA[There&#8217;s a saying among the core Node contributors: if you&#8217;re not using streams, you&#8217;re doing Node wrong*. So I spent last week learning the new Node streaming API (&#8220;streams2&#8243;) while building a small node app. While the documentation is pretty good, there&#8217;s not a lot of examples that are both realistic and easily digestible. This two-part tutorial aims [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>There&#8217;s a saying among the core Node contributors: if you&#8217;re not using streams, you&#8217;re doing Node wrong*. So I spent last week learning the <a title="Streams2" href="http://blog.nodejs.org/2012/12/21/streams2/">new Node streaming API (&#8220;streams2&#8243;)</a> while building a small node app. While the <a title="Stream" href="http://nodejs.org/api/stream.html">documentation</a> is pretty good, there&#8217;s not a lot of examples that are both realistic and easily digestible.</p>
<p>This two-part tutorial aims to build on the <a title="Five Minute Guide to Streams2" href="http://dailyjs.com/2013/04/01/streams-streams-streams/">DailyJS&#8217;s Five Minute Guide to Streams2</a>, providing real use cases for each of the different types of new streams (part 1) and the application of more complex design patterns to streams (part 2). <span id="more-1713"></span>If you haven&#8217;t read DailyJS&#8217;s tutorial yet, go ahead and read it now. Really, go.</p>
<p>You&#8217;re back? Good. You&#8217;ll notice that I use a different style of inheritance. For now, consider it personal preference and feel free to rewrite using your preferred style. <img src='http://codyaray.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Readable Stream</h2>
<p>Let&#8217;s start by creating <strong>a Readable stream that emits Javascript objects</strong>. This was the first custom stream I wrote, since I was buffering data in memory and then wanted to stream it through a CSV formatter and out through FTP. We&#8217;ll create a streams2 <a title="Readable Stream" href="http://nodejs.org/api/stream.html#stream_class_stream_readable">Readable stream</a> that accepts a Javascript array and emits one element of that array at a time.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">var</span> util <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'util'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
  stream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'stream'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">function</span> ArrayStream<span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
&nbsp;
  stream.<span style="color: #660066;">Readable</span>.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>self<span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> objectMode<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  self._read <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>size<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    data.<span style="color: #660066;">forEach</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>element<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      self.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>element<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    self.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
util.<span style="color: #660066;">inherits</span><span style="color: #009900;">&#40;</span>ArrayStream<span style="color: #339933;">,</span> stream.<span style="color: #660066;">Readable</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
module.<span style="color: #660066;">exports</span> <span style="color: #339933;">=</span> ArrayStream<span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Notice that we pass <code>objectMode=true</code> as an option to the stream, which tells it we&#8217;re handling Javascript objects rather than buffers or strings. The <code>size</code> argument to <code>_read</code> is advisory, so we&#8217;ve safely ignored it. We <code>push</code> each element out, one at a time. Finally, you signal the end of a Readable stream by pushing <code>null</code>.</p>
<p>A jasmine-node test for the ArrayStream class will demonstrate ArrayStream usage.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">var</span> stream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'stream'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
  ArrayStream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;../lib/streams/array&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
describe<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Streams: ArrayStream&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  it<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;should stream one element at a time from the array&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>finish<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">var</span> array <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span> <span style="color: #009900;">&#123;</span> a<span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> b<span style="color: #339933;">:</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> c<span style="color: #339933;">:</span> <span style="color: #CC0000;">3</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> x<span style="color: #339933;">:</span> <span style="color: #CC0000;">8</span><span style="color: #339933;">,</span> y<span style="color: #339933;">:</span> <span style="color: #CC0000;">9</span><span style="color: #339933;">,</span> z<span style="color: #339933;">:</span> <span style="color: #CC0000;">10</span> <span style="color: #009900;">&#125;</span> <span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
      source <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">new</span> ArrayStream<span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
      actual <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    source
      .<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'data'</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        actual.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
      .<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'end'</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        expect<span style="color: #009900;">&#40;</span>actual<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">toEqual</span><span style="color: #009900;">&#40;</span>array<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        finish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// ArrayStream</span></pre></td></tr></table></div>

<p>As you can see, ArrayStream emits &#8216;data&#8217; and &#8216;end&#8217; events. In fact, ArrayStream can do everything a Readable stream can do, including being piped.</p>
<h2>Transform Stream</h2>
<p>Okay, so now we have a stream of objects. What if we want to CSVify the objects? We need a<strong> <a title="Transform Stream" href="http://nodejs.org/api/stream.html#stream_class_stream_transform">Transform stream</a> to convert each object into an array</strong> representing a single ordered CSV record. This is what a streaming CSV stringifier needs as input.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">var</span> util <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'util'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
  stream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'stream'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">/*
 * Converts a datapoint into a CSV row (ordered array of fields).
 */</span>
<span style="color: #000066; font-weight: bold;">function</span> CsvPrepStream<span style="color: #009900;">&#40;</span>fields<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #000066; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
&nbsp;
 stream.<span style="color: #660066;">Transform</span>.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>self<span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> objectMode<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
 self._transform <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>datapoint<span style="color: #339933;">,</span> encoding<span style="color: #339933;">,</span> callback<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
   <span style="color: #000066; font-weight: bold;">var</span> record <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
   fields.<span style="color: #660066;">forEach</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>field<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
     record.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>datapoint<span style="color: #009900;">&#91;</span>field<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   self.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>record<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   callback<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
util.<span style="color: #660066;">inherits</span><span style="color: #009900;">&#40;</span>CsvPrepStream<span style="color: #339933;">,</span> stream.<span style="color: #660066;">Transform</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
exports.<span style="color: #660066;">CsvPrepStream</span> <span style="color: #339933;">=</span> CsvPrepStream<span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Note the use of <code>objectMode=true</code> again. This transform stream takes in a datapoint object, loops over the fields to be present in the CSV file (i.e., keys in the datapoint object), and pushes the values of the fields into a <code>record</code> array. We then <code>push</code> the transformed record out and signal completion by calling <code>callback()</code>. If there was an error, we could pass it to the callback as <code>callback(err)</code>.</p>
<h2>PassThrough Stream</h2>
<p>Now we&#8217;ll see one of the most frequent uses of the new <a title="PassThrough Stream" href="http://nodejs.org/api/stream.html#stream_class_stream_passthrough">PassThrough stream</a>: testing! Let&#8217;s write a jasmine-node test for CsvPrepStream; this test will demonstrate usage of PassThrough streams in addition to the functionality of CsvPrepStream.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">var</span> CsvPrepStream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'../lib/formatters/csv'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">CsvPrepStream</span><span style="color: #339933;">,</span>
  stream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'stream'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
describe<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Formatter: CsvPrepStream&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
  <span style="color: #000066; font-weight: bold;">var</span> data <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#123;</span>
    key1<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;foo&quot;</span><span style="color: #339933;">,</span>
    key2<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;bar&quot;</span><span style="color: #339933;">,</span>
    key3<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;baz&quot;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
    key2<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;zar&quot;</span><span style="color: #339933;">,</span>
    key1<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;boo&quot;</span><span style="color: #339933;">,</span>
    key3<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;zas&quot;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000066; font-weight: bold;">var</span> fields <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;key1&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;key2&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;key3&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
  it<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;should emit records with correctly ordered fields&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>finish<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">var</span> prepper <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">new</span> CsvPrepStream<span style="color: #009900;">&#40;</span>fields<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
      source <span style="color: #339933;">=</span> stream.<span style="color: #660066;">PassThrough</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span> objectMode<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
      actual <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
    source.<span style="color: #660066;">pipe</span><span style="color: #009900;">&#40;</span>prepper<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    source.<span style="color: #660066;">write</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    source.<span style="color: #660066;">write</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    source.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    prepper
      .<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'data'</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        actual.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
      .<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'end'</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        expect<span style="color: #009900;">&#40;</span>actual<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">toEqual</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span> <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;foo&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;bar&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;baz&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;boo&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;zar&quot;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;zas&quot;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        finish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// Formatter: CsvPrepStream</span></pre></td></tr></table></div>

<p>As you can see, PassThrough streams make great sources of data in testing! Just <code>write</code> some data into it in chunks, then <code>end</code> the stream. It&#8217;s that easy. If you&#8217;re writing anything other than strings or buffers, just remember that it must have <code>objectMode=true</code>.</p>
<p>Note that in a real test you&#8217;d want to test all possible scenarios, such as fields in the array that aren&#8217;t present as keys in the object and keys in the object that aren&#8217;t present in the array. This merely serves as an example.</p>
<h2>Writable Stream</h2>
<p>The final stream we&#8217;re going to cover today is the <a title="Writable Stream" href="http://nodejs.org/api/stream.html#stream_class_stream_writable">Writable stream</a>. Once the CsvFormatter was written, we needed a way to capture the entire CSV contents as a string for testing it. Thus, the StringBufferStream was born.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">var</span> util <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'util'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
  stream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'stream'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">function</span> StringBufferStream<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">var</span> self <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
&nbsp;
  self.<span style="color: #660066;">string</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933;">;</span>
&nbsp;
  stream.<span style="color: #660066;">Writable</span>.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span>self<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  self._write <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>chunk<span style="color: #339933;">,</span> encoding<span style="color: #339933;">,</span> callback<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    self.<span style="color: #660066;">string</span> <span style="color: #339933;">+=</span> chunk.<span style="color: #660066;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    callback<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
util.<span style="color: #660066;">inherits</span><span style="color: #009900;">&#40;</span>StringBufferStream<span style="color: #339933;">,</span> stream.<span style="color: #660066;">Writable</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
module.<span style="color: #660066;">exports</span> <span style="color: #339933;">=</span> StringBufferStream<span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>And for completeness sake, let&#8217;s go ahead and write a jasmine test for our StringBufferStream.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">var</span> StringBufferStream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'../libs/streams/string-buffer'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
  stream <span style="color: #339933;">=</span> require<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'stream'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
describe<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Streams: StringBufferStream&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
  it<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;should store the chunks in an internal string buffer&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>finish<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">var</span> source <span style="color: #339933;">=</span> stream.<span style="color: #660066;">PassThrough</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
      buffer <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">new</span> StringBufferStream<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    source.<span style="color: #660066;">pipe</span><span style="color: #009900;">&#40;</span>buffer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    source.<span style="color: #660066;">write</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;boo yeah, &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    source.<span style="color: #660066;">write</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;mi amigos&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    source.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    buffer.<span style="color: #660066;">on</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'finish'</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      expect<span style="color: #009900;">&#40;</span>buffer.<span style="color: #660066;">string</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">toEqual</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;boo yeah, mi amigos&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      finish<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// StringBufferStream</span></pre></td></tr></table></div>

<h2>Conclusion</h2>
<p>In this tutorial, we have seen real use cases for almost** all of the &#8220;streams2&#8243; stream: Readable, Writable, Transform, and PassThrough. We&#8217;ve also seen examples of how to pass Javascript objects through your stream pipeline and how to test your custom streams with jasmine-node. In Part 2 of this write-up, we&#8217;ll cover some more advanced uses cases and apply classic design patterns to streams to solve some tricky problems. Stay tuned!</p>
<p>* At least that&#8217;s what I heard from a colleague who attended the last NodeConf.<br />
** Once I find a good use case for the Duplex stream, I&#8217;ll write something up for it too.</p>
<div class="shr-publisher-1713"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/04/intro-to-streams2-new-node-streams-part-1/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Elegant Shell Scripts</title>
		<link>http://codyaray.com/2013/04/elegant-shell-scripts</link>
		<comments>http://codyaray.com/2013/04/elegant-shell-scripts#comments</comments>
		<pubDate>Sun, 21 Apr 2013 00:16:31 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1696</guid>
		<description><![CDATA[Shell scripts aren&#8217;t known for being the cleanest, most elegant part of your technology. But I argue that, as a vital piece of your stack, they should be afforded the same thought and care as other parts of your codebase. Sure, shell scripts like bash have some inherent limitations, but they shouldn&#8217;t prevent you from [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Shell scripts aren&#8217;t known for being the cleanest, most elegant part of your technology. But I argue that, as a vital piece of your stack, they should be afforded the same thought and care as other parts of your codebase.</p>
<p>Sure, shell scripts like bash have some inherent limitations, but they shouldn&#8217;t prevent you from following standard software engineering principles.</p>
<p>For example, bash functions can&#8217;t return values, but functionality should still be broken into small reusable chunks each having a single responsibility. Just <a href="http://www.linuxjournal.com/content/return-values-bash-functions" title="Return values Bash functions">call the function in a subshell</a> and have it echo the result. Or <a href="http://eatnumber1.blogspot.com/2010/07/bash-scripters-stop-using-subshells-to.html" title="Bash scripters: stop using subshells to call functions">use a standardized return value</a>. Plus, you can easily take advantage of the return codes of invoked programs.</p>
<p>Consider this simple script for generating a random alphanumeric identifier that&#8217;s unique across a group of files within a folder <span id="more-1696"></span>(e.g., xml files grouped by folder).</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/usr/bin/env bash</span>
<span style="color: #666666; font-style: italic;"># Generates a unique random fixed-length alphanumeric identifier</span>
<span style="color: #666666; font-style: italic;"># Usage: ./bin/generate-id [vendor|product] [length]</span>
<span style="color: #666666; font-style: italic;">#</span>
<span style="color: #666666; font-style: italic;"># Example: generate a unique id</span>
<span style="color: #666666; font-style: italic;">#        ./bin/generate-id</span>
<span style="color: #666666; font-style: italic;">#</span>
<span style="color: #666666; font-style: italic;"># Example: generate a unique eight-character product id</span>
<span style="color: #666666; font-style: italic;">#        ./bin/generate-id product 8</span>
&nbsp;
<span style="color: #007800;">path</span>=<span style="color: #800000;">${1:-vendor product}</span>
<span style="color: #007800;">length</span>=<span style="color: #800000;">${2:-7}</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> generate_id <span style="color: #7a0874; font-weight: bold;">&#123;</span>
  <span style="color: #666666; font-style: italic;"># https://coderwall.com/p/4zux3a</span>
  <span style="color: #7a0874; font-weight: bold;">echo</span> $<span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #c20cb9; font-weight: bold;">cat</span> <span style="color: #000000; font-weight: bold;">/</span>dev<span style="color: #000000; font-weight: bold;">/</span>urandom <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #007800;">LC_CTYPE</span>=C <span style="color: #c20cb9; font-weight: bold;">tr</span> <span style="color: #660033;">-dc</span> <span style="color: #ff0000;">&quot;a-zA-Z0-9&quot;</span> <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">head</span> <span style="color: #660033;">-c</span> <span style="color: #007800;">$length</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> id_exists <span style="color: #7a0874; font-weight: bold;">&#123;</span>
  <span style="color: #c20cb9; font-weight: bold;">grep</span> <span style="color: #660033;">-qr</span> <span style="color: #007800;">$1</span> <span style="color: #007800;">$2</span>
<span style="color: #7a0874; font-weight: bold;">&#125;</span>
&nbsp;
<span style="color: #007800;">id</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span>generate_id<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">while</span> id_exists <span style="color: #007800;">$id</span> <span style="color: #007800;">$path</span> ; <span style="color: #000000; font-weight: bold;">do</span>
  <span style="color: #007800;">id</span>=$<span style="color: #7a0874; font-weight: bold;">&#40;</span>generate_id<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #000000; font-weight: bold;">done</span>
&nbsp;
<span style="color: #7a0874; font-weight: bold;">echo</span> <span style="color: #007800;">$id</span></pre></td></tr></table></div>

<p>Looks good to this software engineer. <img src='http://codyaray.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="shr-publisher-1696"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/04/elegant-shell-scripts/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What I&#8217;ve Learned About Objective-C</title>
		<link>http://codyaray.com/2013/04/what-ive-learned-about-objective-c</link>
		<comments>http://codyaray.com/2013/04/what-ive-learned-about-objective-c#comments</comments>
		<pubDate>Thu, 18 Apr 2013 17:33:13 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[Ramblin' Thoughts]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1500</guid>
		<description><![CDATA[I spent the start of 2013 working on my first iOS SDK. In no particular order, here&#8217;s some of what I&#8217;ve learned about Objective-C. The hash of a collection is equal to the number of elements in that collection Singletons (er, &#8220;shared singletons&#8220;) are an accepted pattern in Objective-C Categories are cool. They&#8217;re kind of [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>I spent the start of 2013 working on my first iOS SDK. In no particular order, here&#8217;s some of what I&#8217;ve learned about Objective-C.</p>
<ul>
<li>The hash of a collection is equal to the number of elements in that collection</li>
<li>Singletons (er, &#8220;<a title="A Note on Objective-C Singletons" href="http://lukeredpath.co.uk/blog/a-note-on-objective-c-singletons.html">shared singletons</a>&#8220;) are an accepted pattern in Objective-C</li>
<li><a title="Objective-C Categories" href="http://macdevelopertips.com/objective-c/objective-c-categories.html">Categories</a> <a title="Objective-C for Java and Ruby Developers" href="http://snaggled.github.io/2010/02/28/Objective-C-for-Java-and-Ruby-Developers-Part-2.html">are cool</a>. They&#8217;re kind of like Ruby&#8217;s mixins.</li>
<li>Class clusters defy expectations. You can&#8217;t cleanly <a title="Override Hash Value of NSArray" href="http://stackoverflow.com/questions/14696922/override-hash-value-of-nsarray">override a method in a class cluster with a category</a>.</li>
<li>The community seems to be suffering from Apple&#8217;s control. Too many mentions of &#8220;I can&#8217;t tell you because of NDA&#8221; on StackOverflow</li>
<li>Apple&#8217;s docs are pretty good&#8230; if you can find the <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html">right</a> <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html">ones</a></li>
<li>There&#8217;s no easy way to build a &#8220;fat archive&#8221; and static framework unless you start with <a title="iOS Universal Framework" href="https://github.com/kstenerud/iOS-Universal-Framework">this project template</a>, which I didn&#8217;t.</li>
<li><a title="Amazing Apple-Like Documentation" href="http://www.cocoanetics.com/2011/11/amazing-apple-like-documentation/">appledoc</a> should be the de facto documentation engine now, but isn&#8217;t.</li>
<li><a title="Unit Testing NSUrlConnection#sendAsynchronousRequest" href="http://stackoverflow.com/questions/14718650/unit-testing-nsurlconnection-sendasynchronousrequest-with-ocmockito">Unit testing networking code</a> is much harder than it should be.</li>
<li>I miss Guava. Simple things like Objects.toStringHelper, Objects.hashCode, and EqualsTester.</li>
<li>I miss the builder pattern. Objective-C loves telescoping <del>constructors</del> initializers. Likewise, I miss Guice.</li>
<li>Many of my <a title="OCMockito" href="https://github.com/jonreid/OCMockito">favorite</a> <a title="OCHamcrest" href="https://github.com/hamcrest/OCHamcrest">libraries</a> for <a title="Intro to Objective-C TDD" href="http://qualitycoding.org/objective-c-tdd/">unit testing</a> have been ported to Objective-C.</li>
<li>The various abstractions for multithreaded programming are at war. GCD (the latest and greatest) vs NSOperationQueue (the most abstract) vs RunLoops. (Does this belong in this category? NSURLConnection can specify a runloop OR a queue, so I think so.)</li>
<li>Some (but not all) of CoreFoundation is <a title="CF Lite Source Code" href="http://www.opensource.apple.com/source/CF/CF-635/">open source</a>. A lot of NS* classes are the same as their CF counterparts via &#8220;<a title="Toll-Free Bridging" href="http://developer.apple.com/library/ios/#documentation/CoreFoundation/Conceptual/CFDesignConcepts/Articles/tollFreeBridgedTypes.html">toll-free bridging</a>&#8220;</li>
<li><a title="Variable Argument Lists In Cocoa" href="http://www.cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html">Variable argument lists</a> don&#8217;t know the number of arguments without being told. Most people use a nil-terminated list. A format string (implicit count) or explicitly passing the count also works.</li>
<li>There is no NullPointerException; <a href="http://stackoverflow.com/questions/156395/sending-a-message-to-nil">sending a message to nil</a> is fine (no exception raised). This can really bite you in the ass.</li>
<li>There are <a href="http://stuartkhall.com/posts/ios-development-tips-i-would-want-if-i-was-starting-out-today">best practices</a>. Read them before you start your next (first?) iOS or Objective-C project. I found this after I figured them out in bits and pieces.</li>
</ul>
<p>Since I was simultaneously writing an Android SDK, expect a similar post about what I learned about Android in the process.</p>
<div class="shr-publisher-1500"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/04/what-ive-learned-about-objective-c/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Open Source: Cassandra Super Columns to Composite Columns Migrator</title>
		<link>http://codyaray.com/2013/04/open-source-cassandra-super-columns-to-composite-columns-migrator</link>
		<comments>http://codyaray.com/2013/04/open-source-cassandra-super-columns-to-composite-columns-migrator#comments</comments>
		<pubDate>Mon, 15 Apr 2013 16:14:25 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1639</guid>
		<description><![CDATA[If you&#8217;ve been following Cassandra&#8217;s development, you&#8217;ll know that its made huge progress in the last two years. My company first start using Cassandra v0.8.x, and the latest stable version is now v1.2.3. One of the major changes was adding support for composite columns. In DataStax words, &#8220;composite comparators can be thought of simply as [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>If you&#8217;ve been following Cassandra&#8217;s development, you&#8217;ll know that its made <strong>huge</strong> progress in the last two years. My company first start using Cassandra v0.8.x, and the latest stable version is now v1.2.3.</p>
<p>One of the major changes was adding support for <a href="http://www.datastax.com/dev/blog/introduction-to-composite-columns-part-1" title="Introduction to Composite Columns">composite columns</a>. In DataStax words, &#8220;composite comparators can be thought of simply as a comparator composed of several other types of comparators.&#8221; Since introduction of composite columns in v1.0, there&#8217;s been a trend to slowly fade out super columns in favor of composite columns. Cassandra itself is <a href="https://issues.apache.org/jira/browse/CASSANDRA-3237" title="refactor super column implementation to use composite column names instead">refactoring supercolumns to use composites under-the-hood</a> in v2.0.</p>
<p>So when my company upgraded to v1.0, I wrote a little tool to migrate our data from using super columns to use composite columns instead. This was about a year ago, but I wanted to announce I&#8217;ve open sourced it on Github. Better late than never, right?</p>
<p><a href="https://github.com/codyaray/cassandra-sc2cc" title="cassandra-sc2cc">Grab the source and try it yourself</a> **.</p>
<p>** Disclaimer: I waive all responsibility for your use of this code. Think twice before using it on a large production dataset.</p>
<div class="shr-publisher-1639"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/04/open-source-cassandra-super-columns-to-composite-columns-migrator/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Case Study: Measuring Your Health</title>
		<link>http://codyaray.com/2013/04/case-study-measuring-your-health</link>
		<comments>http://codyaray.com/2013/04/case-study-measuring-your-health#comments</comments>
		<pubDate>Sat, 13 Apr 2013 16:27:56 +0000</pubDate>
		<dc:creator>codyaray</dc:creator>
				<category><![CDATA[Case Studies]]></category>

		<guid isPermaLink="false">http://codyaray.com/?p=1557</guid>
		<description><![CDATA[Ever step off the scale and wonder if a weight increase was due to gained fat or muscle? A couple weeks ago, I was frustrated that my scale was showing the same weight, yet I could see my progress in the mirror and on the mat. That&#8217;s when I had a DEXA scan, and I&#8217;ve [...]]]></description>
				<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Ever step off the scale and wonder if a weight increase was due to gained fat or muscle?</p>
<p>A couple weeks ago, I was frustrated that my scale was showing the same weight, yet I could see my progress in the mirror and on the mat. That&#8217;s when I had a DEXA scan, and I&#8217;ve since learned how few people know about it.</p>
<p>If you&#8217;ve read any of my other <a href="http://codyaray.com/category/case-studies">case studies</a>, you&#8217;ll know that I use numbers to make a lot of decisions in my life. I love DEXA because of the awesomely detailed and accurate information it can provide. A couple days ago, we learned <a title="Smart Scales and Body Fat Measurements" href="http://codyaray.com/2013/04/smart-scales-and-body-fat-measurements">why smart scales don&#8217;t cut it for measuring body fat</a>; not coincidentally, data from a DEXA scan was used to make the point.</p>
<p>Now that I&#8217;ve built it up, I bet your wondering what kind of information you can get from DEXA.</p>
<ul>
<li>whole body breakdown into lean pounds, fat pounds, and bone mineral content (BMC)</li>
<li>lean pounds, fat pounds, and BMC for each leg and each arm, your android (abdominal) and gynoid (hips/thighs) areas</li>
<li>lean mass symmetry, fat mass distribution, bone density, and more</li>
</ul>
<p>Forewarning, your body-fat percentage will likely be higher than you expect. I was in shock on my first consultation. DEXA includes all the fatty tissues in your body, even those in your brain (around 8 pounds). If you weigh 160 pounds, that&#8217;s an instant 5% increase in body fat.</p>
<p><strong>What&#8217;s this data look like? Well, I&#8217;m glad you asked.</strong></p>
<p>Without further ado, here are my DEXA results as an example.<span id="more-1557"></span></p>
<p><iframe style="border: 1px solid #CCC; border-width: 1px 1px 0; margin-bottom: 5px;" src="http://www.slideshare.net/slideshow/embed_code/18521010" height="511" width="479" allowfullscreen="" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"></iframe></p>
<div style="margin-bottom: 5px;"><strong> <a title="Cody A. Ray DEXA Report 3/21/2013" href="http://www.slideshare.net/codyaray/raycody-dfr3" target="_blank">DEXA Report 3/21/2013</a> </strong> from <strong><a href="http://www.slideshare.net/codyaray" target="_blank">Cody A. Ray</a></strong></div>
<p>Personal note: I lost 18 pounds of fat and gained 10 pounds of muscle! That&#8217;s a 28 pound re-composition and a decrease of 9% body fat! Woo!</p>
<p>Ok, now you&#8217;re excited. <strong>How can I get my own DEXA scan?</strong></p>
<p>If you&#8217;re in the Chicagoland area, I highly recommend <a title="DexaFit" href="http://dexafit.com">DexaFit</a>, where I have my scans done. Otherwise, if you can&#8217;t find a local center online, call your local orthopedic doctor or hospital. Ask about bone densitometry—DEXA scans are used to diagnose osteoporosis around the country. Its actually what they were designed to do. <img src='http://codyaray.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="shr-publisher-1557"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://codyaray.com/2013/04/case-study-measuring-your-health/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 2.423 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2013-06-18 16:02:45 -->
