Friday, November 16, 2012

Content assist for static imports in Eclipse

Take a look at the following link on how you can enable auto complete in Eclipse for static imports:
http://stackoverflow.com/questions/288861/eclipse-optimize-imports-to-include-static-imports

This is very helpful when you are writing JUnit and Mockito code. Below is the relevant part of the StackOverflow answer: 

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.

Wednesday, March 14, 2012

Jing: Capture screen actions as videos

Every few weeks, at the end of our Agile Sprint, we prepare demos for the work that was done as part of the sprint. Sometimes we do live demos and sometimes to save time, we just capture those demos and replay them at the sprint end meetings.

For capturing the screen actions into videos, I have found Jing to be an amazing software. The user experience is as simple as it can be. You open up Jing in "Capture" mode, then select the screen real estate you want to capture and say "Capture Video". At the end, you "Stop" and "Save". By default, it allows you to save videos in Flash format (.swf files) that can be played in any Flash compatible browser.

You can also do screenshots in Jing but I have found the Snipping Tool, that comes default with Windows Vista and later versions of Windows, to be more valuable.

Jing is available as freemium download for Windows and Mac.

Wednesday, March 7, 2012

Calibre: Reading PDF docs on your Kindle

If you have read pdf docs on your Amazon Kindle, you know how painful it is. On the other hand, reading Kindle eBooks is a heavenly experience. The reason for this mismatch is that Kindle eBooks come in a format called mobi and the pdf viewer on Kindle doesn't boast of user experience as its design goal.

Enter Calibre, a free and open source e-book library management application that provides eBook conversions, amongst its other features. You can open a pdf doc in Calibre and convert it to mobi. Calibre also provides a way to sync the converted .mobi file to your Kindle (through email). Additionally, you can always transfer the .mobi file through USB to your Kindle.

Monday, February 27, 2012

Testing RESTful Web Services


Recently, a lot of companies have been moving towards RESTful web services. REST has a lot of benefits compared to SOAP, XML RPC in terms of performance and ease of development. You can read more about these here:
In development while testing RESTful Web Services, I have found the following tools helpful:
  • curl - Comes in the Cygwin distribution for windows. You can find linux installables for your flavor of linux here. Sample uses of curl to make REST calls:
    • curl -v http://flickr.com/rogermenezes/photos/61 -H 'Content-Type:application/json' -H 'X-FlickrAPI-Version:1.0' -X DELETE
    • curl -v http://flickr.com/rogermenezes/albums -H 'Content-Type:application/json' -H 'X- FlickrAPI -Version:1.0' -X POST -d '{"name": "hawaii 2011", "tags": "vacation, hawaii, ", "creation_date": "2012-02-22T13:42Z"}'
  • Chrome Plugin - Advance REST Client
    • You can install this plugin through the Chrome Web Store. You can save past requests and the plugin also maintains a history of previous calls you had made.
  • Fiddler2 [I'll add another introductory post in the future for Fiddler.]
    • Fiddler2 snoops your network traffic. As soon as you start Fiddler, it creates a proxy through which all of your traffic gets routed. It provides a great interface for digging thought the network traffic. It also provides a way to "reissue and edit" past requests. Here, you can edit your past REST requests and execute them repeatedly.
Enhanced by Zemanta

Wednesday, February 15, 2012

Synergy - Controlling multiple computers with a single mouse and keyboard

Every company that I have worked for in recent years, RIM, AMZN, MSFT, alloted two machines to devs - a laptop and a desktop. People had different options on using a single mouse and keyboard to control both machines at all places. At MSFT, we would remote desktop to the desktop machine and control everything via the laptop peripherals. Folks at AMZN used Synergy as the configuration over there used to be a linux desktop and windows laptop.

Synergy lets you share your mouse and laptop between multiple computers (cross platform - works on Windows, Mac OS X and Linux). The setup instructions are here. The windows config UI is pretty cool. Choosing the desktop as the server has worked well for me in the past. Also, Synergy has evolved quite a lot in the last few years - a lot of the basic issues are gone. Also, the clipboard works flawlessly across the computers.

Matt Cutts also has good instructions to configure Synergy. Looks like Google devs use it too :-)

More people writing about configuring Synergy:
  • http://lifehacker.com/254648/how-to-control-multiple-computers-with-a-single-keyboard-and-mouse
  • http://www.labnol.org/software/two-computers-one-keyboard-mouse/20134/