Category Archives: Software Devlelopment

Asynchronous Rest Services With Jersey

Asynchronous Rest Services With Jersey


There are two major versions of Jersey : Jersey 1 (com.sun.jersey.*) and Jersey 2 (org.glassfish.jersey.*). Currently Jersey 2 is being used but internet has information on both of them and lot has changed between the two.

Jersey can be used with a servlet container such as Jetty Servlet Container, Grizzly Servlet Container and any Generic Servlet 3.x and 2.x containers (tomcat) OR HTTP container such as Grizzly, JDK HTTP Container, Simple HTTP Container, Jetty HTTP Container

2015-03-28 20_33_33-Clipboard


In Jersey, you can return domain objects such as Book or Collection of Books (see below image). This works fine when you don’t want to specify any response details such as HTTP headers or status codes.


You can write tests by extending the JerseyTest testing framework, In the below image, a test to get a book by passing path id and getting Collection of Books is used. Note that you cannot directly pass Collection<Book> because the de-serialization from JSON to Java Object/Data structure will not work. To make this work Jersey provides a GenericType which can be written as (new GenericType<Collection<Book>>(){});


Example of a POST Request: A post request requires entity to be instantiated.




Jackson is a suite of data processing tools for java that support JSON, XML and other formats. Jersey by default comes with Moxy and we can switch to jackson by removing the dependency for moxy  ( and adding the Jackson Provider (Group ID: com.fasterxml.jackson.jaxrs).  Artifact Id can be jackson-jaxrs-json-provider and jackson-jaxrs-xml-provider. You can configure the Jackson Provider:

JacksonJsonProvider json = new JacksonJsonProvider();



Jackson Annotations




Tools for Rest API

Tools For Rest API


A good documentation and healthy rest API request response makes the application more robust, easy to develop, test and maintain. There are three services I came across, that not only document but gives you a testing sandbox from your services and will help your applications grow with managed design and architecture.


Rest Clients

There are many rest clients for chrome and Firefox but the one I liked most is postman as a packaged application. Some of it’s salient features are:

  • it allows you to create cURL scripts out of your requests.
  • it allows you to manage environments by introducing variables such as {{baseURL}} which can be different for Production, QA and development.
  • You can save the responses in the paid version.
  • Has a proxy mode and authentication.


Although rest clients allow you to send the requests and receive the response, HTTP Debuggers allow you to see what happens under the hood and act on the data. Example if a server responds you with JSON, you can intercept it and convert it into XML before the responds reaches the client. You need to configure For chrome to send the requests through this proxy. Some debuggers are:

  • Burp – Good for intercepting requests and responses and for testing security like adding JavaScript in the response.
  • Fiddler
  • Charles

Packet Sniffers

To see what is going on the network interfaces at a much lower level. No need to setup proxy and you can filter by http. You will see data in TCP packets so it will be a breakdown of data. To see the actual request and response, you can right click and click on “Follow TCP Streams” to see the combination of data presented as one request.

  • Wireshark



The client (browser) can cache data based on the HTTP Expires tag. The server can set the Expires tag (HTTP 1.0) and Cache-Control (HTTP 1.1) with HTTP Response. It applies to HTML files, images and resources. Using cache-control you can set the time the resource should be cached (max-age — local client), you can also set the cache-control for proxy (s-maxage). The advantage is less network calls and the disadvantage is stale data. In the case where there is authorization in headers or https, browser doesn’t use caching even if the headers are present.

Validation Caching

To cache personalized resources where expiration caching doesn’t help, validation caching is used. The response has an E-Tag with a certain value. Example, e-tag:4x4hij. Until this e-tag doesn’t change all the client requests coming for the resource are sent back with 304 (Not Modified). The same works with Last-Modified and If-Modified-Since.

 Performance Testing

There are good cloud based load testing tools, that can do stress test to the API.


  •  Splunk
  • Loggly


Tomcat – Defining Manager-GUI role

To access the host manager in Tomcat, you need to define the manager-gui rule as below:

<role rolename=”tomcat”/>
<role rolename=”role1″/>
<user username=”tomcat” password=”tomcat” roles=”tomcat”/>
<user username=”both” password=”tomcat” roles=”tomcat,role1″/>
<user username=”role1″ password=”tomcat” roles=”role1″/>
<role rolename=”manager”/>
<role rolename=”admin”/>
<role rolename=”manager-gui”/>
<user username=”tomcat” password=”password” roles=”admin,manager”/>
<user username=”tomcat” password=”password” roles=”manager-gui”/>


AWT (Abstract Window Toolkit) and Swing

– AWT provides us with very limited set of components because AWT makes native calls to OS to make components. Only those components

which are supported by all the platforms are supported by AWT, so they are very limited. Eg. Button, Text, Scrollbar, Window, Frame, Panel,

Label, Dialog etc.

– Components must be placed in a container. Conatainer class has an add method to place the component inside it.



To create checkbox:

CheckBox cb = new CheckBox("name",null,true);
//null is the group. true specifies whether it should be selected by default

There are no radio buttons in AWT. To create one, you need to create CheckBoxGroup and add checkboxes to it.

CheckBoxGroup cbg = new CheckBoxGroup();

new CheckBox("name",cbg,true)
new CheckBox("name",cbg,false)
new CheckBox("name",cbg,true)

In the above checkbox only the third one will be secleted because in a radio button or checkbox group only one can be selected and that would be

the last one to specify value as true.

How to place components in application program?

public static void main(String args[]){

Button b1 = new Button("Ok");
Button b1 = new Button("Cancel");

//Place the components inside the container

//1. First get the frame. Both diaglog and frame are derived from Window class.
Frame f1 = new Frame("Title");
//in pixels


//Display the frame. This brings out the frame with the components.

//If you need to add components after making the frame visible, then call validate. This method redraws everything.


How to work with Menus?
Assume we are going to put in File and Help Option.
File has Open , Close, Exit
Help has About Status Option (sub options)

Menus are only supported by Frames in AWT. We have a frame that consists of Menu Bar, Menu, Menu Item, Check box Menu Item(Toggle)

You can create objects in whatever sequence but place them in sequence.

public static void main(String args[]){

MenuBar mb = new MenuBar();
Frame fr = new Frame();


Menu f = new Menu("File");
Menu h = new Menu("Help");
Menu op = new Menu("Options");

MenuItem o = new MenuItem("Open");
MenuItem c = new MenuItem("Close");
MenuItem e = new MenuItem("Exit");
MenuItem a = new MenuItem("About");
MenuItem one = new MenuItem("Open");
MenuItem two = new MenuItem("two");

CheckboxMenuItem s = new CheckboxMenuItem("Status");

//Follow the sequence now








What is the size of the component, where am i adding component to, how to interact with the component?

Layout Managers: These tell the container where to have the components. They define how the components will be placed in the contianer.

5 Layouts:

FlowLayout -- Default layout for panel and applet
BorderLayout -- Default for frame and dialog
GridbagConstraints - Helper class for GridbagLayout

Flow Layout: Places components one next to other. It is aligned to center. by default. A container cannot have more than one layout at a time.

You can define the horizontal and vertical distance.

int hgap = 10;
int vgap = 20;
FlowLayout fl = new FlowLayout(FlowLayout.LEFT, FlowLayout, hgap, vgap);
// These values can be specified later as well by using fl object.
new Frame().setLayout(fl);

BorderLayout: Maximum of 5 components in the container. In a BL, there are 5 directions - NEWS and C

size of the component is size of the direction. Center takes all the empty directions if no component is placed there.

container.setLayout(new BorderLayout());

fr.add(b1) -- By default it adds to the center.

CardLayout - The component takes the entire Screen/Container space. Think of tabbed window in browser. Only one component can be

displayed when selected and that takes up the entire screen space. To move from one component to another:

container.setLayout(new CardLayout());

cl.add(b1, "uniquiname");"uniquename")

GridLayout: container is divided into cells.

new GridLayout(rows,cols);

The component will occupy the entire cell. When a new component is added when the grid is full , it extends by the column and rearranges all the

components in order.

new GridLayout(); ---> It is a single cell. When you add components they get added by the column.

GridBagLayout: Like Html - colspan, rowspan , padding . You can give more than one cell space to the component. This is the main difference

between gl and gbl

Properties that are available to work with from GridbagConstraints class are:

gridx (default: 0) top left corner
gridy (default:0) top of the component
gridwidth (default:1) how many rows a component can take up
gridheight (default:1 how many columns a component can take up
anchor (default:center where the component is placed
fill (default:none) - Do you want the component to take the entire Horizontal space or Vertical space or both?
ipadx (default:0 Space padding that should be done between the components
ipady (default:0 )
weightx (default:0)
weighty (default:0)

How to place components in the gbl?

GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();


Button b1 = new Button();
fr.add(b1,gbc); //If you didn't set any values for gbc , it takes all the default values.

Button b2 = new Button();
gbc.gridwidth = 3;
gbc.gridheight = 2;
gbc.gridx = 1;

Button b3 = new Button();
gbc.gridx = 4; // because b2 takes three cells
gbc.gridx = GridbagConstraints.RELATIVE;

// If you want it to take rest of the row space
gbc.gridwidth = GridbagConstraints.REMAINDER

How come the same gbc is used?
It makes clone of the object every time.

What is weightx and weighty?
It places by default to the more center all the components. If you want to spread out the content so that it is more layed out. eg. you specify left

and right margins and write content. Then you do justify
to lay it out/spread it out so that left to right margin is occupied. That is what weightx and weighty does.

weightx spreads out the component horizontally and weighty does it vertically.

You can also define your own layout using the layout manager interface.
fr.setLayout(null) ---> No Layout is used.
In this case you need to specify the position and the size of each component manually and then add it to the frame.

Button b1=new Button();


b1.setBounds(x,y,width,height); --> 50,30,100,80

A container having border layout --> can't specify size because it takes size of the direction
card layout --> can't specify size because it takes size of the entire layout
grid layout --> can't specify size beacause it takes size of the cell.

flow layout --> Can specify size but you need to derive a class from the component class itself and override the setPreferredsize method. You don't

invoke , it will be invoked by the API.
gridbaglayout --> Can specify size but you need to derive a class from the component class itself and override the setPreferredsize method. You

don't invoke , it will be invoked by the API.

// Aplet has a flow layout


public But extends Button(){

public Dimension getPreferredSize(int x, int y){

int x,y;

return newDimension(x, y);


public But(String s, int x, int y){

this.x = x;
this.y = y;

public static void main(String args[]){
But b1 = new But("OK", 70, 90);

Insets: Space between container and component. Like a margin for a word document - top, bottom, left, right

// extend the container and override the getInsets method. This is automatically called

public Insets getInsets(){
return new Insets(top,left,bottm,right);

Handle Events which get raised:

import java.awt.event.*;

This package consists of Event Classes, Interfaces , Adapter Classes (Abstract Classes):

ActionEvent --> Mainly used for Menu, Textfield, Button
AdjustmentEvent --> Scrollbar
TextEvent --> TextArea , Textfield
ItemEvent - MenuItem, CheckboxMenuItem, CheckBox, List, Choice
WindowEvent - whenever we try to close the frame with the close button, minimize, maximize, activate, deactivate
MouseEvent = Mouse Pressed, MouseReleased, MouseDragged
KeyEvent --> KeyPressed , KeyReleased
ContainerEvent --> when you add/remove component from container
ComponentEvent --> relocate or resize compoent
Focus Event --> focus gained or lost on any component

For each event class there exists and Event Interface. They contain event handler methods.

ActionListener, AdjustmentListener, TextListener

There exists an adapter class for listener which have more than one event handler method:
eg for WindowListener there is WindowAdapter
MouseListener there is MouseAdapter
MouseMotionListener there is MouseMotionAdapter

What is the usage of these adapter classes:

interface i1 {



// interface is provided for implementation
class A implements I1{

public void add(){}
public void mod(){ .... }
public void del(){}


// class is provided now to extend
class i1class implemetns i1 {

public void add(){}
public void mod(){}
public void del(){}


Which will you chose? Is there any sense to make instance of i1class? No need of instance. Make it abstract. This is known as an Adapter Class.

// class is provided now to extend
abstract class i1class implemetns i1 {

public void add(){}
public void mod(){}
public void del(){}


Delegation Model:
1. implement the listener or extend the adapter class on the class
2. Implement the event handler methods.
3. Create the instance of the above class which will return the Listener
4. Bind the Component and the Listener by passing the Listener object to the Component. Invoke the method component.addxxxListener

xxx is the appropriate ListenerType . Eg. component.addActionListener
Listener object is placed into the vector of the component class. That is how you register more than one listener. This is like observer pattern.

When a button is clicked , dispatch event of the componet is called which creates ActionEvent object, and goes throgh the vector to find out the

ActionListener object and takes that object and calls the listener methods (actionPerformed) by passing the event object as parameter.

Swing Components: introduced in JDK 1.2

Swing Components are Java Bean Compoents .
These are lightweight Compoents bevauase they are drwan over an OS container.
AWT are heavy Weight Componetns because they call native calls.

There are 4 heighy weight containers in swing:

all siwnf comonet name starts with J.

because swinng compeonts are mere drawings on a container. they support large variety of components - lots of widget - tabls, tees, desktpms.,

icons, borders ect.

Swings started with MVC architecture to decouple the view with the model. Theu clubbed to gether view and the controller classes. so with each

compoent there is a ui and model class. it is now called mui architecture. model+viewcontroller . you can create your own model classes which

represents data for the application. view displays the data, controller

JComponent class is the root of all classes in swing is derived from AWT Compoent class.

New Features:

The layerd pane consists of different layers which gives z-order. smaller the z order number the closer the compoent looks and the higher the z-

order the farther the component.

Swing Containers are directly derived from AWT containers. so these are heavy weight Containers.

You don't directly add the component to the container. You add it to the content pane . call the getContentPane on the container to get

ContentPane and add Compoents to it.

Swing Look and Feel:
Java Look and Feel , now called as Metal Look and Feel

javax.swing.plaf - consists of diff. look and feel classes

UIManager.setLookandFeel(LookAndFeel Class)

Event Handling can be done in two ways:
self contained of event - the component itself handles the event.
delegation of event - make use of listener interface, mostly used.

//Tells which component raised the event
Object o= ActionEvent.getSource();
if(o instanceof Button)
Button tempButton = (Button) o;

String s = tempButton.getLabel();

You can handle multiple events for the component. For example MouseListener and ActionListener for a button. But which one gets executed is

not assured. However if you have the same Listener multiple times for teh component then it is done sequentially.

Using JNDI datasource in Hibernate

To use Jndi data source outside application context:
This is specific to Weblogic.
Make sure you have wlfullclient.jar in your application class path and you have the Hibernate Mapping configured to use the datasource, provide the url as t3://host:port

On not using the wlfullclient.jar, following errors will appear:

Please see:

Dual request to a servlet

If you want to get back a mime – application/PDF or excel as a response and still redirect to a jsp page with a single button click, the. You can have two forms in the requesting page and then call a JavaScript function on-click on both these forms. Both the forms may have the single action that takes it to the same servlet. In JavaScript, do the document.form1.submit and do some arbitrary sleep and then do the document.form2.submit. In response, you will first get the PDF and then the redirection to the jsp. You need to give response.sendredirect on the servlet side for redirecting to the jsp.
Alternatively, this can be done using a target attribute in the form, eg. Target=abc.jsp and in the JavaScript submit function , use self.location.