Friday, November 15, 2013

apiary.io sample


First of all I must mention apiary.io has done great job by providing some easy means to have REST api documentation, collaborate as well as expose it to public or keep it private. With the new release of the same I was struggling little bit to make use of the new version, for that I had to go through the detailed documentation (refer). But I felt this tutorial just demonstrates blueprint code, it doesn't show the corresponding preview related to given blueprint code. I had to invest some time to figure out what code generate which effect. So I have created one sample blueprint for which you can refer the code below and result of the same http://docs.pandurangpatil.apiary.io/. For more details refer api tutorial (http://apiary.io/blueprint), one can add more styling in documentation using markdown, for more help on markdown refer.


 FORMAT: 1A  
 HOST: http://sample.pandurangpatil.com  
   
 # Sample API Documentation  
 Sample api documentation for sample project.  
   
 # Allowed HTTPs requests:  
 <pre>  
 PUT   : To create resource   
 POST  : Update resource  
 GET   : Get a resource or list of resources  
 DELETE : To delete resource  
 </pre>  
   
 # Description Of Usual Server Responses:  
 - 200 `OK` - the request was successful (some API calls may return 201 instead).  
 - 201 `Created` - the request was successful and a resource was created.  
 - 204 `No Content` - the request was successful but there is no representation to return (i.e. the response is empty).  
 - 400 `Bad Request` - the request could not be understood or was missing required parameters.  
 - 401 `Unauthorized` - authentication failed or user doesn't have permissions for requested operation.  
 - 403 `Forbidden` - access denied.  
 - 404 `Not Found` - resource was not found.  
 - 405 `Method Not Allowed` - requested method is not supported for resource.  
   
 # Some sample  
   Test sample         |  test column two  
   First column sadf asdfads  |  sfsdsadf  
   
 ---  
   test one          | Another column    
 ---  
   
 # Table sample  
 <table>  
   <tr>  
     <td> First Column </td>  
     <td> Second Column </td>    
   </tr>  
   <tr>  
     <td> First Column </td>  
     <td> Second Column </td>   
   </tr>  
 </table>  
   
   
 # Code Sample  
 <pre>  
   Some code here  
 </pre>  
   
 # Group User  
 Represents user details.   
   
 ---  
 **User attributes:**  
   
 - id `(Number)` : unique identifier.   
 - fname `(String)` : First Name.  
 - lname `(String)` : Last Name.  
 - email `(String)` : email id of the user.  
   
 ---  
 ## User Collection [/users(?since,limit)]  
 ### List all users [GET]  
 Retrieve paginated list of users.  
   
 + Parameters  
   + since (optional, String) ... Timestamp in ISO 8601 format: `YYYY-MM-DDTHH:MM:SSZ` Only users updated at or after this time are returned.  
   + limit (optional, Number) ... maximum number of records expected by client.  
   
 + Response 200 (application/json)  
   
     [  
       {  
         "id": 1,  
         "fname": "Pandurang",  
         "lname": "Patil",  
         "email": "[email protected]"  
       },  
       {  
         "id": 2,  
         "fname": "Sangram",  
         "lname": "Shinde",  
         "email": "[email protected]"  
       }  
     ]  
   
 + Response 401 (application/json)  
   
     {  
       "error": "error.unauthorized"  
     }  
   
 ### Create a User [PUT]  
 + Request (application/json)  
   
     {  
       "fname": "Ram",  
       "lname": "Jadhav",  
       "email": "[email protected]"  
     }  
   
 + Response 201 (application/json)  
   
     {  
       "id": 3,  
       "fname": "Ram",  
       "lname": "Jadhav",  
       "email": "[email protected]"  
     }  
   
 ## User [/users/{id}]  
 A single User object with all its details  
   
 + Parameters  
   + id (required, Number, `1`) ... Numeric `id` of the User to perform action with.  
   
 ### Retrieve a User [GET]  
 + Response 200 (application/json)  
   
   + Header  
   
       X-My-Header: The Value  
   
   + Body  
   
       {  
         "id": 1,  
         "fname": "Pandurang",  
         "lname": "Patil",  
         "email": "[email protected]"  
       }  
         
 + Response 401 (application/json)  
   
     {  
       "error": "error.unauthorized"  
     }  
   
 ### Update a User [POST]  
 Update user details  
 + Request (application/json)  
   
     {  
       "id": 1,  
       "fname": "Pandurang",  
       "lname": "Patil",  
       "email": "[email protected]"  
     }  
   
 + Response 200 (application/json)  
   
     {  
       "id": 1,  
       "fname": "Pandurang",  
       "lname": "Patil",  
       "email": "[email protected]"  
     }  
   
 + Response 401 (application/json)  
   
     {  
       "error": "error.unauthorized"  
     }  
   
 ### Remove a User [DELETE]  
 + Response 204  
   
 + Response 401 (application/json)  
   
     {  
       "error": "error.unauthorized"  
     }  
   



