Sunday, November 25, 2012

Access annotated dependencies through injector instance


Following sample will demonstrate how to access guice dependency annotated with some annotation through direct Guice injector instance.

Bar.java

 import java.lang.annotation.Retention;  
 import java.lang.annotation.RetentionPolicy;  
 import com.google.inject.BindingAnnotation;  
 @Retention(RetentionPolicy.RUNTIME)  
 @BindingAnnotation  
 public @interface Bar {  
 }  

Foo.java

 import java.lang.annotation.Retention;  
 import java.lang.annotation.RetentionPolicy;  
 import com.google.inject.BindingAnnotation;  
 @Retention(RetentionPolicy.RUNTIME)  
 @BindingAnnotation  
 public @interface Foo {  
 }  

TestDepdency.java

 public interface TestDepdency {  
      String getValue();  
 }  

FooTestDependencyImpl.java

 public class FooTestDependencyImpl implements TestDepdency {  
      @Override  
      public String getValue() {  
           return "Foo";  
      }  
 }  

BarTestDependencyImpl.java

 public class BarTestDependencyImpl implements TestDepdency {  
      @Override  
      public String getValue() {  
           return "Bar";  
      }  
 }  

Test.java

 import com.google.inject.AbstractModule;  
 import com.google.inject.Guice;  
 import com.google.inject.Injector;  
 import com.google.inject.Key;  
 public class Test {  
      public static void main(String[] args) {  
           Injector injector = Guice.createInjector(new AbstractModule() {  
                @Override  
                protected void configure() {  
                     bind(TestDepdency.class).annotatedWith(Foo.class).to(FooTestDependencyImpl.class);  
                     bind(TestDepdency.class).annotatedWith(Bar.class).to(BarTestDependencyImpl.class);  
                }  
           });  
           TestDepdency foo = injector.getInstance(Key.get(TestDepdency.class, Foo.class));  
           System.out.println(foo.getValue());  
           TestDepdency bar = injector.getInstance(Key.get(TestDepdency.class, Bar.class));  
           System.out.println(bar.getValue());  
      }  
 }  


Final output

 Foo  
 Bar  


In the similar way you can retrieve the annotated provider.

Singleton Factory


Singleton factory for single threaded environment:

It is simple to create Singleton factory for single threaded application.

 public class SingleThreadSingleton {  
      private static SingleThreadSingleton     instance;  
      private SingleThreadSingleton() {  
           // Initialise  
      }  
      public static SingleThreadSingleton getInstance() {  
           if (instance == null) {  
                instance = new SingleThreadSingleton();  
           }  
           return instance;  
      }  
 }  

Singleton factory for multi threaded application:

When you want to create Singleton factory for multi threaded application. In which you want single instance to be maintained across all thread. You need to synchronize the creation of a instance. In which case if you synchronize the complete getInstance method in above example you are creating the bottleneck to access the instance. The requirement is to just synchronize the creation of instance. Following is sample Singleton factory for multi threaded application.

1:  public class MultiThreadSingleton {  
2:       private static MultiThreadSingleton     instance;  
3:       private MultiThreadSingleton() {  
4:            // Initialise  
5:       }  
6:       public static MultiThreadSingleton getInstance() {  
7:            if (instance == null) {  
8:                 synchronized (MultiThreadSingleton.class) {  
9:                      if (instance == null) {  
10:                           instance = new MultiThreadSingleton();  
11:                      }  
12:                 }  
13:            }  
14:            return instance;  
15:       }  
16:  }  

As there is possibility that multiple thread calls getInstance method simultenously  before instance is initialized. In that case there is possibility that multiple threads get inside initialization block ( ref line no. 7). As inside code
is synchronized only one thread would get access to it at given instant of time. Other thread will wait till the time first thread release the lock. First thread gets a access it will initialize the instance. When first thread goes out of synchronized block other next thread waiting for the access will get inside synchronized block. Now if we don't add null check for instance inside synchronized block ( ref line no. 9) the second thread will initialize the instance again. Same will happen if there are more threads waiting for the access. To avoid reinitialization we have to add null check for instance inside Synchronized block also. Once instance is created then there is no need to have synchronization to access the instance.

Wednesday, November 21, 2012

Free or less costly tools and services helpful for Software Startup


