<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" version="2.0">

<channel>
	<title>The Server Labs Blog</title>
	
	<link>http://www.theserverlabs.com/blog</link>
	<description>The technical blog of The Server Labs</description>
	<lastBuildDate>Wed, 14 Mar 2012 09:20:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/TheServerLabsBlog" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="theserverlabsblog" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>ALSB/OSB customization using WLST</title>
		<link>http://www.theserverlabs.com/blog/2012/03/14/alsbosb-customization-using-wlst/</link>
		<comments>http://www.theserverlabs.com/blog/2012/03/14/alsbosb-customization-using-wlst/#comments</comments>
		<pubDate>Wed, 14 Mar 2012 09:20:52 +0000</pubDate>
		<dc:creator>Francisco González</dc:creator>
				<category><![CDATA[EAI]]></category>
		<category><![CDATA[Oracle]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=926</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2012/03/14/alsbosb-customization-using-wlst/";</script>One of the primary tasks in release management is environment promotion. From development to test or from test to production, environment promotion is a step which should be as much automated as possible. We can use the service bus MBeans in WLST scripts to automate promotion of AquaLogic/Oracle Service Bus configurations from development environments through [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2012/03/14/alsbosb-customization-using-wlst/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><p>One of the primary tasks in release management is environment promotion. From development to test or from test to production, environment promotion is a step which should be as much automated as possible. </p>
<p>We can use the service bus MBeans in WLST scripts to automate promotion of AquaLogic/Oracle Service Bus configurations from development environments through testing, staging, and finally to production environments.</p>
<p>Each environment has particularities which may need changes in configuration of the software. These are usually centralized in property files, database tables, environment variables or any other place to facilitate environment promotion.</p>
<p>In AquaLogic/Oracle Service Bus there is the concept of environment values: </p>
<blockquote><p>Environment values are certain predefined fields in the configuration data whose values are very likely to change when you move your configuration from one domain to another (for example, from test to production). Environment values represent entities such as URLs, URIs, file and directory names, server names, e-mails, and such. Also, environment values can be found in alert destinations, proxy services, business services, SMTP Server and JNDI Provider resources, and UDDI Registry entries.</p></blockquote>
<p>For these environment values, we have different standard operations</p>
<ul>
<li>Finding and Replacing Environment Values </li>
<li>Creating Customization Files</li>
<li>Executing Customization Files</li>
</ul>
<p>However, these operations are limited to the &#8216;predefined fields whose values are very likely to change&#8217;&#8230; and what happens if we need to modify one of the considered &#8216;not very likely&#8217;? A different story is whether to consider SAP client connection parameters &#8216;not very likely&#8217; to change in a environment promotion from test to production&#8230;</p>
<p>In order to automate these necessary changes, one option is to modify directly the exported configuration prior to importing it to the destination environment but in our case, we want to maintain the philosophy of the customization after the importing, keeping the exported package untouched. We will try to use a WLST script instead of a customization file, as the later doesn&#8217;t satisfy our needs. </p>
<p>The first thing we have to do for using WLST is to add several service bus jar files to the WLST classpath. For example, if we have a Windows platform we add the following at the beginning of wlst.cmd file (I&#8217;m sure *nix people will know how to proceed in their case)</p>
<p>For Aqualogic Service Bus 3.0:</p>

<div class="wp_syntax"><div class="code"><pre class="dos dos" style="font-family:monospace;"><span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">ALSB_HOME</span>=c:\bea\alsb_3.0
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\lib\sb-kernel-api.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\lib\sb-kernel-common.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\lib\sb-kernel-resources.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\lib\sb-kernel-impl.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\..\modules\com.bea.common.configfwk_1.1.0.0.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\..\modules\com.bea.alsb.statistics_1.0.0.0.jar</pre></div></div>

<p>For Oracle Service Bus 10gR3:</p>

<div class="wp_syntax"><div class="code"><pre class="dos dos" style="font-family:monospace;"><span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">ALSB_HOME</span>=c:\bea\osb_10.3
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\lib\sb-kernel-api.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\lib\sb-kernel-common.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\lib\sb-kernel-resources.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\lib\sb-kernel-impl.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\..\modules\com.bea.common.configfwk_1.2.1.0.jar
<span style="color: #b1b100; font-weight: bold;">SET</span> <span style="color: #448844;">CLASSPATH</span>=<span style="color: #33cc33;">%</span><span style="color: #448888;">CLASSPATH</span><span style="color: #33cc33;">%</span>;<span style="color: #33cc33;">%</span><span style="color: #448888;">ALSB_HOME</span><span style="color: #33cc33;">%</span>\..\modules\com.bea.alsb.statistics_1.0.1.0.jar</pre></div></div>

<p>In our example, we will try to change the HTTP timeout in the <strong>normalLoanProcessor</strong> business service present in ALSB/OSB examples server.</p>
<div id="attachment_1474" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/normalLoanProcessor.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/normalLoanProcessor-300x284.jpg" alt="normalLoanProcessor" title="normalLoanProcessor" width="300" height="284" class="size-medium wp-image-1474" /></a><p class="wp-caption-text">normalLoanProcessor configuration</p></div>
<p>For that, we will first connect to the bus from WLST and open a session using <a href="http://docs.oracle.com/cd/E13159_01/osb/docs10gr3/javadoc/com/bea/wli/sb/management/configuration/SessionManagementMBean.html">SessionManagementMBean</a></p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> com.<span style="color: black;">bea</span>.<span style="color: black;">wli</span>.<span style="color: black;">sb</span>.<span style="color: black;">management</span>.<span style="color: black;">configuration</span> <span style="color: #ff7700;font-weight:bold;">import</span> SessionManagementMBean
connect<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;weblogic&quot;</span>, <span style="color: #483d8b;">&quot;weblogic&quot;</span>, <span style="color: #483d8b;">&quot;t3://localhost:7021&quot;</span><span style="color: black;">&#41;</span>
domainRuntime<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
sessionMBean = findService<span style="color: black;">&#40;</span>SessionManagementMBean.<span style="color: black;">NAME</span>, SessionManagementMBean.<span style="color: black;">TYPE</span><span style="color: black;">&#41;</span>
sessionName = <span style="color: #483d8b;">&quot;mysession&quot;</span>
sessionMBean.<span style="color: black;">createSession</span><span style="color: black;">&#40;</span>sessionName<span style="color: black;">&#41;</span></pre></div></div>

<div id="attachment_1481" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/mysession.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/mysession-300x54.jpg" alt="mysession" title="mysession" width="300" height="54" class="size-medium wp-image-1481" /></a><p class="wp-caption-text">mysession shown in sbconsole</p></div>
<p>Nothing new until now. Next thing we need is a reference to the component you want to modify. We chose to use a <a href="http://docs.oracle.com/cd/E13159_01/osb/docs10gr3/javadoc/com/bea/wli/sb/management/query/BusinessServiceQuery.html">BusinessServiceQuery</a> like:</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> com.<span style="color: black;">bea</span>.<span style="color: black;">wli</span>.<span style="color: black;">sb</span>.<span style="color: black;">management</span>.<span style="color: black;">query</span> <span style="color: #ff7700;font-weight:bold;">import</span> BusinessServiceQuery
<span style="color: #ff7700;font-weight:bold;">from</span> com.<span style="color: black;">bea</span>.<span style="color: black;">wli</span>.<span style="color: black;">sb</span>.<span style="color: black;">management</span>.<span style="color: black;">configuration</span> <span style="color: #ff7700;font-weight:bold;">import</span> ALSBConfigurationMBean
bsQuery = BusinessServiceQuery<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
bsQuery.<span style="color: black;">setLocalName</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;normalLoanProcessor&quot;</span><span style="color: black;">&#41;</span> 
bsQuery.<span style="color: black;">setPath</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;MortgageBroker/BusinessServices&quot;</span><span style="color: black;">&#41;</span>
alsbSession = findService<span style="color: black;">&#40;</span>ALSBConfigurationMBean.<span style="color: black;">NAME</span> + <span style="color: #483d8b;">&quot;.&quot;</span> + sessionName, ALSBConfigurationMBean.<span style="color: black;">TYPE</span><span style="color: black;">&#41;</span>
refs = alsbSession.<span style="color: black;">getRefs</span><span style="color: black;">&#40;</span>bsQuery<span style="color: black;">&#41;</span>
bsRef = refs.<span style="color: black;">iterator</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">next</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>After this we have a reference to the business service we want to modify. Now is when fun begins.</p>
<p>There is an undocumented service bus <strong>ServiceConfigurationMBean</strong> (not to be confused with old com.bea.p13n.management.ServiceConfigurationMBean) whose description is &#8216;MBean for configuring Services&#8217;. </p>
<div id="attachment_1514" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/ServiceConfiguration.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/ServiceConfiguration-300x168.jpg" alt="" title="ServiceConfiguration" width="300" height="168" class="size-medium wp-image-1514" /></a><p class="wp-caption-text">ServiceConfiguration.mysession as shown in jconsole</p></div>
<p>Among the different methods, we find one with an interesting name: <strong>getServiceDefinition</strong></p>
<div id="attachment_1515" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/getServiceDefinition.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/getServiceDefinition-300x168.jpg" alt="" title="getServiceDefinition" width="300" height="168" class="size-medium wp-image-1515" /></a><p class="wp-caption-text">getServiceDefinition as shown in jconsole</p></div>
<p>It looks that we can use the <strong>getServiceDefinition</strong> method with our previous reference to the business service for obtaining exactly what its name states.</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> com.<span style="color: black;">bea</span>.<span style="color: black;">wli</span>.<span style="color: black;">sb</span>.<span style="color: black;">management</span>.<span style="color: black;">configuration</span> <span style="color: #ff7700;font-weight:bold;">import</span> ServiceConfigurationMBean
servConfMBean = findService<span style="color: black;">&#40;</span>ServiceConfigurationMBean.<span style="color: black;">NAME</span> + <span style="color: #483d8b;">&quot;.&quot;</span> + sessionName, ServiceConfigurationMBean.<span style="color: black;">TYPE</span><span style="color: black;">&#41;</span>
serviceDefinition = servConfMBean.<span style="color: black;">getServiceDefinition</span><span style="color: black;">&#40;</span>bsRef<span style="color: black;">&#41;</span></pre></div></div>

<p>This is the result of printing <strong>serviceDefinition</strong> variable:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;xml-fragment</span> <span style="color: #000066;">xmlns:tran</span>=<span style="color: #ff0000;">&quot;http://www.bea.com/wli/sb/transports&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:coreEntry</span> <span style="color: #000066;">isEnabled</span>=<span style="color: #ff0000;">&quot;true&quot;</span> <span style="color: #000066;">isProxy</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000066;">xmlns:ser</span>=<span style="color: #ff0000;">&quot;http://www.bea.com/wli/sb/services&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:description</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:binding</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;SOAP&quot;</span> <span style="color: #000066;">xsi:type</span>=<span style="color: #ff0000;">&quot;con:SoapBindingType&quot;</span> <span style="color: #000066;">xmlns:con</span>=<span style="color: #ff0000;">&quot;http://www.bea.com/wli/sb/services/bindings/config&quot;</span> <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;con:wsdl</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;MortgageBroker/WSDL/normalLoan&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;con:binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;con:name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>NormalLoanApprovalServiceSoapBinding<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/con:name<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;con:namespace<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://example.org<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/con:namespace<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/con:binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ser:binding<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:monitoring</span> <span style="color: #000066;">isEnabled</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:aggregationInterval<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>5<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ser:aggregationInterval<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ser:monitoring<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:sla-alerting</span> <span style="color: #000066;">isEnabled</span>=<span style="color: #ff0000;">&quot;true&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:alertLevel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>normal<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ser:alertLevel<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ser:sla-alerting<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:ws-policy<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:binding-mode<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>wsdl-policy-attachments<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ser:binding-mode<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ser:ws-policy<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ser:coreEntry<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ser:endpointConfig</span> <span style="color: #000066;">xmlns:ser</span>=<span style="color: #ff0000;">&quot;http://www.bea.com/wli/sb/services&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tran:provider-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tran:provider-id<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tran:inbound<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>false<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tran:inbound<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tran:URI<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;env:value</span> <span style="color: #000066;">xmlns:env</span>=<span style="color: #ff0000;">&quot;http://www.bea.com/wli/config/env&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>http://localhost:7021/njws_basic_ejb/NormalSimpleBean<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/env:value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tran:URI<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tran:outbound-properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tran:load-balancing-algorithm<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>none<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tran:load-balancing-algorithm<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tran:retry-count<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>0<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tran:retry-count<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tran:retry-interval<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>30<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tran:retry-interval<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tran:retry-application-errors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>true<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tran:retry-application-errors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tran:outbound-properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;tran:provider-specific</span> <span style="color: #000066;">xsi:type</span>=<span style="color: #ff0000;">&quot;http:HttpEndPointConfiguration&quot;</span> <span style="color: #000066;">xmlns:http</span>=<span style="color: #ff0000;">&quot;http://www.bea.com/wli/sb/transports/http&quot;</span> <span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;http:outbound-properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;http:request-method<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>POST<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/http:request-method<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;http:timeout<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>0<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/http:timeout<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/http:outbound-properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/tran:provider-specific<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ser:endpointConfig<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/xml-fragment<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Surprised? It&#8217;s exactly the same definition written in .BusinessService XML files. In fact, the service definition implements <a href="http://xmlbeans.apache.org/docs/2.4.0/reference/org/apache/xmlbeans/XmlObject.html">XMLObject</a>. </p>
<p>Now it&#8217;s time to update the business service definition with our new timeout value (let&#8217;s say 5000 milliseconds) using XPath and XMLBeans. We must also take care of defining namespaces in XPath the same way that are defined in .BusinessService XML files.</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;">nsEnv = <span style="color: #483d8b;">&quot;declare namespace env='http://www.bea.com/wli/config/env' &quot;</span>
nsSer = <span style="color: #483d8b;">&quot;declare namespace ser='http://www.bea.com/wli/sb/services' &quot;</span>
nsTran = <span style="color: #483d8b;">&quot;declare namespace tran='http://www.bea.com/wli/sb/transports' &quot;</span>
nsHttp = <span style="color: #483d8b;">&quot;declare namespace http='http://www.bea.com/wli/sb/transports/http' &quot;</span>
nsIWay = <span style="color: #483d8b;">&quot;declare namespace iway='http://www.iwaysoftware.com/alsb/transports' &quot;</span>
confPath = <span style="color: #483d8b;">&quot;ser:endpointConfig/tran:provider-specific/http:outbound-properties/http:timeout&quot;</span>
confValue = <span style="color: #483d8b;">&quot;5000&quot;</span>
confElem = serviceDefinition.<span style="color: black;">selectPath</span><span style="color: black;">&#40;</span>nsSer + nsTran + nsHttp + confPath<span style="color: black;">&#41;</span><span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span>
confElem.<span style="color: black;">setStringValue</span><span style="color: black;">&#40;</span>confValue<span style="color: black;">&#41;</span></pre></div></div>

<p>We are almost there. First we update the service.</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;">servConfMBean.<span style="color: black;">updateService</span><span style="color: black;">&#40;</span>bsRef, serviceDefinition<span style="color: black;">&#41;</span></pre></div></div>

<div id="attachment_1488" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/mysession_modified.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/mysession_modified-300x51.jpg" alt="" title="mysession_modified" width="300" height="51" class="size-medium wp-image-1488" /></a><p class="wp-caption-text">Modified mysession shown in sbconsole</p></div>
<p>And finally, we activate the session (see <a href="#NOTE">NOTE</a>) like we would do in bus console.</p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;">sessionMBean.<span style="color: black;">activateSession</span><span style="color: black;">&#40;</span>sessionName, <span style="color: #483d8b;">&quot;Comments&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<div id="attachment_1490" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/configuration_change.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/configuration_change-300x50.jpg" alt="" title="configuration_change" width="300" height="50" class="size-medium wp-image-1490" /></a><p class="wp-caption-text">mysession changes shown in sbconsole</p></div>
<div id="attachment_1493" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/task_detail.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/task_detail-300x50.jpg" alt="" title="task_detail" width="300" height="50" class="size-medium wp-image-1493" /></a><p class="wp-caption-text">Task details of mysession</p></div>
<div id="attachment_1491" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/normalLoanProcessor_updated.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2012/03/normalLoanProcessor_updated-300x294.jpg" alt="" title="normalLoanProcessor_updated" width="300" height="294" class="size-medium wp-image-1491" /></a><p class="wp-caption-text">Updated normalLoanProcessor configuration </p></div>
<p>With this approach, it could be possible to build a framework that allows to customize ALL fields as needed.</p>
<p><a name="NOTE">NOTE:</a><br />
If you get the exception below when activating changes, please update your WebLogic Server configuration as described in <a href="http://orasoa.blogspot.com/2008/12/deploy-to-oracle-service-bus-does-not.html">Deploy to Oracle Service Bus does not work</a></p>
<pre>
Traceback (innermost last):
  File "<console>", line 1, in ?
com.bea.wli.config.deployment.server.ServerLockException: Failed to obtain WLS Edit lock; it is currently held by user weblogic. This indicates that you have either started a WLS change and forgotten to activate it, or another user is performing WLS changes which have yet to be activated. The WLS Edit lock can be released by logging into WLS console and either releasing the lock or activating the pending WLS changes.
        at com.bea.wli.config.deployment.server.ServerDeploymentInitiator.__serverCommit(Unknown Source)
        at com.bea.wli.config.deployment.server.ServerDeploymentInitiator.access$200(Unknown Source)
        at com.bea.wli.config.deployment.server.ServerDeploymentInitiator$1.run(Unknown Source)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
        at weblogic.security.service.SecurityManager.runAs(Unknown Source)
        at com.bea.wli.config.deployment.server.ServerDeploymentInitiator.serverCommit(Unknown Source)
        at com.bea.wli.config.deployment.server.ServerDeploymentInitiator.execute(Unknown Source)
        at com.bea.wli.config.session.SessionManager.commitSessionUnlocked(SessionManager.java:420)
        at com.bea.wli.config.session.SessionManager.commitSession(SessionManager.java:339)
        at com.bea.wli.config.session.SessionManager.commitSession(SessionManager.java:297)
        at com.bea.wli.config.session.SessionManager.commitSession(SessionManager.java:306)
        at com.bea.wli.sb.management.configuration.SessionManagementMBeanImpl.activateSession(SessionManagementMBeanImpl.java:47)
[...]
</pre>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/tjPJPQ9nDrk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2012/03/14/alsbosb-customization-using-wlst/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Sonar Reports from Hudson</title>
		<link>http://www.theserverlabs.com/blog/2011/03/16/sonar-reports-with-hudson/</link>
		<comments>http://www.theserverlabs.com/blog/2011/03/16/sonar-reports-with-hudson/#comments</comments>
		<pubDate>Wed, 16 Mar 2011 10:53:56 +0000</pubDate>
		<dc:creator>Gerardo Viedma</dc:creator>
				<category><![CDATA[Agile & XP]]></category>
		<category><![CDATA[Continuous Integration]]></category>
		<category><![CDATA[Default]]></category>
		<category><![CDATA[Methodologies]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[Automation]]></category>
		<category><![CDATA[Hudson]]></category>
		<category><![CDATA[quality]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=1360</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2011/03/16/sonar-reports-with-hudson/";</script>Introduction In order to guarantee the quality of software development projects, it is important to be able to verify that a continuous integration build meets a minimum set of quality control criteria. The open source project Hudson provides the popular continuous integration server we will use throughout our example. Similarly, Sonar is a lead open [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2011/03/16/sonar-reports-with-hudson/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><h2>Introduction</h2>
<p>In order to guarantee the quality of software development projects, it is important to be able to verify that a continuous integration build meets a minimum set of quality control criteria. The open source project <a href="http://hudson-ci.org/" target="_blank">Hudson</a> provides the popular continuous integration server we will use throughout our example. Similarly, <a href="http://www.sonarsource.org/" target="_blank">Sonar</a> is a lead open source tool providing a centralized platform for storing and managing this type of quality control indicators. By integrating Sonar with Hudson, we&#8217;re able to extract and verify quality control metrics stored by Sonar in automated and recurrent manner from Hudson. By verifying these quality metrics we can qualify a given build as valid from a quality perspective, and quickly flag down builds where violations occur. At the same time, it will be very useful to generate summaries of key quality metrics in an automated manner, informing interested parties with a daily email.</p>
<h2>Installing Hudson</h2>
<p>As a first step, you will need to download and install Hudson from <a href="http://hudson-ci.org/" target="_blank">http://hudson-ci.org/</a>.</p>
<h3>Installing the Groovy Postbuild Plugin</h3>
<p>In order to be able to extend Hudson with custom Groovy-based scripts, we will use the  <a href="http://wiki.hudson-ci.org/display/HUDSON/Groovy+Postbuild+Plugin" target="_blank">Groovy Postbuild Plugin</a>. To install this plugin, you will have to click on <em>Manage Hudson</em> followed by <em>Manage Plugins</em>, as shown below:</p>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/hudson1.png" alt="" title="hudson1" width="100%" height="100%" /></p>
<p>You will then have to select the <em>Available</em> tab at the top, and search for <em>Groovy Postbuild Plugin</em> under the section <em>Other Post-Build Actions</em>.<br />
<img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/hudson2.png" alt="" title="hudson2" width="100%" height="100%" /></p>
<h3>Sonar Reporting the Groovy Way</h3>
<p>Once the Groovy Postbuild Plugin has been successfully installed and Hudson restarted, you can go ahead and download the <a href='http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/SonarReports.zip'>SonarReports</a> package and extract it to <em>${HUDSON_HOME}</em>, the home directory of the Hudson server (e.g. the folder <em>.hudson</em> under the user&#8217;s home directory on Windows systems). This zip file contains the file <em>SonarReports.groovy</em> under <em>scripts/groovy</em>, which will be created under ${HUDSON_HOME} after expansion.</p>
<h2>Hudson Job Configuration</h2>
<p>To facilitate reuse of our Hudson configuration for Sonar, we will first create a Sonar Metrics job to be used as a template. We can then create a new job for each project we wish to create Sonar reports for by simply copying this job template.</p>
<p>In the Sonar Metrics job, we first create the necessary parameters that will be used as thresholds and validated by our Groovy script. To this end, we select the checkbox <em>This build is parameterized</em> under the job&#8217;s configuration. We then configure the parameters are shown below, where we have provided the corresponding screenshots:</p>
<ul>
<li><strong>projectName</strong>: project name that will appear in emails sent from Hudson.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param1.png" alt="" title="params"></p>
<li><strong>sonarProjectId</strong>: internal project ID used by Sonar.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param2.png" alt="" title="params"></p>
<li><strong>sonarUrl</strong>: URL for the Sonar server.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param3.png" alt="" title="params"></p>
<li><strong>emailRecipients</strong>: email addresses for recipients of Sonar metrics summary.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param4.png" alt="" title="params"></p>
<li><strong>rulesComplianceThreshold</strong>: minimum percentage of rule compliance for validating a build. A value of <em>false</em> means this metric will not be enforced.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param5.png" alt="" title="params"></p>
<li><strong>blockerThreshold</strong>: maximum number of <em>blocker</em> violations for validating a build. A value of <em>false</em> means this metric will not be enforced.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param6.png" alt="" title="params"></p>
<li><strong>criticalThreshold</strong>: maximum number of <em>critical</em> violations for validating a build. A value of <em>false</em> means this metric will not be enforced.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param7.png" alt="" title="params"></p>
<li><strong>majorThreshold</strong>: maximum number of <em>major</em> violations for validating a build. A value of <em>false</em> means this metric will not be enforced.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param8.png" alt="" title="params"></p>
<li><strong>codeCoverageThreshold</strong>: minimum percentage of code coverage for unit tests for validating a build.  A value of <em>false</em> means this metric will not be enforced.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param9.png" alt="" title="params"></p>
<li><strong>testSuccessThreshold</strong>: minimum percentage of successful unit tests for validating a build.  A value of <em>false</em> means this metric will not be enforced.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param10.png" alt="" title="params"></p>
<li><strong>violationsThreshold</strong>: maximum number of violations of all type for validating a build. A value of <em>false</em> means this metric will not be enforced.</li>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/param11.png" alt="" title="params">
</ul>
<p>Finally, we enable the Groovy Postbuild plugin by selecting the corresponding checkbox under the <em>Post-build Actions</em> section of the job configuration page. In the text box, we include the following Groovy code to call into our script:</p>
<pre code="groovy">
sonarReportsScript = "${System.getProperty('HUDSON_HOME')}/scripts/groovy/SonarReports.groovy"
shell = new GroovyShell(getBinding())
println "Executing script for Sonar report generation from ${sonarReportsScript}"
shell.evaluate(new File(sonarReportsScript))
</pre>
<p>Your Hudson configuration page should look like this:</p>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/groovy.png" alt="" title="groovy" /></p>
<h2>Generating Sonar Reports</h2>
<p>In order to automatically generate Sonar reports, we can configure our Hudson job to build periodically (e.g. daily) by selecting this option under <em>Build Triggers</em>. The job will then execute with the specified frequency, using the default quality thresholds we configured in the job&#8217;s parameters. </p>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/periodically.png" alt="" title="periodic" /></p>
<p>It is also possible to run the job manually to generate reports on demand at any time. In this case, Hudson will ask for the value of the threshold parameters that will be passed in to our Groovy script. These values will override the default values specified in the job&#8217;s configuration. Here is an example:</p>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/manual.png" alt="" title="manual" /></p>
<h3>Verifying Quality Control Metrics</h3>
<p>When the Hudson job runs, our Groovy script will verify that any thresholds defined in the job&#8217;s configuration are met by the project metrics extracted from Sonar. If the thresholds are met, the build will succeed and a summary of the quality control metrics will appear in the Hudson build. In addition, a summary email will be sent to the recipient list <em>emailRecipients</em>, providing interested parties with information regarding the key analyzed metrics. </p>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/pass.png" alt="" title="pass" /></p>
<p>On the other hand, if the thresholds are not met, the build will be marked as failed and the metric violation described in the Hudson build. Similarly, an email will be sent out informing recipients of the quality control violation.</p>
<p><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2011/03/fail.png" alt="" title="fail" /></p>
<h2>Conclusion</h2>
<p>This article demonstrates how Hudson can be extended with the use of dynamic programming languages like Groovy. In our example, we have created a Hudson job that verifies quality control metrics generated by Sonar and automatically sends quality reports by email. This type of functionality is useful in continuous integration environments, in order to extend the default features provided by Hudson or Sonar to meet custom needs.</p>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/n68RK8eWn7g" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2011/03/16/sonar-reports-with-hudson/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Smooks processing recipies</title>
		<link>http://www.theserverlabs.com/blog/2010/12/17/smooks-processing-recipies/</link>
		<comments>http://www.theserverlabs.com/blog/2010/12/17/smooks-processing-recipies/#comments</comments>
		<pubDate>Fri, 17 Dec 2010 10:48:54 +0000</pubDate>
		<dc:creator>mgryszko</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=1333</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/12/17/smooks-processing-recipies/";</script>Introduction In one of our customer projects we had a requirement to import CSV, fixed length and Excel files in different formats and store records in the database. We chose Smooks to accomplish this task. Smooks is a Java framework to read, process and transform data from various sources (CSV, fixed length, XML, EDI, &#8230;) [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/12/17/smooks-processing-recipies/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><h3>Introduction</h3>
<p>In one of our customer projects we had a requirement to import CSV, fixed length and Excel files in different formats and store records in the database. We chose <a href="http://www.smooks.org/">Smooks</a> to accomplish this task.</p>
<p>Smooks is a Java framework to read, process and transform data from various sources (CSV, fixed length, XML, EDI, &#8230;) to various destinations (XML, Java objects, database). It convinced me because:</p>
<ul>
<li>it brings out-of-the-box components to read CSV and fixed length files</li>
<li>it integrates smoothly with an ORM library (Hibernate, JPA)</li>
<li>processing is configured using an XML configuration file &#8211; you need only few lines of code to do the transformations</li>
<li>extensibility &#8211; implementing a custom Excel reader was relatively easy</li>
<li>low added filtering overhead &#8211; reading 100.000 CSV lines and storing them in the database using Hibernate took us less than 30 seconds</li>
</ul>
<p>During the development we had to overcome some hurdles imposed by Smooks processing model. In this post I would like to share our practical experience we gained working with Smooks. First, I&#8217;m going to present a sample transformation use case with requirements similar to a real-world assignment. Then I will present solutions to these requirements in a &#8216;how-to&#8217; style.</p>
<h3>Use case</h3>
<p>We are developing a ticketing application. The heart of your application is <code>Issue</code> class:<br />
<img src="http://mgryszko.files.wordpress.com/2010/12/issue-uml.png" title="Issue class" class="alignnone size-full wp-image-211" /></p>
<p>We have to write an import and conversion module for an external ticketing system. Data comes in the CSV format (for the sake of simplicity). The domain model of the external system is slightly different than ours; however, issues coming from the external issue tracker can be mapped to our Issues.</p>
<p>External system exchange format defines the following fields: description, priority, reporter, assignee, createdDate, createdTime, updatedDate, updatedTime. They should be mapped to our <code>Issue</code> in the following manner:</p>
<ul>
<li><strong>description</strong> property &#8211; description field</li>
<p>This is a simple Smooks mapping. No big issue.</p>
<li><strong>project</strong> property &#8211; there is no project field. <code>Project</code> should be assigned manually</li>
<p>A constant object (from our domain model) must be passed to Smooks engine to be used in Java binding.<br />
See <a href="#assignConstantObjectToProperty">Assign constant object to a property</a>.</p>
<li><strong>priority</strong> property &#8211; priority field; P1 and P2 priorities should be mapped to <code>Priority.LOW</code>, P3 to <code>Priority.MEDIUM</code>, P4 and P5 to <code>Priority.HIGH</code></li>
<p>This mapping could be done using an MVEL expression. However, we want to encapsulate this logic in a separate class that can be easily unit-tested. See <a href="#useExternalObjectToCalculatePropertyValue">Use external object to calculate property value</a></p>
<li><strong>involvedPersons</strong> property &#8211; reporter field plus assignee field if not empty (append assignee using &#8216;;&#8217; separator)</li>
<p><a href="#setCompoundPropertiesInJavaBinding">Set compound properties in Java binding</a> will show how to achieve it.</p>
<li><strong>created</strong> property &#8211; merge createdDate and createdTime fields</li>
<li><strong>updated</strong> property &#8211; merge updatedDate and updatedTime fields</li>
<p>In <a href="#setDatetimeFromDateAndTimeFields">Set datetime from date and time fields</a>, two strategies will be presented.</p>
<p>Before diving into details, I&#8217;m going to present the final Smooks configuration and the invocation code of the transformation (as JUnit 4 test). Later on, in each recipe, I will explain the XML configuration and Java code fragments relevant to that recipe.</p>
<p>The remaining classes (<code>Issue</code>, <code>Priority</code>, <code>Project</code>, <code>IssuePrioritizer</code>) are not included in the text. You can <a href="https://github.com/mgryszko/blog-smooks-recipies">browse online</a> the source code in GitHub. To get your local copy, clone the Git repository:</p>
<p><code><br />
git clone git://github.com/mgryszko/blog-smooks-recipies.git<br />
</code></p>
<p><code><br />
smooks-config.xml<br />
</code></p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;smooks-resource-list</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.milyn.org/xsd/smooks-1.1.xsd&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns:csv</span>=<span style="color: #ff0000;">&quot;http://www.milyn.org/xsd/smooks/csv-1.3.xsd&quot;</span></span>
<span style="color: #009900;">    <span style="color: #000066;">xmlns:jb</span>=<span style="color: #ff0000;">&quot;http://www.milyn.org/xsd/smooks/javabean-1.3.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;params<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;param</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;stream.filter.type&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>SAX<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/param<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/params<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;csv:reader</span> <span style="color: #000066;">fields</span>=<span style="color: #ff0000;">&quot;description,priorityCode,reporter,assignee,createdDate,createdTime,updatedDate,updatedTime&quot;</span> <span style="color: #000066;">skipLines</span>=<span style="color: #ff0000;">&quot;1&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:bean</span> <span style="color: #000066;">beanId</span>=<span style="color: #ff0000;">&quot;transformedProps&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;java.util.HashMap&quot;</span> <span style="color: #000066;">createOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;@reporter&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/reporter&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;@assignee&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/assignee&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;@updatedDate&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/updatedDate&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;@updatedTime&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/updatedTime&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:bean</span> <span style="color: #000066;">beanId</span>=<span style="color: #ff0000;">&quot;issues&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;java.util.ArrayList&quot;</span> <span style="color: #000066;">createOnElement</span>=<span style="color: #ff0000;">&quot;csv-set&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:wiring</span> <span style="color: #000066;">beanIdRef</span>=<span style="color: #ff0000;">&quot;issue&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:bean</span> <span style="color: #000066;">beanId</span>=<span style="color: #ff0000;">&quot;issue&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.tsl.smooks.model.Issue&quot;</span> <span style="color: #000066;">createOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;description&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/description&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:wiring</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;project&quot;</span> <span style="color: #000066;">beanIdRef</span>=<span style="color: #ff0000;">&quot;project&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:expression</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;priority&quot;</span> <span style="color: #000066;">execOnElement</span>=<span style="color: #ff0000;">&quot;csv-record/priorityCode&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            prioritizer.assignPriorityFromCode(_VALUE)
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:expression<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:expression</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;involvedPersons&quot;</span> <span style="color: #000066;">execOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            transformedProps[&quot;reporter&quot;]
                + (org.apache.commons.lang.StringUtils.isNotBlank(transformedProps[&quot;assignee&quot;]) ? &quot;;&quot; + transformedProps[&quot;assignee&quot;] : &quot;&quot;)
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:expression<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;createdDatePart&quot;</span> <span style="color: #000066;">decoder</span>=<span style="color: #ff0000;">&quot;Date&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/createdDate&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:decodeParam</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;format&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>yyyy-MM-dd<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:decodeParam<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;createdTimePart&quot;</span> <span style="color: #000066;">decoder</span>=<span style="color: #ff0000;">&quot;Date&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/createdTime&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:decodeParam</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;format&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>HH:mm<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:decodeParam<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:expression</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;updated&quot;</span> <span style="color: #000066;">execOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            updated = transformedProps[&quot;updatedDate&quot;] + &quot; &quot; + transformedProps[&quot;updatedTime&quot;];
            new java.text.SimpleDateFormat(&quot;yyyy-MM-dd HH:mm&quot;).parse(updated)
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:expression<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/smooks-resource-list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><code><br />
SmooksRecipiesTest<br />
</code></p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.tsl.smooks</span>;
&nbsp;
<span style="color: #666666; font-style: italic;">// imports hidden</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SmooksRecipiesTest <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">SimpleDateFormat</span> DATETIME_FORMAT <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">SimpleDateFormat</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;yyyy-MM-dd HH:mm&quot;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> Source importedIssues <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StringSource<span style="color: #009900;">&#40;</span>
        <span style="color: #0000ff;">&quot;description,priority,reporter,assignee,createdDate,createdTime,updatedDate,updatedTime<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
            <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;Added phased initialization of javabean cartridge,P1,Ataulfo,Teodorico,2010-10-01,13:10,2010-10-10,20:01<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>
            <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;Processing recursive tree like structures with the Javabean Cartridge,P3,Eurico,,2010-10-02,07:15,2010-11-15,09:45&quot;</span>
    <span style="color: #009900;">&#41;</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> Smooks smooks;
    <span style="color: #000000; font-weight: bold;">private</span> ExecutionContext executionContext;
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>Issue<span style="color: #339933;">&gt;</span> expIssues;
    <span style="color: #000000; font-weight: bold;">private</span> Project expProject <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Project<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Smooks&quot;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
    @Before
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> initSmooks<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        smooks <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Smooks<span style="color: #009900;">&#40;</span>getResourceFromClassLoader<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;smooks-config.xml&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
        executionContext <span style="color: #339933;">=</span> smooks.<span style="color: #006633;">createExecutionContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
        executionContext.<span style="color: #006633;">getBeanContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">addBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;project&quot;</span>, expProject<span style="color: #009900;">&#41;</span>;
        executionContext.<span style="color: #006633;">getBeanContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">addBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;prioritizer&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> IssuePrioritizer<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">InputStream</span> getResourceFromClassLoader<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> getClass<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getClassLoader</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getResourceAsStream</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Before
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> createExpIssues<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        expIssues <span style="color: #339933;">=</span> <span style="color: #003399;">Arrays</span>.<span style="color: #006633;">asList</span><span style="color: #009900;">&#40;</span>
            <span style="color: #000000; font-weight: bold;">new</span> Issue<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Added phased initialization of javabean cartridge&quot;</span>, expProject, Priority.<span style="color: #006633;">LOW</span>,
                <span style="color: #0000ff;">&quot;Ataulfo;Teodorico&quot;</span>, DATETIME_FORMAT.<span style="color: #006633;">parse</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;2010-10-01 13:10&quot;</span><span style="color: #009900;">&#41;</span>, DATETIME_FORMAT.<span style="color: #006633;">parse</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;2010-10-10 20:01&quot;</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#41;</span>,
            <span style="color: #000000; font-weight: bold;">new</span> Issue<span style="color: #009900;">&#40;</span>
                <span style="color: #0000ff;">&quot;Processing recursive tree like structures with the Javabean Cartridge&quot;</span>, expProject, Priority.<span style="color: #006633;">MEDIUM</span>,
                <span style="color: #0000ff;">&quot;Eurico&quot;</span>, DATETIME_FORMAT.<span style="color: #006633;">parse</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;2010-10-02 07:15&quot;</span><span style="color: #009900;">&#41;</span>, DATETIME_FORMAT.<span style="color: #006633;">parse</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;2010-11-15 09:45&quot;</span><span style="color: #009900;">&#41;</span>
            <span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @Test
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> process<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Exception</span> <span style="color: #009900;">&#123;</span>
        smooks.<span style="color: #006633;">filterSource</span><span style="color: #009900;">&#40;</span>executionContext, importedIssues<span style="color: #009900;">&#41;</span>;
&nbsp;
        List<span style="color: #339933;">&lt;</span>Issue<span style="color: #339933;">&gt;</span> issues <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>List<span style="color: #339933;">&lt;</span>Issue<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> executionContext.<span style="color: #006633;">getBeanContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;issues&quot;</span><span style="color: #009900;">&#41;</span>;
        assertEquals<span style="color: #009900;">&#40;</span>expIssues, issues<span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a name="assignConstantObjectToProperty"><br />
<h3>Assign a constant object (from your domain model) to a property</h3>
<p></a></p>
<p>According to the Smooks manual, bean context is the place where JavaBean cartridge puts newly created beans. We can add our own bean (<code>Project</code>):</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;">executionContext <span style="color: #339933;">=</span> smooks.<span style="color: #006633;">createExecutionContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
executionContext.<span style="color: #006633;">getBeanContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">addBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;project&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> Project<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Smooks&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<p>&#8230; and reference it in the Java binding configuration:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:bean</span> <span style="color: #000066;">beanId</span>=<span style="color: #ff0000;">&quot;issue&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.tsl.smooks.model.Issue&quot;</span> <span style="color: #000066;">createOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    ....
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:wiring</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;project&quot;</span> <span style="color: #000066;">beanIdRef</span>=<span style="color: #ff0000;">&quot;project&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><a name="useExternalObjectToCalculatePropertyValue"><br />
<h3>Use an external object to calculate property value</h3>
<p></a></p>
<p>Similar to the previous tip we add an additional bean (<code>IssuePrioritizer</code>) to the bean context:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;">executionContext <span style="color: #339933;">=</span> smooks.<span style="color: #006633;">createExecutionContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
executionContext.<span style="color: #006633;">getBeanContext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">addBean</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;prioritizer&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> IssuePrioritizer<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;</pre></div></div>

<p>&#8230; and define an MVEL expression for the property. The MVEL expression uses the bean and references the value being processed (in this case coming from the CSV reader) by the implicit _VALUE variable:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:bean</span> <span style="color: #000066;">beanId</span>=<span style="color: #ff0000;">&quot;issue&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.tsl.smooks.model.Issue&quot;</span> <span style="color: #000066;">createOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    ....
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:expression</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;priority&quot;</span> <span style="color: #000066;">execOnElement</span>=<span style="color: #ff0000;">&quot;csv-record/priorityCode&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        prioritizer.assignPriorityFromCode(_VALUE)
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:expression<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><a name="setCompoundPropertiesInJavaBinding"><br />
<h3>Set compound properties in Java binding</h3>
<p></a></p>
<p>It is not possible to map directly two source fields to a Java bean property. Java bindings with  and  are executed on a SAX visitAfter event bound to to a single XML element/CSV field. We have to define a binding for a helper <code>Map</code> bean with the fields we want to merge:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:bean</span> <span style="color: #000066;">beanId</span>=<span style="color: #ff0000;">&quot;transformedProps&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;java.util.HashMap&quot;</span> <span style="color: #000066;">createOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;@reporter&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/reporter&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;@assignee&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/assignee&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>&#8230; and use an MVEL expression that concatenates two fields using the helper map bean (transformedProps):</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:bean</span> <span style="color: #000066;">beanId</span>=<span style="color: #ff0000;">&quot;issue&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.tsl.smooks.model.Issue&quot;</span> <span style="color: #000066;">createOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    ...
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:expression</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;involvedPersons&quot;</span> <span style="color: #000066;">execOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        transformedProps[&quot;reporter&quot;]
            + (org.apache.commons.lang.StringUtils.isNotBlank(transformedProps[&quot;assignee&quot;]) ? &quot;;&quot; + transformedProps[&quot;assignee&quot;] : &quot;&quot;)
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:expression<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p><a name="setDatetimeFromDateAndTimeFields"><br />
<h3>Set datetime from date and time fields</h3>
<p></a></p>
<p>In this transformation we have to both merge and convert values of two fields. </p>
<p>In the first solution, we create a separate setter for the date and time part in the target <code>Issue</code> class (Smooks uses setters in Java binding):</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Issue <span style="color: #009900;">&#123;</span>
    ...
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setCreatedDatePart<span style="color: #009900;">&#40;</span><span style="color: #003399;">Date</span> createdDatetime<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        createCreatedIfNotInitialized<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
        copyDatePart<span style="color: #009900;">&#40;</span>createdDatetime, created<span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setCreatedTimePart<span style="color: #009900;">&#40;</span><span style="color: #003399;">Date</span> createdDatetime<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        createCreatedIfNotInitialized<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
        copyTimePart<span style="color: #009900;">&#40;</span>createdDatetime, created<span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span>
    ...
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>&#8230; and then use a standard value binding with date decoder:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:bean</span> <span style="color: #000066;">beanId</span>=<span style="color: #ff0000;">&quot;issue&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.tsl.smooks.model.Issue&quot;</span> <span style="color: #000066;">createOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    ...
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;createdDatePart&quot;</span> <span style="color: #000066;">decoder</span>=<span style="color: #ff0000;">&quot;Date&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/createdDate&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:decodeParam</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;format&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>yyyy-MM-dd<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:decodeParam<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:value</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;createdTimePart&quot;</span> <span style="color: #000066;">decoder</span>=<span style="color: #ff0000;">&quot;Date&quot;</span> <span style="color: #000066;">data</span>=<span style="color: #ff0000;">&quot;csv-record/createdTime&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:decodeParam</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;format&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>HH:mm<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:decodeParam<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The advantage of this approach is that you make use of Smooks decoder infrastructure. You can configure the transformation with your own decoders (e.g. custom <code>java.util.Date</code> allowing to specify multiple date formats). If you are using the built-in <code>DateDecoder</code>, you can catch and handle a standard <code>DataDecodeException</code>.</p>
<p>The disadvantage is that you have to change your domain model code. New methods add complexity and must be unit tested, especially in cases when only one of partial setter is called.</p>
<p>In the second solution, you define a binding for a helper <code>Map</code> bean with the date and time fields. In the right binding you use an MVEL expression concatenating date and time strings and converting them to <code>Date</code> (e.g. using a <code>java.text.SimpleDateFormat</code> instance):</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:bean</span> <span style="color: #000066;">beanId</span>=<span style="color: #ff0000;">&quot;issue&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.tsl.smooks.model.Issue&quot;</span> <span style="color: #000066;">createOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    ...
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;jb:expression</span> <span style="color: #000066;">property</span>=<span style="color: #ff0000;">&quot;updated&quot;</span> <span style="color: #000066;">execOnElement</span>=<span style="color: #ff0000;">&quot;csv-record&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        updated = transformedProps[&quot;updatedDate&quot;] + &quot; &quot; + transformedProps[&quot;updatedTime&quot;];
        new java.text.SimpleDateFormat(&quot;yyyy-MM-dd HH:mm&quot;).parse(updated)
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:expression<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/jb:bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>The advantages of the first solution are disadvantages of the second one. You don&#8217;t touch your Java classes. It is simple &#8211; you have to specify only the Smooks configuration. In case of handling of many date/time formats and their combinations, the MVEL expression defining the conversion can become complicated. In case of an exception, you won&#8217;t get <code>DataDecodeException</code>, but an ugly, generic <code>ExpressionEvaluationException</code>.</p>
<h3>Conclusions</h3>
<p>Smooks is a great library that will save you writing a lot of code in case of processing many different formats. With a few lines of code and the XML configuration you will be able to read a file and persist its contents in the database using your favourite ORM framework.</p>
<p>However, Smooks processing model and its usage in built-in cartridges make sometimes difficult to configure the transformation for a real world requirement. The information provided in the user guide is sometimes scarce and unclear. I hope these practical cases will help you use Smooks Java bean mappings and MVEL expressions more effectively.</p>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/a-QzX0QDu8M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2010/12/17/smooks-processing-recipies/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Genomic Processing in the Cloud</title>
		<link>http://www.theserverlabs.com/blog/2010/12/14/genomic-processing-in-the-cloud/</link>
		<comments>http://www.theserverlabs.com/blog/2010/12/14/genomic-processing-in-the-cloud/#comments</comments>
		<pubDate>Tue, 14 Dec 2010 13:34:09 +0000</pubDate>
		<dc:creator>Gerardo Viedma</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cloud Computing]]></category>
		<category><![CDATA[EC2]]></category>
		<category><![CDATA[Genomic Processing]]></category>
		<category><![CDATA[RightScale]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=1291</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/12/14/genomic-processing-in-the-cloud/";</script>Introduction Over the last decade, a new trend has manifested itself in the field of genomic processing. With the advent of the new generation of DNA sequencers has come an explosion in the throughput of DNA sequencing, resulting in the cost per base of generated sequences falling dramatically. Consequently, the bottleneck in sequencing projects around [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/12/14/genomic-processing-in-the-cloud/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><h2>Introduction</h2>
<p>Over the last decade, a new trend has manifested itself in the field of genomic processing. With the advent of the new generation of DNA sequencers has come an explosion in the throughput of DNA sequencing, resulting in the cost per base of generated sequences falling dramatically. Consequently, the bottleneck in sequencing projects around the world has shifted from obtaining DNA reads to the alignment and post-processing of the huge amount of read data now available. To minimize both processing time and memory requirements, specialized algorithms have been developed that trade off speed and memory requirements with the sensitivity of their alignments. Examples include the ultrafast memory-efficient short read aligners BWA and Bowtie, both based on the Burrows-Wheeler transform.</p>
<p>The need to analyse increasingly large amounts of genomics and proteomics data has meant that research labs allocate an increasing part of their time and budget provisioning, managing and maintaining their computational infrastructure. A possible solution to meet their needs for on-demand computational power is to take advantage of the public cloud. With its on-demand operational model, labs can benefit from considerable cost-savings by only paying for hardware when needed for their experiments. Procurement of new hardware is also simplified and more easily justified, without the need to expand in-house resources.</p>
<p>Not only does the cloud reduce the time to provision new hardware; it also provides significant time-savings by automating the installation and customization of the software that runs on top of the hardware. A controlled computational environment for the post-processing of experiments allows results to be more easily reproduced, a key objective to researchers across all disciplines. Results can also be easily shared among researchers, as cloud-based services facilitate the publishing of data over the internet, while allowing researches control over their access. Finally, data storage in the cloud was designed from the ground-up with high-availability and durability as key objectives. By storing their experiment data in the cloud, researchers can ensure their data is safely replicated among data centres. These advantages free researchers from time-consuming operational concerns, such as in-house backups and the provisioning and management of servers from which to share their experiment results.</p>
<p>Given the vast potential benefits of the cloud, The Server Labs is working with the Bioinformatics Department at the <a href="http://www.cnio.es" target="_blank">Spanish National Cancer Research Institute</a> (CNIO) to develop a cloud-based solution that would meet their genomic processing needs.</p>
<h2>An Environment for Genomic Processing in the Cloud</h2>
<p>The first step towards carrying out genomic processing in the cloud is identifying a suitable computational environment, including hardware architecture, operating system and genomic processing tools. CNIO helped us identify the following software packages employed in their typical genomic processing workflows:</p>
<ul>
<li><a href="http://bio-bwa.sourceforge.net/bwa.shtml" target="_blank">Burrows-Wheeler Alignment Tool</a> (BWA): BWA aligns short DNA sequences (reads) to a sequence database such as the human reference genome.</li>
<li><a href="http://www.novocraft.com/download.html" target="_blank">Novoalign</a>: Novoalign is a DNA short read mapper implemented by Novocraft Technologies. The tool uses spaced-seed indexing to align either single or paired-end reads by means of Needleman-Wunsch algorithm. The source code is not available for download. However, anybody may download and use these programs free of charge for their research and any other non-profit activities as long as results are published in open journals.</li>
<li><a href="http://samtools.sourceforge.net" target="_blank">SAM tools</a>: After reads alignment, one might want to call variants or view the alignments against the reference genome. SAM tools is an open-source package of software aplications which includes an alignments viewer and a consensus base caller tool to provide lists of variants (somatic mutations, SNPs and indels).</li>
<li><a href="http://code.google.com/p/bedtools/">BEDTools</a>: This software facilitates common genomics tasks for the comparison, manipulation and annotation of genomic features in Browser Extensible Data (.BED) format. BEDTools supports the comparison of sequence alignments allowing the user to compare next-generation sequencing data with both public and custom genome annotation tracks. BEDTools source code in freely available.</li>
</ul>
<p>Note that, except for Novoalign, all software packages listed above are open source and freely available.</p>
<p>One of the requirements of these tools is that the underlying hardware architecture is 64-bit. For our initial proof of concept, we decided to run a base image with Ubuntu 9.10 for 64-bit on an Amazon EC2 large instance with 7.5 GB of memory, 4 EC2 Compute Units (2 virtual cores with 2 EC2 Compute Units each) and 850 GB of local instance storage. Once we had selected the base image and instance type to run on the cloud, we proceeded to automate the installation and configuration of the software packages. Automating this step ensures that no additional setup tasks are required when launching new instances in the cloud, and provides a controlled and reproducible environment for genomic processing.</p>
<p>By using the RightScale cloud-management platform, we were able to separate out the selection of instance type and base image from the installation and configuration of software specific to genomic processing. First, we created a Server definition for the instance type and operating system specified above. We then scripted the installation and configuration of genomic processing tools, as well as any OS customizations, so that these steps can be executed automatically after new instances are first booted.</p>
<p>Once our new instances were up and running and the software environment finalized, we executed some typical genomic workflows suggested to us by CNIO. We found that for their typical workflow with a raw data input between 3 and 20 GB, the total processing time on the cloud would range between 1 and 4 hours, depending on the size of the raw data and whether the type of alignment was single or paired-end. With an EC2 instance pricing at 38 cents per hour for large instances, and ignoring additional time required for customization of the workflow, <strong>the cost of pure processing tasks totalled less than $2 for a single experiment</strong>.</p>
<p>We also <strong>found the processing times to be comparable to running the same workflow in-house</strong> on similar hardware. However, when processing on the cloud, we found that transferring the raw input data from the lab to the cloud data centre could become a bottleneck, depending on the bandwidth available. We were able to work around this limitation by processing our data on Amazon&#8217;s European data centre and avoiding peak-hours for our data uploads.</p>
<p>Below, we include an example workflow for paired-end alignment that we successfully carried out in the Amazon cloud:</p>
<div id="attachment_1316" class="wp-caption aligncenter" style="width: 496px"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2010/12/cnio-workflow-single-end-alignment.png" alt="Example single-end workflow executed in the cloud." title="cnio-workflow-single-end-alignment" width="486" height="649" class="size-full wp-image-1316" /><p class="wp-caption-text">Example single-end alignment workflow executed in the cloud.</p></div>
<h2>Maximizing the Advantages of the Cloud</h2>
<p>In the first phase, we demonstrated that genomic processing in the cloud is feasible and cost-effective, while providing a performance on par with in-house hardware. To truly realize the benefits of the cloud, however, what we need is an architecture that allows tens or hundreds of experiment jobs to be processed in parallel. This would allow researchers, for instance, to run algorithms with slightly different parameters to analyse the impact on their experiment results. At the same time, we would like a framework which incorporates all of the strengths of the cloud, in particular data durability, publishing mechanisms and audit trails to make experiment results reproducible.</p>
<p>To meet these goals, The Server Labs is developing a genomic processing platform which builds on top of RightScale&#8217;s RightGrid batch processing system. Our platform facilitates the processing of a large number of jobs by leveraging Amazon’s EC2, SQS, and S3 web services in a scalable and cost efficient manner to match demand. The framework also takes care of scheduling, load management, and data transport, so that the genomic workflow can be executed locally on experiment data available to the EC2 worker instance. By using S3 to store the data, we ensure that any input and result data is highly available and persisted between data centres, freeing our users from the need to backup their data. It also ensures that data can be more easily shared with the appropriate level of access control among institutions and researchers. In addition, the monitoring and logging of job submissions provides a convenient mechanism for the production of audit trails for all processing tasks.</p>
<p>The following diagram illustrates the main components of The Server Labs Genomic Processing Cloud Framework:</p>
<div id="attachment_1299" class="wp-caption aligncenter" style="width: 610px"><img class="size-large wp-image-1299" title="cnio-rightgrid" src="http://www.theserverlabs.com/blog/wp-content/uploads/2010/12/cnio-rightgrid.png" alt="The Server Labs Genomic Processing Framework" width="600" height="326" /><p class="wp-caption-text">The Server Labs Genomic Processing Cloud Framework.</p></div>
<p>The Worker Daemon is based on The Server Labs Genomic Processing Server Template, which provides the software stack for genomic processing. It automatically pulls experiment tasks from the SQS input queue along with input data from S3 to launch the genomic processing workflow with the appropriate configuration parameters. Any intermediate and final results are stored in S3 and completed jobs are stored in SQS for auditing.</p>
<h2>Cost Analysis</h2>
<p>Given a RightGrid-based solution for genomic processing, we would like to analyse how much it would cost to run CNIO&#8217;s workflows on the Amazon cloud. Let us assume for the sake of our analysis that CNIO runs 10 experiments in the average month, each of which generate an average of 10 GB of raw input data and produce an additional 20 GB of result data. For each of these experiments, CNIO wishes to run 4 different workflows, with an average running time of 2 hours on a large EC2 instance. In addition, we assume that the experiment results are downloaded once to the CNIO in-house data center. We also assume that the customer already has a RightScale account, the cost of which is not included in the analysis.</p>
<table border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<td width="10%" valign="top"><strong>Amazon Service</strong></td>
<td width="90%" valign="top"><strong>Cost</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td width="10%" valign="top">SQS</td>
<td width="90%" valign="top">Negligible</td>
</tr>
<tr>
<td width="10%" valign="top">S3</td>
<td width="90%" valign="top">
<ul>
<li>Data transfer in: $0.10 per GB * 10 GB per workflow   = $1 per workflow</li>
<li>Data   transfer out: 1 download per workflow * 20 GB per download * $0.15 per GB =   $3 per workflow</li>
<li>Storage: 30   GB per workflow * $0.14 per GB = $4.20 per workflow</li>
<li>Total cost:   $8.20 per workflow</li>
</ul>
</td>
</tr>
<tr>
<td width="55" valign="top">EC2</td>
<td width="371" valign="top">$0.38 per hour * 2 hours per workflow = $0.76 per   workflow</td>
</tr>
<tr>
<td width="55" valign="top">All   services</td>
<td width="371" valign="top"><strong>Total cost: $8.20 + $0.76 = $8.96 per workflow</strong></td>
</tr>
</tbody>
</table>
<p><strong>Total Cost:</strong><br />
10 experiments per month * 4 workflows per experiment * $8.96 per workflow =<br />
<strong> $358.40 per month or $4300 per year</strong></p>
<h2>Towards an On-demand Genomic Processing Service</h2>
<p>By building on the RightGrid framework, The Server Labs is able to offer a robust cloud-based platform on which to perform on-demand genomic processing tasks, at the same time enabling experiment results to be more easily reproduced, stored and published. To make genomic processing even simpler on the cloud, the on-demand model can be taken even one step forward by providing a pay-as-you-go software as a service. In such a model, researchers are agnostic to the fact that the processing of their data is done in the cloud. Instead, they would interact with the platform via a web interface, where they would be able to upload their experiment&#8217;s raw input data, select their workflow of choice, and choose whether or not to share their result data. They would then be notified asynchronously via email once the processing of their experiment data has been completed.</p>
<h2>References</h2>
<p><a href="http://pubs.acs.org/doi/abs/10.1021/pr800970z&quot;http://pubs.acs.org/doi/abs/10.1021/pr800970z" target="_blank">Low Cost, Scalable Proteomics Data Analysis Using Amazon’s Cloud Computing Services and Open Source Search Algorithms</a></p>
<p><a href="http://www.cbcb.umd.edu/publications/files/ShortReadMappingPrimer-reprint.pdf" target="_blank">How to map billions of short reads onto genomes</a></p>
<p><a href="http://support.rightscale.com/12-Guides/RightGrid_User_Guide/01-RightGrid_Overview" target="_blank">The RightGrid batch-processing framework</a></p>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/uXlISgOGWYY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2010/12/14/genomic-processing-in-the-cloud/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SCA Async/Conversational services Part 2: Non-SCA Web Service client</title>
		<link>http://www.theserverlabs.com/blog/2010/11/19/sca-asyncconversational-services-part-2-non-sca-web-service-client/</link>
		<comments>http://www.theserverlabs.com/blog/2010/11/19/sca-asyncconversational-services-part-2-non-sca-web-service-client/#comments</comments>
		<pubDate>Fri, 19 Nov 2010 11:48:47 +0000</pubDate>
		<dc:creator>Jacobo Matute</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[JAX-WS]]></category>
		<category><![CDATA[JAXB]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[SCA]]></category>
		<category><![CDATA[Tuscany]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=1228</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/11/19/sca-asyncconversational-services-part-2-non-sca-web-service-client/";</script>Following my previous post on the internals of asynchronous and conversational services in Tuscany SCA, which options are available for consuming these services when you cannot use a Tuscany SCA runtime on the client?. Depending on the transport binding used you would expect to find a certain level of standarisation on conversational/asynchronous services implementation, allowing [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/11/19/sca-asyncconversational-services-part-2-non-sca-web-service-client/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><p>Following my <a href="http://www.theserverlabs.com/blog/2010/11/12/sca-asyncconversational-services-part-1-internals-of-tuscany-sca/">previous post</a> on the internals of asynchronous and conversational services in Tuscany SCA, which options are available for consuming these services when you cannot use a Tuscany SCA runtime on the client?.</p>
<p>Depending on the transport binding used you would expect to find a certain level of standarisation on conversational/asynchronous services implementation, allowing interoperable solutions. However, it is difficult, if not impossible, to find interoperable solutions for these types of services, even for highly standarised bindings such as SOAP Web Services. We have seen in the previous post how Tuscany SCA handles these services for WS and JMS bindings. We saw that at least for Web Services, some WS-* standards were used (i.e. WS-Addressing), but there are still solution-specific details that do not allow interoperability. This reflects how difficult it is for the standarisation community to define detailed standards and mechanisms to enable interoperable solutions for these kind of services.</p>
<p>In this post I present an option for this situation, using an standard JAX-WS client, attaching the appropriate WS-Addressing headers using JAXB. For that, I extend the pure Tuscany SCA client-server sample of the previous post with a non-SCA client. </p>
<p>You can find the extended source code of the maven projects <a href="http://www.theserverlabs.com/blog/wp-content/uploads/2010/11/scacounterservicesrc_extended.zip">here</a>.</p>
<h1>Overview</h1>
<p>The two main pieces to setup on a JAX-WS client are:</p>
<ol>
<li><strong>Proper WS-Addressing headers</strong> containing the Tuscany&#8217;s specific information (i.e callbackLocation, conversationID and optionally callbackID).</li>
<li><strong>A web service implementing the callback interface</strong>, listening in callbackLocation URI.</li>
</ol>
<h1>JAX-WS WS-Addressing headers setup</h1>
<p>As for a normal WSDL-first client development, the first step is to generate the JAX-WS client classes from the Counter Service WSDL. This is done using the maven <a href="https://jax-ws-commons.dev.java.net/jaxws-maven-plugin/">jaxws-maven-plugin</a> on the wsdl file generated for the service (i.e. http://localhost:8086/CounterServiceComponent?wsdl).</p>
<p>To setup the SOAP WS-Addressing headers, I follow the recommendations from the <a href="https://jax-ws.dev.java.net/guide/SOAP_headers.html#Adding_SOAP_headers_when_sending_requests">JAX-WS guide</a> and use <strong>WSBindingProvider</strong> interface, which offers a much better control on how headers can be added.</p>
<p>Therefore, in the constructor of <strong>CounterServiceClient.java</strong>, the WS-Addressing &#8220;<strong>TuscanyHeader</strong>&#8221; is added:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;">     <span style="color: #000000; font-weight: bold;">public</span> CounterServiceClient<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
        <span style="color: #666666; font-style: italic;">// Initialise JAX-WS Web Service Client.</span>
        service <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> CounterServiceService<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
        servicePort <span style="color: #339933;">=</span> service.<span style="color: #006633;">getCounterServicePort</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
        <span style="color: #666666; font-style: italic;">// Set the WS-Addressing headers to use by the client.</span>
        WSBindingProvider bp <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>WSBindingProvider<span style="color: #009900;">&#41;</span> servicePort;
        <span style="color: #666666; font-style: italic;">// Generate UUID for Tuscany headers</span>
        conversationId <span style="color: #339933;">=</span> UUID.<span style="color: #006633;">randomUUID</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
        callbackId <span style="color: #339933;">=</span> UUID.<span style="color: #006633;">randomUUID</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
        ReferenceParameters rp <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ReferenceParameters<span style="color: #009900;">&#40;</span>conversationId<span style="color: #009900;">&#41;</span>;
        rp.<span style="color: #006633;">setCallbackId</span><span style="color: #009900;">&#40;</span>callbackId<span style="color: #009900;">&#41;</span>;
        TuscanyHeader header <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TuscanyHeader<span style="color: #009900;">&#40;</span>CALLBACKURI, rp<span style="color: #009900;">&#41;</span>;        
        bp.<span style="color: #006633;">setOutboundHeaders</span><span style="color: #009900;">&#40;</span>Headers.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>JAXBRIContext<span style="color: #009900;">&#41;</span> jaxbContext,
                header<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
        ...
    <span style="color: #009900;">&#125;</span></pre></div></div>

<p>The <strong>ReferenceParameters</strong> and <strong>TuscanyHeader</strong> classes are JAXB classes with the required information to map the TuscanyHeader Java object to the WS-Addressing XML header. For instance, the <strong>ReferenceParameters</strong> class, which includes the Tuscany SCA parameters, has the following JAXB definitions:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ReferenceParameters <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> TUSCANYSCA_NS <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;http://tuscany.apache.org/xmlns/sca/1.0&quot;</span>;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/** The conversation id. */</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> conversationId <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span>;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/** The callback id. */</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> callbackId <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">null</span>;
&nbsp;
    ...
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setCallbackId<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> callbackId<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">callbackId</span> <span style="color: #339933;">=</span> callbackId;
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setConversationId<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> conversationId<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">conversationId</span> <span style="color: #339933;">=</span> conversationId;
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @XmlElement<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;CallbackID&quot;</span>, namespace <span style="color: #339933;">=</span> TUSCANYSCA_NS, required <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getCallbackId<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> callbackId;
    <span style="color: #009900;">&#125;</span>
&nbsp;
    @XmlElement<span style="color: #009900;">&#40;</span>name <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;ConversationID&quot;</span>, namespace <span style="color: #339933;">=</span> TUSCANYSCA_NS, required <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getConversationId<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> conversationId;
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h1>JAX-WS callback service setup</h1>
<p>The callback service needs to be created on the client side. For that we define a simple web service (<strong>CounterServiceCallbackImpl.java</strong>) with the CounterServiceCallback as the contract.</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * The CounterServiceCallback implementation.
 * The Web service namespace must be the same as the one defined in the Server Side.
 */</span>
@WebService<span style="color: #009900;">&#40;</span>targetNamespace <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;http://server.demo.tuscany.sca.tsl.com/&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CounterServiceCallbackImpl <span style="color: #000000; font-weight: bold;">implements</span> CounterServiceCallback <span style="color: #009900;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> count;
&nbsp;
	@Override
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> receiveCount<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> count, <span style="color: #000066; font-weight: bold;">int</span> end<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;CounterServiceCallback --- Received Count: &quot;</span> <span style="color: #339933;">+</span> count <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; out of &quot;</span> <span style="color: #339933;">+</span> end<span style="color: #009900;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">count</span> <span style="color: #339933;">=</span> count;
	<span style="color: #009900;">&#125;</span>
        ...
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In this sample project, the web service is also started during the instantiation of the JAX-WS Client. We use the <a href="http://download.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/package-summary.html">embedded Sun httpserver</a> to publish the web service instead of relying in other web application servers as Jetty or Tomcat:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;">     <span style="color: #000000; font-weight: bold;">public</span> CounterServiceClient<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
        ...
&nbsp;
        <span style="color: #666666; font-style: italic;">// Setup Receiver Callback Web Service</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Starting Callback service in &quot;</span> <span style="color: #339933;">+</span> CALLBACKURI<span style="color: #009900;">&#41;</span>;
        callback <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> CounterServiceCallbackImpl<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
        callbackServiceEp <span style="color: #339933;">=</span> Endpoint.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span>callback<span style="color: #009900;">&#41;</span>;
        callbackServiceEp.<span style="color: #006633;">publish</span><span style="color: #009900;">&#40;</span>CALLBACKURI<span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span></pre></div></div>

<h1>Testing the client</h1>
<p>As in the previous post, in order to run the client tests you need to:</p>
<ul>
<li>Run the server side, executing the <strong>run-server.sh</strong> under the <strong>counter-callback-ws-service</strong> directory. The server component should start and wait for client requests.
</li>
<li>Go to the client project, <strong>counter-callback-ws-client-SCA</strong> and execute the tests with:

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">mvn clean test</pre></div></div>

<p>This runs both the SCA and non-SCA client tests.</li>
<li>In case you want to run two clients at the same time, you need to define two separate CallbackURIs. For that purpose the property <strong>sca.callbackuri</strong> has been defined to configure the URI to use. Therefore to run two clients in parallel execute

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">mvn  test -Dsca.callbackuri=&quot;http://localhost:1999/callback&quot; -Dtest=com.tsl.sca.tuscany.demo.client.WebServiceNonSCAClientTest 
and another client with 
mvn  test -Dsca.callbackuri=&quot;http://localhost:2999/callback&quot; -Dtest=com.tsl.sca.tuscany.demo.client.WebServiceNonSCAClientTest</pre></div></div>

<p>Once running you should see the different service calls and conversations IDs interleaved in the server side console:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">setCounterServiceCallback on thread Thread[Thread-2,5,main] 
ConversationID = 81e257cd-af3b-4ea6-ae69-4b8e0d9db8a9. Starting count 
Sleeping ...
setCounterServiceCallback on thread Thread[Thread-5,5,main]                 
ConversationID = 70e86dcf-436c-4df1-ab6b-165b3f9070a4. Starting count   
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
ConversationID = 81e257cd-af3b-4ea6-ae69-4b8e0d9db8a9. Stopping count
Sleeping ...
ConversationID = 70e86dcf-436c-4df1-ab6b-165b3f9070a4. Stopping count
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
ConversationID = 81e257cd-af3b-4ea6-ae69-4b8e0d9db8a9. Restarting count
Sleeping ...
ConversationID = 70e86dcf-436c-4df1-ab6b-165b3f9070a4. Restarting count
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Thread interrupted.
Thread interrupted.</pre></div></div>

</li>
</ul>
<h1>Conclusions</h1>
<p>I hope that these posts have shed some light on how SCA and conversational/async services are implemented taking Tuscany as SCA runtime reference. I also believe that it is important to know the available options for consuming a SCA service without an SCA runtime, and how we can do it in a simple manner. </p>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/0JmwRySU10A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2010/11/19/sca-asyncconversational-services-part-2-non-sca-web-service-client/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SCA Async/Conversational services Part 1: Internals of Tuscany SCA</title>
		<link>http://www.theserverlabs.com/blog/2010/11/12/sca-asyncconversational-services-part-1-internals-of-tuscany-sca/</link>
		<comments>http://www.theserverlabs.com/blog/2010/11/12/sca-asyncconversational-services-part-1-internals-of-tuscany-sca/#comments</comments>
		<pubDate>Fri, 12 Nov 2010 13:12:17 +0000</pubDate>
		<dc:creator>Jacobo Matute</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[JMS]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[SCA]]></category>
		<category><![CDATA[Tuscany]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=1166</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/11/12/sca-asyncconversational-services-part-1-internals-of-tuscany-sca/";</script>Sometime ago I wrote about developing applications with SCA on a JBI-based infrastructure, using simple SCA services for that. I&#8217;m coming back again with two separate SCA blog posts discussing the usage of more complex services, asynchronous and conversational services: In this post, I provide an example client-server project that implements a conversational and asynchronous [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/11/12/sca-asyncconversational-services-part-1-internals-of-tuscany-sca/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><p>
Sometime ago I wrote about <a href="http://www.theserverlabs.com/blog/2009/07/07/developing-apps-with-sca-and-jbi/">developing applications with SCA on a JBI-based infrastructure</a>, using simple SCA services for that. </p>
<p>I&#8217;m coming back again with two separate SCA blog posts discussing the usage of more complex services, asynchronous and conversational services:</p>
<ul>
<li>In this post, I provide <strong>an example client-server project that implements a conversational and asynchronous service</strong> in <a href="http://tuscany.apache.org/">Tuscany SCA</a>, <strong>digging into the internals of the implementation</strong> for handling these services </strong>using Web Services and JMS bindings. I found this information quite difficult to find.</li>
<li><a href="http://www.theserverlabs.com/blog/2010/11/19/sca-asyncconversational-services-part-2-non-sca-web-service-client/">The second post</a> looks into the situation where the usage of a Tuscany SCA runtime is not possible in the client side, but we still need a way to make use of these type of services from a more standard web service client. For the specific case of a web service binding, and knowing the internals of Tuscany I will use a <strong>standard jax-ws client to consume a Tuscany SCA conversational and asynchronous service</strong>. </li>
</ul>
<p>Both posts use a common example project, a Counter service that notifies to the client each time the count is updated (every second) via an asynchronous callback. The service is conversational and allows clients to stop the count and restart it through separate independent service calls. Also, multiple clients can be run in parallel, each one with its own counter service instance. <strong>Version 1.6 of Tuscany SCA</strong> is used in this sample.</p>
<p>The source code of the sample counter service for this post can be found <a href="http://www.theserverlabs.com/blog/wp-content/uploads/2010/11/scacounterservicesrc.zip">here</a>.</p>
<h1>SCA asynchronous and conversational service definition</h1>
<p>Let&#8217;s refresh how to define a service in Tuscany SCA that is both conversational and defines a callback interface for asynchronous calls to the client. Good references for this are the <a href="http://www.osoa.org/display/Main/Service+Component+Architecture+Specifications">SCA specifications</a>, the <a href="http://tuscany.apache.org/java-sca-documentation-menu.html">Tuscany SCA documentation</a> and the <a href="https://svn.apache.org/repos/asf/tuscany/sca-java-1.x/tags/1.6/samples/">sample projects</a> included in the distribution. However, while I could find several callback projects on the Tuscany SCA samples there are none that exercise conversations.</p>
<p>Below, you find the interface definition of the <a href="http://www.osoa.org/download/attachments/35/SCA_JavaAnnotationsAndAPIs_V100.pdf?version=1">SCA service in Java</a> for the CounterService (<strong>counter-callback-ws-service maven project</strong>).</p>
<p>I use the <strong>@Callback</strong> and <strong>@Conversational</strong> annotations to define our service. For the @Callback annotation we need also to define the callback interface class. Therefore, for our counter service we have two interfaces, one for the service which implementation is done in the server side, and another one for the callback which implementation is done in the client side.</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * The remote service that will be invoked by the client
 */</span>
@Remotable
@Callback<span style="color: #009900;">&#40;</span>CounterServiceCallback.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
@Conversational
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> CounterService <span style="color: #009900;">&#123;</span>
&nbsp;
    @OneWay
    <span style="color: #000066; font-weight: bold;">void</span> startCounting<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> maxcount<span style="color: #009900;">&#41;</span>;
&nbsp;
    @OneWay
    <span style="color: #000066; font-weight: bold;">void</span> stopCounting<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
    @OneWay
    <span style="color: #000066; font-weight: bold;">void</span> restartCounting<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;    
&nbsp;
    @OneWay
    <span style="color: #000066; font-weight: bold;">void</span> shutdownCounting<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;     
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The Callback interface is as simple as:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * The callback interface for {@link CounterService}.
 */</span>
@Remotable
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> CounterServiceCallback <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000066; font-weight: bold;">void</span> receiveCount<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> count, <span style="color: #000066; font-weight: bold;">int</span> end<span style="color: #009900;">&#41;</span>;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The server side implementation of the service looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * This class implements CounterService and uses a callback.
 */</span>
@Service<span style="color: #009900;">&#40;</span>CounterService.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
@Scope<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;CONVERSATION&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> CounterServiceImpl <span style="color: #000000; font-weight: bold;">implements</span> CounterService <span style="color: #009900;">&#123;</span>
	@ConversationID
	<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #003399;">String</span> conversationID;
&nbsp;
	<span style="color: #008000; font-style: italic; font-weight: bold;">/**
	 * The setter used by the runtime to set the callback reference
	 * 
	 * @param counterServiceCallback
	 */</span>
	@Callback
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setMyServiceCallback<span style="color: #009900;">&#40;</span>CounterServiceCallback counterServiceCallback<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;setCounterServiceCallback on thread &quot;</span>
				<span style="color: #339933;">+</span> <span style="color: #003399;">Thread</span>.<span style="color: #006633;">currentThread</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
		<span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">counterServiceCallback</span> <span style="color: #339933;">=</span> counterServiceCallback;
	<span style="color: #009900;">&#125;</span></pre></div></div>

<p>On the implementation, the <strong>@Service</strong> SCA annotation is used to identify the SCA service being implemented and the <strong>@Scope</strong> which specifies a visibility and lifecycle contract an implementation has with the SCA runtime. Possible values of @Scope are <strong>STATELESS</strong>, <strong>REQUEST</strong>, <strong>CONVERSATIONAL</strong> and <strong>COMPOSITE</strong>. For this specific service we need to use CONVERSATIONAL, instructing Tuscany that conversation state must be kept in order to correlate interactions between a client and the service. For a description of the rest of scopes, refer to the <a href="http://www.osoa.org/download/attachments/35/SCA_JavaAnnotationsAndAPIs_V100.pdf?version=1">SCA Java Annotations and API reference specification.</a></p>
<p>Last, we use the <strong>@Callback</strong> annotation to instruct Tuscany SCA where to inject the Callback reference to be used by the service.</p>
<p>The server side SCA composite is very similar than the Tuscany SCA official <strong>callback-ws-client</strong> and you can find it under the &#8220;<strong>src/main/resources/counterws.composite</strong>&#8220;. The binding used for the sample is a Web Service binding.</p>
<p><strong>Tuscany SCA Counter Service Client</strong></p>
<p>On the client side (<strong>counter-callback-ws-client-SCA maven project</strong>) we need to define a client interface that makes use of the counter service. To make it simple, the interface has a method that returns the reference to the Counter Service and an additional helper method to get the current count recorded in the client based on the service callbacks. As in the server side, we have to make sure to define the interface as <strong>@Conversational</strong> and the implementation with <strong>@Scope(&#8220;CONVERSATION&#8221;)</strong> so Tuscany populates the service call with conversation information.</p>
<p>Also, to simplify the sample code, the shared interfaces between client and server (i.e. CounterService and CounterServiceCallback) are included in both projects separately. Ideally, these interfaces would be on a separate interfaces library used by both projects.</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * The client component interface.
 */</span>
@Conversational
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> CounterServiceClient <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> CounterService getCounterService<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> getCount<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The client composite is as listed below. It defines the reference to the counter Service and the associated callback. The url defined in the callback is used by Tuscany SCA in the client side to start the listening callback web service:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;composite</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.osoa.org/xmlns/sca/1.0&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">targetNamespace</span>=<span style="color: #ff0000;">&quot;http://counterws&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;counterws-client&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;component</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;CounterServiceClient&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;implementation</span>.java <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.tsl.sca.tuscany.demo.client.SCA.CounterServiceClientImpl&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;reference</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;counterService&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
	        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;interface</span>.java <span style="color: #000066;">interface</span>=<span style="color: #ff0000;">&quot;com.tsl.sca.tuscany.demo.server.CounterService&quot;</span></span>
<span style="color: #009900;">	            <span style="color: #000066;">callbackInterface</span>=<span style="color: #ff0000;">&quot;com.tsl.sca.tuscany.demo.server.CounterServiceCallback&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;binding</span>.ws <span style="color: #000066;">uri</span>=<span style="color: #ff0000;">&quot;http://localhost:8086/CounterServiceComponent&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;callback<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;binding</span>.ws <span style="color: #000066;">uri</span>=<span style="color: #ff0000;">&quot;http://localhost:1999/callback&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/callback<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/reference<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/component<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/composite<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>For the testing, a unit test is setup (<strong>WebServiceSCAClientTest.java</strong>),  exercising the counter service, callbacks and conversations.</p>
<p><strong>Running the counter service sample project</strong></p>
<p>To run the counter service sample, extract the source code and:</p>
<ul>
<li>Run the server side, executing the <strong>run-server.sh</strong> script in the <strong>counter-callback-ws-service</strong> directory. The server component should start and wait for client requests.

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">...
Nov 8, 2010 4:11:23 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8086
Callback server started (press enter to shutdown)
Nov 8, 2010 4:11:23 PM org.apache.tuscany.sca.http.tomcat.TomcatServer addServletMapping
INFO: Added Servlet mapping: http://localhost:8086/CounterServiceComponent</pre></div></div>

</li>
<li>Go to the client project, <strong>counter-callback-ws-client-SCA</strong> and execute the tests with:

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">mvn clean test</pre></div></div>

</li>
<li>On the client side you should see how the client starts the counting service, receives the callbacks and how the counting is stopped and later restarted, continuing the count where it was left.

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">...
Nov 8, 2010 4:11:28 PM org.apache.tuscany.sca.http.tomcat.TomcatServer addServletMapping
INFO: Added Servlet mapping: http://localhost:1999/callback
Starting Count and waiting 5 seconds for counts...
CounterServiceCallback --- Received Count: 0 out of 30
CounterServiceCallback --- Received Count: 1 out of 30
CounterServiceCallback --- Received Count: 2 out of 30
CounterServiceCallback --- Received Count: 3 out of 30
CounterServiceCallback --- Received Count: 4 out of 30
Stopping Count and waiting 5 seconds for no counts...
Restarting Count and waiting 5 seconds for counts...
CounterServiceCallback --- Received Count: 5 out of 30
CounterServiceCallback --- Received Count: 6 out of 30
CounterServiceCallback --- Received Count: 7 out of 30
CounterServiceCallback --- Received Count: 8 out of 30
Stopping the Client Node
Nov 8, 2010 4:11:44 PM org.apache.tuscany.sca.node.impl.NodeImpl stop
...</pre></div></div>

</li>
<li>On the server side, you should see the client call and the associated conversationID.

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">...
INFO: Added Servlet mapping: http://jmatute-laptop:8086/CounterServiceComponent
setMyServiceCallback on thread Thread[Thread-2,5,main]
ConversationID = d8a05f47-064b-4832-9cca-7ad035bd36ee. Starting count
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
ConversationID = d8a05f47-064b-4832-9cca-7ad035bd36ee. Stopping count
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
ConversationID = d8a05f47-064b-4832-9cca-7ad035bd36ee. Restarting count
Sleeping ...
Sleeping ...
Sleeping ...
Sleeping ...
Thread interrupted.</pre></div></div>

</li>
</ul>
<p>Having reached this point, let&#8217;s look into how Tuscany SCA is handling the conversations and callbacks and how the required information is included in the underling transport bindings (WS or JMS).</p>
<h1>Internals of conversational and asynchronous services in Tuscany SCA</h1>
<p>Tuscany SCA conversational services (i.e. marked with <strong>@Conversational</strong>) make use of <strong>conversation IDs</strong> in order to keep track and correctly map multiple invocations associated with a certain conversation.  </p>
<p>SCA and Tuscany asynchronous services are similar to those defined, for instance, in BPEL where the forward and callback service calls are two complete separate service invocation calls. Therefore, Tuscany also requires additional information to know where the callback needs to be send and optionally provide a application correlation id for the callback call.</p>
<p>Summarising, the below table contains the information used by Tuscany SCA for conversation and callback services:</p>
<table border="1" cellspacing="0" cellpadding="10" align="center">
<tbody>
<tr>
<td width="159" valign="top"><strong>Tuscany information</strong></td>
<td width="359" valign="top"><strong>Description</strong></td>
</tr>
<tr>
<td width="159" valign="top"><span lang="EN-US"><strong>conversationID</strong></span></td>
<td width="359" valign="top"><span lang="EN-US">UUID identifying the current conversation. This is used by Tuscany SCA to associate accordingly the service instance associated to that conversation.</span></td>
</tr>
<tr>
<td width="159" valign="top"><span lang="EN-US"><strong>callbackLocation</strong></span></td>
<td width="259" valign="top"><span>The location of the callback service. This, depending on the binding used might be a URI for Web Service binding or a Queue name for JMS.</span></td>
</tr>
<tr>
<td width="159" valign="top"><span lang="EN-US"><strong>callbackID</strong></span></td>
<td width="259" valign="top"><span>Application-specified callback ID, that is used by the application to correlate callbacks with the related application state.<br />
</span></td>
</tr>
</tbody>
</table>
<p>The above information needs to be mapped to the specific binding and here is where <strong>no standarisation exists, making difficult to have interoperable solutions</strong>:</p>
<ul>
<li><strong>WebService Binding</strong> : for the Web Service binding, WS-Addressing headers are used in order to store the Tuscany SCA conversational/async required information. Below it is shown an example of a Tuscany Web Service conversational and asynchronous/bidrectional invocation:
<ul>
<li>The WS-Addressing <strong>Address</strong> contains the Callback URI to be used for the callback invocation. This is normally setup by the client to notify the server where to send the callbacks.</li>
<li>The WS-Addressing <strong>ReferenceParameters</strong> contains the other two information fields under specific Tuscany Namespace, the <strong>CallbackID</strong> and the <strong>ConversationID</strong>.
</ul>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">'1.0'</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">'UTF-8'</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;S:Envelope</span> <span style="color: #000066;">xmlns:S</span>=<span style="color: #ff0000;">&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;S:Header<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;From</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2005/08/addressing&quot;</span> <span style="color: #000066;">xmlns:ns2</span>=<span style="color: #ff0000;">&quot;http://tuscany.apache.org/xmlns/sca/1.0&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;Address<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>http://localhost:1999/callback<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/Address<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ReferenceParameters<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ns2:CallbackID<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>45a963da-2074-4bb2-b9ee-f721e2ec753b<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ns2:CallbackID<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ns2:ConversationID<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>309b8322-1dc2-4c51-a4db-73d65edae391<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ns2:ConversationID<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ReferenceParameters<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/From<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/S:Header<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;S:Body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ns2:startCounting</span> <span style="color: #000066;">xmlns:ns2</span>=<span style="color: #ff0000;">&quot;http://server.demo.tuscany.sca.tsl.com/&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;arg0<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>30<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/arg0<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/ns2:startCounting<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/S:Body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/S:Envelope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</li>
<li><strong>JMS Binding</strong> : For JMS, Tuscany SCA uses JMS Message properties to store the required information. A screenshot (see below) of ActiveMQ console shows an Tuscany SCA JMS Message for conversational and async/bidrectional service.
<ol>
<li><strong>CallbackID, scaConversationID and scaCallbackQueue, </strong> Tuscany SCA propietary JMS message properties to hold the information.</li>
</ol>
<p><div id="attachment_1185" class="wp-caption aligncenter" style="width: 579px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2010/11/tuscanyscajmsmessage.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2010/11/tuscanyscajmsmessage.jpg" alt="Tuscany SCA JMS Message" title="Tuscany SCA JMS Message" width="569" height="316" class="size-full wp-image-1185" /></a><p class="wp-caption-text">Tuscany SCA JMS Message</p></div>
</li>
</ul>
<h1>Conclusion</h1>
<p>In this first post I have presented a Tuscany SCA example that covers both conversational and asynchronous scenarios, not currently available in the official Tuscany SCA samples, and looked into the internals of Tuscany SCA used to handle these services. This provides the basis for the next post, where I will be using this information to extend the project code with a non-SCA JAXWS-based web service client as an approach to consume these services without a Tuscany SCA runtime.</p>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/VxZ4b4r67rM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2010/11/12/sca-asyncconversational-services-part-1-internals-of-tuscany-sca/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Persistence Strategies for Amazon EC2</title>
		<link>http://www.theserverlabs.com/blog/2010/07/08/ec2-persistence-strategies/</link>
		<comments>http://www.theserverlabs.com/blog/2010/07/08/ec2-persistence-strategies/#comments</comments>
		<pubDate>Thu, 08 Jul 2010 14:02:20 +0000</pubDate>
		<dc:creator>Gerardo Viedma</dc:creator>
				<category><![CDATA[Default]]></category>
		<category><![CDATA[Amazon]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Cloud Computing]]></category>
		<category><![CDATA[EC2]]></category>
		<category><![CDATA[persistence]]></category>
		<category><![CDATA[scalability]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=1086</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/07/08/ec2-persistence-strategies/";</script>At The Server Labs, we often run into a need that comes naturally with the on-demand nature of Cloud Computing. Namely, we’d like to keep our team’s AWS bill in check by ensuring that we can safely turn off our Amazon EC2 instances when not in use. In fact, we’d like to take this practice [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/07/08/ec2-persistence-strategies/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><p>At The Server Labs, we often run into a need that comes naturally with the on-demand nature of Cloud Computing. Namely, we’d like to keep our team’s AWS bill in check by ensuring that we can safely turn off our Amazon EC2 instances when not in use. In fact, we’d like to take this practice one step further and automate the times when an instance should be operational (e.g. only during business hours). Stopping an EC2 instance is easy enough, but how do we ensure that our data and configuration persist across server restarts? Fortunately, there are a number of possible approaches to solve the persistence problem, but each one brings its own pitfalls and tradeoffs. In this article, we analyze some of the major persistence strategies and discuss their strengths and weaknesses.</p>
<h2>A Review of EC2</h2>
<p>Since Amazon introduced their EBS-backed AMIs in late 2009 [<a href="http://aws.typepad.com/aws/2009/12/new-amazon-ec2-feature-boot-from-elastic-block-store.html" target="_blank">1</a>], there has been a great deal of confusion around how this AMI type impacts the EC2 lifecycle operations, particularly in the area of persistence. In this section, we’ll review the often-misunderstood differences between S3 and EBS-backed EC2 instances, which will be crucial as we prepare for our discussion of persistence strategies.</p>
<h2>Not All EC2 Instances are Created Equal</h2>
<p>An Amazon EC2 instance can be launched from one of two types of AMIs: the traditional S3-backed AMI and the new EBS-backed AMI [<a href="http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html" target="_blank">2</a>]. These two AMIs exhibit a number of differences, for example in their lifecycle [<a href="http://www.shlomoswidler.com/2009/07/ec2-instance-life-cycle.html" target="_blank">3</a>] and data persistence characteristics [<a href="http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?Concepts_BootFromEBS.html" target="_blank">4</a>]:</p>
<table border="1" cellspacing="0" cellpadding="10">
<tbody>
<tr>
<td width="159" valign="top"><strong>Characteristic</strong></td>
<td width="259" valign="top"><strong>Amazon EBS</strong></td>
<td width="281" valign="top"><strong>Instance (S3) Store</strong></td>
</tr>
<tr>
<td width="159" valign="top"><span lang="EN-US">Lifecycle</span></td>
<td width="259" valign="top"><span lang="EN-US">Supports stopping and restarting of instance by saving state to EBS.</span></td>
<td width="281" valign="top"><span lang="EN-US">Instance cannot be stopped; it is either running or terminated.</span></td>
</tr>
<tr>
<td width="159" valign="top"><span lang="EN-US">Data persistence</span></td>
<td width="259" valign="top"><span>Data persists in EBS on instance failure or restart. Data can also be configured to persist when instance is terminated, although it does not do so by default.</span></td>
<td width="281" valign="top"><span lang="EN-US">Instance storage does not persist on instance shutdown or failure. It is possible to attach non-root devices using EBS for data persistence as needed.</span></td>
</tr>
</tbody>
</table>
<p>As explained in the table above, EBS-backed EC2 instances introduce a new stopped state, unavailable for S3-backed instances.  It is important to note that while an instance is in a stopped state, it will not incur any EC2 running costs. You will, however, continue to be billed for the EBS storage associated with your instance. The other benefit over S3-backed instances is that a stopped instance can be started again while maintaining its internal state. The following diagrams summarize the lifecycles of both S3 and EBS-backed EC2 instances:</p>
<p><img class="aligncenter size-full wp-image-1091" title="s3-lifecycle" src="http://www.theserverlabs.com/blog/wp-content/uploads/2010/07/s3-lifecycle.png" alt="s3-lifecycle" width="410" height="320" /></p>
<p style="text-align: center; font-weight: bold">Lifecycle of an S3-backed EC2 Instance.</p>
<p><img class="aligncenter size-full wp-image-1092" title="ebs-lifecycle" src="http://www.theserverlabs.com/blog/wp-content/uploads/2010/07/ebs-lifecycle.png" alt="ebs-lifecycle" width="551" height="439" /></p>
<p style="text-align: center; font-weight: bold">Lifecycle of an EBS-backed EC2 Instance.</p>
<p>Note that while the instance ID of a restarted EBS-backed instance will remain the same, it will be dynamically assigned a new set of public and private IP and DNS addresses. If you would like assign a static IP address to your instance, you can still do so by using Amazon’s Elastic IP service [<a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1346" target="_blank">5</a>].</p>
<h2>Persistence Strategies</h2>
<p>With an understanding of the differences between S3 and EBS-backed instances, we are well equipped to discuss persistence strategies for each type of instance.</p>
<h3>Persistence Strategy 1: EBS-backed Instances</h3>
<p>First, we’ll start with the obvious choice: EBS-backed instances. When this type of instance is launched, Amazon automatically creates an Amazon EBS volume from the associated AMI snapshot, which then becomes the root device. Any changes to the local storage are then persisted in this EBS volume, and will survive instance failures and restarts. Note that by default, terminating an EBS-backed instance will also delete the EBS volume associated with it (and all its data), unless explicitly configured not to do so [<a href="http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/Using_ChangeRootDeviceVolumeToPersist.html" target="_blank">6</a>].</p>
<h3>Persistence Strategy 2: S3-backed Instances</h3>
<p>In spite of their ease of use, EBS-backed instances present a couple of drawbacks. First, not all software and architectures are supported out-of-the-box as EBS-backed AMIs, so the version of your favorite OS might not be available. Perhaps more importantly, the EBS volume is mounted as the root device, meaning that you will also be billed for storage of all static data such as operating systems files, etc., external to your application or configuration.</p>
<p>To circumvent these disadvantages, it is possible to use an S3-backed EC2 instance that gives you direct control over what files to persist. However, this flexibility comes at a price. Since S3-backed instances use local storage as their root device, you’ll have to manually attach and mount an EBS volume for persisting your data. Any data you write directly to your EBS mount will be automatically persisted. Other times, configuration files exist at standard locations outside of your EBS mount where you will still want to persist your changes. In such situations, you would typically create a symlink on the root device to point to your EBS mount.</p>
<p>For example, assuming you have mounted your EBS volume under <em>/ebs</em>, you would run the following shell commands to persist your apache2 configuration:</p>
<div class="wp_syntax">
<div class="code">
<pre class="bash bash" style="font-family:monospace;">
<span style="color: #336600;"># first backup original configuration
mv /etc/apache2/apache2.conf{,.orig}
# use your persisted configuration from EBS by creating a symlink
ln –s /ebs/etc/apache2/apache2.conf /etc/apache2/apache2.conf</span></pre>
</div>
</div>
<p>Once your S3-backed instance is terminated, any local instance storage (including symlinks) will be lost, but your original data and configuration will persist in your EBS volume. If you would then like to recover the state persisted in EBS upon launching a new instance, you will have to go through the process of recreating any symlinks and/or copying any pertinent configuration and data from your EBS mount to your local instance storage.</p>
<p>Synchronizing between the data persisted in EBS and that in the local instance storage can become complex and difficult to automate when launching new instances. In order to help with these tasks, there are a number of third-party management platforms that provide different levels of automation. These are covered in more detail in the next section.</p>
<h3>Persistence Strategy 3: Third-party Management Platforms</h3>
<p>In the early days of AWS, there were few and limited third-party platforms available for managing and monitoring your AWS infrastucture. Moreover, in order to manage and monitor your instances for you, these types of platforms necessarily need access to your EC2 instance keys and AWS credentials. Although a reasonable compromise for some, this requirement could pose an unacceptable security risk for others, who must guarantee the security and confidentiality of their data and internal AWS infrastructure.</p>
<p>Given these limitations, The Server Labs developed its own Cloud Management Framework in Ruby for managing EC2 instances, EBS volumes and internal SSH keys in a secure manner. Our framework automates routine tasks such as attaching and mounting EBS volumes when launching instances, as well providing hooks for the installation and configuration of software and services at startup based on the data persisted in EBS. It even goes one step further by mounting our EBS volumes using an encrypted file system to guarantee the confidentiality of our internal company data.</p>
<p>Today, companies need not necessarily develop their homegrown frameworks, and can increasingly rely on third-party platforms. An example of a powerful commercial platform for cloud management is Rightscale. For several of our projects, we rely on Rightscale to automatically attach EBS volumes when launching new EC2 instances. We also make extensive use of scripting to install and configure software onto our instances automatically at boot time using Rightscale’s Righscript technology [<a href="http://support.rightscale.com/12-Guides/01-RightScale_Dashboard_User_Guide/03-Design/02-RightScripts" target="_blank">7</a>]. These features make it easy to persist your application data and configuration in EBS, while automating the setup and configuration of new EC2 instances associated with one or more EBS volumes.</p>
<h2>Automating Your Instance Uptimes</h2>
<p>Now that we have discussed the major persistence strategies for Amazon EC2, we are in a good position to tackle our original use case. How can we schedule an instance in Amazon so that it is only operational during business hours? After all, we’d really like to avoid getting billed for instance uptime during times when it is not really needed.</p>
<p>To solve this problem, we’ll have to address two independent considerations. First, we’ll have to ensure that all of our instance state (including data and configuration) is stored persistently. Second, we’ll have to automate the starting and stopping of our instance, as well as restoring its state from persistent storage at boot time.</p>
<h3>Automation Strategy 1: EBS-backed Instances</h3>
<p>By using an EBS-backed instance, we ensure that all of its state is automatically persisted even if the instance is restarted (provided it is not terminated). Since the EBS volume is mounted as the root device, no further action is required to restore any data or configuration. Last, we’ll have to automate starting and stopping of the instance based on our operational times. For scheduling our instance uptimes, we can take advantage of the Linux cron service. For example, in order to schedule an instance to be operational during business hours (9am to 5pm, Monday-Friday), we could create the following two cron jobs:</p>
<div class="wp_syntax">
<div class="code">
<pre class="bash bash" style="font-family:monospace;">
<span style="color: #336600;">0 9 * * 1-5 /opt/aws/bin/ec2-start.sh i-10a64379
0 17 * * 1-/opt/aws/bin/ec2-stop.sh i-10a64379</span></pre>
</div>
</div>
<p>The first cron job will schedule the EBS-backed instance identified by instance ID <em>i-10a64379</em> to be started daily from Monday to Friday at 9am. Similarly, the second job schedules the same instance to be stopped at 5pm Monday through Friday. The cron service invokes the helper scripts <em>ec2-start.sh</em> and <em>ec2-stop.sh</em> to facilitate the configuration of the AWS command-line tools according to your particular environment. You could run this cron job from another instance in the cloud, or you could have a machine in your office launch it.</p>
<p>The following snippet provides sample contents for ec2-start.sh, which does the setup necessary to invoke the AWS <em>ec2-start-instances</em> command. Note that this script assumes that your EBS-backed instance was previously launched manually and you know its instance ID.</p>
<div class="wp_syntax">
<div class="code">
<pre class="bash bash" style="font-family:monospace;">
<span style="color: #336600;">#!/bin/bash
# Name: ec2-start.sh
# Description: this script starts the EBS-backed instance with the specified Instance ID
# by invoking the AWS ec2-start-instances command
# Arguments: the Instance ID for the EBS-backed instance that will be started.

export JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.20
export EC2_HOME=/opt/aws/ec2-api-tools-1.3
export EC2_PRIVATE_KEY=/opt/aws/keys/private-key.pem
export EC2_CERT=/opt/aws/keys/cert.pem
# uncomment the following line to use Europe as the default Zone
#export EC2_URL=https://ec2.eu-west-1.amazonaws.com
PATH=$PATH:${EC2_HOME}/bin
INSTANCE_ID=$1

echo "Starting EBS-backed instance with ID ${INSTANCE_ID}"</span><span style="color: #336600; font-weight: bold">
ec2-start-instances ${INSTANCE_ID}</span></pre>
</div>
</div>
<p>Similarly, ec2-stop.sh would stop your EBS-backed instance by invoking <em>ec2-stop-instances</em> followed by your instance ID. Note that the instance ID of EBS-backed instances will remain the same across restarts.</p>
<h3>Automation Strategy 2: S3-backed Instances</h3>
<p>Amazon instances backed by S3 present the additional complexity that the local storage is not persistent and will be lost upon terminating the instance. In order to persist application data and configuration changes independently of the lifecycle of our instance, we’ll have to rely on EBS. Additionally, we’ll have to carefully restore any persisted state upon launching a new EC2 instance.</p>
<p>The Server Labs Cloud Manager allows us to automate these tasks. Among other features, it automatically attaches and mounts a specified EBS volume when launching a new EC2 instance. It also provides hooks to invoke one or more startup scripts directly from EBS. These scripts are specific to the application, and can be used to restore instance state from EBS, including any appropriate application data and configuration.</p>
<p>If you must use S3-backed instances for your solution, you&#8217;ll either have to develop your own framework along the lines of The Server Labs Cloud Manager, or rely on third-party management platforms like Rightscale. Otherwise, EBS-backed instances provide the path of least resistance to persisting your instance data and configuration.</p>
<h3>Automation Strategy 3: Rightscale</h3>
<p>Rightscale provides a commercial platform with support for boot time scripts (via Righscripts) and automatic attachment of EBS volumes. In addition, Rightscale allows applications to define arrays of servers that grow and shrink based on a number of parameters. By using the server array schedule feature, you can define how an alert-based array resizes over the course of a week [<a href="http://support.rightscale.com/12-Guides/01-RightScale_Dashboard_User_Guide/01-Manage/02-Arrays/Create_an_Alert-based_Server_Array/Server_Array_Schedule" target="_blank">8</a>], and thus ensure a single running instance of your server during business hours. In addition, leveraging boot time scripts and the EBS volume management feature enables you to automate setup and configuration of new instances in the array, while persisting changes to your application data and configuration. Using these features, it is possible to build an automated solution for a server that operates during business hours, and that can be shutdown safely when not in use.</p>
<h2>Conclusion</h2>
<p>This article describes the major approaches to persisting state in Amazon EC2. Persisting state is crucial to building robust and highly-available architectures with the capacity to scale. Not only does it promote operational efficiency by only consuming resources when a need exists; it also protects your application state so that it if your instant fails or is accidentally terminated you can automatically launch a new one and continue where you left off. In fact, these same ideas can also enable your application to scale seamlessly by automatically provisioning new EC2 instances in response to a growth in demand.</p>
<h2>References</h2>
<p>[1] <a href="http://aws.typepad.com/aws/2009/12/new-amazon-ec2-feature-boot-from-elastic-block-store.html" target="_blank">New Amazon EC2 Feature: Boot from Elastic Block Store</a>. Original announcement from Amazon explaining the new EC2 boot from EBS feature. </p>
<p>[2] <a href="http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/ComponentsAMIs.html" target="_blank">Amazon Elastic Compute Cloud User Guide: AMI Basics</a>. Covers basic AMI concepts for S3 and EBS AMI types.</p>
<p>[3] <a href="http://www.shlomoswidler.com/2009/07/ec2-instance-life-cycle.html" target="_blank">The EC2 Instance Life Cycle:</a> excellent blog post describing major lifecycle differences between S3 and EBS-backed EC2 instances.</p>
<p>[4] <a href="http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/index.html?Concepts_BootFromEBS.html" target="_blank">Amazon Elastic Compute Cloud User Guide: AMIs Backed by Amazon EBS</a>. Learn about EBS-backed AMIs and how they work.</p>
<p>[5] <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1346" target="_blank">AWS Feature Guide: Amazon EC2 Elastic IP Addresses</a>. An introduction to Elastic IP Addresses for Amazon EC2.</p>
<p>[6] <a href="http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/Using_ChangeRootDeviceVolumeToPersist.html" target="_blank">Amazon Elastic Compute Cloud User Guide: Changing the Root Volume to Persist.</a> Learn how to configure your EBS-backed EC2 instance so that the associated EBS volume is not deleted upon termination.</p>
<p>[7] <a href="http://support.rightscale.com/12-Guides/01-RightScale_Dashboard_User_Guide/03-Design/02-RightScripts" target="_blank">RightScale User Guide: RightScripts</a>. Learn how to write your own RightScripts.</p>
<p>[8] <a href="http://support.rightscale.com/12-Guides/01-RightScale_Dashboard_User_Guide/01-Manage/02-Arrays/Create_an_Alert-based_Server_Array/Server_Array_Schedule" target="_blank">RightScale User Guide: Server Array Schedule</a>. Learn how to create an alert-based array to resize over the course of the week.</p>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/rDKpc6F_IA0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2010/07/08/ec2-persistence-strategies/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Dynamic LDAP-based authentication and authorization in Servicemix 3</title>
		<link>http://www.theserverlabs.com/blog/2010/06/25/dynamic-ldap-based-authentication-and-authorization-in-servicemix-3/</link>
		<comments>http://www.theserverlabs.com/blog/2010/06/25/dynamic-ldap-based-authentication-and-authorization-in-servicemix-3/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 12:07:54 +0000</pubDate>
		<dc:creator>Jacobo Matute</dc:creator>
				<category><![CDATA[SOA]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Add new tag]]></category>
		<category><![CDATA[Servicemix]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=1006</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/06/25/dynamic-ldap-based-authentication-and-authorization-in-servicemix-3/";</script>Recently, we have been working quite extensively with Apache Servicemix, a JBI-compliant ESB. One of areas we have been looking into is securing services in general and how to perform ldap-based authentication and authorization for those services in particular. A good starting point to understand Servicemix (SMX) security features can be found here. I will [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/06/25/dynamic-ldap-based-authentication-and-authorization-in-servicemix-3/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><p>Recently, we have been working quite extensively with <a href="http://servicemix.apache.org/home.html">Apache Servicemix</a>, a <a href="http://jcp.org/aboutJava/communityprocess/final/jsr208/index.html">JBI-compliant</a> ESB.<br />
One of areas we have been looking into is securing services in general and how to perform ldap-based authentication and authorization for those services in particular.</p>
<p>A good starting point to understand Servicemix (SMX) security features can be found <strong><a href="http://servicemix.apache.org/security.html">here</a></strong>. I will give a brief overview of the security features of JBI and SMX .</p>
<p>JBI does not very concisely define authentication and authorization mechanisms, but it does define the following:</p>
<ul>
<li>JBI relies on <a href="http://java.sun.com/javase/6/docs/technotes/guides/security/jaas/JAASRefGuide.html">JAAS</a> definitions for security features (i.e. security <a href="http://java.sun.com/javase/6/docs/technotes/guides/security/jaas/JAASRefGuide.html#Subject">Subject</a>).</li>
<li>The Binding Components (e.g. servicemix-cxfbc) are expected to transform protocol-specific (e.g. WS-Security) credentials into a normalized format, a security Subject, and inject them into the normalized message.</li>
<li>The ESB will then apply the authentication and authorization mechanism based on Subject information.</li>
</ul>
<p>In particular for SMX we have:</p>
<ul>
<li>For authentication it relies on JAAS, being able to use custom Login modules to integrate different technologies (e.g. LDAP) and implement specific authentication logic. The SMX configuration for JAAS is located under <strong>$SERVICEMIX_HOME/conf/login.properties</strong>.</li>
<ul>
<li>SMX comes by default with a file based authentication mechanism, which is not suitable for use in many environments since it <strong>requires an SMX restart</strong> after any change.</li>
</ul>
<li>For authorization, SMX does not use JAAS, due to the different nature of the items to be authorized (i.e. service endpoints instead of Java code). It defines an specific ACL <strong><a href="http://servicemix.apache.org/dist/servicemix-3.2.1/site/parent/core/servicemix-core/apidocs/org/apache/servicemix/jbi/security/acl/AuthorizationMap.html">AuthorizationMap</a></strong>, used by the NormalizedRouter (SecureBroker) to allow or deny the invocation. The configuration file for this is located in <strong>$SERVICEMIX_HOME/conf/security.xml</strong> </li>
<ul>
<li>Also in this case, SMX comes by default with a file based ACL definition, included in the security.xml file. Any change in the ACLs <strong>requires an SMX restart</strong>.</li>
</ul>
</ul>
<p>So the idea behind this post is to provide a dynamic authentication/authorization mechanism in SMX that does not require an ESB restart after changes whilst also making use of LDAP.</p>
<p>In this post I will go through a complete example that requires the following:</p>
<ol>
<li><a href="http://servicemix.apache.org/servicemix-332.html">Apache ServiceMix 3.3.2</a>.</li>
<li><a href="http://www.opends.org/promoted-builds/2.2.0/">OpenDS 2.2</a> as a test LDAP Server. However you can use any other LDAP server you prefer.</li>
<li>Maven 2.0.9 or higher to build the projects.</li>
</ol>
<p>The complete source code of this post can be found <a href="http://www.theserverlabs.com/blog/wp-content/uploads/2010/06/smx-ldapsample-src.zip">here</a>. It contains:</p>
<ol>
<li>A LDAP ldif file with the sample directory structure used.</li>
<li>As a test service, a secured version of the SMX&#8217;s cxf-wsdl-first, now called <strong>cxf-wsdl-first-secure</strong>.</li>
<li>A <strong>smx-ldap</strong> maven project with the classes we need to deploy in SMX in order to enable LDAP.</li>
<li>A <strong>smxConfig</strong> directory with the required SMX configuration.</li>
</ol>
<p>With that in mind, let&#8217;s go through the details:</p>
<h1>Install Servicemix and OpenDS</h1>
<p>You can skip the OpenDS section if you have your own LDAP server, just make sure the relevant LDAP configuration parameters are used in the coming sections.</p>
<ol>
<li>Download and install Servicemix. No additional modifications are required at this stage.</li>
<li>Download and install OpenDS. If you want to use the sample LDAP ldif file, setup the directory server with the following configuration:</li>
<ul>
<li>Select as &#8220;Directory Base DN&#8221;: <strong>dc=theserverlabs,dc=com</strong>. </li>
<li>Select import data from LDIF and choose the file included in the source package.</li>
<li>Complete installation.
        </ul>
</ol>
<p>The users and passwords defined in the sample ldif are:</p>
<ul>
<li>reader:reader</li>
<li>smx:smx</li>
<li>testuser:testuser</li>
</ul>
<h1>Create a test service that requires authentication</h1>
<p>To show the authentication and authorization of a service deployed in SMX I took the &#8220;cxf-wsdl-first&#8221; example that is included in the SMX distribution and enabled WS-Security authentication headers. The result project is included in the source files as &#8220;cxf-wsdl-first-secure&#8221;.</p>
<p>For that I just added the following interceptors configuration into the xbean.xml file of the CXFBC service unit &#8220;wsdl-first-cxfbc-secure-su&#8221;:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;cxfbc:consumer</span> <span style="color: #000066;">wsdl</span>=<span style="color: #ff0000;">&quot;classpath:person.wsdl&quot;</span></span>
<span style="color: #009900;">                        <span style="color: #000066;">targetService</span>=<span style="color: #ff0000;">&quot;person:PersonService&quot;</span></span>
<span style="color: #009900;">                        <span style="color: #000066;">targetInterface</span>=<span style="color: #ff0000;">&quot;person:Person&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
     <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;cxfbc:inInterceptors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
             <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.apache.cxf.interceptor.LoggingInInterceptor&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
             <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;ref</span> <span style="color: #000066;">bean</span>=<span style="color: #ff0000;">&quot;UserName_RequestIn&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/cxfbc:inInterceptors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/cxfbc:consumer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor&quot;</span>  <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;UserName_RequestIn&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
     <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;constructor-arg<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;map<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;entry</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;action&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;UsernameToken&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #808080; font-style: italic;">&lt;!--</span>
<span style="color: #808080; font-style: italic;">			No real implementation of PasswordCallbackClass is required, thus the</span>
<span style="color: #808080; font-style: italic;">	    	        dummy class. However it must be defined. This is due to the fact</span>
<span style="color: #808080; font-style: italic;">			that the SMX will take care of the authentication, not WSS4J.</span>
<span style="color: #808080; font-style: italic;">		--&gt;</span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;entry</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;passwordCallbackClass&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;com.tsl.jbi.smx.security.DummyCallbackHandler&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;entry</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;passwordType&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;PasswordText&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/map<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/constructor-arg<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>In this case as you see the required passwordCallbackClass just defines a DummyCallbackHandler (also included in the cxfbc su) that does nothing at all, delegating the whole authentication/authorization to SMX.<br />
This is the simplest case and obviously you could have a class that performs additional checks or needs to deal with keystore passwords in case encryption is used. I will not get into the details here about WSS4J as this can be a subject worth a whole entry by itself.</p>
<p>Also, for a very good background reading of WS-Security and SMX check this <a href="http://tmielke.blogspot.com/2009/05/understanding-authentication-and.html">blog post</a> by Torsten Mielke.</p>
<p>To install the example project into SMX, just build the maven project and copy the service assembly to the hotdeploy directory of SMX:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">cd</span> Source<span style="color: #000000; font-weight: bold;">/</span>cxf-wsdl-first-secure<span style="color: #000000; font-weight: bold;">/</span>
mvn clean <span style="color: #c20cb9; font-weight: bold;">install</span>
<span style="color: #c20cb9; font-weight: bold;">cp</span>  wsdl-first-cxf-secure-sa<span style="color: #000000; font-weight: bold;">/</span>target<span style="color: #000000; font-weight: bold;">/</span>wsdl-first-cxf-secure-sa-3.3.2.zip <span style="color: #007800;">$SERVICEMIX_HOME</span><span style="color: #000000; font-weight: bold;">/</span>hotdeploy</pre></div></div>

<p>An example soap request with the WS-Security headers would be:</p>

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;soapenv:Envelope</span> <span style="color: #000066;">xmlns:soapenv</span>=<span style="color: #ff0000;">&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;</span> <span style="color: #000066;">xmlns:typ</span>=<span style="color: #ff0000;">&quot;http://servicemix.apache.org/samples/wsdl-first/types&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;soapenv:Header<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;wsse:Security</span> <span style="color: #000066;">xmlns:wsse</span>=<span style="color: #ff0000;">&quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;wsse:UsernameToken</span> <span style="color: #000066;">wsu:Id</span>=<span style="color: #ff0000;">&quot;UsernameToken-9&quot;</span> <span style="color: #000066;">xmlns:wsu</span>=<span style="color: #ff0000;">&quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
                   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;wsse:Username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>testuser<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/wsse:Username<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
                   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;wsse:Password</span> <span style="color: #000066;">Type</span>=<span style="color: #ff0000;">&quot;http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>testuser<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/wsse:Password<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/wsse:UsernameToken<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
       <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/wsse:Security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/soapenv:Header<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;soapenv:Body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;typ:GetPerson<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;typ:personId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>world<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/typ:personId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/typ:GetPerson<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/soapenv:Body<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/soapenv:Envelope<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h1>Setup the required LDAP classes for JAAS and SMX AuthorizationMap</h1>
<p>The required JAAS LDAP Login Module and the SMX AuthorizationMap contains many LDAP connectivity logic that are common and can be found in several open-source implementations.<br />
I took as a reference the ActiveMQ classes and modify them to fit the SMX needs.  </p>
<p>You can find the two classes in the smx-ldap maven project:</p>
<ul>
<li><strong>LdapLoginModule</strong>: This class implements the JAAS <a href="http://java.sun.com/javase/6/docs/api/javax/security/auth/spi/LoginModule.html">LoginModule</a> interface and it is responsible to perform the authentication (login method) based on the passed credentials. It is also responsible to extract the user&#8217;s roles once it is authenticated and inject them into the Subject as additional principals. The provided class is basically the same implementation used for ActiveMQ, no changes are required.</li>
<li><strong>LdapAuthorizationMap</strong>: This class implements the <a href="http://servicemix.apache.org/dist/servicemix-3.2.1/site/parent/core/servicemix-core/apidocs/org/apache/servicemix/jbi/security/acl/AuthorizationMap.html">AuthorizationMap</a> interface offered by SMX. The interface has just one method:

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;">Set<span style="color: #339933;">&lt;</span>Principals<span style="color: #339933;">&gt;</span> getAcls<span style="color: #009900;">&#40;</span>endpoint, operation<span style="color: #009900;">&#41;</span></pre></div></div>

<p>The class simply provides a set of Principals allowed to invoke the passed endpoint and operation. Also in this case, I took as a baseline the LdapAuthorizationMap include in ActiveMQ. We need to adapt it as ActiveMQ maps work on queues and topics, not endpoints. </li>
</ul>
<p>Having reached this point I needed to define the level of granularity and also the format of the entries in LDAP defining the ACLs. I provide one implementation possibility here and it is definitely not perfect. Depending on your needs you can take this as a baseline an implement a more complex logic, add caching of endpoints ACLs, etc&#8230;</p>
<p>So this is the format I defined:</p>
<ul>
<li>Endpoint ACLs are located under &#8220;ou=endpoints,ou=smx&#8221; in the LDAP tree.
<li>The entries defining the ACLs will be &#8220;GroupOfUniqueNames&#8221;, having an entry per allowed group.</li>
<li>The &#8220;cn&#8221; of the ACLs has the form:

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;">cn<span style="color: #339933;">=&lt;</span>Namespace<span style="color: #339933;">&gt;:&lt;</span>ServiceName<span style="color: #339933;">&gt;:&lt;</span>Operation<span style="color: #339933;">&gt;</span></pre></div></div>

<p>In the defined schema you can also use wildcards on Service and Operation. Examples of ACLs definition for the cxf-wsdl-first-secure project would be:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;">cn<span style="color: #339933;">=</span>http<span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">//servicemix.apache.org/samples/wsdl-first:*:*   </span>
       Grant permissions to all services on that ns.    
&nbsp;
<span style="color: #006633;">cn</span><span style="color: #339933;">=</span>http<span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">//servicemix.apache.org/samples/wsdl-first:PersonService:*   </span>
       Grant permissions to all operations of PersonService.    
&nbsp;
<span style="color: #006633;">cn</span><span style="color: #339933;">=</span>http<span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">//servicemix.apache.org/samples/wsdl-first:*:GetPerson   </span>
       Grant permissions to GetPerson operations of all services in that ns.</pre></div></div>

<p>Another example in case you use dynamic SMX ftp endpoints would be:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;">cn<span style="color: #339933;">=</span>urn<span style="color: #339933;">:</span>servicemix<span style="color: #339933;">:</span>ftp<span style="color: #339933;">:*</span> 
       Grant permissions to all dynamic endpoints of the servicemix<span style="color: #339933;">-</span>ftp BC.</pre></div></div>

</li>
</ul>
<p>This logic is implemented in the LdapAuthorizationMap class.</p>
<p>Both ActiveMQ classes are highly configurable using properties as we will see how to setup their usage in SMX.</p>
<p>To install the classes, build the maven project and copy the jar file to the lib directory of SMX:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">cd</span> Source<span style="color: #000000; font-weight: bold;">/</span>smx-ldap<span style="color: #000000; font-weight: bold;">/</span>
mvn clean <span style="color: #c20cb9; font-weight: bold;">install</span>
<span style="color: #c20cb9; font-weight: bold;">cp</span>  <span style="color: #c20cb9; font-weight: bold;">cp</span> target<span style="color: #000000; font-weight: bold;">/</span>smx-ldap-<span style="color: #000000;">1.0</span>-SNAPSHOT.jar <span style="color: #007800;">$SERVICEMIX_HOME</span><span style="color: #000000; font-weight: bold;">/</span>lib
&nbsp;
<span style="color: #000000; font-weight: bold;">&lt;</span>Restart ServiceMix<span style="color: #000000; font-weight: bold;">&gt;</span></pre></div></div>

<h1>Configure SMX</h1>
<p>To make use of the LDAP authentication and authorization two SMX files need to be modified:</p>
<ul>
<li><strong>$SERVICEMIX_HOME/conf/login.properties</strong>: This is the JAAS authentication configuration and must define the LdapLoginModule. The parameters are for locally configured OpenDS LDAP, modify them with your configuration if required:

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">servicemix-domain <span style="color: #7a0874; font-weight: bold;">&#123;</span>
    com.tsl.jbi.smx.security.login.LDAPLoginModule REQUIRED
        <span style="color: #007800;">debug</span>=<span style="color: #c20cb9; font-weight: bold;">true</span>
        <span style="color: #007800;">initialContextFactory</span>=com.sun.jndi.ldap.LdapCtxFactory
        <span style="color: #007800;">connectionURL</span>=<span style="color: #ff0000;">&quot;ldap://localhost:389&quot;</span>
        <span style="color: #007800;">connectionUsername</span>=<span style="color: #ff0000;">&quot;cn=reader,ou=people,dc=theserverlabs,dc=com&quot;</span>
        <span style="color: #007800;">connectionPassword</span>=reader
        <span style="color: #007800;">connectionProtocol</span>=s
        <span style="color: #007800;">authentication</span>=simple
        <span style="color: #007800;">userBase</span>=<span style="color: #ff0000;">&quot;ou=people,dc=theserverlabs,dc=com&quot;</span>
        <span style="color: #007800;">userRoleName</span>=dummyUserRoleName
        <span style="color: #007800;">userSearchMatching</span>=<span style="color: #ff0000;">&quot;(uid={0})&quot;</span>
        <span style="color: #007800;">userSearchSubtree</span>=<span style="color: #c20cb9; font-weight: bold;">false</span>
        <span style="color: #007800;">roleBase</span>=<span style="color: #ff0000;">&quot;ou=groups,dc=theserverlabs,dc=com&quot;</span>
        <span style="color: #007800;">roleName</span>=cn
        <span style="color: #007800;">roleSearchMatching</span>=<span style="color: #ff0000;">&quot;(member={0})&quot;</span>
        <span style="color: #007800;">roleSearchSubtree</span>=<span style="color: #c20cb9; font-weight: bold;">true</span>
        ;
<span style="color: #7a0874; font-weight: bold;">&#125;</span>;</pre></div></div>

<p>You can see that there are two parameters, <strong>userSearchMatching</strong> and <strong>roleSearchMatching</strong> that allow us to define the user/roles search filter that fit our environment.
</li>
<li><strong>$SERVICEMIX_HOME/conf/security.xml</strong>. This file contains general SMX security configuration and here we will define the bean for the LdapAuthorizationMap:

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">  <span style="color: #808080; font-style: italic;">&lt;!-- Custom, LDAP based authorisation map --&gt;</span>
  <span style="color: #808080; font-style: italic;">&lt;!-- MessageFormat used as LDAP filter to search for Roles of an Specific Endpoint --&gt;</span>
  <span style="color: #808080; font-style: italic;">&lt;!-- {0} will be replaced by Endpoint Namespace, {1} by Endpoint Name and --&gt;</span>
  <span style="color: #808080; font-style: italic;">&lt;!-- {2} by Endpoint operation --&gt;</span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;roleFilterMessageFormat&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;java.text.MessageFormat&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
 <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;constructor-arg</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;(|(|(|(cn={0}:{1}:{2})(cn={0}:{1}:\*))(cn={0}:\*:{2}))(cn={0}:\*:\*))&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;LdapAuthorizationMap&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;com.tsl.jbi.smx.security.LDAPAuthorizationMap&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;initialContextFactory&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;com.sun.jndi.ldap.LdapCtxFactory&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;connectionURL&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ldap://localhost:389&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;connectionUsername&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;cn=reader,ou=people,dc=theserverlabs,dc=com&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;connectionPassword&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;reader&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;connectionProtocol&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;s&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;endpointSearchBase&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;ou=endpoints,ou=smx,dc=theserverlabs,dc=com&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;endpointRoleFilterFormat&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;roleFilterMessageFormat&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;roleAttribute&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;uniqueMember&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Also in this case, we have an <strong>endpointRoleFilterFormat</strong> that defines the ACL&#8217;s search filter. This can be modified to match whatever other LDAP directory setup you want to define for ACLs.
</li>
<li><strong>$SERVICEMIX_HOME/conf/servicemix.xml</strong>. We need to modify the authorizationMap used by the secured broker and point to the new ldap-based map.

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sm:broker<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sm:securedBroker</span> <span style="color: #000066;">authorizationMap</span>=<span style="color: #ff0000;">&quot;#LdapAuthorizationMap&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
       .....
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sm:broker<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

</ul>
<p><strong><br />
Restart ServiceMix to apply the changes and you are ready to go!</strong></p>
<h1>Test the service and play around</h1>
<p>You can test the configuration with SoapUI (example project included in sources) or make use of the client.html (thanks SMX guys for this!!!) included in the cxf-wsdl-first-secure project. </p>
<p>The simplest one is the client.html, just load it in your web browser and fire away.</p>
<div id="attachment_1023" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2010/06/client.jpg"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2010/06/client-300x151.jpg" alt="Test Web Service Client" title="Test Web Service Client" width="300" height="151" class="size-medium wp-image-1023" /></a><p class="wp-caption-text">Test Web Service Client</p></div>
<p>The test should run successfully and return the Person information. </p>
<p>Now, it&#8217;s time to start playing around with the LDAP and see dynamic authentication/authorization:</p>
<ul>
<li>For instance, you can change the ACL group in the endpoint LDAP to SMX-GROUP2 and see how you get a &#8220;Endpoint is not authorized for this user&#8221; exception. </li>
<li>Create a more fine grained endpoint ACL that only assigns SMX-GROUP1 to:

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #007800;">cn</span>=<span style="color: #ff0000;">&quot;http://servicemix.apache.org/samples/wsdl-first:PersonService:GetPerson&quot;</span></pre></div></div>

</li>
<li>Change the password used for authentication of testuser in the SOAP request to get an LDAP login error.</li>
</ul>
<h1>Conclusions</h1>
<p>Dynamic authentication/authorization configuration in an ESB with mechanisms like LDAP is mandatory in any real deployment scenario. </p>
<p>You have seen that adding LDAP-based authentication/authorization to SMX is not difficult but to have a robust model some implementation work is required. The implementation shown in this post can be taken as a good starting point but there are areas of improvement both in terms of performance (e.g. cache, etc&#8230;) and in the authorization model itself (e.g. precedence of ACLs, etc&#8230;).</p>
<p>Also, the SMX authentication/authorization mechanisms described are for version 3.x. They should be applicable also for SMX 4 with its new architecture based on OSGi, as the same type of NMR is sitting on top of the OSGi runtime. </p>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/3NqT5wj1Sd4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2010/06/25/dynamic-ldap-based-authentication-and-authorization-in-servicemix-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>HTML5 Websocket vs Flex Messaging</title>
		<link>http://www.theserverlabs.com/blog/2010/06/09/html5-websocket-vs-flex-messaging/</link>
		<comments>http://www.theserverlabs.com/blog/2010/06/09/html5-websocket-vs-flex-messaging/#comments</comments>
		<pubDate>Wed, 09 Jun 2010 10:51:11 +0000</pubDate>
		<dc:creator>Kevin McCormack</dc:creator>
				<category><![CDATA[Default]]></category>
		<category><![CDATA[activemq]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[JMS]]></category>
		<category><![CDATA[stomp]]></category>
		<category><![CDATA[websocket]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=995</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/06/09/html5-websocket-vs-flex-messaging/";</script>Nearly 18 months ago, I wrote an article on this blog which showed how to develop a simple flex web application using ActiveMQ as a JMS server. It has proved a popular article so there must be a fair amount of interest in this topic. With all the hype surrounding HTML5 at the moment, I [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/06/09/html5-websocket-vs-flex-messaging/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><p>Nearly 18 months ago, I wrote <a href="http://www.theserverlabs.com/blog/2009/01/22/flex-with-jms-using-blazeds-jetty-and-activemq/">an article on this blog</a> which showed how to develop a simple flex web application using ActiveMQ as a JMS server. It has proved a popular article so there must be a fair amount of interest in this topic. </p>
<p>With all the hype surrounding HTML5 at the moment, I figured I&#8217;d try to update the application for the HTML5 world, at the same time seeing how easy it would be to replace Adobe Flex. I&#8217;m sure you&#8217;re all familiar with the fact that Steve Jobs won&#8217;t let Flash (and therefore Flex) onto either the iPhone or iPad, so it&#8217;s worth investigating if the alternatives (in this case HTML5 websocket) are really up to scratch. </p>
<p>The example shown in the article uses HTML 5 websocket, Apache ActiveMQ, the Stomp messaging protocol and (indirectly) Jetty 7. It currently only runs in Google Chrome 5 since this is the only browser with support for websocket available as of May 2010. </p>
<h2>What is Websocket?</h2>
<p>In short, it&#8217;s a way of opening up a firewall-friendly bi-directional communications channel with a server. The channel stays open for a long period of time, allowing the server and client web browser to interchange messages without having to do polling which consumes bandwidth and a lot of server resources. </p>
<p><a href="http://www.kaazing.org/confluence/display/KAAZING/What+is+an+HTML+5+WebSocket">This article</a> describes websocket in much more depth. </p>
<p>Websocket forms part of the (still unapproved) HTML5 specification which all browsers will eventually have to implement. </p>
<h2>Updating the Trader app</h2>
<p>In order to get the best out of this section, it is probably best to have read the <a href="http://www.theserverlabs.com/blog/2009/01/22/flex-with-jms-using-blazeds-jetty-and-activemq/">original Flex-JMS article</a>. </p>
<p><a href='http://www.theserverlabs.com/blog/wp-content/uploads/2010/05/trader-app-websocket1.zip'>Here is the code for the updated trader app</a>. Instead of having a server webapp component with BlazeDS acting as a message proxy and the flex clients, we have a bunch of HTML/CSS/JS files (in the /html folder) and some code to put messages in the JMS queues published by Apache ActiveMQ (in the /server folder).</p>
<h3>Setting up Apache ActiveMQ</h3>
<p>Apache ActiveMQ now comes with support for Websocket (implemented behind the scenes with Jetty 7). We will use ActiveMQ both as our messaging server and web server in this example, though that is not perhaps the best production configuration. </p>
<p><a href="http://www.nighttale.net/activemq/activemq-54-stomp-over-web-sockets.html">This article</a> explains how to configure ActiveMQ and Websocket. I will repeat the key instructions here for the sake of simplicity: </p>
<ol>
<li>Download the latest snapshot of Apache ActiveMQ 5.4 from <a href="https://repository.apache.org/content/repositories/snapshots/org/apache/activemq/apache-activemq/5.4-SNAPSHOT/">here</a> and unzip it somewhere on your filesystem that we will call $ACTIVEMQ_HOME</li>
<li>Edit  $ACTIVEMQ_HOME/conf/activemq.xml and change the transportConnectors section so that it looks like the example below:

<div class="wp_syntax"><div class="code"><pre class="xml xml" style="font-family:monospace;">        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;transportConnectors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;transportConnector</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;openwire&quot;</span> <span style="color: #000066;">uri</span>=<span style="color: #ff0000;">&quot;tcp://0.0.0.0:61616&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;transportConnector</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;websocket&quot;</span> <span style="color: #000066;">uri</span>=<span style="color: #ff0000;">&quot;ws://0.0.0.0:61614&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;transportConnector</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;stomp&quot;</span> <span style="color: #000066;">uri</span>=<span style="color: #ff0000;">&quot;stomp://0.0.0.0:61612?transport.closeAsync=false&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span> 
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;transportConnector</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;stomp+nio&quot;</span> <span style="color: #000066;">uri</span>=<span style="color: #ff0000;">&quot;stomp+nio://0.0.0.0:61613?transport.closeAsync=false&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span> 
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/transportConnectors<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<li>Start ActiveMQ by running bin/activemq from the $ACTIVEMQ_HOME directory. Go to <a href="http://localhost:8161/admin/">http://localhost:8161/admin/</a> and log in with the username/password admin/admin to check that everything is working ok. </li>
</ol>
<h3>Configure an install the aplication</h3>
<p>Download <a href='http://www.theserverlabs.com/blog/wp-content/uploads/2010/05/trader-app-websocket1.zip'>the trader app code</a> and copy the /html folder to $ACTIVEMQ_HOME/webapps/demo, renaming it to /trader-app-websocket (i.e. the full path should be $ACTIVEMQ_HOME/webapps/demo/trader-app-websocket). </p>
<p>Edit stock-quote.js and note the following section:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">    var url = 'ws://localhost:61614/stomp';
    var login = 'guest';
    var passcode = 'guest';
    destination = '/topic/stockQuoteTopic';</pre></div></div>

<p>The url attribute referes to the URL of the ActiveMQ server. Due to a bug in Chrome running on Ubuntu 9.10, I had to put the IP address of my machine here but if you&#8217;re running on another linux flavour, OSX or windows, I would imagine that leaving it as localhost should be OK. The username and password are guest/guest which is standard for ActiveMQ.</p>
<p>Download the latest version of Google Chrome (I have 5.0.375.55 which was released a few days ago) and open the URL http://localhost:8161/demo/trader-app-websocket/. You should see a UI that is similar to the Flex app developed in the original article: </p>
<p><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2010/05/chrome-initial.png"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2010/05/chrome-initial.png" alt="chrome-initial" title="chrome-initial" width="551" height="607" class="aligncenter size-full wp-image-998" /></a></p>
<p>Open up a terminal window and go to the location to which you extracted the /server part of the code download. Run the following (assumes Maven installed);</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">mvn clean compile <span style="color: #7a0874; font-weight: bold;">exec</span>:java -Dexec.mainClass=<span style="color: #ff0000;">&quot;com.theserverlabs.flex.trader.JSONFeed&quot;</span></pre></div></div>

<p>You should see a whole bunch of stock quote information like that shown below scrolling in the terminal:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">&#123;</span><span style="color: #ff0000;">&quot;symbol&quot;</span>: <span style="color: #ff0000;">&quot;XOM&quot;</span>,
<span style="color: #ff0000;">&quot;name&quot;</span>: <span style="color: #ff0000;">&quot;Exxon Mobile Corp&quot;</span>,
<span style="color: #ff0000;">&quot;low&quot;</span>: <span style="color: #000000;">61.317410451219146</span>,
<span style="color: #ff0000;">&quot;high&quot;</span>: <span style="color: #000000;">61.56</span>,
<span style="color: #ff0000;">&quot;open&quot;</span>: <span style="color: #000000;">61.56</span>,
<span style="color: #ff0000;">&quot;last&quot;</span>: <span style="color: #000000;">61.317410451219146</span>,
<span style="color: #ff0000;">&quot;change&quot;</span>: <span style="color: #000000;">61.317410451219146</span><span style="color: #7a0874; font-weight: bold;">&#125;</span></pre></div></div>

<p>This Java program is the same as that used in the original post. It generates random stock price information for a variety of stocks and publishes it in the stockQuote topic in ActiveMQ. In this case, it generates JMS text messages which contain data formatted in the JSON format. </p>
<p>If you go back to the Chrome browser window, you should see the stock quotes update. If they don&#8217;t update, click on refresh: </p>
<p><a href="http://www.theserverlabs.com/blog/wp-content/uploads/2010/05/chrome-stocks.png"><img src="http://www.theserverlabs.com/blog/wp-content/uploads/2010/05/chrome-stocks.png" alt="chrome-stocks" title="chrome-stocks" width="551" height="607" class="aligncenter size-full wp-image-999" /></a></p>
<p>This is pretty much exactly the same as how the original Flex application worked. The UI colours etc. are slightly different and I&#8217;ve not implemented the functionality for subscribing/unsubscribing from a stock price &#8211; but that was just on time grounds, not because it is difficult. </p>
<h2>How does it work?</h2>
<p>When the browser opens the page, it executes the following code in stock-quote.js, which subscribes to the stock quote service:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">$(document).ready(function(){
&nbsp;
    var client, destination;
&nbsp;
    ... 
&nbsp;
    var url = 'ws://localhost:61614/stomp';
    var login = 'guest';
    var passcode = 'guest';
    destination = '/topic/stockQuoteTopic';
&nbsp;
    client = Stomp.client(url);
    client.connect(login, passcode, onconnect);
&nbsp;
});</pre></div></div>

<p>Here we use <a href="http://jmesnil.net/stomp-websocket/doc/">the library provided by Jeff Mesnil </a> which enables us to access ActiveMQ using the <a href="http://stomp.codehaus.org">Stomp protocol</a> instead of JMS. We use it here because it is simple and cross-platform. There is no way of directly subscribing from JavaScript to a JMS server via JMS because there is no client available. </p>
<p>In the same block of code, you can see the code that we execute when we receive a message:</p>

<div class="wp_syntax"><div class="code"><pre class="js" style="font-family:monospace;">&nbsp;
    var onconnect = function(frame) {
&nbsp;
      client.subscribe(destination, function(message) {
        var quote = JSON.parse(message.body);
        $('.' + quote.symbol).replaceWith(&quot;&lt;tr class=\&quot;&quot; + quote.symbol + &quot;\&quot;&gt;&quot; + 
            &quot;&lt;td&gt;&quot; + quote.symbol + &quot;&lt;/td&gt;&quot; +  
            &quot;&lt;td&gt;&quot; + quote.open.toFixed(2) + &quot;&lt;/td&gt;&quot; + 
            &quot;&lt;td&gt;&quot; + quote.last.toFixed(2) + &quot;&lt;/td&gt;&quot; + 
            &quot;&lt;td&gt;&quot; + quote.change.toFixed(2) + &quot;&lt;/td&gt;&quot; + 
            &quot;&lt;td&gt;&quot; + quote.high.toFixed(2) + &quot;&lt;/td&gt;&quot; + 
            &quot;&lt;td&gt;&quot; + quote.low.toFixed(2) + &quot;&lt;/td&gt;&quot; +  
            &quot;&lt;/tr&gt;&quot;);
      });
    };</pre></div></div>

<p>When we receive a message, we parse it using the JSON parser that is part of the JQuery library and then we find the HTML element with class attribute equal to the symbol (e.g. if the symbol is IBM, we look for the HTML element with class=&#8221;IBM&#8221;) and replace it&#8217;s contents with the HTML table row code generated in the method. Simple really. </p>
<p>The rest of the code is just HTML and CSS and is not really that interesting for this article. </p>
<h2>Conclusions</h2>
<p>It is pretty easy to develop an application that uses Websocket &#8211; you only have to look at how little real code there is in this example. I&#8217;d say it is as easy as developing the original Flex app so from a development point of view, there&#8217;s little to chose between these technologies.</p>
<p>Unfortunately the only browser that currently supports Websocket is Google Chrome (and the implementation is a bit buggy). Other browsers (especially Firefox and Safari) should have this functionality soon though. One of the arguments used in support of Flash/Flex has always been the large installed base. Given that the iPhone and iPad are not part of this installed base, it is questionable as to whether this can still be used as a justification for using Flash/Flex. Sure there aren&#8217;t that many browsers that support Websocket but in 6 months time they probably all will and you won&#8217;t need any proprietary plugin to access the apps build using them. I&#8217;d definitely recommend that people developing internal corporate apps who can force their end users to use a browser with Websocket support take a look at this technology. People developing publically accessible webapps are probably going to have to wait till it is more widely implemented in browsers and provide graceful fallback in the case in which it isn&#8217;t. </p>
<p>I should point out that I have an iPhone and use Ubuntu 9.10 64-bit at work and I hate not being able to see content on my iPhone because it has been implemented in Flash and my entire firefox browser often crashes completely due to the 64-bit linux Flash plugin. </p>
<p>I&#8217;ve gone from being a fan of Flash/Flex to not being so sure about it. It&#8217;s hard to escape the feeling that HTML5 will offer much of the functionality currently offered by Flash/Flex in a short period of time. I think the future of these technologies is going to depend on Adobe innovating and offering stuff that is not possible in HTML5, otherwise there is little reason to use it. </p>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/ycWtK67xrTA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2010/06/09/html5-websocket-vs-flex-messaging/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Human readable JVM GC timestamps</title>
		<link>http://www.theserverlabs.com/blog/2010/05/26/human-readable-jvm-gc-timestamps/</link>
		<comments>http://www.theserverlabs.com/blog/2010/05/26/human-readable-jvm-gc-timestamps/#comments</comments>
		<pubDate>Wed, 26 May 2010 16:28:26 +0000</pubDate>
		<dc:creator>Francisco González</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Performance & Tuning]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[GC]]></category>
		<category><![CDATA[log]]></category>

		<guid isPermaLink="false">http://www.theserverlabs.com/blog/?p=855</guid>
		<description><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/05/26/human-readable-jvm-gc-timestamps/";</script>When we are diagnosing problems in a Java (EE or otherwise) application, is often a good idea to check how garbage collection is performing. One of the basic and most unobtrusive actions is to enable garbage collection logging. As you may know, if we add the following arguments to the java start command&#8230; -Xloggc:&#60;file_name&#62; –XX:+PrintGCDetails [...]]]></description>
			<content:encoded><![CDATA[<script type="text/javascript">dzone_url = "http://www.theserverlabs.com/blog/2010/05/26/human-readable-jvm-gc-timestamps/";</script><script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script><p>When we are diagnosing problems in a Java (EE or otherwise) application, is often a good idea to check how garbage collection is performing. One of the basic and most unobtrusive actions is to enable garbage collection logging.</p>
<p>As you may know, if we add the following arguments to the java start command&#8230;</p>
<p><code>-Xloggc:&lt;file_name&gt; –XX:+PrintGCDetails -XX:+PrintGCDateStamps</code></p>
<p>&#8230; the JVM will start writing garbage collection messages to the file we set with the parameter -Xlogcc. The messages should be something like:</p>
<p><code><br />
<strong>2010-04-22T18:12:27.796+0200</strong>: 22.317: [GC 59030K-&gt;52906K(97244K), 0.0019061 secs]<br />
<strong>2010-04-22T18:12:27.828+0200</strong>: 22.348: [GC 59114K-&gt;52749K(97244K), 0.0021595 secs]<br />
<strong>2010-04-22T18:12:27.859+0200</strong>: 22.380: [GC 58957K-&gt;53335K(97244K), 0.0022615 secs]<br />
<strong>2010-04-22T18:12:27.890+0200</strong>: 22.409: [GC 59543K-&gt;53385K(97244K), 0.0024157 secs]<br />
</code></p>
<p>The bold part is simply the date and time when reported garbage collection event starts.</p>
<p>Unfortunately -XX:+PrintGCDateStamps is available only for Java 6 Update 4 and later JVMs. So, if we are unlucky and our application is running on older JVMs we are forced to use&#8230;</p>
<p><code>-Xloggc:&lt;file&gt; –XX:+PrintGCDetails</code></p>
<p>&#8230; and the messages will be like:</p>
<p><code><br />
<strong>22.317</strong>: [GC 59030K-&gt;52906K(97244K), 0.0019061 secs]<br />
<strong>22.348</strong>: [GC 59114K-&gt;52749K(97244K), 0.0021595 secs]<br />
<strong>22.380</strong>: [GC 58957K-&gt;53335K(97244K), 0.0022615 secs]<br />
<strong>22.409</strong>: [GC 59543K-&gt;53385K(97244K), 0.0024157 secs]<br />
</code></p>
<p>Now, the bold numbers (also present in previous format) are the seconds elapsed from JVM start time. </p>
<p>Mmm&#8230; way harder to correlate GC events with information from other log files in this case :/</p>
<p>Wouldn&#8217;t it be easier to process the gc log file and calculate date and time from seconds elapsed? It seems so, but seconds elapsed from&#8230; when? Or, putting it in other words, where do we extract the JVM startup date and time from?</p>
<p>In order to be as unobtrusive as possible, we should try to calculate the start date and time from the same GC log file. That brings us to the file attributes. We have different options:</p>
<table>
<thead>
<tr>
<td>
<strong>Unix</strong>
</td>
<td>
<strong>Windows</strong>
</td>
</thead>
<tbody>
<tr>
<td>
Access time
</td>
<td>
Access time
</td>
</tr>
<tr>
<td>
Change time
</td>
<td>
Creation time
</td>
</tr>
<tr>
<td>
Modify time
</td>
<td>
Modify time
</td>
</tr>
</tbody>
</table>
<p>We discard access time (for obvious reasons) and change time and creation time as they are not available in both platforms, so we are left with modification time, which represents the time when the file was last modified. </p>
<p>In Windows, modification time is maintained when the file is copied elsewhere, but <strong>in Unix we should use the -p flag to preserve timestamp attributes if we want to copy the GC log file prior to our processing</strong>.</p>
<p>The last modification time of the GC log file should match the last timestamp recorded for a GC event in the log file. Well&#8230; for the purists, it should match exactly the last elapsed time plus the execution time (both in bold) as each log line is written piece by piece as it executes.</p>
<p><code><br />
<strong>22.409</strong>: [GC 59543K-&gt;53385K(97244K), <strong>0.0024157</strong> secs]<br />
</code></p>
<p>In our approach, we discard the execution time as we don&#8217;t need accurate precision to have a rough idea of what time each garbage collection event occurred. Nevertheless, keep in mind that GC execution time could sometimes be as long as several seconds in large heaps.</p>
<p>When we experienced this situation in a client recently, we needed to quickly develop a simple and portable script, so we used Python for the task. You already knew we don&#8217;t do just Java, didn&#8217;t you? <img src='http://www.theserverlabs.com/blog/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>

<div class="wp_syntax"><div class="code"><pre class="python python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/env python</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">sys</span>, <span style="color: #dc143c;">os</span>, <span style="color: #dc143c;">datetime</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># true if string is a positive float</span>
<span style="color: #ff7700;font-weight:bold;">def</span> validSeconds<span style="color: black;">&#40;</span>str_sec<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">try</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> 0 <span style="color: #66cc66;">&lt;</span> <span style="color: #008000;">float</span><span style="color: black;">&#40;</span>str_sec<span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">except</span> <span style="color: #008000;">ValueError</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">False</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># show usage                </span>
<span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">len</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#41;</span> <span style="color: #66cc66;">&lt;</span> <span style="color: #ff4500;">2</span>:
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;Usage: %s &lt;gc.log&gt;&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>
    <span style="color: #dc143c;">sys</span>.<span style="color: black;">exit</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
&nbsp;
file_str = <span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>
lastmod_date = <span style="color: #dc143c;">datetime</span>.<span style="color: #dc143c;">datetime</span>.<span style="color: black;">fromtimestamp</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">getmtime</span><span style="color: black;">&#40;</span>file_str<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #008000;">file</span> = <span style="color: #008000;">open</span><span style="color: black;">&#40;</span>file_str, <span style="color: #483d8b;">'r'</span><span style="color: black;">&#41;</span>
lines = <span style="color: #008000;">file</span>.<span style="color: black;">readlines</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #008000;">file</span>.<span style="color: black;">close</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># get last elapsed time</span>
<span style="color: #ff7700;font-weight:bold;">for</span> line <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">reversed</span><span style="color: black;">&#40;</span>lines<span style="color: black;">&#41;</span>:
    parts = line.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">':'</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> validSeconds<span style="color: black;">&#40;</span>parts<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">break</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># calculate start time</span>
start_date = lastmod_date - <span style="color: #dc143c;">datetime</span>.<span style="color: black;">timedelta</span><span style="color: black;">&#40;</span>seconds=<span style="color: #008000;">float</span><span style="color: black;">&#40;</span>parts<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;"># print file prepending human readable time where appropiate  </span>
<span style="color: #ff7700;font-weight:bold;">for</span> line <span style="color: #ff7700;font-weight:bold;">in</span> lines:
    parts = line.<span style="color: black;">split</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">':'</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> validSeconds<span style="color: black;">&#40;</span>parts<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> line.<span style="color: black;">rstrip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">continue</span>
    line_date = start_date + <span style="color: #dc143c;">datetime</span>.<span style="color: black;">timedelta</span><span style="color: black;">&#40;</span>seconds=<span style="color: #008000;">float</span><span style="color: black;">&#40;</span>parts<span style="color: black;">&#91;</span>0<span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">&quot;%s: %s&quot;</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>line_date.<span style="color: black;">isoformat</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>, line.<span style="color: black;">rstrip</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The script output can be redirected to another file, where we&#8217;ll have<br />
<code><br />
<strong>2010-04-22T18:12:27.796375</strong>: 22.317: [GC 59030K-&gt;52906K(97244K), 0.0019061 secs]<br />
<strong>2010-04-22T18:12:27.828375</strong>: 22.348: [GC 59114K-&gt;52749K(97244K), 0.0021595 secs]<br />
<strong>2010-04-22T18:12:27.859375</strong>: 22.380: [GC 58957K-&gt;53335K(97244K), 0.0022615 secs]<br />
<strong>2010-04-22T18:12:27.890375</strong>: 22.409: [GC 59543K-&gt;53385K(97244K), 0.0024157 secs]<br />
</code></p>
<p>You may note the date format is not 100% the same as the one with -XX:+PrintGCDateStamps argument, but it should be enough to get an idea of when each GC event happened (Timezone management in Python is way out of the scope of this blog entry).</p>
<p>This has been my first blog entry for The Server Labs and I hope some of you find it useful. Of course, all comments, suggestions and feedback are very welcome.</p>
<img src="http://feeds.feedburner.com/~r/TheServerLabsBlog/~4/FoeWK42iLs8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.theserverlabs.com/blog/2010/05/26/human-readable-jvm-gc-timestamps/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

