Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, February 25, 2011

Playing with the Play Framework

Back to blog after very long time. This post is basically about the new exciting Java web framework Play and a small implementation of app using it: pptViewer a simple PPT file viewer.

After successfully implementing (basically porting) a small application in Play I can say that every Java programmer who wants to taste agile development must use this framework at least once. Its really simple and lighting fast to build (small to medium size) applications. I have selected this framework for few of my upcoming prototype developments.

The demo application is very trivial one. It accepts a Microsoft PPT file and shows the slide contents on pages.  Apache POI is used to extract PPT file content and stored in MySql database. The original application is intended to manage multiple format Office files over web and is currently under development using Spring MVC. I choose to rebuild a small part of it using Play to evaluate it for slightly bigger and complex application and it worked really well. The framework documentation is very clear and concise for the beginners to quickly learn and implement stuff. The Play Community is growing day by day and illustrates a lot of new features\implementations of the framework.

Play provides most of the features required by any standard web applications (just like RoR, Django and Grails - actually the search is not over yet)). Standard (Static) MVC model, no upfront compilation (a great boon), front-end scripting and full Java stack are few of them. Play infrastructure can be extended with Modules (plugins) and many useful modules are already available. Play can fit nicely between regular Java web framework like Spring MVC and very dynamic framework like Grails. In the end Play has many similarities to Rails and one can say that like many other modern web frameworks (Grails, Roo) Play Team is also quite inspired from RoR.

After "playing" with GWT, Vaadin, Roo and Grails for a while and with my ongoing implementation I think Play is a very good framework in one's framework wardrobe.

A very good discussion of Play and RoR can be found on this Stackoverflow link.

Although my journey with Play is quite short till now but I quite impressed at the moment (if it doesn't work then something new will come, it has always come and I will start using that :) ).

Keep "play"ing.

(Special credit to Linode which enabled me to host the application from setup to deployment in just couple of  hours. I found Linode setup rather easy enough than to convert the application to GAE compatible.)

Wednesday, April 14, 2010

jVark - A small Java/XMPP library to play with Aardvark

After spending some time with Aardvark, i found the tool really great to get answers pretty fast. Aardvark provides many ways to interact with the service however there are no APIs available as such to interact with the service programmatically. Meanwhile I was trying to make my hands dirty with Google GTalk service and developed a small and silly utility to interact with Aardvark service through GTalk in Java.

The library is very basic and helps the developer to connect to Aardvark and fire some command and see the response from Aardvark. jVark source is available at http://code.google.com/p/jvark

However the library requires significant amount of improvement for extensive use.

Friday, March 12, 2010

Another NoSQL Database : FluidDB

FluidDB is another database in the NoSQL category. It is a cloud based data store and follows the Wiki style approach for data storage. By Wiki style user can create objects in the FluidDB space and modify the existing one. Yet it uses a permission model which differentiates the it from being exact Wiki like.

FluidDB provides HTTP API interface with JSON and provides the HTTP Basic Authentication. FluidDB is in the early private Alpha stage and exposed to only limited number of users. A Sandbox is available where anyone can play with the database and for more detail look one can request the private access by sending the FluidDB Team a Mail request.

FluidDB is basically divided into four parts: 1)User 2)Namespace 3)Tag 4)Object. The User is the primary entity like in any other case. User will create Namespaces, Tags or Objects. Namespace is a logical name and physical separation which primarily describes the Subject the User is interested in like Movie, Sport, Book, etc. Tags are the attributes which describe the subject further in detail like Genre, Year and Awards Tags in Movies Namespace. Tags can exist without Namespaces also like Event, Hot, New can be used irrespective of the subject. Objects are the key entities as they contains actual data. An Object can be created with a String value like http://twitter.com/dhavaln or Die Hard With Vengeance as a topic which can be expressed in detail with various Tags.

An Object can be annotated with Tags from any User or any Namespace. By attaching a Tag to an Object user can provide additional information as a Tag Value for that Object like:

Object: Die Hard With Vengeance
Tags:
  Movie=
  Movie/Genre=Action
  Movie/Year=1995

As you can see same name can be used as a Namespace and as a Tag also. Tag may not contain any value alternatively known as Marker Tags.

FluidDB provides a simple query mechanism through which Objects can be search in the FluidDB space with Tag and Tag values. The following query will return all the Objects having Movie/Year value as 1995.

/Movie/Year = 1995

/Movie/Year > 1995 will return all Objects having Movie/Year value greater than 1995. There are many other conditional approaches provided by FluidDB for searching and can be found here.