When you are looking to start on your own Software Start-up you need to look for what all free services, tools that can be help full to start with as saving on Money is very important for a startup.

  • Most important for any start-up is to have email for their custom domain. And I suppose most of the people know which is the best and free option to start with Google Apps for 10 users
    • Its the custom gmail for your domain and you have most of the other free service from Google available with it like Google Drive, Calendar, Task and Sites.
  • Most important for Software start-up is where to keep or host source code repository. And most use full and feature free service upto 5 users that I was able locate is https://bitbucket.org/. It has following features
    • Free private source code repository hosting upto 5 users with mercurial.
    • It has Wiki pages hosting not that great but can be useful.
    • Up to some extent you can have access management on repository.
    • It comes with Jira integeration, which good amount features which can make your life easy to trac the issue and changes.
    • You can add commit commands while committing the code which can link, resolve the respective issue in JIRA.
    • It has services like send commit mail, send diff and issue update notifications.
    • Most importantly you can have unlimited private repositories.
    • You can even configure custom domain.
    • And it also supports code review process. 
  • The product you are developing is having GUI to interact with then most probably you would also require to create mock pages. So that it will be easier for you to communicate and help full to get your imagination on paper before you give it a finishing touch. I found one such tool very help full https://gomockingbird.com/.
    • It is a web based service, so you can access it from anywhere.
    • You can easily drag and drop the widgets and design the page very fast.
    • Most important feature which I liked about it is to link one page corresponding hyper link or tab on other page.
    • You can collaborate with other people.
    • You can download pdf file / images.
    • It is a paid service, which start with 9$/ Month for 2 active projects and unlimited collaborators. But most important part is you can archive your project, in case you are not going to work on it for a month or more than a month. If you don't have any active project for any month you don't have to pay for that month. You can reactivate archived project and work on it again.
  • Project planner you can have tom'splanner to start with free of cost.
  • If you are working in group in different remote location, you might need to share the screen and have group meetings in that case you can use following service free of cost for screen share.
    • You can use skype screen share
    • You have join.me but its not supported to share screen from Linux machine.
    • One recent tool I found was Google Chrome Remote Desktop you will require to use Google Chrome browser. With this you can actually control remote desktop.
  • If yours is the web application which you want to host some where on internet. Either you can host it in house our use hosting service. Hosting in house requires lot of investment and its time and money consuming from the point of maintaining it initially. It may be worth having it if you are big enough to handle it. Following are few services which I found which can be cost effective.
    • To start with you can think of using Google App Engine but it depends what kind of storage you are going to use. If your application requires to use Mysql then I find Google service to be costly but you can use App Engine Data Store using either JDO or JPA with some some limitation. Like it doesn't support Many to Many relationships, Join Queries etc.
    • If you are looking for some VPS service then I was able to locate few cost effective good Services 
      • One is intovps http://www.intovps.com/ starts with 512 MB RAM, 30 GB RAID 10 Storage, 500 GB Monthly traffic, 1 Static IP and root SSH access 10$ / Month. Available to host in Fremont CA, Dallas TX, London UK, Amsterdam NL and Bucharest RO.
      • Other one is yardvps http://www.yardvps.com/ starts 512 RAM, 1 CPU core, 20 GB RAID 10 storage, 1500 GB bandwidth, 1 static IP etc with around 8$ / Month.
  • If you are looking for CDN then https://www.cloudflare.com/ is free and very good service you can use as a CDN.
       I will update it as and when I get some more information. It would be also helpful for me if any body who is reading this blog has some more information or other feedback about above mentioned service it would be helpful for me to know it.

Thursday, October 18, 2012

Mulitple persistence Unit with Guice


If you want to use Guice with multiple persistence Unit. Then its not much difficult task to do it, Guice's official wiki document says it all refer. But I feel it has missed out most important part from it i.e. to expose dependencies, if those dependencies need to be used outside the scope of give PrivateModule.

Note : I have created a complete working sample with multiple persistent unit refer http://code.google.com/p/guice-gwt/ for the code. This sample mainly demonstrates integration of Guice with GWT but I have added multiple persistent unit sample in the same.

