Social Icons


Featured Posts

Thursday, October 23, 2014


When designing RESTful services, one of the scenario comes across is partial updates. Typical REST operations use the whole resource. Normally updates use PUT to modify the resource. More often, you need to do a GET before you modify the resource. This approach has a number of side effects. Increased chatter with the server, bandwidth issues, performance etc. If the resource is really big and you are only updating a few attributes, PUT is not a good idea.

Enter HTTP Patch. This is meant to address this, partial updates of resources.

A sample patch request

RFC 6902 defines a JSON document format for patching
{"op" : "test",    "path" : "/users/john/firstName", "value" : "John"},
{"op" : "replace", "path" : "/users/john/zipcode",   "value" : "94555"},
{"op" : "add",     "path" : "/users/john/phone",     "value" : "888-999-1234"},
{"op" : "remove",  "path" : "/users/john/hobby"},
{"op" : "copy", "from"    : "/users/john/primayAddress", "to" : "/users/john/secondaryAddress"},
{"op" : "move", "from"    : "/users/john/mobilePhone",   "to" : "/users/john/primaryPhone"}
In this post, I discuss a generic framework to patch a single resource.


  1. JAX-RS 2.0
  2. Jackson JSON Processor
  3. json-patch ( implementing RFC6902


public class User {
    private long id;
    private String username;
    private String firstName;
    private String phone;
    private String primaryAddress;
    private String secondaryAddress;
    private String mobilePhone;
    private String primaryPhone;
    private String hobby;

   // .. boiler plate code ..

Patch Framework

Steps involved in applying patch for a single resource:
  1. Define PATCH annotation
  2. Implement JAX-RS Resource
  3. Implement PATCH API
    • Read existing resource from back-end data store
    • Convert the resource to JSON
    • Use json-patch to apply the patch
    • Convert the patched JSON to Java class
    • Save the patched object to back-end data store


public @interface PATCH {

public class UserResource {
    @Inject private UserManager userManager;

    Response patch(@PathParam("username") String username, String json) {
        // get the user from DB
        User user = userManger.findByUsername(username);

         try {
             if (user != null) {
                 ObjectMapper mapper = new ObjectMapper();

                 // convert JSON string to a Java class
                 JsonPatch patch = mapper.readValue(json, JsonPatch.class);

                 // convert User to a JSON object
                 JsonNode userJson = mapper.valueToTree(user);

                 // apply patch
                 JsonNode patched = patch.apply(userJson);

                 // convert the patched object to User
                 user = mapper.readValue(patched.toString(), User.class);

                 // save the patched object
                 user =;
         }  catch (Exception ex) {
             throw new RuntimeException(ex);
         return Response.ok().build();

Monday, September 29, 2014

MySQL Import and Export

To import and export and entire database schema and data, follow these steps:
mysqldump -h host -u user -p --databases database-name > dump.sql # Export from a database
sed '/^\/\*\!50013 DEFINER/d' dump.sql > dump_0.sql # Fix the permission issues in case you have views
mysql -u user -p database-name < dump_0.sql         # Import to database

Tuesday, September 23, 2014

Spring Security and Ajax Session Expiry

One of the requirement in a recent project was to capture the Ajax session expiry and send a JSON response back to the client if the session was expired. There are a few different ways to handle this in Spring Security. Here is one approach

<bean id="ajaxRequestMatcher" class="com.mycompany.AjaxRequestMatcher"/>

  <bean id="loginEntryPoint"
    <constructor-arg value="/login.jsp" />

  <bean id="ajaxEntryPoint"
        class="com.mycompany.AjaxAuthenticationEntryPoint" />
  <bean id="authenticationRequestCache"
    <property name="requestMatcher" ref="ajaxRequestMatcher" />

  <bean id="authenticationEntryPoint"
        <entry key-ref="ajaxRequestMatcher" value-ref="ajaxEntryPoint" />
    <property name="defaultEntryPoint" ref="loginEntryPoint" />

  <security:http entry-point-ref="authenticationEntryPoint">



Java Classes

public class AjaxRequestMatcher implements RequestMatcher {
    public boolean matches(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

public class AjaxAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException)
        throws IOException, ServletException {    

        // form json string
        String json = ....

        response.setHeader("Cache-control", "no-cache");


Monday, September 15, 2014

Spring Security and Active Directory without Manager Username/Password

Recently I run into an issue to integrate an application with corporate LDAP. Typical LDAP requires a bind. If the server does not allow anonymous bind, then a manager/admin username and password must be supplied.

But when dealing with Active Directory, one can use the incoming user and password of an authentication request to do the binding. This is a non-standard way to integrate with a typical LDAP server. Spring Security has direct support for this type of configuration and setup.

<security:authentication-manager alias="authenticationManager">
  <security:authentication-provider ref="adAuthenticationProvider"/>

<bean id="adAuthenticationProvider" class="">
  <constructor-arg value=""/>
  <constructor-arg value="ldap://my-company-active-directory-url"/>
  <property name="useAuthenticationRequestCredentials" value="true"/>
  <property name="convertSubErrorCodesToExceptions" value="true"/>

Accessing Http Session In JAX-RS 2.0

JAX-RS 2.0 defines Filters and Interceptors. One can access the Http session by implementing a filter. For example:
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


public class MyInterceptor implements ContainerRequestFilter {
    private HttpServletRequest servletRequest;

    public void filter(ContainerRequestContext requestContext) throws IOException {
        HttpSession session = servletRequest.getSession(false);

        if (session != null) {
            // do stuff

Friday, September 5, 2014

Gradle and Embedded Jetty access log

The standard Jetty plugin for Gradle has limited features. For example, there seems to have no option to configure access logs with this plugin. Luckily there is a much more feature rich jetty plugin called JettyEclipse for Gradle. This can be found here. Configuring this plugin is quite easy. Add the following into your build.graddle.
buildscript {
    repositories {
    dependencies {
        classpath (group: 'com.sahlbach.gradle', name: 'gradle-jetty-eclipse-plugin', version: '1.9.+')
apply plugin: 'jettyEclipse'

jettyEclipse {
    System.setProperty("catalina.home", "${project.buildDir}")   
    requestLog = new File("${project.buildDir}/logs/access.log")

Then run gradle clean jettyEclipseRun

Handling Resources with Gradle

Gradle copies resources to a different directory than Maven. So when migrating from Maven, the source code needs to be changed to take care of the new resource locations. In order to keep the resources are copied to the correct location, add the following into your projects build.gradle file.

project.buildDir = 'target'

sourceSets {
    main {
        output.resourcesDir "${project.buildDir}/classes"
    test {
        output.resourcesDir "${project.buildDir}/classes/test"

Querydsl JPA Model Generation with Gradle

Querydsl is a very useful tool to write concise JPA queries. This requires a plugin to generate the meta model classes that will be referenced in the queries. There is a maven plugin to handle the code generation. But when using Gradle, this needs to be configured manually. Add this to the build.gradle file.
ext {
    generatedSourcesDir = file("${buildDir}/generated-sources")
    querydslVersion    = "3.4.2"
sourceSets {
    main {
        java {
            srcDir "src/main/java"
            srcDir generatedSourcesDir
configurations {
task generateQueryDSL(type: JavaCompile, group: 'build', description: 'Generates the QueryDSL query types') {
    source =
    classpath = configurations.compile + configurations.querydslapt
    options.compilerArgs = [
            "-processor", "com.mysema.query.apt.jpa.JPAAnnotationProcessor"
    destinationDir = generatedSourcesDir
compileJava {
    doFirst {
    options.compilerArgs += ['-s', generatedSourcesDir]

    dependsOn generateQueryDSL
dependencies {
      compile  "com.mysema.querydsl:querydsl-core:${querydslVersion}"
      compile  "com.mysema.querydsl:querydsl-jpa:${querydslVersion}"
      querydslapt  "com.mysema.querydsl:querydsl-apt:${querydslVersion}"