Tuesday, August 10, 2010

Installing Rhino on mac

From Rhino :
Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.

Rhino is an implementation of JavaScript in Java. Features include full implementation of JavaScript 1.7 and allows direct scripting of Java and more...

There are some good frameworks available like this one from my friend Fred Polgrady, http://github.com/sustainablecode/datastore

I will provide an easy way of installing Rhino on a mac. Follow these three steps for an easy installation...

1. Download Rhino

2. Create "Java/Extensions" in home directory "~/Library/Java/Extensions"

3. Copy the js.jar file from the downloaded Rhino zip file to "Extensions" directory.

Thats it!! You are all set to use Rhino.

$ java org.mozilla.javascript.tools.shell.Main

Rhino 1.7 release 2 2009 03 22

js> eval("print('hello')")


Thats all!!

Monday, August 9, 2010

Java Servlet Specification 3.0 - Overview and Quick Intro

Java Servlet Technology which is the widely accepted technology for creating dynamic java web applications and which is behind all the modern java web frameworks. This major release tries to address the most wanted featues from the community as a JSR and is approved in the form of JSR 315 and is planned to be part of JEE6 (JSR 316). The main focus for this release in helping in ease of developemnt using Java annotations, Pluggability and extendability of using fragments, Asynchoronos Servlet support and security enhancements.
Ease of Development
Using annoations Servlets join the band wagon of using declarative-style programming along with JPA, EJB3, Spring and the rest. This helpa developing Servlets, Filters more easily with the code and the related configuration in the same place and thus making the web.xml an optional. It's the Servlet 3.0 supported contianer which will process all the classes at boot time to find out all the annotated servlets, filters and listener classes and made them available for serving. If you don't want the container to process all the class files to figure out the annotated classes, you can turn it off using the new web.xml configuration parameter metadata-complete on web-app element to true. The other important addition which helps in ease of development and configuration is programmatic setup of serlvets and filters.

The new sample web.xml configuration

<web-app xmlns=“http://java.sun.com/xml/ns/javaee” xsi=“http://www.w3.org/2001/XMLSchema-instance
                schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
        <display-name>Sample Web Application to test Servlet 3.0 </display-name>

@WebServlet and @WebFilter are the two main annotations for configuring the servlets and filters in Servlet 3.0.

The urlPatterns attribute of the @WebServlet annotation qualifies the URL's for this servlets to respond.