Lets take the same example to understand how to use multiple persistent unit. In this sample there are two persistent units Address and User each having one entity Address and Person respectively ( I have taken single entities in each persistent unit for the sake of simplicity). You have separate DAO created to manage each of the persistent unit. In this example we have AddressDao and PearsonDao. As per document you need to bind dependencies with their respective private module. e.g.

I have created AddressPersistModule and UserPersistModule each of them is separate private module loading "Address" and "User" persistence unit respectively and bind Dao in respective module.


 public class UserPersistModule extends PrivateModule {  
      @Override  
      protected void configure() {  
           install(new JpaPersistModule("users"));  
           bind(PersistenceLifeCycleManager.class).annotatedWith(  
                     UserPersistService.class).to(  
                     UserPersistenceLifeCycleManager.class);  
           expose(PersistenceLifeCycleManager.class).annotatedWith(  
                     UserPersistService.class);  
           bind(PersonDao.class).asEagerSingleton();  
           expose(PersonDao.class);  
      }  
 }  


 public class AddressPersistModule extends PrivateModule {  
      @Override  
      protected void configure() {  
           install(new JpaPersistModule("addresses"));  
           bind(PersistenceLifeCycleManager.class).annotatedWith(  
                     AddressPersistService.class).to(  
                     AddressPersistenceLifeCycleManager.class);  
           expose(PersistenceLifeCycleManager.class).annotatedWith(  
                     AddressPersistService.class);  
           bind(AddressDao.class).asEagerSingleton();  
           expose(AddressDao.class);  
      }  
 }  

In respective Dao you can inject EntityManager, and Guice will take care of injecting respective EntityManager for required Persistent Unit. (Note: you will find some different mechanism in above mentioned sample code. but even if you inject just EntityManager it will work seamlessly as per mentioned in document).

Now in above code you will notice we have to expose AddressDao and PersonDao from their respective private modules. Because of which those dependencies will be available globally in given parent injector.

Now you can create the injector like

 Injector injector = Guice.createInjector( new UserPersistModule(), new AddressPersistModule(), ... any other modules );  

You will have other dependencies configured in different modules and you can inject exposed private module dependencies with them. In this way you can have service class which will have AddressDao and PersonDao injected into it and you can use them at single place. Refer below code


 public class PersonService {  
      @Inject  
      private Injector injector;  
      public boolean savePerson(Person p) {  
           PersonDao pd = injector.getInstance(PersonDao.class);  
           pd.savePerson(p);  
           return true;  
      }  
     .  
     .  
     .  
     .  
      public boolean saveAddresss(String personId, List<Address> addresses) {  
           AddressDao ad = injector.getInstance(AddressDao.class);  
           for (Address address : addresses) {  
                if (address.getId() == null || "".equals(address.getId())) {  
                     address.setId(java.util.UUID.randomUUID().toString());  
                }  
                address.setPersonId(personId);  
                ad.saveAddress(address);  
           }  
           return true;  
      }  
 }  



Tuesday, September 25, 2012

Benefits of using GWT


