Wednesday, October 31, 2012

Partial implementation of Interface

Java Stuff: If you are implementing an interface and planning on not supporting all the methods, it a good practice to do the following for not implemented methods:
        throw new org.apache.commons.lang.NotImplementedException.NotImplementedException(
                  "method not implemented by This class");

More details here:
http://stackoverflow.com/questions/1062937/java-equivalent-to-nets-notsupportedexception

Tuesday, October 9, 2012

Git Tricks

I started maintaining a new page at Zoho docs to document my git learning:

Sunday, August 5, 2012

Code highlighting in Blogger

There are helpful instructions on the link below for high-lighting code in your blogger posts:
http://lukabloga.blogspot.com/2008/10/to-test-new-highlighting.html

UPDATE: I found GitHub Gist to be a faster and elegant alternative

There are other alternatives here:
http://stackoverflow.com/q/679189/747479

Stack Overflow rocks!

Saturday, August 4, 2012

Dealing with International Characters in Web Services [Java]

Recently, we had to develop an API where data (resource in RESTful terms) gets created with an emailId as a primary key and then a subsequent lookup is performed to access that resource.

There is an RFC that allows email ids to have international characters:

To support international characters in our API, we had to do the following:
We develop our web services in Java Servlets using the Spring Framework and deploy them using Tomcat. The Create (resource) API had the emailId in the requestBody and the lookup API was a HTTP GET call with the emailId in the URL. 

To get the Create (resource API) working, the client needs to make the request with the charset parameter in the ContentType header:
Content-Type: application/json; charset=utf-8

This instructs the Servlet container to treat the requestBody as an UTF8 encoded string. Without the charset parameter, the encoding is assumed to be ISO-8859-1 (default for Java Servlets). If you ever have to store the string in a DB or encrypt it, remember to retrieve the string in UTF8 encoding. String.getBytes("UTF-8") like stuff.

Now for the lookup API, where the emailId is in the URI, you need to keep two things in mind:
  1. Special characters in URIs are percent encoded.  For a non-ASCII character, it is typically converted to its byte sequence in UTF-8, and then each byte value is percent encoded.
  2. Instruct the Servlet container about the UTF8 URI encoding. This can be done by updating the HTTP connector in server.xml:
    <Connector connectionTimeout="20000" port="8080" 
    protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>
    

For additional insight, the below StackOverflow link has great nuggets of knowledge:
http://stackoverflow.com/questions/138948/how-to-get-utf-8-working-in-java-webapps/138950#138950

I did try the CharacterEncodingFilter filter approach but didn't get it to work. I did set it up as the first filter, also did the force encoding bit wasn't doing anything.

Wednesday, August 1, 2012

JUnit: test if a method throws correct exception

How do you write a JUnit test to check if it throws the correct exception:

You can add the following to the annotated test:
@Test(expected=RequestValidationException.class)

1:  @Test(expected=RequestValidationException.class)  
2:          public void testValidateHeader_contentTypeInvalidValue() throws Exception  
3:          {      
4:              EasyMock.expect(servletRequest.getHeader("content-type")).  
5:                 andReturn("application/xml;charset=utf8");      
6:              EasyMock.replay(servletRequest, encryptionHelper);  
7:              Whitebox.invokeMethod(validator, "validateHeaders", servletRequest);  
8:          }  

Got to know it from here:
http://www.junit.org/node/390

Additional JUnit tip: WhiteBox comes from org.powermock.reflect.Whitebox and is used for invoking private methods

Monday, May 14, 2012

Integration tests for web services with Maven

There is a very nifty Maven plugin, called Maven Jetty plugin through which you can set up quick integration tests as part of your build. This is very valuable to catch erroneous check-ins that cause your code to compile and unit tests to pass but still can induce service start up failures.

With this plug in, you can start up a Servlet container (Jetty) and run your web service in it, as part of your build, in the pre-integration test phase. A sample configuration is pasted below. The following goes in the tag of your Maven pom.xml:


     <plugins>  
             <plugin>  
                 <groupId>org.apache.maven.plugins</groupId>  
                 <artifactId>maven-failsafe-plugin</artifactId>  
                 <version>2.9</version>  
                 <executions>  
                     <execution>  
                         <goals>  
                             <goal>integration-test</goal>  
                             <goal>verify</goal>  
                         </goals>  
                     </execution>  
                 </executions>  
             </plugin>  
             <plugin>  
                 <groupId>org.mortbay.jetty</groupId>  
                 <artifactId>jetty-maven-plugin</artifactId>  
                 <version>7.4.4.v20110707</version>  
                 <configuration>  
                     <connectors>  
                         <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">  
                             <port>9099</port>  
                             <maxIdleTime>60000</maxIdleTime>  
                         </connector>  
                     </connectors>  
                     <stopKey>foo</stopKey>  
                     <stopPort>9999</stopPort>  
                     <!-- webXml>src/main/resources/override-web.xml</webXml> -->  
                     <webAppConfig>  
                         <contextPath>/facebookConnectServlet</contextPath>                          
                     </webAppConfig>                      
                 </configuration>  
                 <executions>  
                     <execution>  
                         <id>start-jetty</id>  
                         <phase>pre-integration-test</phase>  
                         <goals>  
                             <goal>run</goal>  
                         </goals>  
                         <configuration>  
                             <scanIntervalSeconds>0</scanIntervalSeconds>  
                             <daemon>true</daemon>  
                         </configuration>  
                     </execution>  
                     <execution>  
                         <id>stop-jetty</id>  
                         <phase>post-integration-test</phase>  
                         <goals>  
                             <goal>stop</goal>  
                         </goals>  
                     </execution>  
                 </executions>  
             </plugin>  
         </plugins>  

The first plugin, Maven Failsafe Plugin, is designed to run integration tests. The second plug in, Maven Jetty Plugin, is configured subsequently to run Jetty in the pre-integration test phase and stop Jetty in the post integration test phase.

You can then make smoke test level requests to your web service, in the integration test phase, to check if the basic functionality works.

Wednesday, May 9, 2012

Making AES 256 bit encryption work for Java

There are regulatory issues in exporting software that contains AES 192 bit and greater encryption. Read about it here:
http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
[Section: Strong Versus Unlimited Strength Cryptography]

To make AES 256 bit encryption work, you'll have to download the policy files from:
http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

The zip file contains 2 jars: US_export_policy.jar and local_policy.jar

You'll have to copy the jars in your JRE_HOME/lib/security directory. This will make 256 bit AES work.

Also skim through the README file in the zip file for additional insight.