<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>ICE09 . playing with java, scala, groovy and spring .</title>
	<atom:link href="http://ice09.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ice09.wordpress.com</link>
	<description>Playing with Spring</description>
	<lastBuildDate>Fri, 27 Jan 2012 08:21:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='ice09.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>ICE09 . playing with java, scala, groovy and spring .</title>
		<link>http://ice09.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://ice09.wordpress.com/osd.xml" title="ICE09 . playing with java, scala, groovy and spring ." />
	<atom:link rel='hub' href='http://ice09.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Sample Questions for EIwS-1.x-certification-study-guide</title>
		<link>http://ice09.wordpress.com/2012/01/16/sample-questions-for-eiws-1-x-certification-study-guide/</link>
		<comments>http://ice09.wordpress.com/2012/01/16/sample-questions-for-eiws-1-x-certification-study-guide/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 14:59:35 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=961</guid>
		<description><![CDATA[Currently, I am preparing for the Enterprise Integration with Spring 1.x Certification, with the Study Guide. After having tried to google some of the questions, I had to realize that nobody did try to answer the questions (at least openly). Therefore, I will give it a try. Please be aware that these answers are based [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=961&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Currently, I am preparing for the <b>Enterprise Integration with Spring 1.x Certification</b>, with the <b><a href='http://www.springsource.com/files/uploads/all/EIwS-1.x-certification-study-guide.pdf'>Study Guide</a></b>.</p>
<p>After having tried to google some of the questions, I had to realize that nobody did try to answer the questions (at least openly). Therefore, I will give it a try.<br />
<i>Please be aware that these answers are based on my unterstanding of the question topics. It is not very likely, but they may even be completely false. If they are, please tell me&#8230;</i></p>
<h2>Topics by Subject Area</h2>
<h3>Remoting</h3>
<p><b>General</b></p>
<pre>
<ul>
<li>The concepts involved with Spring Remoting on both server- and client-side
  Configuration and Exposition of Business Services declaratively (with no code changes) using exporters
    Support of different protocols in a consistent way: RMI, EJB, HttpInvoker, Hessian/Burlap
  Usage of remote Business Services transparently on client side (using proxy mechanisms with FactoryBeans)
    Proxy can be injected as Business Service interface, client does not know the service call is remote
</li>
<li>The benefits of Spring Remoting over traditional remoting technologies
  No dependency on a concrete Remoting Technology (is abstracted by exception coversion and automatic proxy creation)
  No adherence to a particular Remoting Technology
    Binding etc. is done by Spring Exporters
    Remoting is done by Proxies generated from FactoryBeans
</li>
<li>The remoting protocols supported by Spring
  RMI(-IIOP), Stateless EJB, HttpInvoker, Hessian/Burlap
</li>
</ul>
</pre>
<p><b>RMI-based Spring Remoting</b></p>
<pre>
<ul>
<li>How Spring Remoting-based RMI is less invasive than plain RMI
  Through the use of the RmiProxyFactoryBean and the RmiServiceExporter Spring supports both traditional RMI (with java.rmi.Remote interfaces and java.rmi.RemoteException)
  and transparent remoting via RMI invokers (with any Java interface)
  Client does not have to deal with RemoteExceptions, Server does not have to extend RMI classes
</li>
</ul>
</pre>
<p><b>Spring HTTP Invoker</b></p>
<pre>
<ul>
<li>How client and server interact with each other
  The HttpInvokerProxy (client) sends a POST request (transparently by calling a method invocation) to the HttpInvokerServiceExporter (server)
  using Java serialization (HTTP as transport protocol)
</li>
</ul>
</pre>
<p>(<a href='http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/remoting.html'>Reference</a>)</p>
<h3>Web Services</h3>
<p><b>General</b></p>
<pre>
<ul>
<li>How do Web Services compare to Remoting and Messaging
  Web Services are interoperable across several platforms. Source and Destination can change, there are no direct dependencies (as with remote method invocation (RPC)).
  Web Services (can) resemble Document-based messaging more than RPC with loose coupling as a result, but both styles (RPC vs. document-oriented approach) exist.
  Spring supports the document-oriented Contract-first approach.
</li>
</ul>
</pre>
<p><b>Spring Web Services</b></p>
<pre>
<ul>
<li>The approach to Spring Web Service that Spring-WS supports
  Spring-WS uses the Contract-first approach (start with XSD/WSDL) instead of annotating pre-existing methods
</li>
<li>The Object-to-XML frameworks supported by Spring-OXM
  JAXB1/2, Castor, XMLBeans, XStream and JiBX
</li>
<li>The strategies supported to map requests to endpoints
  Message Payload, SOAP Action Header, WS-Adressing and XPath
  General Request Processing (Message Dispatcher -&gt; Endpoint Mapping -&gt; Endpoint Adapter -&gt; Endpoint)
  PayloadRootAnnotationMethodEndpointMapping and SoapActionAnnotationMethodEndpointMapping
    Request -&gt; MessageDispatcher -&gt; EndpointMapping -&gt; EndpointInvocationChain -&gt; Endpoint and Interceptors
</li>
<li>Of these strategies, how does @PayloadRoot work exactly?
  Sample:
    @PayloadRoot(localPart = "orderRequest", namespace = "http://samples")
    @ResponsePayload
    public Order getOrder(@RequestPayload OrderRequest orderRequest) {
  For this to work the PayloadRootAnnotationMethodEndpointMapping must be registered as a bean
</li>
<li>The functionality offered by the WebServiceTemplate
  WebServiceTemplate simplifies client Web Service (SOAP) access in the usual Spring Template way (cp. JDBCTemplate, JMSTemplate)
  The main functionality is sending an XML Source and receiving an XML Result
  This functionality can be extended by the usual callback mechanisms (eg. access SOAP Header)
  Can use different protocols (JMS, Mail, XMPP)
</li>
</ul>
</pre>
<p><b>Web Services Security</b></p>
<pre>
<ul>
<li>The underlying WS-Security implementations supported by Spring-WS
  XML Web Services and Security (http://xwss.java.net/), integration with XwsSecurityInterceptor
  Uses callback mechanisms and policy configuration files
  Integration with Spring Security (http://static.springsource.org/spring-security/site/)
</li>
<li>How key stores are supported by Spring-WS for use with WS-Security
  Usage of KeyStoreFactoryBean (Properties password (Keystore) and location (JKS-File))
  Usage of KeyStoreCallbackHandler (with private key password)
</li>
</ul>
</pre>
<h3>RESTFul services with Spring-MVC</h3>
<p><b>General</b></p>
<pre>
<ul>
<li>The main REST principles
  With usage of <b>identifiable resources</b>, an <b>uniform interface</b> (GET, HEAD, PUT, POST, DELETE) is used to represent the (abstract)
  resources with different representations (HTML, XML, PDF, etc.). A control flow (client state transition) is introduced by using
  <b>hypermedia</b> links as return values.
</li>
</ul>
</pre>
<p><b>REST support in Spring-MVC</b></p>
<pre>
<ul>
<li>Spring-MVC is an alternative to JAX-RS, not an implementation</li>
<li>The @RequestMapping annotation, including URI template support
  Sample:
  @Controller
  @RequestMapping("/edit{number}")
  public class EditForm {

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(
            @ModelAttribute("edit") Edit edit, BindingResult result, SessionStatus status) {  
</li>
<li>The @RequestBody and @ResponseBody annotations
  @RequestBody annotated parameters for access to the HTTP request body.
  Parameter values are converted to the declared method argument type using HttpMessageConverters.
  If the method is annotated with @ResponseBody, the return type is written to the response HTTP body.
  The return value will be converted to the declared method argument type using HttpMessageConverters

(a href='http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html'&gt;Reference</a>)
</li>
<li>The functionality offered by the RestTemplate
  Similar to the WebServiceTemplate
  The central class for client-side HTTP access. It simplifies communication with HTTP servers, and enforces RESTful principles.
  It handles HTTP connections, leaving application code to provide URLs (with possible template variables) and extract results.
(a href='http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/client/RestTemplate.html'&gt;Reference</a>)
</li>
</ul>
</pre>
<h3>JMS with Spring</h3>
<p><b>General</b></p>
<pre>
<ul>
<li>Where can Spring-JMS applications obtain their JMS resources from
  The container provides the resource, which can be a standalone JMS provider (eg. ActiveMQConnectionFactory) or an
  application server (jee:jndi-lookup jndi-name="...") - is valid for ConnectionFactory and Destination
</li>
<li>The functionality offered by Spring's JMS message listener container, including the use of a MessageListenerAdapter through the 'method' attribute in the  element
  With the a MessageListener call be called, by specifying the method attribute, any POJO can be used (automatically a
  MessageListenerAdapter is generated for the POJO by the framework)
</li>
<li>The functionality offered by the JmsTemplate
  JmsTemplate delegates to MessageConverter and DestinationResolver.
  MessageConverter: String -&gt; TextMessage, Serializable -&gt; ObjectMessage, Map -&gt; MapMessage, byte[] -&gt; BytesMessage
  DynamicDestinationResolver or JndiDestinationResolver, simple one-method-interface
  Also ConnectionFactory necessary to create a JmsTemplate
</li>
</ul>
</pre>
<h3>Transactions</h3>
<p><b>Local JMS Transactions with Spring</b></p>
<pre>
<ul>
<li>How to enable local JMS transactions with Spring's message listener container
  acknowledge="transacted"
</li>
<li>If and if so, how is a local JMS transaction made available to the JMSTemplate
  sessionTransacted=true
  ConnectionFactoryUtils.doGetTransactionalSession
</li>
<li>How does Spring attempt to synchronize a local JMS transaction and a local database transaction
  DataSourceTransactionManager: commit only after successful database commit
</li>
<li>The functionality offered by the JmsTransactionManager
  send and receive multiple messages in one transaction
  works together with declarative transaction management
</li>
</ul>
</pre>
<p><b>JTA and Two-phased commit transactions with Spring</b></p>
<pre>
<ul>
<li>What guarantees does JTA provide that local transactions do not provide
  ACID guarantees: Atomic, Consistent, Isolated, Durable
  ...but on local transactions only in a single resource
</li>
</ul>
</pre>
<h3>Batch processing with Spring Batch</h3>
<p><b>General</b></p>
<pre>
<ul>
<li>Main concepts (Job, Step, Job Instance, Job Execution, Step Execution, etc.
  Job has its own identity, has steps, has an execution (which has start and stop times and status)
  Client starts JobLauncher, which starts Job (use JobParameters to create JobInstance, which has JobExecutions - same for steps)
  JobLauncher also updates Job metadata in JobRepository
  Reader (single entry) and Writer (chunked) with FieldSetMapper
</li>
<li>The interfaces typically used to implement a chunk-oriented Step
  implements ItemWriter with write(List list) method
</li>
<li>How and where state can be store
  Is handled by JobRepository (ie. in a database or a Map)
</li>
<li>What are job parameters and how are they used
  JobParameters can parameterize a JobInstance (eg. schedule.date)
</li>
<li>What is a FieldSetMapper and what is it used for
  Can be used to customzie an FlatFileItemReader, which uses it to map values (with LineTokenizer and
  FieldSetMapper)
</li>
</ul>
</pre>
<h3>Spring Integration</h3>
<p><b>General</b></p>
<pre>
<ul>
<li>Main concepts (Messages, Channels, Endpoint types)
  Message Channel, Message Endpoint, Pipes and Filters, Message Router, Message Translator
  Framework polls to an event source and notifies/invokes services as necessary (SoC)
  Rules: A Message is sent by an Endpoint, Endpoints are connected by Channels and receive Messages from them
  A Message is MessageHeaders and a payload - is immutable always
  A MessageChannel is used for decoupling, with optional buffereing
  MessageChannel can be Point-to-Point, Publish-subscribe and Pollable
  Types of MessageEndpoints (which are the filters in "pipes-and-filter"): Channel Adapter (Jms, File, Method invokation),
  Service Activator (Invoke Method and wrap result), Gateway (two way integration, sync, inbound waits for reply, outbound waits for response)
</li>
<li>How to programmatically create new Messages
  Use MessageBuilder (is immutable, uses Builder pattern)
</li>
<li>Using chains and bridges
  Chain subsumes several different Endpoints in one channel
  Uses same Thread, Transaction Boundaries, etc.
</li>
</ul>
</pre>
<p><b>Synchronous vs. asynchronous message passing</b></p>
<pre>
<ul>
<li>The different Channel types and how each of them should be used
  Subscribable (Direct, Publish Subscribe)
  Pollable (Queue, Priority, Rendezvous)
</li>
<li>The corresponding effects on things like transactions and security
  Context is lost by switching to queued channel (sync -&gt; async)
</li>
<li>The need for active polling and how to configure that
  Active components are sometimes necessary (JMS, File, etc.)
  Configure poller on the Enpoints
</li>
</ul>
</pre>
<p>(<a href='http://static.springsource.org/spring-ws/site/reference/html/index.html'>Reference</a>)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/961/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/961/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/961/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/961/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/961/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/961/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/961/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/961/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/961/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/961/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/961/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/961/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/961/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/961/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=961&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2012/01/16/sample-questions-for-eiws-1-x-certification-study-guide/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>
	</item>
		<item>
		<title>Groovy vs. Ruby &#8211; the CSV shootout (7L7W day 3)</title>
		<link>http://ice09.wordpress.com/2011/10/18/groovy-vs-ruby-the-csv-shootout-7l7w-day-3/</link>
		<comments>http://ice09.wordpress.com/2011/10/18/groovy-vs-ruby-the-csv-shootout-7l7w-day-3/#comments</comments>
		<pubDate>Tue, 18 Oct 2011 00:14:16 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=929</guid>
		<description><![CDATA[Nope, there is no rant here. Even more, there is no CSV shootout. However, a little CSV is here, it&#8217;s even Meta-CSV somehow. Ok, let&#8217;s clarify this: I just started reading the book &#8220;Seven Languages in Seven Weeks&#8221; and I already like it. It&#8217;s exactly written for someone on my language-knowledge level, ie. someone who [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=929&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Nope, there is no rant here. Even more, there is no CSV shootout. However, a little CSV is here, it&#8217;s even Meta-CSV somehow.</p>
<p>Ok, let&#8217;s clarify this: I just started reading the book <a href='http://www.amazon.com/Seven-Languages-Weeks-Programming-Programmers/dp/193435659X/ref=sr_1_1?ie=UTF8&amp;qid=1318894141&amp;sr=8-1'>&#8220;Seven Languages in Seven Weeks&#8221;</a> and I already like it. It&#8217;s exactly written for someone on my language-knowledge level, ie. someone who tried and used several languages and is pretty good at getting the differences between OO and functional languages, but has difficulties to explain what differentiates Clojure from Scala from Haskell from Io besides the different kinds of typing (static vs. dynamic). Someone who has heard of but never knew what <i>prototypes</i> are about and what specialities each language defines (the movie comparison also helps a lot. But be aware that Prolog developers have to relax a little and accept to be compared to Rain Man).</p>
<p>So, the first day is about Ruby. I know Groovy pretty well, so I thought that would be easy. It was. But, I realize that the subtile differences matter a lot. In short, I <i>feel</i> that Ruby is much more consistent (you will see by the sample). However, I like Groovy more &#8211; after all, for a Java developer it&#8217;s the much better fit. But also, I like the <i>even more</i> magic &#8211; which I&#8217;d hate in big production systems but really love for scripting.</p>
<p>So, the sample is a CSV reader &#8211; the Ruby part is much longer than it has to be, but it should show the Metaprogramming mechanisms. And I like them a lot, even more than the Groovy ones (though <code>Categories</code> are really cool for scoping the Metaprogramming).</p>
<p><pre class="brush: ruby;">
class CsvRow
  attr_accessor :values, :keys
  
  def initialize( keys, values )
    @keys = keys
    @values = values 
  end
  
  def method_missing(id, *args)
    if (id==:to_ary) 
      then return @values 
      else return @values[@keys.index(id.to_s)]
    end
  end
end

module ActsAsCsv
  def self.included(base)
    base.extend ClassMethods
  end
  
  module ClassMethods
    def acts_as_csv
      include InstanceMethods
      include Enumerable
    end
  end
  
  module InstanceMethods   
    attr_accessor :headers, :csv_contents
    
    def each &amp;block
       @csv_contents.each{|csvRow| block.call(csvRow)}
    end
    
    def read
      @csv_contents = []
      filename = self.class.to_s.downcase + '.txt'
      file = File.new(filename)
      @headers = file.gets.chomp.split(';').collect{|s| s.delete(&quot;\&quot;&quot;)}
      
      file.each do |row|
        values = row.chomp.split(';').collect{|s| s.delete(&quot;\&quot;&quot;)}
        @csv_contents &lt;&lt; CsvRow.new(@headers, values)
      end
    end
    
    def initialize
      read 
    end
  end
end

class RubyCsv  # no inheritance! You can mix it in
  include ActsAsCsv
  acts_as_csv
end

m = RubyCsv.new
m.each { |it| puts it.Kontonummer }
</pre></p>
<p>I will not explain how this works here, there are bazillions of resources of people really knowing Ruby. The most important fact is how the Metaprogramming works &#8211; and it does it exactly as expected. Even more, it does it right. The best fact to me is that upon including the module (which unfolds itself into the base class very nicely), the include method is called automatically. There is no dependency of the <code>RubyCsv</code> on it&#8217;s Mixin (and there shouldn&#8217;t be!).</p>
<p>So, this is pretty cool. How do I achieve this in Groovy? This is diffficult, there are no modules in Groovy. Of course, Metaprogramming is easy in Groovy, but I want it to mimick the Ruby script.</p>
<p>The most I can get is by using the Groovy 1.6 <b>@Mixin</b> annotation like this:</p>
<p><pre class="brush: groovy;">
class CsvRow {
    def keys = []
    def values = []
    
    def propertyMissing(String name) { 
        values[keys.indexOf(name)]
    }
}

class ActAsCsv {
    public headers = []
    public csvRows = []
    
    def read(def instance) {
        new File(&quot;rubycsv.txt&quot;).eachLine {
            if (instance.headers.isEmpty()) {
                instance.headers = it.trim().split(';').collect{it.replaceAll(&quot;\&quot;&quot;, &quot;&quot;)}
            } else {
                def values = it.trim().split(';').collect{it.replaceAll(&quot;\&quot;&quot;, &quot;&quot;)}
                instance.csvRows &lt;&lt; new CsvRow(keys:instance.headers, values:values)
            }
        }
    }

    def iterator() {
        csvRows.iterator()
    }
}

@Mixin(ActAsCsv)
class GroovyCsv {
    GroovyCsv() {
        read(this)
    }
    //@Delegate ActAsCsv acter = new ActAsCsv()
}


def act = new GroovyCsv()
println act.collect { it.Buchungstext.reverse() }
act.each { println it.Kontonummer }
</pre></p>
<p>So, this is nice as well, but compared to Ruby it&#8217;s more clumsy. The worst thing is the trick with calling the Mixin in the constructor with the <code>this</code> reference. It does not work otherwise, since the fields cannot be set on the Mixin-GroovyCsv-instance itself. This is weird and costs time to debug. It is not a real dependency upon the Mixin itself, but it&#8217;s just superfluous.<br />
Also, the nice template method style of including modules in Ruby is not <i>the same</i>. It fells better in Ruby (look up the Enumerable inclusion, it&#8217;s really nice). On the other hand, just having to declare <code>iterator()</code> the right way to get rid of all Metaprogamming to implement the Collection methods correctly is cool as well. Also, I found it cleaner to use the <b>@Delegate</b> possibility, which works exactly as expected (no <code>this</code> weirdness here).</p>
<p>It&#8217;s as always, there is no best way, I like both versions a lot. I still feel that Ruby feels cleaner, but I can achieve everything in Groovy with the same &#8220;expressiveness&#8221;. But I can use all Java and all it&#8217;s environment and tools as well &#8211; so jep, to me it&#8217;s the better choice. But I see where a lot of the good stuff in Groovy comes from.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/929/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/929/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/929/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/929/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/929/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/929/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/929/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/929/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/929/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/929/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/929/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/929/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/929/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/929/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=929&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2011/10/18/groovy-vs-ruby-the-csv-shootout-7l7w-day-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>
	</item>
		<item>
		<title>DSLs made easy &#8211; with Groovy&#8217;s chain method calls (GEP 3)</title>
		<link>http://ice09.wordpress.com/2011/10/07/dsls-made-easy-with-groovys-chain-method-calls-gep-3/</link>
		<comments>http://ice09.wordpress.com/2011/10/07/dsls-made-easy-with-groovys-chain-method-calls-gep-3/#comments</comments>
		<pubDate>Fri, 07 Oct 2011 20:18:07 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[DSL]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=913</guid>
		<description><![CDATA[As you probably know, the creation of DSLs is quite easy these days. Take Groovy or Scala and the creation of internal DSLs is a day&#8217;s work. Take Xtext 2.0 and the creation of an external DSL is a two days&#8217;s work. However, let&#8217;s assume you do not have a day, but two hours left [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=913&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As you probably know, the creation of DSLs is quite easy these days. Take <a href='http://victorsavkin.com/post/3146590777/series-dsls-in-groovy-part-1'>Groovy</a> or <a href='http://www.scala-lang.org/node/1403'>Scala</a> and the creation of <a href='http://martinfowler.com/bliki/DomainSpecificLanguage.html'>internal DSLs</a> is a day&#8217;s work. Take <a href='http://www.eclipse.org/Xtext/documentation/'>Xtext 2.0</a> and the creation of an <a href='http://martinfowler.com/bliki/DomainSpecificLanguage.html'>external DSL</a> is a two days&#8217;s work.</p>
<p>However, let&#8217;s assume you do not have a day, but two hours left &#8211; still possible? Yes, indeed. With <a href='http://groovy.codehaus.org/Groovy+1.8+release+notes#Groovy1.8releasenotes-CommandchainsfornicerDomainSpecificLanguages'>Groovy 1.8 and its new chained method calls</a> (contributed <a href='http://docs.codehaus.org/display/GroovyJSR/GEP+3+-+Command+Expression+based+DSL'>by GEP 3</a>).</p>
<p>So, chained method calls have always be possible in Groovy, but the new &#8220;conventions&#8221; of GEP 3 make the creation of a DSL really straightforward, since with a little effort you can design a DSL which has no brackets and dots at all!</p>
<h4>.use case.</h4>
<p>A sample use case for a simple DSL is the evaluation of account data. I wanted to have </p>
<ul>
<li>the possibility to parse downloaded CSV files</li>
<li>enrich the items with certain categories</li>
<li>store them in a local (file based) database</li>
<li>be able to evaluate the items for certain time spans and categories</li>
</ul>
<p>Having thought about the GUI which I would have to create for this use case, I felt overwhelmed immediately, given that my design capabilities are &#8230; debatable. But also, I would like to be able to use the data in several ways, transform it, check and validate it and so on. For this I do not want to create my own command set, but I want to use Groovy commands for this. Namely, I want to create an internal DSL.</p>
<p><b>.sample.</b></p>
<p>The following commands I can think of. However, this is not complete</p>
<pre>
load savingsfile     scans a predefined directory for the newest CSV file with a certain pattern and reads this file into memory
                     (as a list of string arrays)
filter database      filter the data in memory against a predefined database file and remove all items from memory which are in the
                     database already (depends on load step)
categorize data      use a certain rule set (external configuration) to automatically categorize the items according to different properties
                     (like sender/receiver of money)
show data            show the actual data in memory
save database        store the actual data in database file (filter step must be executed first)
</pre>
<p>Moreover, the DSL should allow for evaluating the data in memory, with the following syntax</p>
<pre>
evaluation of date september, 2011 category "Clubbing" with display           evaluate the database and display evaluation for
                                                                              september, 2011 in category "Clubbing"
evaluation of date always category "Clubbing" without display                 same as above, but for no specified time span
evaluation of date always category all with display                           same as above, but for no specified time span and no specified category
evaluation of date always category all without display                        same as above, but without display of data (yes, it might not make sense -
                                                                              but it's possible <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )
</pre>
<p>Now, the thing is that I would like to be able to execute all these commands several times, for different data and &#8211; since the data is available as a list of string arrays &#8211; I know I can do whatever I want with it within Groovy.<br />
So, if I do not have a GUI, what about a shell? Of course, <a href='http://groovy.codehaus.org/Groovy+Shell'>Groovy has one</a>. What about TAB completion on my shiny new DSL &#8211; <a href='http://probabilitytrees.blogspot.com/2011/06/better-tab-completions-for-groovyshell.html'>sure, why not?</a> (ok, honestly, due to type inferencing difficulties, this does not work completely, but it&#8217;s a help definitely &#8211; just try it!)</p>
<p>So, let&#8217;s go. Just start the Groovy shell (GROOVY_HOME/bin/groovysh) and copy &amp; paste this code. Yes, that&#8217;s just the skeleton to show the important parts &#8211; but there is a working version <a href='http://ice09-blogcode.googlecode.com/files/umsatzdsl-07102011.groovy'>here</a>, which works if you are customer of the German Sparkasse (shouldn&#8217;t they pay me for this?). If you really want to use this &#8220;real&#8221;, working version, you will need a rule file, which must be named rules.properties and has key/value pairs of regular expressions for the sender field like PAYPAL=Paypal or ^GA=Geldautomat.</p>
<p><pre class="brush: groovy;">
class Savings {
    def read = false
    def filtered = false
    def datenbank
    Savings(datenbank) {
        this.datenbank = datenbank
    }
    def load(sfile) {
        read = true
        println &quot;file loaded.&quot;
        this
    }
    def display(dummy) {
        if (!read) println &quot;no data available.&quot;
        else println &quot;display called.&quot;
    }
    def filter(sfile) {
        filtered = true
        println &quot;data is filtered.&quot;
        this
    }
    def categorize(cat) {
        println &quot;categorize called with category ${cat}.&quot;
    }
    def save(sfile) {
        if (!filtered) println &quot;data is not filtered, aborting storing.&quot;
        else println &quot;data is stored in file $datenbank&quot;; read = false
    }
}

class Evaluation {
    def month
    def year
    def display = false
    def category
    def date(Integer month, Integer year) {
        this.month = month
        this.year = year
        this
    }
    def date(all) {
        this.month = null
        this.year = null
        this
    }
    def without(display) {
        this.display = false
        evaluate()
    }
    def with(ausgabe) {
        this.display = true
        evaluate()
    }
    def category(category) {
        if (category.toString() != &quot;all&quot;)
            this.category = category
        this
    }
    def evaluate() {
        println &quot;evaluate ${(month != null) ? &quot;month ${month+1} year $year&quot; : &quot;all&quot;} in category $category ${display ? &quot;with&quot;:&quot;without&quot;} display&quot;
    }
}

enum words { savingsfile, category, of, data, database, all, always, with, without, display }
(january, february, march, april, may, june, july, august, september, october, november, december) = (0..11)
datenbank = &quot;db.csv&quot;
import static words.*

savings = new Savings(datenbank)

read = { file -&gt; savings.load(file) }
showit = { speicher -&gt; savings.display()}
filter = { file -&gt; savings.filter(file)}
categorize = { speicher -&gt; savings.categorize(speicher)}
store = { file -&gt; savings.save(file)}
evaluation = { of -&gt; new Evaluation() }

//sample commands

read savingsfile
filter database
categorize data
showit data
store database

evaluation of date september, 2011 category &quot;Clubbing&quot; with display
evaluation of date always category &quot;Clubbing&quot; without display
evaluation of date always category all with display
evaluation of date always category all without display
</pre></p>
<p>The last lines (from //sample commands) are actual commands of the DSL. Try these with TAB completion in the shell and see what&#8217;s possible and what&#8217;s not. I will not explain the functionality in detail, because there are <a href='http://groovyconsole.appspot.com/tag/gep3'>several resources</a> which can be used for clarification. </p>
<h4>.conclusion.</h4>
<p>I wanted to show that two hours can be enough to create your own DSL, together with the Groovy shell this is a really powerful way to let people with limited technical abilities use the power of the complete Java/Groovy platform in interactive mode! Imagine the possibilities &#8211; your business analysts will love you.</p>
<p>Obviously, I had to fit the DSL to the conventions of GEP 3 (and moreover, I had to rename &#8220;load&#8221;, &#8220;show&#8221; and &#8220;save&#8221;, since these are reserved keywords in the Groovy shell&#8230;), but still I think it&#8217;s worth it. But if you take care of DSL design and do not want the language to be restricted by the command chain conventions, look for a cleaner approach. For quick &amp; dirty API usage easing, this works as a charm.</p>
<p>If this blog post was useful to you, you can tip me. Maybe you do not want to tip, but please inform yourself about <a href='http://bitcoin.org/'>Bitcoin</a> and applications of Bitcoin like <a href='http://www.youtipit.org/'>Youttipit</a>. <a href='http://utip.it/t/3118-2' target='_blank' title='DSLs made easy ... with Groovy 1.8'><img src='http://static-youtipit.s3-website-eu-west-1.amazonaws.com/Youtipitorange35.png' /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/913/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/913/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/913/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=913&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2011/10/07/dsls-made-easy-with-groovys-chain-method-calls-gep-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://static-youtipit.s3-website-eu-west-1.amazonaws.com/Youtipitorange35.png" medium="image" />
	</item>
		<item>
		<title>Integrating Spring 3 and MyBatis 3 using the Spring JDBC namespace</title>
		<link>http://ice09.wordpress.com/2011/07/25/integrating-spring-3-and-mybatis-3-using-the-spring-jdbc-namespace/</link>
		<comments>http://ice09.wordpress.com/2011/07/25/integrating-spring-3-and-mybatis-3-using-the-spring-jdbc-namespace/#comments</comments>
		<pubDate>Mon, 25 Jul 2011 20:12:43 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[MyBatis]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=861</guid>
		<description><![CDATA[Sources to this blog post are available here. These can be used with Maven 3 and are best suitable for the SpringSource Tool Suite 2.7.1 (just import the unzipped project as &#8220;Existing Maven project&#8221;) There are several tutorials about the integration of MyBatis 3 in Spring 3 applications, which is kind of special. Even more [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=861&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><b>Sources to this blog post are available <a href='http://code.google.com/p/ice09-blogcode/downloads/detail?name=mybatis-spring-3-sample.zip'>here</a>. These can be used with Maven 3 and are best suitable for the SpringSource Tool Suite 2.7.1 (just import the unzipped project as &#8220;Existing Maven project&#8221;)</b></p>
<p>There are several tutorials about the integration of MyBatis 3 in Spring 3 applications, which is kind of <em><a href="http://code.google.com/p/mybatis/">special</a></em>. Even more tutorials are available about the <a href="http://www.brucephillips.name/blog/index.cfm/2009/11/3/Using-Spring-30-To-Create-An-Embedded-InMemory-Database-In-Your-Java-Application">usage of the Spring-JDBC-namespace</a>, mostly together with an embedded database for for unit tests.</p>
<p>This post will show how to combined these mechanisms using the <a href="http://www.springsource.com/downloads/sts">SpringSource Tool Suite 2.7.1</a>.<br />
There is an explanation of the project artifacts first. Afterwards, a step-by-step guide shows the main steps for the creation of a skeleton of this sample project in the SpringSource Tool Suite.</p>
<p><b>The project structure</b><br />
<a href="http://ice09.files.wordpress.com/2011/07/project11.png"><img class="alignnone size-medium wp-image-865" title="project" src="http://ice09.files.wordpress.com/2011/07/project11.png?w=700&#038;h=661" alt="" width="700" height="661" /></a></p>
<p><b>The unit test <i>IntegrationTests.java</i></b><br />
<pre class="brush: java;">
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class IntegrationTests {
	
	@Autowired
	private UserService service;

	@Test
	public void testGetFirstUser() throws Exception {
		assertNotNull(service);
		assertEquals(&quot;Customer1&quot;, service.getFirstUser());
	}
	@Test
	public void testFindUserByName() throws Exception {
		assertNotNull(service);
		assertEquals(&quot;0&quot;, service.findUserByName(&quot;Customer1&quot;));
		assertEquals(&quot;1&quot;, service.findUserByName(&quot;Customer2&quot;));
	}
}
</pre></p>
<p><b>The corresponding configuration file <i>IntegrationTests-context.xml</i></b><br />
<pre class="brush: xml;">
&lt;beans&gt;
	&lt;import resource=&quot;classpath:/META-INF/spring/app-context.xml&quot;/&gt; 

	&lt;jdbc:embedded-database id=&quot;dataSource&quot;&gt;
		&lt;jdbc:script location=&quot;classpath:/de/ice09/blog/init-sql/schema.sql&quot; /&gt;
		&lt;jdbc:script location=&quot;classpath:/de/ice09/blog/init-sql/data.sql&quot; /&gt;
	&lt;/jdbc:embedded-database&gt;
&lt;/beans&gt;
</pre></p>
<p><b>The referenced DDL-SQL for the (embedded test) database (hsqldb)</b><br />
<pre class="brush: sql;">
drop table customer if exists;
create table customer (id integer identity primary key, name varchar(50) not null );
</pre></p>
<p><b>The referenced SQL for initialization of the (embedded) database</b><br />
<pre class="brush: sql;">
insert into customer (name) values ('Customer1');
insert into customer (name) values ('Customer2');
</pre></p>
<p><b>Referenced <i>app-context.xml</i> &#8211; the main configuration file</b><br />
<pre class="brush: xml;">
&lt;beans&gt;
	&lt;import resource=&quot;classpath:/META-INF/spring/dao-context.xml&quot; /&gt;
	&lt;context:component-scan base-package=&quot;de.ice09.blog&quot; /&gt;
&lt;/beans&gt;
</pre></p>
<p><b>The included <i>dao-context.xml</i> infrastructure and DAO configuration file</b><br />
<pre class="brush: xml;">
&lt;beans&gt;
	&lt;!-- infrastructure --&gt;
	&lt;bean id=&quot;sqlSessionFactory&quot; class=&quot;org.mybatis.spring.SqlSessionFactoryBean&quot;&gt;
		&lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot; /&gt;
	&lt;/bean&gt;
	&lt;!-- MyBatis Mapper --&gt;	
	&lt;bean id=&quot;userMapper&quot; class=&quot;org.mybatis.spring.mapper.MapperFactoryBean&quot;&gt;
		&lt;property name=&quot;mapperInterface&quot; value=&quot;de.ice09.blog.dao.mybatis.UserMapper&quot; /&gt;
		&lt;property name=&quot;sqlSessionFactory&quot; ref=&quot;sqlSessionFactory&quot; /&gt;
	&lt;/bean&gt;
&lt;/beans&gt;
</pre></p>
<p><b>The service interface</b><br />
<pre class="brush: java;">
public interface UserService {
	String getFirstUser();
	String findUserByName(String name);
}
</pre></p>
<p><b>The UserService implementation with injected DAO-Mapper</b><br />
<pre class="brush: java;">
@Component
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;
	
	public String getFirstUser() {
		List&lt;User&gt; users = userMapper.getUsers();
		return users.get(0).getLastName();	
	}
	public String findUserByName(String name) {
		return userMapper.findUserByName(name).getId();
	}
}
</pre></p>
<p><b>The mapper with two possible configuration, the <i>getUsers</i> annotated config and the <i>findUsersByName</i> configuration in XML (see below)</b><br />
<pre class="brush: java;">
public interface UserMapper {
	@Select(&quot;SELECT id, name as lastname FROM customer&quot;)
	List&lt;User&gt; getUsers();
	
	User findUserByName(String name);
}
</pre></p>
<p><b>The sample XML configuration as an alternative for the annotation configuration (for <i>findUserByName</i>)</b><br />
<pre class="brush: xml;">
&lt;mapper namespace=&quot;de.ice09.blog.dao.mybatis.UserMapper&quot;&gt;
	&lt;resultMap id=&quot;userResultMap&quot; type=&quot;de.ice09.blog.domain.User&quot;&gt;
	    &lt;id property=&quot;id&quot; column=&quot;id&quot; /&gt;
	    &lt;result property=&quot;lastname&quot; column=&quot;name&quot;/&gt;
	&lt;/resultMap&gt;
 
	&lt;select id=&quot;findUserByName&quot; parameterType=&quot;string&quot; resultMap=&quot;userResultMap&quot;&gt; 
    	    select id, name from customer where name = #{value}
  	&lt;/select&gt;
&lt;/mapper&gt;
</pre></p>
<h4><b>Creating the Project &#8211; Step by Step</b><br />
<h4>
<p><b>Create a new Spring Template Project in STS</b><br />
<a href="http://ice09.files.wordpress.com/2011/07/new.png"><img class="alignnone size-medium wp-image-864" title="new" src="http://ice09.files.wordpress.com/2011/07/new.png?w=500&#038;h=384" alt="" width="500" height="384" /></a></p>
<p><b>Choose Spring Utility Template</b><br />
<a href="http://ice09.files.wordpress.com/2011/07/utility.png"><img class="alignnone size-medium wp-image-867" title="utility" src="http://ice09.files.wordpress.com/2011/07/utility.png?w=500&#038;h=384" alt="" width="500" height="384" /></a></p>
<p><b>Add namespace to Spring XML configuration</b><br />
<a href="http://ice09.files.wordpress.com/2011/07/addns.png"><img class="alignnone size-medium wp-image-863" title="addns" src="http://ice09.files.wordpress.com/2011/07/addns.png?w=600&#038;h=454" alt="" width="600" height="454" /></a></p>
<p>If this blog post was useful to you, you can tip me. Maybe you do not want to tip, but please inform yourself about <a href='http://bitcoin.org/'>Bitcoin</a> and applications of Bitcoin like <a href='http://www.youtipit.org/'>Youttipit</a>. <a href='http://utip.it/t/3118-1' target='_blank' title='Integrating Spring 3 and MyBatis 3 using the Spring JDBC namespace'><img src='http://static-youtipit.s3-website-eu-west-1.amazonaws.com/Youtipitorange35.png' /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/861/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/861/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/861/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=861&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2011/07/25/integrating-spring-3-and-mybatis-3-using-the-spring-jdbc-namespace/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/07/project11.png?w=300" medium="image">
			<media:title type="html">project</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/07/new.png?w=300" medium="image">
			<media:title type="html">new</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/07/utility.png?w=300" medium="image">
			<media:title type="html">utility</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/07/addns.png?w=300" medium="image">
			<media:title type="html">addns</media:title>
		</media:content>

		<media:content url="http://static-youtipit.s3-website-eu-west-1.amazonaws.com/Youtipitorange35.png" medium="image" />
	</item>
		<item>
		<title>&#8230;afraid of SOAP?</title>
		<link>http://ice09.wordpress.com/2011/06/03/afraid-of-soap/</link>
		<comments>http://ice09.wordpress.com/2011/06/03/afraid-of-soap/#comments</comments>
		<pubDate>Fri, 03 Jun 2011 18:50:14 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[SOAP]]></category>
		<category><![CDATA[Spring Web Services]]></category>

		<guid isPermaLink="false">https://ice09.wordpress.com/?p=812</guid>
		<description><![CDATA[Intention Thinking of Web Services, REST, mostly combined with JSON as the transport medium, currently is everywhere. Having done a lot for the acceptance of Web Services and furthermore simplifying the usage of Web Services themselves, there nevertheless seems to be a strong tendency to overuse REST. How can REST be overused? This obviously depends [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=812&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p></p>
<h3>Intention</h3>
<p>Thinking of Web Services, REST, mostly combined with JSON as the transport medium, currently is everywhere. Having done a lot for the acceptance of Web Services and furthermore simplifying the usage of Web Services themselves, there nevertheless seems to be a strong tendency to overuse REST.</p>
<p>How can REST be overused? This obviously depends on the use case, there are several use cases REST is not the definite answer:</p>
<ul>
<li>A strictly defined format of input and output data (the data transfer format), which can easily be validated</li>
<li>A backend to backend communication, where no REST-affine language like JavaScript is used</li>
<li>Communication between legacy systems which would have to have REST adapters built and already have SOAP-compliant adapters</li>
<li>Pure service-oriented components, as well as (pre-)ESB and EAI systems</li>
</ul>
<p>So, REST is not the answer to all Web Service problems. However, it is often proposed as this. To my experience, this is mainly caused by the fact that people think SOAP is just too complicated, not suitable for light services and just too much overhead. Even though that might be true with respect to WS-*, it is really quite easy to setup Web Services server and clients (and tests) which use SOAP – with no hassle.</p>
<h3>The User Web Service &#8211; A practical approach to SOAP Web Services</h3>
<p>We will follow a really practical approach, ie. many pictures, almost no theoretical background. However, whenever necessary, a link will be present to sites explaining the theoretical background.</p>
<p>In this post, <a href="http://static.springsource.org/spring-ws/sites/2.0/">Spring Web Services 2</a> is used for the server and client side. Even though there are “easier” frameworks around, which make creation of (SOAP) Web Services from existing Java code a breeze, this is exactly the approach you should not follow, if maintenance, extensibility and flexibility is of concern.</p>
<p>So, here is the first drawback: we will use the slightly more complicated “contract-first” approach. But just believe in me: after having dealt with several Web Services, you will never regret the challenging beginning when it comes to maintenance of existing services (including versioning, implementing fixes/patches, etc.)</p>
<h3>Let’s go</h3>
<p>During this post, the Spring Tool Suite (currently 2.6.0) is used. You can just as well use Eclipse (or any other IDE), the STS is used since the Maven plugin is already included, as well as Spring tooling, which supports Spring Web Services and eases usage of this framework.</p>
<ol>
<li>Download <a href="http://www.springsource.com/developer/sts">SpringSource Tool Suite</a></li>
<li>Create new Maven Project with spring-ws-archetype</li>
<li>Add XML Schema (the contract)</li>
<li>Generate JAXB classes, the XML-Java data binding from the XML Schema files</li>
<li>Create Endpoint and Spring WS annotations and config</li>
<li>…that’s it – test it</li>
</ol>
<h4>Step 2: Create new Maven Project with spring-ws-archetype</h4>
<p>Choose “File / New / Other… / Maven Project”</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/mvn_new.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="mvn_new" src="http://ice09.files.wordpress.com/2011/06/mvn_new_thumb.png?w=564&#038;h=406" alt="mvn_new" width="564" height="406" border="0" /></a></p>
<p>Choose “archetype selection” (do not check skip…)</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/mvn_new_2.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="mvn_new_2" src="http://ice09.files.wordpress.com/2011/06/mvn_new_2_thumb.png?w=704&#038;h=265" alt="mvn_new_2" width="704" height="265" border="0" /></a></p>
<p>Choose “Add archetype” and type values according to screenshot (we need to add at least version 2.0.2, currently only 2.0.0-M1 is available in catalog)</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/mvn_choose_at.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="mvn_choose_at" src="http://ice09.files.wordpress.com/2011/06/mvn_choose_at_thumb.png?w=710&#038;h=389" alt="mvn_choose_at" width="710" height="389" border="0" /></a></p>
<p>Choose the added archetype from selection</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/mvn_new_4.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="mvn_new_4" src="http://ice09.files.wordpress.com/2011/06/mvn_new_4_thumb.png?w=712&#038;h=347" alt="mvn_new_4" width="712" height="347" border="0" /></a></p>
<p>Choose the settings for your project, these values are arbitrary (for testing purposes you can use the ones from the screenshot)</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/mvn_new_5.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="mvn_new_5" src="http://ice09.files.wordpress.com/2011/06/mvn_new_5_thumb.png?w=716&#038;h=235" alt="mvn_new_5" width="716" height="235" border="0" /></a></p>
<p>The steps above can be shortened by just creating the Maven project from the command line and importing the generated project as an existing maven project in STS/Eclipse (with “File / Import / Existing Maven project”).</p>
<p><code>mvn archetype:create -DarchetypeGroupId=org.springframework.ws -DarchetypeArtifactId=spring-ws-archetype -DarchetypeVersion=2.0.2.RELEASE -DgroupId=de.ice09.blog -DartifactId=userservice-ws</code></p>
<p>However, for this to work Maven has to be installed correctly, M2_HOME and JAVA_HOME have to be set correctly, etc. Using the steps above just require STS or Eclipse + Maven plugin to be installed.</p>
<p>More details about these steps are available in this <a href="http://www.developer.com/java/ent/top-features-in-spring-ws-2.0-release.html">short &amp; nice blog post</a>.</p>
<p>Right now this project structure should have been generated</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/structure_1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="structure_1" src="http://ice09.files.wordpress.com/2011/06/structure_1_thumb.png?w=290&#038;h=294" alt="structure_1" width="290" height="294" border="0" /></a></p>
<h4>Step 3: Add XML Schema (the contract)</h4>
<p>There are several ways for creating a XML Schema, you can use <a href="http://www.altova.com/xml-editor/">XMLSpy</a>, which to me is the best tool for this task, but is quite expensive. The XML Schema editor in Eclipse is quite useful as well (and integrated and free).</p>
<p>A recent discovery is <a href="http://www.wmhelp.com/download.htm">WMHelp XMLPad</a>, which is pretty cool and supports diagrams similar to those of XMLSpy:</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/getuser.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="GetUser" src="http://ice09.files.wordpress.com/2011/06/getuser_thumb.png?w=788&#038;h=347" alt="GetUser" width="788" height="347" border="0" /></a></p>
<p><a href="http://ice09.files.wordpress.com/2011/06/storeuser.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="StoreUser" src="http://ice09.files.wordpress.com/2011/06/storeuser_thumb.png?w=787&#038;h=294" alt="StoreUser" width="787" height="294" border="0" /></a></p>
<p>These diagrams are quite self-explanatory, we want to have to services, the first one accepts requests of type GetUserRequest, which just have an id and returns a GetUserResponse, which consists of id, firstname, lastname, and 1..n buddies, which themselves are just ids. The second service is StoreUser, which is the “storage” equivalent if the “reading” GetUser service.</p>
<p>Since the contract is the most important part of the Web Service, I will list the XML Schemas as well as sample data here, you can just skip them if you are more interested in the framework usage.</p>
<p>Please note: all posted source code in this blog post is just for clarifying purpose, you do not need to copy &amp; paste this code &#8211; a complete SpringSource Tool Suite/Maven-project <a href="http://code.google.com/p/ice09-blogcode/downloads/detail?name=springws_server_03062011.zip&amp;can=2&amp;q=">is available on Google Code</a>.</p>
<p><b>XML Schema (just GetUser, StoreUser is similar)</b></p>
<p><pre class="brush: xml;"> 
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;schema xmlns=&quot;http://www.w3.org/2001/XMLSchema&quot; xmlns:tns=&quot;http://de.ice09.blog/userservice-ws/&quot;
	targetNamespace=&quot;http://de.ice09.blog/userservice-ws/&quot;&gt;

    &lt;element name=&quot;GetUserRequest&quot;&gt;
    	&lt;complexType&gt;
    		&lt;sequence&gt;
	    		&lt;element name=&quot;id&quot; type=&quot;string&quot;/&gt;
    		&lt;/sequence&gt;
    	&lt;/complexType&gt;
    &lt;/element&gt;
    
    &lt;element name=&quot;GetUserResponse&quot;&gt;
    	&lt;complexType&gt;
	    	&lt;sequence&gt;
	    		&lt;element name=&quot;id&quot; type=&quot;string&quot;/&gt;
	    		&lt;element name=&quot;firstname&quot; type=&quot;string&quot;/&gt;
	    		&lt;element name=&quot;lastname&quot; type=&quot;string&quot;/&gt;
	    		&lt;sequence&gt;
	    			&lt;element name=&quot;Buddies&quot;&gt;
	    				&lt;complexType&gt;
	    					&lt;sequence&gt;
	    						&lt;element name=&quot;Buddy&quot; type=&quot;string&quot; minOccurs=&quot;0&quot; maxOccurs=&quot;unbounded&quot;/&gt;
	    					&lt;/sequence&gt;
	    				&lt;/complexType&gt;
	    			&lt;/element&gt;
	    		&lt;/sequence&gt;
	    	&lt;/sequence&gt;
    	&lt;/complexType&gt;
    &lt;/element&gt;
    
&lt;/schema&gt;
</pre></p>
<h4>Step 4: Generate JAXB classes, the XML-Java data binding from the XML Schema files</h4>
<p>For the next step to work we have to enrich our Maven pom.xml with a jaxb-maven-plugin. This plugin will create the JAXB-classes from the XML Schema files during a Maven build.</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/str_xsd.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="str_xsd" src="http://ice09.files.wordpress.com/2011/06/str_xsd_thumb.png?w=332&#038;h=315" alt="str_xsd" width="332" height="315" border="0" /></a></p>
<p>Add the following lines to the pom.xml in the project’s root folder in section “plugins” as well as the dependencies in section “dependencies”. After saving the file, a new folder “generated-sources” in the target-folder should be created (if this does not happen, choose “Project / Clean”). These are the generated classes, which have to be added to the sources.</p>
<p><b>JAXB2-Maven-Plugin</b></p>
<p><pre class="brush: xml;">
&lt;plugin&gt;
  &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
  &lt;artifactId&gt;jaxb2-maven-plugin&lt;/artifactId&gt;
  &lt;executions&gt;
    &lt;execution&gt;
      &lt;goals&gt;
	&lt;goal&gt;xjc&lt;/goal&gt;
      &lt;/goals&gt;
     &lt;/execution&gt;
   &lt;/executions&gt;
  &lt;configuration&gt;
    &lt;schemaDirectory&gt;src/main/webapp/WEB-INF/&lt;/schemaDirectory&gt;
  &lt;/configuration&gt;
&lt;/plugin&gt;
</pre></p>
<p><a href="http://ice09.files.wordpress.com/2011/06/pom_add_plugin.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="pom_add_plugin" src="http://ice09.files.wordpress.com/2011/06/pom_add_plugin_thumb.png?w=611&#038;h=386" alt="pom_add_plugin" width="611" height="386" border="0" /></a></p>
<p><b>JAXB2-Maven-Dependencies</b></p>
<pre class="brush: xml; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">&lt;dependency&gt;
  &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt;
  &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
  &lt;version&gt;2.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt;
  &lt;artifactId&gt;jaxb-impl&lt;/artifactId&gt;
  &lt;version&gt;2.0.3&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.apache.xmlbeans&lt;/groupId&gt;
  &lt;artifactId&gt;xmlbeans&lt;/artifactId&gt;
  &lt;version&gt;2.4.0&lt;/version&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;junit&lt;/groupId&gt;
  &lt;artifactId&gt;junit&lt;/artifactId&gt;
  &lt;version&gt;4.8.1&lt;/version&gt;
  &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;log4j&lt;/groupId&gt;
  &lt;artifactId&gt;log4j&lt;/artifactId&gt;
  &lt;scope&gt;compile&lt;/scope&gt;
  &lt;version&gt;1.2.16&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p><a href="http://ice09.files.wordpress.com/2011/06/pom_add_deps.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="pom_add_deps" src="http://ice09.files.wordpress.com/2011/06/pom_add_deps_thumb.png?w=500&#038;h=245" alt="pom_add_deps" width="500" height="245" border="0" /></a></p>
<h4>Step 5: Create Endpoint and Spring WS annotations and config</h4>
<p>Create a folder named “java” in src/main-folder and add this folder to the source path, analog to the generated-sources folder. This step might not be necessary in future archetype versions.</p>
<p>Afterwards, this classes must be added to the source folder.<br />
<pre class="brush: java;">
//[imports removed]

@Endpoint
public class GetUserEndpoint {

        @Autowired
        private UserService userService;

        @PayloadRoot(localPart = &quot;GetUserRequest&quot;, namespace = &quot;http://de.ice09.blog/userservice-ws/&quot;)
        @ResponsePayload
        public GetUserResponse getUser(@RequestPayload GetUserRequest request) {
                GetUserResponse response = new ObjectFactory().createGetUserResponse();
                response.setLastname(userService.getName());
                response.setFirstname(&quot;firstname&quot;);
                return response;
        }

}
</pre><br />
A detailed explanation of the annotation can be found on the <a href="http://static.springsource.org/spring-ws/sites/2.0/">Spring Web Services</a> site. For now, only a minimal explanation is given: The @Endpoint annotation lets Spring know that this class will be used as a Web Service endpoint. The @Autowired annotation is standard Spring and results in the service class being injected to the endpoint automatically without XML declarations. The interesting part is the @PayloadRoot annotation in combination with @RequestPayload and @ResponsePayload. There is a lot of convention-over-configuration going on here and a lot of magic inside. If used this way, Spring recognizes the generated JAXB-classes on the classpath. When a XML request with an XML element “GetUserRequest” (localPart) and namespace “http://de.ice09.blog/userservice-ws” arrives, the generated JAXB-classes are used to marshall the XML element to a Java object due to the @Request/ResponsePayload annotations and the presence of JAXB and the generated JAXB-classes on the classpath.</p>
<p>If this is new to you, you should get familiar with it, otherwise it will fall back on you if you have to change anything, eg. from JAXB to Castor, DOM, XPath or whatever. This described usage (JAXB and annotations) is the easiest way possible, but the framework allows for almost any thinkable combination and framework usage. There might be more configuration necessary though.</p>
<p>The service is just listed for completeness, it does nothing special. Just note the @Coomponent annotation. This lets Spring know that this bean/class will be injected somewhere, eg. by using @Autowired as we did.</p>
<p><pre class="brush: java;">
de.ice09.blog.ws.service;

import org.springframework.stereotype.Component;

@Component
public class UserService {

        public String getName() {
                return &quot;lastname&quot;;
        }

}
</pre></p>
<p>Now for the most interesting component, the Spring config. It is already present in the WEB-INF directory. You just have to insert these XML elements:</p>
<pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sws="http://www.springframework.org/schema/web-services"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"&gt;

        &lt;bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"&gt;
                &lt;property name="soapVersion"&gt;
                        &lt;util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_12" /&gt;
                &lt;/property&gt;
        &lt;/bean&gt;

        &lt;sws:annotation-driven /&gt;

        &lt;context:component-scan base-package="de.ice09.blog.ws" /&gt;

        &lt;sws:dynamic-wsdl id="GetUser" portTypeName="UserManagement"
                createSoap12Binding="true" createSoap11Binding="false" locationUri="/userservice"
                targetNamespace="http://de.ice09.blog/userservice-ws/"&gt;
                &lt;sws:xsd location="/WEB-INF/GetUser.xsd" /&gt;
        &lt;/sws:dynamic-wsdl&gt;

        &lt;sws:dynamic-wsdl id="StoreUser" portTypeName="UserManagement"
                createSoap12Binding="true" createSoap11Binding="false" locationUri="/userservice"
                targetNamespace="http://de.ice09.blog/userservice-ws/"&gt;
                &lt;sws:xsd location="/WEB-INF/StoreUser.xsd" /&gt;
        &lt;/sws:dynamic-wsdl&gt;

&lt;/beans&gt;</pre>
<p>The most important element is &lt;sws:annotation-driven&gt;, together with &lt;context:componant-scan&gt;. These elements do all the magic, I highly advise you to get accustomed to the way these elements work. The other parts are just for automatic WSDL generation, which eases the usage of the generated Web Services a lot, but are not necessary for the services themselves. The messageFactory is just for compliance with SOAP 1.2 and can be ignored – just make sure you include it if you want to use SOAP 1.2 instead of SOAP 1.1. Same is true for the dynamic WSDL-generation – the attributes must be set to true and false respectively.</p>
<p>For the WSDL generation, the web.xml has to be modified as well, just add the init-param lines:</p>
<pre class="brush: java; auto-links: true; collapse: false; first-line: 1; gutter: true; html-script: false; light: false; ruler: false; smart-tabs: true; tab-size: 4; toolbar: true;">&lt;servlet&gt;
        &lt;servlet-name&gt;spring-ws&lt;/servlet-name&gt;
        &lt;servlet-class&gt;org.springframework.ws.transport.http.MessageDispatcherServlet
        &lt;/servlet-class&gt;
        &lt;init-param&gt;
                &lt;param-name&gt;transformWsdlLocations&lt;/param-name&gt;
                &lt;param-value&gt;true&lt;/param-value&gt;
        &lt;/init-param&gt;
&lt;/servlet&gt;</pre>
<h4>Step 6: …that’s it – test it</h4>
<p>Yes, that’s it. We created a complete new Web Service with really simple steps.</p>
<p>Just start the Web application now on the STS included tc-Server, just by right-clicking the project and choosing “Run As… / Run on Server”</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/run_final1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="run_final" src="http://ice09.files.wordpress.com/2011/06/run_final_thumb1.png?w=766&#038;h=322" alt="run_final" width="766" height="322" border="0" /></a></p>
<p>Afterwards, navigate to <a href="http://localhost:8080/userservicews/GetUser.wsdl">http://localhost:8080/userservicews/GetUser.wsdl</a> there should be a WSDL printed in the browser.</p>
<p>We can now test the Web Service with a Web Service client, for now we will use <a href="http://www.soapui.org/">soapUI</a>, which is a pretty neat tool for this purpose. You can Web Start it or download it, it requires no install. Even better than soapUI is the Spring Web Service client, which we will investigate in the following blog entry.</p>
<p>After starting soapUI, create a new project and provide the aforementioned WSDL-Url. soapUI will ask for creating a test suite and test cases, which should just be unmodified accepted.</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/soapui_new.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="soapui_new" src="http://ice09.files.wordpress.com/2011/06/soapui_new_thumb.png?w=323&#038;h=101" alt="soapui_new" width="323" height="101" border="0" /></a></p>
<p><a href="http://ice09.files.wordpress.com/2011/06/soapui_new_1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="soapui_new_1" src="http://ice09.files.wordpress.com/2011/06/soapui_new_1_thumb.png?w=682&#038;h=383" alt="soapui_new_1" width="682" height="383" border="0" /></a></p>
<p>If everything worked, you can just choose the created test suite with its test case and run the test case. The result should look like the screenshot.</p>
<p><a href="http://ice09.files.wordpress.com/2011/06/soapui_run1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="soapui_run" src="http://ice09.files.wordpress.com/2011/06/soapui_run_thumb1.png?w=814&#038;h=176" alt="soapui_run" width="814" height="176" border="0" /></a></p>
<p>If this blog post was useful to you, you can tip me. Maybe you do not want to tip, but please inform yourself about <a href='http://bitcoin.org/'>Bitcoin</a> and applications of Bitcoin like <a href='http://www.youtipit.org/'>Youttipit</a>. <a href='http://utip.it/t/3118' target='_blank' title='...afraid of SOAP?'><img src='http://static-youtipit.s3-website-eu-west-1.amazonaws.com/Youtipitorange35.png' /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/812/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/812/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/812/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/812/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/812/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/812/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/812/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/812/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/812/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/812/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/812/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/812/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/812/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/812/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=812&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2011/06/03/afraid-of-soap/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/mvn_new_thumb.png" medium="image">
			<media:title type="html">mvn_new</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/mvn_new_2_thumb.png" medium="image">
			<media:title type="html">mvn_new_2</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/mvn_choose_at_thumb.png" medium="image">
			<media:title type="html">mvn_choose_at</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/mvn_new_4_thumb.png" medium="image">
			<media:title type="html">mvn_new_4</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/mvn_new_5_thumb.png" medium="image">
			<media:title type="html">mvn_new_5</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/structure_1_thumb.png" medium="image">
			<media:title type="html">structure_1</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/getuser_thumb.png" medium="image">
			<media:title type="html">GetUser</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/storeuser_thumb.png" medium="image">
			<media:title type="html">StoreUser</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/str_xsd_thumb.png" medium="image">
			<media:title type="html">str_xsd</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/pom_add_plugin_thumb.png" medium="image">
			<media:title type="html">pom_add_plugin</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/pom_add_deps_thumb.png" medium="image">
			<media:title type="html">pom_add_deps</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/run_final_thumb1.png" medium="image">
			<media:title type="html">run_final</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/soapui_new_thumb.png" medium="image">
			<media:title type="html">soapui_new</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/soapui_new_1_thumb.png" medium="image">
			<media:title type="html">soapui_new_1</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/06/soapui_run_thumb1.png" medium="image">
			<media:title type="html">soapui_run</media:title>
		</media:content>

		<media:content url="http://static-youtipit.s3-website-eu-west-1.amazonaws.com/Youtipitorange35.png" medium="image" />
	</item>
		<item>
		<title>Mocking and Stubbing with Mockito</title>
		<link>http://ice09.wordpress.com/2011/01/09/mocking-and-stubbing-with-mockito/</link>
		<comments>http://ice09.wordpress.com/2011/01/09/mocking-and-stubbing-with-mockito/#comments</comments>
		<pubDate>Sun, 09 Jan 2011 23:04:36 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">https://ice09.wordpress.com/?p=770</guid>
		<description><![CDATA[&#160; Intention Let’s assume there is a new requirement for an existing CRM-like system: send a mail to all customers with a balance greater than 1000. Since we are not allowed to access the database directly, we will have to use existing services. Since we are using Spring, the configuration is obvious, the services are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=770&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>&#160;</h1>
<h2>Intention</h2>
<p>Let’s assume there is a new requirement for an existing CRM-like system: send a mail to all customers with a balance greater than 1000. Since we are not allowed to access the database directly, we will have to use existing services.</p>
<p><a href="http://ice09.files.wordpress.com/2011/01/image.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border-width:0;margin:0 0 0 10px;" title="image" border="0" alt="image" src="http://ice09.files.wordpress.com/2011/01/image_thumb.png?w=776&#038;h=359" width="776" height="359" /></a></p>
<p>Since we are using Spring, the configuration is obvious, the services are injected, that’s it.</p>
<h2>Mocking</h2>
<p>However, for testing purposes, we want to mock the services. By examining the classes and methods, we will see why mocking is necessary, but not enough in this case.</p>
<h3>Setup</h3>
<p>Only the interfaces of the services are shown, they are mocked anyway.</p>
<p> <code>MailService</code><br />
<pre class="brush: java;"> 
public interface MailService { 
    
    void sendMails(List&lt;customer&gt; customers); 

}
</pre> </p>
<p><code>CustomerDao</code><br />
<pre class="brush: java;"> 
public interface CustomerDao { 

    List&lt;customer&gt; getCustomers(); 

} 
</pre> This is the class under test, the filter method should be tested.<br />
<pre class="brush: java;"> 
public class CustomerService { 
    
    private CustomerDao customerDao; 
    private MailService mailService; 
    
    public void notifyCustomersWithBalanceGreaterThan(long cbalance) { 
        List&lt;customer&gt; notificationList = new ArrayList&lt;customer&gt;(); 
        List&lt;customer&gt; customers = customerDao.getCustomers(); 
        for (Customer customer : customers) { 
            if (customer.getBalance() &gt; cbalance) { 
                notificationList.add(customer); 
            } 
        }
        mailService.sendMails(notificationList); 
    } 

} 
</pre><br />
<h3>Testing&#8230;</h3>
<p> How do we test if everything worked? There is no result object to check, since mails are sent. Here mocking comes into play, a breeze with <a href="http://mockito.org/">Mockito</a>.<br />
<pre class="brush: java;"> 
@RunWith(MockitoJUnitRunner.class)
public class TestClass {

	private @Mock CustomerDao customerDao;
	private @Mock MailService mailService;
	
	private @InjectMocks CustomerService customerService = new CustomerService();

	private @Captor ArgumentCaptor&lt;List&lt;Customer&gt;&gt; customerCaptor;

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void testIt() {
		//preparation (stubbing)
		when(customerDao.getCustomers()).thenReturn(prepareList());
		
		customerService.notifyCustomersWithBalanceGreaterThan(1000);

		//verification (mocking)
		//has customerDao be called correctly?
		verify(customerDao, times(1)).getCustomers();
		verifyNoMoreInteractions(customerDao);

		//have the mails be sent?
		verify(mailService).sendMails(customerCaptor.capture());
		
		//is the list of customers to notify correct? 
		assertEquals(2, customerCaptor.getValue().size());
		assertEquals(new Customer(3, &quot;eva&quot;, &quot;mustermann&quot;, 2000), customerCaptor.getValue().get(0)); 
		assertEquals(new Customer(6, &quot;hanna&quot;, &quot;mustermann&quot;, 1001), customerCaptor.getValue().get(1)); 
		verifyNoMoreInteractions(mailService);
	}

	private List&lt;Customer&gt; prepareList() {
		List&lt;Customer&gt; customers = new ArrayList&lt;Customer&gt;();
		customers.add(new Customer(1, &quot;hans&quot;, &quot;mustermann&quot;, 100));
		customers.add(new Customer(2, &quot;max&quot;, &quot;mustermann&quot;, 1000));
		customers.add(new Customer(3, &quot;eva&quot;, &quot;mustermann&quot;, 2000));
		customers.add(new Customer(4, &quot;anna&quot;, &quot;mustermann&quot;, 0));
		customers.add(new Customer(6, &quot;hanna&quot;, &quot;mustermann&quot;, 1001));
		return customers;
	}

}
</pre><br />
The mocking part is straightforward. However, we have to stub as well, since we want the <code>CustomerDao</code> to actually return our prepared <code>Customer</code> list. No problem with Mockito (search for Test Spy to see why there are differences in Mocking frameworks regarding the support of Mocking, Stubbing or both &#8211; then being a Test Spy).<br />
<h3>Dependency injection</h3>
<p> Really interesting is the wiring of the components. The <code>MockitoJUnitRunner.class</code> is used to run the Unittest, we do not use Spring for this test. But magically, after calling <code>MockitoAnnotations.initMocks(this)</code>  the <code>@Mock</code> annotated Mocks are injected into the <code>@InjectMocks</code>  annotated class automatically. This being great already, we are furthermore using the <code>@Captor</code> annotation to create a argument captor for all List arguments. Now we can examine the submitted list with <code>Customers</code> to sent mail to and determine, if the correct <code>Customers</code> have been filtered.<br />
So, we have a nice dependency injection, combined with stubbing and mocking. Mockito is really powerful (and much easier to use than similar Mocking frameworks), you can even partially stub objects. However, there should be a really good reason for doing this&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/770/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/770/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/770/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/770/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/770/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/770/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/770/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/770/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/770/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/770/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/770/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/770/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/770/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/770/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=770&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2011/01/09/mocking-and-stubbing-with-mockito/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2011/01/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>QuickTip: SCP with Groovy, Maven and Eclipse</title>
		<link>http://ice09.wordpress.com/2010/12/20/quicktip-scp-with-groovy-maven-and-eclipse/</link>
		<comments>http://ice09.wordpress.com/2010/12/20/quicktip-scp-with-groovy-maven-and-eclipse/#comments</comments>
		<pubDate>Mon, 20 Dec 2010 22:42:45 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Maven]]></category>

		<guid isPermaLink="false">https://ice09.wordpress.com/2010/12/20/quicktip-scp-with-groovy-maven-and-eclipse/</guid>
		<description><![CDATA[Intention It’s easy to use SCP with Java, Groovy and even with Maven. However, it gets more complicated if you want to use all of them simultaneously. It should work this way: An (key-file-based) SCP-connection should take place in a Groovy, so the transferred file can be manipulated straight away. All this should be triggered [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=753&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Intention</h3>
<p>It’s easy to use SCP with Java, Groovy and even with Maven. However, it gets more complicated if you want to use all of them simultaneously.</p>
<p>It should work this way: An (key-file-based) SCP-connection should take place in a Groovy, so the transferred file can be manipulated straight away. All this should be triggered by a Maven build process and alternatively, using Eclipse with the Groovy plugin, it should be possible to directly start the Groovy script.</p>
<h4>Preparation</h4>
<p>Either <a href="http://www.eclipse.org">Eclipse</a> with the <a href="http://groovy.codehaus.org/Eclipse+Plugin">Groovy plugin</a> and the <a href="http://m2eclipse.sonatype.org/">Maven plugin</a> or the <a href="http://www.springsource.com/developer/sts">SpringSource Tool Suite</a> (which includes both plugins) should be installed.</p>
<h4>Maven config</h4>
<p>The Maven config consists of two dependencies:</p>
<ol>
<li>The <a href="http://ant.apache.org/manual/Tasks/scp.html">Ant-SCP-Plugin</a>, which is based on <a href="http://www.jcraft.com/jsch/">JSch</a></li>
<li>Embedded Groovy (groovy-all.jar)</li>
</ol>
<p>And two Maven Plugins:</p>
<ol>
<li><a href="http://docs.codehaus.org/display/GMAVEN/Home">GMaven</a></li>
<li>The <a href="http://mojo.codehaus.org/exec-maven-plugin/java-mojo.html">Exec Maven Plugin</a></li>
</ol>
<p><pre class="brush: xml;">

&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
 xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
 &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
 &lt;groupId&gt;de.ice09.scp&lt;/groupId&gt;
 &lt;artifactId&gt;jsch&lt;/artifactId&gt;
 &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
 &lt;dependencies&gt;
  &lt;dependency&gt;
   &lt;groupId&gt;org.apache.ant&lt;/groupId&gt;
   &lt;artifactId&gt;ant-jsch&lt;/artifactId&gt;
   &lt;version&gt;1.8.1&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
   &lt;groupId&gt;org.codehaus.groovy&lt;/groupId&gt;
   &lt;artifactId&gt;groovy-all&lt;/artifactId&gt;
   &lt;version&gt;1.7.5&lt;/version&gt;
  &lt;/dependency&gt;
 &lt;/dependencies&gt;
 &lt;build&gt;
  &lt;plugins&gt;
   &lt;plugin&gt;
    &lt;groupId&gt;org.codehaus.groovy.maven&lt;/groupId&gt;
    &lt;artifactId&gt;gmaven-plugin&lt;/artifactId&gt;
    &lt;executions&gt;
     &lt;execution&gt;
      &lt;goals&gt;
       &lt;goal&gt;generateStubs&lt;/goal&gt;
       &lt;goal&gt;compile&lt;/goal&gt;
       &lt;goal&gt;generateTestStubs&lt;/goal&gt;
       &lt;goal&gt;testCompile&lt;/goal&gt;
      &lt;/goals&gt;
     &lt;/execution&gt;
    &lt;/executions&gt;
   &lt;/plugin&gt;
   &lt;plugin&gt;
    &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
    &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt;
    &lt;version&gt;1.1&lt;/version&gt;
    &lt;executions&gt;
     &lt;execution&gt;
      &lt;goals&gt;
       &lt;goal&gt;java&lt;/goal&gt;
      &lt;/goals&gt;
     &lt;/execution&gt;
    &lt;/executions&gt;
    &lt;configuration&gt;
     &lt;mainClass&gt;de.ice09.scp.LogLoader&lt;/mainClass&gt;
    &lt;/configuration&gt;
   &lt;/plugin&gt;
  &lt;/plugins&gt;
 &lt;/build&gt;
&lt;/project&gt;

</pre></p>
<h4>Groovy…</h4>
<p>Here comes the Groovy part, in fact it’s quite short, since it focuses on the file transfer part. Obviously, it would be easy to manipulate the transferred files after the SCP-transfer, since we are inside a Groovy script and we can use whatever Java library we want since we are inside a Maven project. The universe is ours!</p>
<p><pre class="brush: java;">

package de.ice09.scp

new AntBuilder()
 .scp(
  file:&quot;root@server.com:/tmp/ls&quot;,
  todir:'C:/temp',
  verbose:true,
  trust:true,
  keyfile:'C:/portables/PuTTY/ossh.ppk',
  passphrase:'passphrase'
 )

</pre></p>
<p><strong>The file must go to src/main/groovy for GMaven to work. The key must be OpenSSH-compliant. If you use PuTTY, you can export this format. Alternatively, you can use username/password instead.</strong></p>
<h4>Testing…</h4>
<p>After creating a new Maven project with the pom.xml listed above, more than half of the work is done. With or without an IDE this can be tested. Just run</p>
<blockquote><p><strong>maven clean install exec:java</strong></p></blockquote>
<p>GMaven should generate the Java stubs, the Execution Plugin should execute the generated Java class file. The dependencies for JSch, Antbuilder etc. are handled by Maven or Groovy itself.</p>
<h4>Eclipse config</h4>
<p>The final step is to enable the Groovy nature in Eclipse. This leads us to a faster development cycle, since the Groovy script can be run “natively”, without having Maven to generate the Java stub before. There is no problem running the two options (Groovy with Maven and Eclipse) side-by-side, so it is really easy to develop and deploy, since there is no big difference. You always have a completely runnable version available, given that Maven is installed on the target system.</p>
<p>Convert to Groovy project</p>
<p><a href="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-16_java.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;margin:0 0 0 10px;" title="2010-12-20_23-16_Java" src="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-16_java_thumb.png?w=644&#038;h=290" border="0" alt="2010-12-20_23-16_Java" width="644" height="290" /></a></p>
<p>Add Groovy sources (from src/main/groovy) to classpath</p>
<p><a href="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-19_java1.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;margin:0 0 0 10px;" title="2010-12-20_23-19_Java" src="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-19_java1.png?w=644&#038;h=362" border="0" alt="2010-12-20_23-19_Java" width="644" height="362" /></a></p>
<p>The deployable way: start process using GMaven and Execution Plugin</p>
<p><a href="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-36_run-configurations.jpg"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;margin:0 0 0 10px;" title="2010-12-20_23-36_Run Configurations" src="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-36_run-configurations_thumb.jpg?w=644&#038;h=479" border="0" alt="2010-12-20_23-36_Run Configurations" width="644" height="479" /></a></p>
<p>Start in development mode using the Groovy Eclipse Plugin</p>
<p><a href="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-38_java.png"><img style="background-image:none;padding-left:0;padding-right:0;display:inline;padding-top:0;border:0;margin:0 0 0 10px;" title="2010-12-20_23-38_Java" src="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-38_java_thumb.png?w=644&#038;h=419" border="0" alt="2010-12-20_23-38_Java" width="644" height="419" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/753/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/753/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/753/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/753/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/753/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/753/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/753/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/753/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/753/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/753/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/753/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/753/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/753/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/753/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=753&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2010/12/20/quicktip-scp-with-groovy-maven-and-eclipse/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-16_java_thumb.png" medium="image">
			<media:title type="html">2010-12-20_23-16_Java</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-19_java1.png" medium="image">
			<media:title type="html">2010-12-20_23-19_Java</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-36_run-configurations_thumb.jpg" medium="image">
			<media:title type="html">2010-12-20_23-36_Run Configurations</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2010/12/2010-12-20_23-38_java_thumb.png" medium="image">
			<media:title type="html">2010-12-20_23-38_Java</media:title>
		</media:content>
	</item>
		<item>
		<title>Preparing a fresh Debian Lenny for Java Enterprise Applications</title>
		<link>http://ice09.wordpress.com/2010/12/18/preparing-a-fresh-debian-lenny-for-java-enterprise-applications/</link>
		<comments>http://ice09.wordpress.com/2010/12/18/preparing-a-fresh-debian-lenny-for-java-enterprise-applications/#comments</comments>
		<pubDate>Sat, 18 Dec 2010 01:36:22 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Debian]]></category>
		<category><![CDATA[GlassFish]]></category>

		<guid isPermaLink="false">https://ice09.wordpress.com/?p=720</guid>
		<description><![CDATA[Intention I am a happy owner of a virtual root server &#8211; this being a great thing, there is one big problem: I have to prepare this box for Java usage myself. This must be achieved with a somewhat limited Linux knowledge. However, with debian lenny this turned out to be a breeze. I had [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=720&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Intention</strong></p>
<p>I am a happy owner of a virtual root server &#8211; this being a great thing, there is one big problem: I have to prepare this box for Java usage myself. This must be achieved with a somewhat limited Linux knowledge. However, with debian lenny this turned out to be a breeze.</p>
<p>I had to follow the steps below to get this running in about 30 minutes:</p>
<ol>
<li>Apache Webserver </li>
<li>MySQL </li>
<li>phpMyAdmin </li>
<li>GlassFish 3</li>
</ol>
<p>Which is pretty much what you need for creating JEE/Spring-Applications in an enterprise scale.</p>
<p>What is still missing (due to a lack of time and necessity) are the following configurations:</p>
<ol>
<li>JNDI-Resource for the MySQL-Database </li>
<li>Apache/GlassFish-mod for forwarding requests on port 80 to GlassFish directly </li>
</ol>
<p><strong>List of Commands</strong></p>
<p><pre class="brush: plain; light: true;">cat /etc/debian_version</pre></p>
<p>For my installation this says <strong>5.0.7. </strong>So obviously: 1. I am using Debian. 2. It is Debian Lenny in version 5.0.7. Yes, we are starting slowly here.</p>
<p><pre class="brush: plain; light: true;">apt-get install apache2</pre></p>
<p>Install the <strong>Apache Web Server</strong>. I more or less need it for <strong>phpMyAdmin</strong>. Obviously, you can choose <strong>lighthttpd</strong> or others here.</p>
<p><pre class="brush: plain; light: true;">apt-get install mysql-server mysql-client phpmyadmin</pre></p>
<p>This is the most important line, it magically does everything exactly like you want to have it (however, this depends on answering the questions during installation correctly).</p>
<p><pre class="brush: plain; light: true;">apt-get install sun-java6-jdk</pre></p>
<p>Ok, this is important as well for <strong>Java development. </strong>I did not expect it to be that easy (remembering licensing issues in the past) and tried it “manually”, but was lost almost immediately. However, with sun-java6-jdk, you will get everything you need. You should check this with:</p>
<p><pre class="brush: plain; light: true;">java –version</pre></p>
<p>which should print out text like this:</p>
<p><pre class="brush: plain; light: true;">
java version &quot;1.6.0_22&quot;
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03, mixed mode)
</pre></p>
<p>Your mileage may vary here of course. It should show <strong>1.6</strong> somewhere though.</p>
<p>Now, the most “difficult” part is the installation of GlassFish. Not surprisingly, we are not the first trying to install GlassFish on Debian, so there exists a really good documentation about this topic here (in German): <a href="http://www.bennyn.de/webanwendungen/virtual-server/glassfish-v3-installieren-auf-debian-lenny.html"><u><font color="#0066cc">http://www.bennyn.de/webanwendungen/virtual-server/glassfish-v3-installieren-auf-debian-lenny.html</font></u></a></p>
<p>Since this HOWTO here should be complete, I am reposting the steps here:</p>
<p>
<pre class="brush: bash;">
wget -O /opt/glassfish-3.0.1.zip http://download.java.net/glassfish/3.0.1/release/glassfish-3.0.1.zip
cd /opt/
unzip glassfish-3.0.1.zip
rm glassfish-3.0.1.zip
cd /etc/init.d/
</pre></p>
<p>Now, only the script <strong>glassfish.sh</strong> is missing:</p>
<p><pre class="brush: bash;">
vim /etc/init.d/glassfish.sh
touch glassfish.sh
chmod 0755 glassfish.sh    
update-rc.d glassfish.sh defaults
</pre></p>
<p>with this content (all taken from the site mentioned above):</p>
<p><pre class="brush: bash;">
#!/bin/sh
### BEGIN INIT INFO
# Provides:          glassfish
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO
#
# This init.d script is used to start the glassfish application server.
# Simplest possible case -- no password file, one default domain
#
 
GLASSFISH_HOME=${GLASSFISH_HOME:-&quot;/opt/glassfishv3/glassfish&quot;}
 
case &quot;$1&quot; in
start)
	$GLASSFISH_HOME/bin/asadmin start-domain | tee -a /var/log/glassfish.log
	;;
stop)
	$GLASSFISH_HOME/bin/asadmin stop-domain | tee -a /var/log/glassfish.log
	;;
restart)
	$GLASSFISH_HOME/bin/asadmin restart-domain | tee -a /var/log/glassfish.log
	;;
*)
    echo &quot;usage: $0 (start|stop|restart|help)&quot;
esac
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/720/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=720&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2010/12/18/preparing-a-fresh-debian-lenny-for-java-enterprise-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>
	</item>
		<item>
		<title>Spring-batch with GMail-Notification using Velocity</title>
		<link>http://ice09.wordpress.com/2010/08/15/spring-batch-with-gmail-notification-using-velocity/</link>
		<comments>http://ice09.wordpress.com/2010/08/15/spring-batch-with-gmail-notification-using-velocity/#comments</comments>
		<pubDate>Sun, 15 Aug 2010 23:24:41 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Mail]]></category>
		<category><![CDATA[Spring Batch]]></category>
		<category><![CDATA[Velocity]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=661</guid>
		<description><![CDATA[The sources to this blog entry are available here. The SpringSource Tool Suite (STS) or an accordingly configured Eclipse (with a mandatory Maven plugin and an optional Spring IDE plugin) has to be installed. The problem The Spring Batch project is really useful in creating new batch jobs. The framework is straightforward and gained quite [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=661&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>The sources to this blog entry are available <a href='http://ice09-blogcode.googlecode.com/files/batch-sample_16082010.zip'>here.</a> The <a href='http://www.springsource.com/developer/sts'>SpringSource Tool Suite (STS)</a> or an accordingly configured <a href='http://eclipse.org/'>Eclipse</a> (with a mandatory Maven plugin and an optional Spring IDE plugin) has to be installed.</strong></p>
<p><strong>The problem</strong></p>
<p>The <a href='http://static.springsource.org/spring-batch/'>Spring Batch</a> project is really useful in creating new batch jobs. The framework is straightforward and gained quite a lot usefulness and user-friendliness with the 2.x branch. However, even with the great <a href='http://static.springsource.org/spring-batch/reference/html/index.html'>reference documentation</a> and the <a href='http://static.springsource.org/spring-batch/getting-started.html'>getting started</a> section, it takes its time to create a simple project with success/error-mail notification.<br />
I will create a really simple batch job using the new 2.x features, adding the almost always necessary mail notification after a successful or failed job execution. The mail context should be rendered using <a href='http://velocity.apache.org/'>Velocity</a>. This post does not explain the Spring (Batch) components used, please refer to the <a href='http://static.springsource.org/spring-batch/reference/html/index.html'>Spring Batch reference documentation</a> for detailed explanations.</p>
<p><strong>The setup</strong></p>
<p>The structure is taken from the <i>Template Project</i> in STS, the howto is available in the getting started page.</p>
<p><b><i>project structure</i></b><br />
<img src='http://ice09.files.wordpress.com/2010/08/structure.png'></img></p>
<p>It is important to note the separation of concerns in the two spring contexts <i>launch-context.xml</i> and <i>module-context.xml</i>. The first one contains <b>all beans relevant to the job&#8217;s infrastructure</b>, there is no business logic contained. The module config is included using <i>import resource</i>. The <b>module config just contains business logic</b>, the actual batch job logic is configured here.</p>
<p><b><i>module-config.xml</i></b><br />
<img src='http://ice09.files.wordpress.com/2010/08/module-config.png'></img></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns:batch=&quot;http://www.springframework.org/schema/batch&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd&quot;&gt;

	&lt;batch:job id=&quot;job1&quot; xmlns=&quot;http://www.springframework.org/schema/batch&quot;&gt;
		&lt;batch:step id=&quot;step1&quot; parent=&quot;simpleStep&quot;&gt;
			&lt;batch:tasklet ref=&quot;processorTasklet&quot;&gt;
				&lt;batch:listeners&gt;
					&lt;batch:listener ref=&quot;errorlistener&quot;/&gt;
				&lt;/batch:listeners&gt;
			&lt;/batch:tasklet&gt;
		&lt;/batch:step&gt;
		&lt;batch:listeners&gt;
			&lt;batch:listener ref=&quot;samplemailnotification&quot;/&gt;
		&lt;/batch:listeners&gt;
	&lt;/batch:job&gt;
	
	&lt;bean id=&quot;samplemailnotification&quot; parent=&quot;mailnotification&quot;&gt;
		&lt;property name=&quot;errorMailPath&quot; value=&quot;mailtemplate.vm&quot;/&gt;
		&lt;property name=&quot;successMailPath&quot; value=&quot;mailtemplate.vm&quot;/&gt;
		&lt;property name=&quot;subject&quot; value=&quot;Mail from batch-sample&quot;/&gt;
	&lt;/bean&gt;
	
	&lt;bean id=&quot;processorTasklet&quot; class=&quot;org.springframework.sample.batch.example.ExampleProcessor&quot;/&gt;

&lt;/beans&gt;
</pre></p>
<p>The processor used just writes a data item to a shared Map. This Map is initialized and written into the job execution context by the <code>StatusMailJobListener</code> in its <code>JobExecutionListener.beforeJob(...)</code> method. In <code>afterJob(...)</code> this Map is evaluated and the following logic is applied: if an error-element is present, remove all provided data and just set the error-element in the Velocity context. Otherwise, copy all data from the values-element into the Velocity context. The origin of the values-element is explained below.</p>
<p><pre class="brush: java;">
package org.springframework.sample.batch.example;

//[imports excluded]
public class StatusMailJobListener implements JobExecutionListener {
	
	private String recipient;
	private String sender;
	private String successMailPath;
	private String errorMailPath;
	private String subject;
	
	@Autowired
	private JavaMailSenderImpl mailSender;
	@Autowired
	private VelocityEngine velocityEngine;

	public void afterJob(JobExecution jobExecution) {
		String exitCode = jobExecution.getExitStatus().getExitCode();
		if (exitCode.equals(ExitStatus.COMPLETED.getExitCode())) {
			sendMail(successMailPath, &quot;[OK] &quot; + subject, jobExecution.getExecutionContext());
		} else {
			sendMail(errorMailPath, &quot;[ERROR] &quot; + subject, jobExecution.getExecutionContext());
		}
	}

	private void sendMail(final String messagePath, final String subject, final ExecutionContext executionContext) {
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
				message.setSubject(subject);
				message.setTo(recipient);
				message.setFrom(sender);
				Map&lt;String, String&gt; values = (Map&lt;String, String&gt;) executionContext.get(&quot;values&quot;);
				if (executionContext.containsKey(&quot;error&quot;)) {
					values.clear();
					values.put(&quot;error&quot;, executionContext.getString(&quot;error&quot;));
				}
				String text = 
					VelocityEngineUtils.
						mergeTemplateIntoString(velocityEngine, messagePath, values);
				message.setText(text, true);
			}
		};
		mailSender.send(preparator);
	}

	public void beforeJob(JobExecution jobExecution) {
		Map&lt;String, String&gt; values = new HashMap&lt;String, String&gt;();
		jobExecution.getExecutionContext().put(&quot;values&quot;, values);
	}

        //[setters excluded]

}
</pre></p>
<p>For this setup to work, a contract is defined: <b>every step/tasklet, which wants to add information to the context which should be available in the Velocity context for rendering the mail content, must write to the predefined Map</b>.<br />
This can be done eg. by using <code>((Map)chunkContext.getStepContext().getJobExecutionContext().get("values")).put("content", "add this text")</code>. Initially, this Map is created by the MailNotificationListener as described above (of course, you should check for existance of this Map first in real code).<br />
The errorhandling is done magically by Spring, if an error occurs, the Listeners can just check the ExitStatus and react accordingly (compare the <code>afterJob(...)</code> method).</p>
<p><pre class="brush: java;">
package org.springframework.sample.batch.example;

//[imports excluded]

public class ExampleProcessor implements Tasklet {

	public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
		//throw new RuntimeException(&quot;bla&quot;);
		((Map&lt;String, String&gt;)chunkContext.getStepContext().getJobExecutionContext().get(&quot;values&quot;)).put(&quot;test&quot;, &quot;[successfully invoked exampleprocessor]&quot;);
		return RepeatStatus.FINISHED;
	}

}
</pre></p>
<p>How and when is the error-element set into the job execution context? This is done by the last missing item, the <code>ErrorListener</code>, which is a <code>StepExecutionListener</code>. </p>
<p><pre class="brush: java;">
package org.springframework.sample.batch.example;

//[imports excluded]

public class ErrorListener implements StepExecutionListener {

	public ExitStatus afterStep(StepExecution stepExecution) {
		String exitCode = stepExecution.getExitStatus().getExitCode();
		if (exitCode.equals(ExitStatus.FAILED.getExitCode())) {
			StringBuilder messages = new StringBuilder();
			for (Throwable error : stepExecution.getFailureExceptions()) {
				messages.append(error.getMessage());
			}
			stepExecution.getJobExecution().getExecutionContext().put(&quot;error&quot;, messages.toString());
			return stepExecution.getExitStatus();
		}
		return ExitStatus.COMPLETED;
	}

	public void beforeStep(StepExecution stepExecution) {
		// Nothing to do here.
	}

}
</pre></p>
<p><strong>Tips &amp; Tricks</strong></p>
<p>There is not much missing, however, for this thing to run with GMail, certain properties have to be provided, therefore I will list the complete <i>launch-config</i> here. However, this is available in the sources to this post as well. Just fill in the correct data (GMail-account, recipients) and it should work as excepted. The velocity template is so short, I attached it as well FWIW.</p>
<p><b><i>launch-config.xml</i></b><br />
<img src='http://ice09.files.wordpress.com/2010/08/launch-config.png'></img></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns:batch=&quot;http://www.springframework.org/schema/batch&quot;
	xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
	xmlns:util=&quot;http://www.springframework.org/schema/util&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
		http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.0.xsd&quot;&gt;

	&lt;import resource=&quot;classpath:/META-INF/spring/module-context.xml&quot; /&gt;

	&lt;bean id=&quot;jobRepository&quot; class=&quot;org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean&quot;&gt;
    	&lt;property name=&quot;transactionManager&quot; ref=&quot;transactionManager&quot;/&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;jobLauncher&quot;
		class=&quot;org.springframework.batch.core.launch.support.SimpleJobLauncher&quot;&gt;
		&lt;property name=&quot;jobRepository&quot; ref=&quot;jobRepository&quot; /&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;transactionManager&quot;
		class=&quot;org.springframework.batch.support.transaction.ResourcelessTransactionManager&quot;&gt;
	&lt;/bean&gt;

	&lt;bean id=&quot;mailnotification&quot; class=&quot;org.springframework.sample.batch.example.StatusMailJobListener&quot; abstract=&quot;true&quot;&gt;
		&lt;property name=&quot;recipient&quot; value=&quot;MAILADDRESS_OF_RECIPIENTS&quot;/&gt;
		&lt;property name=&quot;sender&quot; value=&quot;MAILADDRESS_OF_SENDER&quot;/&gt;
	&lt;/bean&gt;
	
	&lt;bean id=&quot;errorlistener&quot; class=&quot;org.springframework.sample.batch.example.ErrorListener&quot;/&gt;

	&lt;util:properties id=&quot;props&quot;&gt;
		&lt;prop key=&quot;mail.smtp.starttls.enable&quot;&gt;true&lt;/prop&gt;
	&lt;/util:properties&gt;

   &lt;bean id=&quot;mailSender&quot; class=&quot;org.springframework.mail.javamail.JavaMailSenderImpl&quot;&gt;
      &lt;property name=&quot;host&quot; value=&quot;smtp.googlemail.com&quot;/&gt;
      &lt;property name=&quot;username&quot; value=&quot;YOUR_GMAIL_ACCOUNT&quot;/&gt;
      &lt;property name=&quot;password&quot; value=&quot;YOUR_GMAIL_PASSWORD&quot;/&gt;
      &lt;property name=&quot;javaMailProperties&quot; ref=&quot;props&quot;/&gt;
   &lt;/bean&gt;

	&lt;bean id=&quot;simpleStep&quot;
		class=&quot;org.springframework.batch.core.step.item.SimpleStepFactoryBean&quot;
		abstract=&quot;true&quot;&gt;
		&lt;property name=&quot;transactionManager&quot; ref=&quot;transactionManager&quot; /&gt;
		&lt;property name=&quot;jobRepository&quot; ref=&quot;jobRepository&quot; /&gt;
		&lt;property name=&quot;startLimit&quot; value=&quot;100&quot; /&gt;
		&lt;property name=&quot;commitInterval&quot; value=&quot;1&quot; /&gt;
	&lt;/bean&gt;
	
	&lt;bean id=&quot;velocityEngine&quot; class=&quot;org.springframework.ui.velocity.VelocityEngineFactoryBean&quot;&gt;
      &lt;property name=&quot;velocityProperties&quot;&gt;
         &lt;value&gt;
          resource.loader=class
          class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
         &lt;/value&gt;
      &lt;/property&gt;
   &lt;/bean&gt;

&lt;/beans&gt;
</pre></p>
<p><b><i>mailtemplate.vm</i></b><br />
<pre class="brush: plain;">
#if ($error)
Sorry, there was an error, please check the logs.&lt;br/&gt;
exceptionmessages: $error 
#else
Cool, it worked, there is a message for you: $test
#end
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/661/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/661/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/661/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/661/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/661/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/661/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/661/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/661/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/661/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/661/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/661/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/661/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/661/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/661/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=661&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2010/08/15/spring-batch-with-gmail-notification-using-velocity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2010/08/structure.png" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2010/08/module-config.png" medium="image" />

		<media:content url="http://ice09.files.wordpress.com/2010/08/launch-config.png" medium="image" />
	</item>
		<item>
		<title>Quick Tip: Extending WebDriver to react on stopwords</title>
		<link>http://ice09.wordpress.com/2010/07/18/quick-tip-extending-webdriver-to-react-on-stopwords/</link>
		<comments>http://ice09.wordpress.com/2010/07/18/quick-tip-extending-webdriver-to-react-on-stopwords/#comments</comments>
		<pubDate>Sun, 18 Jul 2010 16:33:30 +0000</pubDate>
		<dc:creator>ice09</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://ice09.wordpress.com/?p=634</guid>
		<description><![CDATA[The requirement Happily using WebDriver for some time now, I realized that it makes sense to intercept each call that changes the page source in a way that certain &#8220;stopwords&#8221;, eg. &#8220;exception&#8221;, &#8220;error&#8221;, etc. cause an immediate exception. This is useful if you want to be sure that in a complex test case an exception [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=634&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>The requirement</strong></p>
<p>Happily using <a href='http://code.google.com/p/selenium/'>WebDriver</a> for some time now, I realized that it makes sense to intercept each call that changes the page source in a way that certain &#8220;stopwords&#8221;, eg. &#8220;exception&#8221;, &#8220;error&#8221;, etc. cause an immediate exception. This is useful if you want to be sure that in a complex test case an exception will never occur. Otherwise, you would have to manually check for it each time the page source is altered.</p>
<p><strong>The problem</strong></p>
<p>I wanted to use the <strong>ProxyBeanFactory</strong> for this requirement, since it seemed the least compromising way of manipulating the calls to the actual WebDriver. However, I realized that I would have to use AspectJ for this, since calls to private/protected methods inside the bean itself cannot be intercepted by proxies. This is necessary to intercept the call to the method <code>sendMessage</code>, which is used by <code>WebDriver</code> and <code>WebElement</code> for methods which actually change the page source (which makes sense, since this method actually communicates with the plugin via <code>Command</code>s).</p>
<p><img src='http://ice09.files.wordpress.com/2010/07/webdriver_s_c.png'></img></p>
<p><strong>The solution</strong></p>
<p>I decided not to use proxies, but just to subclass the <code>FireFoxWebDriver</code> with my own one, which just overwrites the &#8220;sendMessage&#8221; method. That&#8217;s it, the code is as follows.</p>
<p><i>The Spring config</i><br />
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
	xmlns:util=&quot;http://www.springframework.org/schema/util&quot;
	xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd&quot;&gt;

    &lt;context:annotation-config/&gt;
    &lt;context:component-scan base-package=&quot;de.demo.proxy&quot;/&gt;

	&lt;util:list id=&quot;stopwords&quot;&gt;
    	&lt;value&gt;exception&lt;/value&gt;
    	&lt;value&gt;Comment&lt;/value&gt;
	&lt;/util:list&gt;
    
&lt;/beans&gt;
</pre></p>
<p><i>The new WebDriver</i><br />
<pre class="brush: java;">
package de.demo.proxy;

import java.util.List;

import javax.annotation.Resource;

import org.openqa.selenium.firefox.Command;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.springframework.stereotype.Component;

@Component
public class InterceptedFireFoxDriver extends FirefoxDriver {
	
	@Resource(name=&quot;stopwords&quot;)
	private List&lt;String&gt; stopwords;
	
	@Override
	protected String sendMessage(Class&lt;? extends RuntimeException&gt; throwOnFailure, Command command) {
		String result = super.sendMessage(throwOnFailure, command);
		// avoid endless recursion, sendMessage... is called by getPageSource as well
		if (command.getCommandName().equals(&quot;getPageSource&quot;)) {
	        return result;
		}
		String content = super.getPageSource();
		// might be null due to initialization issues (already called during spring context creation)
		if (stopwords != null) {
			for (String stopword : stopwords) {
				if (content.contains(stopword)) {
					throw new IllegalStateException(&quot;command [&quot; + command.getCommandName() + &quot;] causes page content with stopword: &quot; + stopword);
				}
			}
		}
		return result;
	}

}
</pre></p>
<p><i>The sample class</i><br />
<pre class="brush: java;">
package de.demo.proxy;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class MainClass {
	
    @Autowired
	private WebDriver driver;
    
    public void start() {
        driver.get(&quot;http://www.google.com&quot;);

        // Find the text input element by its name
        WebElement element = driver.findElement(By.name(&quot;q&quot;));

        // Enter something to search for
        element.sendKeys(&quot;Hello&quot;);

        // Now submit the form. WebDriver will find the form for us from the element
        element.submit();

        // Check the title of the page
        System.out.println(&quot;Page title is: &quot; + driver.getTitle());
        
        driver.findElement(By.xpath(&quot;//a&quot;)).click();
        
        driver.close();
    }
	
	public static void main(String[] args) {
			ApplicationContext appCtx = new ClassPathXmlApplicationContext(&quot;app.xml&quot;);
			MainClass mc = appCtx.getBean(MainClass.class);
			try {
				mc.start();
			} finally {
				mc.driver.close();
			}
	}

}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/ice09.wordpress.com/634/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/ice09.wordpress.com/634/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/ice09.wordpress.com/634/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/ice09.wordpress.com/634/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/ice09.wordpress.com/634/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/ice09.wordpress.com/634/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/ice09.wordpress.com/634/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/ice09.wordpress.com/634/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/ice09.wordpress.com/634/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/ice09.wordpress.com/634/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/ice09.wordpress.com/634/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/ice09.wordpress.com/634/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/ice09.wordpress.com/634/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/ice09.wordpress.com/634/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=ice09.wordpress.com&amp;blog=3813526&amp;post=634&amp;subd=ice09&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://ice09.wordpress.com/2010/07/18/quick-tip-extending-webdriver-to-react-on-stopwords/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f2a51094591b2803906de70211427418?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ice09</media:title>
		</media:content>

		<media:content url="http://ice09.files.wordpress.com/2010/07/webdriver_s_c.png" medium="image" />
	</item>
	</channel>
</rss>
