<?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>.dev.blog</title>
	<atom:link href="http://techo-ecco.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://techo-ecco.com/blog</link>
	<description>developer blog</description>
	<lastBuildDate>Mon, 01 Aug 2011 04:41:39 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Spring custom annotations using context:component-scan</title>
		<link>http://techo-ecco.com/blog/spring-custom-annotations/</link>
		<comments>http://techo-ecco.com/blog/spring-custom-annotations/#comments</comments>
		<pubDate>Tue, 19 Jul 2011 10:42:57 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[Annotation]]></category>
		<category><![CDATA[context]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Reflections]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=522</guid>
		<description><![CDATA[Everyone seems to think annotations are cool and want to use them now days. A lot has been written about the pros and cons of using annotations and personally I think they should be used with caution. Mixing annotation domains to a point of total confusion, spreading configuration related meta-data across large code bases to [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/07/Scan.jpg" alt="Scan Spring custom annotations using context:component scan" align="right" width="200" title="Spring custom annotations using context:component scan" /></p>
<p>Everyone seems to think annotations are cool and want to use them now days. A lot has been written about the pros and cons of using annotations and personally I think they should be used with caution. Mixing annotation domains to a point of total confusion, spreading configuration related meta-data across large code bases to a point where refactoring becomes very hard are only some of the risks. Nevertheless, annotations are cool. </p>
<p>I wanted to add annotation functionality to some &#8220;aspect&#8221; of our code base. An aspect being an interface Foo and multiple implementations of Foo in various artifacts (e.g., FooA from project A, FooB from project B and so on). </p>
<p><span id="more-522"></span></p>
<pre class="brush: java; title: ; notranslate">
public interface Foo{
  void bar();
}
</pre>
<pre class="brush: java; title: ; notranslate">
public class FooA implements Foo{
  @Override
  public void bar(){
    System.out.println(&quot;I am number 6!&quot;);
  }
}
</pre>
<p>First thing I created a Fooish type-level (class-level) annotation</p>
<pre class="brush: java; title: ; notranslate">
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Fooish {
  boolean cool() default true;

  String[] tags() default { &quot;all&quot; };
}
</pre>
<p>Next I annotated my classes with my new Fooish annotation:</p>
<pre class="brush: java; title: ; notranslate">
@Fooish(cool=false, tags= {&quot;sixfoo&quot;})
public class FooA implements Foo{
  @Override
  public void bar(){
    System.out.println(&quot;I am number 6!&quot;);
  }
}
</pre>
<p>Meanwhile, in another Foo across the galaxy from A:</p>
<pre class="brush: java; title: ; notranslate">
@Fooish(cool=true, tags= {&quot;freefoo&quot;})
public class FooB implements Foo{
  @Override
  public void bar(){
    System.out.println(&quot;I am not a number, I am a free man!&quot;);
  }
}
</pre>
<p>I am now ready to do some classpath scanning for my Foos. At first I went a looked the <a href="http://code.google.com/p/reflections/" title="Reflections Library on Google Code" target="_blank">reflections</a> library which I have to say is quite cool. </p>
<p>I popped the maven repository and dependencies:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;repository&gt;
    &lt;id&gt;reflections-repo&lt;/id&gt;
    &lt;name&gt;Reflections Maven2 Repository&lt;/name&gt;
    &lt;url&gt;http://reflections.googlecode.com/svn/repo&lt;/url&gt;
&lt;/repository&gt;
</pre>
<pre class="brush: xml; title: ; notranslate">
&lt;dependency&gt;
  &lt;groupId&gt;org.reflections&lt;/groupId&gt;
  &lt;artifactId&gt;reflections&lt;/artifactId&gt;
  &lt;version&gt;0.9.5&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.google.collections&lt;/groupId&gt;
  &lt;artifactId&gt;google-collections&lt;/artifactId&gt;
  &lt;version&gt;1.0&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>And now I am ready to start scanning for annotations:</p>
<pre class="brush: java; title: ; notranslate">
final StopWatch sw = new StopWatch();
sw.start();
final Reflections reflections = new Reflections(&quot;org.projectx&quot;, new TypeAnnotationsScanner());
Set&lt;Class&lt;?&gt;&gt; theFoos = reflections.getTypesAnnotatedWith(Fooish.class);
sw.stop();
System.out.println(&quot;Classpath scanning took: &quot; + sw.getTime() + &quot;ms&quot;);
for (final Class&lt;?&gt; theFoo : theFoos) {
final Fooish annotation = theFoo.getAnnotation(Fooish.class);
  if (Arrays.asList(annotation.tags()).contains(&quot;freefoo&quot;)) {
     System.out.println(&quot;This foo &quot;+ theFoo.getClass().getName() + &quot;, is a free foo&quot;);
  }
}
</pre>
<p>The reflections API has much more than is shown here, the output of the scan showed:</p>
<pre class="brush: bash; title: ; notranslate">
Classpath scanning took: 1782ms
</pre>
<p>Not bad for quite a large code base, but still, incurring a 2 seconds penalty for service load time is severe a production environment where services might be candidate to frequent restarts. Continuous deployment requires it to be snappy. A side note here, you should never try to do this kind of scanning during runtime, only load time. Reflection-based operations are costly in Java. </p>
<p>Next I suddenly remembered that Spring does this kind of work when you do stuff like <strong>&lt;mvc:annotation-driven /&gt;</strong> and <strong>&lt;context:component-scan /&gt;</strong> in you bean configuration file. There&#8217;s gotta be a way to hook up into that process use it for my own good. Turns out there is.</p>
<p>Spring allows you to load your annotated classes into their container if you also annotate them with the <strong>@Component</strong> type-level annotation. So my Foos need another annotation:</p>
<pre class="brush: java; title: ; notranslate">
@Fooish(cool=true, tags= {&quot;freefoo&quot;})
@Component
public class FooB implements Foo{
  @Override
  public void bar(){
    System.out.println(&quot;I am not a number, I am a free man!&quot;);
  }
}
</pre>
<p>To load all my Foos into the Spring application context I added the following to my Spring configuration file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;context:component-scan base-package=&quot;org.projectx&quot;&gt;
  &lt;context:include-filter type=&quot;annotation&quot; expression=&quot;com.projectX.annotation.Fooish&quot; /&gt;
&lt;/context:component-scan&gt;
</pre>
<p>You can have other component scanners in the Spring configuration but this one is dedicated only to the classes annotated with <strong>@Component</strong> and <strong>@Fooish</strong>.</p>
<p>Now I want a Fooish handler which handles all instances of Fooish beans loaded to the context, I can easily do it with by implementing the <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/context/ApplicationContextAware.html" title="ApplicationContextAware javadoc" target="_blank">ApplicationContextAware</a> interface, then calling the <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/beans/factory/ListableBeanFactory.html#getBeansWithAnnotation%28java.lang.Class%29" title="getBeansWithAnnotation method javadoc" target="_blank">getBeansWithAnnotation</a> method of the <strong>ApplicationContext</strong>.</p>
<pre class="brush: java; title: ; notranslate">
public class MyFooishHandler implements ApplicationContextAware, InitializingBean {
  private ApplicationContext applicationContext;

  @Override
  public void afterPropertiesSet() throws Exception {

    final Map&lt;String, Object&gt; myFoos = applicationContext.getBeansWithAnnotation(Fooish.class);

    for (final Object myFoo : myFoos.values()) {
      final Class&lt;? extends Object&gt; fooClass = myFoo.getClass();
      final Fooish annotation = fooClass.getAnnotation(Fooish.class);
      System.out.println(&quot;Found foo class: &quot; + fooClass + &quot;, with tags: &quot; + annotation.tags());
    }
  }

  @Override
  public void setApplicationContext(final ApplicationContext applicationContext)
      throws BeansException {
    this.applicationContext = applicationContext;
  }
}
</pre>
<p>I am sure there&#8217;s some overhead here to but the up side is once I annotate my Foos with @Component I can also take advantage of other features of the Spring container and this method doesn&#8217;t require additional dependencies on the classpath assuming Spring&#8217;s already there.</p>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/spring-custom-annotations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Elasticsearch with Spring</title>
		<link>http://techo-ecco.com/blog/elasticsearch-with-spring/</link>
		<comments>http://techo-ecco.com/blog/elasticsearch-with-spring/#comments</comments>
		<pubDate>Sat, 09 Jul 2011 15:28:57 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[elasticsearch]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=290</guid>
		<description><![CDATA[Elasticsearch is a good abstraction around Lucene Search Engine and an alternative to Solr. ElasticSearch provides out of the box index distribution along with a decent JSON RESTful interface backed by a Java/Groovy API. ElasticSearch also elaborate list of modules for a variety of integrations. I wanted to integrate ElasticSearch in my Spring-based application and [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/07/ElasticSearch.jpg" alt="ElasticSearch Elasticsearch with Spring" align="right" width="250" title="Elasticsearch with Spring" /></p>
<p><a href="http://www.elasticsearch.org/" target="blank">Elasticsearch</a> is a good abstraction around Lucene Search Engine and an alternative to Solr. ElasticSearch provides out of the box index distribution along with a decent JSON RESTful interface backed by a Java/Groovy API. ElasticSearch also  elaborate list of <a href="http://www.elasticsearch.org/guide/reference/modules/" title="ElasticSearch Modules" target="_blank">modules</a> for a variety of integrations.</p>
<p>I wanted to integrate ElasticSearch in my Spring-based application and a factory/configuration abstraction came to mind.</p>
<p>A an embedded node within a cluster can be instantiated and used to execute requests against the distributed index. It deserves its own factory bean since it has lifecycle management operations and configuration associated with it. Note that configLocation can be provided along with local map of settings, if neither are provided elasticsearch will looks for its configuration files in the working directory or a &#8220;config&#8221; subdirectory. The local property can also be set (overridable via system property for unit tests). </p>
<p><span id="more-290"></span></p>
<pre class="brush: xml; title: ; notranslate">
    &lt;bean
        class=&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;&gt;
        &lt;property name=&quot;systemPropertiesModeName&quot; value=&quot;SYSTEM_PROPERTIES_MODE_OVERRIDE&quot; /&gt;
        &lt;property name=&quot;searchSystemEnvironment&quot; value=&quot;true&quot; /&gt;
        &lt;property name=&quot;locations&quot;&gt;
            &lt;list&gt;
                &lt;value&gt;classpath*:**/elasticsearch.properties&lt;/value&gt;
            &lt;/list&gt;
        &lt;/property&gt;
        &lt;property name=&quot;properties&quot;&gt;
            &lt;props&gt;
                &lt;prop key=&quot;projectx.index.dir&quot;&gt;/var/tmp/index&lt;/prop&gt;
                &lt;prop key=&quot;projectx.index.dir.create&quot;&gt;true&lt;/prop&gt;
                &lt;prop key=&quot;projectx.index.name&quot;&gt;projectx&lt;/prop&gt;
            &lt;/props&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;esNode&quot;
        class=&quot;org.projectx.elasticsearch.ElasticsearchNodeFactoryBean&quot;&gt;
        &lt;property name=&quot;configLocation&quot;
            value=&quot;classpath:org/projectx/elasticsearch/elasticsearch.properties&quot; /&gt;
    &lt;/bean&gt;
</pre>
<p>Once we have an ElasticSearch <strong>Node</strong> at hand we can start performing operations on the distributed index. However for the majority of the data access a Template style class could be handy:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;bean id=&quot;esNodeTemplate&quot; class=&quot;org.projectx.elasticsearch.NodeTemplate&quot;&gt;
        &lt;constructor-arg ref=&quot;esNode&quot; /&gt;
        &lt;constructor-arg value=&quot;${projectx.index.name}&quot; /&gt;
    &lt;/bean&gt;
</pre>
<p>To display how the template get&#8217;s use you can look at the intergration test base class:</p>
<pre class="brush: java; title: ; notranslate">
public class ElasticsearchTestBase {

  @Resource
  NodeTemplate nodeTemplate;

  @Before
  public void before() {
    if (!nodeTemplate.indexExists()) {

      nodeTemplate.executeGet(new NodeCallback&lt;CreateIndexResponse&gt;() {

        @Override
        public ActionFuture&lt;CreateIndexResponse&gt; execute(final IndicesAdminClient admin) {
          return admin.create(Requests.createIndexRequest(nodeTemplate.getIndexName()));
        }
      });
    }
  }

  @After
  public void after() {
    nodeTemplate.deleteIndex();
  }

  protected void refreshIndex() {
    nodeTemplate.refreshIndex();
  }

  protected void flushIndex() {
    nodeTemplate.flushIndex();
  }

  protected IndexResponse index(final XContentBuilder content) {
    final IndexResponse response = nodeTemplate.executeGet(new ClientCallback&lt;IndexResponse&gt;() {

      @Override
      public ActionFuture&lt;IndexResponse&gt; execute(final Client client) {
        final IndexRequest request = Requests.indexRequest(nodeTemplate.getIndexName())
                                             .source(content).type(&quot;log&quot;);
        return client.index(request);
      }
    });
    assertNotNull(&quot;response is null&quot;, response);
    return response;
  }

  protected &lt;Q&gt; List&lt;SearchHit&gt; search(final String field, final Q value, final int maxResults) {
    return nodeTemplate.search(field, value, maxResults);
  }

}
</pre>
<p>An then the actual test:</p>
<pre class="brush: java; title: ; notranslate">

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { &quot;classpath:org/projectx/elasticsearch/applicationContext-elasticsearch.xml&quot; })
public class ElasticSearchIntegrationTest extends ElasticsearchTestBase {

  @Test
  public void testIndex() throws Exception {

    final Collection&lt;File&gt; files = Collections.singletonList(new File(
        &quot;src/test/resources/othello1-1.txt&quot;));

    int totalDocs = 0;
    for (final File file : files) {
      @SuppressWarnings(&quot;unchecked&quot;)
      final List&lt;String&gt; lines = FileUtils.readLines(file, &quot;UTF-8&quot;);

      int lineNumber = 1;
      for (final String line : lines) {
        indexLine(file, line, lineNumber);
        lineNumber++;
        totalDocs++;
      }
    }

    refreshIndex();

    final List&lt;SearchHit&gt; hits = search(&quot;rownum&quot;, 1, 100);

    assertEquals(&quot;incorrect number of results&quot;, 1, hits.size());
  }

  private void indexLine(final File file, final String line, final int rownum) throws Exception {
    final XContentBuilder jsonBuilder = XContentFactory.jsonBuilder();
    jsonBuilder.startObject();
    jsonBuilder.field(&quot;rownum&quot;, rownum);
    jsonBuilder.field(&quot;path&quot;, file.getAbsolutePath());
    jsonBuilder.field(&quot;modified&quot;, file.lastModified());
    jsonBuilder.field(&quot;contents&quot;, line);
    jsonBuilder.endObject();

    index(jsonBuilder);
  }
</pre>
<p>This provides an good application-layer abstraction around dealing with nodes and a good integration to the Spring container.</p>
<p>ElasticSearch Spring integration is on <a href="https://github.com/erezmazor/projectx/tree/master/org.projectx.elasticsearch" title="ElasticSearch Spring Integration on GitHub" target="_blank">GitHub</a></p>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/elasticsearch-with-spring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Leader Election with Zookeeper</title>
		<link>http://techo-ecco.com/blog/leader-election-with-zookeeper/</link>
		<comments>http://techo-ecco.com/blog/leader-election-with-zookeeper/#comments</comments>
		<pubDate>Sat, 09 Jul 2011 11:44:51 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[leader election]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[zokeeper]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=474</guid>
		<description><![CDATA[Recently I had to implement an active-passive redundancy of a singleton service in our production environment where the general rule is always have &#8220;more than one of anything&#8221;. The main motivation is to alleviate the need to manually monitor and manage these services, whose presence is crucial to the overall health of the site. This [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/07/Zoo.jpg" alt="Zoo Leader Election with Zookeeper" align="right" width="250" title="Leader Election with Zookeeper" /></p>
<p>Recently I had to implement an active-passive redundancy of a singleton service in our production environment where the general rule is always have &#8220;more than one of anything&#8221;. The main motivation is to alleviate the need to manually monitor and manage these services, whose presence is crucial to the overall health of the site.</p>
<p>This means that we sometime have a service installed on several machines for redundancy, but only one of the is active at any given moment. If the active services goes down for some reason, another service rises to do its work. Turns out this is actually called <a href="http://en.wikipedia.org/wiki/Leader_election" title="leader election" target="_blank">leader election</a>. One of the most prominent open source implementation facilitating the process of leader election is <a href="http://zookeeper.apache.org/" title="Apache Zookeeper" target="_blank">Zookeeper</a>. </p>
<p>Originally developed by <a href="http://research.yahoo.com/project/1849" title="Yahoo reasearch" target="_blank">Yahoo reasearch</a>, Zookeepr is a service providing reliable distributed coordination. It is highly concurrent, very fast and suitable mainly for read-heavy access patterns.  Reads can be done against any node of a Zookeeper cluster while writes a quorum-based. To reach a quorum, Zookeeper utilizes an <a href="http://en.wikipedia.org/wiki/Atomic_broadcast" title="Atomic Broadcast" target="_blank">atomic broadcast protocol</a>. </p>
<p><span id="more-474"></span></p>
<p>After reading the <a href="http://zookeeper.apache.org/doc/current/" title="Zookeeper documentation" target="_blank">documentation</a> several times to get a good grasp of both core concepts and operational aspects. My favourite method is to read the documentation once quickly, then go implement something, a tutorial if you&#8217;d like, then go back and read it again, quickly. After this start writing the actual code. Finally go back to the documentation and read it again, that last time is always the clearest, everything falls into place. Why? maybe because documentations are written by people with close familiarity to the topic and for people with close familiarity with the topic (or it&#8217;s just me making excuses for the fact that I am slow in the head).  So how does Zookeeper work?</p>
<h2>Connectivity, State and Sessions</h2>
<p>Zookeeper maintains an active connection with all its clients using a heartbeat mechanism. Furthermore, Zookeeper maintains a <a href="http://zookeeper.apache.org/doc/current/zookeeperProgrammers.html#ch_zkSessions" title="Zookeeper sessions" target="_blank">session</a> for each active client that is connected to it. When a client is disconnected from Zookeeper for more than a specified timeout the session expires. This means that Zookeeper keeps a pretty good picture of all the animals in its zoo. The key thing here is that Zookeeper knows about the state of its clients and is able to notify others in a consistent, ordered manner about this state and its changes.</p>
<h2>Data Model</h2>
<p>The Zookeeper <a href="http://zookeeper.apache.org/doc/r3.2.2/zookeeperProgrammers.html#ch_zkDataModel" title="Zookeeper data model" target="_blank">data model</a> consists of  a hierarchy of nodes, called <strong>ZNodes</strong>. ZNodes can hold a relatively small (efficiency is key here) amount of data, they are versioned and timestamped . There are several properties a ZNode can have that make them particularly useful for different use cases. Each node in Zookeeper can have the persistent, ephemeral and sequential flags. These determine the naming of the node and its behavior with respect to the client session. </p>
<ul>
<li>The <strong>persistent</strong> node is basically a managed data bin</li>
<li>The <strong>ephemeral</strong> node exists for the lifetime of its client session</li>
<li>The <strong>sequential</strong> node, when created, gets a unique number (identity, sequence, counter and like a hundred different names you could call this) suffixed to its name</li>
</ul>
<p>The latter two provide the means to implementing a variety of distribution tasks such as locks, queues, barriers, transactions, elections and other synchronization related tasks. </p>
<h2>Events</h2>
<p>Zookeeper allows its clients to watch for different events in its node hierarchy. This way clients can get notified of different changes in the distributed state of affairs and act accordingly. These watches are one timers and should be persisted again by the client after notification. The client is also responsible of handling session expiration which means that ephemeral nodes should be re-persisted after an expiration. </p>
<p>Phew, am I babbling today or what? down to business.</p>
<p>Zookeeper requires a lot of boiler plate code, mostly around connectivity and for the majority of the time you will be doing the same things over and over. Luckily <a href="http://www.datameer.com" title="Stefan Groschupf's Blog" target="_blank">Stefan Groschupf</a> and  <a href="http://phunt1.wordpress.com/" title="Patrick Hunt's Blog" target="_blank">Patrick Hunt</a>  wrote a client abstraction called <a href="https://github.com/sgroschupf/zkclient" title="ZkClient on GitHub" target="_blank">ZkClient</a>.  I published a maven artifact for this on <a href="https://oss.sonatype.org/index.html#nexus-search;quick~zkclient" title="ZkClient on OSS Maven Repository" target="_blank">OSS</a> so it&#8217;s available to our build system.  The library also provides a persistent notification scheme in the form of listeners. </p>
<p>Next I cooked up a factory bean for <strong>ZkClient</strong> and a template style class to act as an applicative abstraction to Zookeeper operations</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;bean id=&quot;zkClient&quot; class=&quot;org.projectx.zookeeper.ZkClientFactoryBean&quot;&gt;
        &lt;property name=&quot;ensemble&quot; value=&quot;localhost:2181,localhost:2182,localhost:2183&quot; /&gt;
        &lt;property name=&quot;connectionTimeout&quot; value=&quot;2000&quot; /&gt;
        &lt;property name=&quot;sessionTimeout&quot; value=&quot;10000&quot; /&gt;
        &lt;property name=&quot;stateListeners&quot;&gt;
            &lt;list&gt;
                &lt;ref local=&quot;zkStatsCollector&quot; /&gt;
            &lt;/list&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;zkStatsCollector&quot; class=&quot;org.projectx.zookeeper.ZookeeperClientStatsCollector&quot; /&gt;

    &lt;bean id=&quot;zkTemplate&quot; class=&quot;org.projectx.zookeeper.ZookeeperTemplate&quot;&gt;
        &lt;constructor-arg ref=&quot;zkClient&quot; /&gt;
    &lt;/bean&gt;
</pre>
<p>The <strong>ZooKeeperClientStatsCollector</strong> is a listener implementation which collects stats about session connects/disconnects, exported to JMX as an MBean. </p>
<p>Now I can happily create nodes to my heart&#8217;s content.</p>
<h2>Leader Election</h2>
<p>The <a href="http://zookeeper.apache.org/doc/current/recipes.html#sc_leaderElection" title="Leader Election - Zookeeper Documentation" target="_blank">Zookeeper documentation</a> describes in general terms how leader election is to be performed. The general idea is that all participants of the election process create an ephemeral-sequential node on the same election path. The node with the smallest sequence number is the leader. Each &#8220;follower&#8221; node listens to the node with the next lower sequence number to prevent a herding effect when the leader goes away. In effect this creates a linked list of nodes. When a node&#8217;s local leader dies it goes to election either find a smaller node or becoming the leader if it has the lowest sequence number.</p>
<p>The following image describes a scenario with 3 clients participating in the election process:</p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/07/Zookeeper-Leader-Election.jpg" alt="Zookeeper Leader Election Leader Election with Zookeeper" align="center" title="Leader Election with Zookeeper" /></p>
<p> Each client participating in this process has to:</p>
<ol>
<li> Create an ephemeral-sequential node to participate under the election path</li>
<li>Find its leader and follow (watch) it</li>
<li>Upon leader removal go to election and find a new leader, or become the leader if no leader is to be found</li>
<li> Upon session expiration check the election state and go to election if needed</li>
</ol>
<p>One thing to consider here is the nature of the work being done by the leader. Make sure it&#8217;s state can be preserved if its leadership is revoked. Leader loss could be caused by any number of reasons including initiated restarts due to maintenance and releases. It could also be brought about by network partitioning. </p>
<p>Designing services for graceful recovery is a requirement for distributed systems not leader election. </p>
<p>Spring helps here because interception can be used to suppress method invocations of various services based on leadership status. Below is an example of an interception based leadership control:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;bean id=&quot;leaderElectionProxyTemplate&quot; class=&quot;org.springframework.aop.framework.ProxyFactoryBean&quot;
        abstract=&quot;true&quot;&gt;
        &lt;property name=&quot;interceptorNames&quot;&gt;
            &lt;list&gt;
                &lt;value&gt;leaderElectionTarget&lt;/value&gt;
            &lt;/list&gt;
        &lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;leaderElectionTarget&quot;  class=&quot;org.projectx.zookeeper.election.LeaderElectionTargetInterceptor&quot; /&gt;

    &lt;bean id=&quot;myService&quot; parent=&quot;leaderElectionProxyTemplate&quot;&gt;
        &lt;property name=&quot;target&quot;&gt;
            &lt;bean class=&quot;org.projetx.service.MyService&quot;&gt;
        &lt;/property&gt;
    &lt;/bean&gt;
</pre>
<p>The service <strong>myService</strong> is the one controlled by leader election, all it&#8217;s method are going to be suppressed or invoked based on leadership status.</p>
<p>Another implementation uses a quartz scheduler instance as its target target:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;bean id=&quot;leaderElectionTarget&quot;
        class=&quot;org.projectx.zookeeper.election.quartz.SchedulerElectionTarget&quot;&gt;
        &lt;constructor-arg ref=&quot;myScheduler&quot; /&gt;
    &lt;/bean&gt;
</pre>
<p>This implementation puts a quartz scheduler on standby mode when leadership is revoked and resumes it when it&#8217;s granted (notice it will not actually stop running tasks, this will be allowed their natural completion, so in effect you may have a scheduled task running on two services due to partitioning scenarios. This means that whatever is scheduled has to be aware of another service possibly doing the same work. This problem can be easily solved with a Zookeeper barrier implementation,  more on that in another post. </p>
<p>But Zookeeper&#8217;s  capabilities extend far beyond Leader Election. </p>
<h2>Presence</h2>
<p>Another very good use for Zookeeper is maintaining a clear image of who&#8217;s alive in the data center. Every service creates an ephemeral node on some presence path. This can then be viewed by the human eye in the <a href="https://github.com/apache/zookeeper/tree/trunk/src/contrib/huebrowser" title="Zookeeper Hue Browser on GitHub" target="_blank">Zookeeper Hue Browser</a>, the <a href="https://github.com/apache/zookeeper/tree/trunk/src/contrib/rest" title="Zookeeper Rest Server on GitHub" target="_blank">Rest Server</a> or the <a href="http://wiki.apache.org/solr/SolrCloud" title="SolrCloud Wiki - Zookeeper" target="_blank">Solr Cloud</a> console. You could also use the various client APIs to point your monitoring tools at Zookeeper to know who&#8217;s where. </p>
<p>Here&#8217;s an example of defining a presence manager with Spring:</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;bean id=&quot;presenceNodeFactory&quot; class=&quot;org.projectx.zookeeper.presence.PresenceNodeFactory&quot;&gt;
        &lt;constructor-arg ref=&quot;zookeeperTemplate&quot; /&gt;
        &lt;constructor-arg value=&quot;${org.projectx.zookeeper.services.root}/${org.projectx.environment}&quot; /&gt;
        &lt;constructor-arg value=&quot;${zookeeper.entity.name}&quot; /&gt;
        &lt;constructor-arg ref=&quot;serviceMetaDataProvider&quot; /&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;presenceManager&quot; class=&quot;org.projectx.zookeeper.presence.PresenceManager&quot;&gt;
        &lt;constructor-arg ref=&quot;presenceNodeFactory&quot; /&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;serviceMetaDataProvider&quot;
        class=&quot;org.projectx.zookeeper.presence.ServiceMetaDataProvider&quot;&gt;
        &lt;constructor-arg value=&quot;${zookeeper.entity.name}&quot; /&gt;
    &lt;/bean&gt;
</pre>
<p>The <strong>serviceMetaDataProvider</strong> decorates the node with whatever data you&#8217;d like to see on the presence node (ip, revision, release numbers, various timestamps and what not).</p>
<h2>Configuration</h2>
<p>Some applications use Zookeeper to keep configuration stored (considering it&#8217;s within the size limits <a href="http://zookeeper.apache.org/doc/current/zookeeperProgrammers.html#Data+Access" title="Zookeeper Documentation - Data Access" target="_blank">recommended by Zookeeper</a>). This is much better than managing your configuration in property files, xmls or even a database (remember Zookeeper is <strong>Fast</strong> for reads). Zookeeper also offers access control with <a href="http://zookeeper.apache.org/doc/r3.1.2/zookeeperProgrammers.html#sc_ZooKeeperAccessControl" target="_blank" title="Zookeeper Documentation - ACLs">ACL</a>s on it&#8217;s node structure and this comes in handy when managing configurations. <a href="http://wiki.apache.org/solr/SolrCloud" title="SolrCloud Wiki - Zookeeper" target="_blank">Solr Cloud</a> and <a href="https://github.com/linkedin/glu/wiki" title="Glu deployment and monitoring automation platform" target="_blank">Glu</a> use Zookeeper in this way.</p>
<p>If you wish to run your data center the democratic way, where important decisions are made in coordination with other stakeholders, Zookeeper certainly helps. </p>
<p>Leader Election with Spring is on <a href="https://github.com/erezmazor/projectx/tree/master/org.projectx.zookeeper" title="Zookeeper Leader Election with Spring on GitHub" target="_blank">GitHub</a>, Source shown in this post can be found on <a href="https://gist.github.com/1073533" title="Zookeeper Post Snippets on Gist" target="_blank">Gist</a>.</p>
<p>Happy Zookeeping!</p>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/leader-election-with-zookeeper/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Creating a Facebook app with Google App Engine and Google Web Toolkit</title>
		<link>http://techo-ecco.com/blog/creating-a-facebook-app-with-google-app-engine-and-google-web-toolkit/</link>
		<comments>http://techo-ecco.com/blog/creating-a-facebook-app-with-google-app-engine-and-google-web-toolkit/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 08:10:00 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[Facebook]]></category>
		<category><![CDATA[Google AppEngine]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[J2EE]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=360</guid>
		<description><![CDATA[One of the challenges with writing a presumably successful Facebook application is taking care of scale. with an ever growing user base and the high viral growth potential brought by this social platform you could be looking at a very high traffic if your application is successful. It is wise to plan ahead. Integrating a [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/04/social.jpg" alt="social Creating a Facebook app with Google App Engine and Google Web Toolkit" align="right" width="250" title="Creating a Facebook app with Google App Engine and Google Web Toolkit" /><br />
One of the challenges with writing a presumably successful Facebook application is taking care of scale. with an ever growing user base and the high viral growth potential brought by this social platform you could be looking at a very high traffic if your application is successful. It is wise to plan ahead. Integrating a service like <a href="http://code.google.com/appengine/">Google App Engine</a> or <a href="http://aws.amazon.com/documentation/">Amazon AWS</a> could do the trick. Especially for small and medium enterprises which can find the cost model beneficial for their first baby steps.</p>
<p>This post is not going to dwell on the details of creating an <a href="https://appengine.google.com/start/createapp?">App Engine</a> account or a <a href="http://www.facebook.com/developers">Facebook</a> application. Those are described very well by their providers and across the web.</p>
<p>The example is an application called &#8220;famousity&#8221;. It authenticates a Facebook user then looks through his friends and determines how famous they are by executing a Google search on their exact name and comparing the hit count. Not very clever but will do in order to get a first feel of these tools.</p>
<p><span id="more-360"></span></p>
<p>After creating a Facebook application you should be see the following screen:</p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/03/FacebookAppSettings.jpg" alt="FacebookAppSettings Creating a Facebook app with Google App Engine and Google Web Toolkit"  title="Creating a Facebook app with Google App Engine and Google Web Toolkit" /></p>
<p>As you can see the Canvas URL is <strong>http://fbfamousity.appspot.com</strong> is where our Google App Engine application resides. We&#8217;re going to need our application id, API Key and App Secret values moving forward so we keep them handy by creating a class to encapsulate them (of course in a real world scenario we should have externalized these):</p>
<pre class="brush: java; collapse: true; light: false; title: ; toolbar: true; notranslate">
public class FacebookUtil {
    private static final String API_KEY = &quot;API_KEY&quot;; // replace with real values from Facebook app configuration
    private static final String SECRET = &quot;SECRET&quot;; // replace with real values from Facebook app configuration
    private static final String APPLICATION_ID = &quot;APPLICATION_ID &quot;; // replace with real values from Facebook app configuration

    private static final String FB_GRAPH_URL = &quot;https://graph.facebook.com/&quot;;
    private static final String FB_OAUTH_URL = FB_GRAPH_URL + &quot;oauth/&quot;;
    private static final String FB_FRIENDS_URL = FB_GRAPH_URL + &quot;me/friends?&quot;;

    // private static final String REDIRECT_URL =
    // &quot;http://apps.facebook.com/famousity/&quot;;

    // localhost is for testing
    private static final String REDIRECT_URL = &quot;http://localhost:8888/&quot;;

    public static String getApplicationId() {
        return APPLICATION_ID;
    }

    public static String getAPIKey() {
        return API_KEY;
    }

    public static String getSecret() {
        return SECRET;
    }

    public static String getAuthorizeUrl() {
        final StringBuilder sb = new StringBuilder(FB_OAUTH_URL);
        sb.append(&quot;authorize?client_id=&quot;).append(APPLICATION_ID);
        sb.append(&quot;&amp;display=page&amp;redirect_uri=&quot;).append(REDIRECT_URL);
        sb.append(&quot;&amp;scope=user_status,publish_stream,offline_access,email&quot;);
        return sb.toString();
    }

    public static String getAccessTokenUrl(final String authCode) {
        final StringBuilder sb = new StringBuilder(FB_OAUTH_URL);
        sb.append(&quot;access_token?canvas=1&amp;fbconnect=0&amp;type=user_agent&amp;client_id=&quot;).append(
                APPLICATION_ID);
        sb.append(&quot;&amp;redirect_uri=&quot;).append(REDIRECT_URL);
        sb.append(&quot;&amp;client_secret=&quot;).append(SECRET);
        sb.append(&quot;&amp;code=&quot;).append(authCode);
        return sb.toString();
    }

    public static String getFriendsUrl(final String authToken) {
        return FB_FRIENDS_URL + authToken;
    }
}
</pre>
<p>One thing to note here about this class is that the <strong>REDIRECT_URI</strong> field has a value of either <strong>http://localhost:8888/</strong> or <strong>http://apps.facebook.com/famousity/</strong> depending on weather we are working in our local development environment or the App Engine &#8220;production&#8221; environment. Remember to change this before deploying your application to App Engine (the change needs to take place in the Facebook application settings as well).</p>
<p>For my development environment I used <a href="http://www.springsource.com/products/springsource-google-download">STS with Google Integration</a>. However, if you use Eclipse you can simply install the <a href="http://code.google.com/eclipse/docs/download.html">Google Eclipse Plugin</a> which provides App Engine and GWT support within the IDE.</p>
<p>After installing the IDE plugin you get a new Google toolbar for creating a new web application, compiling GWT, profiling to speed tracer and deploying your app to App Engine. It seems that even tighter Eclipse integration is planned for the <a href="http://googlewebtoolkit.blogspot.com/2011/04/gwtgpe-23-cloud-connecting-eclipse.html" dir="rtl">next version of the plugin</a>.</p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/03/GoogleEclipseToolbar.jpg" alt="GoogleEclipseToolbar Creating a Facebook app with Google App Engine and Google Web Toolkit"  title="Creating a Facebook app with Google App Engine and Google Web Toolkit" /></p>
<hr />
<p>Facebook&#8217;s authentication is composed of several steps:</p>
<p>The user initially goes to http://apps.facebook.com/famousity the canvas page is invoked. After that ourapplication needs to send an authorization request with the appropriate <a href="http://developers.facebook.com/docs/authentication/permissions/">permissions</a>. Something along the lines of: </p>
<blockquote><p>https://graph.facebook.com/oauth/authorize?client_id=APP_CLIENT_ID&#038;display=page&#038;redirect_uri=http://localhost:8888/&#038;scope=user_status,publish_stream,offline_access,email</p></blockquote>
<p>Once the user authorizes our app it will redirect back to the parameter specified under &#8220;redirect_uri&#8221; with the access token.</p>
<p>This covers the initial authorization flow, but you must also account for the scenario where the user denies access to your app in which case face will provide you with an error message parameter in the form of:</p>
<blockquote><p>http://YOUR_CANVAS_PAGE?error_reason=user_denied&#038;error=access_denied&#038;error_description=The+user+denied+your+request</p></blockquote>
<p>The next time the user arrives at the application it has already been authorized but you still need to retrieve the access token. The application needs to execute access token request. It looks like:</p>
<blockquote><p>https://graph.facebook.com/oauth/access_token?canvas=1&#038;fbconnect=0&#038;type=user_agent&#038;client_id=APP_CLIENT_ID&#038;redirect_uri=http://localhost:8888/&#038;client_secret=APP_SECRET</p></blockquote>
<p>After that the application can proceed to execute authorized graph API calls using the provided token:</p>
<blockquote><p>https://graph.facebook.com/me/friends?access_token=FB_PROVIDED_ACCESS_TOKEN</p></blockquote>
<hr />
<p>To create a new GWT-App Engine-Facebook project open Eclipse and click the <strong>New Web Application Project</strong>, type the name and a package and click Finish. This will create a new GWT application. It will also generate some sample code, notice it has created a &#8220;client&#8221;, &#8220;server&#8221; and &#8220;shared&#8221; packages The client package should contain two interfaces the <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/user/client/rpc/RemoteService.html">RemoteService</a> specification interface and it&#8217;s Async correspondent. In our case we will create a Facebook service to handle facebook operations:</p>
<pre class="brush: java; title: ; notranslate">
@RemoteServiceRelativePath(&quot;facebook&quot;)
public interface FacebookService extends RemoteService {
    public String login(String authToken);
    public List&lt;FbFriend&gt; findFriends(String authToken);
}
</pre>
<p>And it&#8217;s Async twin, an identical interface with another parameter, a typed <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/user/client/rpc/AsyncCallback.html">AsyncCallback</a>:</p>
<pre class="brush: java; title: ; notranslate">
public interface FacebookServiceAsync {
    public void login(String authToken, AsyncCallback&lt;String&gt; asyncCallback);
    public void findFriends(String authToken, AsyncCallback&lt;List&lt;FbFriend&gt;&gt; asyncCallback);
}
</pre>
<p>Our Facebook service contains two methods, one is for the initial authentication of the user and accepts an existing authentication token used to pass back to the client. This lets the client know that the user was previously authenticated and can proceed into the app. For more information on the Facebook authentication flow check their <a href="http://developers.facebook.com/docs/authentication/">documentation</a>. The login method returns the authentication token which is later used in subsequent calls to the Facebook API.</p>
<p>The <strong>findFriends</strong> method accepts the authentication token and retrieves a list of <strong>FbFriend</strong> instances. Note that in GWT classes used to communicate between the client and the remote service must implement the <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/user/client/rpc/IsSerializable.html">IsSerializable</a> interface.</p>
<pre class="brush: java; collapse: true; light: false; title: ; toolbar: true; notranslate">
public class FbFriend implements IsSerializable {

    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public void setId(final Long id) {
        this.id = id;
    }
}
</pre>
<p>The FacebookService implementation is shown below</p>
<pre class="brush: java; collapse: true; light: false; title: ; toolbar: true; notranslate">
public class FacebookServiceImpl extends RemoteServiceServlet implements FacebookService {
    private static final long serialVersionUID = 1L;

    public String login(final String authToken) {
        final String url = FacebookUtil.getAccessTokenUrl(Util.encode(authToken));
        return Util.fetchURL(url);
    }

    public List&lt;FbFriend&gt; findFriends(final String authToken) {
        final String friendsUrl = FacebookUtil.getFriendsUrl(encodeUrl(authToken));
        final String json = Util.fetchURL(friendsUrl);
        final FBFriends fbFriends = new Gson().fromJson(json, FBFriends.class);
        return fbFriends.getData();
    }

    private static String encodeUrl(final String unencodedToken) {
        final String[] parts = unencodedToken.split(&quot;=&quot;);
        if (parts.length &lt; 2) {
            return &quot;&quot;;
        }
        return &quot;access_token=&quot; + Util.encode(parts[1]);
    }
}
</pre>
<p>Our FacebookService will handle the login and the friend retrieval but what about the Google name search hit counts? For this we devise another service with an async counterpart:</p>
<pre class="brush: java; title: ; notranslate">
@RemoteServiceRelativePath(&quot;google&quot;)
public interface GoogleService extends RemoteService {
    public Long findFriendRanking(FbFriend friend);
}
</pre>
<pre class="brush: java; title: ; notranslate">
public interface GoogleServiceAsync {
    public void findFriendRanking(FbFriend friend, final AsyncCallback&lt;Long&gt; asyncCallback);
}
</pre>
<p>And here is the implementation for this service:</p>
<pre class="brush: java; collapse: true; light: false; title: ; toolbar: true; notranslate">
public class GoogleServiceImpl extends RemoteServiceServlet implements GoogleService {
    private static final long serialVersionUID = 1L;

    private static final Logger logger = LoggerFactory.getLogger(Util.class);
    private static final String GOOGLE_API_URL = &quot;http://ajax.googleapis.com/ajax/services/search/web?v=1.0&amp;q=&quot;;

    private final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    public Long findFriendRanking(final FbFriend friend) {
        final Key key = KeyFactory.createKey(&quot;profile&quot;, friend.getId());
        try {
            final Entity profile = datastore.get(key);
            final Object result = profile.getProperty(&quot;estimatedResultCount&quot;);
            return (Long) result;
        } catch (final EntityNotFoundException e) {
            logger.debug(&quot;Could not find an entry for {} in the datastore.&quot;, friend.getId());
            final Long resultCount = findResultCount(friend.getName());
            final Entity newProfile = new Entity(key);
            newProfile.setProperty(&quot;profileName&quot;, friend.getName());
            newProfile.setProperty(&quot;estimatedResultCount&quot;, resultCount);
            datastore.put(newProfile);
            return resultCount;
        }
    }

    public Long findResultCount(final String name) {
        final String queryUrl = GOOGLE_API_URL + Util.encode(&quot;\&quot;&quot; + name + &quot;\&quot;&quot;);
        logger.debug(&quot;Executing google query {}&quot;, queryUrl);
        final String resultJson = Util.fetchURL(queryUrl);

        final ResponseDataContainer container = new Gson().fromJson(resultJson,
                ResponseDataContainer.class);

        if (null != container &amp;&amp; null != container.getResponseData()
                &amp;&amp; null != container.getResponseData().getCursor()) {
            final Long resultCount = container.getResponseData().getCursor()
                    .getEstimatedResultCount();
            return resultCount;
        } else {
            return -1L;
        }
    }
}
</pre>
<p>We create a key based on the friend&#8217;s Facebook id and then use that key to search the AppEngine datastore. If the key doesn&#8217;t exist we handle the <a href="http://code.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/EntityNotFoundException.html">EntityNotFoundException</a> by executing a new search and placing the result values in the datastore for future use. </p>
<p>When working in the local development environment, notice that the AppEngine library has created a local datastore for you. This can be found under &#8220;<strong>war/WEB-INF/appengine-generated/local_db.bin</strong>&#8221; in our workspace.</p>
<p>In case you&#8217;re wondering about the validity of the results here it is a complete spoof. The Google Ajax Search API has been <a href="http://code.google.com/apis/websearch/">deprecated</a> for quite some time now and the correctness of the results is dubious at best. It will do for this example but not for any real world apps. </p>
<hr/>
<p>Now to the GWT client code, here we need to perform a few basic steps:</p>
<p>We use the returned &#8220;code&#8221; parameter returned to us by Facebook to see if the user has an access token. If he doesn&#8217;t we redirect him to the authorization Url this will cause Facebook to display the following authorization dialog:</p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/03/FacebookAuthorizeFamousity.jpg" alt="FacebookAuthorizeFamousity Creating a Facebook app with Google App Engine and Google Web Toolkit"  title="Creating a Facebook app with Google App Engine and Google Web Toolkit" /></p>
<p>Next we check for the &#8220;user_denied&#8221; parameter place by the caller (Facebook) and display an appropriate error message to the user (if we want to force him to authorize all permissions, depending on what our app requires to function). If the user has denied our authorization request we better notify him that he needs to authorize us:</p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/03/FamousityDeny.jpg" alt="FamousityDeny Creating a Facebook app with Google App Engine and Google Web Toolkit"  title="Creating a Facebook app with Google App Engine and Google Web Toolkit" /></p>
<p>After we&#8217;re done with the authorization checks we can now safely proceed with our access token to retrieve the user&#8217;s friend list, using our FacebookService remote interface. For each friend returned we draw a widget then execute a name search using our GoogleService remote interface. </p>
<pre class="brush: java; collapse: true; light: false; title: ; toolbar: true; notranslate">
public class Famousity implements EntryPoint {

    private final FacebookServiceAsync facebookService = GWT.create(FacebookService.class);
    private final GoogleServiceAsync googleService = GWT.create(GoogleService.class);

    private MessageBox messageBox;

    public void onModuleLoad() {
        final String authToken = Location.getParameter(&quot;code&quot;);
        final String error = Location.getParameter(&quot;error_reason&quot;);

        if (null != error &amp;&amp; error.equals(&quot;user_denied&quot;)) {
            userDenied();
        } else if (authToken == null || &quot;&quot;.equals(authToken)) {
            redirect(FacebookUtil.getAuthorizeUrl());
        } else {
            messageBox = MessageBox.wait(&quot;Famousity&quot;, &quot;&quot;, &quot;Analyzing friend rankings...&quot;);

            facebookService.login(authToken, new AsyncCallback&lt;String&gt;() {
                public void onFailure(final Throwable caught) {
                    handleError(caught);
                }

                public void onSuccess(final String authToken) {
                    rankFriends(authToken);
                }
            });
        }
    }

    private void userDenied() {
        MessageBox.confirm(&quot;Error authrizing famousity&quot;,
                &quot;You have deined famousity from installing correctly, click 'Yes' to try again&quot;,
                new Listener&lt;MessageBoxEvent&gt;() {

                    public void handleEvent(final MessageBoxEvent be) {
                        if (be.getButtonClicked().getText().equals(&quot;Yes&quot;)) {
                            redirect(FacebookUtil.getAuthorizeUrl());
                        } else {
                            be.getMessageBox().close();
                        }
                    }
                });
    }

    private void rankFriends(final String authToken) {

        final RootPanel rootPanel = RootPanel.get();
        facebookService.findFriends(authToken, new AsyncCallback&lt;List&lt;FbFriend&gt;&gt;() {
            public void onFailure(final Throwable caught) {
                Window.alert(caught.getMessage());
            }

            public void onSuccess(final List&lt;FbFriend&gt; friends) {
                closeMessageBox();
                final Header header = new Header();
                header.setText(&quot;How famous are your friends&quot;);
                rootPanel.add(header);

                for (final FbFriend friend : friends) {
                    final Panel friendPanel = new HorizontalPanel();

                    friendPanel.setStyleName(&quot;panel&quot;);
                    final Image profilePic = new Image(getProfilePictureUrl(friend));
                    profilePic.setStyleName(&quot;profilePic&quot;);
                    friendPanel.add(profilePic);
                    friendPanel.add(new Hidden(friend.getId().toString()));
                    friendPanel.add(new Text(friend.getName()));
                    final Text countText = new Text(&quot;&quot;);
                    friendPanel.add(countText);
                    rootPanel.add(friendPanel);

                    googleService.findFriendRanking(friend, new AsyncCallback&lt;Long&gt;() {

                        public void onFailure(final Throwable caught) {
                            handleError(caught);
                        }

                        public void onSuccess(final Long result) {
                            if (result &gt; 0) {
                                countText.setText(result.toString());
                            } else {
                                countText.getParent().setVisible(false);
                            }
                        }
                    });
                }
            }

        });

    }

    private void handleError(final Throwable caught) {
        Window.alert(caught.getMessage());
    }

    private String getProfilePictureUrl(final FbFriend friend) {
        return &quot;http://graph.facebook.com/&quot; + friend.getId() + &quot;/picture&quot;;
    }

    private void closeMessageBox() {
        if (messageBox != null) {
            messageBox.close();
            messageBox = null;
        }
    }

    // redirect the browser to the given url
    public static native void redirect(String url)/*-{
		$wnd.location = url;
    }-*/;
}
</pre>
<p>While the user is waiting a neat progress bar is displayed using the aid of <a href="http://code.google.com/p/gwt-ext/">GWT-EXT</a>:</p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/03/FamousityProgress.jpg" alt="FamousityProgress Creating a Facebook app with Google App Engine and Google Web Toolkit"  title="Creating a Facebook app with Google App Engine and Google Web Toolkit" /></p>
<p>This is what the (censored) output looks like:</p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/03/FanmousityRankTable.jpg" alt="FanmousityRankTable Creating a Facebook app with Google App Engine and Google Web Toolkit"  title="Creating a Facebook app with Google App Engine and Google Web Toolkit" /></p>
<p>A few words about the GWT code here. GWT relies heavily on asynchronous calls. There is some suspicion that rises from nesting these calls although Google has a good <a href="http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/d929d9eb0ce427f9">explanation</a> for why this is the way it is. Some discussion of this issue can be found <a href="http://stackoverflow.com/questions/2993085/clean-way-in-gwt-java-to-wait-for-multiple-asynchronous-events-to-finish">here</a> and <a href="http://www.summa-tech.com/blog/2010/11/29/parallel-asynchronous-calls-in-gwt/">here</a>. It seems some recommend moving logic to the server while other try to devise more neat solutions for the code. In AppEngine more logic running on the server may pose a problem due to the <a href="http://code.google.com/appengine/docs/whatisgoogleappengine.html">30 second limitation</a>. We must take these matters under consideration when combining these two technologies. The need to explicitly implement the RemoteService and it&#8217;s Async twin seem a bit off as well, they smell a little like the old EJB stuff. Other MVC implementations save you this kind of boilerplate code by using annotations or configuration files.  </p>
<p>After testing the application in Eclipse, click the &#8220;Deploy App Engine Project&#8221; button in Eclipse then provide the Google credentials and our application get&#8217;s compiled and deployed automatically. A pretty cool combination, for my next social project I think I am going to take a closer look at <a href="http://www.springsource.org/spring-social">Spring Social</a>.</p>
<p>Source code is available <a href="https://github.com/erezmazor/famousity">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/creating-a-facebook-app-with-google-app-engine-and-google-web-toolkit/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Quartz and Spring Integration</title>
		<link>http://techo-ecco.com/blog/quartz-and-spring-integration/</link>
		<comments>http://techo-ecco.com/blog/quartz-and-spring-integration/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 07:15:45 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[quartz]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=213</guid>
		<description><![CDATA[Quartz is an excellent, open-source scheduler which provides many enterprise features such as job persistence to a variety of job store implementations (e.g., RAM, JDBC, etc.), transactions and clustering. Spring offers good integration for Quartz and provides some nice abstractions for using it within the IoC container such as MethodInvokingJobDetailFactoryBean which allows you to use [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/04/clock.jpg" alt="clock Quartz and Spring Integration" align="right" width="250" title="Quartz and Spring Integration" /><br />
<a href="http://www.quartz-scheduler.org/" target="blank">Quartz</a> is an excellent, open-source scheduler which provides many enterprise features such as job persistence to a variety of job store implementations (e.g., RAM, JDBC, etc.), transactions and clustering. Spring offers good <a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/htmlsingle/spring-framework-reference.html#scheduling-quartz" target="blank">integration</a> for Quartz and provides some nice abstractions for using it within the IoC container such as <a href="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/scheduling/quartz/MethodInvokingJobDetailFactoryBean.html" target="blank">MethodInvokingJobDetailFactoryBean</a> which allows you to use any old bean/method as a <a href="http://www.quartz-scheduler.org/docs/api/1.8.1/org/quartz/JobDetail.html" target="blank">JobDetail</a>. </p>
<p><span id="more-213"></span></p>
<p>One thing is the Spring documentation and most examples I&#8217;ve found in my travels have pointed toward the scenario where all your JobDetails and <a href="http://www.quartz-scheduler.org/docs/api/1.8.1/index.html?org/quartz/Trigger.html" target="blank">Triggers</a> are defined &#8220;statically&#8221; in the Spring configuration files, not at runtime. My use case is slightly different, I need to create these Triggers at runtime. Some posts like this <a href="http://forum.springsource.org/showthread.php?t=50606&#038;page=2" target="blank">one</a> suggests using a dependency-injected factory which will both create and wire the Triggers at runtime with dependencies, this is a valid solution but violates the IoC principle.</p>
<p>In a <a href="http://techo-ecco.com/blog/spring-prototype-scoped-beans-and-dependency-injection">previous post</a> I showed how to use Spring prototype scoped beans with dependency injection. In this post I&#8217;d like to show how the same notion can be applied to create prototype-scoped Quartz Triggers and JobDetails with Spring.</p>
<p>Let&#8217;s start by defining the scheduler using a <a href="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/scheduling/quartz/SchedulerFactoryBean.html" target="blank">SchedulerFactoryBean</a> to create an instance of the scheduler:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;quartzScheduler&quot;
	class=&quot;org.springframework.scheduling.quartz.SchedulerFactoryBean&quot;&gt;
	&lt;property name=&quot;jobFactory&quot;&gt;
		&lt;bean class=&quot;org.springframework.scheduling.quartz.SpringBeanJobFactory&quot; /&gt;
	&lt;/property&gt;
	&lt;property name=&quot;configLocation&quot; value=&quot;classpath:quartz.properties&quot; /&gt;
	&lt;property name=&quot;waitForJobsToCompleteOnShutdown&quot; value=&quot;true&quot; /&gt;
	&lt;property name=&quot;triggerListeners&quot;&gt;
		&lt;list&gt;
			&lt;ref bean=&quot;myTriggerListener&quot; /&gt;
		&lt;/list&gt;
	&lt;/property&gt;
	&lt;property name=&quot;schedulerContextAsMap&quot;&gt;
		&lt;map&gt;
			&lt;entry key=&quot;myServiceBean&quot; value-ref=&quot;myServiceBean&quot; /&gt;
		&lt;/map&gt;
	&lt;/property&gt;
	&lt;property name=&quot;dataSource&quot; ref=&quot;datasource&quot; /&gt;
&lt;/bean&gt;
</pre>
<p>Notice how <strong>myServiceBean</strong> is wired into the <strong>schedulerContextAsMap</strong> property. In its <a href="http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/scheduling/quartz/JobDetailBean.html#setJobDataAsMap(java.util.Map)" target="blank">documentation</a> Spring suggests that for persistent jobs you wire your beans this way and not via the <a href="http://www.quartz-scheduler.org/docs/api/1.8.1/index.html?org/quartz/JobDataMap.html" target="blank">JobDataMap</a>, the &#8220;state context&#8221; mechanism for jobs.</p>
<p>So now I can get to work and define my Trigger and JobDetail prototype factories:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;jobTriggerFactory&quot;
	class=&quot;org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean&quot;&gt;
	&lt;property name=&quot;targetBeanName&quot;&gt;
		&lt;idref local=&quot;jobTrigger&quot; /&gt;
	&lt;/property&gt;
&lt;/bean&gt;
&lt;bean id=&quot;jobTrigger&quot; class=&quot;org.springframework.scheduling.quartz.SimpleTriggerBean&quot;
	scope=&quot;prototype&quot;&gt;
      &lt;property name=&quot;group&quot; value=&quot;myJobs&quot; /&gt;
      &lt;property name=&quot;description&quot; value=&quot;myDescription&quot; /&gt;
      &lt;property name=&quot;repeatInterval&quot; value=&quot;${myproperties.repeatinterval}&quot; /&gt;
&lt;/bean&gt;

&lt;bean id=&quot;jobDetailFactory&quot;
	class=&quot;org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean&quot;&gt;
	&lt;property name=&quot;targetBeanName&quot;&gt;
		&lt;idref local=&quot;jobDetail&quot; /&gt;
	&lt;/property&gt;
&lt;/bean&gt;

&lt;bean id=&quot;jobDetail&quot; class=&quot;org.springframework.scheduling.quartz.JobDetailBean&quot;
	scope=&quot;prototype&quot;&gt;
	&lt;property name=&quot;jobClass&quot; value=&quot;org.echotech.scheduler.MyJob&quot; /&gt;
	&lt;property name=&quot;volatility&quot; value=&quot;false&quot; /&gt;
	&lt;property name=&quot;durability&quot; value=&quot;false&quot; /&gt;
	&lt;property name=&quot;requestsRecovery&quot; value=&quot;true&quot; /&gt;
&lt;/bean&gt;

&lt;bean id=&quot;schedulerManager&quot; class=&quot;org.echotech.scheduler.MySchedulerManagerImpl&quot;&gt;
	&lt;constructor-arg ref=&quot;quartzScheduler&quot; /&gt;
	&lt;constructor-arg ref=&quot;jobDetailFactory&quot; /&gt;
	&lt;constructor-arg ref=&quot;jobTriggerFactory&quot; /&gt;
&lt;/bean&gt;
</pre>
<p>The code for <strong>MySchedulerManagerImpl</strong> shows how to register a new Job with the scheduler using the provided factories.</p>
<pre class="brush: java; title: ; notranslate">
public class MySchedulerManagerImpl {
   private final Scheduler scheduler;
   private final ObjectFactory&lt;SimpleTrigger&gt; jobTriggerFactory;
   private final ObjectFactory&lt;JobDetail&gt; jobDetailFactory;

   public MySchedulerManagerImpl(final Scheduler scheduler,
         final ObjectFactory&lt;JobDetail&gt; jobDetailFactory,
         final ObjectFactory&lt;SimpleTrigger&gt; jobTriggerFactory) {
      Assert.notNull(scheduler, &quot;scheduler cannot be null&quot;);
      Assert.notNull(jobDetailFactory, &quot;jobDetailFactory cannot be null&quot;);
      Assert.notNull(jobTriggerFactory, &quot;jobTriggerFactory cannot be null&quot;);
      this.scheduler = scheduler;
      this.jobDetailFactory = jobDetailFactory;
      this.jobTriggerFactory = jobTriggerFactory;
   }

   public void scheduleNewJob(final Map&lt;String, String&gt; parameters,
         final String name) {
      // create a trigger
      SimpleTrigger trigger = jobTriggerFactory.getObject();
      trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
      trigger.setStartTime(new Date());
      trigger.setName(name);

      // create job details
      JobDetail jobDetail = jobDetailFactory.getObject();

      jobDetail.setName(name);
      jobDetail.setGroup(trigger.getGroup());
      jobDetail.getJobDataMap().putAll(parameters);

      try {
         scheduler.scheduleJob(jobDetail, trigger);
      } catch (SchedulerException e) {
         // handle this, either wrap and re-throw with runtime variant or do
         // something meaningful
      }
   }
}
</pre>
<p>This way you can decide what JobDetail and Trigger parameters you want to be defined in the Spring container (values can be externalized to property files, JNDI or other sources using the common Spring abstractions) and what is determined at runtime.</p>
<p>Hope this helps, happy scheduling</p>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/quartz-and-spring-integration/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>TestNG with Cobertura</title>
		<link>http://techo-ecco.com/blog/testng-with-cobertura/</link>
		<comments>http://techo-ecco.com/blog/testng-with-cobertura/#comments</comments>
		<pubDate>Tue, 15 Jun 2010 08:26:41 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[cobertura]]></category>
		<category><![CDATA[testng]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=198</guid>
		<description><![CDATA[Cobertura is one of the key static analysis tool every developer should work with. I've seen numerous project increase their code coverage using this tool and which in turn can and will reduce QA cycles and overall bug counts any given system. ]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/04/eclipse.jpg" alt="eclipse TestNG with Cobertura" align="right" width="250" title="TestNG with Cobertura" /><br />
For most cases I prefer JUnit over <a href="http://testng.org/doc/index.html">TestNG</a>, the fact that it the de-facto standard for unit testing make integration with eclipse, CI servers and build systems easier. However, TestNG has its merits, it is more flexible than JUnit, grouping is highly configurable and the DataProvider feature is also good.</p>
<p><a href="http://cobertura.sourceforge.net/">Cobertura</a> is one of the key static analysis tool every developer should work with. I&#8217;ve seen numerous project increase their code coverage using this tool and which in turn can and will reduce QA cycles and overall bug counts any given system. </p>
<p><span id="more-198"></span></p>
<p>I recently had to integrate Cobertura code coverage with TestNG into the build system and CI server and found very little on the net on how to do it. <a href="http://www.eclemma.org/">EclEmma</a> has a great coverage plugin for eclipse which is a must for every developer writing tests (a small nit that I had with TestNG and this plugin is that you have to run the tests first using the TestNG plugin and only then I was successful in running them again in coverage mode). But the plugin is not enough, it is also important to run coverage reports on a nightly build and continuously monitor the coverage percentage of your application as the project evolves.</p>
<p>In order to run the Cobertura coverage you need to:</p>
<p>1. instrument your classes<br />
2. execute your tests with the instrumented classes<br />
3. use the cobertura generated execution file created at step 2 to generate an html report.</p>
<p>For keeping things DRY, you&#8217;re better off not copying your test ant targets but reuse the existing ones. In order to do this let&#8217;s make the <strong>classpathref</strong> attribute of the TestNG task parametric (I used a var so I can override it from other builds, you need <a href="http://ant-contrib.sourceforge.net/" target="blank">antcontrib</a> to use var). </p>
<pre class="brush: xml; title: ; notranslate">
   &lt;property name=&quot;cb.file&quot; location=&quot;${basedir}/cobertura.bin&quot; /&gt;
   &lt;var name=&quot;cb.arg&quot; value=&quot;none&quot; /&gt;

   &lt;!-- normally this would contain your standard test classpath --&gt;
   &lt;var name=&quot;test.cp&quot; value=&quot;test.cp&quot; /&gt;
   &lt;target name=&quot;test&quot;&gt;
      &lt;testng classpathref=&quot;${test.cp}&quot;
              haltOnFailure=&quot;true&quot;&gt;
         &lt;xmlfileset dir=&quot;${basedir}/src/test&quot; includes=&quot;tests.xml&quot; /&gt;
         &lt;sysproperty key=&quot;${cb.arg}&quot; value=&quot;${cb.file}&quot; /&gt;
      &lt;/testng&gt;
   &lt;/target&gt;
</pre>
<p>The remainder of the build file looks roughly something like this:</p>
<pre class="brush: xml; title: ; notranslate">
   &lt;!-- define the cobertura jars classpath --&gt;
   &lt;path id=&quot;cb.cp&quot;&gt;
      &lt;!--
		Includes the following jars:
		asm-all 3.2
		cobertura 1.9.4.1
		log4j 1.2.14
		oro 2.0.8
		--&gt;
   &lt;/path&gt;

   &lt;target name=&quot;cb.init&quot;&gt;
      &lt;!-- output directory --&gt;
      &lt;property name=&quot;cb.report.dir&quot; value=&quot;${basedir}/cobertura&quot; /&gt;
      &lt;!-- instrumentation directory --&gt;
      &lt;property name=&quot;cb.instrument.dir&quot;
                value=&quot;${cb.report.dir}/.cobertura-instrumented-classes&quot; /&gt;

      &lt;!-- your main java source files --&gt;
      &lt;property name=&quot;cb.src.dir&quot; value=&quot;${basedir}/src/main&quot; /&gt;
      &lt;!-- your main class files files --&gt;
      &lt;property name=&quot;cb.classes.dir&quot; value=&quot;${basedir}/bin/main&quot; /&gt;
      &lt;!-- your test class files --&gt;
      &lt;property name=&quot;cb.test.classes.dir&quot; value=&quot;${basedir}/bin/test&quot; /&gt;

      &lt;taskdef classpathref=&quot;cb.cp&quot; resource=&quot;tasks.properties&quot; /&gt;
   &lt;/target&gt;

   &lt;target name=&quot;cb&quot; depends=&quot;cb.gen, cb.xml, cb.html&quot;&gt;
      &lt;delete file=&quot;${cb.file}&quot; /&gt;
      &lt;delete dir=&quot;${cb.instrument.dir}&quot; /&gt;
   &lt;/target&gt;

   &lt;target name=&quot;cb.instrument&quot;&gt;
      &lt;mkdir dir=&quot;${cb.report.dir}&quot; /&gt;
      &lt;cobertura-instrument todir=&quot;${cb.instrument.dir}/&quot;
                            maxmemory=&quot;512M&quot;
                            datafile=&quot;${cb.file}&quot;&gt;
         &lt;fileset dir=&quot;${cb.classes.dir}&quot;&gt;
            &lt;include name=&quot;**/*.class&quot; /&gt;
         &lt;/fileset&gt;
      &lt;/cobertura-instrument&gt;
   &lt;/target&gt;

   &lt;target name=&quot;init.cb.path&quot;&gt;
      &lt;var name=&quot;test.cp&quot; value=&quot;cb.test.cp&quot; /&gt;
      &lt;var name=&quot;cb.sysarg&quot; value=&quot;net.sourceforge.cobertura.datafile&quot; /&gt;
      &lt;path id=&quot;cb.test.cp&quot;&gt;
         &lt;pathelement path=&quot;${cb.instrument.dir}&quot; /&gt;
         &lt;pathelement path=&quot;${cb.classes.dir}&quot; /&gt;
         &lt;pathelement path=&quot;${cb.test.classes.dir}&quot; /&gt;
         &lt;path refid=&quot;test.cp&quot; /&gt;
         &lt;path refid=&quot;cb.cp&quot; /&gt;
      &lt;/path&gt;
   &lt;/target&gt;
   &lt;target name=&quot;cb.run&quot; depends=&quot;init.cb.path, test&quot; /&gt;
   &lt;target name=&quot;cb.gen&quot; depends=&quot;cb.init, cb.instrument, cb.run&quot; /&gt;
   &lt;target name=&quot;cb.html&quot;&gt;
      &lt;cobertura-report format=&quot;html&quot;
                        destdir=&quot;${cb.report.dir}&quot;
                        maxmemory=&quot;512M&quot;
                        datafile=&quot;${cb.file}&quot;&gt;
         &lt;fileset dir=&quot;${cb.src.dir}&quot;&gt;
            &lt;include name=&quot;**/*.java&quot; /&gt;
         &lt;/fileset&gt;
      &lt;/cobertura-report&gt;
   &lt;/target&gt;

   &lt;target name=&quot;cb.xml&quot;&gt;
      &lt;cobertura-report format=&quot;xml&quot;
                        destdir=&quot;${cb.report.dir}&quot;
                        maxmemory=&quot;512M&quot;
                        datafile=&quot;${cb.file}&quot;&gt;
         &lt;fileset dir=&quot;${cb.src.dir}&quot;&gt;
            &lt;include name=&quot;**/*.java&quot; /&gt;
         &lt;/fileset&gt;
      &lt;/cobertura-report&gt;
   &lt;/target&gt;
</pre>
<p>Make sure you remember to initialize your test classpath properly as part of the Cobertura flow.</p>
<p>Once you get this working (had to overcome a couple of obstacles with Cobertura report not finding the datafile and tweak the classpath a bit to get it to work) it is really easy to connect this to your CI build. If you&#8217;re using <a href="https://hudson.dev.java.net/">Hudson</a> then download the <a href="http://wiki.hudson-ci.org/display/HUDSON/Cobertura+Plugin" target="blank">Cobertura Plugin</a> and point it to all of your projects output <strong>cobertura.xml</strong> files. These CI servers are great in aggregating these reports and providing a time-lapse view of your code coverage:</p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2010/06/cobertura.jpg" alt="cobertura TestNG with Cobertura" id="AX48980073" title="TestNG with Cobertura" /></p>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/testng-with-cobertura/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Spring prototype scoped beans and dependency injection</title>
		<link>http://techo-ecco.com/blog/spring-prototype-scoped-beans-and-dependency-injection/</link>
		<comments>http://techo-ecco.com/blog/spring-prototype-scoped-beans-and-dependency-injection/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 09:29:36 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[context]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=136</guid>
		<description><![CDATA[Within the typical Spring container most of the beans with dependency on other beans end up being stateless singleton beans. However every once in a while you want a stateful prototype beans with dependencies. A common example of this scenario comes to mind when implementing the BusinessDelegate pattern within a Spring managed application. In this [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/04/toy-car.jpg" alt="toy car Spring prototype scoped beans and dependency injection" align="right" width="250" title="Spring prototype scoped beans and dependency injection" /><br />
Within the typical Spring container most of the beans with dependency on other beans end up being stateless singleton beans. However every once in a while you want a stateful prototype beans with dependencies. <span id="more-136"></span> A common example of this scenario comes to mind when implementing the <a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/BusinessDelegate.html" target="blank">BusinessDelegate</a> pattern within a Spring managed application.</p>
<p>In this example I have a <strong>SearchBusinessDelegate</strong> which depends on <strong>MyService</strong> to execute the search. </p>
<p><br/><br/></p>
<p><strong>MyService</strong>&#8216;s interface:</p>
<pre class="brush: java; title: ; notranslate">
public interface MyService {
	List&lt;Long&gt; executeSerch(final int maxResults, final SearchCriteria criteria);
}
</pre>
<p>and here is <strong>SearchBusinessDelegate</strong>&#8216;s implementation:</p>
<pre class="brush: java; title: ; notranslate">
public class SearchBusinessDelegate {

	private final MyService myService;

	private SearchCriteria statefulCriteria;
	private int maxResults;

	public SearchBusinessDelegate(final MyService myService) {
		this.myService = myService;
	}

	public void initCriteria(final SearchCriteria searchCriteria, final int maxResults) {
		this.statefulCriteria = searchCriteria;
		this.maxResults = maxResults;
	}

	public List&lt;Long&gt; executeSearch() {
		Assert.isTrue(maxResults &gt; 0, &quot;maxResult cannot be less than 1&quot;);
		Assert.notNull(statefulCriteria, &quot;search criteria cannot be null&quot;);
		return myService.executeSerch(maxResults, statefulCriteria);
	}
}
</pre>
<p>Notice the delegate&#8217;s mix of load time dependencies and run time parameters. IMO you should be extremely cautious about using these kind of stateful delegates, one noticeable drawback of this implementation is the need to assert that <strong>initCriteria</strong> was invoked prior to invoking <strong>executeSearch</strong>, which is a foxhole. For the sake of implementing the pattern correctly this is now kept as is.</p>
<p>The traditional way of doing this is to implement a <strong>BusinessDelegateFactory</strong> which gets injected the <strong>BusinessDelegate</strong>&#8216;s dependencies and does the dependency injection on the business delegate upon creation. For example:</p>
<pre class="brush: java; title: ; notranslate">
public class SearchBusinessDelegateFactory {
	private final MyService myService;

	public SearchBusinessDelegateFactory(final MyService myService) {
		this.myService = myService;
	}

	public SearchBusinessDelegate create(final SearchCriteria searchCriteria, final int maxResults) {
		final SearchBusinessDelegate delegate = new SearchBusinessDelegate(myService);
		delegate.initCriteria(searchCriteria, maxResults);
		return delegate;
	}
}
</pre>
<p>And the Spring configuration would be:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;myService&quot; class=&quot;org.echotech.service.MyServiceImpl&quot; /&gt;

&lt;bean id=&quot;searchBusinessDelegateFactory&quot; class=&quot;org.echotech.service.SearchBusinessDelegateFactory&quot;&gt;
	&lt;constructor-arg ref=&quot;myService&quot; /&gt;
&lt;/bean&gt;
</pre>
<p>Using this factory however causes us to lose <a href="http://en.wikipedia.org/wiki/Inversion_of_control" target="blank">IoC</a> principle en-route. We are creating the delegate in code which kind of defeats the purpose (for example, think about how you&#8217;d wrap the <strong>SearchBusinessDelegate</strong>&#8216;s with AOP interception this way), bummer. We could have our factory implement the <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/context/ApplicationContextAware.html" target="blank">ApplicationContextAware</a> and retrieve the prototype instance from the context each time. But this factory code, is it really necessary? isn&#8217;t that the purpose of using Spring in the first place?</p>
<p>The answer is yes, we can take advantage of Spring&#8217;s <a href="http://static.springsource.org/spring/docs/current/api/index.html?org/springframework/beans/factory/ObjectFactory.html" target="blank">ObjectFactory</a> implementations, namely <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBean.html" target="blank">ObjectFactoryCreatingFactoryBean</a>.</p>
<p>First we define the factory in Spring:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;myService&quot; class=&quot;org.echotech.service.MyServiceImpl&quot; /&gt;

&lt;bean id=&quot;searchBusinessDelegate&quot; class=&quot;org.echotech.service.SearchBusinessDelegate&quot;
	scope=&quot;prototype&quot;&gt;
	&lt;constructor-arg ref=&quot;myService&quot; /&gt;
&lt;/bean&gt;

&lt;bean id=&quot;searchBusinessDelegateFactory&quot;
	class=&quot;org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean&quot;&gt;
	&lt;property name=&quot;targetBeanName&quot;&gt;
		&lt;idref local=&quot;searchBusinessDelegate&quot; /&gt;
	&lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>Now we can wire the factory in our client (in this case, a controller) which ensures a fresh instance of the delegate (prototype scope in Spring) is used for every invocation of <strong>executeSomething</strong> method:</p>
<pre class="brush: java; title: ; notranslate">
@Controller
public class MyController {

	private final ObjectFactory&lt;SearchBusinessDelegate&gt; delegateFactory;

	public MyController(final ObjectFactory&lt;SearchBusinessDelegate&gt; delegateFactory) {
		this.delegateFactory = delegateFactory;
	}

	@RequestMapping(method = RequestMethod.GET)
	public List&lt;Long&gt; executeSomething(@RequestParam(value = &quot;keyword&quot;) final String keyword) {
		final SearchBusinessDelegate delegate = delegateFactory.getObject();
		delegate.initCriteria(new SearchCriteria(keyword, true), 100);
		return delegate.executeSearch();
	}
}
</pre>
<p>This way we can get a prototype instance of our delegate for each invocation while taking advantage of Spring dependency injection and other Spring features (e.g., AOP, post processing, etc.) for our prototype.</p>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/spring-prototype-scoped-beans-and-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Spring Application Context Hierarchy and ContextSingletonBeanFactoryLocator</title>
		<link>http://techo-ecco.com/blog/spring-application-context-hierarchy-and-contextsingletonbeanfactorylocator/</link>
		<comments>http://techo-ecco.com/blog/spring-application-context-hierarchy-and-contextsingletonbeanfactorylocator/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 19:20:40 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[context]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=107</guid>
		<description><![CDATA[Setting up spring application context hierarchies in a typical enterprise dependency stack using ContextSingletonBeanFactoryLocator]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/04/hierarchy.jpg" alt="hierarchy Spring Application Context Hierarchy and ContextSingletonBeanFactoryLocator" align="right" width="250" title="Spring Application Context Hierarchy and ContextSingletonBeanFactoryLocator" /><br />
Large scale development environments are typically composed of multiple application component stacks each of which can be represented as a directed graph of dependencies between components. </p>
<p><span id="more-107"></span></p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2010/02/dependency-graph.gif" alt="dependency graph Spring Application Context Hierarchy and ContextSingletonBeanFactoryLocator"  title="Spring Application Context Hierarchy and ContextSingletonBeanFactoryLocator" /></p>
<p>For each application there is typically a single top node (the web or desktop application layer). From this node the dependencies spread out to the various components which the application requires. Further down the stack these dependencies join where low level components are shared by higher level components for re-usability. </p>
<p>When you decide to go full stack Spring, modularity can get tricky, the Spring documentation typically tells you to bootstrap the application context in code or via the deployment descriptor (web.xml for j2ee web applications using <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/web/context/ContextLoaderListener.html" target="blank">ContextLoaderListener</a>).</p>
<p>In code this is done by instantiating one of the <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/context/ApplicationContext.html" target="blank">ApplicationContext</a> variants:</p>
<pre class="brush: java; title: ; notranslate">
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {&quot;a1-file.xml&quot;, &quot;a2-file.xml&quot;});
</pre>
<p>In the <strong>web.xml</strong> the configuration is quite similar:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;context-param&gt;
  &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
  &lt;param-value&gt;/WEB-INF/a1-file.xml /WEB-INF/a2-file.xml&lt;/param-value&gt;
&lt;/context-param&gt;

&lt;listener&gt;
  &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
</pre>
<p>But now what happens when you want to inject dependencies from lower level components into higher level components? The most straightforward solution is to add an import into <strong>A</strong>&#8216; s context file:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;beans&gt;
    &lt;import resource=&quot;classpath*:b1-file.xml&quot;/&gt;
    &lt;import resource=&quot;classpath*:b2-file.xml&quot;/&gt;
    &lt;import resource=&quot;classpath*:c1-file.xml&quot;/&gt;
    &lt;import resource=&quot;classpath*:c2-file.xml&quot;/&gt;   

    &lt;!-- from here on A's beans can be injected with b's and c's beans --&gt;
&lt;/beans&gt;
</pre>
<p>This seems easy but has some obvious pitfalls. For starters we just stated that A has to manage the bean definition for the entire stack which reeks of a maintenance hurdle. A more natural approach would be to have each component manage its own bean definition and define a single dependency between each component in the graph. </p>
<p>To solve this we can create a single file in each component, a descriptor file if you wish, and import only that component&#8217;s file-set in the descriptor file.</p>
<p>So <strong>B</strong>&#8216;s and <strong>C</strong>&#8216;s descriptors would look like</p>
<p>SpringDescriptor.xml in component <strong>B</strong>:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;beans&gt;
    &lt;import resource=&quot;classpath*:b1-file.xml&quot;/&gt;
    &lt;import resource=&quot;classpath*:b2-file.xml&quot;/&gt;
&lt;/beans&gt;
</pre>
<p>SpringDescriptor.xml in component <strong>C</strong>:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;beans&gt;
    &lt;import resource=&quot;classpath*:c1-file.xml&quot;/&gt;
    &lt;import resource=&quot;classpath*:c2-file.xml&quot;/&gt;
&lt;/beans&gt;
</pre>
<p>This way we can define a single import for all the components in our stack in <strong>A</strong>&#8216;s context:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;beans&gt;
    &lt;import resource=&quot;classpath*:**/**SpringDescriptor*.xml&quot;/&gt;   

    &lt;!-- from here on A's beans can be injected with any component that contains the SpringDescriptor*.xml files --&gt;
&lt;/beans&gt;
</pre>
<p>So is this good enough? IMO no, it still has some drawbacks. When you load your beans this way, everything gets piled loaded into a single ApplicationContext which is created at the application&#8217;s entry point and contains beans from the entire stack. For small applications with few dependencies this might work but when this scales up things might get tangled. For example defining <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/beans/factory/config/BeanPostProcessor.html" target="blank">BeanPostProcessor</a> or <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html" target="blank">PropertyPlaceholderConfigurer</a> for a single-component-scope is not possible in this design and is often desirable. </p>
<p>Another evil scenario I&#8217;ve come across is one where due to improper initialization of the application context (using a static singleton for bootstrapping application context) the application context actually gets initialized twice. Spring references this scenario in <a href="http://static.springsource.org/spring/docs/current/reference/beans.html" target="blank">Glue code and the evil singleton</a>.</p>
<p>To the rescue comes <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/context/access/ContextSingletonBeanFactoryLocator.html" target="blank">ContextSingletonBeanFactoryLocator</a> which brings a bombastrous name and a handy solution for the task at hand.</p>
<p>The idea here is that every component contains a descriptor XML file (similar to our <strong>SpringDescriptor.xml</strong>, the default convention is <strong>beanRefContext.xml</strong> which can be customized by defining a different selector). This descriptor is keyed and defines the application context for that component.<br />
Here is an example of the <strong>beanRefContext.xml</strong> from our <strong>B</strong> component.</p>
<pre class="brush: xml; title: ; notranslate">
 &lt;beans&gt;
   &lt;bean id=&quot;bContext&quot;
         class=&quot;org.springframework.context.support.ClassPathXmlApplicationContext&quot;&gt;
     &lt;constructor-arg&gt;
       &lt;list&gt;
         &lt;value&gt;b1-file.xml&lt;/value&gt;
         &lt;value&gt;b2-file.xml&lt;/value&gt;
       &lt;/list&gt;
     &lt;/constructor-arg&gt;
     &lt;constructor-arg ref=&quot;cContext&quot;&gt;
   &lt;/bean&gt;

 &lt;/beans&gt;
</pre>
<p>As you can see this is nothing short of instantiating an <strong>ApplicationContext</strong> for each component in our graph, taking advantage of the second constructor argument of <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/context/support/ClassPathXmlApplicationContext.html" target="blank">ClassPathXmlApplicationContext</a> which defines a parent context. Yes, <strong>ApplicationContext</strong>s can be chained in a hierarchy (unidirectional, beans can &#8220;see&#8221; other beans in parent contexts only and not vice-versa). </p>
<p>Bootstrapping the context in code is the carried out this way:</p>
<pre class="brush: java; title: ; notranslate">
BeanFactoryLocator beanFactoryLocator = ContextSingletonBeanFactoryLocator.getInstance();
BeanFactoryReference beanFactoryReference = beanFactoryLocator.useBeanFactory(&quot;aContext&quot;);
BeanFactory beanFactory = beanFactoryReference.getFactory();
</pre>
<p>Note that the <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/context/access/ContextSingletonBeanFactoryLocator.html#getInstance(java.lang.String)" target="blank">getInstance</a> method of the <strong>ContextSingletonBeanFactoryLocator</strong> class has an overload which accepts a selector argument designating the convention for descriptor files. </p>
<p>In a web deployment the <strong>ContextSingletonBeanFactoryLocator</strong> is utilized using the <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/web/context/ContextLoader.html#LOCATOR_FACTORY_KEY_PARAM" target="blank">LOCATOR_FACTORY_KEY_PARAM</a> and the <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/web/context/ContextLoader.html#LOCATOR_FACTORY_SELECTOR_PARAM" target="blank">LOCATOR_FACTORY_SELECTOR_PARAM</a> of the <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/web/context/ContextLoader.html" target="blank">ContextLoader</a> class. These can be specified in <strong>web.xml</strong></p>
<pre class="brush: xml; title: ; notranslate">
&lt;context-param&gt;
  &lt;param-name&gt;parentContextKey&lt;/param-name&gt;
  &lt;param-value&gt;aContext&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;!-- Specfies the parent context of the root WebApplicationContext --&gt;

&lt;context-param&gt;
  &lt;param-name&gt;locatorFactorySelector&lt;/param-name&gt;
  &lt;param-value&gt;SpringDescriptor.xml&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;!-- Specifies a different convention. the default being beanRefContext.xml --&gt;
</pre>
<p>The only problem which remains is how to define components with more than one parent contexts. This cannot be done with the standard <strong>ApplicationContext</strong> as it only accepts a single context for the parent, which forces a liner hierarchy between contexts. You could still arrange the context so that all beans have the desired visibility scope for example the dependency graph shown above could be organized the following way:</p>
<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2010/02/dependency-graph-spring.gif" alt="dependency graph spring Spring Application Context Hierarchy and ContextSingletonBeanFactoryLocator"  title="Spring Application Context Hierarchy and ContextSingletonBeanFactoryLocator" /></p>
<p>Finally, with the introduction of <a href="http://www.springsource.org/osgi" target="blank">Spring OSGi</a> the approach towards initialization and life-cycle of <strong>ApplicationContext</strong>s has changed but more on that in another post.</p>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/spring-application-context-hierarchy-and-contextsingletonbeanfactorylocator/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>List of my favorite eclipse plugins</title>
		<link>http://techo-ecco.com/blog/list-of-my-favorite-eclipse-plugins/</link>
		<comments>http://techo-ecco.com/blog/list-of-my-favorite-eclipse-plugins/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 20:53:25 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[J2EE]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=95</guid>
		<description><![CDATA[Can anyone remember the days when jBuilder was the king of J2EE IDEs? can you imagine what J2EE development look like without Eclipse? However, eclipse truely reveals its power when you add healthy dosage of plugins to the mix. Everyone has their list, here are my favorites:]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/04/connect.jpg" alt="connect List of my favorite eclipse plugins" align="right" width="250" title="List of my favorite eclipse plugins" /><br />
Can anyone remember the days when jBuilder was the king of J2EE IDEs? can you imagine what J2EE development look like without Eclipse?</p>
<p>However, eclipse truely reveals its power when you add healthy dosage of plugins to the mix. Everyone has their list, here are my favorites:</p>
<p><span id="more-95"></span><br />

<table id="wp-table-reloaded-id-1-no-1" class="wp-table-reloaded wp-table-reloaded-id-1">
<thead>
	<tr class="row-1 odd">
		<th class="column-1">Name</th><th class="column-2">Web Page</th><th class="column-3">Update Site</th><th class="column-4">Comments</th>
	</tr>
</thead>
<tbody>
	<tr class="row-2 even">
		<td class="column-1">SpringSTS</td><td class="column-2"><a href="http://www.springsource.com/products/sts" target="blank">Plugin Web Page</a><br />
</td><td class="column-3"><a href="http://dist.springsource.com/snapshot/STS/nightly/e3.4<br />
" target="blank">http://dist.springsource.com/snapshot/STS/nightly/e3.4<br />
</a><br />
</td><td class="column-4">A must for anyone who uses spring<br />
for eclipse 3.5 see <a href="http://blog.springsource.com/2009/06/24/installing-sts-into-eclipse-35/" target="blank">the spring blog</a></td>
	</tr>
	<tr class="row-3 odd">
		<td class="column-1">FindBugs</td><td class="column-2"><a href="http://findbugs.sourceforge.net/" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://findbugs.cs.umd.edu/eclipse" target="blank">http://findbugs.cs.umd.edu/eclipse</a><br />
</td><td class="column-4">Find bugs is a must for any developer, you can learn about avoiding common coding mistakes, and become a better programmer  </td>
	</tr>
	<tr class="row-4 even">
		<td class="column-1">PMD</td><td class="column-2"><a href="http://pmd.sourceforge.net/" target="blank">Plugin Web Page</a><br />
</td><td class="column-3"><a href="http://pmd.sourceforge.net/eclipse" target="blank">http://pmd.sourceforge.net/eclipse</a></td><td class="column-4">PMD complements and enhances FindBugs</td>
	</tr>
	<tr class="row-5 odd">
		<td class="column-1">EclEmma</td><td class="column-2"><a href="http://www.eclemma.org/" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://update.eclemma.org/" target="blank">http://update.eclemma.org/</a></td><td class="column-4">Get instant coverage information on your unit and integration tests</td>
	</tr>
	<tr class="row-6 even">
		<td class="column-1">Spell Checker</td><td class="column-2"><a href="http://www.bdaum.de/eclipse/" target="blank">Plugin Web Page</a></td><td class="column-3"> <a href="http://www.bdaum.de/eclipse/eSpell3" target="blank">http://www.bdaum.de/eclipse/eSpell3</a></td><td class="column-4">For some reason I was never quite happy with the eclipse spell chekcer. </td>
	</tr>
	<tr class="row-7 odd">
		<td class="column-1">JbossTools</td><td class="column-2"><a href="http://www.hibernate.org/255.html" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://download.jboss.org/jbosstools/updates/stable/" target="blank">http://download.jboss.org/jbosstools/updates/stable/</a></td><td class="column-4">A must for hibernate users</td>
	</tr>
	<tr class="row-8 even">
		<td class="column-1">Subclipse SVN</td><td class="column-2"><a href="http://subclipse.tigris.org/" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://subclipse.tigris.org/update_1.6.x" target="blank">http://subclipse.tigris.org/update_1.6.x</a></td><td class="column-4">SVN source control plugin</td>
	</tr>
	<tr class="row-9 odd">
		<td class="column-1">AccuBridge for Accurev</td><td class="column-2"><a href="http://www.accurev.com/accubridge.html" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://www.accurev.com/download/eclipseupdate/34" target="blank">http://www.accurev.com/download/eclipseupdate/34</a></td><td class="column-4">Source control plugin for Accurev (the plugin is free, the software is not)</td>
	</tr>
	<tr class="row-10 even">
		<td class="column-1">JsEclipse</td><td class="column-2"><a href="http://www.interaktonline.com/products/eclipse/jseclipse/overview/" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://download.macromedia.com/pub/labs/jseclipse/autoinstall/" target="blank">http://download.macromedia.com/pub/labs/jseclipse/autoinstall/</a></td><td class="column-4">Javascript plugin</td>
	</tr>
	<tr class="row-11 odd">
		<td class="column-1">Atlassian IDE Connector</td><td class="column-2"><a href="http://confluence.atlassian.com/display/IDEPLUGIN/IDE+Connector+Documentation" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://update.atlassian.com/atlassian-eclipse-plugin/e3.4" target="blank">http://update.atlassian.com/atlassian-eclipse-plugin/e3.4</a></td><td class="column-4">Great for Jira and other Atlassian products,  update site works for eclipse 3.5 as well></td>
	</tr>
	<tr class="row-12 even">
		<td class="column-1">Structure 101</td><td class="column-2"><a href="http://www.headwaysoftware.com/products/structure101/plugin/index.php" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://www.headwaysoftware.com/downloads/structure101/ideplugin/eclipse/" target="blank">http://www.headwaysoftware.com/downloads/structure101/ideplugin/eclipse/</a></td><td class="column-4">Structure 101 Plugin, <a href="http://www.agilej.com/structureViews" target="blank">AgileJ</a> has one too if you use that</td>
	</tr>
	<tr class="row-13 odd">
		<td class="column-1">IvyDE</td><td class="column-2"><a href="http://ant.apache.org/ivy/ivyde/" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://www.apache.org/dist/ant/ivyde/updatesite" target="blank">http://www.apache.org/dist/ant/ivyde/updatesite</a></td><td class="column-4">Plugin for working with Apache Ivy</td>
	</tr>
	<tr class="row-14 even">
		<td class="column-1">JDepend4Eclipse</td><td class="column-2"><a href="http://andrei.gmxhome.de/jdepend4eclipse/index.html" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://andrei.gmxhome.de/eclipse/" target="blank" />http://andrei.gmxhome.de/eclipse/</a></td><td class="column-4">A java dependency analysis tool (a free albeit feature-less version of structure 101)</td>
	</tr>
	<tr class="row-15 odd">
		<td class="column-1">Perforce P4WSAD</td><td class="column-2"><a href="http://www.perforce.com/perforce/products/p4wsad.html" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://www.perforce.com/downloads/http/p4-wsad/install/3.5" target="blank">http://www.perforce.com/downloads/http/p4-wsad/install/3.5</a></td><td class="column-4">A plugin for working with the Perforce SCM system</td>
	</tr>
	<tr class="row-16 even">
		<td class="column-1">Google Eclipse Plugin</td><td class="column-2"><a href="http://code.google.com/eclipsel" target="blank">Plugin Web Page</a></td><td class="column-3"><a href="http://dl.google.com/eclipse/plugin/3.6" target="blank">http://dl.google.com/eclipse/plugin/3.6</a></td><td class="column-4">A plugin for working with Google Web Toolkit and Google App Engine</td>
	</tr>
</tbody>
</table>
</p>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/list-of-my-favorite-eclipse-plugins/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pattern based resource matching with Spring&#8217;s PathMatchingResourcePatternResolver</title>
		<link>http://techo-ecco.com/blog/pattern-based-resource-matching-with-springs-pathmatchingresourcepatternresolver/</link>
		<comments>http://techo-ecco.com/blog/pattern-based-resource-matching-with-springs-pathmatchingresourcepatternresolver/#comments</comments>
		<pubDate>Mon, 18 Jan 2010 13:54:49 +0000</pubDate>
		<dc:creator>erez</dc:creator>
				<category><![CDATA[Java/J2EE]]></category>
		<category><![CDATA[J2EE]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[resolution]]></category>
		<category><![CDATA[resource]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://techo-ecco.com/blog/?p=86</guid>
		<description><![CDATA[Spring has a very good resource abstraction mechanism allowing resources to be defined in the application context in a simple fashion, automatic assignment to class members based on type, etc. In addition Spring provides an Ant-like pattern for locating resources, this comes into play in the resource location definition of an application context (when defined [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://techo-ecco.com/blog/wp-content/uploads/2011/04/puzzle.jpg" alt="puzzle Pattern based resource matching with Springs PathMatchingResourcePatternResolver" align="right" width="250" title="Pattern based resource matching with Springs PathMatchingResourcePatternResolver" /><br />
Spring has a very good <a href="http://static.springsource.org/spring/docs/current/reference/resources.html" target="blank">resource abstraction</a> mechanism allowing resources to be defined in the application context in a simple fashion, automatic assignment to class members based on type, etc. In addition Spring provides an Ant-like pattern for locating resources, this comes into play in the resource location definition of an application context (when defined in web.xml, beanRefContext.xml etc.):<br />
<span id="more-86"></span></p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;myApplicationContext&quot; lazy-init=&quot;false&quot;
	class=&quot;org.springframework.context.support.ClassPathXmlApplicationContext&quot;&gt;
	&lt;constructor-arg&gt;
		&lt;list&gt;
			&lt;value&gt;classpath*:myJar-applicationContext.xml&lt;/value&gt;
			&lt;value&gt;localXml-applicationContext.xml&lt;/value&gt;
		&lt;/list&gt;
	&lt;/constructor-arg&gt;
&lt;/bean&gt;
</pre>
<p>And then again in <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/orm/hibernate3/LocalSessionFactoryBean.html" target="blank">LocalSessionFactoryBean</a> when defining hibernate mapping locations:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;hibernateSessionFactory&quot;
	class=&quot;org.springframework.orm.hibernate3.LocalSessionFactoryBean&quot;&gt;
	&lt;property name=&quot;mappingLocations&quot;&gt;
		&lt;list&gt;
			&lt;value&gt;classpath*:org/echotech/**/*.hbm.xml&lt;/value&gt;
			...
		&lt;/list&gt;
	&lt;/property&gt;
	...
&lt;/bean&gt;
</pre>
<p>And on to several more places in the Spring framework where resource locations need to be defined. At the heart of this mechanism lies the <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/core/io/support/PathMatchingResourcePatternResolver.html" target="blank">PathMatchingResourcePatternResolver</a> class. This class is not exposed much in the Spring documentation, I guess framework developers treat it as an internal utility class. </p>
<p>Why is this useful to me? I the enterprise application domain resources can be quite difficult to manage, they are usually numerous and they reside in many artifacts (jars). Good componentization is useful, almost a must, for defining resource-ownership, but sometimes cross-cutting concerns require you to scan and retrieve everything. Assuming naming conventions are well-enforced, pattern-based resolution can prove to be quite powerful.</p>
<p>In my example I want to use pattern matching for classes rather than resources. Here is the proposed bean definition:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;bean id=&quot;classResourcePatternResolver&quot; class=&quot;org.echotech.util.ClassResourcePatternResolver&quot;&gt;
	&lt;constructor-arg&gt;
		&lt;list&gt;
			&lt;value&gt;classpath*:org/echotech/**/**Service.class&lt;/value&gt;
		&lt;/list&gt;
	&lt;/constructor-arg&gt;
&lt;/bean&gt;
</pre>
<p>As you can see I am trying to capture of all of my service classes, regardless of package location (or physical jar/compiled class location). Here is the implementation of ClassResourcePatternResolver:</p>
<pre class="brush: java; title: ; notranslate">
public class ClassResourcePatternResolver {

	private static final String CLASS_SUFFIX = &quot;.class&quot;;
	private static final String CLASSES_LOCATION = &quot;classes&quot;;

	private final List&lt;Class&lt;?&gt;&gt; classes = new LinkedList&lt;Class&lt;?&gt;&gt;();
	private final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

	public ClassResourcePatternResolver(final List&lt;String&gt; resourceLocations) throws IOException,
			ClassNotFoundException {
		for (final String resourceLocation : resourceLocations) {
			classes.addAll(resolveClassesFromPattern(resourceLocation));
		}
	}

	private Collection&lt;Class&lt;?&gt;&gt; resolveClassesFromPattern(final String pattern)
			throws IOException, ClassNotFoundException {
		final Collection&lt;Class&lt;?&gt;&gt; classes = new LinkedList&lt;Class&lt;?&gt;&gt;();
		if (ResourcePatternUtils.isUrl(pattern)) {
			final Resource[] resources = resourcePatternResolver.getResources(pattern);
			for (final Resource resource : resources) {
				final String className;
				final URL url = resource.getURL();
				if (ResourceUtils.isJarURL(url)) {
					className = resolveClassFromjar(url.toString());
				} else {
					className = resolveClassFromPath(url.toString());
				}

				if (StringUtils.hasText(className)) {
					classes.add(Class.forName(className));
				}
			}
		} else {
			classes.add(Class.forName(pattern));
		}

		return classes;
	}

	private static String resolveClassFromPath(final String url) {
		final String classUrl = url.substring(url.indexOf(CLASSES_LOCATION)
				+ CLASSES_LOCATION.length() + 1, url.indexOf(CLASS_SUFFIX));
		return ClassUtils.convertResourcePathToClassName(classUrl);
	}

	private static String resolveClassFromjar(final String url) {
		final String classUrl = url.substring(url.indexOf(ResourceUtils.JAR_URL_SEPARATOR) + 2, url
				.indexOf(CLASS_SUFFIX));
		return ClassUtils.convertResourcePathToClassName(classUrl);
	}

	public List&lt;Class&lt;?&gt;&gt; getClasses() {
		return classes;
	}
}
</pre>
<p>Notice that I have to handle both the jar resource url and the local filesystem resource url (assuming in any scenario the compile classes will either reside in a jar or in an exploded classes directory, be it <strong>/WEB-INF/classes</strong> or <strong>build/classes</strong>). Notice I&#8217;ve used several utility classes from the Spring toolbox such as <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/util/ClassUtils.html" target="blank">ClassUtils</a>, <a href="http://static.springsource.org/spring/docs/current/api/org/springframework/core/io/support/ResourcePatternUtils.html" target="blank">ResourcePatternUtils</a> and more, all complement each other in this implementation.</p>
<p>Finally a simple unit test:</p>
<pre class="brush: java; title: ; notranslate">
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { &quot;/spring/util-context.xml&quot; })
public class ClassResourcePatternResolverTest extends AbstractJUnit38SpringContextTests {
	@Autowired
	private ClassResourcePatternResolver classResourcePatternResolver;

	@Test
	public void test() throws Exception {

		List&lt;Class&lt;?&gt;&gt; classes = classResourcePatternResolver.getClasses();

		for (Class&lt;?&gt; clazz : classes) {
			System.out.println(&quot;Resolved class: &quot; + clazz.getName());
		}
	}
}
</pre>
<p>Will produce the following output:</p>
<pre class="brush: plain; title: ; notranslate">
...
Resolved class: org.echotech.service.AnotherService
Resolved class: org.echotech.service.MyService
</pre>
<p>I can easily use this to detect classes from the entire classpath, changing the pattern to <strong>classpath*:org/**/**Url*.class</strong> will detect all classes containing Url in my classpath</p>
<pre class="brush: plain; title: ; notranslate">
...
Resolved class: org.apache.jasper.tagplugins.jstl.core.Url
Resolved class: org.springframework.remoting.support.UrlBasedRemoteAccessor
Resolved class: org.springframework.core.io.UrlResource
Resolved class: org.springframework.web.util.UrlPathHelper
Resolved class: org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping
Resolved class: org.springframework.web.servlet.handler.AbstractUrlHandlerMapping$PathExposingHandlerInterceptor
Resolved class: org.springframework.web.servlet.handler.AbstractUrlHandlerMapping$UriTemplateVariablesHandlerInterceptor
Resolved class: org.springframework.web.servlet.handler.AbstractUrlHandlerMapping
Resolved class: org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
Resolved class: org.springframework.web.servlet.handler.SimpleUrlHandlerMapping
Resolved class: org.springframework.web.servlet.mvc.AbstractUrlViewController
Resolved class: org.springframework.web.servlet.mvc.UrlFilenameViewController
Resolved class: org.springframework.web.servlet.mvc.multiaction.AbstractUrlMethodNameResolver
Resolved class: org.springframework.web.servlet.mvc.support.AbstractControllerUrlHandlerMapping
Resolved class: org.springframework.web.servlet.tags.UrlTag$UrlType
Resolved class: org.springframework.web.servlet.tags.UrlTag
Resolved class: org.springframework.web.servlet.view.AbstractUrlBasedView
Resolved class: org.springframework.web.servlet.view.UrlBasedViewResolver
Resolved class: org.apache.taglibs.standard.tag.common.core.UrlSupport
Resolved class: org.apache.taglibs.standard.tag.el.core.UrlTag
Resolved class: org.apache.taglibs.standard.tag.rt.core.UrlTag
Resolved class: org.apache.tiles.definition.dao.BaseLocaleUrlDefinitionDAO
Resolved class: org.apache.tiles.definition.dao.CachingLocaleUrlDefinitionDAO$WildcardMapping
Resolved class: org.apache.tiles.definition.dao.CachingLocaleUrlDefinitionDAO
Resolved class: org.apache.tiles.definition.dao.LocaleUrlDefinitionDAO
Resolved class: org.apache.tiles.definition.dao.ResolvingLocaleUrlDefinitionDAO
Resolved class: org.apache.tiles.definition.UrlDefinitionsFactory$CompatibilityDefinitionsImpl
Resolved class: org.apache.tiles.definition.UrlDefinitionsFactory
</pre>
]]></content:encoded>
			<wfw:commentRss>http://techo-ecco.com/blog/pattern-based-resource-matching-with-springs-pathmatchingresourcepatternresolver/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