Tuesday, October 29, 2013

Convert mercurial (hg) to git repository for bitbucket

To convert hg repository on bitbucket to git repository follow below steps.

  • Create new repository with Repository Type selected as Git
  • follow below commands with the assumption that you already have hg repository cloned on your system. If not then you first need to clone existing hg repository.

1:  $ git clone git://repo.or.cz/fast-export.git  
2:  $ mkdir <new git repo>  
3:  $ cd <new git repo>  
4:  $ git init  
5:  $ ../fast-export/hg-fast-export.sh -r <path to hg local repository>  
6:  $ git checkout HEAD  
7:  $ git remote add origin https://<username>@bitbucket.org/<username>/<new git repo>.git  
8:  or if you are going to use ssh authentication to push   
9:  $ git remote add origin [email protected]:<username>/<new git repo>.git  
10:  $ git push origin master  

This will convert your hg repository to git repository and it also maintains the commit history inside git repository.

Sunday, October 27, 2013

Install and run memcached on OS-X


One need to have gcc installed for that you need to install xcode along with command line tools. To install the same one can refer to this link for xcode 5.0.1.  Libevent is required to be installed for memcached so you need to first install libevent, if it is already installed on your machine you can skip this step.

Create temp directory and change directory to that location and execute following commands.


 $ curl -O http://www.monkey.org/~provos/libevent-1.4.14-stable.tar.gz  
 $ tar xzvf libevent-1.4.14-stable.tar.gz  
 $ cd libevent-1.4.14-stable  
 $ ./configure   
 $ make  
 $ sudo make install   

now install memcached

 $ curl -O http://memcached.googlecode.com/files/memcached-1.4.15.tar.gz  
 $ tar -zxvf memcached-1.4.15.tar.gz  
 $ cd memcached-1.4.15  
 $ ./configure  
 $ make  
 $ sudo make install  

Above steps will install the memcached on your OS-X. Once it is done you can start it

 $ memcached -d -p 11211  


Saturday, October 26, 2013

Access file (JAVA)


Access resource / file packaged inside a jar or a located on classpath.

Two ways to access the file located inside jar or located on classpath. 


  1. Use getResourceAsStream("filename") on ClassLoader, one can retrieve the class loader instance from class instance of any class or Thread.currentThread().getClassLoader(). When you try to load the file using class loader, file will be always searched inside root folder on classpath. e.g
    Thread.currentThread().getClassLoader().getResourceAsStream("config.properties") and Thread.currentThread().getClassLoader().getResourceAsStream("/config.properties") either way class loader will try to search file from root folder which is on class path or from root folder inside jar.
  2. User getResourceAsStream("filename") on Class instance of a class. One can retrieve the class instance using ClassName.class or this.getClass(). When you try to load the file using class, file search will depend on how do you specify the file name. When you specify file "config.properties" this.getClass().getResourceAsStream("config.properties"), file will be searched inside same package as that of given class on which you are calling getResourceAsStream(). When you specify file like "/config.properties" given file will be searched from root folder which is on class path or from root folder inside jar.
