<?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>the higher you fly &#187; programming</title>
	<atom:link href="http://mikemclean.ca/wp/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://mikemclean.ca/wp</link>
	<description></description>
	<lastBuildDate>Tue, 22 Nov 2011 23:33:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Test that camel route</title>
		<link>http://mikemclean.ca/wp/2009/05/22/test-that-camel-route/</link>
		<comments>http://mikemclean.ca/wp/2009/05/22/test-that-camel-route/#comments</comments>
		<pubDate>Sat, 23 May 2009 04:02:14 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[camel]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=245</guid>
		<description><![CDATA[You might want to get a bit of context by reading the 2 first parts of this series. This time, I&#8217;ll show you how a route is tested by using mock producers and consumers and setting up the expectations. As I always remind the team, this is unit testing, not integration testing. At this point,]]></description>
			<content:encoded><![CDATA[<p>You might want to get a bit of context by reading the 2 <a href="http://mikemclean.ca/muse/2009/05/apache-camel-3-words-wow/">first</a> <a href="http://mikemclean.ca/muse/2009/05/a-bit-more-meat-camel-applied-jms-to-file/">parts</a> of this series.</p>
<p>This time, I&#8217;ll show you how a route is tested by using mock producers and consumers and setting up the expectations. As I always remind the team, this is unit testing, not integration testing. At this point, we need to trust that the Camel team has properly tested all it&#8217;s components. What we want to do is check that 1) our route is routing messages to the proper endpoints, and 2) our enrichers or filters are kicking in properly.</p>
<p>To better understand the rest of this post, reading through <a href="http://camel.apache.org/testing.html" target="_blank">this</a> might be usefull.</p>
<h2>Route Builder modifications</h2>
<p>In the previous example, I had hard coded all route and processor information directly into the RouteBuilder implementation.</p>
<p>Obviously, this won&#8217;t cut it if we want to test. So the first thing we want to do is externalize the routeconfiguration information to a class (backed by an interface. You&#8217;ll se why later).</p>
<pre class="java" name="code">
class MyRouteBuilder extends RouteBuilder {

private IRouteBuilderConiguration config;

@Override
public void configure() throws Exception {
errorHandler(
deadLetterChannel(config.getDlqEndpointUrl()).
delay(config.getErrorHandlerDelay()).
maximumRedeliveries(config.getErrorHandlerRetries())
);

from(config.getSourceEndpointUrl()).
choice().
   when(config.getMessageFilter()).
     process(config.getMessageEnricher()).to(config.getMessageEndpointUrl()).
   otherwise().to(config.getErrorEndpointUrl());
}

}
</pre>
<p>What&#8217;s missing here is a concrete implementation of the IRouteBuilderConfiguration interface. It would look something like:</p>
<pre class="java" name="code">
public class MyRouteBuilderConfiguration implements IRouteBuilderConfiguration {
    public String getMessageEndpointUrl() {
        return ....
    }
    ....
}
</pre>
<p>I used spring to inject the configuration into the builder, but you can use whatever you want.</p>
<pre class="xml" name="code">
&lt;bean id="myRouteBuilder" class="default.MyRouteBuilder"&gt;
&lt;property name="configuration"&gt;
  &lt;bean class="default.MyRouteBuilderConfiguration"&gt;
    &lt;property name="messageFilter" ref="myFilter"/&gt;
    &lt;property name="messageEnricher" ref="myEnricher"/&gt;
  &lt;/bean&gt;
&lt;/property&gt;
&lt;/bean&gt;
</pre>
<h2>Test class</h2>
<p>Once that&#8217;s done, then it&#8217;s simply a case of following what&#8217;s in the Camel testing example page with a few variations.</p>
<ul>
<li>Overide the createRouteBuilder() method, but make sure to send back your own implementation</li>
<li>Inject a different IRouteBuilderConfiguration implementation which uses mock and direct endpoints.</li>
</ul>
<p>For example:</p>
<pre class="java" name="code">
public class TestMessageRouter extends CamelTestSupport {
   private static final String SOURCE_COMPONENT_URL = "direct:start";
   private static final String DLQ_COMPONENT_URL = "mock:dlq";
   private static final String INVALID_COMPONENT_URL = "mock:invalid";
   private static final String ENDPOINT_URL = "mock:endpoint";

   @EndpointInject(uri = DLQ_COMPONENT_URL)
   protected MockEndpoint dlqEndpoint;

   @EndpointInject(uri = INVALID_COMPONENT_URL)
   protected MockEndpoint invalidEndpoint;

   @EndpointInject(uri = ENDPOINT_URL)
   protected MockEndpoint endpoint;

   @Produce(uri= SOURCE_COMPONENT_URL)
   protected ProducerTemplate producerTemplate;

   public void testMessageOk() throws Exception {
     producerTemplate.sendBodyAndHeaders("a", getValidHeaders());

     invalidEndpoint.expectedMessageCount(0);
     dlqEndpoint.expectedMessageCount(0);
     endpoint.expectedMessageCount(1);

     dlqEndpoint.assertIsSatisfied();
     invalidEndpoint.assertIsSatisfied();
     endpoint.assertIsSatisfied();

     Message inMessage = endpoint.getReceivedExchanges().get(0).getIn();
     Assert.assertEquals("a", inMessage.getBody());
  }

  public void testWithInvalidBodyType() throws Exception {
     Map&lt;String, Object&gt; headers =createValidHeaders();
     producerTemplate.sendBodyAndHeaders(Integer.valueOf(1), headers);

     invalidEndpoint.expectedMessageCount(1);
     endpoint.expectedMessageCount(0);
     dlqEndpoint.expectedMessageCount(0);

     dlqEndpoint.assertIsSatisfied();
     invalidEndpoint.assertIsSatisfied();
     endpoint.assertIsSatisfied();
  }

  @Override
  protected RouteBuilder createRouteBuilder() throws Exception {
     MyRouteBuilder builder = new MyRouteBuilder();
     builder.setConfiguration(new TestRunnerRouteConfiguration());
     return builder;
  }

  class TestRunnerRouteConfiguration implements IRouteBuilderConfiguration {
     public Endpoint getMessageEndpoint() {
        return endpoint;
     }
     public String getDLQCompomentUrl() {
        return DLQ_COMPONENT_URL;
     }
     public String getInvalidMessageComponentUrl() {
       return INVALID_COMPONENT_URL;
     }
     public String getSourceComponentUrl() {
       return SOURCE_COMPONENT_URL;
     }
      ....
  }
}
</pre>
<p>The example isn&#8217;t complete, but it does give a good idea of what can be done. The learning curve isn&#8217;t extremely steep with Camel, but it&#8217;s there and you most likely won&#8217;t pickup all the concepts immediately. We&#8217;re not talking weeks and days, just a few hours.</p>
<p>I guess that covers it for now. I&#8217;ll be looking to setup a Component that can publish to Tumblr, just as an excersise, so if I get around to that, I&#8217;ll post the results here.</p>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2009/05/22/test-that-camel-route/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A bit more meat: Camel applied : JMS to File</title>
		<link>http://mikemclean.ca/wp/2009/05/13/a-bit-more-meat-camel-applied-jms-to-file/</link>
		<comments>http://mikemclean.ca/wp/2009/05/13/a-bit-more-meat-camel-applied-jms-to-file/#comments</comments>
		<pubDate>Wed, 13 May 2009 23:09:03 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[camel]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=216</guid>
		<description><![CDATA[As mentionned before, here is the use case: Listen on a queue for new messages Validate that the message is properly formed (has a body and has the proper headers) Save the content to a file (file name is in one of the headers) Spring configuration &#60;bean id="myRouteBuilder" class="default.MyRouteBuilder"/&#62; &#60;bean id="myFilter" class="default.MyMessageFilter"/&#62; &#60;bean id="myEnricher" class="default.MyMessageEnricher"/&#62;]]></description>
			<content:encoded><![CDATA[<p>As mentionned before, here is the use case:</p>
<ol>
<li>Listen on a queue for new messages</li>
<li>Validate that the message is properly formed (has a body and has the proper headers)</li>
<li>Save the content to a file (file name is in one of the headers)</li>
</ol>
<p><a href="http://mikemclean.ca/muse/wp-content/uploads/2009/05/flow.png"><img class="alignnone size-full wp-image-219" title="flow" src="http://mikemclean.ca/muse/wp-content/uploads/2009/05/flow.png" alt="" width="500" height="233" /></a></p>
<h2><strong>Spring configuration</strong></h2>
<pre class="xml">&lt;bean id="myRouteBuilder" class="default.MyRouteBuilder"/&gt;
    &lt;bean id="myFilter" class="default.MyMessageFilter"/&gt;
    &lt;bean id="myEnricher" class="default.MyMessageEnricher"/&gt;

    &lt;camel:camelContext id="myCamelContext"&gt;
    &lt;camel:routeBuilder ref="myRouteBuilder"/&gt;
    &lt;/camel:camelContext&gt;

    &lt;bean id="jms" class="org.apache.camel.component.jms.JmsComponent"&gt;
        &lt;property name="connectionFactory"&gt;
        &lt;bean class="org.apache.activemq.ActiveMQConnectionFactory"&gt;
             &lt;property name="brokerURL" value="tcp://localhost:61616"/&gt;
        &lt;/bean&gt;
    &lt;/property&gt;
&lt;/bean&gt;</pre>
<p>The important bean here is the camelContext bean. The RouteBuilder refered to will be initialized (by calling up the configure() method on it) when the spring container gets initialized.</p>
<p>The &#8216;jms&#8217; bean is used to configure the JMS component which can be refered to by name inside the route builder.</p>
<p>The 2 other beans (myEnricher and myFilter) are simply used by the route builder. A spring bean lookup is used to get a handle on these from the router.</p>
<p><strong><em>1 gotcha</em></strong><strong>:</strong> My ide (Eclipse) was giving me a lot of greif over the suggested namespace setup. Save yourself some trouble, and save the camel-spring.xsd offline  and change your namesapce declaration to something like:</p>
<pre class="xml">&lt;beans xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://camel.apache.org/schema/spring classpath:META-INF/camel-spring.xsd"&gt;</pre>
<p>The RouteBuilder</p>
<p>This is where you build the Came routing for any messages. In this case, remember that we want to route incoming queue messages to a file (1 file per message). Ideally, any messages we can&#8217;t deal with and where there is an error in processing the message would be put into a DLQ, and any invalid messages would be put onto another queue.</p>
<p>public class MyRouteBuilder extends RouteBuilder implements ApplicationContextAware {<br />
private ApplicationContext context;</p>
<pre class="java">@Override
public void configure() throws Exception {
    Predicate messageFilter = (Predicate) context.getBean("myFilter");
    Processor contentEnricher = (Processor) context.getBean("myEnricher");

    errorHandler(
       deadLetterChannel("jms:queue:my.dlq").
       delay(2000).
       maximumRedeliveries(5)
    );

    from("jms:queue:my.queue").
    choice().when(messageFilter).process(contentEnricher).to("file://var/tmp").
    otherwise().to("jms:queue:my.queue.invalid");
}</pre>
<p>Explanation:</p>
<ul>
<li>The first section is a simple error handler that will force a message to a DLQ in the event of an exception. A lot more can be done, but this is all I needed</li>
<li>Second we define the source compoment: &#8220;jms:&#8221; refers to the &#8220;jms&#8221; bean in the spring containter. Had we named that bean &#8220;activemqconnection&#8221; we would have used &#8220;activemqconnection:queue:my.queue&#8221; instead.</li>
<li>We then apply a filter (implements Predicate) to determine if our message is valid (in my case, I check for specific header values). If the Predicate returns false, then we route the message to another queue.</li>
<li>If the predicate passes, the message is stored in the /var/tmp directory. Specifically, for the Camel File component, the myEnricher bean takes care of setting a special header called CamelFileName which tells the component which name to give the saved file. Had that header not been present, the file would have been saved with a defaulting mechanism. An alternative would have been to use the ?fileName option in the component url (file://var/tmp?fileName=xxxxxx). See the docs for the File2 compoment.</li>
</ul>
<h2>Other classes</h2>
<p>This isn&#8217;t super interesting, but it gives an idea how simple it is to setup a content enricher (which is really jsut a process) and a filter (Predicate)</p>
<p><strong>Enricher</strong></p>
<p>A note: This could have been done using the Camel DSL language, but I prefered to bring it out.</p>
<pre class="java">public class MyMessageEnricher implements Processor {
    private static final Logger logger = LogManager.getLogger(MyMessageEnricher.class);

    public void process(Exchange exchange) throws Exception {
       if (logger.isTraceEnabled()) {
            logger.trace("Enriching received message");
       }

    String fileName = (String) exchange.getIn().getHeader("fileName");
    exchange.getIn().setHeader(Exchange.FILE_NAME, fileName);

    if (logger.isTraceEnabled()) {
        logger.trace("Enriched content header: " + exchange.getIn().getHeader(Exchange.FILE_NAME).toString());
    }
  }
}</pre>
<p><strong>Filter</strong></p>
<p>(This also could have been implemented using the DSL)</p>
<pre class="java">public class MyMessageFilter implements Predicate {
    private static final Logger logger = LogManager.getLogger(MyMessageFilter.class);

    public boolean matches(Exchange exchange) {
        if (logger.isTraceEnabled()) {
           logger.trace("Excecuting message filter");
        }

       Message in = exchange.getIn();
          for (String header : MyMessageHeaderKeys.MANDATORY_HEADERS) {
             if (in.getHeader(header) == null) {
                logger.warn("Filtering out message because of missing header: " + header);
                return false;
             }
          }

          if (in.getBody() == null) {
             logger.warn("Filtering out message because there is no content");
             return false;
          }

          if (logger.isTraceEnabled()) {
              logger.trace("Message was found to be valid. Continuing route");
          }
          return true;
      }
}</pre>
<p>Next post, I&#8217;ll explain what brings all this together. The test cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2009/05/13/a-bit-more-meat-camel-applied-jms-to-file/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Object oriented supremacy</title>
		<link>http://mikemclean.ca/wp/2009/04/21/object-oriented-supremacy/</link>
		<comments>http://mikemclean.ca/wp/2009/04/21/object-oriented-supremacy/#comments</comments>
		<pubDate>Tue, 21 Apr 2009 23:40:13 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=196</guid>
		<description><![CDATA[Good article right here. I tend to agree with most of the article. I can&#8217;t say where the industry is going, but I&#8217;m definitely getting ready. I just received Real World Haskell by the mail today, so I&#8217;ll be digging in soon. The pain he describes in the article, I&#8217;m currently going through right now.]]></description>
			<content:encoded><![CDATA[<p>Good article right <a href="http://blog.objectmentor.com/articles/2009/04/20/is-the-supremacy-of-object-oriented-programming-over" target="_blank">here</a>. I tend to agree with most of the article. I can&#8217;t say where the industry is going, but I&#8217;m definitely getting ready. I just received <a href="http://www.realworldhaskell.org" target="_blank">Real World Haskell</a> by the mail today, so I&#8217;ll be digging in soon.</p>
<p>The pain he describes in the article, I&#8217;m currently going through right now. Is FP, or a combination of OO and FP the solution, we&#8217;ll see.</p>
<blockquote><p>We’ve led ourselves down the wrong path. Or, to be more precise, we followed a single, very good path, but we didn’t know when to take a different path.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2009/04/21/object-oriented-supremacy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The jury is out &#8211; SpringContracts is s &#8211; l &#8211; o &#8211; w</title>
		<link>http://mikemclean.ca/wp/2009/03/06/the-jury-is-out-springcontracts-is-s-l-o-w/</link>
		<comments>http://mikemclean.ca/wp/2009/03/06/the-jury-is-out-springcontracts-is-s-l-o-w/#comments</comments>
		<pubDate>Sat, 07 Mar 2009 03:32:04 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[design by contract]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=179</guid>
		<description><![CDATA[Honnestly, I&#8217;m not surprised. We&#8217;ve got an aspect that hits every single method call on every object, AND it needs to do reflection and interpret through an EL. But, really; it&#8217;s friggin slow. Prohibitively slow. Painfully slow. The test There&#8217;s nothing magic in all this code. It&#8217;s only an interface where the contracts are defined,]]></description>
			<content:encoded><![CDATA[<p>Honnestly, I&#8217;m not surprised. We&#8217;ve got an aspect that hits every single method call on every object, AND it needs to do reflection and interpret through an EL.</p>
<p>But, really; it&#8217;s friggin slow. Prohibitively slow. Painfully slow.</p>
<p><strong>The test</strong></p>
<p>There&#8217;s nothing magic in all this code. It&#8217;s only an interface where the contracts are defined, a bogus implementation and a test class containing two test methods. The first method uses nothing at all (straight objects with no contracts), and the second method uses the full burito.</p>
<p><em>First thing was the interface</em></p>
<pre class="java" name="code">
public interface IPersonManager {
   @Precondition( condition = "arg1 &gt; 0" )
   @Postcondition(condition="not empty return and return.id &gt; 0")
   public Person getPerson(int id);

   @Postcondition(condition="not empty return")
   public List&lt;Person&gt; getAll();

   @Precondition(bindArgs="arg1=person", condition = "not empty person and person.id &lt; 1")
   @Postcondition(condition="not empty return and return.id &gt; 0")
   public Person insert(Person person);

   @Precondition(bindArgs="arg1=person", condition = "not empty person and person.id &gt; 0")
   @Postcondition(condition="not empty return and return.id &gt; 0")
   public Person update(Person person);

   @Precondition(bindArgs="arg1=person", condition = "not empty person and person.id &gt; 0")
   public void delete(Person person);
}
</pre>
<p><em>And a simple bogus implementation</em></p>
<pre class="java" name="code">
public class PersonManagerImpl implements IPersonManager {
   public void delete(Person person) {
   }

   public List&lt;Person&gt; getAll() {
      List&lt;Person&gt; list = new ArrayList&lt;Person&gt;();
      list.add(new Person());
      return list;
   }

   public Person getPerson(int id) {
      Person p = new Person();
      p.setId(id);
      p.setFirstName("Mike");
      p.setLastName("McLean");
      return p;
   }

   public Person insert(Person person) {
      Person p = new Person();
      p.setId(3);
      p.setFirstName("Mike");
      p.setLastName("McLean");
      return p;
   }

   public Person update(Person person) {
      return person;
   }
}
</pre>
<p><em>The spring configuration</em></p>
<pre class="xml" name="code">

<aop:aspectj-autoproxy/> 

<aop:config>
	<aop:aspect ref="contractValidationAspect">
		<aop:pointcut id="allMethods" expression="execution(* *(..))"/>
			<aop:around pointcut-ref="allMethods" method="validateMethodCall"/>
     	</aop:aspect>
  	</aop:config> 

	<bean id="contractValidationAspect" class="org.springcontracts.dbc.interceptor.ContractValidationInterceptor"/> 

	<bean id="personManager" class="com.stw.sandbox.contracts.PersonManagerImpl"/>
</pre>
<p><em>And finally the test class:</em></p>
<pre class="java" name="code">
@Test
	public void testWithNoContracts() throws Exception {
		IPersonManager manager = new PersonManagerImpl();

		long start = System.currentTimeMillis();
		loopAFewTimes(manager);
		long end = System.currentTimeMillis();

		System.out.println("No spring, no contracts: " + ((end - start) / 1000) + " seconds and " + (end - start)  + " millis.");
	}

	@Test
	public void testWithContracts() throws Exception {
		ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
		IPersonManager manager = (IPersonManager)  context.getBean("personManager");

		long start = System.currentTimeMillis();
		loopAFewTimes(manager);
		long end = System.currentTimeMillis();

		System.out.println("Full enchilada: " + ((end - start) / 1000) + " seconds and " + (end - start)  + " millis.");
	}

	public void loopAFewTimes(IPersonManager manager) {
		for (int x = 0; x < 10000; x++) {
			manager.getPerson(1);
			manager.getAll();

			Person personInsert = new Person();
			personInsert.setId(0);

			manager.insert(personInsert);

			Person personUpdate = new Person();
			personUpdate.setId(2);
			manager.update(personUpdate);

			manager.delete(personUpdate);
		}
	}
</pre>
<p><strong>The results</strong></p>
<p>No spring, no contracts: 0 seconds or 14 millis.<br />
Full enchilada: 24 seconds or 24792 millis.</p>
<p>Now, I understand that this is not scientific, bordering on stupid and unprofessional, but still. Across 10000 loops ....! Nuff said.</p>
<p>I'd seriously have to re-consider using this in anything that has any need for performance. I might consider it for a low-traffic data entry site, but nothing much more. I haven't tried other implementations, so this might not be fair towards the whole DBC community. </p>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2009/03/06/the-jury-is-out-springcontracts-is-s-l-o-w/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Design by contract musings</title>
		<link>http://mikemclean.ca/wp/2009/03/05/design-by-contract-musings/</link>
		<comments>http://mikemclean.ca/wp/2009/03/05/design-by-contract-musings/#comments</comments>
		<pubDate>Fri, 06 Mar 2009 02:07:57 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[design by contract]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=177</guid>
		<description><![CDATA[A colleague of mine introduced me to the Design By Contract implementation done for Spring called SpringContracts. It&#8217;s gotten me looking at it for the last couple days. It&#8217;s most definitely an interesting concept, so I brought it up to the rest of the guys at work to find out what they thought. The biggest]]></description>
			<content:encoded><![CDATA[<p>A colleague of mine introduced me to the <a href="http://en.wikipedia.org/wiki/Design_by_contract" target="_blank">Design By Contract</a> implementation done for Spring called <a href="http://springcontracts.sourceforge.net/home.html" target="_blank">SpringContracts</a>. It&#8217;s gotten me looking at it for the last couple days. It&#8217;s most definitely an interesting concept, so I brought it up to the rest of the guys at work to find out what they thought.</p>
<p>The biggest concerns were:</p>
<p><strong>1) Binds you to Spring</strong> (if you use SpringContacts):</p>
<p>No big deal here. We&#8217;re already fully invested into Spring.  Either way, I don&#8217;t beleive in complete de-coupling of technology. If you&#8217;re using a technology and investing time and man-power into it, you had better make the most of it. I reject the idea that putting Spring specific annotations in your code is bad practice (in my current environment at least)</p>
<p><strong>2) Need to learn a new technology/language</strong></p>
<p>Again, I have a lot of trouble with this. Do we need to always stay at the lowest denominator just to satisfy the ones who refuse to learn? I beleive that enthousiasm for something new and teams that are willing to teach and share their knowledge don&#8217;t mind these types of additions, especially if they get something out of it. Luckily, I work with that type of team (they really are friggin great!)</p>
<p>There&#8217;s a good discussion about that very subject <a href="http://weblog.raganwald.com/2008/06/little-something-about-dumbing-code.html" target="_blank">here</a>.</p>
<p><strong>3) AOP + Introspection = Lowered performance</strong></p>
<p>Yup. Absolutely. If this thing puts a major hit on the performance of my code, then I&#8217;d have to re-consider. In my current environment, I can&#8217;t afford a big hit to performance. But in most places, having more solid, more self-documented, more bug free code is what you should strive for. An extra millisecond here or there won&#8217;t kill anyone. Remember: &#8220;<a href="http://teddziuba.com/2008/04/im-going-to-scale-my-foot-up-y.html" target="_blank">Scalability is not your problem. Getting people to give a shit is.</a>&#8221;</p>
<p>I&#8217;ll try to post some benchmarks this weekend &#8230;</p>
<p><strong>4) All this to avoid a few null checks</strong></p>
<p>EXACTLY! If I can enforce the semantics of every class that implements an interface, then I don&#8217;t need to check for those nulls and those illegal arguments. Ever. How many times do you just do that check &#8230; just in case a new implementation doesn&#8217;t do what you expect it to. With an annotated interface defining and enforcing the state of a returned object, you have cleaner and more readable code.</p>
<p>What&#8217;s important here is that Design By Contract isn&#8217;t just about fancy assertions. It&#8217;s a way to enforce the semantics of an implementing class.</p>
<p>That being said, all the Java implementations of DBC libraries have been inactive forever. That makes me think that it may have turned out to be a big shinny and temporary toy. I&#8217;d be curious to know if anyone has used this. I&#8217;m still on the fence, but the concept is definitely winner.</p>
<p>(Something to <a href="http://www.artima.com/intv/contracts2.html" target="_blank">read</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2009/03/05/design-by-contract-musings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Good quotes</title>
		<link>http://mikemclean.ca/wp/2009/02/01/good-quotes/</link>
		<comments>http://mikemclean.ca/wp/2009/02/01/good-quotes/#comments</comments>
		<pubDate>Mon, 02 Feb 2009 02:56:41 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[Quotes]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=171</guid>
		<description><![CDATA[Some of my favorites found here. Some people, when confronted with a problem, think &#8220;I know, I’ll use regular expressions.&#8221; Now they have two problems &#8211; Jamie Zawinski Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. &#8211; Rick Osborne The most]]></description>
			<content:encoded><![CDATA[<p>Some of my favorites found <a href="http://stackoverflow.com/questions/58640/great-programming-quotes/58796" target="_blank">here</a>.</p>
<ul>
<li>
<div class="post-text">
<p>Some people, when confronted with a problem, think &#8220;I know, I’ll use regular expressions.&#8221; Now they have two problems &#8211; Jamie Zawinski</p></div>
</li>
<li>Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. &#8211; Rick Osborne</li>
<li> The most exciting phrase to hear in science, the one that heralds new   discoveries, is not &#8216;Eureka!&#8217; but &#8216;That&#8217;s funny&#8230;&#8217; &#8211; Isaac Asimov</li>
<li><strong>There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult</strong></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2009/02/01/good-quotes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit testing ehcache (Take #2)</title>
		<link>http://mikemclean.ca/wp/2009/01/23/unit-testing-ehcache-take-2/</link>
		<comments>http://mikemclean.ca/wp/2009/01/23/unit-testing-ehcache-take-2/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 03:45:55 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=162</guid>
		<description><![CDATA[My solution works, but there was something smelly in there. I wasn&#8217;t satisfied with the way I was checking to ensure that the cache had actually been accessed. Given that the notification interface doesn&#8217;t define a method to find that out, I had sort of tricked it &#8230;. Well, I obviously couldn&#8217;t leave it at]]></description>
			<content:encoded><![CDATA[<p>My <a href="http://mikemclean.ca/muse/2009/01/unit-testing-ehcache/" target="_blank">solution</a> works, but there was something smelly in there. I wasn&#8217;t satisfied with the way I was checking to ensure that the cache had actually been accessed. Given that the notification <a href="http://ehcache.sourceforge.net/apidocs/net/sf/ehcache/event/CacheEventListener.html" target="_blank">interface</a> doesn&#8217;t define a method to find that out, I had sort of tricked it &#8230;.</p>
<p>Well, I obviously couldn&#8217;t leave it at that. So the solution to a better smelling cache unit test lies below (tip: use the <a href="http://ehcache.sourceforge.net/apidocs/net/sf/ehcache/Statistics.html" target="_blank">Statistics</a> information that&#8217;s right there on the cache, but I hadn&#8217;t noticed)</p>
<pre class="java" name="code">import junit.framework.Assert;

@Test
public void testCache() throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
    DataFacade dataFacade = (DataFacade) context.getBean("cacheInjectedDataFacade");

    TestCacheListener listener = new TestCacheListener();
    Cache cache = dataFacade.getCache();
    cache.getCacheEventNotificationService().registerListener(listener);

    dataFacade.getData();
    Assert.assertEquals(ListenerStatus.ELEMENT_ADDED, listener.getLastStatus());
    Assert.assertNotNull(cache.get(DataFacade.CACHE_KEY));

    listener.resetLastStatus();
    Assert.assertEquals(listener.getLastStatus(), ListenerStatus.RESET);

    dataFacade.getData();
    Assert.assertEquals(1, cache.getStatistics().getCacheHits());

    Thread.sleep(2500);
    dataFacade.getData();
    Assert.assertEquals(ListenerStatus.ELEMENT_ADDED, listener.getLastStatus());
}
</pre>
<p><strong>Also, remember to reset your cache through cache.removeAll() between tests (through the @BeforeTest) or else your cache hits won&#8217;t jive.<br />
</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2009/01/23/unit-testing-ehcache-take-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit testing ehcache</title>
		<link>http://mikemclean.ca/wp/2009/01/17/unit-testing-ehcache/</link>
		<comments>http://mikemclean.ca/wp/2009/01/17/unit-testing-ehcache/#comments</comments>
		<pubDate>Sun, 18 Jan 2009 02:33:00 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=149</guid>
		<description><![CDATA[I just had to write some unit tests to make sure my caching mechanism was working properly. Obviously, there are better ways to do this, but for what I needed, it was ample. Any suggestions are definitely welcome. Setup We&#8217;ll start with a simple service class in which all caching manipulations are done from. The]]></description>
			<content:encoded><![CDATA[<p>I just had to write some unit tests to make sure my caching mechanism was working properly. Obviously, there are better ways to do this, but for what I needed, it was ample. Any suggestions are definitely welcome.</p>
<p><strong>Setup</strong></p>
<p>We&#8217;ll start with a simple service class in which all caching manipulations are done from. The class is kept simple so as to not obfuscate what I&#8217;m really trying to show.</p>
<pre class="java" name="code">
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

public class DataFacade {
    private static final String CACHE_KEY = "mykey";

    private Cache cache;

    public String getData() {
        Element element = cache.get(CACHE_KEY);
        if (element != null &amp;&amp; element.getValue() != null) {
            return (String) element.getValue();
        } else {
            String data = "lama";
            cache.put(new Element(CACHE_KEY, data));
            return data;
        }
    }

    public Cache getCache() {
        return cache;
    }

    public void setCache(Cache cache) {
        this.cache = cache;
    }
}
</pre>
<p><strong>Spring Setup</strong></p>
<p>Now, we need to write a test to ensure that the cache is being hit and expired properly. To do this, we&#8217;ll need to setup a test listener that will be injected into the Cache object used by the service class. Using spring, this is pretty easy, but we can also hand code it.</p>
<p>We&#8217;ll need a spring context configuration file somewhere in the classpath.</p>
<pre class="xml" name="code">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans&gt;
    &lt;bean id="cacheInjectedDataFacade" class="org.mikem.DataFacade"&gt;
        &lt;property name="cache" ref="cache"/&gt;
    &lt;/bean&gt;

    &lt;bean id="cacheManager"
          class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"&gt;
        &lt;property name="configLocation" value="classpath:ehcache-config.xml"/&gt;
    &lt;/bean&gt;

    &lt;bean id="cache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"&gt;
        &lt;property name="cacheManager"&gt;
            &lt;ref local="cacheManager"/&gt;
        &lt;/property&gt;
        &lt;property name="timeToIdle" value="2"/&gt;
        &lt;property name="timeToLive" value="2"/&gt;
        &lt;property name="eternal" value="false"/&gt;
        &lt;property name="diskPersistent" value="false"/&gt;
        &lt;property name="cacheName" value="org.mikem.lamacache"/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</pre>
<p>The things to watch out for here are:</p>
<ul>
<li>We&#8217;re not using a ehcache.xml confguration file. All config is done through spring.</li>
<li>The package names should be changed to reflect where your own DataFacade is</li>
<li>Notice the timeToIdel and timeToExpire properties on the cache bean. More on that later</li>
</ul>
<p><b>Unit test and the cache event listener</b></p>
<p>Now we&#8217;re ready to write the unit test related code. We&#8217;ll first need an implementation of the net.sf.ehcache.event.CacheEventListener interface. That implementation should look like the following:</p>
<pre class="java" name="code">
public class TestCacheListener implements CacheEventListener {
    public static enum ListenerStatus {
         RESET,
         DISPOSED, ELEMENT_EVICTED, ELEMENT_EXPIRED, ELEMENT_ADDED,
         ELEMENT_REMOVED, ELEMENT_UPDATED, REMOVED_ALL,
    };

    public ListenerStatus lastStatus;

    public ListenerStatus getLastStatus() {
        return this.lastStatus;
    }

    public void resetLastStatus() {
       this.lastStatus = ListenerStatus.RESET;
    }

    public void dispose() {
        this.lastStatus = ListenerStatus.DISPOSED;
    }

    public void notifyElementEvicted(Ehcache arg0, Element arg1) {
       this.lastStatus = ListenerStatus.ELEMENT_EVICTED;
    }

    public void notifyElementExpired(Ehcache arg0, Element arg1) {
        this.lastStatus = ListenerStatus.ELEMENT_EXPIRED;
    }

    public void notifyElementPut(Ehcache arg0, Element arg1) throws CacheException {
        this.lastStatus = ListenerStatus.ELEMENT_ADDED;
    }

    public void notifyElementRemoved(Ehcache arg0, Element arg1) throws CacheException {
          this.lastStatus = ListenerStatus.ELEMENT_REMOVED;
    }

    public void notifyElementUpdated(Ehcache arg0, Element arg1) throws CacheException {
         this.lastStatus = ListenerStatus.ELEMENT_UPDATED;
    }

    public void notifyRemoveAll(Ehcache arg0) {
         this.lastStatus = ListenerStatus.REMOVED_ALL;
    }
}
</pre>
<p>What this gives us is a listener class which we&#8217;ll inject into the cache. On each cache event, the last status member will be updated.</p>
<p>Now for the finale:</p>
<pre class="java" name="code">
import junit.framework.Assert;
import net.sf.ehcache.Cache;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.stw.sandbox.TestCacheListener.ListenerStatus;

public class TestDataFacade {

@Test
public void testCache() throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
    DataFacade dataFacade = (DataFacade) context.getBean("cacheInjectedDataFacade");

    TestCacheListener listener = new TestCacheListener();
    Cache cache = dataFacade.getCache();
    cache.getCacheEventNotificationService().registerListener(listener);

    dataFacade.getData();
    Assert.assertEquals(ListenerStatus.ELEMENT_ADDED, listener.getLastStatus());
    Assert.assertNotNull(cache.get(DataFacade.CACHE_KEY));

    listener.resetLastStatus();
    Assert.assertEquals(listener.getLastStatus(), ListenerStatus.RESET);

    dataFacade.getData();
    Assert.assertEquals(ListenerStatus.RESET, listener.getLastStatus());

    Thread.sleep(2500);
    dataFacade.getData();
    Assert.assertEquals(ListenerStatus.ELEMENT_ADDED, listener.getLastStatus());
}
}
</pre>
<p>Explanation:</p>
<ul>
<li>Lines 14 and 15 are the spring access and retrieval of the DataFacade instance</li>
<li>Lines 17 through 19 take care of creating a new instance of the TestCacheListener and injecting it into the data facade instance</li>
<li>Line 21 runs the method where we have some cache access going on</li>
<li>Line 22: Because our last line actually put something in the cache, our cache listeners status will have changed. Here we&#8217;re making sure the status has been changed accordingly.</li>
<li>Line 23: Make sure we have data in the cache (we could also check that the content is right)</li>
<li>Line 25: Reset the last status on the listener</li>
<li>Line 28: Fetch the data once again. At this point, the listeners last status will remain to RESET since it won&#8217;t have been put into the cache anew.</li>
<li>Line 31: Because we configured our timeToIdle and timeToExpire to 2 seconds (see the spring config), we know that by sleeping 2.5 seconds, the next hit to our method will force a renewal of the cache content</li>
</ul>
<p>Voila! Obviously, you could and should expand on this, but it&#8217;s start.</p>
<p><em>[EDIT] I&#8217;ve <a href="http://mikemclean.ca/muse/2009/01/unit-testing-ehcache-take-2/" target="_blank">posted</a> an update, mainly about how to access cache hits.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2009/01/17/unit-testing-ehcache/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby callbacks</title>
		<link>http://mikemclean.ca/wp/2008/12/29/ruby-callbacks/</link>
		<comments>http://mikemclean.ca/wp/2008/12/29/ruby-callbacks/#comments</comments>
		<pubDate>Mon, 29 Dec 2008 17:47:09 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=113</guid>
		<description><![CDATA[I&#8217;ve read the books on Ruby and Rails, even programmed a few personal things, but never found a real compelling reason to use them. But I must admin that stuff like this (found through Raganwald) is uber-cool and useful. You get some of this (all?) through Groovy, but it doesn&#8217;t feel as elegant.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve read <a href="http://www.pragprog.com/titles/ruby/programming-ruby" target="_blank">the</a> <a href="http://www.pragprog.com/titles/rails3/agile-web-development-with-rails-third-edition" target="_blank">books</a> on Ruby and Rails, even programmed a few personal things, but never found a real compelling reason to use them.</p>
<p>But I must admin that stuff like <a href="http://www.khelll.com/blog/ruby/ruby-callbacks/" target="_blank">this</a> (found through Raganwald) is uber-cool and useful.</p>
<p>You get some of this (all?) through <a href="http://groovy.codehaus.org/" target="_blank">Groovy</a>, but it doesn&#8217;t feel as elegant.</p>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2008/12/29/ruby-callbacks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Arrays, what&#8217;s their point. Dito.</title>
		<link>http://mikemclean.ca/wp/2008/12/26/arrays-whats-their-point-dito/</link>
		<comments>http://mikemclean.ca/wp/2008/12/26/arrays-whats-their-point-dito/#comments</comments>
		<pubDate>Fri, 26 Dec 2008 17:29:33 +0000</pubDate>
		<dc:creator>mikem</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://mikemclean.ca/muse/?p=108</guid>
		<description><![CDATA[I agree with Damien. When I first saw the post on Reddit, I found the reaction harsh (I still think the original poster meant &#8220;why use arrays instead of lists&#8221;). As with Erlang, in Java arrays get in the way of readability. I understand arrays and the different usages, but I still prefer a List]]></description>
			<content:encoded><![CDATA[<p>I <a href="http://damienkatz.net/2008/12/arrays_whats_the_point_good_qu.html" target="_blank">agree with Damien</a>.</p>
<p>When I first saw the post on Reddit, I found the reaction harsh (I still think the original poster meant &#8220;why use arrays instead of lists&#8221;).</p>
<p>As with Erlang, in Java arrays get in the way of readability. I understand arrays and the different usages, but I still prefer a List which is inifinitely more usable.</p>
]]></content:encoded>
			<wfw:commentRss>http://mikemclean.ca/wp/2008/12/26/arrays-whats-their-point-dito/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