I have been exploring GWT for 4 years now. I have seen it enhancing and improving year over year. I have also used it in few of my projects. After using it for long I see following benefits of using GWT. I have added these point based on my experience after using GWT. So I might be wrong on some points please feel free to add your comments about the same. I would be more than happy to understand other angles of given point. As I feel there is lot I have to learn in this space.
  • Every JSP call made to server takes some CPU cycles of server to execute the JSP and return the results. Results will be mostly in the form of HTML.   
  • In case of GWT it's up to you as developer which calls needs to be evaluated by server. You can create an application with single HTML/JSP page loaded once and rest of the pages are generated on client side i.e. on browser side. Your application only have to make data calls back to the server. If your application is very big with lot of screens, you can make use of lazy loading of JavaScript. If you feel your application would become heavy then you can create multiple modules and divide the number of screens in different modules.    
  • The advantage you get with GWT is distribution of work load across individual user's browser for generation of HTML. Which in case of JSP has to be borne by the server. Even if you cache the JSP results on server, still there is a cost involved in making a call to server and server has to at least flush the cached HTML. In normal JSP based application, with increase in number of users, load on your server also increases drastically as more requests will be processed by server to serve HTML's. In turn increase in cost of Hardware. In case of GWT or any other JavaScript library your application load gets distributed across multiple browsers (clients) to generate HTML. So if user base increases, load on server should not increase that much in comparison with that of JSP application ( it also depends on how big and heavy data processing your application is doing on server side. If you are doing some heavy data processing on server then in that case even if you use GWT with increase in number of users your hardware cost may increase) server only need to handle data calls.
  • As GWT client application is written in Java, one get an opportunity to catch syntactical mistakes at compile time because of the same (Though it doesn't support all the JRE classes as those features are not supported by the browsers itself). Lets take an example to understand what I am saying. If you misspell a JavaScript variable name by using pure JavaScript library. The only way you can catch such mistake is to run the application and test for desired results.
  • Java features like Generics and Annotations are use full and can be used in your application. 
  • One can make use of existing available libraries or write one to generate code as per requirement with ease as the code that need to be generated need to be in Java. GWT compiler takes care of compiling it and converting it in to JavaScript.
  • Management of code becomes more easier.
  • One can simply write some common business logic in a such way that it can be used in GWT client side code and also on server side code as its in Java e.g. validation of data or some common utility functions.
  • With the use of GWT eclipse plug-in, you can easily debug the client code in Java for your business logic.
  • As GWT compiler compiles your client Java code and generates JavaScript out of it. Which you need deploy it to your server, and it gets served and executed in user browser when requested. While generating this JavaScript it will do some optimisations.
    • It doesn't consider dead code while generating JavaScript, when I say dead code I mean to say "code which is there but not getting called from main flow". In turn reduces the effective size of your final JavaScript code.
    • It takes care of obfuscating generated JavaScript code.
    • It does minification of generated JavaScript code.
    • And more importantly it will generate browser specific optimised code separately. When I say separately, it will generate browser specific separate JavaScript which will be served when respective request is received from given browser. Which in turn reduces the size of the JavaScript code which gets downloaded for specific browser as it doesn't contain all browser specific handling in one single code.
  • If you are writing your application for different languages i.e. English, Hindi, Marathi etc by using Internationalisation feature of GWT. While generating JavaScript code it creates copy per language and browser combination. Which makes generated JavaScript code for given combination of language and browser most optimal and small one.
  • In case you need to use direct JavaScript which can be called from Java GWT code one can do it using JSNI ( JavaScript Native Interface). One can even call GWT Java Code back from JavaSctipt.
  • If you want to make Bookmark able pages then you can make use of History feature of GWT.
  • If you want to make use of JSON as data format for communication and manipulation it has very good feature called JavaScript Overlay Types.
  • Deferred Binding feature of GWT is a good feature which I suppose is possible to provide because of Java.
  • You can build your user interface using available widgets of GWT in Java Swing style. You can even create your custom widgets very easily.
  • If you want to build your user interface ( Web pages ) in pure html style, you can make use of Declarative UI feature of GWT. Which I feel one of the major feature of GWT. Which makes it easier for developer to build pages in pure HTML style. Which I suppose is more maintainable than Swing style coding. And most importantly you can still have your logic in Java and only presentation part in pure HTML. (Note: which ever method you use (Declarative UI or Swing Style) ultimately its going to be HTML only but what makes difference is the way you code and maintain it).
  • Client Bundle feature of GWT makes it very easy to manage your other web resources like css, images and other text contents.
    • CSS resources makes it possible to have conditional logic inside your css. You can also access some dynamic values from you GWT client side Java code. It will also take care of obfuscating your css classes. And most importantly GWT has automated generation of interfaces from your css files to use css classe's.
    • Image resource makes it easier for developer to use images in your application in very easily maintainable fashion. When I say easily I mean to say when you want to use images in GWT Java code rather than using hard coded URL, you can use image resource. Benefit you will get using image resource is if you are going to change the location or use some different image with different name you just need to change it at one location. More important feature of image resource is when you use it with CSS resource as sprite. It will take care of making that image as in-line data uri. I don't say its not possible to do it with other frameworks what's more important is how fast and easily you can do it. GWT makes it much easier for you.
    • Data Resource add some optimisation for data files like .pdf to rename those files based on their contents to make it strongly cacheable by browser. Small data files may be converted in to in-line data uri.
    • By making use of Client Bundle for other web resources and if you properly structure you application into different modules. It can become completely reusable modules as whole with every resource. What's the big deal about reusable modules? well if you are using images by using direct URL in some module. And if you include that module in other module and try to use the components created in that module you still need to have those images copied to public URL of your final application. Which you don't have to do it if you use those images as image resources. 
    • Other optimisation you can achieve by creating small modules by using client bundle for css and images. Where you can chose to include only required modules inside your final module/s. The difference it will make is final module JavaScript and other resources will only contain required contents and not the whole contents even if you want to use small piece of the module.
  • Cell Widgets: To present paginated data collection GWT has Cell Widgets. There are widgets like CellTable, CellList, CellTree and CellBrowser. 
    • CellTable is meant for presenting data in paginated table format, it has feature where in you can change the contents of given cell in place. It supports pagination on client side  and server side both, it support sorting on column and also it supports selection of one or multiple records and generating events for the same.
    • CellList can be used to present data in list format and items can displayed in custom format. It also supports client and server side pagination and selection of one or multiple records and generates events for selection.
    • CellTree and CellBrowser can be used to present data in tree format.
  • Communication with server from GWT client code. It supports multiple ways to implement client server communication. 
    • If you are not concerned about the protocol being used for data transfer then it GWT RPC mechanism. Its very easy to integrate your client side code for data transfer with server. You can define custom DTO's (data transfer object) in client code which can be even used on server side code. Server side implementation accepts the same DTO's as parameter or return value. Everything else is taken care by GWT RPC frame work. It even propagates exceptions raised from server side code to caller in client side code (Provided you need to define those Exception classes inside client side code package. GWT RPC internally makes use of AJAX calls with their own custom protocol for data transfer.
    • If you don't want to use GWT RPC you can make server AJAX calls to fetch data from server using Request Builder. Which is also much easier to implement.
    • It also has interesting feature Request Factory. With this feature you can make your DAO or Service layer exposed to get called from client code. To do that you need define few set of interfaces for your service and custom data types. And using these interfaces you can access those services from client code. I have written maven plugin to generate these interface. If you annotate your DAO layer with some required annotations refer refer mvn-helper-test module inside it for usage. Request Factory is more targeted to integrate with ORM layer like JDO or JPA on server. It has a support to call persist on given entity from client code. And most important when you call persist method it compute and send only change (delta) to server to save.
    • If you want to make cross domain JSONP call you can do the same refer
  • Logging
  • Junit
  • Deployment

Monday, July 23, 2012

GWT Cell Widget sample using UiRenderer with GWT 2.5-RC1


GWT Cell Widget sample using UiRenderer.


            I tried this sample with GWT 2.5 RC1 release. For official documentation refer. Below sample is simple sample which will display contents of Person entity using custom cell. And such list of entities can be displayed with cell list.

Person.java


 public class Person {  
   private String  fname;  
   private String  lname;  
   private String  emailid;  
   private int    age;  
   /**  
    * @return the fname  
    */  
   public String getFname() {  
     return fname;  
   }  
   /**  
    * @param fname  
    *      the fname to set  
    */  
   public void setFname(String fname) {  
     this.fname = fname;[email protected]   
   }  
   /**  
    * @return the lname  
    */  
   public String getLname() {  
     return lname;  
   }  
   /**  
    * @param lname  
    *      the lname to set  
    */  
   public void setLname(String lname) {  
     this.lname = lname;  
   }  
   /**  
    * @return the emailid  
    */  
   public String getEmailid() {  
     return emailid;  
   }  
   /**  
    * @param emailid  
    *      the emailid to set  
    */  
   public void setEmailid(String emailid) {  
     this.emailid = emailid;  
   }  
   /**  
    * @return the age  
    */  
   public int getAge() {  
     return age;  
   }  
   /**  
    * @param age  
    *      the age to set  
    */  
   public void setAge(int age) {  
     this.age = age;  
   }  
 }  


PersonCell.ui.xml

 <ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'>  
   <ui:with field='person' />  
   <div>  
     First Name :  
     <span>  
       <ui:text from='{person.getFname}' />  
     </span>  
     <p>  
       Last Name :  
       <span>  
         <ui:text from='{person.getLname}' />  
       </span>  
     </p>  
     <p>  
       Email :  
       <span>  
         <ui:text from='{person.getEmailid}' />  
       </span>  
     </p>  
   </div>  
 </ui:UiBinder>  

PersonCell.java

 public class PearsonCell extends AbstractCell<Person> {  
   interface MyUiRenderer extends UiRenderer {  
     void render(SafeHtmlBuilder sb, Person person);  
   }  
   private static MyUiRenderer  renderer  = GWT.create(MyUiRenderer.class);  
   @Override  
   public void render(com.google.gwt.cell.client.Cell.Context context, Person value, SafeHtmlBuilder sb) {  
     renderer.render(sb, value);  
   }  
 }  

Using above created PersonCell

     PersonCell cell = new PersonCell();  
     CellList<Person> cellList = new CellList<Person>(cell);  
     List<Person> list = new ArrayList<Person>();  
     Person p = new Person();  
     p.setFname("Pranoti");  
     p.setLname("Patil");  
     p.setEmailid("[email protected]");  
     p.setAge(30);  
     list.add(p);  
     p = new Person();  
     p.setFname("Pandurang");  
     p.setLname("Patil");  
     p.setEmailid("[email protected]");  
     p.setAge(30);  
     list.add(p);  
     p = new Person();  
     p.setFname("Ravi");  
     p.setLname("Kumar");  
     p.setEmailid("[email protected]");  
     p.setAge(30);  
     list.add(p);  
     cellList.setRowCount(list.size(), true);  
     cellList.setRowData(list);  
     RootPanel.get().add(cellList);   

Out put of above sample :

First Name : Pranoti Last Name : Patil
Email :.[email protected]
First Name : Pandurang Last Name : Patil
Email : [email protected]
First Name : Ravi Last Name : Kumar
Email : [email protected]


Refer discussion.






Thursday, June 28, 2012

Advantage of using Maven over ant.

What is Maven?

        It is a tool that can be used for build process and managing Java project. The way ant is used for build process of Java projects. But it does it very smartly and you can set-up your Java project very fast.

Advantage of using Maven over Ant.
  • With ant you have to do everything on your own, you have to write lot of code/configuration in build.xml. Where as maven is simple, easy and with minimal code you can start. 
  • The main important advantage you get is to manage your artifact ( could be .jar or .war ) by way of properly versioned artifactes. And easy way of managing dependencies (as in other libraries required by given project) of of a project. 
  • Another advantage it has which is more interesting for people who are using Eclipse as IDE. That is maven project can be directly imported into Eclipse with the help of few plugins for more details refer. And it will setup a required eclipse project by looking at your maven build script. You might say it is possible with ant also you just have to configure Ant builder in Eclipse and one can fire the build from eclipse but it simply calls ant build as it is the way it can be fired through command prompt. But you yourself have to configure and setup project by configuring all of its dependencies. There are ways to import ant build files but it fails to import some complicated ant projects. Where as in case of Maven it doesn't fire maven build as it is the way it will be fired through command prompt. When you import maven project into eclipse it sets up eclipse project on its own by configuring all of its dependencies. It also configures eclipse builders that are used to build given project, which will make it more easier for developers to work in properly configured eclipse project.
  • It has major and important feature to share your artifact with other people required in your company or even you can share with wide audience over Internet with the help of some openly available software tools.
  • It has life cycle phase in which your junits are invoked.
  • It enforces proper arrangement of your source code directories. 
  • I have seen in lot of the projects which uses ant as a build tool. Keep all their source files at one location. And generate multiple artifactes from the same source location by including and excluding some packages. This way of managing code makes it more difficult for a new person to understand the code arrangement and what goes in which artifact. This could be bad way of doing things, for which ant should not be blamed. But in contrary Maven don't allow you to generate multiple artifact by including few resources in one artifact and excluding those from others. That way you are forced to create another module and add dependency of that module where ever it is required. That makes your code more readable and segregated and looking at the dependency you can easily make out at what all places it is getting used.
refer this discussion for more detailed insights

look out for my next blog on Start with maven

Start with maven


Start with Maven

            To start with Maven lets create a sample application which will result into artifact packaged into .jar. Maven being build system for Java application, you need to have following software's installed on your machine and set few environment variables.
  • JDK may be latest version at least jdk 1.6.
  • Maven installation download latest version.
  • Set Maven's bin directory into path variable so that it is accessible from anywhere.
  • Set JAVA_HOME environment variable pointing to required JDK installation
 It is very easy to create simple jar project with the help of Maven archetype ( in short it is a Java project templating tool, which has different templates to create different kinds of projects. Which makes it easier for developer to setup the required project quickly with bare minimal configuration)

1:  mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart  

When you run above command it will run a wizard which will ask you few inputs following are the details for the same.

1:  Define value for property 'groupId': : com.sample  

A.  groupId: you need to provide meaningful group id to your module/artifact. Group Id is something which will help you categorize your artifacts. So when you have multiple modules you have clear segregation of those modules. It acts like namespace or package (most prominently similar to package concept inside java).

1:  Define value for property 'artifactId': : test  

B. artifactId: You need to provide some meaningful name to your module/project/artifact.

1:  Define value for property 'version': 1.0-SNAPSHOT: :  

C. version: You need to provide the version for given module/project. It shows default value as "1.0-SNAPSHOT". Will explain in detail in my next blog what's the meaning of SNAPSHOT. In short when you are developing your code and it is under development for long time. You should keep the version of your module in prefixed with "-SNAPSHOT".

1:  Define value for property 'package': com.sample: :  

D. package: This input is not exactly related to artifact. When I say exactly related it means its not part of the requirement to define a module/project in maven. This is being asked by this archetype is because this is quick start template. So it creates a sample project with sample "Hello World" app, to place the required Java class, it will ask you to provide some package name. As default value it will assume value of the groupId you have provided previously.

Once you enter all the values required by the wizard, it will show you entered values for required parameters and will ask you to confirm the same. Once you confirm the inputs. It will create a sample module/project with given input.

If you look into directory from where you run this quick start archetype, it must have created a directory with the same name as that of artifactId. And directory structure under that directory will be as follows

1:  test  
2:  |-- pom.xml  
3:  `-- src  
4:    |-- main  
5:    |  `-- java  
6:    |    `-- com  
7:    |      `-- sample  
8:    |        `-- App.java  
9:    |            
10:    `-- test  
11:      `-- java  
12:        `-- com  
13:          `-- sample  
14:            `-- AppTest.java  

This quick start archetype creates a jar module. When I say jar module, packaging type of the module will be "jar".

To make a build from command prompt. Follow below commands.

1:  $ cd test  
2:  $ mvn clean package  

This will make a build, Maven creates target folder inside respective module folder, to generate build output, once you run above command to build the module. You will find a jar created inside test/target folder with the name "test-1.0-SNAPSHOT.jar". So final artifact will be generated as "<artifactId>-<version>.jar" for jar packaging type. One can override the default name with their own name by using <finalName> tag inside <build> tag inside your pom.xml file (refer pom reference).

To test the application which just compiled run following command

1:  $ java -cp target/test-1.0-SNAPSHOT.jar com.sample.App  

This should print out as

1:  Hello World!  


For more details refer getting started guide and maven in 5 mins.

To import the maven project inside eclipse to setup eclipse project refer


Sunday, May 20, 2012

GWT use I18 Message resource in uiBinder

To use I18 Message resource in uiBinder you need to follow the same mechanism as that of ClientBundle

In your corresponding java class add @uiFactory method which will return the object of required Message interface e.g.

package com.test.module.client;

public interface Messages extends com.google.gwt.i18n.client.Messages {
 
  @DefaultMessage("Home")
  @Key("home")
  String home();
}

public class MyUiBinder extends Composite{
......
.....
.....

    @UiFactory
    public static Messages getResources() {
        return GWT.create(Messages.class);
    }
}


And you can use the same inside corresponding MyUiBinder.ui.xml file as

<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
    xmlns:g='urn:import:com.google.gwt.user.client.ui'>

    <ui:with field='msg'
        type='com.test.module.client.Messages' />
    <g:HTMLPanel>
                 <g:Button text='{msg.home}'></g:Button>

    ......
    ......
    ......
    </g:HTMLPanel>
</ui:UiBinder>



Get New line after using float:left or right

To get new line after using float property on previous element. I found straight forward solution to use either "clear: both;" on next element.
e.g.
<div style="float: left;">
               ....
</div>
<div style="clear: both;">

               ....
</div>

for more details refer  http://www.positioniseverything.net/easyclearing.html