Access resource / file from file location

  To access file form given path outside the class path, one need to make use of java.io.File .

File file = new File("filename with absolute path");
FileInputStream fStream = new FileInputStream(file); 
  

Friday, October 18, 2013

maven properties not being substituted inside resources


You need to add following configuration which indicates those resources need to be processed and property values will be replaced. By default Maven resources plug-in will not do property value substitution (filtering), so it will need to be enabled within the <build> section of the pom.xml file. Filtering value true will enable the resources processing and substitute property values. In addition to that one can include / exclude the resources


 <build>  
           .....  
         .....  
           <resources>  
                <resource>  
                     <directory>src/main/resources</directory>  
                     <filtering>true</filtering>  
                </resource>  
           </resources>  
           .....  
         .....  
 </build>  


Thursday, September 26, 2013

Zeromq setup on MAC OSX 10.9.3 (mavericks) with Java binding

Steps:

With reference to following blogs written by Vivek http://technicalvvkydv.blogspot.in/2011/06/making-zeromq-jar-for-mac.html to install zeromq and by Jean http://jsdelfino.blogspot.in/2012/08/autoconf-and-automake-on-mac-os-x.html to install auto tools. I faced few issues ( one of them is following error ./configure: line 15284: ` PKG_CHECK_MODULES) which I tried to address with following steps:

  1. Install gcc ( to install gcc you need to install xcode 5 download it from https://developer.apple.com/xcode/ and install.)
  2. Make sure you have java installed. If you want to install JDK 7 refer this http://docs.oracle.com/javase/7/docs/webnotes/install/mac/mac-jdk.html 
  3. Make sure you have git installed to checkout zeromq java binding source code.
  4. Make sure that libtool, autoconf, automake are installed. (refer http://jsdelfino.blogspot.in/2012/08/autoconf-and-automake-on-mac-os-x.html). I preferred installing binaries in system directory directly. If you have already installed it then you can skip this step.
     # create a temporary folder to checkout / download source code and build the same  
     $ mkdir build  
     $ cd build  
     $ curl -OL http://ftpmirror.gnu.org/autoconf/autoconf-2.69.tar.gz  
     $ tar -xzf autoconf-2.69.tar.gz  
     $ cd autoconf-2.69  
     $ ./configure  
     $ make  
     $ sudo make install  
     $ cd ../  
     $ curl -OL http://ftpmirror.gnu.org/automake/automake-1.14.tar.gz  
     $ tar -xzf automake-1.14.tar.gz  
     $ cd automake-1.14  
     $ ./configure  
     $ make  
     $ sudo make install  
     $ cd ../  
     $ curl -OL http://ftpmirror.gnu.org/libtool/libtool-2.4.2.tar.gz  
     $ tar xzf libtool-2.4.2.tar.gz  
     $ cd libtool-2.4.2  
     $ ./configure  
     $ make  
     $ sudo make install  
     $ cd ../  
    
  5. Install core zero mq library.
     #Download latest zermoq source code http://zeromq.org/area:download   
     #I tried it with zeromq-3.2.4.tar.gz (http://download.zeromq.org/zeromq-4.0.4.tar.gz)   
     $ curl -OL http://download.zeromq.org/zeromq-4.0.4.tar.gz  
     $ tar -zxvf zeromq-4.0.4.tar.gz  
     $ cd zeromq-4.0.4  
     $ ./configure  
     $ make  
     $ sudo make install  
     $ cd ../  
    
  6. Install pkg-config. If you already have it installed then you can skip this step.
     $ curl -OL http://pkgconfig.freedesktop.org/releases/pkg-config-0.28.tar.gz  
     $ tar -zxvf pkg-config-0.28.tar.gz  
     $ cd pkg-config-0.28   
     $ ./configure --with-internal-glib 
     $ make  
     $ sudo make install  
     $ cd ../  
    
  7. Install / generate zeromq JAVA binding for more details refer http://zeromq.org/bindings:java
     $ git clone https://github.com/zeromq/jzmq.git  
     $ cd jzmq  
     # if you already have JAVA_HOME set you can skip this  
     $ export JAVA_HOME=`/usr/libexec/java_home`  
     $ ./autogen.sh  
     $ ./configure  
     $ make  
     $ sudo make install  
    

At the end you will find zmq.jar generated at location /usr/local/share/java/


Tuesday, August 6, 2013

Override JPA persistence unit properties in code with Google Guice

To override properties from persistence.xml through code while using it with Google guice. One can read the properties from different source and add those properties while installing JpaPersistModule. Following is the sample


1:  Properties persistenceUnit = new Properties();  
2:  persistenceUnit.put("javax.persistence.jdbc.url", "jdbc:mysql://192.168.9.102/MyDB");  
3:  persistenceUnit.put("javax.persistence.jdbc.user", "myuser");  
4:  persistenceUnit.put("javax.persistence.jdbc.password", "mypassword");  
5:  Injector injector = Guice.createInjector(new JpaPersistModule("my-persistence-unit").properties(persistenceUnit));  


One can chose to read this configuration from some other file and install JpaPersistModule with those properties. This could be useful to override database url for test and production.

Friday, May 17, 2013

Generate complete package (ZIP) of Java (executable jar) application with required dependencies in it using Maven


To generate a zip file, packaging all required dependent libraries and newly generated jar, using maven-assembly-plugin (for more detail on plugin refer).

I will demonstrate generation of package using assembly descriptor file.
  • Create a assembly descriptor file which is a xml file (for more details refer and format ) as following. Create this file inside your project directory. One can keep this descriptor file any where inside given project directory. I have tried it by keeping this file at location <Project dir>/src/main/assembly/test-app-assembly.xml and providing complete path to descriptor file in pom.xml.

1:  <?xml version="1.0" encoding="UTF-8"?>  
2:  <assembly  
3:       xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"  
4:       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
5:       xsi:schemaLocation="  
6:    http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2  
7:     http://maven.apache.org/xsd/assembly-1.1.2.xsd  
8:   ">  
9:       <formats>  
10:            <format>zip</format>  
11:       </formats>  
12:       <files>  
13:            <file>  
14:                 <outputDirectory>/</outputDirectory>  
15:                 <source>target/test-app.jar</source>  
16:            </file>  
17:       </files>  
18:       <!-- use this section if you want to package dependencies -->  
19:       <dependencySets>  
20:            <dependencySet>  
21:                 <outputDirectory>lib</outputDirectory>  
22:                 <useStrictFiltering>true</useStrictFiltering>  
23:                 <useProjectArtifact>false</useProjectArtifact>  
24:                 <scope>runtime</scope>  
25:            </dependencySet>  
26:       </dependencySets>  
27:  </assembly>  

  • In above descriptor file, its assumed the current project artifact is generated before this plugin gets executed and maven-assembly-plugin configured to run in "install" phase only.
  • refer line 12 to 17 in above code. We are specifying include generated artifact from the current module inside packaging, which will be placed inside root "/" directory of the package zip. Note: by default maven generates artifact in following format "<artifact name>-<version>.jar" (with assumption packaging mentioned as "jar"). You need to make sure to specify constant file name using property <finalName> inside your pom.xml

1:  <build>  
2:  ......  
3:  ....  
4:        <finalName>test-app.jar</finalName>   
5:  .......  
6:  ....  
7:  </build>  

  • Next refer line 19 - 26. Here we are specifying copy all dependency jars inside "/lib" directory of the package zip.
  • Next refer below changes in pom.xml.

1:  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
2:       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
3:       ......  
4:      .........  
5:       <build>  
6:            <finalName>test-app</finalName>  
7:            <plugins>  
8:                 <plugin>  
9:                      <groupId>org.apache.maven.plugins</groupId>  
10:                      <artifactId>maven-assembly-plugin</artifactId>  
11:                      <executions>  
12:                           <execution>  
13:                                <id>create-distribution</id>  
14:                                <phase>install</phase>  
15:                                <goals>  
16:                                     <goal>single</goal>  
17:                                </goals>  
18:                                <configuration>  
19:                                     <descriptors>  
20:                                          <descriptor>src/main/assembly/test-app-assembly.xml</descriptor>  
21:                                     </descriptors>  
22:                                </configuration>  
23:                           </execution>  
24:                      </executions>  
25:                 </plugin>  
26:              ................  
27:              ................  
28:            </plugins>  
29:       </build>  
30:  </project>  
  • Refer line 8 - 25 in above code from sample pom.xml. Here we are configuring maven-assembly-plugin to invoke "single" goal in "install" phase by referring test-app-assembly.xml file (refer line 20).
  • When you run the build "mvn clean install" at the end you will see file "test-app.zip" is generated inside target folder. If you open the zip file you will find test-app.jar and "lib" folder in it and if you go inside lib folder you will find all required dependencies of current project are copied inside this "lib" folder.

Above steps demonstrates how to generate required single package as zip with all required dependencies in it. Now we will look at how to make given application as executable jar (When I say executable jar, one can configure main class of given application, so that JVM can invoke the application directly without specifying which class to invoke on command line. you can run application like "<extracted location of zip>$ java -jar test-app.jar -classpath <location of each dependent jar file>"). But its not just sufficient to just specify only main class, we also need to add required dependent jar files in class path while running application from command prompt. If we can add those dependent jar locations inside jar itself then you don't have to mention it at command line. Refer below code changes using maven-jar-plugin.

1:  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
2:       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
3:       ......  
4:      .........  
5:       <build>  
6:            <finalName>test-app</finalName>  
7:            <plugins>  
8:                 <plugin>  
9:                      <groupId>org.apache.maven.plugins</groupId>  
10:                      <artifactId>maven-assembly-plugin</artifactId>  
11:                      <executions>  
12:                           <execution>  
13:                                <id>create-distribution</id>  
14:                                <phase>install</phase>  
15:                                <goals>  
16:                                     <goal>single</goal>  
17:                                </goals>  
18:                                <configuration>  
19:                                     <descriptors>  
20:                                          <descriptor>src/main/assembly/test-app-assembly.xml</descriptor>  
21:                                     </descriptors>  
22:                                </configuration>  
23:                           </execution>  
24:                      </executions>  
25:                 </plugin>  
26:                 <plugin>  
27:                      <groupId>org.apache.maven.plugins</groupId>  
28:                      <artifactId>maven-jar-plugin</artifactId>  
29:                      <configuration>  
30:                           <archive>  
31:                                <manifest>  
32:                                     <addClasspath>true</addClasspath>  
33:                                     <classpathPrefix>lib/</classpathPrefix>  
34:                                     <mainClass>com.pp.test.Sample</mainClass>  
35:                                </manifest>  
36:                           </archive>  
37:                      </configuration>  
38:                 </plugin>  
39:            </plugins>  
40:       </build>  
41:  </project>  


  • refer line 34, here we are specifying which the class having main method. At line 32 we are specifying add all dependency jars into classpath. But as all the dependent jars we have placed inside "lib" folder as per above packaging configuration, while specifying class path we need to prefix jar file name with "lib/". This will result in generation of META-INF/MANIFEST.MF file refer sample below. 
 Manifest-Version: 1.0  
 Archiver-Version: Plexus Archiver  
 Created-By: Apache Maven  
 Built-By: pandurang  
 Build-Jdk: 1.7.0_17  
 Main-Class: com.pp.test.Sample  
 Class-Path: lib/javapns-2.2.jar lib/junit-4.8.1.jar lib/commons-lang-2.6.jar lib/commons-io-2.4.jar lib/mail-1.4.5.jar lib/activation-1.1.jar lib/google-http-client-jackson2-1.13.1-beta.jar lib/j  
  ackson-core-2.0.5.jar lib/jcommander-1.30.jar lib/log4j-1.2.17.jar lib/slf4j-api-1.6.6.jar   

  • With this you will be able to generate complete zip file with an executable jar file in it. Which makes the deployment and execution of application very easy. For deployment you need to just ship this generated "test-app.zip" file which is a complete package. To run your application you can extract the zip file and issue following command "<extracted location of zip>$ java -jar test-app.jar". Note here when jar is generated all required dependencies are mentioned inside MANIFEST.MF you don't have to specify them here.  

OpenID and OAuth

First of all OpenID and OAuth are two different standards don't mix them together.

OpenID is only limited to identify the end user i.e. getting user authenticated from the third party provider like Google, Yahoo etc. The benefit of integrating with third party service provider for end user's authentication has following benefits.


  • End user don't have to remember another credentials for your site. They will be able to authenticate them self with their existing registered account with any of the third party service provider.
  • Along with that it also gives you advantage of Single Sign on for your site. 

Oauth provides way to identify (Authenticate with Oauth 2.0) end user as well as, provides a mechanism to get user's authorization to access his / her data with the given provider. 

Comparison:
       There is no comparison, both are different standars targeted to solve different problems. OpenId is targeted to get authentication done from third party service rather than having own system for the same. One can support multiple third service providers for authenticating user's with openId on their site. 
       Where as Oatuh is targeted to get user's authorization (for you application / site) to access his / her data from given service provider using respective api, exposed by same service provider. 


Saturday, February 2, 2013

Intercept GWT Request Factory on client side


How to intercept GWT Request Factory on client before call is being made and after response is received?

One can extend DefaultRequestTransport and intercept send call, at the same time writing a wrapper over TrasnportReceiver one can intercept response's. Following is the example.

1:  public class LoaderRequestTransport extends DefaultRequestTransport {  
2:       private Loader     loader;  
3:       public LoaderRequestTransport(Loader loader) {  
4:            this.loader = loader;  
5:       }  
6:       public LoaderRequestTransport() {  
7:            this(new Loader(LoaderResources.INSTANCE.communicating()));  
8:       }  
9:       @Override  
10:       public void send(final String payload, final TransportReceiver receiver) {  
11:            final TransportReceiver proxy = new TransportReceiver() {  
12:                 @Override  
13:                 public void onTransportFailure(final ServerFailure failure) {  
14:                      loader.hide();  
15:                      receiver.onTransportFailure(failure);  
16:                 }  
17:                 @Override  
18:                 public void onTransportSuccess(final String payload) {  
19:                      loader.hide();  
20:                      receiver.onTransportSuccess(payload);  
21:                 }  
22:            };  
23:            loader.show();  
24:            super.send(payload, proxy);  
25:       }  
26:  }  

Use this LoaderRequestTransport

1:  MVPRequestFactory requestFactory = GWT.create(MVPRequestFactory.class);  
2:  requestFactory.initialize(eventBus, new LoaderRequestTransport());  






Sunday, January 20, 2013

Intercept GWT RPC Request and Response


Some times you want to do some generic things like setting some header or adding some log or may be even showing a progress bar while rpc call is in progress and hide it once you receive the response. I came across one of such requirement for showing progress bar while service call is in progress. Following is complete end to end solution I found after searching for some solutions. I got some help at following threads https://groups.google.com/forum/?fromgroups=#!msg/google-web-toolkit/VeiJUPBUsi4/Hq2VDMF9W1kJ and http://stackoverflow.com/questions/5309624/how-to-intercept-the-onsuccess-method-in-gwt

I created one complete end  to end working example from that help.

1:  public class LoaderRpcRequestBuilder extends RpcRequestBuilder {  
2:       private Loader     loader;  
3:       private class RequestCallbackWrapper implements RequestCallback {  
4:            private RequestCallback     callback;  
5:            RequestCallbackWrapper(RequestCallback aCallback) {  
6:                 this.callback = aCallback;  
7:            }  
8:            @Override  
9:            public void onResponseReceived(Request request, Response response) {  
10:                 loader.hide();  
11:                 callback.onResponseReceived(request, response);  
12:            }  
13:            @Override  
14:            public void onError(Request request, Throwable exception) {  
15:                 loader.hide();  
16:                 callback.onError(request, exception);  
17:            }  
18:       }  
19:       public LoaderRpcRequestBuilder(Loader loader) {  
20:            this.loader = loader;  
21:       }  
22:       public LoaderRpcRequestBuilder() {  
23:            this(new Loader());  
24:       }  
25:       @Override  
26:       protected RequestBuilder doCreate(String serviceEntryPoint) {  
27:            RequestBuilder rb = super.doCreate(serviceEntryPoint);  
28:            loader.show();  
29:            return rb;  
30:       }  
31:       @Override  
32:       protected void doFinish(RequestBuilder rb) {  
33:            super.doFinish(rb);  
34:            rb.setCallback(new RequestCallbackWrapper(rb.getCallback()));  
35:       }  
36:  }  

Here in above code we are creating our own custom RpcRequestBuilder by extending RpcRequestBuilder and by overriding its doCreate and doFinish() method. We are intercepting the calls that will be made. In doCreate() we are showing loader and then inside doFinish we are setting one general purpose RequestCallback wrapper which we have created to intercept response received. Where we are hiding our loader inside onResponseReceived() and onError.

Note: be sure to call super.doFinish(rb); other wise you will get SecurityException. There are some tokens which is set by doFinish method to avoid XSRF attack. (Though they say one should not just rely on this mechanism to avoid XSRF attack.)

Now that we have created custom RpcRequestBuilder we need to understand how to use it.

1:  ServiceAsync serivce = GWT.create(Service.class);  
2:  ServiceDefTarget target = (ServiceDefTarget) serivce;  
3:  target.setRpcRequestBuilder(new LoaderRpcRequestBuilder());  

When we make rpc call we get async instance before making any service call we need to set our own custom RpcRequestBuilder.





Wednesday, January 2, 2013

set Servlet RequestScope Guice dependencies


Set some commonly used dependencies which are dependent on some parameter of HTTP Request.

The most common use case is to add logged in user context in request scope from session id inside filter. To do that you need to bind such a dependency inside your ServletModule like following.

 bind(User.class).annotatedWith(Names.named("user")).to(User.class).in(ServletScopes.REQUEST);  

You are just binding a given User.class with @Named("user") annotation inside RequestScope. Now you have to take care of setting required value when request is made. Which can be achieved by using Servlet filter as follows.

1:  public class AuthCheckFilter implements Filter {  
2:       @Override  
3:       public void destroy() {  
4:       }  
5:       @Override  
6:       public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  
7:            HttpServletRequest httpRequest = (HttpServletRequest) request;  
8:            .....< Code to retrieve session from request either through query param,   
9:            cookie or HTTP header and validate the session.   
10:            session is not valid throw error as per application specific requirement>.....  
11:            User us = ...<code to retrieve user from session>  
12:            httpRequest.setAttribute(Key.get(User.class, Names.named("user")).toString(), us);  
13:            chain.doFilter(httpRequest, response);  
14:       }  
15:       @Override  
16:       public void init(FilterConfig arg0) throws ServletException {  
17:       }  
18:  }  

Note: We are setting User object for @Named("user") dependency at line no 12. When you set the user value inside httpRequest object as attribute.

Now that we have set the value. We can access it or inject it

1:  @Singleton  
2:  public class SomeDao {  
3:    @Inject  
4:    @Named("user")  
5:    Provider<User> user;  
6:    public void someMethod() {  
7:      User user = user.get();  
8:    }  
9:  }  

As it is request scoped dependency you need to access / inject it through Provider.

http://code.google.com/p/google-guice/wiki/ServletModule refer Using RequestScope section.