<?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>Team Lazer Beez Blog</title>
	<atom:link href="http://blog.teamlazerbeez.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.teamlazerbeez.com</link>
	<description></description>
	<lastBuildDate>Tue, 17 Apr 2012 22:11:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Extending the simple Java/Jetty/Guice/Jersey/Jackson web stack with automatic Jersey resource method metrics</title>
		<link>http://blog.teamlazerbeez.com/2012/03/31/extending-the-simple-javajettyguicejerseyjackson-web-stack-with-automatic-jersey-resource-method-metrics/</link>
		<comments>http://blog.teamlazerbeez.com/2012/03/31/extending-the-simple-javajettyguicejerseyjackson-web-stack-with-automatic-jersey-resource-method-metrics/#comments</comments>
		<pubDate>Sun, 01 Apr 2012 05:47:49 +0000</pubDate>
		<dc:creator>Marshall Pierce</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[jackson]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jersey]]></category>
		<category><![CDATA[jetty]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[metrics]]></category>

		<guid isPermaLink="false">http://blog.teamlazerbeez.com/?p=2769</guid>
		<description><![CDATA[Several months ago I put up a tutorial on using Jetty, Jersey, Jackson and Guice to make a small JSON web service stack. The code is more of a proof of concept than anything else, but we&#8217;re going to be giving it a few more real-world features today by adding the use of the Metrics [...]]]></description>
			<content:encoded><![CDATA[<p>Several months ago I put up a <a href="http://blog.teamlazerbeez.com/2011/08/15/a-simple-java-web-stack-with-guice-jetty-jersey-and-jackson/">tutorial on using Jetty, Jersey, Jackson and Guice</a> to make a small JSON web service stack. The <a href="https://github.com/teamlazerbeez/simple-web-stack">code</a> is more of a proof of concept than anything else, but we&#8217;re going to be giving it a few more real-world features today by adding the use of the <a href="http://metrics.codahale.com/">Metrics</a> library.</p>
<p>As a quick review, the project is a web service that allows accessing peanut butter &#038; jelly sandwiches over HTTP. It has a primitive &#8220;stats&#8221; resource to allow you to see how many sandwiches have been made and how much peanut butter &#038; jelly was used. This stats facility is more of demo of how to wire stuff together with Guice and how requests are routed to JAX-RS resources than a useful way to monitor usage, though.</p>
<p>We&#8217;re going to do two things to improve the situation. First, we&#8217;ll re-implement the number of sandwiches and amount of PB&#038;J tracking using individual <a href="http://metrics.codahale.com/manual/core/#counters">Counters</a> and Gauges. Second, we&#8217;ll add code to automatically create various useful metrics for every resource method via Jersey ResourceFilter, ResourceFilterFactory, ContainerFilterResponseFilter, ResourceMethodDispatchAdapter, and ResourceMethodDispatchProvider implementations. Fun! :)</p>
<p>As before, I&#8217;ll outline the code changes in this article, but the complete code is in the <a href="https://github.com/teamlazerbeez/simple-web-stack">repo</a> for your browsing pleasure.</p>
<h2>Reimplementing Sandwich stats</h2>
<p>The SandwichStats object (a singleton) keeps track of the number of sandwiches and the amount of PB &#038; J used to make them. This data is exposed through SandwichStatsResource, which response to GET of <code>/sandwich/stats</code> with data like <code>{"sandwichesMade":2,"gramsOfJam":200,"gramsOfPeanutButter":400}</code>. We want to keep track of those three numbers with metrics now as well. Metrics (the library) offers many different types of metrics (the concept).  For these three numbers, there are two ways we could do it. We could use a Gauge to expose the numbers that SandwichStats is already tracking internally, or we could use a Counter that we increment whenever we increment the fields that SandwichStats already has. To demonstrate the use of Gauges and Counters, we&#8217;ll do some of both.</p>
<p>When creating a metric object, you can use a MetricsRegistry instance or the static method on the Metrics class. If you have multiple applications running inside the same JVM, or need that separation of metrics for other reasons, use MetricsRegistery. If you aren&#8217;t doing that, you can use the static methods on Metrics, but we&#8217;ll go ahead and use a MetricsRegistry because it&#8217;s just as easy as using the Metrics class when we have Guice to help us.</p>
<p>First, add a binding for MetricsRegistry in a Guice module:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">    bind<span style="color: #009900;">&#40;</span>MetricsRegistry.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toInstance</span><span style="color: #009900;">&#40;</span>Metrics.<span style="color: #006633;">defaultRegistry</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>We&#8217;ll inject a MetricsRegistry into the SandwichStats ctor:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Counter jamCounter<span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Counter pbCounter<span style="color: #339933;">;</span>
&nbsp;
@Inject
SandwichStats<span style="color: #009900;">&#40;</span>MetricsRegistry metricsRegistry<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    metricsRegistry.<span style="color: #006633;">newGauge</span><span style="color: #009900;">&#40;</span>SandwichStats.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #0000ff;">&quot;sandwich-count&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Gauge<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Integer</span> value<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	    <span style="color: #000000; font-weight: bold;">return</span> sandwichesMade<span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    jamCounter <span style="color: #339933;">=</span> metricsRegistry.<span style="color: #006633;">newCounter</span><span style="color: #009900;">&#40;</span>SandwichStats.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #0000ff;">&quot;grams-of-jam&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    pbCounter <span style="color: #339933;">=</span> metricsRegistry.<span style="color: #006633;">newCounter</span><span style="color: #009900;">&#40;</span>SandwichStats.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #0000ff;">&quot;grams-of-pb&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Then, we can update the existing recordSandwich method:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #000066; font-weight: bold;">void</span> recordSandwich<span style="color: #009900;">&#40;</span>Sandwich sandwich<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    sandwichesMade<span style="color: #339933;">++;</span>
    gramsOfJam <span style="color: #339933;">+=</span> sandwich.<span style="color: #006633;">getGramsOfJam</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    gramsOfPeanutButter <span style="color: #339933;">+=</span> sandwich.<span style="color: #006633;">getGramsOfPeanutButter</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    jamCounter.<span style="color: #006633;">inc</span><span style="color: #009900;">&#40;</span>sandwich.<span style="color: #006633;">getGramsOfJam</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    pbCounter.<span style="color: #006633;">inc</span><span style="color: #009900;">&#40;</span>sandwich.<span style="color: #006633;">getGramsOfPeanutButter</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></div></div>

<p>We don&#8217;t have to do anything for the &#8220;sandwich-count&#8221; metric because it&#8217;s a Gauge that references the existing field. The other two metrics are Counters, and therefore need to be updated separately.</p>
<p>Start up the service&#8217;s main method and open JConsole. When you connect to your process, open the MBeans tab and look in the com.teamlazerbeez.http.sandwich package. You should see some SandwichStats MBeans. Expand the grams-of-jam MBean, select the attribute and double click the numeric value to open a graph. Re-run the /sandwich/create request a few times and note that the graph will periodically update.</p>
<h2>Automatic Jersey Request Metrics</h2>
<p>Using and creating metrics by hand is already useful, but we can do better. We&#8217;re going to hook into the Jersey request dispatch mechanism to automatically create metrics for per-status code counts, etc. for every JAX-RS resource method.</p>
<p>In Jersey, resource methods are represented by subclasses of AbstractMethod. AbstractMethod is an abstract class representing a method that is invoked by Jersey. This could be a setter that&#8217;s invoked by Jersey&#8217;s IoC mechanism or a resource method or other types of methods. We only care about two subclasses: AbstractResourceMethod and AbstractSubResourceMethod (a subclass of AbstractResourceMethod). In JAX-RS, a resource method is one that uses the @Path annotation of its containing class, and a <a href="http://jersey.java.net/nonav/documentation/latest/user-guide.html#d4e374">sub-resource method</a> is one that has a @Path annotation of its own.</p>
<p>There are two mechanisms that we&#8217;re going to use in the Jersey request invocation pipeline to do this. We&#8217;ll do the the simpler one first. </p>
<h2>Per-resource method counters with ResourceFilterFactory</h2>
<p>Think of a Jersey <a href="http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/container/ResourceFilter.html">ResourceFilter</a> as filling a subset of the role of a javax.servlet.Filter. It can observe and modify the input and the output of a JAX-RS method invocation, but it does not wrap the actual invocation the way a servlet Filter does. This is still useful, though, since we can observe the HTTP status codes being output and create metrics to expose them. </p>
<p>A ResourceFilter itself doesn&#8217;t do much of anything except provide getters for ContainerRequestFilter and ContainerResponseFilter. Those two do the actual work. In our case (observing status codes) we only care about the latter. However, ResourceFilter objects are created by ResourceFilterFactory implementations, so we&#8217;ll start there. Here&#8217;s part of an implementation of a ResourceFilterFactory (check the <a href="https://github.com/teamlazerbeez/simple-web-stack/blob/master/src/main/java/com/teamlazerbeez/http/metrics/HttpStatusCodeMetricResourceFilterFactory.java">source</a> for the full details):</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">public</span> List<span style="color: #339933;">&lt;</span>ResourceFilter<span style="color: #339933;">&gt;</span> create<span style="color: #009900;">&#40;</span>AbstractMethod am<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// documented to only be AbstractSubResourceLocator, AbstractResourceMethod, or AbstractSubResourceMethod</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>am <span style="color: #000000; font-weight: bold;">instanceof</span> AbstractSubResourceLocator<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">// not actually invoked per request, nothing to do</span>
	logger.<span style="color: #006633;">debug</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Ignoring AbstractSubResourceLocator &quot;</span> <span style="color: #339933;">+</span> am<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</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> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>am <span style="color: #000000; font-weight: bold;">instanceof</span> AbstractResourceMethod<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #003399;">String</span> metricBaseName <span style="color: #339933;">=</span> getMetricBaseName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>AbstractResourceMethod<span style="color: #009900;">&#41;</span> am<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	Class<span style="color: #339933;">&lt;?&gt;</span> resourceClass <span style="color: #339933;">=</span> am.<span style="color: #006633;">getResource</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getResourceClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">return</span> Lists.<span style="color: #339933;">&lt;</span>ResourceFilter<span style="color: #339933;">&gt;</span>newArrayList<span style="color: #009900;">&#40;</span>
		<span style="color: #000000; font-weight: bold;">new</span> HttpStatusCodeMetricResourceFilter<span style="color: #009900;">&#40;</span>metricBaseName, resourceClass<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;">else</span> <span style="color: #009900;">&#123;</span>
	logger.<span style="color: #006633;">warn</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Got an unexpected instance of &quot;</span> <span style="color: #339933;">+</span> am.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;: &quot;</span> <span style="color: #339933;">+</span> am<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</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>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>What we see here is that if the AbstractMethod is an AbstractResourceMethod, we generate a &#8216;metricBaseName&#8217; (a prefix common to all metrics tied to that resource method) and return a list of ResourceFilter objects containing a HttpStatusCodeMetricResourceFilter, which is one of our classes. Here&#8217;s what that class does (again, check the <a href="https://github.com/teamlazerbeez/simple-web-stack/blob/master/src/main/java/com/teamlazerbeez/http/metrics/HttpStatusCodeMetricResourceFilter.java">source</a>).</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">class</span> HttpStatusCodeMetricResourceFilter <span style="color: #000000; font-weight: bold;">implements</span> ResourceFilter, ContainerResponseFilter <span style="color: #009900;">&#123;</span>
&nbsp;
    ....
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> ContainerResponse filter<span style="color: #009900;">&#40;</span>ContainerRequest request, ContainerResponse response<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">Integer</span> status <span style="color: #339933;">=</span> response.<span style="color: #006633;">getStatus</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        Counter counter <span style="color: #339933;">=</span> counters.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>status<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>counter <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: #666666; font-style: italic;">// despite the method name, this actually will return a previously created metric with the same name</span>
            Counter newCounter <span style="color: #339933;">=</span> metricsRegistry.<span style="color: #006633;">newCounter</span><span style="color: #009900;">&#40;</span>resourceClass, metricBaseName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; &quot;</span> <span style="color: #339933;">+</span> status <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; counter&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            Counter otherCounter <span style="color: #339933;">=</span> counters.<span style="color: #006633;">putIfAbsent</span><span style="color: #009900;">&#40;</span>status, newCounter<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>otherCounter <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: #666666; font-style: italic;">// we lost the race to set that counter, but shouldn't create a duplicate since Metrics.newCounter will do the right thing</span>
                counter <span style="color: #339933;">=</span> otherCounter<span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
                counter <span style="color: #339933;">=</span> newCounter<span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        counter.<span style="color: #006633;">inc</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> response<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This filter doesn&#8217;t modify the response; instead, it just gets the HTTP status, gets the appropriate Counter (creating it if need be), and increments it.</p>
<p>We have enough now to be able to hook our status-code-counting filter into Jersey. This is a little ungainly, but basically we&#8217;re informing GuiceContainer (the Jersey code that interacts with Guice and Guice Servlet) the ResourceFilterFactory to use. You can specify more than one (comma-separated strings, Class[], etc &#8212; check the docs on ResourceConfig.PROPERTY_RESOURCE_FILTER_FACTORIES) but we have just one here.<br />
Before:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">serve<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/*&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">with</span><span style="color: #009900;">&#40;</span>GuiceContainer.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>After:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Map<span style="color: #339933;">&lt;</span>String, String<span style="color: #339933;">&gt;</span> guiceContainerConfig <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HashMap<span style="color: #339933;">&lt;</span>String, String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
guiceContainerConfig.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>ResourceConfig.<span style="color: #006633;">PROPERTY_RESOURCE_FILTER_FACTORIES</span>,
    HttpStatusCodeMetricResourceFilterFactory.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getCanonicalName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
serve<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/*&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">with</span><span style="color: #009900;">&#40;</span>GuiceContainer.<span style="color: #000000; font-weight: bold;">class</span>, guiceContainerConfig<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Start up the service and check the MBeans. You&#8217;ll see SandwichStats, but nothing for the SandwichMakerResource until you use the &#8220;/sandwich/create&#8221; endpoint. Once you do that, you&#8217;ll see a metric named &#8220;/sandwich/create GET 200 counter&#8221; appear, and it will update appropriately as you make more requests.</p>
<h2>Per-resource method timing with ResourceMethodDispatchAdapter and friends</h2>
<p>Status code counters are great, but we really want to be able to generate timing info for request invocation, and to get timing information we&#8217;d have to use a ThreadLocal in a ContainerRequestFilter/ContainerResponseFilter pair, and that&#8217;s not how we roll. </p>
<p>The Metrics library has <a href="http://metrics.codahale.com/manual/guice/">built-in support for timing method invocations</a> if you annotate the methods you wish to be timed with @Timed. This uses <a href="https://code.google.com/p/google-guice/wiki/AOP">Guice AOP</a> under the hood, which has a few limitations (no non-final classes, must instantiate via Guice, etc.), so let&#8217;s see if we can do it a little less invasively.</p>
<p>We&#8217;ll hook into the Jersey method invocation mechanism via <a href="http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/container/ResourceMethodDispatchAdapter.html">ResourceMethodDispatchAdapter</a> and <a href="http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/spi/container/ResourceMethodDispatchProvider.html">ResourceMethodDispatchProvider</a>. A ResourceMethodDispatchProvider is responsible for creating RequestDispatcher objects for AbstractResourceMethods, and a ResourceMethodDispatchAdapter is a Jersey extension mechanism to allow us to control what ResourceMethodDispatchProvider gets used. Therefore, by registering our ResourceMethodDispatchAdapter, we can wrap the default ResourceMethodDispatchProvider with one that gathers timing info. The code you&#8217;ll see here does timing for all resource methods, but you could trivially make it conditional on an annotation on the resource method or class or anything you wish.</p>
<p>We&#8217;ll start with our <a href="https://github.com/teamlazerbeez/simple-web-stack/blob/master/src/main/java/com/teamlazerbeez/http/metrics/TimingRequestDispatcher.java">custom RequestDispatcher implementation TimingRequestDispatcher</a>. We want to use whatever dispatcher Jersey provides under the hood, so we wrap that dispatcher and just capture timing info.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> dispatch<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> resource, HttpContext context<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">final</span> TimerContext time <span style="color: #339933;">=</span> timer.<span style="color: #006633;">time</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
	wrappedDispatcher.<span style="color: #006633;">dispatch</span><span style="color: #009900;">&#40;</span>resource, context<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #009900;">&#123;</span>
	time.<span style="color: #006633;">stop</span><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;">&#125;</span></pre></div></div>

<p>We then can use this RequestDispatcher in <a href="https://github.com/teamlazerbeez/simple-web-stack/blob/master/src/main/java/com/teamlazerbeez/http/metrics/TimingResourceMethodDispatchProvider.java">TimingResourceMethodDispatchProvider</a>. If you wanted to have conditional logic to sometimes not create timers, this would be a good place to do it.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">public</span> RequestDispatcher create<span style="color: #009900;">&#40;</span>AbstractResourceMethod abstractResourceMethod<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">String</span> metricBaseName <span style="color: #339933;">=</span> getMetricBaseName<span style="color: #009900;">&#40;</span>abstractResourceMethod<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">Timer</span> timer <span style="color: #339933;">=</span> metricsRegistry.<span style="color: #006633;">newTimer</span><span style="color: #009900;">&#40;</span>abstractResourceMethod.<span style="color: #006633;">getResource</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getResourceClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>,
	metricBaseName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; timer&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> TimingRequestDispatcher<span style="color: #009900;">&#40;</span>wrappedProvider.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span>abstractResourceMethod<span style="color: #009900;">&#41;</span>, timer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>We can use that ResourceMethodDispatchProvider in a <a href="https://github.com/teamlazerbeez/simple-web-stack/blob/master/src/main/java/com/teamlazerbeez/http/metrics/TimingResourceMethodDispatchAdapter.java">TimingResourceMethodDispatchAdapter</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">public</span> ResourceMethodDispatchProvider adapt<span style="color: #009900;">&#40;</span>ResourceMethodDispatchProvider provider<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> TimingResourceMethodDispatchProvider<span style="color: #009900;">&#40;</span>metricsRegistry, provider<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And then bind your Adapter class (which must also be annotated with com.google.inject.Singleton and javax.ws.rs.ext.Provider):</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">bind<span style="color: #009900;">&#40;</span>TimingResourceMethodDispatchAdapter.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Start up the service and you should see Timer metrics being generated for all endpoints. It&#8217;s a little bit more convoluted to use the ResourceMethodDispatchAdapter approach, but it&#8217;s probably only really needed for timing; the ResourceFilterFactory approach should work for most everything else. Either way, now you know how to use the basics of the Metrics library, and how to execute custom logic before (ContainerRequestFilter), after (ContainerResponseFilter), and around (ResourceMethodDispatchAdapter) Jersey resource method invocation.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2012/03/31/extending-the-simple-javajettyguicejerseyjackson-web-stack-with-automatic-jersey-resource-method-metrics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java 2-way TLS/SSL (Client Certificates) and PKCS12 vs JKS KeyStores</title>
		<link>http://blog.teamlazerbeez.com/2011/10/18/java-2-way-tlsssl-client-certificates-and-pkcs12-vs-jks-keystores/</link>
		<comments>http://blog.teamlazerbeez.com/2011/10/18/java-2-way-tlsssl-client-certificates-and-pkcs12-vs-jks-keystores/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 23:11:27 +0000</pubDate>
		<dc:creator>Marshall Pierce</dc:creator>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[crypto]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jks]]></category>
		<category><![CDATA[jsse]]></category>
		<category><![CDATA[pkcs12]]></category>
		<category><![CDATA[ssl]]></category>
		<category><![CDATA[tls]]></category>
		<category><![CDATA[x509]]></category>

		<guid isPermaLink="false">http://blog.teamlazerbeez.com/?p=2733</guid>
		<description><![CDATA[There&#8217;s some confusion on the Internet about how to control which certificates are used for server (and non-server) TLS sockets and why client certs just don&#8217;t seem to work right (see here, here, here, here, etc.). I&#8217;ll explain how the process is supposed to happen, explain why it doesn&#8217;t necessarily work easily with Java, and [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s some confusion on the Internet about how to control which certificates are used for server (and non-server) TLS sockets and why client certs just don&#8217;t seem to work right (see <a href="http://stackoverflow.com/questions/875467/java-client-certificates-over-https-ssl">here</a>, <a href="http://denistek.blogspot.com/2010/05/mutual-authentication-with-client.html">here</a>, <a href="http://stackoverflow.com/questions/1788031/how-can-i-have-multiple-ssl-certificates-for-a-java-server">here</a>, <a href="http://forums.devshed.com/java-help-9/javax-net-ssl-sslhandshakeexception-received-fatal-alert-bad-certificate-220576.html">here</a>, etc.). I&#8217;ll explain how the process is supposed to happen, explain why it doesn&#8217;t necessarily work easily with Java, and how to work around the problem. Though this article generally applies to SSL as well as TLS, I&#8217;ll refer to just TLS from now on. Also, the testing and bug hunting in this article were done against Sun/Oracle&#8217;s JDK 6u25. I have not confirmed whether or not these issues are fixed in Java 7.</p>
<h2>Basic terminology</h2>
<dl>
<dt>Certificate or cert</dt>
<dd>The public half of a public/private key pair, though it&#8217;s not generally referred to as a key. This part is freely given to anyone.</dd>
<dt>Private key</dt>
<dd>A private key is never given out publicly. It is used to sign or encrypt data. A private key can be used to verify that its corresponding certificate was used to sign or encrypt things and vice versa.</dd>
<dt>Certificate Signing Request or CSR</dt>
<dd>A file that you generate with your private key. You can send just the CSR to your CA and they will create a signed certificate for you.</dd>
<dt>Certificate Authority or CA</dt>
<dd>These are places like Thawte that you pay in order to get a certificate that browsers will accept. You can also use someone like CACert.org to get a free certificate that browsers will not accept. You can also generate your own simple CA using openssl. A CA uses its private key to digitally sign a CSR and create a signed cert so that browsers can use the CA&#8217;s cert to tell that <em>your</em> cert is approved by that CA.</dd>
<dt>Distinguished Name or DN</dt>
<dd>This is defined by LDAP. It&#8217;s a grouping of RDNs (Relative Distinguished Names). A RDN is something like &#8220;CN=your name&#8221;. This one means that the Common Name is set to the string &#8220;your name&#8221;. A DN would be something like &#8220;CN=your name,OU=Engineering,O=Initech&#8221;. In this case, OU means Organizational Unit and O means Organization. </dd>
</dl>
<dt>X509</dt>
<dl>A specification governing the format and usage of certificates.</dl>
<p></p>
<h2>How client certs are supposed to work</h2>
<p>This is a greatly simplified explanation of the TLS 1.0 protocol. Check out <a href="http://tools.ietf.org/html/rfc2246">the RFC</a> for more details at around section 7.4. (There are newer versions of TLS, but 1.0 is what Java 6 supports.) I&#8217;m showing the case where client certificates have been configured on the server side, so this isn&#8217;t exactly what happens when you do normal server-only TLS.</p>
<ol>
<li>ClientHello: client informs server what ciphers and compression methods it supports</li>
<li>ServerHello
<ul>
<li>Server picks a cipher and compression that both it and the client support and tells the client about its choices, as well as some other things like a session id</li>
<li>It presents its certificate (this is what the client needs to validate as being signed by a trusted CA)</li>
<li>It presents a list of certificate authority DNs that client certs may be signed by</li>
</ul>
<li>Client response
<ul>
<li>The client continues the key exchange protocol necessary to set up a TLS session</li>
<li>The client presents a certificate that was signed by one of the CAs described in the Server hello</li>
</ul>
</li>
<li>The server accepts the cert that the client presented and all is well</li>
</ol>
<p>Note that the ServerHello does not ask for specific client certificates. It just provides info about CAs (in the form of DNs) and expects the client to figure out an appropriate cert that was signed by one of those CAs.</p>
<h2>File formats for certs and keys</h2>
<p>There are many different formats used for storing keys and certs on-disk, but the most common ones are probably PEM, PKCS12, and JKS. The formats are not treated equally by Java, so it&#8217;s important to understand the different formats. It&#8217;s not obvious how to manipulate these formats, so I&#8217;ve also included sample commands for working them them.</p>
<h4>PEM</h4>
<p>PEM is just <a href="http://en.wikipedia.org/wiki/Distinguished_Encoding_Rules">DER</a> that&#8217;s been Base64 encoded. It looks like this for a certificate:</p>
<pre>
-----BEGIN CERTIFICATE-----
(base 64 encoded stuff)
-----END CERTIFICATE-----
</pre>
<p>or for a private key:</p>
<pre>
-----BEGIN PRIVATE KEY-----
(base 64 encoded stuff)
-----END PRIVATE KEY-----
</pre>
<p>Sometimes PEM files will have a human-readable block of text above the Base64 encoded block. You can safely remove this human-readable text. (It confuses Java&#8217;s keytool.)</p>
<p>Some applications prefer the cert PEM and the private key PEM to be in one file. (Apache httpd is one, if I remember correctly.) Since PEM files are just plain text, you can do that with cat: <code>cat cert.pem key.pem > cert-with-key.pem</code>. While you could arbitrarily combine as many PEM blocks as you wanted into one file, typically they are kept separate except for this one case.</p>
<p>You can get a human-readable description of a cert in PEM format with <code>openssl x509 -in cert.pem -noout -text</code>. (Certs are X509 formatted, hence the &#8216;x509&#8242; subcommand to openssl.) For keys, the command is <code>openssl rsa -in key.pem -text -noout</code>.</p>
<p>Private keys can also be encrypted, in which case the marker block will say BEGIN ENCRYPTED PRIVATE KEY. You can create the decrypted form of the key with <code>openssl rsa -in key-encrypted.pem -out key-decrypted.pem</code>.</p>
<h4>PKCS12</h4>
<p>PKCS12 is a password-protected format that can contain multiple certificates and keys. </p>
<p>You can view the contents of a PKCS12 file (typically .p12 is used for PKCS12 files) with <code>openssl pkcs12 -in file.p12</code>. Add <code>-info</code> for a little bit more metadata. Note that if the file includes a private key, openssl will ask you for another password after asking for the decryption password for the PKCS12 file. This second password is used to encrypt the private key before displaying its PEM data to you. You could put this data in a separate file and decrypt it as shown above if you want the decrypted form.</p>
<p>You can create PKCS12 files with or without private keys or CA certs.<br />
Cert and key:<br />
<code>openssl pkcs12 -export -out cert-and-key.p12 -in cert.pem -inkey key.pem</code><br />
Cert and key that includes the CA cert that signed the cert:<br />
<code>openssl pkcs12 -export -out cert-and-key-with-ca.p12 -in cert.pem -inkey key.pem -CAfile /path/to/cacert.pem -chain</code><br />
Cert without key (useful for CA certs):<br />
<code>openssl pkcs12 -export -out cacert.p12 -in cacert.pem -nokeys</code></p>
<h4>JKS</h4>
<p>A JKS keystore stores multiple certs and keys like PKCS12, but it&#8217;s just a Java thing, not a widespread standard like PKCS12. The tool to manage JKS files is &#8216;keytool&#8217; which ships with the JDK. Entries in a JKS file have an &#8220;alias&#8221; that must be unique. If you don&#8217;t specify an alias, it will use &#8220;mycert&#8221; by default. This is fine if you&#8217;re only putting one thing in a keystore, but if you add another thing you&#8217;ll get an error because it will try to use the same (default) alias twice. JKS keystores also have a password, just like PKCS12.</p>
<p>You can use keytool to add PEM and PKCS12 files.<br />
Create JKS with cert, key and CA cert from PKCS12:<br />
<code>keytool -importkeystore -destkeystore cert-and-key-with-ca.jks -srckeystore cert-and-key-with-ca.p12 -srcstoretype PKCS12</code><br />
Add a CA cert, then add the cert without a key:<br />
<code>keytool -keystore cacert-added-then-cert-nokey.jks -import -file cacert.pem -alias cacert</code> (Say yes when it asks if you want to trust the CA)<br />
<code>keytool -keystore cacert-added-then-cert-nokey.jks -import -file cert.pem -alias cert</code><br />
Add a CA cert, then add the cert with a key:<br />
<code>keytool -keystore cacert-added-then-cert-withkey.jks -import -file cacert.pem -alias cacert</code> (Say yes when it asks if you want to trust the CA)<br />
<code>keytool -destkeystore cacert-added-then-cert-withkey.jks -importkeystore -srckeystore cert-and-key.p12 -srcstoretype PKCS12</code></p>
<h2>TLS with Java</h2>
<p>There are going to be a lot of certs involved in configuring TLS, so let&#8217;s first decide on some names.</p>
<ul>
<li>server-cert: the cert that the server presents to clients</li>
<li>server-key: the private key that corresponds to server-cert</li>
<li>server-ca-cert: the cert of the CA that signed server-cert</li>
<li>client-cert: the cert that the client presents to the server (if asked to)</li>
<li>client-key: the private key that corresponds to client-cert</li>
<li>client-ca-cert: the cert of the CA that signed client-cert</li>
</ul>
<p>When client certs aren&#8217;t enabled, the server presents server-cert to the client. If the client has server-ca-cert designated as a trusted CA, the connection can proceed. When client certs are enabled, the server presents server-cert as its cert and also sends the DN of client-ca-cert. The client checks server-cert against its trusted CA certs as before. It then looks for any certs that it has that are signed by client-ca-cert, finds client-cert, and sends that back. The server-key and client-key keys are used in other parts of the TLS protocol. To be as general as possible, I&#8217;m going to assume that client-ca-cert and server-ca-cert are not the same cert and are also not in the system-wide set of trusted CAs.</p>
<p> <a href="http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html">Oracle&#8217;s JSSE Reference Guide</a> is useful when figuring out how all these crypto classes fit together, so you may want to have that open as a reference.</p>
<p>If you want to examine the internals of the SSLSocket/SSLServerSocket implementation, set the system property javax.net.debug to &#8220;all&#8221; for maximum verbosity. You can download the OpenJDK code and step through it by looking for where the debug statements are printed. It&#8217;s not as good as a debugger, but there&#8217;s not much code and the debug statements are frequent enough that it&#8217;s not hard to follow. <a href="http://www.wireshark.org/">Wireshark</a> is also extremely useful.</p>
<p>In Java, you use SSLSocketFactory to get SSLSockets and and SSLServerSocketFactory to get SSLServerSocket instances. The simplest usage looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">/* 
 * The static getDefault() methods return the non-SSL
 * factory classes, so they have to be cast.
 */</span>
SSLServerSocketFactory serverSocketFactory <span style="color: #339933;">=</span> 
    <span style="color: #009900;">&#40;</span>SSLServerSocketFactory<span style="color: #009900;">&#41;</span> SSLServerSocketFactory.<span style="color: #006633;">getDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
SSLServerSocket serverSocket <span style="color: #339933;">=</span> 
    <span style="color: #009900;">&#40;</span>SSLServerSocket<span style="color: #009900;">&#41;</span> serverSocketFactory.<span style="color: #006633;">createServerSocket</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">8443</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
SSLSocketFactory socketFactory <span style="color: #339933;">=</span> 
    <span style="color: #009900;">&#40;</span>SSLSocketFactory<span style="color: #009900;">&#41;</span> SSLSocketFactory.<span style="color: #006633;">getDefault</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
SSLSocket socket <span style="color: #339933;">=</span> 
    <span style="color: #009900;">&#40;</span>SSLSocket<span style="color: #009900;">&#41;</span> socketFactory.<span style="color: #006633;">createSocket</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;localhost&quot;</span>, <span style="color: #cc66cc;">8443</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
<span style="color: #666666; font-style: italic;">// do the standard socket stuff with byte streams, etc.</span></pre></div></div>

<p>This isn&#8217;t really going to work, though, since we haven&#8217;t told the server socket what cert to use. Time for more terminology!</p>
<ul>
<li>A <em>keystore</em> has certs and keys in it and defines what is going to be presented to the other end of a connection.</li>
<li>A <em>truststore</em> has just certs in it and defines what certs that the other end will send are to be trusted. You could put keys in a truststore, but they wouldn&#8217;t be used for anything.</li>
</ul>
<p>Confusingly, the Java class java.security.KeyStore is used in the process of creating both keystores and truststores. I will be careful to capitalize as KeyStore when I mean the class as opposed to the conceptual items.</p>
<p>For the server socket, we need to specify a keystore containing server-cert and server-key. We also need a truststore containing client-ca-cert. For the client socket, we need a keystore containing the client cert and key and a truststore containing the server-ca-cert.</p>
<p>To get these keystores and truststores, we need to construct KeyStore instances with the appropriate certificate and key data. KeyStores can be created for JKS or PKCS12 files. This code creates a KeyStore and loads data from an input stream. After load() has been called, the KeyStore is ready for use.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// keyStoreType is either &quot;JKS&quot; or &quot;PKCS12&quot;</span>
<span style="color: #003399;">KeyStore</span> keyStore <span style="color: #339933;">=</span> <span style="color: #003399;">KeyStore</span>.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span>keyStoreType<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
keyStore.<span style="color: #006633;">load</span><span style="color: #009900;">&#40;</span>inputStream, keyStorePassword.<span style="color: #006633;">toCharArray</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>A KeyStore is just an intermediate step, though. Once we have a KeyStore with the keystore data and a KeyStore with the truststore data, the next step is a TrustManager (for a truststore) and a KeyManager (for a keystore).</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">TrustManagerFactory trustManagerFactory <span style="color: #339933;">=</span> 
    TrustManagerFactory.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;PKIX&quot;</span>, <span style="color: #0000ff;">&quot;SunJSSE&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
trustManagerFactory.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>trustStore<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Now we have a TrustManagerFactory instance. JSSE is fairly agnostic towards cryptosystems, so it can, at least in theory, support things beyond X509. In practice, X509 is all we care about, and looking in the OpenJDK source code will give the impression that X509 is all it&#8217;s built to support anyway. The &#8220;PKIX&#8221; algorithm implements cert-chain validation for X509 certs. A TrustManagerFactory can create an array of TrustManagers, one for each type of &#8220;trust material&#8221;. We only care about the X509TrustManager instance.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">X509TrustManager x509TrustManager <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>TrustManager trustManager <span style="color: #339933;">:</span> trustManagerFactory.<span style="color: #006633;">getTrustManagers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>trustManager <span style="color: #000000; font-weight: bold;">instanceof</span> X509TrustManager<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	x509TrustManager <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>X509TrustManager<span style="color: #009900;">&#41;</span> trustManager<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>x509TrustManager <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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NullPointerException</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now we have the X509TrustManager instance we want. A similar approach will get you the X509KeyManager.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">KeyManagerFactory keyManagerFactory <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: #0000ff;">&quot;SunJSSE&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
keyManagerFactory.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span>keyStore, password.<span style="color: #006633;">toCharArray</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
X509KeyManager x509KeyManager <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>KeyManager keyManager <span style="color: #339933;">:</span> keyManagerFactory.<span style="color: #006633;">getKeyManagers</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>keyManager <span style="color: #000000; font-weight: bold;">instanceof</span> X509KeyManager<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	x509KeyManager <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>X509KeyManager<span style="color: #009900;">&#41;</span> keyManager<span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>x509KeyManager <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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NullPointerException</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now you can construct an SSLContext. Here&#8217;s the code to create a SSLServerSocket.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// load in the appropriate keystore and truststore for the server</span>
<span style="color: #666666; font-style: italic;">// get the X509KeyManager and X509TrustManager instances</span>
&nbsp;
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;TLS&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// the final null means use the default secure random source</span>
sslContext.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> KeyManager<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span>keyManager<span style="color: #009900;">&#125;</span>, 
    <span style="color: #000000; font-weight: bold;">new</span> TrustManager<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span>trustManager<span style="color: #009900;">&#125;</span>, <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
SSLServerSocketFactory serverSocketFactory <span style="color: #339933;">=</span> 
    sslContext.<span style="color: #006633;">getServerSocketFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
SSLServerSocket serverSocket <span style="color: #339933;">=</span> 
    <span style="color: #009900;">&#40;</span>SSLServerSocket<span style="color: #009900;">&#41;</span> serverSocketFactory.<span style="color: #006633;">createServerSocket</span><span style="color: #009900;">&#40;</span>PORT<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
serverSocket.<span style="color: #006633;">setNeedClientAuth</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// prevent older protocols from being used, especially SSL2 which is insecure</span>
serverSocket.<span style="color: #006633;">setEnabledProtocols</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span><span style="color: #0000ff;">&quot;TLSv1&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// you can now call accept() on the server socket, etc</span></pre></div></div>

<p>And here&#8217;s how to construct an SSLSocket. Make sure you don&#8217;t use the same keystore and truststore that you did for the server! They almost certainly need to be different.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// load in the appropriate keystore and truststore for the client</span>
<span style="color: #666666; font-style: italic;">// get the X509KeyManager and X509TrustManager instances</span>
&nbsp;
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;TLS&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
sslContext.<span style="color: #006633;">init</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> KeyManager<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span>keyManager<span style="color: #009900;">&#125;</span>, 
    <span style="color: #000000; font-weight: bold;">new</span> TrustManager<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span>trustManager<span style="color: #009900;">&#125;</span>, <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
SSLSocketFactory socketFactory <span style="color: #339933;">=</span> sslContext.<span style="color: #006633;">getSocketFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
SSLSocket socket <span style="color: #339933;">=</span> 
    <span style="color: #009900;">&#40;</span>SSLSocket<span style="color: #009900;">&#41;</span> socketFactory.<span style="color: #006633;">createSocket</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;localhost&quot;</span>, SslServer.<span style="color: #006633;">PORT</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
socket.<span style="color: #006633;">setEnabledProtocols</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#123;</span><span style="color: #0000ff;">&quot;TLSv1&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// read from the socket, etc</span></pre></div></div>

<p>It <em>should</em> now work. Unfortunately, Java&#8217;s default KeyStore implementation has some bugs, so depending on how you set up your server-side trust store, it may or may not work.</p>
<h2>But it doesn&#8217;t work when I try that!</h2>
<p>There&#8217;s a bug in the way cert chains are handled for X509TrustManager objects in the Sun/Oracle implementation. A quick look in the OpenJDK code in sun.security.ssl.X509TrustManagerImpl and sun.security.validator.KeyStores shows that the logic used to get issuers is simply wrong. In the case where the KeyStore entry in a KeyStore is a key entry (not a bare cert), it unconditionally uses the first cert in the chain of certs for that key, regardless of whether or not it is even a CA cert or the actual issuing cert in the chain. In fact, the documentation for KeyStore.getCertificateChain() says that the root cert is the <em>last</em> cert in the chain, not the first. This code was probably tested using self-signed certs (which only have one cert in the chain, so it will always work) and not using separate CA certs.</p>
<p>There&#8217;s also a separate bug in the way PKCS12 files are loaded. It looks like maybe the PKCS12 parsing code can&#8217;t figure out what to do when there isn&#8217;t a private key. I haven&#8217;t looked into the source of that bug yet. The SunJSSE description in the JSSE Reference Guide has this terse note: &#8220;Storing trusted anchors in PKCS12 is not supported. Users should store trust anchors in JKS format and save private keys in PKCS12 format.&#8221; It&#8217;s unfortunate that this isn&#8217;t broadcast more clearly in the documentation.</p>
<p>If you load a PKCS12 file containing just client-ca-cert, you get <em>nothing</em> in the server&#8217;s X509TrustManager KeyStore. This is the PKCS12 loading bug. When you connect a client, you get <code>java.net.SocketException: Broken pipe</code> on the client side and <code>javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found</code> on the server. This happens because the server has sent a CertificateRequest in the ServerHello, but has not included any DNs for the client to look up certs by. </p>
<p>Construct a PKCS12 file containing client-cert, client-key, and client-ca-cert and then import that in one step (using the -importkeystore option to keytool). If you load that PKCS12 file or the resulting JKS, you get a chain of client-cert and client-ca-cert in the KeyStore. This is correct. However, X509TrustManager.getIssuers() mistakenly returns client-cert as an issuer (which it is not) and does not return client-ca-cert. The correct behavior would be to return only client-ca-cert. (An &#8220;issuer&#8221; is a CA.) In this case, you get <code>javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate</code> on the client and <code>javax.net.ssl.SSLHandshakeException: null cert chain</code> on the server. The server sends the DN of client-cert in the CertificateRequest part of the ServerHello. The client (correctly) does not find any certs signed by that cert, so it returns no certificates. The server rejects the connection with error code 42 for &#8220;bad certificate&#8221; (see the TLS RFC section A.3 for error codes) and dies with its own error that (accurately) says there is a null certificate chain from the client.</p>
<p>If you load a JKS file that was created by separately adding client-ca-cert in step 1 (using -import -file client-ca-cert.pem) and then the client-cert (with -import -file client-cert.pem or -importkeystore with a p12 containing client-cert and client-pem) in step 2, the JKS will have two separate entries instead of one entry containing a chain of certs. This will lead to getIssuers() returning both client-cert and client-ca-cert, so both certs will have their DNs in the ServerHello. This is technically incorrect (client-cert is not a CA cert) but does work.</p>
<h2>The good news</h2>
<p>Fortunately, the JKS implementation of KeyStore is not suffering from the same bug as the PKCS12 code.  A KeyStore loaded from a JKS containing <em>only</em> client-ca-cert does end up with a cert in it. Since it&#8217;s just a cert, not a cert in a chain attached to a key, it avoids the buggy code path in KeyStores, so the correct DN gets sent to the client in the ServerHello and all proceeds normally.</p>
<table>
<tr>
<th>Key contents</th>
<th>Key type</th>
<th>Result of getIssuers()</th>
</tr>
<tr>
<td>client-cert, client-key, client-ca-cert</td>
<td>PKCS12</td>
<td>client-cert</td>
</tr>
<tr>
<td>client-cert, client-key, client-ca-cert</td>
<td>JKS</td>
<td>client-cert</td>
</tr>
<tr>
<td>client-cert, client-key</td>
<td>PKCS12</td>
<td>client-cert</td>
</tr>
<tr>
<td>client-cert, client-key</td>
<td>JKS</td>
<td>client-cert</td>
</tr>
<tr>
<td>client-cert, client-ca-cert</td>
<td>PKCS12</td>
<td>(empty)</td>
</tr>
<tr>
<td>client-ca-cert</td>
<td>PKCS12</td>
<td>(empty)</td>
</tr>
<tr>
<td>client-ca-cert added first, then client-cert &amp; client-key</td>
<td>JKS</td>
<td>client-cert <em>and</em> client-ca-cert</td>
</tr>
<td>client-ca-cert added first, then client-cert</td>
<td>JKS</td>
<td>client-cert <em>and</em> client-ca-cert</td>
</tr>
<tr>
<td>client-ca-cert</td>
<td>JKS</td>
<td>client-ca-cert <strong>(what you want)</strong></td>
</tr>
</table>
<p>The result of all this analysis:<br />
<strong>For your SSLServerSocket&#8217;s TrustManager&#8217;s KeyStore, use a JKS containing only the CA cert for the client certs.</strong> If you us a PKCS12, you&#8217;ll get <strong>no</strong> certs. If you include the cert and key that you&#8217;re looking for as well as the CA cert and you create the JKS keystore from one PKCS12 containing all three entities, you&#8217;ll get the <strong>wrong</strong> cert. If you create a JKS keystore using the CA cert and then add the client cert (with or without key) later, you&#8217;ll get <strong>too many</strong> certs.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2011/10/18/java-2-way-tlsssl-client-certificates-and-pkcs12-vs-jks-keystores/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Embedded MySQL in Java with Connector/MXJ and 64-bit Linux</title>
		<link>http://blog.teamlazerbeez.com/2011/10/03/embedded-mysql-on-java-with-connectormxj-and-64-bit-linux/</link>
		<comments>http://blog.teamlazerbeez.com/2011/10/03/embedded-mysql-on-java-with-connectormxj-and-64-bit-linux/#comments</comments>
		<pubDate>Mon, 03 Oct 2011 20:10:20 +0000</pubDate>
		<dc:creator>Marshall Pierce</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://blog.teamlazerbeez.com/?p=2757</guid>
		<description><![CDATA[MySQL&#8217;s Connector/MXJ is a tool that exposes the ability to start and stop an embedded MySQL server through a Java API. You can have the MySQL JDBC driver start up a server just by appropriately configuring your JDBC url or you can programmatically control the server through the MysqldResource class. It does this by bundling [...]]]></description>
			<content:encoded><![CDATA[<p>MySQL&#8217;s <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-mxj.html">Connector/MXJ</a> is a tool that exposes the ability to start and stop an embedded MySQL server through a Java API. You can have the MySQL JDBC driver start up a server just by <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-mxj-configuration-driver-launched.html">appropriately configuring your JDBC url</a> or you can <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-mxj-configuration-java-object.html">programmatically control the server through the MysqldResource class</a>. It does this by bundling precompiled versions of the mysql (client) and mysqld (server) binaries and invoking the correct ones based on the <code>os.name</code> and <code>os.arch</code> system properties.</p>
<p>This sounds great for spinning up an instance of mysqld for testing, but there are a few issues to be solved. MySQL hasn&#8217;t published any recent versions of MXJ to the central Maven repository, so you&#8217;ll have to install the files by hand into your local ~/.m2 (or repo server, if you have one set up). Also, they don&#8217;t include 64-bit Linux binaries.<br />
<strong>Update: I have submitted artifacts for Connector/MXJ 5.0.12 to Maven Central and they have been approved, so you need only add the following dependency to your code and you&#8217;re good to go.</strong></p>
<pre>
&lt;dependency&gt;
  &lt;groupId&gt;mysql&lt;/groupId&gt;
  &lt;artifactId&gt;mysql-connector-mxj&lt;/artifactId&gt;
  &lt;version&gt;5.0.12&lt;/version&gt;
  &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>If you&#8217;d like to build the artifacts yourself, carry on with the instructions&#8230;</p>
<p>Download the zip distribution yourself from <a href="http://dev.mysql.com/downloads/connector/mxj/">MySQL&#8217;s download page</a> (5.0.12 is current as of this article). When unzipped, you&#8217;ll find two jars: mysql-connector-mxj-gpl-5-0-12-db-files.jar (the &#8216;db-files&#8217; jar) and mysql-connector-mxj-gpl-5-0-12.jar (the &#8216;mxj&#8217; jar). The mxj jar is quite small and just contains some Java classes. The db-files jar is pretty hefty because it contains the actual binaries for x86 32-bit FreeBSD, Linux, Mac OS X, Windows and Solaris (as well as Solaris on SPARC in case anyone still uses that&#8230;).</p>
<p>Alas, no 64-bit Linux&#8230; If this doesn&#8217;t affect you, <a href="#maven-install">skip to the end of the article</a> to see how to install the jars correctly into your local ~/.m2 repo. You&#8217;ll know that you&#8217;re hitting this problem if you get output like this:</p>
<pre>[MysqldResource] launching mysqld (driver_launched_mysqld_1)
/tmp/test-mxj/bin/mysqld: error while loading shared libraries: libaio.so.1: cannot open shared object file: No such file or directory</pre>
<p>This is (correctly) saying is that the 32-bit mysqld binary cannot find libaio. You should have libaio installed since the 64-bit version we&#8217;ll be building will need it, though!</p>
<h2>Adding 64-bit Linux binaries to the db-files jar</h2>
<p>Fortunately, MySQL provides <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-mxj-usagenotes-packaging.html">instructions on how to modify the db-files jar</a>. If you&#8217;d rather use my pre-built jar with Linux 64-bit binaries, <a href="#maven-install">go to the end of the article</a>. Download the mysql 5.5.9 source tarball from <a href="http://downloads.mysql.com/archives.php">the MySQL archives</a>. 5.5.9 isn&#8217;t the latest version, but all the other binaries in MXJ 5.0.12 were built with 5.5.9 so we&#8217;ll use that to stay consistent. The <a href="http://dev.mysql.com/doc/refman/5.5/en/installing-source-distribution.html">source installation manual</a> shows the steps necessary to perform a complete installation. We don&#8217;t need to do all of that since we just need the compiled code.</p>
<pre>cmake .
make</pre>
<p>The <code>mysql</code> binary is in <code>client/mysql</code> and the <code>mysqld</code> binary is in <code>sql/mysqld</code>.</p>
<p>Extract mysql-connector-mxj-gpl-5-0-12-db-files.jar into a directory of your choosing so we can add in proper 64-bit versions of mysql and mysqld.</p>
<p>The actual binaries that are run is determined by the platform-map.properties file in the root of db-files jar. Replace the following section</p>
<pre>Linux-x86_64=Linux-i386
Linux-amd64=Linux-i386</pre>
<p>with</p>
<pre>Linux-x86_64=Linux-x86_64
Linux-amd64=Linux-x86_64</pre>
<p>This means that when x86_64 or amd64 are seen in the <code>os.arch</code> Java system property, the contents of the Linux-x86_64 directory will be used. First, we&#8217;ll need the directory to exist inside the 5-5-9 directory:</p>
<pre>mkdir 5-5-9/Linux-x86_64</pre>
<p>Copy your newly compiled mysql and mysqld binaries into the Linux-x86_64 directory, and add a version.txt file containing appropriate contents. I followed the template of the Linux-i386 version, modifying for my newer kernel (3.0.4) and platform (x86_64).</p>
<pre>mysql-5.5.9-linux3.0.4-x86_64/bin/mysqld</pre>
<p>Go back to the root of the extracted jar, then create a new jar.</p>
<pre>jar -cf ../mysql-connector-mxj-gpl-5-0-12-db-files.jar *</pre>
<h2 id="maven-install">Installing the Maven artifacts</h2>
<p>Now we&#8217;ve constructed a mysql-connector-mxj-gpl-5-0-12-db-files.jar. To use it, you&#8217;ll need to install it into your ~/.m2 repo. I&#8217;ve built a <a href="http://blog.teamlazerbeez.com/uploads/mysql-connector-mxj-gpl-5-0-12-db-files.pom">very simple pom.xml</a> for it to save you the trouble. Download the pom and put it in the same directory as your newly built jar. Or, if you&#8217;d rather not go to the trouble of building your own db-files jar, <a href="http://blog.teamlazerbeez.com/uploads/mysql-connector-mxj-gpl-5-0-12-db-files.jar">download mine</a>.</p>
<pre>mvn install:install-file -Dfile=mysql-connector-mxj-gpl-5-0-12-db-files.jar -DpomFile=mysql-connector-mxj-gpl-5-0-12-db-files.pom</pre>
<p>You still need the mxj jar, though, so I built <a href="http://blog.teamlazerbeez.com/uploads/mysql-connector-mxj-gpl-5-0-12.pom">a pom for that jar as well</a>.</p>
<pre>mvn install:install-file -Dfile=mysql-connector-mxj-gpl-5-0-12.jar -DpomFile=mysql-connector-mxj-gpl-5-0-12.pom</pre>
<p>MXJ will re-use a deployment of mysql that it has made previously, so make sure to remove any temporary directories left over by mysql. Otherwise, you&#8217;ll keep on using the old (broken) mysqld binaries. This will clear both the default mxj directory and the one used by ConnectorMXJUrlTestExample, in case you ran that previously. Make sure to add also include any directories you&#8217;ve configured yourself (e.g. by setting server.basedir in the JDBC url).</p>
<pre>rm -rf /tmp/mysql-c.mxj
rm -rf /tmp/test-mxj</pre>
<p>MXJ should now be ready to use. To depend on it from a Maven project, this is the dependency you need (you probably don&#8217;t want to use MXJ for production deployments, so it&#8217;s set to test scope). If you&#8217;re using Maven 3, you will also need to put the artifacts in your repo server since Maven 3 complains if it can only find artifacts in the local ~/.m2 repo.</p>
<pre>
&lt;dependency&gt;
  &lt;groupId&gt;mysql&lt;/groupId&gt;
  &lt;artifactId&gt;mysql-connector-mxj&lt;/artifactId&gt;
  &lt;version&gt;5.0.12&lt;/version&gt;
  &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2011/10/03/embedded-mysql-on-java-with-connectormxj-and-64-bit-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A simple Java web stack with Guice, Jetty, Jersey and Jackson</title>
		<link>http://blog.teamlazerbeez.com/2011/08/15/a-simple-java-web-stack-with-guice-jetty-jersey-and-jackson/</link>
		<comments>http://blog.teamlazerbeez.com/2011/08/15/a-simple-java-web-stack-with-guice-jetty-jersey-and-jackson/#comments</comments>
		<pubDate>Mon, 15 Aug 2011 22:05:22 +0000</pubDate>
		<dc:creator>Marshall Pierce</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[jackson]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jax-rs]]></category>
		<category><![CDATA[jersey]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://blog.teamlazerbeez.com/?p=2747</guid>
		<description><![CDATA[Another Java web framework? Not really&#8230; There are dozens of web technologies for Java (Struts, Stripes, Tapestry, Wicket, GWT, Spring MVC, Vaadin, Play, plain old servlets and JSP, Dropwizard, etc.) and they all have their advantages and disadvantages. This article isn&#8217;t about comparing frameworks. Instead, I&#8217;ll describe how to serve HTTP requests from Java without [...]]]></description>
			<content:encoded><![CDATA[<h3>Another Java web framework? Not really&#8230;</h3>
<p>There are dozens of web technologies for Java (<a href="http://struts.apache.org/">Struts</a>, <a href="http://www.stripesframework.org/display/stripes/Home">Stripes</a>, <a href="http://tapestry.apache.org/">Tapestry</a>, <a href="http://wicket.apache.org/">Wicket</a>, <a href="http://code.google.com/webtoolkit/">GWT</a>, <a href="http://www.springsource.org/">Spring MVC</a>, <a href="http://vaadin.com/home">Vaadin</a>, <a href="http://www.playframework.org/">Play</a>, <a href="http://download.oracle.com/javaee/6/tutorial/doc/">plain old servlets and JSP</a>, <a href="http://dropwizard.codahale.com/">Dropwizard</a>, etc.) and they all have their advantages and disadvantages. This article isn&#8217;t about comparing frameworks. Instead, I&#8217;ll describe how to serve HTTP requests from Java without using a monolithic framework in a way that&#8217;s a lot more pleasant than using just HttpServletRequests: <a href="http://www.eclipse.org/jetty/">Jetty</a> for handling low-level HTTP things, <a href="http://jersey.java.net/">Jersey</a> for request routing, <a href="http://jackson.codehaus.org/">Jackson</a> for serialization and <a href="http://code.google.com/p/google-guice/">Guice</a> to tie it all together. </p>
<p><strong>Update</strong>: If you actually want to write something quickly using stuff shown in this article, <a href="http://dropwizard.codahale.com/">Dropwizard</a> has since come out, and looks like a solid choice. If you want to learn more about how to build such a stack, check out the <a href="http://blog.teamlazerbeez.com/2012/03/31/extending-the-simple-javajettyguicejerseyjackson-web-stack-with-automatic-jersey-resource-method-metrics/">second article in this series</a>.</p>
<p>If you want to write your web UI on the server side (whether it&#8217;s translated to JavaScript ala GWT or simply HTML markup like you might put in a JSP), this probably isn&#8217;t an approach that will be very attractive. You won&#8217;t have a web framework already there to provide pre-canned view helpers or login forms or &#8220;is this a phone number&#8221; validation or any of that.</p>
<p>If you are transitioning towards making the server be more of a data store and putting display logic entirely in the client (regardless of whether the client is a browser or a native mobile app), the no-big-framework approach can make a lot of sense. You don&#8217;t need portlets or JavaScript components when you&#8217;re simply shoving JSON or XML or what-have-you over HTTP.</p>
<p>I&#8217;ll be including code samples as new concepts are introduced, but if you want to browse the finished example project, it&#8217;s <a href="https://github.com/teamlazerbeez/simple-web-stack">on the Team Lazer Beez GitHub site</a>.</p>
<h3>Jetty</h3>
<p>Jetty is a HTTP server and servlet container that&#8217;s been designed expressly for easy embedding. I think it&#8217;s easier to do the edit-restart-test cycle with a simple main method that starts a Jetty server (no IDE I&#8217;ve used has ever had integration with a servlet container that works as fast or as reliably as running a main method). If you prefer to run and debug inside a separate container, or if you need container-managed security or JTA or XA or any of that stuff, feel free bundle your code as a war instead of using Jetty.</p>
<p>Here&#8217;s how you start a Jetty server listening on localhost:8080.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Server server <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Server<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">8080</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// handlers go here</span>
server.<span style="color: #006633;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Pretty easy! But, this server doesn&#8217;t do anything since we haven&#8217;t told it what to do for incoming requests. So, before we call <code>start()</code>, we need to give the server a Handler. Handlers are a Jetty concept that can do pretty much anything in response to a HTTP request. You might have a Handler that only gathers performance metrics or only does logging. In this case, we want a Handler that can invoke servlets.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">ServletContextHandler handler <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ServletContextHandler<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
handler.<span style="color: #006633;">setContextPath</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// set up handler</span>
server.<span style="color: #006633;">setHandler</span><span style="color: #009900;">&#40;</span>handler<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>One odd thing about Jetty&#8217;s ServletContextHandler is that it likes to have one servlet always, even though in our case we won&#8217;t actually end up needing any to run our business logic. So, we&#8217;ll give the handler a servlet:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// jetty always needs one servlet</span>
handler.<span style="color: #006633;">addServlet</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> ServletHolder<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> InvalidRequestServlet<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>, <span style="color: #0000ff;">&quot;/*&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>InvalidRequestServlet is a simple HttpServlet that always 404s.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> service<span style="color: #009900;">&#40;</span>HttpServletRequest req, HttpServletResponse resp<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> ServletException, <span style="color: #003399;">IOException</span> <span style="color: #009900;">&#123;</span>
    resp.<span style="color: #006633;">setStatus</span><span style="color: #009900;">&#40;</span>HttpServletResponse.<span style="color: #006633;">SC_NOT_FOUND</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    resp.<span style="color: #006633;">setContentType</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;text/plain&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    resp.<span style="color: #006633;">setContentType</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;UTF-8&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    resp.<span style="color: #006633;">getWriter</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;404&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>If you create a main method with the code to start up Jetty and run it, you should now be able to go to <a href="http://localhost:8080">http://localhost:8080</a> in your browser and see the result of your InvalidRequestServlet. Before we can start adding some actual logic, though, I&#8217;ll need to explain Guice and its servlet layer. </p>
<h3>Guice</h3>
<p>Guice is a dependency injection framework. Though it accomplishes more or less the same job that Spring does, it has a slightly different philosophy. Whereas Spring tends to think in terms of bean ids when gluing code together, Guice tends to think in terms of types. They&#8217;re both good tools with different strengths, but I am only going to show how to use Guice (or this article will never end!). I&#8217;ll give a whirlwind tutorial in Guice and Guice Servlet and then we&#8217;ll get back to building our stack.</p>
<h4>Making some PB&#038;J Sandwiches</h4>
<p>One of the problems (but not the only one) that DI/IoC frameworks like Guice and Spring are trying to solve is the problem of passing an instance through many layers of constructors just because some deep-down class is structured to take an instance of some interface. No doubt you&#8217;ve seen this anti-pattern: Class1 instantiates Class2 which instantiates Class3, but Class3 takes a Foo instance  in its constructor, so somewhere higher up (perhaps in Class1, or even higher up than that) you create the correct Foo instance and then it gets passed around for a while until it&#8217;s finally used in Class3. This sucks, but it&#8217;s a worthy goal to have Class3 take a Foo instance in its constructor rather than directly instantiating some concrete implementation: this benefits testability, separation of concerns, etc. Guice can help make this easier.</p>
<p>As an example, let&#8217;s suppose that you have a SandwichMaker class that takes a PeanutButter implementation in its constructor.  For testing your SandwichMaker, you may wish to use a mock PeanutButter implementation, but in an actual deployment you might wish to use an OrganicCrunchyValenciaPeanutButter (OCVPB for short).</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> SandwichMaker <span style="color: #009900;">&#123;</span>
<span style="color: #666666; font-style: italic;">// ...</span>
    SandwichMaker<span style="color: #009900;">&#40;</span>PeanutButter peanutButter<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;">peanutButter</span> <span style="color: #339933;">=</span> peanutButter<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">interface</span> PeanutButter <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">void</span> applyToSandwich<span style="color: #009900;">&#40;</span>Sandwich sandwich, <span style="color: #000066; font-weight: bold;">int</span> grams<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now the question is where in your actual app do you instantiate your OCVPB? It&#8217;s not ideal to do it in the class that creates a SandwichMaker since that class will now be using actual peanut butter when it&#8217;s run during tests as it&#8217;s hardcoded the concrete implementation. It&#8217;s also not ideal to create the OCVPB in the top-level main method and pass the instance around through however many levels of constructors are needed to get to the SandwichMaker. To explain how we can use Guice to solve this problem, there are a few concepts to explain.</p>
<h4>Guice concepts</h4>
<p>Rather than explicitly creating instances with the <code>new</code> keyword, Guice lets you define how classes depend on each other and takes care of wiring things together for you. In our case, we want our SandwichMaker to have a PeanutButter implementation provided to it. We inform Guice of this by annotating the ctor with @Inject. (There are versions of Inject and some other classes from both com.google.inject and from the standardized JSR 330 javax.inject packages. They work almost exactly the same; check the <a href="http://code.google.com/p/google-guice/wiki/JSR330">Guice documentation</a> for details. Just pick one and stick with it.)</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> SandwichMaker <span style="color: #009900;">&#123;</span>
<span style="color: #666666; font-style: italic;">// ...</span>
    @Inject
    SandwichMaker<span style="color: #009900;">&#40;</span>PeanutButter peanutButter<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;">peanutButter</span> <span style="color: #339933;">=</span> peanutButter<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now that we&#8217;ve said that SandwichMaker needs a PeanutButter, we need to say which PeanutButter to use. We do this with a binding in a module. Modules are intended to represent functional boundaries in your application. The decision of when to put things in separate modules is like learning when to put things in separate packages: you&#8217;ll simply need to get a feel for it by trying it out. For now, let&#8217;s create a module that sets up everything you need to make sandwiches.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> SandwichModule <span style="color: #000000; font-weight: bold;">extends</span> AbstractModule <span style="color: #009900;">&#123;</span>
    @Override
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> configure<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        bind<span style="color: #009900;">&#40;</span>PeanutButter.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">to</span><span style="color: #009900;">&#40;</span>OrganicCrunchyValenciaPeanutButter.<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>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This informs Guice to create a new instance of OCVPB whenever it sees a request to inject a PeanutButter instance. PeanutButter seems like the sort of thing that should be a singleton since it represents a real-life resource, though, so let&#8217;s go ahead and fix that:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">bind<span style="color: #009900;">&#40;</span>PeanutButter.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">to</span><span style="color: #009900;">&#40;</span>OrganicCrunchyValenciaPeanutButter.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">in</span><span style="color: #009900;">&#40;</span>Scopes.<span style="color: #006633;">SINGLETON</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>We could also have annotated our OCVPB implementation class with @Singleton to achieve the same effect. Now, no matter how many SandwichMakers we get, only one PeanutButter will be used.</p>
<p>We create an Injector with all of the modules necessary (in this case, just the one module) and use it to get an instance of SandwichMaker. It will inspect the bindings and injection targets and create a OCVPB and pass it to the SandwichMaker ctor. We don&#8217;t actually need to get a standalone SandwichMaker instance, but if we did, this is how we would do it.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Injector injector <span style="color: #339933;">=</span> Guice.<span style="color: #006633;">createInjector</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> SandwichModule<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
SandwichMaker maker <span style="color: #339933;">=</span> injector.<span style="color: #006633;">createInstance</span><span style="color: #009900;">&#40;</span>SandwichMaker.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// use the maker</span></pre></div></div>

<p>This is just the very most basic usage of Guice. Check out their <a href="http://code.google.com/p/google-guice/wiki/Motivation">documentation</a> for more details.</p>
<h4>Guice Servlet</h4>
<p>Now that we know how to bind instances (whether as singletons or new-one-every-time) and inject them, we can move on to Guice Servlet. This extension to Guice allows us to get rid of web.xml entirely (if embedding Jetty) or make it much simpler (if using a war).</p>
<p>Suppose you have a FooServlet servlet. In the old days of web.xml, there would be servlet tags and servlet-mapping tags to wire it up. Here&#8217;s how it is with Guice Servlet:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> FooServletModule <span style="color: #000000; font-weight: bold;">extends</span> ServletModule <span style="color: #009900;">&#123;</span>
    @Override
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> configureServlets<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        bind<span style="color: #009900;">&#40;</span>FooServlet.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        serve<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/foo&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">with</span><span style="color: #009900;">&#40;</span>FooServlet.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// other servlets</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Since Guice is instantiating your FooServlet class intead of relying on the servlet container to invoke the 0-args ctor, this also means that you can use @Inject on the ctor and get the objects you need that way instead of pulling them out of init params or servlet context.</p>
<p>To feed incoming requests into the servlets you&#8217;ve laid out with Guice Servlet, you need to set up GuiceFilter as a filter for all requests. You can do this in web.xml if you&#8217;re using a war (it&#8217;s the only thing you&#8217;ll actually need in web.xml) or just configure Jetty directly.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Injector injector <span style="color: #339933;">=</span> Guice.<span style="color: #006633;">createInjector</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> SandwichModule<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, <span style="color: #000000; font-weight: bold;">new</span> AbstractModule<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    @Override
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> configure<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        binder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">requireExplicitBindings</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        bind<span style="color: #009900;">&#40;</span>GuiceFilter.<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>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
FilterHolder guiceFilter <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> FilterHolder<span style="color: #009900;">&#40;</span>injector.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span>GuiceFilter.<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>
handler.<span style="color: #006633;">addFilter</span><span style="color: #009900;">&#40;</span>guiceFilter, <span style="color: #0000ff;">&quot;/*&quot;</span>, EnumSet.<span style="color: #006633;">allOf</span><span style="color: #009900;">&#40;</span>DispatcherType.<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></pre></div></div>

<p>Now, you can stop here and bind your servlets in a ServletModule and get the benefits of being able to initialize your servlets with Guice, but it gets even easier with Jersey.</p>
<h3>Jersey and Jackson</h3>
<p>Jersey is the reference implementation of JAX-RS. It lets you do things like POST the url &#8220;http://localhost:8080/foo?bar=baz&#038;quux=1234&#8243; and handle the request with this class:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Path<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/foo&quot;</span><span style="color: #009900;">&#41;</span>
@Produces<span style="color: #009900;">&#40;</span>MediaType.<span style="color: #006633;">APPLICATION_JSON</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">class</span> FooResource <span style="color: #009900;">&#123;</span>
    @POST
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> handleFooPost<span style="color: #009900;">&#40;</span>@QueryParam<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bar&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #003399;">String</span> bar, @QueryParam<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;quux&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">int</span> quux<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
       <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;{<span style="color: #000099; font-weight: bold;">\&quot;</span>yay<span style="color: #000099; font-weight: bold;">\&quot;</span>:<span style="color: #000099; font-weight: bold;">\&quot;</span>hooray<span style="color: #000099; font-weight: bold;">\&quot;</span>}&quot;</span><span style="color: #339933;">;</span> 
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The class, method and parameter names are not magic; only the annotations are what ties this code to handling that request. Jersey will set the status code, content length, etc. appropriately. It can also do void methods (returns status 204 for you), streaming responses, and entirely custom responses (pick the status code, the entity, etc), so check the documentation for the details.</p>
<p>If you use Jersey to handle actually calling your business logic instead of writing plain old servlets directly, you only need to have one servlet binding in your Guice Servlet module:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SandwichServletModule <span style="color: #000000; font-weight: bold;">extends</span> ServletModule <span style="color: #009900;">&#123;</span>
    @Override
    <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> configureServlets<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// bind resource classes here</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// hook Jersey into Guice Servlet</span>
        bind<span style="color: #009900;">&#40;</span>GuiceContainer.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// hook Jackson into Jersey as the POJO &lt;-&gt; JSON mapper</span>
        bind<span style="color: #009900;">&#40;</span>JacksonJsonProvider.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">in</span><span style="color: #009900;">&#40;</span>Scopes.<span style="color: #006633;">SINGLETON</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        serve<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/*&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">with</span><span style="color: #009900;">&#40;</span>GuiceContainer.<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>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>GuiceContainer is a class that ships with Jackson. When you use GuiceContainer, all you need to do is bind the resource classes (like FooResource above) with Guice. The JacksonJsonProvider binding to make it easier to return objects as JSON; you&#8217;ll see what it does a bit later. To go back to our sandwich example, let&#8217;s suppose we have two resources: one to make sandwiches and one to say how many sandwiches have been made.</p>
<p>Let&#8217;s start with the stats one (at /sandwich/stats) since it is simpler (doesn&#8217;t need to modify state). Supposing I have a SandwichStats class that can provide StatSnapshot objects that represent the total amount of jam, peanut butter and sandwiches, the resource is very simple:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Singleton
@Produces<span style="color: #009900;">&#40;</span>MediaType.<span style="color: #006633;">APPLICATION_JSON</span><span style="color: #009900;">&#41;</span>
@Path<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/sandwich/stats&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SandwichStatsResource <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> SandwichStats sandwichStats<span style="color: #339933;">;</span>
&nbsp;
    @Inject
    SandwichStatsResource<span style="color: #009900;">&#40;</span>SandwichStats sandwichStats<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;">sandwichStats</span> <span style="color: #339933;">=</span> sandwichStats<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @GET
    <span style="color: #000000; font-weight: bold;">public</span> SandwichStats.<span style="color: #006633;">StatsSnapshot</span> getStats<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> sandwichStats.<span style="color: #006633;">getStats</span><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;">&#125;</span></pre></div></div>

<p>You&#8217;ll also need to bind the resource class so that GuiceContainer can find it. When you have a lot of resources, you might want to put their bindings in a module just for that purpose, but for now just add a binding in SandwichServletModule:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">bind<span style="color: #009900;">&#40;</span>SandwichStats.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The resource requests a SandwichStats object in its ctor so that it can ask it for the latest info every time a request is made. The SandwichStats object should also be a singleton since we want it to live as long as the app is up. (Guice is easy to use for non-singletons too &#8212; it just happens that in this contrived example I seem to be ending up with lots of singletons.)</p>
<p>Note that the @GET method returns an object, not a string. This is where the <code>ImmutableMap.of(JSONConfiguration.FEATURE_POJO_MAPPING, "true")</code> comes in. It tells Jersey to attempt to map the POJO returned from the method to JSON. To do this, we use the Jackson JSON library.</p>
<p>Jackson is a fast JSON serialization/deserialization library, and one of its features is easy annotation-based configuration for POJO mapping. It&#8217;s probably easiest to just show what it looks like in practice:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> StatsSnapshot <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// ...</span>
    @JsonProperty
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> getSandwichesMade<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> sandwichesMade<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @JsonProperty
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> getGramsOfJam<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> gramsOfJam<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @JsonProperty
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> getGramsOfPeanutButter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> gramsOfPeanutButter<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>When serialized by Jackson, an object of that class will end up as a JSON object with three keys (&#8220;gramsOfJam&#8221;, &#8220;gramsOfPeanutButter&#8221; and &#8220;sandwichesMade&#8221;). Since Jersey has been configured to automatically use Jackson to serialize objects, you can go to /sandwich/stats in your browser and get something like this: <code>{"gramsOfJam":150,"gramsOfPeanutButter":200,"sandwichesMade":1}</code></p>
<p>Now let&#8217;s add a resource that lets you make sandwiches. Normally I wouldn&#8217;t have something that modifies state be a GET but I want this to be easy to test in a browser, so let&#8217;s say that a GET to http://localhost:8080/sandwich/create will make a sandwich (with optional jam and peanutButter query parameters to specify how many grams of jam and peanut butter to use) and that the sandwich created should be returned as JSON. This is what such a resource might look like:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Singleton
@Produces<span style="color: #009900;">&#40;</span>MediaType.<span style="color: #006633;">APPLICATION_JSON</span><span style="color: #009900;">&#41;</span>
@ThreadSafe
@Path<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;/sandwich/create&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SandwichMakerResource <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> SandwichMaker sandwichMaker<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> SandwichStats sandwichStats<span style="color: #339933;">;</span>
&nbsp;
    @Inject
    SandwichMakerResource<span style="color: #009900;">&#40;</span>SandwichMaker sandwichMaker, SandwichStats sandwichStats<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;">sandwichMaker</span> <span style="color: #339933;">=</span> sandwichMaker<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">sandwichStats</span> <span style="color: #339933;">=</span> sandwichStats<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @GET
    <span style="color: #000000; font-weight: bold;">public</span> Sandwich makeSandwich<span style="color: #009900;">&#40;</span>@QueryParam<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;jam&quot;</span><span style="color: #009900;">&#41;</span> @DefaultValue<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;100&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">int</span> gramsOfJam,
                                 @QueryParam<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;peanutButter&quot;</span><span style="color: #009900;">&#41;</span> @DefaultValue<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;200&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">int</span> gramsOfPeanutButter<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Sandwich sandwich <span style="color: #339933;">=</span> sandwichMaker.<span style="color: #006633;">makeSandwich</span><span style="color: #009900;">&#40;</span>gramsOfPeanutButter, gramsOfJam<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        sandwichStats.<span style="color: #006633;">recordSandwich</span><span style="color: #009900;">&#40;</span>sandwich<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> sandwich<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The resource (yet another singleton) gets SandwichMaker and SandwichStats instances injected, and whenever it makes a sandwich it updates the SandwichStats object. Try accessing it via your browser a few times and check the stats page to see that the counts do update correctly.</p>
<p>I&#8217;ve only scratched the surface of what these libraries can do with this simple example. Let me know if you think there&#8217;s some cool feature I missed (as long as it won&#8217;t complicate things too much to work it in).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2011/08/15/a-simple-java-web-stack-with-guice-jetty-jersey-and-jackson/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>A new Java Salesforce API Library</title>
		<link>http://blog.teamlazerbeez.com/2011/03/03/a-new-java-salesforce-api-library/</link>
		<comments>http://blog.teamlazerbeez.com/2011/03/03/a-new-java-salesforce-api-library/#comments</comments>
		<pubDate>Thu, 03 Mar 2011 08:19:57 +0000</pubDate>
		<dc:creator>Marshall Pierce</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[salesforce]]></category>
		<category><![CDATA[salesforce.com]]></category>
		<category><![CDATA[SOAP]]></category>

		<guid isPermaLink="false">http://blog.teamlazerbeez.com/?p=2731</guid>
		<description><![CDATA[I&#8217;ve posted a lot of information about Salesforce over the years (Partner API Gotchas Part 1, Part 2, Part 3, Part 4, JAX-WS Tutorial Part 1, Part 2, Part 3, Part 4). I&#8217;m supplementing that with the release of an open source Java library for using the REST, Partner, Metadata and Apex APIs. You can [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve posted a lot of information about Salesforce over the years (<a href="http://blog.teamlazerbeez.com/2009/05/06/salesforcecom-api-gotchas-1/">Partner API Gotchas Part 1</a>, <a href="http://blog.teamlazerbeez.com/2009/05/17/salesforcecom-api-gotchas-2/">Part 2</a>, <a href="http://blog.teamlazerbeez.com/2009/08/10/salesforcecom-soap-api-gotchas-part-3/">Part 3</a>, <a href="http://blog.teamlazerbeez.com/2010/01/25/salesforcecom-soap-api-gotchas-part-4/">Part 4</a>, <a href="http://blog.teamlazerbeez.com/2009/05/23/salesforcecom-partner-soap-api-jax-ws-tutorial-part-1/">JAX-WS Tutorial Part 1</a>, <a href="http://blog.teamlazerbeez.com/2009/07/09/salesforcecom-partner-soap-api-jax-ws-tutorial-part-2/">Part 2</a>, <a href="http://blog.teamlazerbeez.com/2009/07/21/salesforcecom-partner-soap-api-jax-ws-tutorial-part-3/">Part 3</a>, <a href="http://blog.teamlazerbeez.com/2009/07/28/salesforcecom-partner-soap-api-jax-ws-tutorial-part-4/">Part 4</a>). I&#8217;m supplementing that with the release of an open source Java library for using the REST, Partner, Metadata and Apex APIs. You can get the source from the <a href="https://github.com/teamlazerbeez/sf-api-connector">Team Lazer Beez open source project</a>. The code is under active development but it is stable and ready for use. When I do cut a release, I&#8217;ll update this blog post to point to it. </p>
<h2>Features</h2>
<ul>
<li>Easy-to-use wrappers around the APIs. The classes that tools generate for the SOAP APIs are clumsy and unintuitive (and not thread safe), so I&#8217;ve written better versions.</li>
<li>Limits concurrent API calls for Partner, Metadata and Apex connectors. This helps you avoid &#8216;concurrent request limit exceeded&#8217; errors. (The REST API is harder to hit the limit with. I will add it to the request limiting system in the future.)</li>
<li>Transparent handling of INVALID_SESSION_ID for the Partner API. If someone else has closed the session ID you were using, the library will automatically re-login as needed.</li>
<li>Designed to be used with many different organizations simultaneously. If your app needs to talk to the orgs of many different customers all at the same time, it&#8217;s easy to do so. Of course, it&#8217;s also easy to work with just one org if that&#8217;s what you need.</li>
<li>Connections are reconfigurable at any time. You can update the login and password (for SOAP connections) or OAuth token (for REST connections) and the next API call you make will seamlessly use the updated information, even if it&#8217;s in another thread.</li>
<li>Designed with thread-safety in mind. Where practical, classes are thread-safe or immutable.</li>
<li>HTTP communication is gzip-compressed.</li>
<li>Well-tested, robust code.</li>
<li>Business-friendly Apache License (no GPL issues)</li>
</ul>
<h2>Getting started</h2>
<p>First you&#8217;ll need to check out and build the code. </p>
<pre>
% git clone git://github.com/teamlazerbeez/sf-api-connector.git
% cd sf-api-connector
% mvn clean install -DskipTests
</pre>
<p>Maven will probably need to download a bunch of plugins if you&#8217;re not a Maven user yet. Once it&#8217;s done, you&#8217;ll have installed the jars into your local maven repository. The reason tests are skipped is that some of the tests actually use Salesforce&#8217;s real API and are therefore restricted to only come from certain blocks of IP addresses, so those tests will fail unless you happen to be using my ISP. Also, the tests take quite some time to run.</p>
<p>The SOAP-based APIs (Partner, Metadata and Apex) are in the sf-soap-api-connector module and the REST API is in the sf-rest-api-connector module. The dependencies to use for your pom.xml are shown below. You only need to include the dependency for the API that you&#8217;ll be using (that is, you don&#8217;t need both unless you&#8217;re using both). The dependencies are both SNAPSHOT versions because that&#8217;s what&#8217;s declared in the project&#8217;s pom.xml right now.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.teamlazerbeez<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>sf-soap-api-connector<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>trunk-SNAPSHOT<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.teamlazerbeez<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>sf-rest-api-connector<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>trunk-SNAPSHOT<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h2>Using the REST API</h2>
<p>Most people can probably do what they need with the REST API, so I&#8217;ll start with that since it&#8217;s simpler. RestConnectionPool is the starting point for using the REST API. The class has a generic parameter to allow you to use any class you want to identify organizations. You might use the Salesforce organization id (the id that starts with &#8217;00D&#8217;) or perhaps the primary key for a table in your DB that has a row for each organization. Make sure you use an immutable class with a useful hashCode()/equals() implementation since these objects will be used as keys in a Map. In this example I&#8217;ll use Integer.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// in your app setup, create a pool that's shared for the whole app</span>
RestConnectionPool<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span> pool <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> RestConnectionPoolImpl<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Before you can use the pool to get a connection for a specific org, you need to inform the pool about that org.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">pool.<span style="color: #006633;">configureOrg</span><span style="color: #009900;">&#40;</span>orgId, host, oauthToken<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The host is the HTTP endpoint to use. Different orgs may be on different Salesforce clusters, so this is a per-org setting. You can extract the host from the partner server URL (see ConnectionBundle.getBindingConfig() in the SOAP API module or the tip later on in this article) if you don&#8217;t already have it. The OAuth token is something you&#8217;ll get by following the steps outlined in <a href="http://www.salesforce.com/us/developer/docs/api_rest/Content/quickstart_oauth.htm">Salesforce&#8217;s OAuth docs</a>. You can also use a session Id from the SOAP API as the OAuth token.</p>
<p>You can configure a pool with as many orgs as you want. The pool is shared between all of them for efficiency. You can also reconfigure the data for an org in a pool at any time.</p>
<p>Now that the pool is configured, let&#8217;s actually use a connection.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">RestConnection connection <span style="color: #339933;">=</span> pool.<span style="color: #006633;">getRestConnection</span><span style="color: #009900;">&#40;</span>orgId<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
SObject contact <span style="color: #339933;">=</span> connection.<span style="color: #006633;">retrieve</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Contact&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Id<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;0035000000kmAZJ&quot;</span><span style="color: #009900;">&#41;</span>,
    <span style="color: #003399;">Arrays</span>.<span style="color: #006633;">asList</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;FirstName&quot;</span>, <span style="color: #0000ff;">&quot;LastName&quot;</span>, <span style="color: #0000ff;">&quot;Email&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Got a &quot;</span> <span style="color: #339933;">+</span> contact.<span style="color: #006633;">getType</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> 
    <span style="color: #0000ff;">&quot; object with id &quot;</span> <span style="color: #339933;">+</span> contact.<span style="color: #006633;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Map</span>.<span style="color: #006633;">Entry</span><span style="color: #339933;">&lt;</span>String,String<span style="color: #339933;">&gt;</span> entry<span style="color: #339933;">:</span> contact.<span style="color: #006633;">getAllFields</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Field &lt;&quot;</span> <span style="color: #339933;">+</span> entry.<span style="color: #006633;">getKey</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&gt; has value &lt;&quot;</span> <span style="color: #339933;">+</span> 
        entry.<span style="color: #006633;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&gt;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
SObject newLead <span style="color: #339933;">=</span> RestSObjectImpl.<span style="color: #006633;">getNew</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Lead&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
newLead.<span style="color: #006633;">setField</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;LastName&quot;</span>, <span style="color: #0000ff;">&quot;Smith&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
newLead.<span style="color: #006633;">setField</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Company&quot;</span>, <span style="color: #0000ff;">&quot;FooCorp&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
SaveResult result <span style="color: #339933;">=</span> connection.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span>newLead<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>result.<span style="color: #006633;">isSuccess</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Created a lead with id &quot;</span> <span style="color: #339933;">+</span> result.<span style="color: #006633;">getId</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;">else</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Creation failed with errors &quot;</span> <span style="color: #339933;">+</span> result.<span style="color: #006633;">getErrors</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></div></div>

<p>Check the RestConnection interface to see what else you can do with it.</p>
<h2>Using the SOAP APIs</h2>
<p>The SOAP APIs are a little more complicated because there are three different WSDLs that share some common configuration. First you&#8217;ll need to pick a &#8220;partner key&#8221; or &#8220;client id&#8221;. This is a fairly arbitrary identifier that will be used to identify what application made an individual API call. Choose something at least mildly human-readable.</p>
<p>As with RestConnectionPool, you can choose any class you like to be your org identifier. Here I&#8217;ll use Integer again.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">ConnectionPool<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span> pool <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConnectionPoolImpl<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>yourPartnerKey<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
pool.<span style="color: #006633;">configureOrg</span><span style="color: #009900;">&#40;</span>orgId, username, password, maxConcurrentApiCalls<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Username and password are the Salesforce username and password of the person you want to log in as. The last parameter sets the max number of concurrent calls you want to happen per org. Fortunately in a recent update (API version 19 or 20, I think) Salesforce greatly relaxed the limits on concurrent connection usage to only apply to calls that take longer than 20 seconds, so you can set this limit fairly high unless you&#8217;re going to be doing long-running calls. See <a href="http://www.salesforce.com/us/developer/docs/api/Content/implementation_considerations.htm#sforce_api_rate_metering">Salesforce&#8217;s API Usage Metering docs</a> for more details.</p>
<p>You can now get a ConnectionBundle for an org. A ConnectionBundle represents the per-org configuration needed for all SOAP connections.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">ConnectionBundle bundle <span style="color: #339933;">=</span> pool.<span style="color: #006633;">getConnectionBundle</span><span style="color: #009900;">&#40;</span>orgId<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
PartnerConnection partnerConn <span style="color: #339933;">=</span> bundle.<span style="color: #006633;">getPartnerConnection</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
ApexConnection apexConn <span style="color: #339933;">=</span> bundle.<span style="color: #006633;">getApexConnection</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
MetadataConnection metadataConn <span style="color: #339933;">=</span> bundle.<span style="color: #006633;">getMetadataConnection</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// partner connection</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;User id is &quot;</span> <span style="color: #339933;">+</span> partnerConn.<span style="color: #006633;">getUserInfo</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getUserId</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: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;First contact's email is &quot;</span> <span style="color: #339933;">+</span> 
    partnerConn.<span style="color: #006633;">query</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SELECT Email FROM Contact LIMIT 1&quot;</span><span style="color: #009900;">&#41;</span>
        .<span style="color: #006633;">getSObjects</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getField</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Email&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// metadata connection</span>
List<span style="color: #339933;">&lt;</span>FileProperties<span style="color: #339933;">&gt;</span> fileProps <span style="color: #339933;">=</span> metadataConn
    .<span style="color: #006633;">listMetadata</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><span style="color: #000000; font-weight: bold;">new</span> ListMetadataQuery<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;CustomField&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</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>FileProperties fp<span style="color: #339933;">:</span> fileProps<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Custom field &quot;</span> <span style="color: #339933;">+</span> fp.<span style="color: #006633;">getFullName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; has id &quot;</span> <span style="color: #339933;">+</span> fp.<span style="color: #006633;">getId</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>
&nbsp;
<span style="color: #666666; font-style: italic;">// apex connection</span>
ExecuteAnonResult result <span style="color: #339933;">=</span> 
    apexConn.<span style="color: #006633;">executeAnonyous</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;System.debug('test debug statement');&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Compile succeeded: &quot;</span> <span style="color: #339933;">+</span> result.<span style="color: #006633;">isCompiled</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: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Debug log output: &quot;</span> <span style="color: #339933;">+</span> result.<span style="color: #006633;">getDebugLog</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Note that the Metadata API example shows how to get custom field Ids, something that is <a href="http://blog.teamlazerbeez.com/2009/05/17/salesforcecom-api-gotchas-2/">impossible via the Partner API</a>.</p>
<p>The ConnectionBundle interface also lets you get the current configuration data for an org. You can use this to get the hostname that you need for RestConnectionPool. Using OAuth to get the token is recommended if that&#8217;s an option, but if not you can also get the current session Id from the configuration data and use that as the OAuth token.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">BindingConfig bindingConfig <span style="color: #339933;">=</span> soapPool.<span style="color: #006633;">getConnectionBundle</span><span style="color: #009900;">&#40;</span>orgId<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getBindingConfig</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">String</span> host <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">URL</span><span style="color: #009900;">&#40;</span>bindingConfig.<span style="color: #006633;">getPartnerServerUrl</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getHost</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003399;">String</span> token <span style="color: #339933;">=</span> bindingConfig.<span style="color: #006633;">getSessionId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
restPool.<span style="color: #006633;">configureOrg</span><span style="color: #009900;">&#40;</span>orgId, host, token<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The library doesn&#8217;t support every single possible call in all of the APIs, but it does support most of them. I only implemented the calls I had occasion to use, so the Partner, Metadata and REST APIs have fairly complete support while the Apex API only supports a fraction of the available calls. If there&#8217;s a call that you use that the library doesn&#8217;t support, let me know and I&#8217;ll see what I can do. Similarly, if the library&#8217;s API doesn&#8217;t seem intuitive or doesn&#8217;t fit well with what you&#8217;re doing, I&#8217;d like to hear about that as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2011/03/03/a-new-java-salesforce-api-library/feed/</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Using dynamically generated configs with puppet</title>
		<link>http://blog.teamlazerbeez.com/2010/11/04/using-dynamically-generated-configs-with-puppet/</link>
		<comments>http://blog.teamlazerbeez.com/2010/11/04/using-dynamically-generated-configs-with-puppet/#comments</comments>
		<pubDate>Thu, 04 Nov 2010 18:41:44 +0000</pubDate>
		<dc:creator>Jon Heise</dc:creator>
				<category><![CDATA[System Administration]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Jon Heise]]></category>
		<category><![CDATA[Puppet]]></category>

		<guid isPermaLink="false">http://blog.teamlazerbeez.com/?p=2712</guid>
		<description><![CDATA[After using Puppet with an external node classifier for a while one starts questioning what other information could be generated by this instead of just YAML to feed the puppetmaster. When supervisor was being rolled out there was a need to a large number of near identical config files to be generated, however any special [...]]]></description>
			<content:encoded><![CDATA[<p>After using Puppet with an external node classifier for a while one  starts questioning what other information could be generated by this  instead of just YAML to feed the puppetmaster. When supervisor was being  rolled out there was a need to a large number of near identical config  files to be generated, however any special information about the configs  really had no place in Puppet. So the solution to this was to have the  Django app generate the config files and then have puppet pull them down  with a custom parser.</p>
<p>In /var/lib/puppet/lib/puppet/parser/functions lives the file webcontent.rb which has the following contents:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'open-uri'</span>
<span style="color:#9966CC; font-weight:bold;">module</span> <span style="color:#6666ff; font-weight:bold;">Puppet::Parser::Functions</span>
    newfunction<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:webcontent</span>, <span style="color:#ff3333; font-weight:bold;">:type</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#ff3333; font-weight:bold;">:rvalue</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>args<span style="color:#006600; font-weight:bold;">|</span>
        server = args<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#93;</span>
        configpath = args<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#93;</span>
        config = <span style="color:#996600;">&quot;&quot;</span>
        <span style="color:#9966CC; font-weight:bold;">begin</span>⋅
            <span style="color:#CC0066; font-weight:bold;">open</span><span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#996600;">&quot;http://#{server}/#{configpath}/&quot;</span> <span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>f<span style="color:#006600; font-weight:bold;">|</span>
             f.<span style="color:#9900CC;">each_line</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>line<span style="color:#006600; font-weight:bold;">|</span>
                 config = <span style="color:#996600;">&quot;#{config}#{line}&quot;</span>
             <span style="color:#9966CC; font-weight:bold;">end</span>
            <span style="color:#9966CC; font-weight:bold;">end</span>⋅
        <span style="color:#9966CC; font-weight:bold;">rescue</span> <span style="color:#6666ff; font-weight:bold;">OpenURI::HTTPError</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; e
            <span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#6666ff; font-weight:bold;">Puppet::ParseError</span>, <span style="color:#996600;">&quot;404 for http://#{server}/#{configpath}/&quot;</span>
&nbsp;
        <span style="color:#9966CC; font-weight:bold;">rescue</span> <span style="color:#CC00FF; font-weight:bold;">Exception</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; e
            <span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#6666ff; font-weight:bold;">Puppet::ParseError</span>, <span style="color:#996600;">&quot;content string is http://#{server}/#{configpath}/ #{e}&quot;</span>
        <span style="color:#9966CC; font-weight:bold;">end</span>
        <span style="color:#0000FF; font-weight:bold;">return</span> config
    <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Using the Ruby module open-uri content is grabbed by the puppetmaster  and placed into the catalog. Using the following Django model, view and  template a config file is easily generated and passed along to Puppet</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> SupervisorProgram<span style="color: black;">&#40;</span>models.<span style="color: black;">Model</span><span style="color: black;">&#41;</span>:
    name = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">128</span><span style="color: black;">&#41;</span>
    command = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">512</span><span style="color: black;">&#41;</span>
    autostart = models.<span style="color: black;">BooleanField</span><span style="color: black;">&#40;</span>default=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    autorestart = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">32</span>,choices=<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'false'</span>,<span style="color: #483d8b;">'false'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'true'</span>,<span style="color: #483d8b;">'true'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'unexpected'</span>,<span style="color: #483d8b;">'unexpected'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    startsecs = models.<span style="color: black;">IntegerField</span><span style="color: black;">&#40;</span>default=<span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>
    startretries = models.<span style="color: black;">IntegerField</span><span style="color: black;">&#40;</span>default=<span style="color: #ff4500;">3</span><span style="color: black;">&#41;</span>
    exitcodes = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">64</span>,default=<span style="color: #483d8b;">&quot;0,2&quot;</span><span style="color: black;">&#41;</span>
    stopsignal = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">5</span>,choices=<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'TERM'</span>,<span style="color: #483d8b;">'TERM'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'HUP'</span>,<span style="color: #483d8b;">'HUP'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'INT'</span>,<span style="color: #483d8b;">'INT'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'QUIT'</span>,<span style="color: #483d8b;">'QUIT'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'KILL'</span>,<span style="color: #483d8b;">'KILL'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'USR1'</span>,<span style="color: #483d8b;">'USR1'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'USR2'</span>,<span style="color: #483d8b;">'USR2'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,default=<span style="color: #483d8b;">&quot;TERM&quot;</span><span style="color: black;">&#41;</span>
    stopwaitsecs = models.<span style="color: black;">IntegerField</span><span style="color: black;">&#40;</span>default=<span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">user</span> = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">16</span> ,default=<span style="color: #483d8b;">&quot;nagios&quot;</span><span style="color: black;">&#41;</span>
    redirect_stderr = models.<span style="color: black;">BooleanField</span><span style="color: black;">&#40;</span>default=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
    stdout_logfile = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">256</span>,default=<span style="color: #483d8b;">&quot;AUTO&quot;</span><span style="color: black;">&#41;</span>
    stdout_logfile_maxbytes = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span> max_length = <span style="color: #ff4500;">8</span>,default=<span style="color: #483d8b;">&quot;50MB&quot;</span><span style="color: black;">&#41;</span>
    stdout_logfile_backups = models.<span style="color: black;">IntegerField</span><span style="color: black;">&#40;</span>default=<span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>
    stderr_logfile = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">256</span>,default=<span style="color: #483d8b;">&quot;AUTO&quot;</span><span style="color: black;">&#41;</span>
    stderr_logfile_maxbytes = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span> max_length = <span style="color: #ff4500;">8</span>,default=<span style="color: #483d8b;">&quot;50MB&quot;</span><span style="color: black;">&#41;</span>
    stderr_logfile_backups = models.<span style="color: black;">IntegerField</span><span style="color: black;">&#40;</span>default=<span style="color: #ff4500;">10</span><span style="color: black;">&#41;</span>
    environment = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span> max_length=<span style="color: #ff4500;">512</span>,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    directory = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">128</span>,default=<span style="color: #483d8b;">&quot;/&quot;</span><span style="color: black;">&#41;</span>
    umask = models.<span style="color: black;">IntegerField</span><span style="color: black;">&#40;</span>blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    priority = models.<span style="color: black;">IntegerField</span><span style="color: black;">&#40;</span>default=<span style="color: #ff4500;">999</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__unicode__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">name</span>
    <span style="color: #ff7700;font-weight:bold;">class</span> Meta:
        ordering = <span style="color: black;">&#40;</span><span style="color: #483d8b;">'name'</span>,<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> SupervisorProgramAdmin<span style="color: black;">&#40;</span>admin.<span style="color: black;">ModelAdmin</span><span style="color: black;">&#41;</span>:
    list_display = <span style="color: black;">&#40;</span><span style="color: #483d8b;">'name'</span>,<span style="color: #483d8b;">'command'</span>,<span style="color: #483d8b;">'autorestart'</span>,<span style="color: #483d8b;">'stopsignal'</span>,<span style="color: #483d8b;">'exitcodes'</span>,<span style="color: #483d8b;">'user'</span>,<span style="color: #483d8b;">'stdout_logfile'</span>,<span style="color: #483d8b;">'stderr_logfile'</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The following is the view used:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> getSupervisorConfig<span style="color: black;">&#40;</span>request,service<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;getSupervisorConfig has been called for %s&quot;</span> <span style="color: #66cc66;">%</span> service
    service = get_object_or_404<span style="color: black;">&#40;</span>SupervisorProgram,name=service<span style="color: black;">&#41;</span>
    directives = <span style="color: black;">&#123;</span><span style="color: black;">&#125;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;command&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">command</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;process_name&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">name</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;priority&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>service.<span style="color: black;">priority</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;autostart&quot;</span> <span style="color: black;">&#93;</span> = service.<span style="color: black;">autostart</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;autorestart&quot;</span><span style="color: black;">&#93;</span> = service.<span style="color: black;">autorestart</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;startsecs&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>service.<span style="color: black;">startsecs</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;startretries&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>service.<span style="color: black;">startretries</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;exitcodes&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">exitcodes</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;stopsignal&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">stopsignal</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;stopwaitsecs&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>service.<span style="color: black;">stopwaitsecs</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;user&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: #dc143c;">user</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;redirect_stderr&quot;</span><span style="color: black;">&#93;</span> = service.<span style="color: black;">redirect_stderr</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;stdout_logfile&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">stdout_logfile</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;stdout_logfile_maxbytes&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">stdout_logfile_maxbytes</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;stdout_logfile_backups&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>service.<span style="color: black;">stdout_logfile_backups</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;stderr_logfile&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">stderr_logfile</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;stderr_logfile_maxbytes&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">stderr_logfile_maxbytes</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;stderr_logfile_backups&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">int</span><span style="color: black;">&#40;</span>service.<span style="color: black;">stderr_logfile_backups</span><span style="color: black;">&#41;</span>
    directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;directory&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">directory</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> service.<span style="color: black;">environment</span>:
        directives<span style="color: black;">&#91;</span><span style="color: #483d8b;">&quot;environment&quot;</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>service.<span style="color: black;">environment</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">return</span> render_to_response<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;sock/supervisor.conf&quot;</span>,directives<span style="color: black;">&#41;</span></pre></div></div>

<p>With the 20 configuration options per supervisord controlled process  there are far too many options that should be sanely passed to  puppetmaster from the external node classifier.</p>
<p>Here is the Django template:</p>

<div class="wp_syntax"><div class="code"><pre class="django" style="font-family:monospace;">#generated config
[program:{{ process_name }}]
command={{ command }}
process_name=%(program_name)s
priority={{ priority }}
autostart={{ autostart }}
autorestart={{ autorestart }}
startsecs={{ startsecs }}
startretries={{ startretries }}
exitcodes={{ exitcodes }}
stopsignal={{ stopsignal }}
stopwaitsecs={{ stopwaitsecs }}
user={{ user }}
redirect_stderr={{ redirect_stderr }}
stdout_logfile={{ stdout_logfile }}
stdout_logfile_maxbytes={{ stdout_logfile_maxbytes }}
stdout_logfile_backups={{ stdout_logfile_backups }}
stderr_logfile={{ stderr_logfile }}
stderr_logfile_maxbytes={{ stderr_logfile_maxbytes }}
stderr_logfile_backups={{ stderr_logfile_backups }}
{% if environment %}
environment={{ environment }}
{% endif %}</pre></div></div>

<p>Finally all of this can be referenced with a custom define as follows:</p>

<div class="wp_syntax"><div class="code"><pre class="puppet" style="font-family:monospace;">define supervisorconfig(
        $program,
        $server = &quot;${rserver}&quot;
) {
    file {
        &quot;${name}.conf&quot;:
            owner =&amp;gt; root,
            group =&amp;gt; root,
            mode =&amp;gt; 0644,
            path =&amp;gt; &quot;/etc/supervisord.d/${name}.conf&quot;,
            content =&amp;gt; webcontent( $server, &quot;dpuppet/sock3/getsupervisorconfig/$program&quot;)
    }
}</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2010/11/04/using-dynamically-generated-configs-with-puppet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Database Fixtures for Isolated Testing in PHP</title>
		<link>http://blog.teamlazerbeez.com/2010/11/03/database-fixtures-for-isolated-testing-in-php/</link>
		<comments>http://blog.teamlazerbeez.com/2010/11/03/database-fixtures-for-isolated-testing-in-php/#comments</comments>
		<pubDate>Wed, 03 Nov 2010 18:31:40 +0000</pubDate>
		<dc:creator>Drew Stephens</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Drew Stephens]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blog.teamlazerbeez.com/?p=2717</guid>
		<description><![CDATA[Long ago, Ryan wrote the history of our fixture frameworks. Now, you too can have the awesome Team Lazer Beez database fixture for your own project. With the release of Team Lazer Beez Open Source (formerly Genius Open Source) version 1.2, our YAML-backed, easy-to-setup fixture framework has been integrated into the gosTest framework. Here is [...]]]></description>
			<content:encoded><![CDATA[<p>Long ago, Ryan wrote the <a href="http://blog.teamlazerbeez.com/2009/03/30/testing-db-dependencies-with-phpunit/">history of our fixture frameworks</a>.  Now, you too can have the awesome Team Lazer Beez database fixture for your own project.  With the release of <a href="https://launchpad.net/genius">Team Lazer Beez Open Source</a> (formerly Genius Open Source) <a href="https://launchpad.net/genius/+download">version 1.2</a>, our YAML-backed, easy-to-setup fixture framework has been integrated into the gosTest framework.</p>
<p>Here is a simple example from our <a href="http://bazaar.launchpad.net/~genius.com/genius/trunk/annotate/head:/php/Fixture/example.php">Fixture package</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">// Include the Genius config file</span>
<span style="color: #b1b100;">require_once</span> <span style="color: #990000;">dirname</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">dirname</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">__FILE__</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'/Core/gosConfig.inc.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/**
 * A function to get single values from a database table
 */</span>
<span style="color: #000000; font-weight: bold;">function</span> getThingFromDB<span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$db</span> <span style="color: #339933;">=</span> gosDB_Helper<span style="color: #339933;">::</span><span style="color: #004000;">getDBByName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'main'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$db</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getOne</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;SELECT s1 FROM fixture_test WHERE i1 = &quot;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$id</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In a nearby test file:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">// Include the Genius fixture configuration. This geneartes a database</span>
<span style="color: #666666; font-style: italic;">// and applies the schema to it.  See fixtureTestConfig.inc.php</span>
<span style="color: #666666; font-style: italic;">// for more details.</span>
<span style="color: #b1b100;">require_once</span><span style="color: #009900;">&#40;</span>GOS_ROOT <span style="color: #339933;">.</span> <span style="color: #0000ff;">'Fixture/fixtureTestConfig.inc.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">function</span> testGetThingFromDB<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Create a fixture</span>
    <span style="color: #000088;">$fixture</span> <span style="color: #339933;">=</span> gosTest_Fixture_Controller<span style="color: #339933;">::</span><span style="color: #004000;">getByDBName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'main'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Load the fixture into the database</span>
    <span style="color: #000088;">$fixture</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">parseFixtureFile</span><span style="color: #009900;">&#40;</span>GOS_ROOT <span style="color: #339933;">.</span> <span style="color: #0000ff;">'Fixture/example_fixture.yaml'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Directly access the fixture, which is identical to what the database contains</span>
    <span style="color: #000088;">$idToGet</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$fixture</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'fixtureName.fixture_test.i1'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Pull the value we want directly from the fixture</span>
    <span style="color: #000088;">$fixtureThing</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$fixture</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'fixtureName.fixture_test.s1'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">// Pull the value we want from the DB via the function we're testing</span>
    <span style="color: #000088;">$thing</span> <span style="color: #339933;">=</span> getThingFromDB<span style="color: #009900;">&#40;</span><span style="color: #000088;">$idToGet</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;The fixture put <span style="color: #006699; font-weight: bold;">$fixtureThing</span> into the DB.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Our function selected <span style="color: #006699; font-weight: bold;">$thing</span> from the DB.<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Run the test</span>
testGetThingFromDB<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The first magical line here is that require_once—<tt>fixtureTestConfig.inc.php</tt> uses the database connection information defined in <tt>Fixture/fixtureConfig.yaml</tt> to create a database is used for the duration of this PHP process only.  Subsequent test runs (or invocations of this example script) will generate an entirely new database.  See <a href="http://bazaar.launchpad.net/~genius.com/genius/trunk/view/head:/php/DB/lib/gosDB/AutoDBGenerator.cls.php">gosDB_AutoDBGenerator</a> for details on these ephemeral databases.  The takeaway is that you must have a user listed in that fixture config YAML file that can create databases.</p>
<p>In the test function itself, we create a fixture on the appropriate database, in this case our <tt>main</tt> database, and load the data from our fixture file, a simple YAML file defining what data we want in the database:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;"># The name of this fixture
fixtureName:
    # A table we will insert data into
    fixture_test:
        i1: 11
        s1: str1</pre></div></div>

<p>At this point, we&#8217;re ready to start testing.  First we get the ID that we need to pass to <tt>getThingFromDB</tt>, which we simply pull from the fixture.  Next, we get the value that we are expecting from the same table in the fixture.  Now that we have the ID we want to give to the function we&#8217;re testing, and the value we expect to get back, we can execute that function and compare the results.  Go ahead and try this all for yourself; the above example works all on its own.  The easiest way is to download the <a href="http://bazaar.launchpad.net/~genius.com/genius/trunk/download/head%3A/example.php-20101020230226-k49vggonvao9pdwi-1/example.php">example.php</a> and the necessary <a href="http://bazaar.launchpad.net/~genius.com/genius/trunk/download/head%3A/example_fixture.yaml-20101021212556-i3d4ph8xswy4yo8m-1/example_fixture.yaml">YAML file</a>.</p>
<p>The gosFixture class automatically cleans up the database tables that it touched (see <tt>Core/lib/gosTest/Framework/TestCase.acls.php</tt>), so you need to re-apply the fixture for every test.  The easiest way to do this is to put the fixture initialization in the <tt>setUpExtension()</tt> of a test class, giving you completely fresh fixture data for each and every test.</p>
<p>So go forth and test your code with better isolation and known clean data.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2010/11/03/database-fixtures-for-isolated-testing-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Puppet External Node Classifier</title>
		<link>http://blog.teamlazerbeez.com/2010/10/13/puppet-external-node-classifier/</link>
		<comments>http://blog.teamlazerbeez.com/2010/10/13/puppet-external-node-classifier/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 18:06:59 +0000</pubDate>
		<dc:creator>Jon Heise</dc:creator>
				<category><![CDATA[System Administration]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[Jon Heise]]></category>
		<category><![CDATA[Puppet]]></category>

		<guid isPermaLink="false">http://eng.genius.com/blog/?p=2657</guid>
		<description><![CDATA[In Puppet the initial method of holding information about your machines is through the site.pp config file, this rapidly becomes tiresome when you have more than 5 servers. This is where an external node classier comes in as a handy tool. The first step in setting up an external node classifier is developing what will [...]]]></description>
			<content:encoded><![CDATA[<p>In Puppet the initial method of holding information about your machines is through the site.pp config file, this rapidly becomes tiresome when you have more than 5 servers. This is where an external node classier comes in as a handy tool.</p>
<p>The first step in setting up an external node classifier is developing what will be generating the YAML for the puppetmaster to read. In this situation Django chosen as a web framework as the built in admin interface saved a bit of development time for management. Additional thought behind using an ORM framework was cutting down on development time on other projects that might need access to the truth database and could simply pull YAML from it. Within the Django application there are classes describing hosts, environments, server class, puppet classes, hard drive and filesystem layout. Here is the class describing a host:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> Host<span style="color: black;">&#40;</span>models.<span style="color: black;">Model</span><span style="color: black;">&#41;</span>:
    hostname = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>null=<span style="color: #008000;">True</span>,blank=<span style="color: #008000;">False</span>,max_length=<span style="color: #ff4500;">128</span><span style="color: black;">&#41;</span>
    basename = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>null=<span style="color: #008000;">True</span>,blank=<span style="color: #008000;">True</span>,max_length=<span style="color: #ff4500;">128</span><span style="color: black;">&#41;</span>
    maintenance = models.<span style="color: black;">BooleanField</span><span style="color: black;">&#40;</span>default=<span style="color: #008000;">False</span><span style="color: black;">&#41;</span>
    datacenter = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">5</span>,choices=<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'sjc'</span>,<span style="color: #483d8b;">'san jose'</span><span style="color: black;">&#41;</span>,
        <span style="color: black;">&#40;</span><span style="color: #483d8b;">'smc'</span>,<span style="color: #483d8b;">'server room'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    environment = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">5</span>,choices=<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'app'</span>,<span style="color: #483d8b;">'production'</span><span style="color: black;">&#41;</span>,
        <span style="color: black;">&#40;</span><span style="color: #483d8b;">'stg1'</span>,<span style="color: #483d8b;">'staging 1'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'stg2'</span>,<span style="color: #483d8b;">'staging 2'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'dev'</span>,<span style="color: #483d8b;">'development'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    env = models.<span style="color: black;">ForeignKey</span><span style="color: black;">&#40;</span>Environment<span style="color: black;">&#41;</span>
    ostype = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">32</span>,choices=<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'linux'</span>,<span style="color: #483d8b;">'linux'</span><span style="color: black;">&#41;</span>,
        <span style="color: black;">&#40;</span><span style="color: #483d8b;">'windows'</span>,<span style="color: #483d8b;">'windows'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'mac'</span>,<span style="color: #483d8b;">'mac'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    info = models.<span style="color: black;">TextField</span><span style="color: black;">&#40;</span>blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    bit = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span>,max_length=<span style="color: #ff4500;">5</span>,choices=<span style="color: black;">&#40;</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'32'</span>,<span style="color: #483d8b;">'32 bit'</span><span style="color: black;">&#41;</span>,<span style="color: black;">&#40;</span><span style="color: #483d8b;">'64'</span>,<span style="color: #483d8b;">'64 bit'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    puppetrun = models.<span style="color: black;">IntegerField</span><span style="color: black;">&#40;</span>default=<span style="color: #ff4500;">1800</span><span style="color: black;">&#41;</span>
    serverclass = models.<span style="color: black;">ForeignKey</span><span style="color: black;">&#40;</span>SvrClass<span style="color: black;">&#41;</span>
&nbsp;
    classes = models.<span style="color: black;">ManyToManyField</span><span style="color: black;">&#40;</span>PuppetClass,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    drives = models.<span style="color: black;">ManyToManyField</span><span style="color: black;">&#40;</span>Drive,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    interfaces = models.<span style="color: black;">ManyToManyField</span><span style="color: black;">&#40;</span>NetInterface,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    script = models.<span style="color: black;">ManyToManyField</span><span style="color: black;">&#40;</span>Script,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    osver = models.<span style="color: black;">ManyToManyField</span><span style="color: black;">&#40;</span>Osversion,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    services = models.<span style="color: black;">ManyToManyField</span><span style="color: black;">&#40;</span>Service,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
    supervisors = models.<span style="color: black;">ManyToManyField</span><span style="color: black;">&#40;</span>SupervisorProgram,blank=<span style="color: #008000;">True</span>,null=<span style="color: #008000;">True</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> getBranch<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">env</span>.<span style="color: black;">branch</span>.<span style="color: black;">name</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> getEnvironment<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">env</span>.<span style="color: black;">name</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__str__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: #0000cd;">__repr__</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">&quot;hostname: %s environment: %s&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>.<span style="color: black;">hostname</span>,<span style="color: #008000;">self</span>.<span style="color: black;">env</span>.<span style="color: black;">name</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> HostAdmin<span style="color: black;">&#40;</span>admin.<span style="color: black;">ModelAdmin</span><span style="color: black;">&#41;</span>:
    list_display    =   <span style="color: black;">&#40;</span><span style="color: #483d8b;">'hostname'</span>,<span style="color: #483d8b;">'environment'</span>,<span style="color: #483d8b;">'bit'</span>,<span style="color: #483d8b;">'ostype'</span>,<span style="color: #483d8b;">'datacenter'</span>,<span style="color: #483d8b;">'maintenance'</span><span style="color: black;">&#41;</span>
    list_filter     =   <span style="color: black;">&#40;</span><span style="color: #483d8b;">'environment'</span>,<span style="color: #483d8b;">'datacenter'</span><span style="color: black;">&#41;</span>
    ordering        =   <span style="color: black;">&#40;</span><span style="color: #483d8b;">'hostname'</span>,<span style="color: #483d8b;">'datacenter'</span>,<span style="color: #483d8b;">'environment'</span><span style="color: black;">&#41;</span>
    search_fields   =   <span style="color: black;">&#40;</span><span style="color: #483d8b;">'hostname'</span>,<span style="color: black;">&#41;</span></pre></div></div>

<p>and now the code for the Puppet class in Python, the Puppet class class:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> PuppetClass<span style="color: black;">&#40;</span>models.<span style="color: black;">Model</span><span style="color: black;">&#41;</span>:
    name = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">128</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__unicode__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">name</span>
    <span style="color: #ff7700;font-weight:bold;">class</span> Meta:
        ordering = <span style="color: black;">&#40;</span><span style="color: #483d8b;">'name'</span>,<span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> PuppetClassAdmin<span style="color: black;">&#40;</span>admin.<span style="color: black;">ModelAdmin</span><span style="color: black;">&#41;</span>:
    list_display = <span style="color: black;">&#40;</span><span style="color: #483d8b;">'name'</span>,<span style="color: black;">&#41;</span></pre></div></div>

<p> With these two classes a host and what Puppet classes it has assigned to it can readily be described and the following code will output YAML describing the host as the puppetmaster understands:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> yaml
&nbsp;
<span style="color: #ff7700;font-weight:bold;">def</span> hostinfo<span style="color: black;">&#40;</span>request,hostname<span style="color: black;">&#41;</span>:
    host = get_object_or_404<span style="color: black;">&#40;</span>Host,hostname=hostname<span style="color: black;">&#41;</span>
    classlist = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
    <span style="color: black;">&#91;</span>classlist.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #008000;">str</span><span style="color: black;">&#40;</span>x.<span style="color: black;">name</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> host.<span style="color: black;">classes</span>.<span style="color: #008000;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
    <span style="color: #808080; font-style: italic;">#if a host's classlist is empty at this point pull from the default list</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> classlist:
        <span style="color: #808080; font-style: italic;">#default list is simply a list of puppet class objects</span>
        defaultlist = DefaultList.<span style="color: black;">objects</span>.<span style="color: black;">get</span><span style="color: black;">&#40;</span>name=<span style="color: #483d8b;">&quot;standard&quot;</span><span style="color: black;">&#41;</span>
        <span style="color: black;">&#91;</span>classlist.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #008000;">str</span><span style="color: black;">&#40;</span>x.<span style="color: black;">name</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">for</span> x <span style="color: #ff7700;font-weight:bold;">in</span> defaultlist.<span style="color: black;">classes</span>.<span style="color: #008000;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#93;</span>
    <span style="color: #808080; font-style: italic;">#add in some extra parameters</span>
    params = <span style="color: black;">&#123;</span><span style="color: #483d8b;">'datacenter'</span>:<span style="color: #008000;">str</span><span style="color: black;">&#40;</span>host.<span style="color: black;">datacenter</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'machine'</span>:<span style="color: #008000;">str</span><span style="color: black;">&#40;</span>host.<span style="color: black;">basename</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'serverclass'</span>:<span style="color: #008000;">str</span><span style="color: black;">&#40;</span>host.<span style="color: black;">serverclass</span>.<span style="color: black;">name</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'env'</span>:<span style="color: #008000;">str</span><span style="color: black;">&#40;</span>host.<span style="color: black;">env</span>.<span style="color: black;">name</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'branch'</span>:<span style="color: #483d8b;">'%s'</span> <span style="color: #66cc66;">%</span> <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>host.<span style="color: black;">env</span>.<span style="color: black;">branch</span>.<span style="color: black;">name</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'envmaint'</span>:<span style="color: #008000;">str</span><span style="color: black;">&#40;</span>host.<span style="color: black;">env</span>.<span style="color: black;">maintenance</span><span style="color: black;">&#41;</span>,<span style="color: #483d8b;">'hostmaint'</span>:<span style="color: #008000;">str</span><span style="color: black;">&#40;</span>host.<span style="color: black;">maintenance</span><span style="color: black;">&#41;</span><span style="color: black;">&#125;</span>
    params<span style="color: black;">&#91;</span><span style="color: #483d8b;">'rserver'</span><span style="color: black;">&#93;</span> = <span style="color: #008000;">str</span><span style="color: black;">&#40;</span>host.<span style="color: black;">env</span>.<span style="color: black;">rserver</span><span style="color: black;">&#41;</span>
    yamlsrc = yaml.<span style="color: black;">dump</span><span style="color: black;">&#40;</span><span style="color: black;">&#123;</span><span style="color: #483d8b;">'classes'</span>:classlist,<span style="color: #483d8b;">'parameters'</span>:params<span style="color: black;">&#125;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">return</span>  render_to_response<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;sock/hostinfo.yaml&quot;</span>,<span style="color: black;">&#123;</span><span style="color: #483d8b;">'hostname'</span>:hostname,<span style="color: #483d8b;">'yaml'</span>:yamlsrc<span style="color: black;">&#125;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>One issue that was encountered with exporting data from django to yaml was the usage of utf for strings, hence the continual usage of str(). The result of the function is dumped out through the following incredibly complex template</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">---
{{ yaml }}</pre></div></div>

<p>At the end of all of this we finally get data that comes out as something similar to the following:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">---
classes: [bots, puppet-classes, puppet-master, repos, yamlsvn]
parameters: {branch: '33', datacenter: sjc, env: app, envmaint: '0', hostmaint: '0',
  machine: repo, rserver: sjc-repo.genops.net, serverclass: none}</pre></div></div>

<p>Next we need a command that the puppetmaster can run to get the YAML, here is the current script:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">#!/bin/sh</span>
curl http:<span style="color: #000000; font-weight: bold;">//</span>example.genius.com<span style="color: #000000; font-weight: bold;">/</span>dpuppet<span style="color: #000000; font-weight: bold;">/</span>sock3<span style="color: #000000; font-weight: bold;">/</span>hostinfo<span style="color: #000000; font-weight: bold;">/</span><span style="color: #007800;">$1</span><span style="color: #000000; font-weight: bold;">/</span> <span style="color: #000000;">2</span><span style="color: #000000; font-weight: bold;">&gt;/</span>dev<span style="color: #000000; font-weight: bold;">/</span>null <span style="color: #000000; font-weight: bold;">|</span> \
<span style="color: #c20cb9; font-weight: bold;">sed</span> <span style="color: #ff0000;">&quot;s/&amp;#39;/'/g&quot;</span>
<span style="color: #7a0874; font-weight: bold;">exit</span> <span style="color: #000000;">0</span>;</pre></div></div>

<p>Finally the puppetmaster needs to be configured to pull from the external node classifier:</p>

<div class="wp_syntax"><div class="code"><pre class="conf" style="font-family:monospace;">[main]
    # Where Puppet stores dynamic and growing data.
    # The default value is '/var/puppet'.
    vardir = /var/lib/puppet
&nbsp;
    # The Puppet log directory.
    # The default value is '$vardir/log'.
    logdir = /var/log/puppet
&nbsp;
    # Where Puppet PID files are kept.
    # The default value is '$vardir/run'.
    rundir = /var/run/puppet
&nbsp;
    # Where SSL certificates are kept.
    # The default value is '$confdir/ssl'.
    ssldir = $vardir/ssl
    # use external nodes ftw
    external_nodes = /usr/local/bin/puppetinfo.sh
    node_terminus = exec
&nbsp;
[puppetd]
    # The file in which puppetd stores a list of the classes
    # associated with the retrieved configuratiion.  Can be loaded in
    # the separate ``puppet`` executable using the ``--loadclasses``
    # option.
    # The default value is '$confdir/classes.txt'.
    classfile = $vardir/classes.txt
&nbsp;
    # Where puppetd caches the local configuration.  An
    # extension indicating the cache format is added automatically.
    # The default value is '$confdir/localconfig'.
    localconfig = $vardir/localconfig
    server =  puppetmaster.genius.com
    runinterval = 300</pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2010/10/13/puppet-external-node-classifier/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Puppet at Genius</title>
		<link>http://blog.teamlazerbeez.com/2010/10/12/puppet-at-genius/</link>
		<comments>http://blog.teamlazerbeez.com/2010/10/12/puppet-at-genius/#comments</comments>
		<pubDate>Tue, 12 Oct 2010 18:00:18 +0000</pubDate>
		<dc:creator>Jon Heise</dc:creator>
				<category><![CDATA[System Administration]]></category>
		<category><![CDATA[Jon Heise]]></category>
		<category><![CDATA[Puppet]]></category>
		<category><![CDATA[sysadmin]]></category>

		<guid isPermaLink="false">http://eng.genius.com/blog/?p=2651</guid>
		<description><![CDATA[Puppet is a configuration management system  that was created with the goal of making more portions of system administration tasks reuseable. At Genius puppet is used in all of our environments: production, staging, and development. Within this setup each environment has its own puppetmaster, with each master pulling against its own version of the puppet [...]]]></description>
			<content:encoded><![CDATA[<p>Puppet is a configuration management system  that was created with the goal of making more portions of system administration tasks reuseable. At Genius puppet is used in all of our environments: production, staging, and development. Within this setup each environment has its own puppetmaster, with each master pulling against its own version of the puppet classes.  All of the masters in turn pull all of their information nodes from a central external node classifier.</p>
<p>The masters act as their own clients, syncing against themselves with a puppet class that controls checkouts of an svn repository holding all puppet classes.  All of the servers have been configured with custom defines to handle subervision checkouts and configs for supervisor, additionally a custom parser has been written to allow pulling down webpages as part a content description. All servers run on an interval of 5 minutes with clients running on a 15 minute interval, with some special exceptions for dns servers.  Additionally the web app that powers the external node classier also handles generating config files and maintaining a truth database for other tasks, like imaging.</p>
<p>This is the first in a series of post regarding our setup, following posts will cover our external node classifier, truth database, customer parser, custom defines.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2010/10/12/puppet-at-genius/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using HornetQ without a separate JNDI server</title>
		<link>http://blog.teamlazerbeez.com/2010/10/08/using-hornetq-without-a-separate-jndi-server/</link>
		<comments>http://blog.teamlazerbeez.com/2010/10/08/using-hornetq-without-a-separate-jndi-server/#comments</comments>
		<pubDate>Fri, 08 Oct 2010 22:10:19 +0000</pubDate>
		<dc:creator>Marshall Pierce</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[open source]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://eng.genius.com/blog/?p=2619</guid>
		<description><![CDATA[This tutorial shows how to get HornetQ JMS resources out of JNDI. It also includes utilities to help use an embedded HornetQ server when writing test code.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.jboss.org/hornetq">HornetQ</a> is JBoss&#8217;s latest messaging product. It provides a JMS implementation as well as its own <a href="http://hornetq.sourceforge.net/docs/hornetq-2.1.2.Final/user-manual/en/html/using-core.html">alternate API</a>. JMS is the Java Message Service: a set of APIs built around asynchronous messaging through topics (think bulletin boards) and queues (self-explanatory). For more, see <a href="http://download.oracle.com/javaee/1.3/jms/tutorial/1_3_1-fcs/doc/jms_tutorialTOC.html">the standard JMS tutorial</a>.</p>
<p>This tutorial shows how to access HornetQ JMS resources via JNDI without needing a separate JNDI server. It also provides a test utility to run an embedded HornetQ server (perfect for unit tests that need a JMS broker running!).</p>
<h2>Why JNDI?</h2>
<p>Since JMS is part of Java EE, you&#8217;ll often see tutorials that have JMS resources (e.g. connection factories or queues) being provided to your code is via JNDI. This isn&#8217;t the only choice, though: you could instead <a href="http://hornetq.sourceforge.net/docs/hornetq-2.1.2.Final/user-manual/en/html/using-jms.html#d0e1186">manually instantiate</a> your preferred provider&#8217;s implementations of the resources you need.</p>
<p>If you choose the latter approach, you might use the following to get a Queue if you were using <a href="http://activemq.apache.org/">ActiveMQ</a> (another JMS implementation):</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Queue queue <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ActiveMQQueue<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;queueName&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This works fine until you switch to another provider, at which point you need to change all your queues (and connection factories and topics and&#8230;) to look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Queue queue <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HornetQQueue<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;queueName&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is why it&#8217;s recommended to instead pull those objects out of JNDI. If you&#8217;re getting the queue out of JNDI with the following code, you wouldn&#8217;t need to change anything if you switch providers other than changing how the JNDI context gets populated.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Context</span> context <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">InitialContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Queue queue<span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
    queue <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Queue<span style="color: #009900;">&#41;</span> context.<span style="color: #006633;">lookup</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;jndiNameForQueue&quot;</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;">finally</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// release your context's resources when you're done with it</span>
    context.<span style="color: #006633;">close</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This isn&#8217;t meant to be a JNDI tutorial, but it should be clear why getting JMS resources (as well as things like JDBC DataSource objects and other &#8220;managed&#8221; objects) out of JNDI is a good thing: it makes it easier to program to interfaces, not implementations, and maintain vendor neutrality.</p>
<h2>HornetQ&#8217;s JNDI support</h2>
<p>HornetQ comes with all you need to be able to <a href="http://hornetq.sourceforge.net/docs/hornetq-2.1.2.Final/user-manual/en/html/using-jms.html#d0e1087">connect to a JNDI server</a> and pull JMS resources out of that server. You can set up the HornetQ server to serve JNDI in addition to JMS by enabling the appropriate bean in hornetq-beans.xml.</p>
<p>This approach is straightforward, but it becomes problematic if you want your HornetQ servers to be in a <a href="http://hornetq.sourceforge.net/docs/hornetq-2.1.2.Final/user-manual/en/html/ha.html">HA (high availability)</a> pair. It&#8217;s hard enough to configure and test HA without also needing JNDI service to fail over as well. Though there is <a href="http://hornetq.sourceforge.net/docs/hornetq-2.1.2.Final/user-manual/en/html/appserver-integration.html#d0e8107">some documentation on how to set up HA JNDI</a>, it would be simpler (and surely faster as well) if there was no need to talk to a server at all to get JMS resources. This approach makes sense if your deployment setup is simple enough that you know which queues and JMS servers you will be using and can put that information in a few config files and bundle it with your code during deployment. This is the case for many uses of JMS. If, on the other hand, you&#8217;re already tied to using a Java EE server that provides JNDI, then you might as well use that.</p>
<p>ActiveMQ provides <a href="http://activemq.apache.org/jndi-support.html">a simple way to configure JMS resources in local JNDI</a>, but HornetQ doesn&#8217;t come with anything similar. This tutorial provides a way to do local JNDI with HornetQ.</p>
<h2>Local JNDI Configuration</h2>
<p>The starting point to accessing JNDI objects is creating a new InitialContext. The specific way that the resulting Context gets populated with data is controlled by the implementation of InitialContextFactory that you&#8217;re using. You can change the implementation by specifying the <code>java.naming.factory.initial</code> property in <code>jndi.properties</code> to be the fully qualified class name of an impementation of InitialContextFactory.</p>
<p>We can use this mechanism to specify an implementation of InitialContextFactory that reads HornetQ&#8217;s config files. More sophisticated implementations might produce a Context that accesses data on some remote server, but our goal here is something that reads data out of config files and populates a memory-only Context. We&#8217;ll need to read the core HornetQ config file to get connection factory information and the JMS HornetQ config file to get the JNDI names to assign to queues, topics, etc. We&#8217;ll also need something to actually create a Context implementation since we don&#8217;t want to have to write that ourselves. Implementing Context requires a non-trivial amount of work to do well. <a href="http://www.osjava.org/simple-jndi/">simple-jndi</a> provides a basic in-memory InitialContextFactory, so we&#8217;ll use that.</p>
<p>Your <code>jndi.properties</code> would look something like this:</p>
<pre>
java.naming.factory.initial = com.genius.hornetq.XmlHornetQInitialContextFactory
hornetq.jndi.wrapped.initialcontextfactory.impl = org.osjava.sj.memory.MemoryContextFactory
hornetq.xml.jms.path = /path-to-hornetq-jms.xml
hornetq.xml.config.path = /path-to-hornetq-config.xml
</pre>
<p>The <code>java.naming.factory.initial</code> tells InitialContext which class to instantiate to return the underlying Context (look at the source that comes with the JDK if you&#8217;re curious how). In this case, we want InitialContext to use our custom implementation that reads HornetQ XML files.</p>
<p>The other properties are only relevant to our custom InitialContextFactory. See the <a href="http://hornetq.sourceforge.net/docs/hornetq-2.1.2.Final/user-manual/en/html/using-server.html#using-server.configuration">HornetQ documentation</a> for more about what to put in the XML config files.<br />
<code>hornetq.jndi.wrapped.initialcontextfactory.impl</code> defines what InitialContextFactory we&#8217;ll use to actually create a Context object. In this case, it&#8217;s the simple-jndi memory-only InitialContextFactory.<br />
<code>hornetq.xml.jms.path</code> is the path in the classpath to the HornetQ JMS config file. This is typically &#8220;hornetq-jms.xml&#8221;.<br />
<code>hornetq.xml.config.path</code> is the path in the classpath to the HornetQ core config file. This is typically &#8220;hornetq-configuration.xml&#8221;.</p>
<p>Now that we&#8217;ve got jndi.properties ready, I&#8217;ve added the custom InitialContextFactory source below. The only tricky part is handling HornetQ&#8217;s LogDelegateFactory selection. The LogDelegateFactory system lets you change the logging system used by HornetQ and is configurable via the core config file. (I&#8217;d link to the documentation, but this option is undocumented. See FileConfigurationParser#parseMainConfig() in the HornetQ source.) Unfortunately, a <a href="https://jira.jboss.org/browse/HORNETQ-406">bug in the way the LogDelegateFactory instance is set</a> causes some classes to not properly pick up your custom implementation, so if you wish to use a custom LogDelegateFactory, note the commented out call to <code>Logger.setDelegateFactory</code>. Other than that, it&#8217;s pretty simple. We use HornetQ&#8217;s configuration parsing code to get the information we need out of the config files, then populate the Context we get from simple-jndi with the resulting JMS objects.</p>
<p>The only dependency outside of HornetQ is <a href="http://www.slf4j.org/">SLF4J</a> for logging.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.genius.hornetq</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.api.core.Pair</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.api.core.TransportConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.api.jms.HornetQJMSClient</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.core.config.Configuration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.core.deployers.impl.FileConfigurationParser</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.client.HornetQConnectionFactory</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.client.HornetQDestination</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.JMSServerConfigParser</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.config.ConnectionFactoryConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.config.JMSConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.config.JMSQueueConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.config.TopicConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.impl.JMSServerConfigParserImpl</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.spi.core.logging.LogDelegateFactory</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.slf4j.Logger</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.slf4j.LoggerFactory</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.jms.Queue</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.jms.Topic</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.Context</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.NamingException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.spi.InitialContextFactory</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.InputStream</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.lang.reflect.Constructor</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.lang.reflect.InvocationTargetException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.ArrayList</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.HashMap</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Hashtable</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>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Map</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Parses hornetq jms and core configuration files and populates the resulting Context appropriately.
 *
 * The following properties are needed:
 *
 * hornetq.xml.jms.path = path in the classpath to hornetq jms xml file
 *
 * hornetq.xml.config.path = path in classpath to hornetq core config file
 *
 * hornetq.jndi.wrapped.initialcontextfactory.impl = fully qualified classname of InitialContextFactory to use to
 * provide the Context instance that will be populated with configured JMS objects. An instance of this class will be
 * created and passed an empty environment.
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> XmlHornetQInitialContextFactory <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">InitialContextFactory</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> JMS_XML_PATH_KEY <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;hornetq.xml.jms.path&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> CONFIG_XML_PATH_KEY <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;hornetq.xml.config.path&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> INTERNAL_ICF_IMPL_KEY <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;hornetq.jndi.wrapped.initialcontextfactory.impl&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Logger logger <span style="color: #339933;">=</span> LoggerFactory.<span style="color: #006633;">getLogger</span><span style="color: #009900;">&#40;</span>XmlHornetQInitialContextFactory.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> XmlHornetQInitialContextFactory<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        logger.<span style="color: #006633;">trace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Instantiated&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;">Context</span> getInitialContext<span style="color: #009900;">&#40;</span>Hashtable<span style="color: #339933;">&lt;?</span>, <span style="color: #339933;">?&gt;</span> environmentHashtable<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        logger.<span style="color: #006633;">trace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Creating InitialContext&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        Map<span style="color: #339933;">&lt;</span>string, String<span style="color: #339933;">&gt;</span> env <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HashMap<span style="color: #339933;">&lt;</span>string, String<span style="color: #339933;">&gt;</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><span style="color: #003399;">Map</span>.<span style="color: #006633;">Entry</span><span style="color: #339933;">&lt;?</span>, <span style="color: #339933;">?&gt;</span> entry <span style="color: #339933;">:</span> environmentHashtable.<span style="color: #006633;">entrySet</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>entry.<span style="color: #006633;">getKey</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">String</span> <span style="color: #339933;">&amp;&amp;</span> entry.<span style="color: #006633;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">instanceof</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                env.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span> entry.<span style="color: #006633;">getKey</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span> entry.<span style="color: #006633;">getValue</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: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">checkKeys</span><span style="color: #009900;">&#40;</span>env, JMS_XML_PATH_KEY, INTERNAL_ICF_IMPL_KEY, CONFIG_XML_PATH_KEY<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #003399;">Context</span> ctx <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getContext</span><span style="color: #009900;">&#40;</span>env<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        populateContext<span style="color: #009900;">&#40;</span>env, ctx<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> ctx<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> populateContext<span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, String<span style="color: #339933;">&gt;</span> env, <span style="color: #003399;">Context</span> ctx<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">InputStream</span> configXmlStream <span style="color: #339933;">=</span> getStream<span style="color: #009900;">&#40;</span>env.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>CONFIG_XML_PATH_KEY<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">/*
        * A bug in HQ 2.1.2 means that the log delegate factory will not be applied to any classes that use static
        * loggers and were loaded before the config-specified delegate factory is applied. A fix is scheduled for 2.2.0.
         * Until then, we'll hardcode the delegate factory to slf4j for the first few loggers.
        */</span>
        <span style="color: #666666; font-style: italic;">//org.hornetq.core.logging.Logger.setDelegateFactory(new YourCustomLogDelegateFactory());</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">final</span> Configuration config<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            config <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> FileConfigurationParser<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">parseMainConfig</span><span style="color: #009900;">&#40;</span>configXmlStream<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</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;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> getNamingException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't get configuration from xml&quot;</span>, e<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;">final</span> LogDelegateFactory logDelegateFactory <span style="color: #339933;">=</span>
                <span style="color: #009900;">&#40;</span>LogDelegateFactory<span style="color: #009900;">&#41;</span> instantiate<span style="color: #009900;">&#40;</span>config.<span style="color: #006633;">getLogDelegateFactoryClassName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        org.<span style="color: #006633;">hornetq</span>.<span style="color: #006633;">core</span>.<span style="color: #006633;">logging</span>.<span style="color: #006633;">Logger</span>.<span style="color: #006633;">setDelegateFactory</span><span style="color: #009900;">&#40;</span>logDelegateFactory<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
&nbsp;
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">InputStream</span> jmsXmlStream <span style="color: #339933;">=</span> getStream<span style="color: #009900;">&#40;</span>env.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>JMS_XML_PATH_KEY<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">final</span> JMSServerConfigParser jmsServerConfigParser <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> JMSServerConfigParserImpl<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        JMSConfiguration jmsConfig<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            jmsConfig <span style="color: #339933;">=</span> jmsServerConfigParser.<span style="color: #006633;">parseConfiguration</span><span style="color: #009900;">&#40;</span>jmsXmlStream<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</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;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> getNamingException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't get jms info from xml&quot;</span>, e<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;">for</span> <span style="color: #009900;">&#40;</span>ConnectionFactoryConfiguration cfConfig <span style="color: #339933;">:</span> jmsConfig.<span style="color: #006633;">getConnectionFactoryConfigurations</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">final</span> HornetQConnectionFactory hqcf <span style="color: #339933;">=</span>
                    getHornetQConnectionFactory<span style="color: #009900;">&#40;</span>cfConfig, config.<span style="color: #006633;">getConnectorConfigurations</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: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> jndiName <span style="color: #339933;">:</span> cfConfig.<span style="color: #006633;">getBindings</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                ctx.<span style="color: #006633;">bind</span><span style="color: #009900;">&#40;</span>jndiName, hqcf<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>JMSQueueConfiguration queueConfiguration <span style="color: #339933;">:</span> jmsConfig.<span style="color: #006633;">getQueueConfigurations</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            Queue queue <span style="color: #339933;">=</span> HornetQDestination.<span style="color: #006633;">createQueue</span><span style="color: #009900;">&#40;</span>queueConfiguration.<span style="color: #006633;">getName</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: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> jndiName <span style="color: #339933;">:</span> queueConfiguration.<span style="color: #006633;">getBindings</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                ctx.<span style="color: #006633;">bind</span><span style="color: #009900;">&#40;</span>jndiName, queue<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>TopicConfiguration topicConfiguration <span style="color: #339933;">:</span> jmsConfig.<span style="color: #006633;">getTopicConfigurations</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            Topic topic <span style="color: #339933;">=</span> HornetQDestination.<span style="color: #006633;">createTopic</span><span style="color: #009900;">&#40;</span>topicConfiguration.<span style="color: #006633;">getName</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: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> jndiName <span style="color: #339933;">:</span> topicConfiguration.<span style="color: #006633;">getBindings</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                ctx.<span style="color: #006633;">bind</span><span style="color: #009900;">&#40;</span>jndiName, topic<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: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">InputStream</span> getStream<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> xmlPath<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">InputStream</span> xmlStream <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span>xmlPath<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>xmlStream <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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NamingException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cannot find resource at &lt;&quot;</span> <span style="color: #339933;">+</span> xmlPath <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&gt;&quot;</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> xmlStream<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Context</span> getContext<span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, String<span style="color: #339933;">&gt;</span> env<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> icfClassName <span style="color: #339933;">=</span> env.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>INTERNAL_ICF_IMPL_KEY<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #003399;">InitialContextFactory</span> icf <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">InitialContextFactory</span><span style="color: #009900;">&#41;</span> instantiate<span style="color: #009900;">&#40;</span>icfClassName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">//noinspection UseOfObsoleteCollectionType</span>
        <span style="color: #000000; font-weight: bold;">return</span> icf.<span style="color: #006633;">getInitialContext</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Hashtable<span style="color: #339933;">&lt;</span>object, Object<span style="color: #339933;">&gt;</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>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Instantiate the supplied class name via its 0-arg ctor.
     *
     * @param className class name to instantiate
     *
     * @return instance of className
     *
     * @throws NamingException if the class cannot be instantiated
     */</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Object</span> instantiate<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> className<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003399;">Object</span> obj<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">final</span> Class<span style="color: #339933;">&lt;?&gt;</span> klass <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">Class</span>.<span style="color: #006633;">forName</span><span style="color: #009900;">&#40;</span>className<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">final</span> Constructor<span style="color: #339933;">&lt;?&gt;</span> ctor <span style="color: #339933;">=</span> klass.<span style="color: #006633;">getConstructor</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            obj <span style="color: #339933;">=</span> ctor.<span style="color: #006633;">newInstance</span><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: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">ClassNotFoundException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> getNamingException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't find class &quot;</span> <span style="color: #339933;">+</span> className, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</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;">NoSuchMethodException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> getNamingException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't find 0-arg constructor for &quot;</span> <span style="color: #339933;">+</span> className, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</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;">InvocationTargetException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> getNamingException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't instantiate &quot;</span> <span style="color: #339933;">+</span> className, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</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;">InstantiationException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> getNamingException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't instantiate &quot;</span> <span style="color: #339933;">+</span> className, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</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;">IllegalAccessException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> getNamingException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't instantiate &quot;</span> <span style="color: #339933;">+</span> className, e<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> obj<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399;">NamingException</span> getNamingException<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> message, <span style="color: #003399;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">NamingException</span> ne <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NamingException</span><span style="color: #009900;">&#40;</span>message<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        ne.<span style="color: #006633;">initCause</span><span style="color: #009900;">&#40;</span>e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> ne<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * @param env  the env to look in
     * @param keys the keys to check for
     *
     * @throws NamingException if any key is not found in the env or if the value is null
     */</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> checkKeys<span style="color: #009900;">&#40;</span>Map<span style="color: #339933;">&lt;</span>string, String<span style="color: #339933;">&gt;</span> env, <span style="color: #003399;">String</span>... <span style="color: #006633;">keys</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> key <span style="color: #339933;">:</span> keys<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>env.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>key<span style="color: #009900;">&#41;</span> <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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NamingException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't find &quot;</span> <span style="color: #339933;">+</span> key <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; property in &quot;</span> <span style="color: #339933;">+</span> env<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: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">static</span> HornetQConnectionFactory getHornetQConnectionFactory<span style="color: #009900;">&#40;</span>ConnectionFactoryConfiguration cfConfig,
            Map<span style="color: #339933;">&lt;</span>string, TransportConfiguration<span style="color: #339933;">&gt;</span> connectorConfigurations<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">/*
         * Implementation largely lifted from JMSServerManagerImpl
         */</span>
&nbsp;
        List<span style="color: #339933;">&lt;</span>pair<span style="color: #339933;">&lt;</span>transportConfiguration, TransportConfiguration<span style="color: #339933;">&gt;&gt;</span> connectorConfigs <span style="color: #339933;">=</span>
                <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>pair<span style="color: #339933;">&lt;</span>transportConfiguration, TransportConfiguration<span style="color: #339933;">&gt;&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>Pair<span style="color: #339933;">&lt;</span>string, String<span style="color: #339933;">&gt;</span> configConnector <span style="color: #339933;">:</span> cfConfig.<span style="color: #006633;">getConnectorNames</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #003399;">String</span> connectorName <span style="color: #339933;">=</span> configConnector.<span style="color: #006633;">a</span><span style="color: #339933;">;</span>
            <span style="color: #003399;">String</span> backupConnectorName <span style="color: #339933;">=</span> configConnector.<span style="color: #006633;">b</span><span style="color: #339933;">;</span>
&nbsp;
            TransportConfiguration connector <span style="color: #339933;">=</span> connectorConfigurations.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>connectorName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>connector <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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NamingException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;No configured connector with name &lt;&quot;</span> <span style="color: #339933;">+</span> connectorName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&gt;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            logger.<span style="color: #006633;">debug</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Found connector config for &lt;&quot;</span> <span style="color: #339933;">+</span> connectorName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&gt;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            TransportConfiguration backupConnector <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>backupConnectorName <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>
                backupConnector <span style="color: #339933;">=</span> connectorConfigurations.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>backupConnectorName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
                <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>backupConnector <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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NamingException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;No configured backup connector with name &lt;&quot;</span> <span style="color: #339933;">+</span> connectorName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&gt;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
&nbsp;
                logger.<span style="color: #006633;">debug</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Found backup connector config for &lt;&quot;</span> <span style="color: #339933;">+</span> backupConnectorName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&gt;&quot;</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;">else</span> <span style="color: #009900;">&#123;</span>
                logger.<span style="color: #006633;">debug</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Not using a backup connector for main connector &lt;&quot;</span> <span style="color: #339933;">+</span> connectorName <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;&gt;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
&nbsp;
            connectorConfigs.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Pair<span style="color: #339933;">&lt;</span>transportConfiguration, TransportConfiguration<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>connector, backupConnector<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
        HornetQConnectionFactory cf <span style="color: #339933;">=</span> HornetQJMSClient.<span style="color: #006633;">createConnectionFactory</span><span style="color: #009900;">&#40;</span>connectorConfigs<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setClientID</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getClientID</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setClientFailureCheckPeriod</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getClientFailureCheckPeriod</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setConnectionTTL</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getConnectionTTL</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setCallTimeout</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getCallTimeout</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setCacheLargeMessagesClient</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">isCacheLargeMessagesClient</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setMinLargeMessageSize</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getMinLargeMessageSize</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setConsumerWindowSize</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getConsumerWindowSize</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setConsumerMaxRate</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getConsumerMaxRate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setConfirmationWindowSize</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getConfirmationWindowSize</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setProducerWindowSize</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getProducerWindowSize</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setProducerMaxRate</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getProducerMaxRate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setBlockOnAcknowledge</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">isBlockOnAcknowledge</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setBlockOnDurableSend</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">isBlockOnDurableSend</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setBlockOnNonDurableSend</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">isBlockOnNonDurableSend</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setAutoGroup</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">isAutoGroup</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setPreAcknowledge</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">isPreAcknowledge</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setConnectionLoadBalancingPolicyClassName</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getLoadBalancingPolicyClassName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setTransactionBatchSize</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getTransactionBatchSize</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setDupsOKBatchSize</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getDupsOKBatchSize</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setUseGlobalPools</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">isUseGlobalPools</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setScheduledThreadPoolMaxSize</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getScheduledThreadPoolMaxSize</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setThreadPoolMaxSize</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getThreadPoolMaxSize</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setRetryInterval</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getRetryInterval</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setRetryIntervalMultiplier</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getRetryIntervalMultiplier</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setMaxRetryInterval</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getMaxRetryInterval</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setReconnectAttempts</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getReconnectAttempts</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setFailoverOnInitialConnection</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">isFailoverOnInitialConnection</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setFailoverOnServerShutdown</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">isFailoverOnServerShutdown</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        cf.<span style="color: #006633;">setGroupID</span><span style="color: #009900;">&#40;</span>cfConfig.<span style="color: #006633;">getGroupID</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> cf<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Testing JMS code</h2>
<p>As a bonus for reading this far, here&#8217;s <code>JmsTestServerManager</code>. This class makes it easy to start and stop an embedded HornetQ server. This is ideal for testing code that reads from or writes to JMS queues or topics, for instance. You should create one instance per test class (via @BeforeClass if you&#8217;re using JUnit 4) and call start() in setup (@Before) and stop()  in teardown (@After). This means you&#8217;ll have a fresh server instance for each test. No more needing to clean up leftover messages in queues between each test! Fortunately, HornetQ stops and starts quite quickly so this is unlikely to be a performance problem for your tests.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.genius.testutil.jms</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">net.jcip.annotations.NotThreadSafe</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.api.core.TransportConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.core.config.Configuration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.core.config.impl.ConfigurationImpl</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.core.remoting.impl.invm.InVMAcceptorFactory</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.core.server.HornetQServer</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.core.server.HornetQServers</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.JMSServerConfigParser</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.JMSServerManager</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.config.JMSConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.config.JMSQueueConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.config.TopicConfiguration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.impl.JMSServerConfigParserImpl</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.hornetq.jms.server.impl.JMSServerManagerImpl</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.jetbrains.annotations.NotNull</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.jetbrains.annotations.Nullable</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.slf4j.Logger</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.slf4j.LoggerFactory</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.Context</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.InitialContext</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.NamingException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.InputStream</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.HashSet</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Set</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">/*
 * See org.hornetq.tests.util.JMSTestBase
 */</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Runs an embedded HornetQ server suitable for use in unit tests that need JMS. It should be re-used across test
 * methods; just call start() in @Before and stop() in @After.
 */</span>
@NotThreadSafe
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JmsTestServerManager <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Logger logger <span style="color: #339933;">=</span> LoggerFactory.<span style="color: #006633;">getLogger</span><span style="color: #009900;">&#40;</span>JmsTestServerManager.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> INVM_ACCEPTOR_FACTORY <span style="color: #339933;">=</span> InVMAcceptorFactory.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getCanonicalName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> DEFAULT_HORNETQ_TEST_JMS_XML <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;/hornetq-test-jms.xml&quot;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Queues to add when the server is started
     */</span>
    @NotNull
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Set<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> queueNames<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Topics to add when the server is started
     */</span>
    @NotNull
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Set<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> topicNames<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * The context passed to the jms server (proxied to prevent close()). No objects are registered in it; it is simply
     * provided to the server so that the server doesn't try to create its own.
     */</span>
    @NotNull
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">Context</span> context<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * null if the server is stopped
     */</span>
    @Nullable
    <span style="color: #000000; font-weight: bold;">private</span> JMSServerManager jmsServer<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * null if the server is stopped
     */</span>
    @Nullable
    <span style="color: #000000; font-weight: bold;">private</span> HornetQServer server<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * @param context    the context to give to the server.
     * @param queueNames set of queue names to create in the server
     * @param topicNames set of topic names to create in the server
     */</span>
    <span style="color: #000000; font-weight: bold;">private</span> JmsTestServerManager<span style="color: #009900;">&#40;</span>@NotNull <span style="color: #003399;">Context</span> context, @NotNull Set<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> queueNames,
            @NotNull Set<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> topicNames<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;">queueNames</span> <span style="color: #339933;">=</span> queueNames<span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// avoid having the server initialize its own InitialContext, and don't let it close the InitialContext</span>
        <span style="color: #666666; font-style: italic;">// since we want to keep it open across invocations</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">context</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ReadOnlyContextProxy<span style="color: #009900;">&#40;</span>context<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">topicNames</span> <span style="color: #339933;">=</span> topicNames<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * @param context      The JNDI context to pass to the server
     * @param pathToJmsXml The classpath path to the hornetq jms file to read topics and queues from
     *
     * @return a configured JmsTestServerManager in the stopped state
     */</span>
    <span style="color: #000000; font-weight: bold;">static</span> JmsTestServerManager getNew<span style="color: #009900;">&#40;</span>@NotNull <span style="color: #003399;">Context</span> context, @NotNull <span style="color: #003399;">String</span> pathToJmsXml<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">final</span> JMSConfiguration configuration <span style="color: #339933;">=</span> getJmsConfiguration<span style="color: #009900;">&#40;</span>pathToJmsXml<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> JmsTestServerManager<span style="color: #009900;">&#40;</span>context, getQueueNames<span style="color: #009900;">&#40;</span>configuration<span style="color: #009900;">&#41;</span>, getTopicNames<span style="color: #009900;">&#40;</span>configuration<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;">/**
     * Create a new InitialContext and read queues &amp; topics from the default xml path.
     *
     * @return a configured JmsTestServerManager in the stopped state
     *
     * @throws NamingException if an InitialContext can't be created
     * @see JmsTestServerManager#getNew(Context, String)
     */</span>
    <span style="color: #000000; font-weight: bold;">static</span> JmsTestServerManager getNew<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// It's ok to not close this context since we want it to be left open</span>
        <span style="color: #666666; font-style: italic;">//noinspection JNDIResourceOpenedButNotSafelyClosed</span>
        <span style="color: #000000; font-weight: bold;">return</span> getNew<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">InitialContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, DEFAULT_HORNETQ_TEST_JMS_XML<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;">/**
     * Provides access to the context used by this object to avoid needing to re-create it.
     *
     * @return the context used by this reader
     */</span>
    @NotNull
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Context</span> getContext<span style="color: #009900;">&#40;</span><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;">this</span>.<span style="color: #006633;">context</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Start the server and add all queues to it.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> start<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">server</span> <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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalStateException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Server already started&quot;</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;">this</span>.<span style="color: #006633;">server</span> <span style="color: #339933;">=</span> HornetQServers.<span style="color: #006633;">newHornetQServer</span><span style="color: #009900;">&#40;</span>createDefaultConfig<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: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">jmsServer</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> JMSServerManagerImpl<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">server</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">jmsServer</span>.<span style="color: #006633;">setContext</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">context</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">jmsServer</span>.<span style="color: #006633;">start</span><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: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> YourCustomTestException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't start JMS server&quot;</span>, e<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;">try</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> queue <span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">queueNames</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                logger.<span style="color: #006633;">debug</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Adding queue &quot;</span> <span style="color: #339933;">+</span> queue<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">jmsServer</span>.<span style="color: #006633;">createQueue</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">false</span>, queue, <span style="color: #000066; font-weight: bold;">null</span>, <span style="color: #000066; font-weight: bold;">false</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;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> topicName <span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">topicNames</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                logger.<span style="color: #006633;">debug</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Adding topic &quot;</span> <span style="color: #339933;">+</span> topicName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">jmsServer</span>.<span style="color: #006633;">createTopic</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">false</span>, topicName<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: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> YourCustomTestException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't create destination&quot;</span>, e<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Shut down the server.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> stop<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">server</span> <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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">IllegalStateException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Server not started&quot;</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;">try</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">jmsServer</span>.<span style="color: #006633;">stop</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;">this</span>.<span style="color: #006633;">server</span>.<span style="color: #006633;">stop</span><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: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> YourCustomTestException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't stop JMS server&quot;</span>, e<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;">this</span>.<span style="color: #006633;">jmsServer</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">server</span> <span style="color: #339933;">=</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: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> JMSConfiguration getJmsConfiguration<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> pathToJmsXml<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">InputStream</span> xmlStream <span style="color: #339933;">=</span> JmsTestServerManager.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span>pathToJmsXml<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>xmlStream <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;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> YourCustomTestException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't find hornetq jms xml&quot;</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;">final</span> JMSServerConfigParser jmsServerConfigParser <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> JMSServerConfigParserImpl<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        JMSConfiguration jmsConfig<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
            jmsConfig <span style="color: #339933;">=</span> jmsServerConfigParser.<span style="color: #006633;">parseConfiguration</span><span style="color: #009900;">&#40;</span>xmlStream<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</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;">Exception</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> YourCustomTestException<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Couldn't get jms info from xml&quot;</span>, e<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;">return</span> jmsConfig<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> Set<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> getTopicNames<span style="color: #009900;">&#40;</span>JMSConfiguration jmsConfig<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Set<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> topicNames <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</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>TopicConfiguration topicConfiguration <span style="color: #339933;">:</span> jmsConfig.<span style="color: #006633;">getTopicConfigurations</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            topicNames.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>topicConfiguration.<span style="color: #006633;">getName</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>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> topicNames<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> Set<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> getQueueNames<span style="color: #009900;">&#40;</span>JMSConfiguration jmsConfig<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Set<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> queueNames <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HashSet<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</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>JMSQueueConfiguration jmsQueueConfiguration <span style="color: #339933;">:</span> jmsConfig.<span style="color: #006633;">getQueueConfigurations</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            queueNames.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>jmsQueueConfiguration.<span style="color: #006633;">getName</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>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> queueNames<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> Configuration createDefaultConfig<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        Configuration configuration <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConfigurationImpl<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        configuration.<span style="color: #006633;">setSecurityEnabled</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        configuration.<span style="color: #006633;">setJMXManagementEnabled</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        configuration.<span style="color: #006633;">setPersistenceEnabled</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        configuration.<span style="color: #006633;">setFileDeploymentEnabled</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        configuration.<span style="color: #006633;">getAcceptorConfigurations</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> TransportConfiguration<span style="color: #009900;">&#40;</span>INVM_ACCEPTOR_FACTORY<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// avoid the log about using the default cluster password</span>
        configuration.<span style="color: #006633;">setClusterPassword</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;asdf&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        configuration.<span style="color: #006633;">setLogDelegateFactoryClassName</span><span style="color: #009900;">&#40;</span>SLF4JLogDelegateFactory.<span style="color: #000000; font-weight: bold;">class</span>.<span style="color: #006633;">getCanonicalName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">return</span> configuration<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>You may have noticed ReadOnlyContextProxy being used in JmsTestServerManager. That&#8217;s a rather boring Context implementation that proxies all read-only method calls to an internal Context instance and has a no-op close() implementation. This is to prevent HornetQ from closing the Context since we want to keep the Context open through all test method invocations to prevent pointlessly re-creating an InitialContext every time.</p>
<p>The rather uninteresting source of ReadOnlyContextProxy follows to save you from writing your own.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.genius.testutil.jms</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">net.jcip.annotations.NotThreadSafe</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.Binding</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.Context</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.Name</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.NameClassPair</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.NameParser</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.NamingEnumeration</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">javax.naming.NamingException</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Hashtable</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Proxies Context methods to let us control what happens to a Context that we pass in to the embedded JMS server.
 */</span>
@NotThreadSafe
<span style="color: #000000; font-weight: bold;">class</span> ReadOnlyContextProxy <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Context</span> <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;">Context</span> context<span style="color: #339933;">;</span>
&nbsp;
    ReadOnlyContextProxy<span style="color: #009900;">&#40;</span><span style="color: #003399;">Context</span> context<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;">context</span> <span style="color: #339933;">=</span> context<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> close<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// no op</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">/*
     * State-change methods not allowed. Could also no-op them if the exception becomes problematic, but
     * org.hornetq.tests.unit.util.InVMContext UOEs on many operations.
     */</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> bind<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name, <span style="color: #003399;">Object</span> obj<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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> bind<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name, <span style="color: #003399;">Object</span> obj<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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> rebind<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name, <span style="color: #003399;">Object</span> obj<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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> rebind<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name, <span style="color: #003399;">Object</span> obj<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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> unbind<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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> unbind<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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> rename<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> oldName, <span style="color: #003399;">Name</span> newName<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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> rename<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> oldName, <span style="color: #003399;">String</span> newName<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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> destroySubcontext<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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> destroySubcontext<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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;">Object</span> addToEnvironment<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> propName, <span style="color: #003399;">Object</span> propVal<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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;">Object</span> removeFromEnvironment<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> propName<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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;">Context</span> createSubcontext<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</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;">Context</span> createSubcontext<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">UnsupportedOperationException</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">/*
     * Read-only methods left alone.
     */</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> NamingEnumeration<span style="color: #339933;">&lt;</span>nameClassPair<span style="color: #339933;">&gt;</span> list<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">list</span><span style="color: #009900;">&#40;</span>name<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> NamingEnumeration<span style="color: #339933;">&lt;</span>nameClassPair<span style="color: #339933;">&gt;</span> list<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">list</span><span style="color: #009900;">&#40;</span>name<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> NamingEnumeration<span style="color: #339933;">&lt;</span>binding<span style="color: #339933;">&gt;</span> listBindings<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">listBindings</span><span style="color: #009900;">&#40;</span>name<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> NamingEnumeration<span style="color: #339933;">&lt;</span>binding<span style="color: #339933;">&gt;</span> listBindings<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">listBindings</span><span style="color: #009900;">&#40;</span>name<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;">Object</span> lookupLink<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">lookupLink</span><span style="color: #009900;">&#40;</span>name<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;">Object</span> lookupLink<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">lookupLink</span><span style="color: #009900;">&#40;</span>name<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;">NameParser</span> getNameParser<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">getNameParser</span><span style="color: #009900;">&#40;</span>name<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;">NameParser</span> getNameParser<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">getNameParser</span><span style="color: #009900;">&#40;</span>name<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;">Name</span> composeName<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name, <span style="color: #003399;">Name</span> prefix<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">composeName</span><span style="color: #009900;">&#40;</span>name, prefix<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;">String</span> composeName<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name, <span style="color: #003399;">String</span> prefix<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">composeName</span><span style="color: #009900;">&#40;</span>name, prefix<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> Hashtable<span style="color: #339933;">&lt;?</span>, <span style="color: #339933;">?&gt;</span> getEnvironment<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">getEnvironment</span><span style="color: #009900;">&#40;</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;">Object</span> lookup<span style="color: #009900;">&#40;</span><span style="color: #003399;">Name</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">lookup</span><span style="color: #009900;">&#40;</span>name<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;">Object</span> lookup<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">lookup</span><span style="color: #009900;">&#40;</span>name<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;">String</span> getNameInNamespace<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">NamingException</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> context.<span style="color: #006633;">getNameInNamespace</span><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;">&#125;</span></pre></div></div>

<p>With these classes, you&#8217;ve got all you need to get started writing JMS code (and testing it, too).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.teamlazerbeez.com/2010/10/08/using-hornetq-without-a-separate-jndi-server/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 8.505 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-05-20 09:17:37 -->

