<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Solution Hacker &#187; spring</title>
	<atom:link href="http://www.solutionhacker.com/tag/spring/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.solutionhacker.com</link>
	<description>This blog provides solutions for enterpreneurs!</description>
	<lastBuildDate>Wed, 04 Aug 2010 11:37:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Powerful combination: JMX + Annotation + AOP</title>
		<link>http://www.solutionhacker.com/implement-your-idea/scale-your-website/powerful-combination-jmx-spring-aop/</link>
		<comments>http://www.solutionhacker.com/implement-your-idea/scale-your-website/powerful-combination-jmx-spring-aop/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 06:30:03 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[2.4. Scale Your Site]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[aspectj]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[cross-cutting concern]]></category>
		<category><![CDATA[interceptor]]></category>
		<category><![CDATA[JMX]]></category>
		<category><![CDATA[management]]></category>
		<category><![CDATA[monitoring]]></category>
		<category><![CDATA[proxy-based]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.solutionhacker.com/?p=215</guid>
		<description><![CDATA[What is AOP? AOP is a way to modularize cross-cutting concerns. Ok, what does &#8220;modularize&#8221; really mean? Modularization is the encapsulation of a unit of functionality. It is exactly what &#8220;Class&#8221; is doing in OO world. How about &#8220;cross-cutting concerns&#8221;? Basically it means any functionalities that span multiple modules/ classes. They include Transaction Management, Security, [...]]]></description>
			<content:encoded><![CDATA[<h2>What is AOP?</h2>
<p>AOP is a way to <strong>modularize</strong> cross-cutting concerns. Ok, what does &#8220;modularize&#8221; really mean? Modularization is the encapsulation of a unit of functionality. It is exactly what &#8220;Class&#8221; is doing in OO world. How about &#8220;cross-cutting concerns&#8221;? Basically it means any functionalities that span multiple modules/ classes. They include <strong>Transaction</strong> <strong>Management</strong>, <strong>Security</strong>, <strong>Caching</strong>, <strong>Performance Monitoring </strong>and etc. To understand how AOP works, we first look at the common terms in this area:</p>
<ol>
<li><strong>Join point</strong> &#8211; An identifiable point in the execution of a program like method invocation, exception thrown.</li>
<li><strong>Pointcut</strong> &#8211; Program construct that selects join points and collects context at those points. AspectJ has a rich pointcut expression language!</li>
<li><strong>Advice</strong> &#8211; Code to be executed at a join point that has been selected by a pointcut.</li>
</ol>
<p>To me, I found it easier to understand these terms if I consider<strong> join point</strong> as event generated point in code, <strong>pointcut </strong>as a way to define what events to be captured and <strong>advice </strong>as event handler.</p>
<p>AOP is indeed a powerful way to factor out system or infrasturcture-related code from the business oriented code. Typically, we use it to take care of transaction, security and profiling aspects. But it doesn&#8217;t stop you putting creativity in this domain. With a bit more creativity, you can also do the following::</p>
<ol>
<li><strong>Exception translation</strong> &#8211; checked to runtime</li>
<li><strong>Catch ConcurrencyFailureExceptions</strong> and transparently retry if an idempotent operation fails with, for example, a deadlock loser exception.</li>
</ol>
<p><span id="more-215"></span></p>
<h2>How I use Spring AOP in my project?</h2>
<p>I have been told to report the elapsed time for all calls to the database. If I don&#8217;t know how to use AOP, I may end up putting code to measure time for every JDBC calls. It ends up <strong>tangling</strong> performance monitoring code with my main line business logic and the same logic will be <strong>scattered everywhere</strong> in my data access code. Bad!! That is why we need to know how to factor out the performance monitoring code into an <strong>aspect </strong>like below:</p>
<p style="text-align: center;"><img alt="" style="width: 541px; height: 163px;" src="http://www.solutionhacker.com/wp-content/uploads/image/aspectCode1.JPG" /></p>
<p>Here we use <strong>AspectJ annotation approach</strong> to implement the aspect. &#8220;Around&#8221; is to intercept start and end of any repository method. Here is what states in Spring 2.5 reference:</p>
<blockquote>
<p>Spring 2.0 introduces a simpler and more powerful way of writing       custom aspects using either a <a title="6.3.&#160;Schema-based AOP support" href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-schema">schema-based       approach</a> or the <a title="6.2.&#160;@AspectJ support" href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-ataspectj">@AspectJ annotation       style</a>. Both of these styles offer fully typed advice and use of       the AspectJ pointcut language, while still using Spring AOP for       weaving.</p>
</blockquote>
<p>If you use <strong>AspectJ annotation</strong>, you need to put <strong>&lt;aop:aspectj-autoproxy/&gt;</strong> in your application-context.xml. The limitation of Spring proxy-based AOP is that it is limited to method invocation interception. To get around that, you can use AspectJ syntax in your pointcut expression. You don&#8217;t need to build the application with ajc (the AspectJ compiler) even you are using AspectJ syntax. Spring AOP can also understand @AspectJ aspects. I strong suggest you use Annotation driven AOP because it is cleaner and simplier. Working with AOP, I have faced 2 questions.</p>
<ol>
<li>How to select the methods that I want to intercept without hardcoding the method or package name in my pointcut expression. So, my aspect or pointcut doesn&#8217;t contain application specific information &#8211; Look into annotation and AOP section.</li>
<li>How to turn on and off AOP without restarting the web application? I would use <strong>JMX</strong>. Look into &#8220;What is JMX&#8221; section.&#160;</li>
</ol>
<h2>Annotation and AOP</h2>
<p><strong>Annotation </strong>provides a better way other than code signature for selecting join point that leads to creating loosely coupled aspect. In fact, you can see annotation as another signature of a method in other dimension. And a method can have multiple annotations and each concern just bother its own annotation. It is called <strong>multidimensional signature space</strong>. For example,</p>
<blockquote>
<p>@Authentication(&#8220;bankOperation&#8221;)<br />
@Transactional(REQUIRED)<br />
public void credit(){&#8230;}</p>
</blockquote>
<p><strong>Pointcut </strong>uses annotation to capture join points. For example:</p>
<blockquote>
<p>execution(@Transactional * *.*(..)) Execution of a method annotated as Transactional<br />
execution((@Trasactional *) *.*(..)) Execution of a method that returns object annotated as Transactional<br />
execution(* (@Transactional *).*(..)) Execution of a method defined for type annotated as Transactional</p>
</blockquote>
<p>Selection can use <strong>Annotation types</strong> and <strong>Annotation values</strong>.&#160; What is more, annotation values can be used in Advice implementation.</p>
<p>Here is a great <a href="http://www.parleys.com/display/PARLEYS/Home#talk=2097291;slide=1;title=Leveraging%20Annotations%20with%20AOP">video</a> from Parleys that talked about &#8220;Leveraging Annotation with AOP&#8221;. I have included some key points Ramnivas made here:</p>
<ul>
<li>Write you pointcut in a smart way to avoid annotation mess. Try to use naming and package convention to help you. For example, if you want to write app log for all public facing service method, you can use &#8220;public&#8221; with package name containing &#8220;service&#8221; wildcard to help you.</li>
<li>If you really need to use annotation like <strong>@Transaction</strong> that designer has no way to define the pointcut beforehand, use annotation to describe <strong>what the join point is</strong> but not how to handle it. So, your transaction aspect only need to worry annotation @Transaction and decouple from the application.</li>
<li>You can piggyback annotation. For example, you can make all entities auditable via <strong><span style="color: rgb(51, 153, 102);">declare @type: @Entity *: @Auditable;&#160;</span></strong></li>
</ul>
<h2><strong>How does Spring AOP work internally?</strong></h2>
<p>The magic behind AOP is the concept of Proxy/ Decorator/ Interceptor/ Filter pattern. To me, all those patterns are conceptually the same. They all try to present itself as target object (thru implementing the same interface), intercept method call and execute injected logics. And you can have more than one interceptors invoked in series. In Spring AOP, there is one thing we need to pay attention:</p>
<p>However, once the call has finally reached the target object, &#8230;any method calls that it may make on itself, such as 	<tt class="methodname">this.bar()</tt> or <tt class="methodname">this.foo()</tt>, are going to be 	invoked against the <span class="emphasis"><em><tt class="literal">this</tt></em></span> reference, and <span class="emphasis"><em>not</em></span> 	the proxy. This has important implications. It means that self-invocation is <span class="emphasis"><em>not</em></span> 	going to result in the advice associated with a method invocation getting a chance to execute. To handle this, either you refactor your code such that the self-invocation does not happen (best approach) or you make self invocation call thru proxy like&#160;<strong>((Pojo) AopContext.currentProxy()).bar()</strong> (invasive approach b/c it totally couples your code to Spring AOP, <span class="emphasis"><em>and</em></span> it makes the class     itself aware of the fact that it is being used in an AOP context, which flies in the face of AOP. Avoid using it).</p>
<p><em>However, it must be noted that AspectJ does not have this self-invocation issue because it is 	not a proxy-based AOP framework.</em></p>
<h2>What is JMX?</h2>
<p>In short, it is a way to enable management and monitoring of Java applications over a generic API. JMX has a simple architecture that contains <strong>instrumentation </strong>level, <strong>agent </strong>level and <strong>distribution service </strong>level. In instrumentation layer, we register MBean to the MBeanServer. In simple term, In simple term, <strong>MBean </strong>is a&#160; JavaBean with defined management interface that exposes attributes and operations to the world. <strong>MBeanServer </strong>acts as a <strong>broker </strong>to decouple communication among application MBeans and/or remote clients.</p>
<p><img alt="" style="width: 473px; height: 327px;" src="http://www.solutionhacker.com/wp-content/uploads/image/jmxaArchitecture2.JPG" /></p>
<h2>Combine AOP and JMX</h2>
<p>AOP is statically defined and intercept at the runtime. It is hard to take this out or add another aspect in after you start your machine. However, with JMX, you can enable and disable it via skipping the aspect code. <img src="../../../../../wp-includes/images/smilies/icon_cool.gif" alt=":cool:" onclick="grin(':cool:');" /> On the other hand, you can also use JMX to configure and report SLA metrics like configure thresholds and send notifications of violations. That sounds very interesting to me. There are other interesting usages mentioned in the Parley&#8217;s video as well:</p>
<ol>
<li><strong>Service blocking</strong> &#8211; throw an exception if particular service you don&#8217;t want to user to use it for a period of time esp during maintenance time.</li>
<li><strong>Caching management</strong> &#8211; I am currently using interceptor pattern and IoC to intercept dao method calls for cache lookup.&#160;</li>
</ol>
<h2>Reference</h2>
<ol>
<li><a href="http://developers.sun.com/learning/javaoneonline/2007/pdf/TS-1106.pdf">JavaOne 07 &#8211; JMX, AOP and Spring (Nice Presentation)</a></li>
<li><a href="http://www.parleys.com/display/PARLEYS/Home#talk=2097315;slide=3;title=Spring%20AOP%20and%20JMX">Parley&#8217;s AOP and JMX (Video)</a></li>
<li><a href="http://www.infoq.com/articles/Simplifying-Enterprise-Apps">Simplifying Enterprise Applications with Spring 2.0 and AspectJ</a></li>
<li><a href="http://www.infoq.com/articles/Orchestration-Oleg-Zhurakousky">Workflow Orchestration Using AOP</a></li>
<li><a href="http://www.ibm.com/developerworks/java/library/j-aopwork10/index.html">Performance Monitoring with AOP and JMX</a></li>
</ol>
<p>&#160;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.solutionhacker.com/implement-your-idea/scale-your-website/powerful-combination-jmx-spring-aop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Speed up your website via caching</title>
		<link>http://www.solutionhacker.com/uncategorized/webcaching/</link>
		<comments>http://www.solutionhacker.com/uncategorized/webcaching/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 19:31:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[6. Uncategorized]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[cdn]]></category>
		<category><![CDATA[coral]]></category>
		<category><![CDATA[jcs]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[squid]]></category>

		<guid isPermaLink="false">http://www.solutionhacker.com/?p=207</guid>
		<description><![CDATA[Introduction Caching is a crucial performance tuning strategy, especially your system has high read to write ratio. You can perform caching strategy at different levels from client browser cache all the way to disk cache at server side. Lets take a brief look at where we can cache based on the invocation path for a [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Caching is a crucial performance tuning strategy, especially your system has high read to write ratio. You can perform caching strategy at different levels from <strong>client browser cache</strong> all the way to <strong>disk cache</strong> at server side. Lets take a brief look at where we can cache based on the invocation path for a request to be fulfilled:</p>
<ol>
<li>Client browser cache</li>
<li><strong>CDN network</strong>
<ul>
<li>A <strong>CDN </strong>is a network, like <strong>Akamai</strong>, where a web site such as JustProposed.com can offload high-bandwidth static files like photos and videos to another network, so that my web site doesn&#8217;t need to have such huge bandwidth to run. Since bandwidth is a major expense, especially as we grow or when we get <strong>slashdotted </strong>(in which case we run out of bandwidth), a CDN has looked interesting. However, Akamai is too expensive for us to use. So, we will go for the free network, <a href="http://www.coralcdn.org/">Coral CDN</a>.</li>
<li>Apart from the bandwidth, JustProposed.com has lots of non-USA users who sometimes find my site slow to use. So, CDN network gives us proximity advantages.</li>
<li>To use Coral CDN, you simply append <span style="color: rgb(255, 0, 0);">nydu.net:8080</span> to the end of the hostname in the URL of your expensive resources. For example, <strong>http://www.justproposed.com/raydoris/myphoto.jpg</strong> to <strong>http://www.justproposed.com.<span style="color: rgb(255, 0, 0);">nydu.net:8080</span>/raydoris/myphoto.jpg</strong></li>
<li>Coral looks great, the only problem I have with it is that it&#8217;s running on a high port, so that people behind proxy servers that don&#8217;t automatically support http over anything bug port 80 will have problems. To use Coral, follow this <a href="http://wiki.coralcdn.org/wiki.php?n=Main.Servers">instruction</a>.</li>
</ul>
</li>
<li><strong>Reverse proxy server</strong> and content accelerator &#8211; Squid<span style="display: none;" id="1232960301723S">&#160; </span>
<ul>
<li>&#160;Why not use Apache as reverse proxy instead of putting Squid in front of Apache? <a href="http://abdussamad.com/archives/121-Squid-reverse-proxy-Apache-on-centos-4.5.html">Here</a> are some of the benefits of this setup. The main reason is that Apache spawns out a new process per request that eats up lots of resources.</li>
<li>&#160;</li>
</ul>
</li>
</ol>
<p>&#160;<span style="display: none;" id="1232960273972S">&#160;</span><img src="http://www.redhat.com/docs/manuals/cms/rhea-dpg-cms-en-6.1/figs/ccm_hw_arch.png" style="width: 523px; height: 234px;" alt="" /></p>
<p>There are several things that you need to look at when you go for caching approach:</p>
<ol>
<li><strong>What to cache?</strong> The data used by most web applications varies in its           dynamicity, from completely static to always changing at every           request.  Everything that has some degree of stability can be           cached. However, I always pick the ones that are most frequently access and/or expensive to compute and retrieve to cache because of the limited resource (ie. memory).</li>
</ol>
<h2>Application level caching (for J2EE)</h2>
<p><u><strong>JCS &#8211; Java Caching System</strong></u></p>
<p><img style="width: 551px; height: 356px;" src="http://www.solutionhacker.com/wp-content/uploads/image/caching.JPG" alt="" /></p>
<ol>
<li><strong>Configuration</strong>
<ul>
<li>To understand the power of <a href="http://jakarta.apache.org/jcs/index.html">JCS</a>, the best way is to look at its configuration file. To find out what is each configurable parameter does, take a look at this <a href="http://www.informit.com/guides/content.aspx?g=java&amp;seqNum=438">article</a>.</li>
</ul>
</li>
<li><strong>Integrate with Spring</strong>
<ul>
<li>To use JCS with Spring, take a look at this <a href="http://gleichmann.wordpress.com/2008/04/29/pragmatic-caching-a-simple-cache-configuration-model-for-spring/">article</a>. It talks about how to create a wrapper or Interceptor for your DAO and inject it to your service for caching purpose. To implement cache as an aspect with full control of what and how to cache, it doesn&#8217;t use the declarative Spring module caching approach. Regular dependency injection can do the trick!</li>
</ul>
</li>
<li><strong>Distributed caching</strong>
<ul>
<li>JCS is a front-tier cache that can be configured to maintain         consistency across multiple servers by using a <strong>centralized         remote server</strong> <strong>(client-server)</strong> or by <strong>lateral distribution (peer-to-peer)</strong> <strong>of cache updates.</strong>&#160;</li>
</ul>
</li>
</ol>
<h2>Reference</h2>
<ol>
<li><a href="http://www.mysqlperformanceblog.com/2006/05/21/speedup-your-lamp-stack-with-lighttpd/">Speed up your LAMP stack with lighhttpd</a></li>
<li><a href="http://kevin.vanzonneveld.net/techblog/article/install_squid_apache_on_1_server/">Squid and Apache on the same server</a> &#8211; have squid listened on port 80 and apache listened on port 8080</li>
<li><a href="http://www.visolve.com/squid/squid24s1/contents.php">Squid configuration variable </a></li>
</ol>
<p>&#160;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.solutionhacker.com/uncategorized/webcaching/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wiring up Flex, Mate, BlazeDS, Spring, Hibernate and MySQL with Maven 2 &#8211; Part 1</title>
		<link>http://www.solutionhacker.com/uncategorized/wiring-up-flex-mate-blazeds-spring-hibernate-and-mysql-with-maven-2/</link>
		<comments>http://www.solutionhacker.com/uncategorized/wiring-up-flex-mate-blazeds-spring-hibernate-and-mysql-with-maven-2/#comments</comments>
		<pubDate>Thu, 25 Dec 2008 10:50:47 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[2.1. Develop Your Team]]></category>
		<category><![CDATA[2.2. Build Your Site]]></category>
		<category><![CDATA[5. Fun]]></category>
		<category><![CDATA[6. Uncategorized]]></category>
		<category><![CDATA[AMF]]></category>
		<category><![CDATA[application stack]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[build process]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[hibernate]]></category>
		<category><![CDATA[jetty plugin]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.solutionhacker.com/?p=199</guid>
		<description><![CDATA[Introduction This article is written on top of the great work that&#160;Sébastien Arbogast has done. He has written 3 articles that showed you how to wire up Flex, BlazeDS, Spring, Hibernate and MySQL with Maven as build process. I have included his articles below as your reference. The Flex, Spring, and BlazeDS full stack – [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>This article is written on top of the great work that&#160;<strong>Sébastien Arbogast </strong>has done. He has written 3 articles that showed you how to wire up Flex, BlazeDS, Spring, Hibernate and MySQL with Maven as build process. I have included his articles below as your reference.</p>
<ol>
<li><a href="http://www.adobe.com/devnet/flex/articles/fullstack_pt1.html">The Flex, Spring, and BlazeDS full stack – Part 1: Creating a Flex module</a></li>
<li><a href="http://www.adobe.com/devnet/flex/articles/fullstack_pt2.html">The Flex, Spring and BlazeDS full stack – Part 2: Writing the to-do list server</a></li>
<li><a href="http://www.adobe.com/devnet/flex/articles/fullstack_pt3.html">The Flex, Spring and BlazeDS full stack – Part 3: Putting the application together</a></li>
</ol>
<p>I have found Sebastien&#8217;s work as a good foundation for my own project. To contribute back to the community, I will write a series of articles to show you how can customize and extend the todolist sample.</p>
<p><u>What is in the Part 1 of the series&#8230;</u></p>
<ol>
<li>Enhancements on the <strong>Maven </strong>build process
<ul>
<li>Leverage <strong>RSL </strong>to factor our the framework swc, so the size of the application swf will be reduced. Apart from that, I also take advantage of <strong>Flash Player Cache</strong> that is available after version 9 update 3 to cache the framework libraries.</li>
<li>Clean up the Flex and <strong>BlazeDS </strong>dependencies in POM as the latest version of the sdk is available and the BlazeDS dependencies are officially available.</li>
<li>Include some common reports for maven site generation</li>
<li>Embed <strong>Jetty</strong> web server in the build process for quick deployment and testing</li>
</ul>
</li>
<li>Document how to get the sample up on <strong>Eclipse </strong>for development<strong><br />
    </strong></li>
<li>Use <strong>Mate </strong>as Flex framework
<ul>
<li>Restructure ToDoList sample to leverage Mate framework</li>
<li>Factor out Mate as RSL and integrate it with Maven build process via Flex-mojo plugin.</li>
</ul>
</li>
</ol>
<p><u>What are in the coming articles&#8230;</u></p>
<ol>
<li>In part 2 of this series, I will show you how to use flex-mojo to build a modular Flex application.</li>
<li>In part 3 of this series, I will show you how to test your flex app via FlexUnit (Unit test) and FlexMonkey (Functional test)</li>
<li>In part 4 or this series, I will work on server side. I am planning to add monitoring, caching and security to the server side.</li>
</ol>
<p><span id="more-199"></span><!--more--></p>
<h2><!--more-->Review &#8220;ToDoList&#8221; sample</h2>
<p>Before I start my journey, let me highlight what Sebastien has done first:</p>
<ol>
<li>Sebastien&#8217;s sample demonstrates how to use Maven as a build process. There are 3 parts or subprojects in his sample. They are:
<ul>
<li><strong>todolist-config</strong> (configuration files shared by other subprojects)</li>
<li><strong>todolist-ria </strong>(Flex frontend)</li>
<li><strong>todolist-web</strong> (Server side that supports the Frontend)</li>
</ul>
</li>
<li>All these subprojects are considered as <strong>modules </strong>of the main project (root POM). Finally, they are combined together into war artifact and ready to deploy to Tomcat or other J2EE webapp server.</li>
<li>Flex frontend and backend communicate through a binary RPC protocol &#8211; <strong>AMF</strong>. AMF is considered to be the simplest and fastest remoting approach available in Flex. Recently, Adobe has released BlazeDS as an open source implementation of AMF spec. In this sample, <strong>BlazeDS </strong>is used. To use BlazeDS, there are few things you need to do:
<ul>
<li>Externalize your POJO service via BlazeDS. This sample shows you how to integrate BlazeDS with Spring</li>
<li>Make BlazeDS endpoints availabe to the Net via Servlet.</li>
<li>Have frontend and backend shared the same BlazeDS configuration files.</li>
</ul>
</li>
<li>In this sample, you can also find out how to use <strong>flex-mojo</strong> maven plugin to compile the Flex frontend code into swf. Apart from <a href="http://docs.flex-mojos.info/flex-compiler-mojo/compile-swf-mojo.html">flex-mojo plugin</a>, there are other two good plugins worth to mention:
<ul>
<li><strong>maven-assembly-plugin </strong>- can be used to bundle all the files under a directory into a zip file. It is used by todolist-config to bundle all the configuration files (<strong>service-config.xml </strong>and <strong>remoting-config.xml</strong>) into a zip during the <strong>package </strong>phase.</li>
<li><strong>maven-dependency-plugin</strong><strong> &#8211; </strong>can be used to unpack the zip file and move to the place you want. It is used by todolist-web to unpack the config zip during the <strong>generate-resources</strong> phase.</li>
</ul>
</li>
</ol>
<h2>Enhancements on maven POM</h2>
<p>I have modified the sample&#8217;s maven pom as follows:</p>
<ul>
<li>Link to new repository &#8220;<strong>Sonatype Forge</strong>&#8221; in the root POM. So, I can use the new version of flex-mojo and simplify the todolist-ria adobe framework dependencies. Apart from that, I also take away the private repository from Sebastein because BlazeDS libraries are available in official maven repository (Note: The BlazeDS libraries available in official maven repo are in version 3.0 instead of 3.0.0.544. So, you need to modify the webapp pom correspondingly).</li>
</ul>
<blockquote>
<p>&#160;&#160;&#160; &lt;repositories&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;repository&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;id&gt;flex-mojos-repository&lt;/id&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;url&gt;http://svn.sonatype.org/flexmojos/repository/&lt;/url&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;releases&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;enabled&gt;true&lt;/enabled&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/releases&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;snapshots&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;enabled&gt;false&lt;/enabled&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/snapshots&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/repository&gt;<br />
&#160;&#160;&#160; &lt;/repositories&gt;</p>
<p>&#160;&#160;&#160; &lt;pluginRepositories&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;pluginRepository&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;id&gt;flex-mojos-repository&lt;/id&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;url&gt;http://svn.sonatype.org/flexmojos/repository/&lt;/url&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;releases&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;enabled&gt;true&lt;/enabled&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/releases&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;snapshots&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;enabled&gt;false&lt;/enabled&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/snapshots&gt;<br />
&#160;&#160;&#160;&#160;&#160;&#160;&#160; &lt;/pluginRepository&gt;<br />
&#160;&#160;&#160; &lt;/pluginRepositories&gt;</p>
</blockquote>
<ul>
<li>Because I link to Sonatype repository, I can have my todolist-ria depends on one flex-framework pom dependency instead of all the swc dependencies. Note that the pom dependency is a way to factor out all the adobe swc dependencies that makes your pom easier to maintain.</li>
</ul>
<blockquote>
<p>&#160;&#160;&#160; &#160;&#160;&#160; &lt;dependency&gt;<br />
&#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &lt;groupId&gt;com.adobe.flex.framework&lt;/groupId&gt;<br />
&#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &lt;artifactId&gt;flex-framework&lt;/artifactId&gt;<br />
&#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &lt;version&gt;3.1.0.2710&lt;/version&gt;<br />
&#160;&#160;&#160; &#160;&#160;&#160; &#160;&#160;&#160; &lt;type&gt;pom&lt;/type&gt;<br />
&#160;&#160;&#160; &#160;&#160;&#160; &lt;/dependency&gt;</p>
</blockquote>
<ul>
<li>I include mysql driver as dependency in my webapp pom. I think it is cleaner to bundle it in war. I have also added <strong>jetty plugin</strong> in the POM so you have a web server embedded in the build process. With this, you can run this sample application right after you check it out from svn (assume you have maven 2 installed). To start jetty, you can issue the following maven command under your webapp project.</li>
</ul>
<blockquote>
<p>project_root&gt; mvn clean install<br />
project_root/jp-web&gt; mvn jetty:run-war</p>
</blockquote>
<ul>
<li>I have included some reports that will be shown after site generation. You may not be able to do <strong>mvn site-deploy </strong>because it is linked to my web hosting site. However, you can modify it for your own sake.</li>
</ul>
<h2>Get the sample up on Eclipse</h2>
<p>To develop on Eclipse, you can follow the steps below:</p>
<ol>
<li>Create Eclipse project file via running the command below at the project root. This will create 2 eclipse projects. One for todolist-ria and one for the webapp. You noticed that I use the <strong>-Declipse.downloadSource=true</strong> to include the source files of my dependencies in my eclipse project. Therefore, I can get to the source code if needed.</li>
</ol>
<blockquote>
<p>mvn -Declipse.downloadSource=true eclipse:eclipse</p>
</blockquote>
<ol>
<li>Import the projects into Eclipse</li>
<li>Add new variable<strong> M2_REPO</strong> and set it equals to<strong> [home]/.m2/repository</strong></li>
<li>If you have installed <strong>Flex Builder plugin</strong> to your Eclipse, you can Add <strong>Flex Project Nature</strong> to the todolist-ria project.
<ul>
<li>Select Application Server Type: J2EE</li>
<li>Put check on &#8220;Use remote object access service&#8221; with LiveCycle Data Service selected.</li>
<li>Set up the path. I have my tomcat installed under C:\tools with default <strong>8080 </strong>as port. You should make the changes if you installed it differently.</li>
<li><img src="http://www.solutionhacker.com/wp-content/uploads/image/flexEclipse1.JPG" style="width: 531px; height: 284px;" alt="" /></li>
<li>Remove the generated <strong>main.mxml</strong> under the src folder.</li>
<li>Set <strong>index.mxml </strong>under src folder as default Flex application file to run.</li>
<li>Use <strong>Default Flex SDK </strong>in Flex Compiler Configuration instead of Server Flex SDK</li>
<li>Right click and select <strong>Recreate HTML Template</strong> if you see error.</li>
<li>After all these, you have configured your Flex application pointing to the webapp server and sharing the BlazeDS configuration files. You can verify in Flex Compiler Configuration&#8217;s Additional Compiler Parameters. See whether you see this: <strong>-services &#8220;C:\tools\tomcat-6.0.16\webapps\jp\WEB-INF\flex\services-config.xml&#8221; -locale en_US</strong></li>
<li>Move the war to your tomcat&#8217;s webapp folder and start it under remote debugging setting. If you are using window, set<strong> DEBUG_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=8787,suspend=n</strong> under your bin/catalina.bat.</li>
<li>Start your webapp via bin/startup.bat</li>
<li>Put breakpoint under <strong>TodoServiceImpl</strong> save method and start remote debugger on localhost:8787</li>
<li>Right click the<strong> index.mxml</strong> and Run As Flex Application.</li>
<li>Add a new entry and save it on the flex app. <img onclick="grin(':razz:');" alt=":razz:" src="../../../../../wp-includes/images/smilies/icon_razz.gif" /> You should see your remote debugger halt at the breakpoint for you to debug.</li>
<li>Now you can change your flex code and test it out without leaving your Eclipse. However, if you modify the service in webapp, you need to run &#8220;<strong>mvn clean install</strong>&#8221; and deploy the war to the tomcat before your flex code can call your server-side code via <strong>AMF</strong>.</li>
</ul>
</li>
</ol>
<h2>Use Mate as Framework</h2>
<p>If you are not familiar with Mate, click the image below that moves you to a nice presentation.</p>
<p>&#160;<a href="http://mate.asfusion.com/assets/content//presentations/360_max_presentation.pdf"><img src="http://www.solutionhacker.com/wp-content/uploads/image/mate1.JPG" style="width: 589px; height: 339px;" alt="" /></a></p>
<p><u>What did I do to restructure the todolist sample to make it Mate app?</u></p>
<ol>
<li>&#160;</li>
</ol>
<h2>Download</h2>
<p>I have made my work available at: <a href="http://www.solutionhacker.com/wp-content/uploads/todolist-jp-modified.zip">www.solutionhacker.com/wp-content/uploads/todolist-jp-modified.zip</a></p>
<h2>Reference</h2>
<p>Below are the references I used for the article:</p>
<ol>
<li><a href="http://docs.flex-mojos.info/flex-compiler-mojo/compile-swf-mojo.html">Flex mojo compiler user guide</a></li>
<li><a href="http://blog.flex-mojos.info/2008/06/04/scopes/">Flex mojo dependency scope rules</a></li>
<li><a href="http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:Flex_3_RSLs">Flex 3 feature introduction: Flex 3 RSL</a></li>
<li><a href="http://www.adobe.com/devnet/flex/articles/flash_player_cache.html">Improving Flex application performance using Flash Player Cache</a></li>
<li><a href="http://fna.googlecode.com/svn/trunk/fna/site/mvn_archetypes/index.html">FNA archetype projects&#160;</a></li>
</ol>
<p>&#160;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.solutionhacker.com/uncategorized/wiring-up-flex-mate-blazeds-spring-hibernate-and-mysql-with-maven-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Flex Remoting and Session Management</title>
		<link>http://www.solutionhacker.com/data-intelligence/data-visualization/flex-remoting-and-session-management/</link>
		<comments>http://www.solutionhacker.com/data-intelligence/data-visualization/flex-remoting-and-session-management/#comments</comments>
		<pubDate>Sun, 22 Jun 2008 10:10:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[2.1. Architect Corner]]></category>
		<category><![CDATA[4.2. Visualize Your Data]]></category>
		<category><![CDATA[BlazeDS]]></category>
		<category><![CDATA[flex]]></category>
		<category><![CDATA[session]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.solutionhacker.com/2008/06/22/flex-remoting-and-session-management/</guid>
		<description><![CDATA[Power of BlazeDS Recently, I found out that Adobe has released BlazeDS (subset of LiveCycleDS) that has 4 main advantages: AS3 to Java object communication (no XML passes back and forth is needed!) Boost up performance b/c AMF is a binary protocol Built-in proxy support that gets around the cross domain security issue from Flex [...]]]></description>
			<content:encoded><![CDATA[<h2>Power of BlazeDS</h2>
<p>Recently, I found out that Adobe has released BlazeDS (subset of LiveCycleDS) that has 4 main advantages:</p>
<ol>
<li>AS3 to Java object communication (no XML passes back and forth is needed!)</li>
<li>Boost up performance b/c AMF is a binary protocol</li>
<li>Built-in proxy support that gets around the cross domain security issue from Flex in ease.</li>
<li>Allow push messaging</li>
</ol>
<p>I have followed the guideline and set it up. Now my Flex application can call my Java object method without passing xml back and forth. It is awesome! During the setup process, you may experience your flex cannot find the destination set up in the server.</p>
<div class="content">
<blockquote>
<p>The error &ldquo;[MessagingError message=&rsquo;Destination &lsquo;SomeBean&rsquo; either does not exist or the destination has no channels defined (and the application does not define any default channels.)&rsquo;]&rdquo;.</p>
</blockquote>
</div>
<p>The trick here is to add a services argument to the mxmlc call, something of the form below should do the trick!&nbsp;</p>
<blockquote>
<p>-services &ldquo;[local path to your java project]/WEB-INF/flex/services-config.xml&rdquo;</p>
</blockquote>
<p>Now you may start enjoying how AS3 talks to your Java Object. However, if&nbsp; we bypass the Servlet layer in the code, how can we carry session across remote method calls? Great that I have found out how to handle it via this <a href="http://sujitreddyg.wordpress.com/2008/05/16/session-data-management-in-flex-remoting/">article</a>. In short, you can access Session from your Java object via:</p>
<blockquote>
<p>FlexContext.getFlexSession()</p>
</blockquote>
<p>Here is the quote I got from the <a href="http://livedocs.adobe.com/blazeds/1/blazeds_devguide/">BlazeDS developer guide</a>.</p>
<blockquote>
<p>The FlexContext class is useful for getting access to the session and the HTTP pieces of the session, such as the HTTP servlet request and response. This lets you access HTTP data when you use a Flex application in the context of a larger web application where other classes, such as JSPs or Struts actions, might have stored information.</p>
<p>The FlexSession class provides access to an ID and also provides <samp class="codeph">setAttribute</samp> and <samp class="codeph">getAttribute</samp> functionality. This is useful for storing data on the server that doesn&#8217;t have to go back to the client. However, FlexSession is not cluster-aware; if a client connects to a different server in the cluster, the client receives a new FlexSession. Nothing stored in the FlexSession attributes is persisted for clustering purposes. The FlexSessionListener class is useful for monitoring who is connected. You add a listener by using the static method to track new connections being made. You receive a reference to the session that was added. Each session can then report when it is destroyed to those same listeners. You use this for monitoring connections that close, and also to clean up resources.</p>
</blockquote>
<p>When I looked into the source of FlexContext, I noticed that it leverages <strong>ThreadLocal </strong>to store context info like request, response and session.</p>
<pre name="code" class="java">
    private static ThreadLocal sessions = new ThreadLocal();
    /**
     * The FlexSession for the current request.  Available for users.
     */
    public static FlexSession getFlexSession()
    {
        return (FlexSession)sessions.get();
    }
</pre>
<h2>Reference</h2>
<p>Below are some of the useful references I have read so far:</p>
<ol>
<li><a href="http://jim-boone.com/2008/04/10/ria-prototype-client-using-blazeds-messaging-and-jms-j2ee-server/#more-33">Jim Boone&#8217;s Blog</a></li>
</ol>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.solutionhacker.com/data-intelligence/data-visualization/flex-remoting-and-session-management/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Part 1 &#8211; Spring Security Architectural Review</title>
		<link>http://www.solutionhacker.com/uncategorized/part-1-spring-security-architectural-review/</link>
		<comments>http://www.solutionhacker.com/uncategorized/part-1-spring-security-architectural-review/#comments</comments>
		<pubDate>Tue, 27 May 2008 21:15:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[2.2. Build Your Site]]></category>
		<category><![CDATA[2.5. Protect Your Site]]></category>
		<category><![CDATA[6. Uncategorized]]></category>
		<category><![CDATA[acegi]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[aspect]]></category>
		<category><![CDATA[authentication]]></category>
		<category><![CDATA[authorization]]></category>
		<category><![CDATA[JXplorer]]></category>
		<category><![CDATA[LDAP]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.solutionhacker.com/?p=146</guid>
		<description><![CDATA[My Web application needs both authentication and role-based authorization features. And our user profile is currently stored in an OpenLDAP server. I am looking for a security framework that can help me to integrate LDAP and provide these security features with the least amount of effort. On top of that, I want to achieve this [...]]]></description>
			<content:encoded><![CDATA[<p><img width="216" height="120" align="left" alt="" src="http://www.solutionhacker.com/wp-content/uploads/securityLogo.gif" style="margin-right: 10px;" /></p>
<p>My Web application needs both authentication and role-based authorization features. And our user profile is currently stored in an OpenLDAP server. I am looking for a security framework that can help me to integrate LDAP and provide these security features with the least amount of effort. On top of that, I want to achieve this without polluting my business logic with security code (ie. via AOP). At my first glance, Spring security (aka. acegi security) looks promising to me. After evaluating it a bit more, I believe it does provide what I need for my project. So, I started creating a prototype and gave it a trial. In this article, I will go over the steps I took to build my prototype and I will provide you the necessary explanation to move forward alongside. Hopefully, you will get over the initial learning curve as quick as possible with this guide. <span id="more-146"></span></p>
<p><!--more--></p>
<h2>Spring Security Overview</h2>
<p><strong><u>Step 1. Specify the location of the configuration files for Spring and Log4J in web.xml<br />
</u></strong></p>
<p>The configuration below tells Spring and Log4J the location of the configuration files. These files will be parsed by the <strong>ContextLoaderListener </strong>(for Spring) and <strong>Log4JConfigListener </strong>(for log4j) during the initial loading process.</p>
<pre class="xml" name="code">
&lt;context-param&gt;
	&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
	&lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt;
&lt;/context-param&gt;

&lt;context-param&gt;
	&lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt;
	&lt;param-value&gt;/WEB-INF/classes/log4j.properties&lt;/param-value&gt;
&lt;/context-param&gt;
</pre>
<p><strong><u>Step 2. Define the Acegi Filter Chain Proxy Filter in web.xml<br />
</u></strong></p>
<p>Spring Security&#8217;s support for web security is heavily based on <strong>servlet filters</strong>. These filters intercept an incoming request and apply some security processing before the request is handled by your application. Spring security comes with a handful of filters that intercept servlet requests and pass them on to the authentication and access decision manager to enforce security. However if you ever used servlet filters, you know that for them to take effect, you must configure them in the web application&#8217;s web.xml file, using the &lt;filter&gt; and &lt;filter-mapping&gt; elements. While this works, it doesn&#8217;t lend itself to configuration using dependency injection. You have no control of the life-cycle of the filter (like instantiation), but you may be able to override the constructor and use <strong>WebApplicationContextUtil </strong>to load the bean your filter needs to act on. This is not ideal as you need to hardcode a reference to the name of the bean. That is why Filter Chain Proxy is created. The <strong>FilterToBeanProxy</strong> is a special servlet filter that, by itself, doesn&#8217;t do much. Instead, it delegate its work to a bean implements the Filter interface just like other servlet filter. In the configuration below, the target class is the filter class that I talk about. Using this approach, Spring security is able to <strong>plug in</strong> its security functionality in a modular way. NOTE: The mechanism is <strong>not </strong>Spring Security specific. You can use this approach if you have no control of the life-cycle of the class you are interested in.</p>
<pre class="xml" name="code">
   &lt;filter&gt;
        &lt;filter-name&gt;Acegi Filter Chain Proxy&lt;/filter-name&gt;
        &lt;filter-class&gt;net.sf.acegisecurity.util.FilterToBeanProxy&lt;/filter-class&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;targetClass&lt;/param-name&gt;
            &lt;param-value&gt;net.sf.acegisecurity.util.FilterChainProxy&lt;/param-value&gt;
        &lt;/init-param&gt;
   &lt;/filter&gt;</pre>
<p><strong><u>Step 3. Define the Filter chain in ApplicationContext.xml<br />
</u></strong></p>
<p>Now you have the proxy to redirect the request to your Spring bean. What is next? Spring Security requires at least 4 filters to be functioned. Does this mean that you have to configure a FilterToBeanProxy for each of the filters. No! To make life easier, Spring Security offers &quot;FilterChainProxy&quot; that can be configured to chain together several filters at once. The filters we need as part of the request processing are:</p>
<ol>
<li><u>HttpSessionContextIntegrationFilter</u>
<ul>
<li>Check to see if the user&#8217;s Authentication information is in <strong>Session</strong>. If so, it makes the authentication info available to the current request. At the end of the request, it will deposit the authentication info back into the session so that it will be available for the next request.</li>
<li>It prevents user from logging in again.</li>
</ul>
</li>
<li><u>AuthenticationProcessingFilter          </u>
<ul>
<li>Delegate to <strong>AuthenticationManager </strong>to do the actual authentication. <strong>AuthenticationManager</strong> determines who you are. Once you are identified, a list of <strong>roles </strong>that belongs to you will be populated. As with the rest of Spring Security, the authentication manager is a <strong>pluggable interface-based</strong> component. This makes it possible to use Spring Security with virtually any authentication mechanism.</li>
<li>Process authentication based on username and password given to it in <strong>j_username</strong> and <strong>j_password.</strong></li>
<li>&quot;<strong>filterProcessesUrl</strong>&quot; property tells which URL it should intercept. Default to<strong> /j_acegi_security_check.</strong></li>
<li>&quot;<strong>authenticationFailureUrl</strong>&quot; property indicates where the user will be sent should authentication fail.</li>
<li>When authentication is successful, <strong>Authentication </strong>object will be placed to the Session.</li>
</ul>
</li>
<li><u>ExceptionTranslationFilter</u>
<ul>
<li>Handle <strong>AuthenticationException </strong>via sending the user to the authentication entry point. It is configured in the &quot;authenticationEntryPoint&quot; property. There are different type of entry points: Basic, Form, Digest and X.509 cert.</li>
<li>Handle <strong>AccessDeniedException </strong>- Default to HTTP 403 error to the browser. You can configure AccessDeniedHandlerImpl to forward the user to nice-looking error page.</li>
<li>Without anything to handle Spring Security exceptions above, they would flow up to the servlet container and be displayed in the browser as stack trace.</li>
</ul>
</li>
<li><u>FilterSecurityInterceptor</u>
<ul>
<li>Enforce web security. If user has not been authenticated, throw an <strong>AuthenticationException </strong>which will be handled by exception translation filter. If user has no right to access the resource, it will throw an <strong>AccessDeniedException </strong>that will be handled by exception translation filter as well.</li>
<li>It is wired with authenticationManager and accessDecisionManager</li>
<li><strong>Access Decision Manager</strong> determines whether you are <strong>authorized</strong> to access the secured resource. It performs authorization, deciding whether to let you in by considering your authentication information and the security attributes that have been associated with the secured resource. Access Decision Manager is also pluggable.</li>
<li>&quot;<strong>objectDefinitionSource</strong>&quot; property specifies which resources (ie. urls) are secured and what privileges are required to access them via url pattern with roles.</li>
</ul>
</li>
<li><u>ChannelProcessingFilter</u> (optional)
<ul>
<li>Even you have done all the secure protection as stated above, the information you are authorized to obtain still needs to transfer to you via the Internet unprotected. You may want to encrypt it to prevent people from stealing it. Use <strong>HTTPS</strong>!</li>
<li>ChannelProcessingFilter offers a foolproof way to ensure that certain pages be transferred using HTTPS via intercept the request, check to see if it needs to be secure and, if so, call https by <strong>redirecting the request </strong>to an HTTPS form of the original request URL.</li>
</ul>
</li>
</ol>
<p><strong>NOTE</strong>: &quot;securityEnforcementFilter&quot; can combine ExceptionTranslationFilter and FilterSecurityInterceptor together.</p>
<p>To chain them up, here is the xml piece for FilterChainProxy.</p>
<pre name="code" class="xml">
&lt;bean id=&quot;filterChainProxy&quot; class=&quot;net.sf.acegisecurity.util.FilterChainProxy&quot;&gt;
      &lt;property name=&quot;filterInvocationDefinitionSource&quot;&gt;
         &lt;value&gt;
	    CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
	    PATTERN_TYPE_APACHE_ANT
	    /**=httpSessionContextIntegrationFilter, authenticationProcessingFilter, exceptionTranslationFilter, filterSecurityInterceptor
         &lt;/value&gt;
      &lt;/property&gt;
    &lt;/bean&gt;</pre>
<p>You can put more than 1 pattern if you want. The order of the filters are important because it governs the order of the filters in the chain.</p>
<p><strong><u>Step 4. Customize the authentication mechanism<br />
</u></strong></p>
<p>Now you have all the filters wired. You may want to provide a custom authentication against your own database or ldap server. To do that, you need to implement UserDetail class and wire it up with authentication manager. Below is the method you need to override.</p>
<pre class="java" name="code">
public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException, DataAccessException {
        User user = null;
        GrantedAuthority[] grantedAuthorities = null;
        try {
            user = getUserDAO().lookupUser(userId);

            if(user==null) {
                throw new UsernameNotFoundException(&quot;Invalid User&quot;);
            }

            Set roles = user.getRoles();
            int i = 0;
            grantedAuthorities = new GrantedAuthority[roles.size()];
            for (Iterator iter = roles.iterator(); iter.hasNext(); i++) {
                Role role = (Role) iter.next();

                GrantedAuthority authority = new GrantedAuthorityImpl(role.getRole());
                grantedAuthorities[i] = authority;
            }
        } catch (DataStoreException e) {
            throw new DataRetrievalFailureException(&quot;Cannot loadUserByUsername userId:&quot;+userId+ &quot; Exception:&quot; + e.getMessage(), e);
        }

        UserDetails userDetails = new org.acegisecurity.userdetails.User(
                user.getUserId(),
                user.getPassword(),
                user.isEnabled(), //enabled
                user.isEnabled(), //accountNonExpired
                user.isEnabled(), //credentialsNonExpired
                user.isEnabled(), //accountNonLocked
                grantedAuthorities
                );
        return userDetails;
    }
</pre>
<p>Now you need to wire it up to your Authentication Manager</p>
<pre name="code" class="xml">
&lt;bean id=&quot;authenticationManager&quot; class=&quot;org.acegisecurity.providers.ProviderManager&quot;&gt;
  &lt;property name=&quot;providers&quot;&gt;
	 &lt;list&gt;
		&lt;ref local=&quot;daoAuthenticationProvider&quot;/&gt;
	 &lt;/list&gt;
  &lt;/property&gt;
&lt;/bean&gt;

&lt;!-- Acegi will use our UserService bean to do authentication --&gt;
&lt;bean id=&quot;daoAuthenticationProvider&quot; class=&quot;org.acegisecurity.providers.dao.DaoAuthenticationProvider&quot;&gt;
  &lt;property name=&quot;userDetailsService&quot;&gt;&lt;ref bean=&quot;UserService&quot;/&gt;&lt;/property&gt;
  &lt;property name=&quot;passwordEncoder&quot;&gt;&lt;ref local=&quot;passwordEncoder&quot;/&gt;&lt;/property&gt;
&lt;/bean&gt;

&lt;bean id=&quot;UserService&quot;
      class=&quot;org.springframework.transaction.interceptor.TransactionProxyFactoryBean&quot;&gt;
  &lt;property name=&quot;transactionManager&quot;&gt;
    &lt;ref bean=&quot;myTransactionManager&quot;/&gt;
  &lt;/property&gt;
  &lt;property name=&quot;target&quot;&gt;
    &lt;bean class=&quot;com.solutionhacker.user.UserServiceImpl&quot; &gt;
      &lt;property name=&quot;userDAO&quot;&gt;
        &lt;ref local=&quot;UserDAO&quot; /&gt;
      &lt;/property&gt;
    &lt;/bean&gt;
  &lt;/property&gt;
  &lt;property name=&quot;transactionAttributes&quot;&gt;
    &lt;props&gt;
      &lt;prop key=&quot;*&quot;&gt;PROPAGATION_REQUIRED,-Exception&lt;/prop&gt;
    &lt;/props&gt;
  &lt;/property&gt;
&lt;/bean&gt;</pre>
<h2>View-layer security</h2>
<p>&nbsp;As you may notice, filters only provide a coarse-grained security, limiting access at the request level like either you can access the resource or not. In some cases, you may want more fine-grained control over what the user is allowed to see. Maybe all users of an application will be allowed to see a certain page, but only users who are granted special authority may see certain elements on that page. To handle this, Spring Security uses JSP tag library. This tag library provides only 3 tags: <strong>&lt;authz:acl&gt;, &lt;authz:authentication&gt; </strong>and <strong>&lt;authz:authorize&gt;</strong>. You can use this tag to wrap around the UI element and conditionally allows it to display or not based on the role. I will not go through the detail of this here. Since I advocate to use Flex as View, so I will write another article to talk about how we can achieve it in Flex.</p>
<h2>Secure method invocation</h2>
<p>&nbsp;Similar</p>
<h2>Conclusion</h2>
<p>As you can tell, you don&#8217;t write much java code to protect your resource. Everything is almost driven by configuration there. It is nice. However, on the other hand, the tedious work is shifted to configuration. To me, reading the configuration is harder than reading code. You can tell most of the configuration there are not coupled with application. Only the section that is application specific is the security policies you put in under &quot;<strong>objectDefinitionSource</strong>&quot;.&nbsp; Again, to associate all the stuff I want to protect with the role names are tedious and hardcoded.</p>
<p><em><strong>UPDATE</strong>: Acegi is moved to Spring Security 2.0 that has new namespace for security. The main thing they fix is to make the configuration much cleaner. I will talk about that in my next article. </em></p>
<p><strong><em>UPDATE</em></strong><em>: Riable has walked us through how to upgrade from Acegi to Spring Security <a href="http://raibledesigns.com/rd/entry/upgrading_to_spring_security_2" target="_blank">here</a>. So, I don&#8217;t need to write one!</em></p>
<h2>Reference</h2>
<p><a target="_blank" href="http://springtips.blogspot.com/search/label/security">http://springtips.blogspot.com/search/label/security</a></p>
<p><a target="_blank" href="http://i-proving.ca/space/Technologies/Acegi+Security+System+for+Spring">http://i-proving.ca/space/Technologies/Acegi+Security+System+for+Spring</a></p>
<p><a target="_blank" href="http://static.springframework.org/spring-security/site/reference/pdf/springsecurity.pdf">http://static.springframework.org/spring-security/site/reference/pdf/springsecurity.pdf</a></p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.solutionhacker.com/uncategorized/part-1-spring-security-architectural-review/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Configuration Management and Monitoring via Spring</title>
		<link>http://www.solutionhacker.com/implement-your-idea/dev-process/monitoring-via-spring/</link>
		<comments>http://www.solutionhacker.com/implement-your-idea/dev-process/monitoring-via-spring/#comments</comments>
		<pubDate>Fri, 25 Jan 2008 09:56:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[2.1. Develop Your Team]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[configuration management]]></category>
		<category><![CDATA[mbean]]></category>
		<category><![CDATA[monitoring]]></category>
		<category><![CDATA[spring]]></category>

		<guid isPermaLink="false">http://www.solutionhacker.com/2008/01/25/monitoring-via-spring/</guid>
		<description><![CDATA[Externalize your configuration from war For settings that are going to change across different environments like database connection, you should externalize them from your war file. So, you can have your war be environment agnositic. Then, you can promote via simply copying your war across different environments. In Spring, there are several ways to achieve [...]]]></description>
			<content:encoded><![CDATA[<h2><strong>Externalize your configuration from war</strong></h2>
<p>For settings that are going to change across different environments like database connection, you should externalize them from your war file. So, you can have your war be environment agnositic. Then, you can promote via simply copying your war across different environments. In Spring, there are several ways to achieve this.</p>
<h2><strong>What does Spring provide?</strong></h2>
<ol>
<li>PropertyPlaceHolderConfigurer</li>
<li>PropertyOverrideConfigurer</li>
<li>Write your own ApplicationContext</li>
</ol>
<p>The first solutions you can get the detailed from <a href="http://blog.arendsen.net/index.php/2005/03/12/configuration-management-with-spring/">here</a>.  For the 3rd solution, you can subclass XmlWebApplicationContext and override the loadBeanDefinitions method.</p>
<pre class="java" name="code">
public class XmlWebApplicationContext extends
  org.springframework.web.context.support.XmlWebApplicationContext {

  private static ApplicationContextOverride eaco = new ApplicationContextOverride();
  protected final void loadBeanDefinitions(final XmlBeanDefinitionReader reader)
     throws IOException {

     ArrayList allLocations = new ArrayList(); // get standard locations
     String[] configLocations = getConfigLocations();
     allLocations.addAll(Arrays.asList(configLocations));
     allLocations.addAll(eaco.findFiles(configLocations));
     for (String apc : allLocations) {
       log.info("loading file: " + apc);
       reader.loadBeanDefinitions(apc);
     }
  }
}
</pre>
<h2><strong>What is JMX?</strong></h2>
<p>JMX is a technology that enables you to instrument applications for management, monitoring and configuration. Spring JMX module enables you to export Spring beans as <strong>Model MBean</strong> (ie dynamic) so that you can see inside your application and tweak the configuration even while the application is running.</p>
<h2><strong>How to expose your service as MBean in Spring? </strong></h2>
<p>To make your service configurable via JMX, you can follow the steps below:</p>
<ol>
<li><em>Optional:</em> Create a MBean Server if there is no MBean Server instance in your environment. MBean Server is a container where MBeans live and through which the MBeans are accessed.</li>
<li>Use MBeanExporter to expose/register your Spring beans as Model MBeans in an MBean Server. MBean in MBean Server will be identified by ObjectName. You can use jConsole or MC4J to visualize it.</li>
<li>Optional: By default, all the public members of your Spring bean are exported as MBean operations and attributes. This is probably not what you want. Don&#8217;t worry, you are given the power to select which attributes and operations to expose via MBeanInfoAssembler.</li>
</ol>
<p>&#160;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.solutionhacker.com/implement-your-idea/dev-process/monitoring-via-spring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