Many developers has started using the interesting FluidDB and created API libraries for various languages which can be found here. I have already started using the database with JFluidDB and finding its usefulness in many cases.

The simple HTTP and JSON based interface makes FluidDB widely acceptable in many problem domains in various languages and frameworks.

Tuesday, March 2, 2010

Easyb Revisited - A Groovy based BDD Testing Framework

easyb is a behavior driven development framework for testing. easyb accepts the Groovy syntax for better explanation of the test scenarios. The first time i encountered easyb, i could not understand the syntactical and semantical sugar but after learning Groovy now i am finding the framework pretty good and useful.

easyb provides two types of templates: one is Ruby RSpac based "it 'should...'" style and another is "given".."when".."then" style. I use the "given.." style because its very explanatory and yet simple make someone understand.

Let's take an example to understand the benefits of the easyb from a programmer and non-programmer's point.

// A utility class to be tested
public class StringList{
      public void add(String element){
           if(element == null){
                  throw new RuntimeException("Null values not allowed");
           }
           // add value
      }
}

//easyb story - given..when..then style
scenario "check StringList with null value addition", {   // scenario with a reason
     given "an empty StringList", {  // what all things available in the scenario
          strList = new StringList()
     }


     when "insert null value", {   // what all operations has to be carried out in the scenario
          insertNull = {
                strList.add(null)
          }
     }


     then "a runtime exception should be thrown", {  // what should be the result
           ensureThrows(RuntimeException){
                  insertNull()
           }
     }
}

//easyb story - it 'should..' style
description 'check StringList with null value addition'


before "initialize the StringList before each spec", {
    strList = new StringList()
}


it "should throw an exception when null value inserted", {
    ensureThrows(RuntimeException){
         strList.add(null)
    }
}

The above stories can be easily divided into two parts one who writes plain test scenarios and another who fills the valid code for testing. No additional knowledge or logic is required to write the test case. An online system can very well generate this kind of templates based on the user input.

// plain test scenario
scenario "check StringList with null value addition", {   // scenario with a reason
     given "an empty StringList", {  // what all things available in the scenario
     }

     when "insert null value", {   // what all operations has to be carried out in the scenario
     }

     then "a runtime exception should be thrown", {  // what should be the result
     }
}

The development or testing team can fill the scenario blocks later with actual code. easyb generates report with pending scenarios and executable scenarios. Pending scenarios are those in which no test code has been added so user can easily identify pending test cases from the reports.

The textual description is right available with the code and is also executable and comes in the result report. The approach helps team members to understand the test cases without much efforts or external documentation. 

The easyb comes in a .tar.gz distribution having easyb jar along with Groovy and Apache Commons CLI. So no additional Groovy dependencies are required.

...dev\tdd\easyb>java -cp .;$easyb_home\easyb-0.9.6.jar;$easyb_home\commons-cli-1.2.jar;$easyb_home\groovy-1.6.4.jar org.easyb.BehaviorRunner *.groovy

The above statement will execute all the .groovy files through easyb interpreter BehaviorRunner. There are various switches for detail result of the execution.

easyb generates the result reports in various formats like PlainText, HTML and XML, which can be integrated with any test-case reporting system.

The flexible syntax helps the business analyst and testing team to create test scenarios independent of the development team. A web-based test scenario identification system would be very helpful in generating various kinds of test cases from different users.

I use Netbeans IDE for all my development purpose. There is no plugin available for NetBeans but Eclipse and IntelliJ provides plugin for easyb. For NetBeans one can use the Ant scriptlets provided at Running easyb.

Additional refrences:

Monday, March 1, 2010

bsGrid - A simple HTML/Javascript/jQuery based data grid

bsGrid is a small javascript/jquery based data grid i have developed for data visualization. The grid is Ajax enabled and for each data operation calls a special service URL.

The grid provides basis functionalities like Sorting, Complex Searching, Paging, Column Freezing, etc. The server to client communication is in JSON so that simple POJOs can be used on the server side.


As of now the code uses Servlet for initial rendering but soon that will be converted to a jQuery Plugin for multiple platform. For other detail refer to the Google Code project site : http://code.google.com/p/bsgrid

Saturday, February 20, 2010

GWT client with REST

This article explains a small prototype i developed for a friend to show how REST services can be used can be used from the client code and avoid additional RPC call. The demo explains only two fundamental class structures to access the remote service.

RequestBuilder
GWT client API is having an HTTP request builder class which helps the application to make remote connection through HTTP request and supported methods (GET, POST).

RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, urlAddress);
builder.sendRequest("", new RequestCallback() {
  
  public void onResponseReceived(Request request, Response response) {
     //use response.getText() to get the resulting text from the service
  }


  public void onError(Request request, Throwable exception) {
     // exception handling
  }
});

