<?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>REVERT TO CONSOLE</title>
	<atom:link href="http://www.reverttoconsole.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.reverttoconsole.com</link>
	<description>for f in *;do echo &#124; sed &#039;i\rtc&#039; &#62;&#62; $f;done; java programming et al</description>
	<lastBuildDate>Fri, 30 Mar 2012 13:01:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Integrating ActiveDirectory on Windows NTLM using Spring Security and custom authorization to simulate a single-sign-on web application</title>
		<link>http://www.reverttoconsole.com/blog/security/integrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization/</link>
		<comments>http://www.reverttoconsole.com/blog/security/integrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization/#comments</comments>
		<pubDate>Thu, 12 Jan 2012 19:33:11 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=1047</guid>
		<description><![CDATA[Goals Authenticate a Spring web application deployed on Windows NTLM network using ActiveDirectory, manage Roles in web application (custom authorization), and simulate a single-sign-on environment, where a use can simply access a url and on successful local windows login, application would redirect to home page. So there&#8217;s no login screen required. Integrate with Spring Security [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Goals</strong><br />
Authenticate a Spring web application deployed on Windows NTLM network using ActiveDirectory, manage Roles in web application (custom authorization), and simulate a single-sign-on environment, where a use can simply access a url and on successful local windows login, application would redirect to home page. So there&#8217;s no login screen required. Integrate with Spring Security framework is desirable. If possible, the solution should be reusable across multiple Spring web apps.</p>
<p><strong>STRATEGIES:</strong><br />
Though Spring Security provides tools to integrate LDAP, a seamless integration of ActiveDirectory in a web application using spring security is still a pain. I recently came across this problem and after some research found <a href="http://waffle.codeplex.com" target="_blank">Waffle Security</a> the best tool for this job. I had to modify the source code to customize the solution based on my requirements. Here&#8217;s a writeup of my findings:</p>
<p><strong>Spring Security LDAP</strong><br />
* <a href="http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ldap" target="_blank">Spring LDAP Security Reference</a><br />
* Spring uses ActiveDirectoryLdapAuthenticationProvider, which delegates the work to LdapAuthenticator and LdapAuthoritiesPopulator which are responsible for authenticating the user and retrieving the user&#8217;s set of GrantedAuthoritys respectively.UserDetails can be populated using DefaultLdapAuthoritiesPopulator.<br />
* A local LDAP instance can be easily setup (and tested) in a web app.<br />
* You must update ldap properties in users.ldif (sample ldap user info) for authentication/authorization to work. However this doesn&#8217;t work as a single-sign on environment, since additional filters need to be written.</p>
<p>Hence this approach was not suited for a single-sign-on requirement.</p>
<p><strong>Tomcat 7 integration</strong><br />
* Not sure how <a href="http://tomcat.apache.org/tomcat-7.0-doc/windows-auth-howto.html" target="_blank">Tomcat integration</a> is useful since configuring Realms and other server settings is an additional step outside of the App. Each environment has to ensure these settings exist, which means local development and test, stage, prod configuration grow exponentially. Also, the authentication object should to be populated in Spring&#8217;s context (ie., the application&#8217;s context). This leads to Spring being aware of Tomcat&#8217;s Realms and settings +  the web app supporting Tomcat&#8217;s authentication (SPNEGO) etc.,<br />
* Tomcat integration is geared towards plain servlet apps.</p>
<p>Due to the above reasons I didn&#8217;t find this solution extensible.</p>
<p><strong>Spring Security Kerberos/SPNEGO Extension</strong><br />
* For Kerberos (unix or windows) based, client based (browser) authentication, this extension from Spring is apt<br />
* You need some knowledge on the server side (setup kerberos etc.,) so this may not be an &#8220;out of the box&#8221; solution<br />
* Reference example is <a href="http://blog.springsource.com/2009/09/28/spring-security-kerbero" target="_blank">here</a></p>
<p>Ideally this solution would&#8217;ve been great but at the point of this writing (to my findings), this solution doesn&#8217;t integrate with Active Directory on NTLM. </p>
<p><strong>Kerberos + NTLM with Waffle Filter support with Spring Security</strong><br />
* More flexible than the above example since it supports both Kerberos and Windows NTLM. Waffle will allow you to get rid of IIS (as a pass through) as well. Unlike many other implementations WAFFLE on Windows does not usually require any server-side Kerberos keytab setup, it&#8217;s a drop-in solution.<br />
* Integrates well with Spring Security<br />
* Project Site is <a href="http://waffle.codeplex.com" target="_blank">here</a>.<br />
* Reference example is <a href="http://code.dblock.org/single-sign-on-spring-security-negotiate-filter-kerberos-ntlm-wwaffle" target="_blank">here</a>.<br />
* Was able to get this working with custom classes that extend Waffle&#8217;s filter and custom Authentication object. WORKS as a single-sign within a corporate network and roles are correctly mapped into granted authorities.</p>
<p><strong>Implementation Summary</strong><br />
* The above reference example provided by Waffle is a good start, however that code also assumes authorization loaded from ActiveDirectory. In order to customize authorization, you must extend waffle.spring.NegotiateSecurityFilter. Since Waffle doesn&#8217;t open up api to override (Duh#TemplatePatternWouldBeSoNice), I had to copy its implementation and make changes myself.</p>
<pre>

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import waffle.servlet.WindowsPrincipal;
import waffle.spring.NegotiateSecurityFilter;
import waffle.util.AuthorizationHeader;
import waffle.windows.auth.IWindowsIdentity;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Custom Authentication Filter extending Waffle's built-in Filter.
 * Loads User Roles from Db and uses custom AuthenticationToken.
 * For the most part its same as NegotiateSecurityFilter. See #Note below for the key difference
 */
public class CustomAuthenticationFilter extends NegotiateSecurityFilter {

    Logger logger = LoggerFactory.getLogger(CustomAuthenticationFilter.class);

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        logger.info(request.getMethod() + " " + request.getRequestURI() + ", contentlength: " + request.getContentLength());
        AuthorizationHeader authorizationHeader = new AuthorizationHeader(request);

        // authenticate user
        if (!authorizationHeader.isNull()
                &#038;&#038; getProvider().isSecurityPackageSupported(authorizationHeader.getSecurityPackage())) {

            // log the user in using the token
            IWindowsIdentity windowsIdentity = null;

            try {
                windowsIdentity = getProvider().doFilter(request, response);
                if (windowsIdentity == null) {
                    return;
                }
            } catch (Exception e) {
                logger.warn("error logging in user: " + e.getMessage());
                sendUnauthorized(response, true);
                return;
            }

            if (!getAllowGuestLogin() &#038;&#038; windowsIdentity.isGuest()) {
                logger.warn("guest login disabled: " + windowsIdentity.getFqn());
                sendUnauthorized(response, true);
                return;
            }

            try {
                logger.debug("logged in user: " + windowsIdentity.getFqn() +
                        " (" + windowsIdentity.getSidString() + ")");
                WindowsPrincipal principal = new WindowsPrincipal(
                        windowsIdentity, getPrincipalFormat(), getRoleFormat());
                logger.debug("roles: " + principal.getRolesString());

                /// NOTE: This is where you customize auth. You'd need your own token and initialization mechanism different from
                /// Waffle's built in token implementation
                // Populate Authentication Token along with GrantedAuthorities
                CustomAuthenticationToken authentication = new CustomAuthenticationToken(principal);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                logger.info("successfully logged in user: " + windowsIdentity.getFqn());
            } finally {
                windowsIdentity.dispose();
            }
        }

        chain.doFilter(request, response);
    }

    /**
     * Send a 401 Unauthorized along with protocol authentication headers.
     *
     * @param response HTTP Response
     * @param close    Close connection.
     */
    private void sendUnauthorized(HttpServletResponse response, boolean close) {
        try {
            getProvider().sendUnauthorized(response);
            if (close) {
                response.setHeader("Connection", "close");
            } else {
                response.setHeader("Connection", "keep-alive");
            }
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            response.flushBuffer();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
</pre>
<p>Here&#8217;s the custom Authentication Token:</p>
<pre>
import xxx.domain.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import waffle.servlet.WindowsPrincipal;

import java.util.Collection;
import java.util.List;

/**
 * Custom Authentication Token to comply with custom Waffle Authentication mechanism.
 * Variation of Waffle&#039;s WindowsAuthenticationToken. See #Note below
 */
public class CustomAuthenticationToken implements Authentication {

    Logger logger = LoggerFactory.getLogger(CustomAuthenticationToken.class);

    private static final long serialVersionUID = 1L;
    private WindowsPrincipal windowsPrincipal = null;
    private org.springframework.security.core.userdetails.User principal = null;
    private Collection&lt;GrantedAuthority&gt; authorities = null;

    // Move this to a config
    public static final String MY_DOMAIN = &quot;&lt;your corporate domain&gt;&quot;;

    /**
     * Constructor that fully initializes the principal
     *
     * @param windowsPrincipal windows principal
     */
    public CustomAuthenticationToken(WindowsPrincipal windowsPrincipal) {
        this.windowsPrincipal = windowsPrincipal;
        // Strip domainName in &lt;domainName&gt;\\username to get mapped username in App
        String username = windowsPrincipal.getName().substring(MY_DOMAIN.length()+1);
        logger.debug(&quot;App Login Info derived from ActiveDirectory: &quot; + username);

        // Load roles
        Collection&lt;GrantedAuthority&gt; authorities = loadAuthorities(username);

        // Create UserDetails object
        this.principal = new org.springframework.security.core.userdetails.User(username, &quot;&quot;, true, true,
                true, true, authorities);
    }

    /**
     * Loads granted authorities by looking up User=&gt;Roles.
     * Throws UsernameNotFoundException if principal isn&#039;t mapped mapped to Db
     * @return
     */
    private Collection&lt;GrantedAuthority&gt; loadAuthorities(String username) {

        // Match User Account from Db
        User account = null;
        try {
            // NOTE: I Use Spring Roo&#039;s inbuilt finder but you can easily replace the below code by JDBC/JPA/Hibernate Dao or Service
            account = User.findUserByName(username);
        }
        catch (Exception e) {
            logger.info(&quot;A unique account &quot; + username + &quot; could not be found: &quot; + e.getMessage());
            throw new UsernameNotFoundException(&quot;A unique account &quot; + username + &quot; could not be found&quot;);
        }

        // Load User Roles
        List&lt;String&gt; roles = account.getRoleNames();
        logger.debug(&quot;Loaded Roles from Database: &quot; + roles.toString());
        Collection&lt;GrantedAuthority&gt; grantedAuthorities = toGrantedAuthorities(roles);
        this.authorities = grantedAuthorities;
        return authorities;
    }

    @Override
    public Collection&lt;GrantedAuthority&gt; getAuthorities() {
        return authorities;
    }

    public Object getCredentials() {
        return null;
    }

    public Object getDetails() {
        return windowsPrincipal;
    }

    public Object getPrincipal() {
        return principal;
    }

    public boolean isAuthenticated() {
        return (principal != null);
    }

    public void setAuthenticated(boolean authenticated) throws IllegalArgumentException {
        throw new IllegalArgumentException();
    }

    public String getName() {
        return principal.getUsername();
    }

    private static Collection&lt;GrantedAuthority&gt; toGrantedAuthorities(List&lt;String&gt; roles) {
        List&lt;GrantedAuthority&gt; result = new ArrayList&lt;GrantedAuthority&gt;();

        for (String role : roles) {
            result.add(new GrantedAuthorityImpl(role));
        }

        return result;
    }
}
</pre>
<p>And here&#8217;s the Spring Config (very similar to the Waffle&#8217;s reference example):</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:sec=&quot;http://www.springframework.org/schema/security&quot;
       xsi:schemaLocation=&quot;
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd&quot;&gt;

    &lt;bean id=&quot;loggerListener&quot; class=&quot;org.springframework.security.authentication.event.LoggerListener&quot; /&gt;

    &lt;!-- Windows authentication provider --&gt;
    &lt;bean id=&quot;waffleWindowsAuthProvider&quot; class=&quot;waffle.windows.auth.impl.WindowsAuthProviderImpl&quot;/&gt;

    &lt;!-- Collection of security filters --&gt;
    &lt;bean id=&quot;negotiateSecurityFilterProvider&quot; class=&quot;waffle.servlet.spi.NegotiateSecurityFilterProvider&quot;&gt;
        &lt;constructor-arg ref=&quot;waffleWindowsAuthProvider&quot;/&gt;
    &lt;/bean&gt;
    &lt;bean id=&quot;basicSecurityFilterProvider&quot; class=&quot;waffle.servlet.spi.BasicSecurityFilterProvider&quot;&gt;
        &lt;constructor-arg ref=&quot;waffleWindowsAuthProvider&quot;/&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;waffleSecurityFilterProviderCollection&quot; class=&quot;waffle.servlet.spi.SecurityFilterProviderCollection&quot;&gt;
        &lt;constructor-arg&gt;
            &lt;list&gt;
                &lt;ref bean=&quot;negotiateSecurityFilterProvider&quot;/&gt;
                &lt;ref bean=&quot;basicSecurityFilterProvider&quot;/&gt;
            &lt;/list&gt;
        &lt;/constructor-arg&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;negotiateSecurityFilterEntryPoint&quot; class=&quot;waffle.spring.NegotiateSecurityFilterEntryPoint&quot;&gt;
        &lt;property name=&quot;provider&quot; ref=&quot;waffleSecurityFilterProviderCollection&quot;/&gt;
    &lt;/bean&gt;

    &lt;!-- Waffle authentication provider --&gt;
    &lt;sec:authentication-manager alias=&quot;authenticationProvider&quot;/&gt;

    &lt;!-- Custom Authentication Filter --&gt;
    &lt;bean id=&quot;waffleNegotiateSecurityFilter&quot; class=&quot;xxx.CustomAuthenticationFilter&quot;&gt;
        &lt;property name=&quot;provider&quot; ref=&quot;waffleSecurityFilterProviderCollection&quot;/&gt;
        &lt;property name=&quot;allowGuestLogin&quot; value=&quot;false&quot;/&gt;
        &lt;property name=&quot;principalFormat&quot; value=&quot;fqn&quot;/&gt;
        &lt;property name=&quot;roleFormat&quot; value=&quot;both&quot;/&gt;
    &lt;/bean&gt;

    &lt;!-- Core config--&gt;
    &lt;sec:http entry-point-ref=&quot;negotiateSecurityFilterEntryPoint&quot;&gt;
        &lt;sec:custom-filter ref=&quot;waffleNegotiateSecurityFilter&quot; position=&quot;BASIC_AUTH_FILTER&quot;/&gt;

        &lt;sec:logout logout-url=&quot;/app/logout&quot; logout-success-url=&quot;/app/home&quot;/&gt;
        &lt;sec:access-denied-handler error-page=&quot;/app/accessdenied&quot;/&gt;

        &lt;sec:intercept-url pattern=&quot;/**&quot; access=&quot;IS_AUTHENTICATED_FULLY&quot;/&gt;
        &lt;sec:intercept-url pattern=&quot;/app/resource/*&quot; filters=&quot;none&quot;/&gt;
        &lt;sec:intercept-url pattern=&quot;/app/javax.*/**&quot; filters=&quot;none&quot;/&gt;
    &lt;/sec:http&gt;

&lt;/beans&gt;
</pre>
<p>That&#8217;s it.</p>
<p>The above spring config is loaded via web.xml, along with other spring contexts. </p>
<p>Now when user tries to access the application url, CustomAuthenticationFilter correctly recognizes the authenticated Windows user and redirects to app home page. Yes it&#8217;s a single-sign-on!</p>
<p>To simplify testing, I&#8217;d recommended having a &#8220;Spring-LDAP-security&#8221; for dev and switch to Waffle Filter for prod environments.  </p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fintegrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization%2F&amp;title=Integrating+ActiveDirectory+on+Windows+NTLM+using+Spring+Security+and+custom+authorization+to+simulate+a+single-sign-on+web+application" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fintegrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization%2F&amp;title=Integrating+ActiveDirectory+on+Windows+NTLM+using+Spring+Security+and+custom+authorization+to+simulate+a+single-sign-on+web+application" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fintegrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization%2F&amp;title=Integrating+ActiveDirectory+on+Windows+NTLM+using+Spring+Security+and+custom+authorization+to+simulate+a+single-sign-on+web+application" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fintegrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization%2F&amp;title=Integrating+ActiveDirectory+on+Windows+NTLM+using+Spring+Security+and+custom+authorization+to+simulate+a+single-sign-on+web+application" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fintegrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization%2F&amp;title=Integrating+ActiveDirectory+on+Windows+NTLM+using+Spring+Security+and+custom+authorization+to+simulate+a+single-sign-on+web+application', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fintegrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fintegrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fintegrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization%2F&amp;title=Integrating+ActiveDirectory+on+Windows+NTLM+using+Spring+Security+and+custom+authorization+to+simulate+a+single-sign-on+web+application" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fsecurity%2Fintegrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization%2F&amp;title=Integrating+ActiveDirectory+on+Windows+NTLM+using+Spring+Security+and+custom+authorization+to+simulate+a+single-sign-on+web+application" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/security/integrating-activedirectory-on-windows-ntlm-using-spring-security-and-custom-authorization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating XML Schema and Classes using JaxB and Maven pom</title>
		<link>http://www.reverttoconsole.com/blog/core-java/generating-xml-schema-and-classes-using-jaxb-and-maven-pom/</link>
		<comments>http://www.reverttoconsole.com/blog/core-java/generating-xml-schema-and-classes-using-jaxb-and-maven-pom/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 09:11:23 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Core Java]]></category>
		<category><![CDATA[Maven/Ivy]]></category>
		<category><![CDATA[Xml]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=1059</guid>
		<description><![CDATA[Xml Binding via JaxB is a standard way to work with Xml objects in Java 6 and beyond. While there are ant tools and cmd line utilities to automate this, externalizing the automation in a dedicated maven module, along with nice wrapper methods for a fluent api would be nice. Below are the steps to [...]]]></description>
			<content:encoded><![CDATA[<p>Xml Binding via JaxB is a standard way to work with Xml objects in Java 6 and beyond. While there are ant tools and cmd line utilities to automate this, externalizing the automation in a dedicated maven module, along with nice wrapper methods for a <a href="http://code.google.com/p/jaxb-fluent-api-ext/wiki/Introduction" target="_blank">fluent api</a> would be nice. Below are the steps to generate jaxb objects with a fluent api via Maven Pom configuration.</p>
<p><strong>Source Structure</strong><br />
- src/main/resources/sample.xsd<br />
- src/main/resources/binding/binding.xjb</p>
<pre>
&lt;bindings xmlns=&quot;http://java.sun.com/xml/ns/jaxb&quot; version=&quot;2.0&quot; xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
  &lt;globalBindings&gt;
    &lt;javaType name=&quot;java.util.Calendar&quot; xmlType=&quot;xs:date&quot;
      parseMethod=&quot;javax.xml.bind.DatatypeConverter.parseDate&quot;
      printMethod=&quot;javax.xml.bind.DatatypeConverter.printDate&quot;
    /&gt;
  &lt;/globalBindings&gt;
&lt;/bindings&gt;
</pre>
<p>- Finally, integrate jaxb compile and generate step via pom.xml</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;artifactId&gt;common-xml-schema&lt;/artifactId&gt;
    &lt;packaging&gt;jar&lt;/packaging&gt;
    &lt;name&gt;Common Schema and JaxB Module&lt;/name&gt;

    &lt;description&gt;Common Module to hold all XML Schemas and JaxB objects&lt;/description&gt;
    &lt;dependencies&gt;
         &lt;dependency&gt;
            &lt;groupId&gt;javax.xml.bind&lt;/groupId&gt;
            &lt;artifactId&gt;jaxb-api&lt;/artifactId&gt;
            &lt;version&gt;2.2.2&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.sun.xml.bind&lt;/groupId&gt;
            &lt;artifactId&gt;jaxb-impl&lt;/artifactId&gt;
            &lt;version&gt;2.2.4&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;build&gt;
        &lt;plugins&gt;
            &lt;!-- It&#039;s advised not to checkin the generated classes. By default they are generated in target/generated-sources with xmlns namespace provided
            in xsd. If you need the sources to be generated uncomment the below.
            &lt;plugin&gt;
                &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
                &lt;artifactId&gt;jaxb2-maven-plugin&lt;/artifactId&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;xjc&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
                &lt;configuration&gt;
                    &lt;packagename&gt;xxx.schema&lt;/packagename&gt;
                    &lt;schemaDirectory&gt;${basedir}/src/main/resources&lt;/schemaDirectory&gt;
                    &lt;outputdirectory&gt;${basedir}/src/main/java/xxx/generated&lt;/outputdirectory&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
            --&gt;

            &lt;plugin&gt;
                &lt;groupId&gt;org.jvnet.jaxb2.maven2&lt;/groupId&gt;
                &lt;artifactId&gt;maven-jaxb2-plugin&lt;/artifactId&gt;

                &lt;configuration&gt;
                    &lt;extension&gt;true&lt;/extension&gt;
                    &lt;args&gt;
                        &lt;arg&gt;-Xfluent-api&lt;/arg&gt;
                    &lt;/args&gt;
                    &lt;plugins&gt;
                        &lt;plugin&gt;
                            &lt;groupId&gt;net.java.dev.jaxb2-commons&lt;/groupId&gt;
                            &lt;artifactId&gt;jaxb-fluent-api&lt;/artifactId&gt;
                            &lt;version&gt;2.1.8&lt;/version&gt;
                        &lt;/plugin&gt;
                    &lt;/plugins&gt;
                    &lt;bindingDirectory&gt;src/main/resources/binding&lt;/bindingDirectory&gt;
                &lt;/configuration&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;generate&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;

&lt;/project&gt;
</pre>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fgenerating-xml-schema-and-classes-using-jaxb-and-maven-pom%2F&amp;title=Generating+XML+Schema+and+Classes+using+JaxB+and+Maven+pom" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fgenerating-xml-schema-and-classes-using-jaxb-and-maven-pom%2F&amp;title=Generating+XML+Schema+and+Classes+using+JaxB+and+Maven+pom" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fgenerating-xml-schema-and-classes-using-jaxb-and-maven-pom%2F&amp;title=Generating+XML+Schema+and+Classes+using+JaxB+and+Maven+pom" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fgenerating-xml-schema-and-classes-using-jaxb-and-maven-pom%2F&amp;title=Generating+XML+Schema+and+Classes+using+JaxB+and+Maven+pom" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fgenerating-xml-schema-and-classes-using-jaxb-and-maven-pom%2F&amp;title=Generating+XML+Schema+and+Classes+using+JaxB+and+Maven+pom', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fgenerating-xml-schema-and-classes-using-jaxb-and-maven-pom%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fgenerating-xml-schema-and-classes-using-jaxb-and-maven-pom%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fgenerating-xml-schema-and-classes-using-jaxb-and-maven-pom%2F&amp;title=Generating+XML+Schema+and+Classes+using+JaxB+and+Maven+pom" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fgenerating-xml-schema-and-classes-using-jaxb-and-maven-pom%2F&amp;title=Generating+XML+Schema+and+Classes+using+JaxB+and+Maven+pom" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/core-java/generating-xml-schema-and-classes-using-jaxb-and-maven-pom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Add session user info to log4j logging (custom file appender)</title>
		<link>http://www.reverttoconsole.com/blog/core-java/add-session-user-info-to-log4j-logging-custom-file-appender/</link>
		<comments>http://www.reverttoconsole.com/blog/core-java/add-session-user-info-to-log4j-logging-custom-file-appender/#comments</comments>
		<pubDate>Sat, 06 Aug 2011 00:23:28 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Core Java]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=1064</guid>
		<description><![CDATA[Ever wondered how to add additional session related info in log4j logging? I like to see logged in user, along with session-id info in logging messages in applications, where analyzing secure operations becomes critical (healthcare, financial apps). Here&#8217;s a sample filter log4j&#8217;s MDC to add diagnostic context in log messages. package com.cramer.srf.web.filter; import java.io.IOException; import [...]]]></description>
			<content:encoded><![CDATA[<p>Ever wondered how to add additional session related info in log4j logging?</p>
<p>I like to see logged in user, along with session-id info in logging messages in applications, where analyzing secure operations becomes critical (healthcare, financial apps).</p>
<p>Here&#8217;s a sample filter log4j&#8217;s MDC to add diagnostic context in log messages.</p>
<pre>
package com.cramer.srf.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.MDC;

import com.cramer.srf.util.SRFUtils;

/**
 * Filter that adds user session info in log4j MDC (Mapped Diagnoistic Context)
 *
 */
public class Log4jSessionFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			if (SRFUtils.getLoggedUser() != null) {
			    MDC.put("user", SRFUtils.getLoggedUser());
			}
		}
		filterChain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// NO OP
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// NO OP
	}
}
</pre>
<p>The corresponding log4j file. Note &#8216;[%X{user}]&#8216; in the ConversionPattern below.</p>
<pre>
&lt;!-- File appender --&gt;
&lt;appender name=&quot;FILE&quot; class=&quot;org.apache.log4j.DailyRollingFileAppender&quot;&gt;
    &lt;param name=&quot;File&quot; value=&quot;logs/rx.log&quot; /&gt;
    &lt;param name=&quot;Append&quot; value=&quot;true&quot;
    &lt;param name=&quot;DatePattern&quot; value=&quot;&#039;.&#039;yyyy-ww&quot; /&gt;
    &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt;
        &lt;param name=&quot;ConversionPattern&quot; value=&quot;%d{ISO8601}  %-5p [%X{user}] [%t:%X{SESSION}] %c - %m%n&quot; /&gt;
    &lt;/layout&gt;
&lt;/appender&gt;
</pre>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fadd-session-user-info-to-log4j-logging-custom-file-appender%2F&amp;title=Add+session+user+info+to+log4j+logging+%28custom+file+appender%29" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fadd-session-user-info-to-log4j-logging-custom-file-appender%2F&amp;title=Add+session+user+info+to+log4j+logging+%28custom+file+appender%29" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fadd-session-user-info-to-log4j-logging-custom-file-appender%2F&amp;title=Add+session+user+info+to+log4j+logging+%28custom+file+appender%29" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fadd-session-user-info-to-log4j-logging-custom-file-appender%2F&amp;title=Add+session+user+info+to+log4j+logging+%28custom+file+appender%29" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fadd-session-user-info-to-log4j-logging-custom-file-appender%2F&amp;title=Add+session+user+info+to+log4j+logging+%28custom+file+appender%29', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fadd-session-user-info-to-log4j-logging-custom-file-appender%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fadd-session-user-info-to-log4j-logging-custom-file-appender%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fadd-session-user-info-to-log4j-logging-custom-file-appender%2F&amp;title=Add+session+user+info+to+log4j+logging+%28custom+file+appender%29" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fcore-java%2Fadd-session-user-info-to-log4j-logging-custom-file-appender%2F&amp;title=Add+session+user+info+to+log4j+logging+%28custom+file+appender%29" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/core-java/add-session-user-info-to-log4j-logging-custom-file-appender/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Command Line Dictionary Using Groovy WS</title>
		<link>http://www.reverttoconsole.com/blog/general/command-line-dictionary-using-groovy-ws/</link>
		<comments>http://www.reverttoconsole.com/blog/general/command-line-dictionary-using-groovy-ws/#comments</comments>
		<pubDate>Mon, 18 Jul 2011 22:37:18 +0000</pubDate>
		<dc:creator>Steve</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Web Services]]></category>
		<category><![CDATA[dictionary command line groovy groovyws ws client bash]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=1015</guid>
		<description><![CDATA[Alas, another 15 years has passed since I&#8217;ve last posted. This time it was prompted by a fairly simple need: to lookup a word via the command line. Now, I already had a very simple solution to this using WordNet. That is simple enough: sudo apt-get install wordnet Then simply type: wn hello -over You [...]]]></description>
			<content:encoded><![CDATA[<p>Alas, another 15 years has passed since I&#8217;ve last posted.  This time it was prompted by a fairly simple need: to lookup a word via the command line.  Now, I already had a very simple solution to this using <a href="http://wordnet.princeton.edu/">WordNet</a>.  That is simple enough:</p>
<pre>
sudo apt-get install wordnet
</pre>
<p>Then simply type:</p>
<pre>
wn hello -over
</pre>
<p>You should see output similar to this:</p>
<p>Overview of noun hello</p>
<p>The noun hello has 1 sense (first 1 from tagged texts)</p>
<p>1. (1) hello, hullo, hi, howdy, how-do-you-do &#8212; (an expression of greeting; &#8220;every morning they exchanged polite hellos&#8221;)</p>
<p>That&#8217;s all well and good, until I typed this:</p>
<pre>wn smote -over</pre>
<p>And came up empty.  Indeed WordNet is useful but it is limited.  There are 2 solutions that immediately came to mind.	</p>
<ol>
<li>Figure out how to get more definitions loaded into my instance of WordNet</li>
<li>Find a dictionary service that is much more comprehensive than WordNet, and write a client for it</li>
</ol>
<p>After a couple of quick Google searches I decided on the latter.  And, since I&#8217;ve been doing a fair amount of Grails work lately, I thought, why not try this in Groovy?</p>
<p>One of those Google searches brought me to <a href="http://services.aonaware.com/DictService/">http://services.aonaware.com/DictService/</a>.  After a few trials with the simple front-end on the page, I was satisfied.  Then it was time to find a Groovy example, which I found quickly enough with <a href="http://groovy.codehaus.org/GroovyWS">Groovy WS</a>.</p>
<p>If you look at the code snippet on that page, it is incredibly simple.</p>
<pre>
@Grab(group='org.codehaus.groovy.modules', module='groovyws', version='0.5.2')
import groovyx.net.ws.WSClient

proxy = new WSClient("http://www.w3schools.com/webservices/tempconvert.asmx?WSDL", this.class.classLoader)
proxy.initialize()

result = proxy.CelsiusToFahrenheit(0)
println "You are probably freezing at ${result} degrees Farhenheit"
</pre>
<p>I tried this example as is, but seemed to have problems with the annotation at the top.  Being rather impatient, I found a Groovy WS Standalone jar here at:<br />
<a href="http://snapshots.dist.codehaus.org/groovy/distributions/groovyws/groovyws-standalone-0.5-SNAPSHOT.jar">http://snapshots.dist.codehaus.org/groovy/distributions/groovyws/groovyws-standalone-0.5-SNAPSHOT.jar</a></p>
<p>I dropped it into my $GROOVY_HOME/lib directory, and then removed the annotation from the code.  The example worked perfectly.</p>
<p>So, using the <a href="http://services.aonaware.com/DictService/DictService.asmx?WSDL">WSDL</a> from the service I mentioned earlier, I made a few modifications and named it Pablo.groovy.  Why Pablo?  Why not?  When speed counts, who cares?!</p>
<pre>
import groovyx.net.ws.WSClient

proxy = new WSClient("http://services.aonaware.com/DictService/DictService.asmx?WSDL", this.class.classLoader)
proxy.initialize()

//Define is a name of the service method, see the service WSDL
result = proxy.Define(args[0])

if(result != null) {
	for(defin in result.definitions.definition) {
		println "${defin.wordDefinition}"
	}
}
</pre>
<p>I needed to analyze the WSDL to figure out how to interpret the results, but other than that, it was a pleasantly pain-free experience.</p>
<p>Now I type:</p>
<pre>groovy Pablo.groovy smote</pre>
<p>And I get a much more satisfying result, save the logging garbage at the top!</p>
<p>Jul 18, 2011 5:11:29 PM org.apache.cxf.endpoint.dynamic.DynamicClientFactory outputDebug<br />
INFO: Created classes: com.aonaware.services.webservices.ArrayOfDefinition, com.aonaware.services.webservices.ArrayOfDictionary, com.aonaware.services.webservices.ArrayOfDictionaryWord, com.aonaware.services.webservices.ArrayOfStrategy, com.aonaware.services.webservices.Define, com.aonaware.services.webservices.DefineInDict, com.aonaware.services.webservices.DefineInDictResponse, com.aonaware.services.webservices.DefineResponse, com.aonaware.services.webservices.Definition, com.aonaware.services.webservices.Dictionary, com.aonaware.services.webservices.DictionaryInfo, com.aonaware.services.webservices.DictionaryInfoResponse, com.aonaware.services.webservices.DictionaryList, com.aonaware.services.webservices.DictionaryListExtended, com.aonaware.services.webservices.DictionaryListExtendedResponse, com.aonaware.services.webservices.DictionaryListResponse, com.aonaware.services.webservices.DictionaryWord, com.aonaware.services.webservices.Match, com.aonaware.services.webservices.MatchInDict, com.aonaware.services.webservices.MatchInDictResponse, com.aonaware.services.webservices.MatchResponse, com.aonaware.services.webservices.ObjectFactory, com.aonaware.services.webservices.ServerInfo, com.aonaware.services.webservices.ServerInfoResponse, com.aonaware.services.webservices.Strategy, com.aonaware.services.webservices.StrategyList, com.aonaware.services.webservices.StrategyListResponse, com.aonaware.services.webservices.WordDefinition<br />
Jul 18, 2011 5:11:30 PM groovyx.net.ws.AbstractCXFWSClient getBindingOperationInfo<br />
WARNING:  Using SOAP version: 1.1<br />
Smite \Smite\ (sm[imac]t), v. t. [imp. {Smote} (sm[=o]t), rarely<br />
   {Smit} (sm[i^]t); p. p. {Smitten} (sm[i^]t&#8221;t&#8217;n), rarely<br />
   {Smit}, or {Smote}; p. pr. &#038; vb. n. {Smiting}<br />
   (sm[imac]t&#8221;[i^]ng).] [AS. sm[=i]tan to smite, to soil,<br />
   pollute; akin to OFries. sm[=i]ta to smite, LG. smiten, D.<br />
   smijten, G. schmeissen, OHG. sm[=i]zan to smear, stroke, OSw.<br />
   &#038; dial. Sw. smita to smite, Dan. smide to throw, Goth.<br />
   bismeitan, to anoint, besmear; cf. Skr. m[=e]d to be fat. The<br />
   original sense seems to have been, to daub on, to smear. Cf.<br />
   {Smut}.]<br />
   1. To strike; to inflict a blow upon with the hand, or with<br />
      any instrument held in the hand, or with a missile thrown<br />
      by the hand; as, to smite with the fist, with a rod,<br />
      sword, spear, or stone.<br />
      [1913 Webster]</p>
<p>Now to smote the logging and be rid of it; simply adding these few lines will do:</p>
<pre>
import java.util.logging.Level
import java.util.logging.LogManager

LogManager.getLogManager().getLogger("").setLevel(Level.SEVERE)
</pre>
<p>Now the output is as tidy as I want it to be for now.</p>
<p>$ groovy Pablo.groovy smote<br />
Smite \Smite\ (sm[imac]t), v. t. [imp. {Smote} (sm[=o]t), rarely<br />
   {Smit} (sm[i^]t); p. p. {Smitten} (sm[i^]t&#8221;t&#8217;n), rarely<br />
   {Smit}, or {Smote}; p. pr. &#038; vb. n. {Smiting}<br />
   (sm[imac]t&#8221;[i^]ng).] [AS. sm[=i]tan to smite, to soil,<br />
   pollute; akin to OFries. sm[=i]ta to smite, LG. smiten, D.<br />
   smijten, G. schmeissen, OHG. sm[=i]zan to smear, stroke, OSw.<br />
   &#038; dial. Sw. smita to smite, Dan. smide to throw, Goth.<br />
   bismeitan, to anoint, besmear; cf. Skr. m[=e]d to be fat. The<br />
   original sense seems to have been, to daub on, to smear. Cf.<br />
   {Smut}.]<br />
   1. To strike; to inflict a blow upon with the hand, or with<br />
      any instrument held in the hand, or with a missile thrown<br />
      by the hand; as, to smite with the fist, with a rod,<br />
      sword, spear, or stone.<br />
      [1913 Webster]</p>
<p>            Whosoever shall smite thee on thy right cheek, turn<br />
            to him the other also.                &#8211;Matt. v. 39.<br />
      [1913 Webster]</p>
<p>            And David . . . took thence a stone, and slang it,<br />
            and smote the Philistine in his forehead. &#8211;1 Sam.<br />
                                                  xvii. 49.<br />
      [1913 Webster]</p>
<p>   2. To cause to strike; to use as an instrument in striking or<br />
      hurling.<br />
      [1913 Webster]</p>
<p>            Prophesy, and smite thine hands together. &#8211;Ezek.<br />
                                                  xxi. 14.<br />
      [1913 Webster]</p>
<p>            Saul . . . smote the javelin into the wall. &#8211;1 Sam.<br />
                                                  xix. 10.<br />
      [1913 Webster]</p>
<p>   3. To destroy the life of by beating, or by weapons of any<br />
      kind; to slay by a blow; to kill; as, to smite one with<br />
      the sword, or with an arrow or other instrument.<br />
      [1913 Webster]</p>
<p>   4. To put to rout in battle; to overthrow by war.<br />
      [1913 Webster]</p>
<p>   5. To blast; to destroy the life or vigor of, as by a stroke<br />
      or by some visitation.<br />
      [1913 Webster]</p>
<p>            The flax and the barly was smitten.   &#8211;Ex. ix. 31.<br />
      [1913 Webster]</p>
<p>   6. To afflict; to chasten; to punish.<br />
      [1913 Webster]</p>
<p>            Let us not mistake God&#8217;s goodness, nor imagine,<br />
            because he smites us, that we are forsaken by him.<br />
                                                  &#8211;Wake.<br />
      [1913 Webster]</p>
<p>   7. To strike or affect with passion, as love or fear.<br />
      [1913 Webster]</p>
<p>            The charms that smite the simple heart. &#8211;Pope.<br />
      [1913 Webster]</p>
<p>            Smit with the love of sister arts we came. &#8211;Pope.<br />
      [1913 Webster]</p>
<p>   {To smite off}, to cut off.</p>
<p>   {To smite out}, to knock out, as a tooth. &#8211;Exod. xxi. 27.</p>
<p>   {To smite with the tongue}, to reproach or upbraid; to<br />
      revile. [Obs.] &#8211;Jer. xviii. 18.<br />
      [1913 Webster]</p>
<p>Smite \Smite\ (sm[imac]t), v. t. [imp. {Smote} (sm[=o]t), rarely<br />
   {Smit} (sm[i^]t); p. p. {Smitten} (sm[i^]t&#8221;t&#8217;n), rarely<br />
   {Smit}, or {Smote}; p. pr. &#038; vb. n. {Smiting}<br />
   (sm[imac]t&#8221;[i^]ng).] [AS. sm[=i]tan to smite, to soil,<br />
   pollute; akin to OFries. sm[=i]ta to smite, LG. smiten, D.<br />
   smijten, G. schmeissen, OHG. sm[=i]zan to smear, stroke, OSw.<br />
   &#038; dial. Sw. smita to smite, Dan. smide to throw, Goth.<br />
   bismeitan, to anoint, besmear; cf. Skr. m[=e]d to be fat. The<br />
   original sense seems to have been, to daub on, to smear. Cf.<br />
   {Smut}.]<br />
   1. To strike; to inflict a blow upon with the hand, or with<br />
      any instrument held in the hand, or with a missile thrown<br />
      by the hand; as, to smite with the fist, with a rod,<br />
      sword, spear, or stone.<br />
      [1913 Webster]</p>
<p>            Whosoever shall smite thee on thy right cheek, turn<br />
            to him the other also.                &#8211;Matt. v. 39.<br />
      [1913 Webster]</p>
<p>            And David . . . took thence a stone, and slang it,<br />
            and smote the Philistine in his forehead. &#8211;1 Sam.<br />
                                                  xvii. 49.<br />
      [1913 Webster]</p>
<p>   2. To cause to strike; to use as an instrument in striking or<br />
      hurling.<br />
      [1913 Webster]</p>
<p>            Prophesy, and smite thine hands together. &#8211;Ezek.<br />
                                                  xxi. 14.<br />
      [1913 Webster]</p>
<p>            Saul . . . smote the javelin into the wall. &#8211;1 Sam.<br />
                                                  xix. 10.<br />
      [1913 Webster]</p>
<p>   3. To destroy the life of by beating, or by weapons of any<br />
      kind; to slay by a blow; to kill; as, to smite one with<br />
      the sword, or with an arrow or other instrument.<br />
      [1913 Webster]</p>
<p>   4. To put to rout in battle; to overthrow by war.<br />
      [1913 Webster]</p>
<p>   5. To blast; to destroy the life or vigor of, as by a stroke<br />
      or by some visitation.<br />
      [1913 Webster]</p>
<p>            The flax and the barly was smitten.   &#8211;Ex. ix. 31.<br />
      [1913 Webster]</p>
<p>   6. To afflict; to chasten; to punish.<br />
      [1913 Webster]</p>
<p>            Let us not mistake God&#8217;s goodness, nor imagine,<br />
            because he smites us, that we are forsaken by him.<br />
                                                  &#8211;Wake.<br />
      [1913 Webster]</p>
<p>   7. To strike or affect with passion, as love or fear.<br />
      [1913 Webster]</p>
<p>            The charms that smite the simple heart. &#8211;Pope.<br />
      [1913 Webster]</p>
<p>            Smit with the love of sister arts we came. &#8211;Pope.<br />
      [1913 Webster]</p>
<p>   {To smite off}, to cut off.</p>
<p>   {To smite out}, to knock out, as a tooth. &#8211;Exod. xxi. 27.</p>
<p>   {To smite with the tongue}, to reproach or upbraid; to<br />
      revile. [Obs.] &#8211;Jer. xviii. 18.<br />
      [1913 Webster]</p>
<p>Smote \Smote\,<br />
   imp. (&#038; rare p. p.) of {Smite}.<br />
   [1913 Webster]</p>
<p>smite<br />
     v 1: inflict a heavy blow on, with the hand, a tool, or a weapon<br />
     2: affect suddenly with deep feeling; &#8220;He was smitten with love<br />
        for this young girl&#8221;<br />
     3: cause pain or suffering in; &#8220;afflict with the plague&#8221;; &#8220;That<br />
        debasement of the verbal currency that afflicts terms used<br />
        in advertisement&#8221; [syn: {afflict}]<br />
     [also: {smote}, {smitten}, {smit}]</p>
<p>smote<br />
     See {smite}</p>
<p>The results are lengthy, but for right now, it&#8217;s all that I want.  And nay, I shan&#8217;t complain!</p>
<p>It was quick and easy, and as long as I use it less than several thousand times per day, I am operating well within the <a href="http://services.aonaware.com/DictService/tos.htm">terms of service</a>.</p>
<p>Till next time!</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fcommand-line-dictionary-using-groovy-ws%2F&amp;title=Command+Line+Dictionary+Using+Groovy+WS" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fcommand-line-dictionary-using-groovy-ws%2F&amp;title=Command+Line+Dictionary+Using+Groovy+WS" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fcommand-line-dictionary-using-groovy-ws%2F&amp;title=Command+Line+Dictionary+Using+Groovy+WS" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fcommand-line-dictionary-using-groovy-ws%2F&amp;title=Command+Line+Dictionary+Using+Groovy+WS" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fcommand-line-dictionary-using-groovy-ws%2F&amp;title=Command+Line+Dictionary+Using+Groovy+WS', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fcommand-line-dictionary-using-groovy-ws%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fcommand-line-dictionary-using-groovy-ws%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fcommand-line-dictionary-using-groovy-ws%2F&amp;title=Command+Line+Dictionary+Using+Groovy+WS" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fcommand-line-dictionary-using-groovy-ws%2F&amp;title=Command+Line+Dictionary+Using+Groovy+WS" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/general/command-line-dictionary-using-groovy-ws/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Understanding OpenJPA InvalidStateException: Detected reentrant flush</title>
		<link>http://www.reverttoconsole.com/blog/hibernate-jpa/understanding-openjpa-invalidstateexception-detected-reentrant-flush/</link>
		<comments>http://www.reverttoconsole.com/blog/hibernate-jpa/understanding-openjpa-invalidstateexception-detected-reentrant-flush/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 18:37:22 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Hibernate/JPA]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=995</guid>
		<description><![CDATA[Ran into this issue today: &#60;openjpa-1.2.2-r422266:898935 fatal user error&#62; org.apache.openjpa.persistence.InvalidStateException: Detected reentrant flush. Make sure your flush-time instance callback methods or event listeners do not invoke any operations that require the in-progress flush to complete. at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:1923) at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1698) at org.apache.openjpa.kernel.QueryImpl.isInMemory(QueryImpl.java:956) at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:838) at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:779) at org.apache.openjpa.kernel.DelegatingQuery.execute(DelegatingQuery.java:525) This is a tricky exception since the verbose [...]]]></description>
			<content:encoded><![CDATA[<p>Ran into this issue today:</p>
<pre>
&lt;openjpa-1.2.2-r422266:898935 fatal user error&gt; org.apache.openjpa.persistence.InvalidStateException: Detected reentrant flush.  Make sure your flush-time instance callback methods or event listeners do not invoke any operations that require the in-progress flush to complete.
	at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:1923)
	at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1698)
	at org.apache.openjpa.kernel.QueryImpl.isInMemory(QueryImpl.java:956)
	at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:838)
	at org.apache.openjpa.kernel.QueryImpl.execute(QueryImpl.java:779)
	at org.apache.openjpa.kernel.DelegatingQuery.execute(DelegatingQuery.java:525)
</pre>
<p>This is a tricky exception since the verbose description does not clarify the intent.</p>
<p><strong>The problem:</strong><br />
I had to write my own Auditing since we weren&#8217;t using Hibernate (and so no <a href="http://www.jboss.org/envers">Envers</a>) but openjpa 1.2.2. Don&#8217;t ask me why. It&#8217;s a big financial company and they like Websphere 7 (which &#8220;ships&#8221; openjpa 1.2). </p>
<p>A sample &#8220;Profile&#8221; entity</p>
<pre>
@Entity
@EntityListeners({ProfileAuditListener.class})
public class Profile implements Serializable {
 ...
}
</pre>
<p>The standard JPA Entity Listener:</p>
<pre>
@Named
public class ProfileAuditListener implements ApplicationContextAware {
        private ProfileAuditDao auditDao;

	@PostUpdate
	@Transactional
	public void postUpdate(Profile newProfile) {
	    ProfileAudit audit = new ProfileAudit();
	    ...
    	    ...
   	    Profile oldProfile = profileDao.read(newProfile.getEmail());
            // InvalidStateException thrown above
            ...
            // Compare field by field for editable fields
	    ...	

	    auditDao.audit(audit);
	}
}
</pre>
<p>A simple Dao</p>
<pre>
@Repository(&quot;profileDao&quot;)
public class JPAProfileDao implements ProfileDao {

	@Transactional(readOnly = true)
	public Profile read(String email) {
		List&lt;Profile&gt; profiles = em.createNamedQuery(&quot;findByEmail&quot;).setParameter(&quot;email&quot;, email);
		if (profiles.size() != 0) {
			return profiles.get(0);
		}
		return null;
	}
}
</pre>
<p>As you can see, nothing fancy here. An Audit interceptor trying to see the difference in &#8216;Profile&#8217; properties just after updated the entity in db. However an exception is thrown where I execute a read-only Transactional query.</p>
<p><strong>Explanation:</strong><br />
The exception indicates that the event listener might be executing a flush accidentally from another operation and OpenJPA doesnt allow a flush to occur during a flush. Wait, a <em>flush</em>? But I&#8217;m not <em>flushing </em>anywhere, in fact &#8212; I think it&#8217;s all <em>default </em>flushing. </p>
<p>That&#8217;s the catch. The default querying in openjpa is FlushModeType.AUTO and that causes a flush to occur even if it&#8217;s a @Transactional(readOnly=true)</p>
<p><strong>Solution:</strong><br />
set the flush mode to FlushModeType.COMMIT on that particular query.</p>
<p>You can also set a <a href="http://openjpa.apache.org/builds/1.2.2/apache-openjpa-1.2.2/docs/manual/manual.html#ref_guide_dbsetup_retain">system wide property</a> like setting false flushBeforeQueries = true in persistence.xml but I wouldn&#8217;t recommend that unless you want this behavior explicitly. For instance, my unit tests needed the auto flush to work since I persist and read in the same transaction (Spring Transactional tests).</p>
<p>In general, your use case might be different from mine but the underlying concept is same. Look for the accidental flushes from openjpa. If in doubt, always tune up the DEBUG logging.</p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Funderstanding-openjpa-invalidstateexception-detected-reentrant-flush%2F&amp;title=Understanding+OpenJPA+InvalidStateException%3A+Detected+reentrant+flush" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Funderstanding-openjpa-invalidstateexception-detected-reentrant-flush%2F&amp;title=Understanding+OpenJPA+InvalidStateException%3A+Detected+reentrant+flush" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Funderstanding-openjpa-invalidstateexception-detected-reentrant-flush%2F&amp;title=Understanding+OpenJPA+InvalidStateException%3A+Detected+reentrant+flush" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Funderstanding-openjpa-invalidstateexception-detected-reentrant-flush%2F&amp;title=Understanding+OpenJPA+InvalidStateException%3A+Detected+reentrant+flush" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Funderstanding-openjpa-invalidstateexception-detected-reentrant-flush%2F&amp;title=Understanding+OpenJPA+InvalidStateException%3A+Detected+reentrant+flush', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Funderstanding-openjpa-invalidstateexception-detected-reentrant-flush%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Funderstanding-openjpa-invalidstateexception-detected-reentrant-flush%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Funderstanding-openjpa-invalidstateexception-detected-reentrant-flush%2F&amp;title=Understanding+OpenJPA+InvalidStateException%3A+Detected+reentrant+flush" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fhibernate-jpa%2Funderstanding-openjpa-invalidstateexception-detected-reentrant-flush%2F&amp;title=Understanding+OpenJPA+InvalidStateException%3A+Detected+reentrant+flush" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/hibernate-jpa/understanding-openjpa-invalidstateexception-detected-reentrant-flush/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Mock Unit Testing Services and Daos with Mockito and Spring 3</title>
		<link>http://www.reverttoconsole.com/blog/spring/mock-unit-testing-services-and-daos-with-mockito-and-spring-3/</link>
		<comments>http://www.reverttoconsole.com/blog/spring/mock-unit-testing-services-and-daos-with-mockito-and-spring-3/#comments</comments>
		<pubDate>Mon, 09 May 2011 14:46:02 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[UnitTest]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=984</guid>
		<description><![CDATA[If you haven&#8217;t been mocking yet, check this out. There are other tools in Groovy using DSLs but if you want to stick to Java, Mockito is by far the best BDD-style mock unit testing tool. Traditional examples provide a List mocking example or foo/bar example which I find it mostly annoying since it doesn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t been <em>mocking </em>yet, check <a href="http://www.mockito.org/">this </a>out. There are other tools in Groovy using DSLs but if you want to stick to Java, Mockito is by far the best BDD-style mock unit testing tool.  </p>
<p>Traditional examples provide a List mocking example or foo/bar example which I find it mostly annoying since it doesn&#8217;t teach you how to solve real problems. And the documentation is verbose and crams with unnecessary features confusing us further. In this tutorial, I&#8217;ll dive straight into a relevant example of mock testing Daos in Service layer. I&#8217;m not a big fan of Daos anymore (after the advent of JPA), however for the purposes of this tutorial, it&#8217;ll be easier to explain.</p>
<p>Consider a Profile entity (like facebook user profile) with daos/services: ProfileDao/JPAProfileDao, ProfileService/ProfileServiceImpl. To complicate things further, say you are using DTOs since it&#8217;s a client server app with a GWT front end. You might need a simple mapper class. Let&#8217;s call it ProfileMapper/ProfileMapperImpl. </p>
<pre>
@Service("profileService")
public class ProfileServiceImpl implements ProfileService {
	private final ProfileDao profileDao;
	private final ProfileMapper profileMapper;

	@Inject
	public ProfileServiceImpl(final ProfileDao profileDao, final ProfileMapper profileMapper) {
		this.profileDao = profileDao;
		this.profileMapper = profileMapper;
	}

	@Transactional
	public void create(ProfileDto profile) throws DuplicateProfileException {
		if (profile == null) {
			throw new IllegalArgumentException("profile cannot be null.");
		}

		Profile profile = profileMapper.toEntity(profile);
		// set default state as active
		profile .setIsActive(true);

		try {
			profileDao.save(profile);
		}
		catch (DuplicateKeyException e) {
			logger.warn("Unable to save profile with userId: " + profile.getUserId() + " already exists.");
			throw new DuplicateProfileException();
		}
		logger.debug("Profile saved successfully.");
	}

	@Transactional(readOnly = true)
	public ProfileDto read(String userId) throws InvalidProfileException {
		validateProfileInfo(userId);

		ProfileDto profileDto = null;
		Profile profile = profileDao.read(userId);
		if (profile != null) {
			profileDto = profileMapper.fromEntity(profile);
			logger.debug("Profile retrieved successfully.");
		}
		else {
			logger.debug("...");
		}
		return profileDto;
	}

	...
}
</pre>
<p>Now, in order to test ProfileService, you need to mock out ProfileMapper and ProfileDao, right? Let&#8217;s see how we do this in a simple JUnit 4.4+ test.</p>
<pre>
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class ProfileServiceTest {

	@Mock
	ProfileDao profileDao;

	@Mock
	ProfileMapper profileMapper;

	// Can't use @InjectMocks because Mockito doesn't support constructor injection
	// As a workaround use @Before below to initialize service with stubs
	ProfileService profileService;

	@Before
	public void init() {
		profileService = new ProfileServiceImpl(profileDao, profileMapper);
	}

	@Test
	public void testRead() throws InvalidProfileException {
		// Simulate InvalidProfileException
		try {
			profileService.read("");
			fail(); // should never execute
		}
		catch (InvalidProfileException e) {
			e.getMessage(); // expected
		}

		// Given
		Profile profile = TestData.createTestProfile("userid"); // test utility to create a test Profile
		when(profileDao.read("userid")).thenReturn(profile);
		when(profileMapper.fromEntity(profile )).thenReturn(TestData.createTestProfileDto("userid"));

		// When
		ProfileDto dto = profileService.read("userid");

		// Then
		assertEquals(dto.getUserId(), "userid");
	}
}
</pre>
<p>Explanation:<br />
1) Wrapping your test with @RunWith(MockitoJUnitRunner.class) helps create the mock initialization through annotation scanning (@Mock, @InjectMocks)<br />
2) Add @Mock annotations for the components to mock. In this case profileDao, profileMapper<br />
3) As of 1.8.5, Mockito doesn&#8217;t provide @InjectMock with construction injection. @Before test initializer is a workaround to inject ProfileService with mocks. Note that this will not be required if ProfileService has setter/getter injection of dependencies. However, I prefer JSR330 construction injection which is a <a href="http://martinfowler.com/articles/injection.html#ConstructorVersusSetterInjection">best practice </a>.<br />
4) The actual @Test class with mockito stubs. Let&#8217;s dig deep into this.</p>
<p>As a template, it&#8217;s a good practice to view tests like a BDD style test. </p>
<pre>
// Given 

// When

// Then
</pre>
<p>The above template forces you to think on the explicit conditions during which we run our unit test.</p>
<p>Next, we need to figure out a way to stub our mock component&#8217;s methods,</p>
<pre>
when(operation).thenReturn(object)
</pre>
<p>In our example we want to mock profileDao.read(userId). So that translates to</p>
<pre>
when(profileDao.read("userid")).thenReturn(profile);
</pre>
<p>Note that we&#8217;re letting the mocked dao return a profile object that we just created in the previous step. This will be 50% of most of your mocking use cases.</p>
<p>The next common used use case is to simulate exceptions from the mocked classes. Consider a test for create(&#8230;) that simulates the DuplicateProfileException.          </p>
<pre>
@Test
	public void testCreateDuplicate() {
		// Given
		ProfileDto dto = TestData.createTestProfileDto("userid");
		Profile profile = TestData.createTestProfile("userid");
		when(profileMapper.toEntity(dto)).thenReturn(profile);
		doThrow(new DuplicateKeyException("duplicate profile")).when(profileDao).save(profile);

		// When
		try {
			profileService.create(dto);
			assertEquals(1, 2); // should never execute
		}
		// Then
		catch (DuplicateProfileException e) {
			e.getMessage();
		}
	}
</pre>
<p>Notice the line</p>
<pre>
doThrow(new DuplicateKeyException("duplicate profile")).when(profileDao).save(profile);
</pre>
<p>Quite simple, isn&#8217;t it? </p>
<p>If you&#8217;ve read so far, you can succuessfully write mock unit tests for 80% of your use cases. There are other advanced features like finding <a href="http://www.mockito.org/">redundant invocations</a>, spying on objects to simulate partial mocking, most of which I don&#8217;t see implementing for majority of my use cases. </p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fspring%2Fmock-unit-testing-services-and-daos-with-mockito-and-spring-3%2F&amp;title=Mock+Unit+Testing+Services+and+Daos+with+Mockito+and+Spring+3" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/spring/mock-unit-testing-services-and-daos-with-mockito-and-spring-3/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Blogging With Org Mode and Emacs</title>
		<link>http://www.reverttoconsole.com/blog/general/blogging-with-org-mode-and-emacs/</link>
		<comments>http://www.reverttoconsole.com/blog/general/blogging-with-org-mode-and-emacs/#comments</comments>
		<pubDate>Sun, 17 Apr 2011 04:31:00 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=948</guid>
		<description><![CDATA[Org Mode is a really nice mode for emacs, I use it daily to keep todo lists, but it does a lot more. For this post I&#8217;m not going to talk about the details of org mode, but if you&#8217;re not familiar with it and are interested, I found Abhijeet Chavan&#8217;s article on linuxjournal to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://orgmode.org">Org Mode</a> is a really nice mode for emacs, I use it daily to keep todo lists, but it does a lot more. For this post I&#8217;m not going to talk about the details of org mode, but if you&#8217;re not familiar with it  and are interested, I found <a href="http://www.linuxjournal.com/article/9116">Abhijeet Chavan&#8217;s article on linuxjournal</a> to be a great starting point. </p>
<p> To get started, you don&#8217;t need to add much more to your .emacs than this: </p>
<pre class="example">
<pre>
(add-to-list 'load-path "~/.emacs.d/vendor/org-7.5/lisp")

(add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
</pre>
</pre>
<p> I recently discovered <a href="https://github.com/punchagan/org2blog">org2blog</a>, a means of publishing blog posts to wordpress from within org mode.  I guess it&#8217;s now technically org2blog/wp, so as not to be confused with another org2blog for blogger,  but whatever. </p>
<p> I added this for org2blog: </p>
<pre class="example">
<pre>
(require 'org2blog-autoloads)

(setq org2blog/wp-blog-alist
      '(("wordpress"
         :url "http://myblog.com/xmlrpc.php"
         :username "username"
         :default-categories ("emacs"))))
(setq org2blog/wp-use-tags-as-categories t)
</pre>
</pre>
<p> <span style="text-decoration:underline;">wordpress</span> above is the name of the entry, you&#8217;ll use it later. </p>
<p> And lastly, because I work behind a strict firewall, my proxy info: </p>
<p>
<pre> (setq url-proxy-services '(("http" . "my.awesome.proxy:8081"))) </pre>
</p>
<p> To get started, I&#8217;d recommended reading <a href="https://github.com/punchagan/org2blog">the instructions on the github page</a>,  but quickly: </p>
<ol>
<li>Login- <b>M-x org2blog/wp-login</b>. It will prompt you for the entry, and then your password. </li>
<li><b>M-x org2blog/wp-new-entry</b>. Give your post a title, write something. </li>
<li><b>C-c d</b> to post buffer as draft. It will prompt you to preview in a browser. Do that. </li>
<li><b>C-c p</b> publish away! </li>
</ol></div>
<p> </body> </html> </p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fblogging-with-org-mode-and-emacs%2F&amp;title=Blogging+With+Org+Mode+and+Emacs" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fblogging-with-org-mode-and-emacs%2F&amp;title=Blogging+With+Org+Mode+and+Emacs" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fblogging-with-org-mode-and-emacs%2F&amp;title=Blogging+With+Org+Mode+and+Emacs" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fblogging-with-org-mode-and-emacs%2F&amp;title=Blogging+With+Org+Mode+and+Emacs" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fblogging-with-org-mode-and-emacs%2F&amp;title=Blogging+With+Org+Mode+and+Emacs', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fblogging-with-org-mode-and-emacs%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fblogging-with-org-mode-and-emacs%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fblogging-with-org-mode-and-emacs%2F&amp;title=Blogging+With+Org+Mode+and+Emacs" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fgeneral%2Fblogging-with-org-mode-and-emacs%2F&amp;title=Blogging+With+Org+Mode+and+Emacs" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/general/blogging-with-org-mode-and-emacs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Accessing Github Using Corkscrew for SSH Tunneling Over HTTP</title>
		<link>http://www.reverttoconsole.com/blog/tools/accessing-github-using-corkscrew-for-ssh-tunneling-over-http/</link>
		<comments>http://www.reverttoconsole.com/blog/tools/accessing-github-using-corkscrew-for-ssh-tunneling-over-http/#comments</comments>
		<pubDate>Sun, 17 Apr 2011 03:45:09 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=941</guid>
		<description><![CDATA[In my last post, I showed how to use corkscrew to access a remote host via an http_proxy. To extend this example, I wanted to use git and my github account. I can do this because github was nice enough to have port 443 available for ssh. Like in my example before, I created a [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.reverttoconsole.com/blog/tools/tunneling-ssh-over-http-proxies-with-corkscrew/">last post</a>, I showed how to use <a href="http://www.agroman.net/corkscrew/">corkscrew</a> to access a remote host via an http_proxy.</p>
<p>To extend this example, I wanted to use git and <a href="https://github.com/jeffhemminger">my github account</a>. I can do this because github was nice enough to have port 443 available for ssh.</p>
<p>Like in my example before, I created a config entry for github:</p>
<pre>
host gh
     user git
     hostname ssh.github.com
     port 443
     proxycommand corkscrew my.http.proxy 8081 %h %p ~/.ssh/proxyauth
</pre>
<p>From there it&#8217;s really easy:</p>
<pre>
> git clone gh:jeffhemminger/dot-emacs.git
</pre>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Faccessing-github-using-corkscrew-for-ssh-tunneling-over-http%2F&amp;title=Accessing+Github+Using+Corkscrew+for+SSH+Tunneling+Over+HTTP" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Faccessing-github-using-corkscrew-for-ssh-tunneling-over-http%2F&amp;title=Accessing+Github+Using+Corkscrew+for+SSH+Tunneling+Over+HTTP" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Faccessing-github-using-corkscrew-for-ssh-tunneling-over-http%2F&amp;title=Accessing+Github+Using+Corkscrew+for+SSH+Tunneling+Over+HTTP" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Faccessing-github-using-corkscrew-for-ssh-tunneling-over-http%2F&amp;title=Accessing+Github+Using+Corkscrew+for+SSH+Tunneling+Over+HTTP" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Faccessing-github-using-corkscrew-for-ssh-tunneling-over-http%2F&amp;title=Accessing+Github+Using+Corkscrew+for+SSH+Tunneling+Over+HTTP', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Faccessing-github-using-corkscrew-for-ssh-tunneling-over-http%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Faccessing-github-using-corkscrew-for-ssh-tunneling-over-http%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Faccessing-github-using-corkscrew-for-ssh-tunneling-over-http%2F&amp;title=Accessing+Github+Using+Corkscrew+for+SSH+Tunneling+Over+HTTP" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Faccessing-github-using-corkscrew-for-ssh-tunneling-over-http%2F&amp;title=Accessing+Github+Using+Corkscrew+for+SSH+Tunneling+Over+HTTP" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/tools/accessing-github-using-corkscrew-for-ssh-tunneling-over-http/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tunneling SSH Over HTTP Proxies With Corkscrew</title>
		<link>http://www.reverttoconsole.com/blog/tools/tunneling-ssh-over-http-proxies-with-corkscrew/</link>
		<comments>http://www.reverttoconsole.com/blog/tools/tunneling-ssh-over-http-proxies-with-corkscrew/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 03:44:18 +0000</pubDate>
		<dc:creator>Jeff</dc:creator>
				<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=932</guid>
		<description><![CDATA[In some work situations it&#8217;s necessary to implement strict firewalls that block, for example, common ssh ports. In such situations it&#8217;s common that you&#8217;ll be provided with an http-proxy, and this can be used if necessary to tunnel SSH. I&#8217;ve recently had to do this, and this is how I did it, after installing corkscrew: [...]]]></description>
			<content:encoded><![CDATA[<p>In some work situations it&#8217;s necessary to implement strict firewalls that block, for example, common ssh ports.</p>
<p>In such situations it&#8217;s common that you&#8217;ll be provided with an http-proxy, and this can be used if necessary to tunnel SSH.</p>
<p>I&#8217;ve recently had to do this, and this is how I did it, after installing <a href="http://www.agroman.net/corkscrew/">corkscrew</a>:</p>
<p>Create a config file in ~/.ssh</p>
<pre>
host myremoteserver
    user username
    hostname my.remote.domain
    port 443
    proxycommand corkscrew my.http.proxy 8081 %h %p ~/.ssh/proxyauth
</pre>
<p>Create an auth file containing your proxy username and password (I added mine to ~/.ssh/proxyauth in the above example)</p>
<pre>
username:password
</pre>
<p>Now, to ssh to the remote server:</p>
<pre>
ssh myremoteserver
</pre>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Ftunneling-ssh-over-http-proxies-with-corkscrew%2F&amp;title=Tunneling+SSH+Over+HTTP+Proxies+With+Corkscrew" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Ftunneling-ssh-over-http-proxies-with-corkscrew%2F&amp;title=Tunneling+SSH+Over+HTTP+Proxies+With+Corkscrew" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Ftunneling-ssh-over-http-proxies-with-corkscrew%2F&amp;title=Tunneling+SSH+Over+HTTP+Proxies+With+Corkscrew" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Ftunneling-ssh-over-http-proxies-with-corkscrew%2F&amp;title=Tunneling+SSH+Over+HTTP+Proxies+With+Corkscrew" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Ftunneling-ssh-over-http-proxies-with-corkscrew%2F&amp;title=Tunneling+SSH+Over+HTTP+Proxies+With+Corkscrew', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Ftunneling-ssh-over-http-proxies-with-corkscrew%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Ftunneling-ssh-over-http-proxies-with-corkscrew%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Ftunneling-ssh-over-http-proxies-with-corkscrew%2F&amp;title=Tunneling+SSH+Over+HTTP+Proxies+With+Corkscrew" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Ftools%2Ftunneling-ssh-over-http-proxies-with-corkscrew%2F&amp;title=Tunneling+SSH+Over+HTTP+Proxies+With+Corkscrew" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/tools/tunneling-ssh-over-http-proxies-with-corkscrew/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Database Surrogate keys Vs Natural keys</title>
		<link>http://www.reverttoconsole.com/blog/database/database-surrogate-keys-vs-natural-keys/</link>
		<comments>http://www.reverttoconsole.com/blog/database/database-surrogate-keys-vs-natural-keys/#comments</comments>
		<pubDate>Tue, 12 Apr 2011 18:06:07 +0000</pubDate>
		<dc:creator>Priyatam</dc:creator>
				<category><![CDATA[Database]]></category>

		<guid isPermaLink="false">http://www.reverttoconsole.com/?p=993</guid>
		<description><![CDATA[Ran into this issue at my client recently and it was hard to convince the db admin why surrogate keys was an advantage for a developer working in an ORM solution Natural key - business requirements changes, then you have to change the natural key - not easy to index an alphanumeric or String value [...]]]></description>
			<content:encoded><![CDATA[<p>Ran into this issue at my client recently and it was hard to convince the db admin why surrogate keys was an advantage for a developer working in an ORM solution</p>
<p><strong>Natural key</strong><br />
- business requirements changes, then you have to change the natural key<br />
- not easy to index an alphanumeric or String value<br />
- can&#8217;t expose the natural key to end users who can then guess the business key and use for querying undesireable data<br />
- you can&#8217;t rename the type without changing everything<br />
- If using strings, joins are a bit slower as compared to the int data-type joins, storage is more as well.  Since storage is more, less data-values get stored per index page.  Also, reading strings is a two step process in some RDBMS: one to get the actual length of the string and second to actually perform the read operation to get the value.<br />
- Locking contentions can arise if using application driven generation mechanism for the key.<br />
- Can’t enter a record until value is known since the value has some meaning. </p>
<p><strong>Surrogate key</strong><br />
- A surrogate key is immune to changes in business. In addition, the key depends on only one field, so it’s compact. The auto-incrementing field provides a unique, stable, and compact primary key.<br />
- Business Logic is not in the keys.<br />
- Small 4-byte key (the surrogate key will most likely be an integer and SQL Server for example requires only 4 bytes to store it, if a bigint, then 8 bytes).<br />
- Joins are very fast.<br />
- No locking contentions because of unique constraint (this refers to the waits that get developed when two sessions are trying to insert the same unique business key) as the surrogates get generated by the DB and are cached. Very scalable. </p>
<p>Not to mention, for surrogate keys, a Java developer could assume and code several reusable strategies:<br />
- Have a common BaseIdEntity with an @Id attribute with a common generation strategy or named sequence generators<br />
- Have Base generic services or daos (FooServiceImpl extends BaseServiceImpl<Foo>)<br />
- Generic finder methods with named queries<br />
- And many other referential lookups that can be streamlined once a common id is used</p>
<p>References:<br />
<a href="http://www.techrepublic.com/article/the-great-primary-key-debate/1045050">The great primary key debate</a></p>

<span class="slashdigglicious">
<a href="http://slashdot.org/bookmark.pl?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fdatabase%2Fdatabase-surrogate-keys-vs-natural-keys%2F&amp;title=Database+Surrogate+keys+Vs+Natural+keys" title="Slashdot It!"><img src="http://slashdot.org/favicon.ico" height="16" width="16" alt="[Slashdot]" /></a>
<a href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fdatabase%2Fdatabase-surrogate-keys-vs-natural-keys%2F&amp;title=Database+Surrogate+keys+Vs+Natural+keys" title="Digg This Story"><img src="http://digg.com/favicon.ico" width="16" height="16" alt="[Digg]" /></a>
<a href="http://reddit.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fdatabase%2Fdatabase-surrogate-keys-vs-natural-keys%2F&amp;title=Database+Surrogate+keys+Vs+Natural+keys" title="Reddit"><img src="http://reddit.com/favicon.ico" width="16" height="16" alt="[Reddit]" /></a>
<a href="http://del.icio.us/post?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fdatabase%2Fdatabase-surrogate-keys-vs-natural-keys%2F&amp;title=Database+Surrogate+keys+Vs+Natural+keys" title="Save to del.icio.us" onclick="window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fdatabase%2Fdatabase-surrogate-keys-vs-natural-keys%2F&amp;title=Database+Surrogate+keys+Vs+Natural+keys', 'delicious', 'toolbar=no,width=700,height=400'); return false;"><img src="http://images.del.icio.us/static/img/delicious.small.gif" width="16" height="16" alt="[del.icio.us]" /></a>
<a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fdatabase%2Fdatabase-surrogate-keys-vs-natural-keys%2F" title="Share on Facebook"><img src="http://www.facebook.com/favicon.ico" width="16" height="16" alt="[Facebook]" /></a>
<a href="http://technorati.com/faves?add=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fdatabase%2Fdatabase-surrogate-keys-vs-natural-keys%2F" title="Add to my Technorati Favorites"><img src="http://technorati.com/favicon.ico" width="16" height="16" alt="[Technorati]" /></a>
<a href="http://www.google.com/bookmarks/mark?op=edit&amp;output=popup&amp;bkmk=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fdatabase%2Fdatabase-surrogate-keys-vs-natural-keys%2F&amp;title=Database+Surrogate+keys+Vs+Natural+keys" title="Save to Google Bookmarks"><img src="http://www.google.com/favicon.ico" width="16" height="16" alt="[Google]" /></a>
<a href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.reverttoconsole.com%2Fblog%2Fdatabase%2Fdatabase-surrogate-keys-vs-natural-keys%2F&amp;title=Database+Surrogate+keys+Vs+Natural+keys" title="Stumble it!"><img src="http://www.stumbleupon.com/favicon.ico" width="16" height="16" alt="[StumbleUpon]" /></a>
</span>]]></content:encoded>
			<wfw:commentRss>http://www.reverttoconsole.com/blog/database/database-surrogate-keys-vs-natural-keys/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

