Social Icons

Pages

Featured Posts

Thursday, October 30, 2014

Identifying duplicate rows in a table

select column-name from table group by column-name having count(*) > 1;

Thursday, October 23, 2014

JAX-RS 2.0 and HTTP PATCH

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" : "/firstName", "value" : "John"},
{"op" : "replace", "path" : "/zipcode",   "value" : "94555"},
{"op" : "add",     "path" : "/phone",     "value" : "888-999-1234"},
{"op" : "remove",  "path" : "/hobby"},
{"op" : "copy", "from"    : "/primayAddress", "to" : "/secondaryAddress"},
{"op" : "move", "from"    : "/mobilePhone",   "to" : "/primaryPhone"}
In this post, I discuss a generic framework to patch a single resource.

Environment

  1. JAX-RS 2.0
  2. Jackson JSON Processor
  3. json-patch (https://github.com/fge/json-patch) implementing RFC6902

Model

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

Implementation

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@HttpMethod("PATCH")
@Documented
@NameBinding
public @interface PATCH {
}

@Produces('application/json")
public class UserResource {
    @Inject private UserManager userManager;

    @PATCH
    @Path("/users/{username}")
    @Transactional
    public 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 = userManager.save(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"
        class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
    <constructor-arg value="/login.jsp" />
  </bean>

  <bean id="ajaxEntryPoint"
        class="com.mycompany.AjaxAuthenticationEntryPoint" />
  
  <bean id="authenticationRequestCache"
        class="org.springframework.security.web.savedrequest.HttpSessionRequestCache">
    <property name="requestMatcher" ref="ajaxRequestMatcher" />
  </bean>

  <bean id="authenticationEntryPoint"
        class="org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint">
    <constructor-arg>
      <map>
        <entry key-ref="ajaxRequestMatcher" value-ref="ajaxEntryPoint" />
      </map>
    </constructor-arg>
    <property name="defaultEntryPoint" ref="loginEntryPoint" />
  </bean>

  <security:http entry-point-ref="authenticationEntryPoint">
    <security:intercept-url
        access="IS_AUTHENTICATED_REMEMBERED"
        pattern="/secure/**"/>

    <security:form-login
        login-page="/login.jsp"/>
    <security:logout/>

  </security:http>

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 {
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException)
        throws IOException, ServletException {    

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

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setHeader("Cache-control", "no-cache");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        response.getWriter().print(json);
        response.getWriter().flush();
        response.getWriter().close();
    }
}



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"/>
</security:authentication-manager>

<bean id="adAuthenticationProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
  <constructor-arg value="mycompany.com"/>
  <constructor-arg value="ldap://my-company-active-directory-url"/>
  <property name="useAuthenticationRequestCredentials" value="true"/>
  <property name="convertSubErrorCodesToExceptions" value="true"/>
</bean>

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 java.io.IOException;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;

@Named
@Provider
public class MyInterceptor implements ContainerRequestFilter {
    @Context
    private HttpServletRequest servletRequest;

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

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