XmlParser
GWT client API also provides XML parsing capabilities but to use that XML.gwt.xml has to be included in the modules file.

The following code can parse the XML text and prepare complex node list which can be traversed to access the attributes and node values.

    Document doc = XMLParser.parse(response.getText());

Once Document instance is generated program can start traversal from the root node or can search for the particular nodes based on the name.

    NodeList nodeList = doc.getChildNodes(); // to start from root node
    NodeList nodeList = doc.getElementsByTagName(nodeName);  // to start from selected node

Full source code with example services is available here.

Thursday, February 18, 2010

Vaadin-Spring Integration

I remember the time when i was trying to integrate Spring with Struts2 and GWT applications. The problem was rather documenting the integration stuff i tried to remember them and as usual tend to forgot them. So this time have decided to document the Spring integration with Vaadin.

  • web.xml changes
So first we need to add the Spring Context listener to load the bean configuration file.

<listener>
  <listener-class>
    org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

Add the Spring Servlet to intercept Vaadin requests

<servlet>
  <servlet-name>VaadinSpringServlet</servlet-name>
  <servlet-class>com.dhaval.web.vaadin.spring.servlet.SpringApplicationServlet</servlet-class>
  <init-param>
    <param-name>applicationBean</param-name>
    <param-value>testApplication</param-value>
  </init-param>
</servlet>

<servlet-mapping>
  <servlet-name>VaadinSpringServlet</servlet-name>
  <url-pattern>/vaadin/*</url-pattern>
</context-param>
  • Spring Servlet
This servlet connects the Spring with Vaadin. The servlet loads the Vaadin Application class and dispatches all the HTTP requests/responses. The Servlet is available in the Simple Application provided by Vaadin Team for Spring integration.
  • Spring bean configuration
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property>name="driverClassName" value="${db.driver}"/>
  <property>name="url" value="${db.url}"/>
  <property>name="username" value="${db.user}"/>
  <property>name="password" value="${db.pass}"/>    
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  <property>name="dataSource" ref="dataSource"/>
</bean>

<bean id="dao.user" class="com.dhaval.web.vaadin.spring.dao.UserDaoImpl">
  <constructor-arg>ref="jdbcTemplate"/>
</bean>

<bean id="testApplication" class="com.dhaval.web.vaadin.spring.MyApplication">
  <constructor-arg>ref="dao.user"/>
</bean>

testApplication bean id is same as we have given in the web.xml as an init-param to Spring Servlet.
  • Vaadin Main Application class
This is my Vaadin Application class

public class MyApplication extends Application{
    private UserDaoImpl userDao;

    public MyApplication(UserDaoImpl userDao){
        this.userDao = userDao;
    }

    public void init() {
        Window mainWindow = new Window("Simple Vaadin Spring Integration");

        final TextField txtUser = new TextField("Enter username");
        Button btnCheckUser = new Button("Check Username");
        final Label lblCheckMsg = new Label("");

        btnCheckUser.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                boolean result = userDao.hasUser(txtUser.getValue().toString());
                if(result){
                    lblCheckMsg.setValue("Available");
                }else{
                    lblCheckMsg.setValue("Not Available");
                }
            }
        });

        mainWindow.addComponent(txtUser);
        mainWindow.addComponent(btnCheckUser);
        mainWindow.addComponent(lblCheckMsg);

        setMainWindow(mainWindow);
   }
}

The full source code is available at vaadin-spring-integration in download section.

Tuesday, February 9, 2010

Calling Groovy closure from Java

After spending some time with Groovy alone i thought to mix Groovy code with Java. As closures seems the most weird in Groovy i tried to access a closure method from the Java class.

// Groovy code
class ClosureTest{
String firstName
String lastName

def proc(Closure closure){
closure.call(firstName, lastName)
}
}

// Groovy client
def ct = new ClosureTest()
ct.firstName = "dhaval"
ct.lastName = "nagar"
ct.proc{fn, ln -> println "$fn, $ln"}

// Java client

import groovy.lang.Closure;

class JavaClosureClient{
public static void main(String[] args){
ClosureTest ct = new ClosureTest();
ct.setFirstName("dhaval");
ct.setLastName("nagar");

ct.proc(new Closure(ct){
public Object call(Object[] argument){
System.out.println(argument[0] + ", " + argument[1]);
return null;
}
});
}
}

Well the difference shows the verbosity of the Java client compared to the Groovy one.

At my workplace we are not in a position to use Groovy extensively but with such silent integration between the two i am sure we can leverage some of the Groovy features.