@WebServlet(name = "helloServlet", urlPatterns = {"/hello"})
public class HelloServlet extends HttpServlet {
         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                PrintWriter writer = response.getWriter();
                writer.print("<h1>HttpServlet using Servlet 3.0</h1>");

Note that the class still needs to extends HttpServlet (It is a mandatory requirement)

Servlet filters and Listeners follow the same pattern except that the class needs to implement Filter and ServletContextListener classes and the annoation @WebFilter, @WebListener respectively

Asynchronous Support
Asynchronous Http Request Processing (aka Comet) is a way that allows you to process a single Http Request using non-blocking I/O. More details about Coment and Asynchronous programming here(http://en.wikipedia.org/wiki/Comet_%28programming%29). Basically all this means is your servlet can continue working on the request while waiting for some other resource to be released or some other operation to be done like a database update.
To enable async support for your servlet, you can enable it using asyncSupported attribute of @WebServlet to true. Enabling this will give you support for few new methods in the Servletrequest itself inclluding startAsync(servletRequest, servletResponse), startAsync(), and getAsyncContext(). Once async attribute is set on the Servlet class you should either call startAsync(servletRequest, servletResponse) or startAsync() method to make an asynchronous request.
A simple example:

@WebServlet("/foo" asyncSupported=true)
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) {
AsyncContext aCtx = request.startAsync(req, res);
ScheduledThreadPoolExecutor executor = new ThreadPoolExecutor(10);
executor.execute(new AsyncWebService(aCtx));

public class AsyncWebService implements Runnable {
AsyncContext ctx;
public AsyncWebService(AsyncContext ctx) {
this.ctx = ctx;
public void run() {
// Invoke web service and save result in request attribute
// Dispatch the request to render the result to a JSP.

More detailed tutorial on writing Asynchronous Servlets in my next entry.

A new notion called web fragments has been introduced in servlet 3.0 specification which helps reduce the configuration. A webfragment is a part or all of web.xml configuration that can be specified by any framework or a jar file dropped into the web application. In this way the framework can by default configure itself to work with the application with out the application developer confioguring it.

Thursday, September 11, 2008

Partial mocking of objects using easymock classextensions

Ocassionally, some of your methods in your classes need to call some other public methods in the same class to get the job done. But when writing unit tests for the calling methods, you want to keep your tests isolated from the calls to other public methods. I encountered such a scenario recently and found that Easymock can help you by mocking some of the methods while keeping the rest of the methods intact.

Let us see an example,
The BlogSearchService has two public methods, first method filterBlogsByAuthor takes an author name and a list of blogs and returns all the blogs written by that particular order author.
The other business method searchBlogs will take a search paramter and the author, it will get all the blogs by the search parameter using a custom logic and do some other house keeping tasks like sorting them by published date and number of comments and then filter the methods by author.

package com.teja.blogs;

import java.util.Collections;
import java.util.List;

* @author Teja

public class BlogSearchService {

public List<Blog> searchBlogs(String searchString, String author){

//do some custom logic here on these blogs like sorting them by posted date.
return filterBlogsByAuthor(author, Collections.EMPTY_LIST);

public List<Blog> filterBlogsByAuthor(String author, List<Blog> blogs){
return Collections.EMPTY_LIST;


When writing the test cases for the second method, I don't want to test the other public method filterByAuthor as
(i)it has already been tested by other test cases,
(ii)I want to keep my test cases more unit.

So in my test case where I am testing my searchBlogs, I am creating the mock service class which has mock methods only for filterBlogsByAuthor, but the actual mehtod(searchBlogs) which is about to be tested is not.
As usual you can do expectations on the mock class, replay and verify as if it is some other external resource being mocked.

To create a partial mock class of the service, the extra parameter you need to pass is the name of the method to be mocked and the parameter types it accepts (coz, it need to know which version of the method you want to mock if you have overloaded methods)

Here is our test class:

package com.teja.blogs;

import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.easymock.classextension.EasyMock;

* @author Teja

public class BlogSearchServiceTest {

public void testSearchBlogs() throws NoSuchMethodException {
String author = "Teja";
BlogSearchService blogSearchService =EasyMock.createMock(BlogSearchService.class,
BlogSearchService.class.getMethod("filterBlogsByAuthor", new Class[]{String.class, List.class}));
EasyMock.expect(blogSearchService.filterBlogsByAuthor(author, Collections.EMPTY_LIST)).andReturn(Collections.EMPTY_LIST);
blogSearchService.searchBlogs("easymock", author);


Saturday, September 6, 2008

Pagination in rails using will_paginate

Pagination is a technique of presenting large amount of data on the UI, allowing the users to navigate between pages/data in an easy way.
Being a java developer for so many years, I remember doing dirty logic to achieve pagination to using some very useful and advanced tag libraries like displaytag. What ever may be the technique, pagination is never been an easy task.
But when I started playing around with rails and I got a situation where I need to do some pagination. And I readily found a gem will_paginate and doing pagination on rails is a breeze.

Lets get started first by installing the gem.

sudo gem install will_paginate

To check whether the plugin installed successfully or not, you can do the following in your rails console.

defined? WillPaginate
ActiveRecord::Base.respond_to? :paginate

Now lets add pagination support to an imaginary page listing all the clients

  def list_clients
@clients = Client.paginate(:page => params[:page], :per_page => 5)
and then render the pagination in the ui using this simple snippet


<%= will_paginate @clients %>
<!--Loop through all the clients and printem-->
<table width=100% cellpadding=0 cellspacing=0 border=0>
<% for @client in @clients do%>
<tr class='client_details'>
<td align='center'><%=@client.client_name.upcase%><
<%=@client.address_line_1%>,<%=@client.address_line_2%><br />

The code <%= will_paginate @clients %> will add the links to previous/next page along with the page numbers to naviage.
The next few lines of code is just to print the client details.

Monday, August 25, 2008

Developing web services using Spring ws and JAXB marshaller

Spring web services a product of spring community, helps in developing web services using contract first web services and helps in manipulating the xml in many ways. In this tutorial I am about to show a step by step guide in developing spring web services using JAXB as mashalling technology.

You can download spring, spring web services here.

We are about to develop a web service which search the blogs based on a search criteria on title string and published date.

So lets get started,

1.Create a web application
This is a general spring web MVC application. for a skeleton application, you can just run this maven archetype to quickly start with,

mvn archetype:create -DarchetypeGroupId=org.springframework.ws \
-DarchetypeArtifactId=spring-ws-archetype \
-DarchetypeVersion=1.5.4 \
-DgroupId=com.teja \

Or you can just add the spring nature to your existing web application by configuring the web.xml shown in the next step. Here is the file structure I am using for this simple demo.

2.Configure web.xml.
  1. <servlet>

  2. <servlet-name>spring-ws</servlet-name>

  3. <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>

  4. </servlet>

  5. <servlet-mapping>

  6. <servlet-name>spring-ws</servlet-name>

  7. <url-pattern>/*</url-pattern>

  8. </servlet-mapping>

  9. <servlet-mapping>

  10. <servlet-name>spring-ws</servlet-name>

  11. <url-pattern>*.wsdl</url-pattern>

  12. </servlet-mapping>

  13. <servlet-mapping>

  14. <servlet-name>spring-ws</servlet-name>

  15. <url-pattern>*.soap</url-pattern>

  16. </servlet-mapping>

Spring strongly supports only contract first web services for several reasons like Fragility, performance, re usability and versioning.
You can find more information visit this link

So lets start first by developing our XSD....
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"

  3. targetNamespace="http://com.tejakantamneni/schemas"

  4. xmlns:tns="http://com.tejakantamneni/schemas"

  5. elementFormDefault="qualified">

  6. </xsd:schema>

This is a plain regular xsd where we will define all our xml elements going to create our wsdl file.
Lets define our blog object, the blog is just a complex type object with three properties the "Title" for the blog, the "AbstractDetail" of the blog and the date when the blog is published "PublishedDate". This can be defined in the xml complex type
as follows...

  1. <xsd:complexType name="Blog">

  2. <xsd:sequence>

  3. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  4. <xsd:element name="AbstractDetail" type="xsd:string" nillable="true"/>

  5. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  6. </xsd:sequence>

  7. </xsd:complexType>

Next step is defining the search criteria object, I am wrapping the search criteria into a seperate object so that in future, we can extend the search criteria by adding more elements like author, subject. Here the xsd definition of the search criteria
object with two fields title and published date.

  1. <xsd:element name="SearchCriteria">

  2. <xsd:complexType>

  3. <xsd:sequence>

  4. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  5. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  6. </xsd:sequence>

  7. </xsd:complexType>

  8. </xsd:element>

The next stepa are creating the actual request object for our web service, which is basically a wrapper on the search criteria and our response object which is just a array/list of blog objects (which can be either zero size, if search results nothing
or can be of size n if search returns n objects).
Here is our completed xsd,
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"

  3. targetNamespace="http://com.tejakantamneni/schemas"

  4. xmlns:tns="http://com.tejakantamneni/schemas"

  5. elementFormDefault="qualified">

  6. <xsd:element name="BlogSearchRequest">

  7. <xsd:complexType>

  8. <xsd:sequence>

  9. <xsd:element ref="tns:SearchCriteria" minOccurs="0" maxOccurs = "unbounded" />

  10. </xsd:sequence>

  11. </xsd:complexType>

  12. </xsd:element>

  13. <xsd:element name="BlogSearchResponse">

  14. <xsd:complexType>

  15. <xsd:sequence>

  16. <xsd:element name="blogList" type="tns:Blog" minOccurs="0" maxOccurs = "unbounded" />

  17. </xsd:sequence>

  18. </xsd:complexType>

  19. </xsd:element>

  20. <xsd:element name="SearchCriteria">

  21. <xsd:complexType>

  22. <xsd:sequence>

  23. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  24. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  25. </xsd:sequence>

  26. </xsd:complexType>

  27. </xsd:element>

  28. <xsd:complexType name="Blog">

  29. <xsd:sequence>

  30. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  31. <xsd:element name="AbstractDetail" type="xsd:string" nillable="true"/>

  32. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  33. </xsd:sequence>

  34. </xsd:complexType>

  35. </xsd:schema>

The next in developing our web services is defining our contract, the WSDL file.
Here is the complete version the WSDL file.
Essentilly we are improting the xsd file which we had created in the earlier step to use them in the wsdl
Then create the message parts, the port and the binding operation for the blog search service. This is self explanatory.
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <definitions name="BlogSearch" targetNamespace="http://com.tejakantamneni/definitions"

  3. xmlns="http://schemas.xmlsoap.org/wsdl/"

  4. xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

  5. xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"

  6. xmlns:xsd="http://www.w3.org/2001/XMLSchema"

  7. xmlns:tns="http://com.tejakantamneni/definitions"

  8. xmlns:schema="http://com.tejakantamneni/schemas">

  9. <wsdl:types>

  10. <xsd:schema targetNamespace="http://com.tejakantamneni/definitions" xmlns:schema="http://com.tejakantamneni/schemas">

  11. <xsd:import namespace="http://com.tejakantamneni/schemas" schemaLocation="../schemas/BlogSearch.xsd"/>

  12. </xsd:schema>

  13. </wsdl:types>

  14. <wsdl:message name="BlogSearchRequest">

  15. <wsdl:part name="BlogSearchRequest" element="schema:BlogSearchRequest"/>

  16. </wsdl:message>

  17. <wsdl:message name="BlogSearchResponse">

  18. <wsdl:part name="BlogSearchResponse" element="schema:BlogSearchResponse"/>

  19. </wsdl:message>

  20. <wsdl:portType name="BlogSearchService">

  21. <wsdl:operation name="BlogSearchOperation">

  22. <wsdl:input message="tns:BlogSearchRequest" name="BlogSearchRequest" />

  23. <wsdl:output message="tns:BlogSearchResponse" name="BlogSearchResponse" />

  24. </wsdl:operation>

  25. </wsdl:portType>

  26. <wsdl:binding name="BlogSearchBinding" type="tns:BlogSearchService">

  27. <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

  28. <wsdl:operation name="BlogSearchOperation">

  29. <soap:operation soapAction="http://tejakantamneni.com/SearchBlogs"/>

  30. <wsdl:input name="BlogSearchRequest">

  31. <soap:body use="literal" />

  32. </wsdl:input>

  33. <wsdl:output name="BlogSearchResponse">

  34. <soap:body use="literal" />

  35. </wsdl:output>

  36. </wsdl:operation>

  37. </wsdl:binding>

  38. <wsdl:service name="BlogSearchService">

  39. <wsdl:port binding="tns:BlogSearchBinding" name="BlogSearchBindingPort">

  40. <soap:address location="http://localhost:8080/spring-ws-test/BlogSearch.soap"/>

  41. </wsdl:port>

  42. </wsdl:service>

  43. </definitions>

next step is creating the JAXB objects for your xsd elements using xjc compiler. you can either craft the JAXB objects by hand or just
use the xjc compiler. I prefer the later one. see https://jaxb.dev.java.net/guide/ for more details. (My Intellij Idea supports generating JAXB objects directly from xsd).

(Posting all the code is not practical, So I am moving here ahead posting the important parts)
Here is the endpoint
  1. /*

  2. * To change this template, choose Tools | Templates

  3. * and open the template in the editor.

  4. */
  5. package com.teja.service.endpoint;
  6. import com.teja.Blog;
  7. import com.teja.BlogSearchRequest;
  8. import com.teja.BlogSearchResponse;
  9. import com.teja.SearchCriteria;
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.GregorianCalendar;
  13. import java.util.List;
  14. import javax.xml.datatype.DatatypeConfigurationException;
  15. import javax.xml.datatype.DatatypeFactory;
  16. import javax.xml.datatype.XMLGregorianCalendar;
  17. import javax.xml.transform.Source;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.oxm.Marshaller;
  20. import org.springframework.oxm.support.MarshallingSource;
  21. import org.springframework.ws.server.endpoint.annotation.Endpoint;
  22. import org.springframework.ws.server.endpoint.annotation.XPathParam;
  23. import org.springframework.ws.soap.server.endpoint.annotation.SoapAction;

  24. /**

  25. * @author Teja Kantamneni
  26. * @version 1.0 Aug 25, 2008 - 11:30:49 AM
  27. */

  28. @Endpoint
  29. public class BlogSearchEndpoint {

  30. public static final String BLOG_SEARCH_ACTION = "http://tejakantamneni.com/SearchBlogs";

  31. @Autowired
  32. Marshaller marshaller;

  33. @SoapAction(BLOG_SEARCH_ACTION)
  34. // public Source searchBlogs(@XPathParam("/sch:BlogSearchRequest/sch:SearchCriteria/sch:Title") String title, @XPathParam("/sch:BlogSearchRequest/sch:SearchCriteria/sch:PublishedDate") String publishedDate) throws DatatypeConfigurationException {
  35. public BlogSearchResponse searchBlogs(BlogSearchRequest blogSearchRequest) throws DatatypeConfigurationException {
  36. BlogSearchResponse blogSearchResponse = new BlogSearchResponse();
  37. List<Blog> resultBlogs = new ArrayList<Blog>();

  38. DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
  39. GregorianCalendar gregorianCalendar = new GregorianCalendar();
  40. gregorianCalendar.setTime(new Date());
  41. XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);

  42. Blog b = new Blog();
  43. b.setAbstractDetail("Abstract details -teja");
  44. b.setTitle("Teja test");
  45. b.setPublishedDate(xmlGregorianCalendar);

  46. resultBlogs.add(b);
  47. for (Blog blog : resultBlogs) {
  48. blogSearchResponse.getBlogList().add(blog);
  49. }
  50. return blogSearchResponse;
  51. }
  52. }

now the last and more important step, putting all the things together to deploy the service,configuring the spring-ws-servlet.xml

First and the most important point here is I am autowiring the endpoint by using the annotation @Endpoint.

So in the context.xml, we are defining the wsdl to be exposed as a bean using the class org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition.
I am specifying the JAXBMarshaller and injecting all the jaxb classes.
I am also configuring a couple of beans for validating and logging each and every request and response.

  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans xmlns="http://www.springframework.org/schema/beans"

  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  4. xmlns:context="http://www.springframework.org/schema/context"

  5. xmlns:jee="http://www.springframework.org/schema/jee"

  6. xmlns:lang="http://www.springframework.org/schema/lang"

  7. xmlns:util="http://www.springframework.org/schema/util"

  8. xmlns:p="http://www.springframework.org/schema/p"

  9. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

  10. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

  11. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd

  12. http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd

  13. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">

  14. <bean id="BlogSearch" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition"

  15. p:wsdl="/wsdls/BlogSearch.wsdl"/>

  16. <bean class="org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter" >

  17. <constructor-arg ref="marshaller" index="0"/>

  18. </bean>

  19. <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">

  20. <property name="classesToBeBound">

  21. <list>

  22. <value>com.teja.Blog</value>

  23. <value>com.teja.BlogSearchRequest</value>

  24. <value>com.teja.BlogSearchResponse</value>

  25. <value>com.teja.SearchCriteria</value>

  26. </list>

  27. </property>

  28. <property name="schema" value="/schemas/BlogSearch.xsd" />

  29. </bean>

  30. <bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">

  31. <property name="interceptors">

  32. <list>

  33. <bean class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor"/>

  34. <ref bean="validatingInterceptor"/>

  35. </list>

  36. </property>

  37. </bean>

  38. <bean class="org.springframework.ws.soap.server.endpoint.mapping.SoapActionAnnotationMethodEndpointMapping">

  39. <property name="interceptors">

  40. <list>

  41. <bean class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor"/>

  42. <ref bean="validatingInterceptor"/>

  43. </list>

  44. </property>

  45. </bean>

  46. <bean id="validatingInterceptor"

  47. class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor"

  48. p:schema="/schemas/BlogSearch.xsd"

  49. p:validateRequest="true"

  50. p:validateResponse="true"/>

  51. <bean class="org.springframework.ws.server.endpoint.adapter.XPathParamAnnotationMethodEndpointAdapter">

  52. <property name="namespaces">

  53. <props>

  54. <prop key="sch">http://com.tejakantamneni/schemas</prop>

  55. <prop key="xs">http://www.w3.org/2001/XMLSchema</prop>

  56. </props>

  57. </property>

  58. </bean>

  59. <!-- scan classes for dependency annotations -->

  60. <context:component-scan base-package="com.teja"/>

  61. <context:annotation-config/>

  62. <bean class="org.springframework.ws.soap.server.endpoint.SoapFaultAnnotationExceptionResolver">

  63. <property name="order" value="2"/>

  64. </bean>

  65. </beans>

you can access the wsdl at http://localhost:8080/spring-ws-test/wsdl/BlogSearch.wsdl