Building RESTful Web Services with JAX-RS – Annotations

Post moved to

http://srinichekuri.com/2016/01/17/building-restful-web-services-with-jax-rs-annotations/

**********************************************************************

Let’s take a look at annotations that are used to build RESTful services. Based on the implementation framework that you are using, there might be many annotations. In this post we will discuss annotations that are supported by JAX-RS specs only.

@Path

  • @Path annotation identifies URI Path template
  • Can be used at class or method level.
  • Always specifies relative url to base url (host)
  • @Path value need not have leading or tailing slashes (/). JAX-RS treats them them the same either ways
  • Variables can be specified in @path as follows 
    • Multiple Variables can be specified. Eg @Path(“/users/{username_1}/{username_2}”)

 

//Variable in path is specified by {}
@Path("/users/{username}")
public class UserResource {

    @GET
    @Produces("text/xml")
    //variable specified in @Path can be accessed by @PathParam
    public String getUser(@PathParam("userName") String userName) {
        ...
    }
}


Request Method Designator Annotations (@GET, @POST, @PUT, @DELETE and @HEAD):

  • @GET – The Java method annotated with this will process HTTP GET requests.
  • @POST – The Java method annotated with this will process HTTP POST requests.
  • @PUT – The Java method annotated with this will process HTTP PUT requests.
  • @DELETE – The Java method annotated with this will process HTTP DELETE requests.
  • @HEAD – The Java method annotated with this will process HTTP HEAD requests.

Few logistics that should be followed to use JAX-RS for request methods designator annotations are as follows

  • Methods decorated with request method designators must return following:
    • void
    • A Java programming language type
    • A javax.ws.rs.core.Response Object.
  • Multiple parameters may be extracted from the URI using @PathParam or @QueryParam (Explained below).
  • The HTTP PUT and POST methods expect an HTTP request body.
  • Both @PUT and @POST can be used to create or update a resource.
  • POST can mean anything, so any semantics can be used. PUT has well defined semantics.When using PUT for creation, the client declares the URI for the newly created resource.
  • A common pattern is to use POST to create a resource and return a 201 response with a location header value is the URI to the newly created resource. In this pattern, the web service declares the URI for the newly created resource.

@Consumes and @Produces

@Produces annotation is used to specify the MIME media type that are sent back to client.

  • If specified on class level, all methods will follow it.
  • One can override class level by specifying this on method level.
  • If no methods in a resource are able to produce the MIME type in a client request, then JAX-RS runtime sends back an HTTP ‘406 Not Acceptable’ error.
  • Multiple MIME-types can be specified as follows
      • @Produces({“image/jpeg,image/png”})

     

 

@Path("/myResource")
@Produces("text/plain")
public class SomeResource {
    @GET
    public String doGetAsPlainText() {
        ...
    }

    @GET
    @Produces("text/html") //overides class level
    public String doGetAsHtml() {
        ...
    }
}


@Consumes represents the media types a resource  can accept.

  • If specified on class level, all methods will follow it.
  • One can override class level by specifying this on method level.
  • If a resource is unable to consume the MIME type of a client request, the JAX-RS runtime sends back an HTTP “415 (‘Unsupported Media Type’)” error.
  • If @consumes is used on method that returns ‘void’ then HTTP 204 (‘No Content’) error is returned.

    @POST@Consumes(“text/plain”)public void postClichedMessage(String message) {    // Store the message }

@Path("/myResource")
@Consumes("multipart/related")
public class SomeResource {
    @POST
    public String doPost(MimeMultipart mimeMultipartData) {
        ...
    }

    @POST
    @Consumes("application/x-www-form-urlencoded")
    public String doPost2(FormURLEncodedProperties formData) {
        ...
    }
}

 

Request Parameters (@QueryParam, @PathParam, @DefaultValue, @MatrixParam, @HeaderParam, @CookieParam, @FormParam)

Both @QueryParam and @PathParam can be used only on following Java types:

  • All primitive types except char.
  • All wrapper classes of primitive types except Character
  • Any class with a constructor that accepts a single String argument.
  • Any class with static method named valueOf (String) that accepst a single String argument
  • List<T>, Set<T> or SortedSet<T>, where T matches the already listed criteria.

 

@Path(&quot;smooth&quot;)
@GET
public Response smooth(
        @DefaultValue(&quot;4&quot;) @QueryParam(&quot;number&quot;) int colorNumber,
        @DefaultValue(&quot;red&quot;) @QueryParam(&quot;last-color&quot;) String color
        ) { ... }

Advertisements

Building RESTful Web Services with JAX-RS – Introduction

Post moved to

http://srinichekuri.com/2016/01/17/building-restful-web-services-with-jax-rs-introduction/

**********************************************************************

Introduction to REST:

REST Stands for REpresentational State Transfer. REST  is built to work best in web and uses a stateless communication protocol, typically HTTP. Following principles make RESTful application simple, lightweight and fast.

  • URIs are used to identify resources (services).
  • Uniform Indentification for CRID activities
    • Create – PUT
    • Read – GET
    • Update – POST
    • Delete – DELETE
  • Resources (Services) are decoupled from representation so their content can be accessed in variety of formats. Eg: HTML, Plain Text, XML, JSON etc
  • As Rest Services are Stateless, Stateful interaction can be done by URI rewriting, cookies and hidden fields.

Advantages of REST

  • Better Performance
  • Scalability
  • Modifiability.

Disadvantages of REST

  • Less Secure

<Put in an HelloWorldRest Service here with  text on what annotation means what>

Step by Step guide – Convert to Maven Project in Eclipse

Post moved to:

http://srinichekuri.com/2016/01/15/step-by-step-guide-convert-to-maven-project-in-eclipse/

**********************************************************************

This post is for step by step guide to convert a single project to Maven project in Eclipse. I recommend going through these links before you read any further.

Step 1: Maven Plugin for Eclipse

First you should make sure that you have Maven Plugin installed in your Eclipse. I am using Eclipse Mars for this demo and this version comes with Maven Plugin. If you are using Eclipse doesn’t have this built in feature then try to install a Maven Plugin. I recommend M2Eclipse Plugin.

Step 2: Convert Java/J2ee Project to Maven Project

Right click on Java Eclipse and select Configure -> Convert to Maven Project.

convert_to_Maven_Project_Eclipse

A popup up that will show build parameters that will be published in pom.xml will be shown.

convert_to_Maven_Project_Eclipse_1

Step 3: Add dependencies to pom.xml

Open pom.xml and Click on Dependencies tab.

Lets try to add log4j.jar as a dependency in pom.xml.

convert_to_Maven_Project_Eclipse_3

convert_to_Maven_Project_Eclipse_4

Step 4: Run Maven Build

Run Maven build by right clicking on pom.xml and selecting Run As -> Maven install.

convert_to_Maven_Project_Eclipse_5

Step 5: Verify Build

You will see that folder is created with naming convention <artifactId>-<version> in build folder. Also you will see that all dependencies are saved to build/<artifactId>-<version>/WEB-INF/lib folder. Also you will see all dependecies are placed in build path under Maven Dependencies.

convert_to_Maven_Project_Eclipse_6

 

convert_to_Maven_Project_Eclipse_7

Multiple dependencies can be added in similar fashion.

 

Step by Step guide for Hello World Page (HTML and JSP)

This post has been moved to http://srinichekuri.com/2016/01/14/step-by-step-guide-for-hello-world-html-and-jsp/

**********************************************************************

This post is a step by step guide to develop your first html and jsp. Traditionally, developers code ‘Hello World !!!’ as first page and I am sticking to this tradition.

I am using a Eclipse IDE and Apache Tomcat for this tutorial. I recommend going through ‘Step by Step guide to configure Eclipse and Apache Tomcat‘ before you proceed any further.

Step-1: Create Dynamic Web Application

Create a new Dynamic Web Project by clicking on FIle -> New -> Dynamic Web Project

dynamic_project.png

Give a project name and click on Finish.

dynamic_project_1

Step-2: Create a HTML page

Create a new html page by right clicking on WebContent and selecting New -> HTML File.

dynamic_project_2.png

Put in a filename helloWorld.html and click on Finish.

dynamic_project_3.png

Put in this code in helloWorld.html.

<!DOCTYPE html>
<html>
<head>
 <meta charset="ISO-8859-1">
 <title>Hello World</title>
</head>
<body>
 <h5>Hello World - html</h5>
</body>
</html>

Step-3: Create a JSP page

Create a new jsp page by right clicking on WEB-INF and selecting New -> JSP File.

dynamic_project_9

 

Put in a filename helloWorld.jsp and click on Finish.

dynamic_project_10

 

You are seeing any compilation errors then make sure that you have right Runtimes checked as shown below.

dynamic_project_5_1

Put in below code into the jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<h5>Hello World - jsp</h5>
</body>
</html>

Step-4: Add Project to Server.

Add Project server to Server.

dynamic_project_5_2

dynamic_project_5_3.png

Step-5: Access new pages.

Access html page by url in browser. Url will be in “http://localhost:<port>/HelloWorld/helloWorld.html&#8221; format

dynamic_project_6.png

Access jsp page by url in browser. Url will be in “http://localhost:<port>/HelloWorld/helloWorld.jsp&#8221; format

dynamic_project_7.png

 

 

Step by Step guide to configure Eclipse and Apache Tomcat

This post has been moved to http://srinichekuri.com/2016/01/12/step-by-step-guide-to-configure-eclipse-and-apache-tomcat/

*********************************************************************

Eclipse is a very commonly used IDE by developers across the globe. Eclipse with Apache Tomcat server is a great combination for beginners and for experienced web developers.

This post will provide step-by-step guidance to set up Eclipse with Tomcat Server.

Note: Below screen shots are for windows 64-bit version. Please act accordingly for 32-bit versions.

Step-1: Download Java.

Click Here to download Java 7 SDK.

Java7_download

You will see that there are two folder created in your C:\Program files\Java. (In my case I already had Java 6 installed too).

Java7_download_2

Step-2: Download Apache Tomcat Server

Click Here to download Apache Tomcat Server 7.

Apache_Tomcat7_download

Once dowloaded, extract the server to D:\Software. You will see following structure after the extract is complete.

Apache_Tomcat7_download_1

Note: you can also choose to install from 32-bit/64-bit Windows Service Installer if you want to install it like a service.

Step-3: Configure Environment Variables

Configure following environment variables and restart your pc when done.

  • JAVA_HOME: “C:\Program Files\Java\jdk1.7.0_79”java_home_environment_variable
  • JRE_HOME: “C:\Program Files\Java\jre7”jre_home_environment_variable
  • CATALINA_HOME: “D:\Software\apache-tomcat-7.0.67”catalina_home_environment_variable

 

Step-4: Download Eclipse

Click Here to download Eclipse. For this guide, I am downloading Eclipse Mars. But you can download anything that is compatible with Java version you downloaded.

Eclipse_Mars_Download

Once downloaded extract contents to D:\Software.  You will see following structure after download is complete.

Eclipse_Mars_Download_1

 

Step 5: Setup Server Configuration in Eclipse

Open Eclipse and Open Server View (Window -> Show View -> Servers)

Right Click New -> Server

Eclipse_server_setup

Select Tomcat 7. You might have to Add Server runtime environment.

Eclipse_server_setup_1

(Dialog when clicked on ‘Add…’ in above screen shot)

Eclipse_server_setup_2

Click on Finish when Done.

Double click on Server to open deployment descriptor and make sure that you have default ports.

Eclipse_server_setup_3

Now start the server by clicking on start button and you will see that server has started successfully.

Eclipse_server_setup_4

Eclipse_server_setup_5

Hope this Set up process was helpful. Please use the comment section if you face any issues setting up and I will help  you as soon as I can.

 

 

Cannot use javahl, JavaSVN nor command line svn client

This post has been moved to http://srinichekuri.com/2014/02/14/cannot-use-javahl-javasvn-nor-command-line-svn-client/

*********************************************************************

I was working on a old project that had all build files that were working fine when coded originally. I tried using the same files and I ran into this issue.

Error: Cannot use javahl, JavaSVN nor command line svn client

Research:
I have googled on this and I was able to find two feasible solutions that apparently worked for others.

  1. javahl.dll or svnjavahl.dll files have to be appended to PATH variable. This solution didn’t work for me. First of all I didn’t find these files and even if would have found them, I wouldn’t have done it as changing PATH variable was not an option for me.
  2. Download a svn client like silksvn and install it. This will put in a PATH variable which will in turn help fixing the issue. This was not an option either as I was not willing to install a software for something that was supposed to work stand alone.

Solution:
After multiple trails this is what worked for me.

  • I downloaded the latest SvnAnt (svn 1.2.x at time of documentation).
  • I replaced svnant.jar, svnClientAdapter.jar, svnjavahl.jar files that were preexisiting and added svnkit.jar.
  • Add these files to classpath in ant script. (No changes done to PATH variables or any other system level variable)
&lt;typedef resource=&quot;org/tigris/subversion/svnant/svnantlib.xml&quot;&gt;
 &lt;classpath&gt;
 &lt;pathelement location=&quot;C:/svnAnt/lib/svnant.jar&quot;/&gt;
 &lt;pathelement location=&quot;C:/svnAnt/lib/svnClientAdapter.jar&quot;/&gt;
 &lt;pathelement location=&quot;C:/svnAnt/lib/svnjavahl.jar&quot;/&gt;
 &lt;pathelement location=&quot;C:/svnAnt/lib/svnkit.jar&quot;/&gt;
 &lt;/classpath&gt;
 &lt;/typedef&gt;

Hope this helps!!!

SCEA/OCMJEA Assignment

This post has been moved to http://srinichekuri.com/2013/06/04/sceaocmjea-assignment/

**********************************************************************

Today I got the magical email that I have passed assignment with a score of 146/160. Needless to say, I was very happy. I am blogging my experience with the hope that future aspirants will benefit from this.

I have submitted Assignment about 10 days before voucher expires.To start I have downloaded the assignment almost immediately after my Step-1 which started my clock(for people who don’t know Step 2 and Step 3 should be done within six months after the assignment is downloaded). Well if the question is did it actually take six month to complete this project, the answer is a big NO. I have started working on it for few hours everyday for 2 weeks. When I understood the assignment well and designed the system, I also drew class diagrams, sequence diagrams on scrap papers and then I stopped. I guess I was thinking that the challenging part is complete and I had to take care of the boring part( documenting it).
When I took up the project again after 5 months, I realized that it was a mistake due to following reasons:

  • The break wiped out project from my memory and I had to start all over again. Ofcourse my design that I scrapped on paper really helped me to get it all back.
  • I have under estimated deployment diagram. I never had to decide on hardware profile before and this turned out to be quite challenging.
  • UML took good chunk of time. By UML I mean deciding on the tool, planning on how you project your diagrams to make evaluation easy and actually drawing them took some time.
  • Documenting did take some time.

The project that was assigned to me was a web application with peak usage of 200 users. The domain diagram had 11 classes.
I have worked on UML diagrams in following order:
Class Diagram:
I have decided to divide my class diagrams into 2 parts by separating out domain classes. Although I started out with a thought to accommodate all the classes into one diagram, I thought that domain classes can be shown separately just to avoid clutter. This worked out pretty well for me. I have used various patterns like MVC, Factory, Business Delegate, Proxy Pattern, Data Access Object, Value Object, Transfer Object and Domain store. I have used following technologies/frameworks:

  •     Struts 2.0 for presentation layer.
  •     EJB 3.0 enterprise beans for session and transaction management.
  •     JPA for persistence.
  •     Java Mail API for email notification.
  •     Spring 3.0 for Authentication and Authorization.
  •     Spring 3.0 for dependency injection, aspect-oriented programming.
  •     Log4j for logging.
  •     WebServices.
  •     Ehcache for Caching (Out of box with Spring 3.0).

My class diagram also included few classes and jsps for user scenarios that were not mentioned in the requirement. For Eg: Maintenance module was not mentioned in my assignment, I have included that after adding proper assumptions.
In all I had 9 jsps, 25 classes and 11 domain objects.
Although I mentioned class names for value objects and transfer Objects, I didn’t show them in my class diagram.

Sequence Diagram:
I had six sequence diagrams in my project. I made sure all the use cases that are mentioned in assignment are addressed here. I had to do some reading for this as I found that UML 2 had good features to represent our views. I have used two opts.

Component Diagram:
I have done this after I was almost done with class diagram and know what to be done in sequence diagrams. This helped me with all the components that would go under various tiers.

Deployment Diagram:
This was a very good learning experience in whole of the project. Having worked for multinational companies all through my career, I never go to involve myself in hardware discussions. I did however have experience working on a projects where I had to make decisions on over all architecture (Firewalls, load balancer, server clustering, hot backups etc). This was the strategy that I have followed before deciding on the hardware profile and the vendor that would host my application

  • In-house hosting costs vs Outsourcing hosting costs
  • Privacy compromises for in-house vs outsourcing.
  • Licensing costs
  • Resource costs for maintenance

For my project, privacy was not a concern (added this to assumption as well) and the cost of hosting in house by buying a server was too high (Eg: Cost of IBM Power 710 Server, 4 core 4.2 Ghz with 8GB RAM, Rack mount 2 x 146 GB SFF Harddisk (IBM AIX 5.3 operating system) is $6255 without other licensing costs and resource costs). I have decided to outsource hosting for my application. The advantage in my case for outsourcing was that maintenance costs(possibly licensing costs) were included in hosting costs.

For Outsourcing I have looked at two options

  • Rent Physical Server: I have looked into multiple providers but the cheapest option was provided by rackspace.com. It costs $262.80/month for box with 4GB RAM, 2 core 160 GB disk space (Linux operating system)
  • Cloud Solution: Again there were multiple that provided cloud solutions but I best I found was Amazon Elastic Compute Cloud (Amazon EC2) service. The price for ‘3 year upfront option’ for ‘M1 Large Instance’ $384.

I have decided to go for Amazon Ec2 as it had other advantages.

Amazon Elastic Compute Cloud (Amazon EC2) services seem to be secure, reliable and have scalability options for increased traffic in future.

  • Load Balancing: This service provides elastic load balancing which automatically distributes incoming application traffic across multiple Amazon EC2 instances. This has capability to detect unhealthy instances within a pool and automatically reroute traffic to healthy instances.
  • Hardware/Software Application Server – Primary: I chose ‘M1 Large Instance’ option which provides 7.5 GB of memory, 4 EC2 Compute units (2 Virtual cores with 2 EC2 compute units each, 850 GB of disk space, 64-bit platform). Operating System is Red Hat Enterprise Linux. Application Server is IBM Websphere.
  • Application Server – Backup:  I chose ‘M1 Medium Instance’ option which provides 3.75 GB of memory, 2 EC2 Compute Units (1 Virtual core with 2 EC2 Compute units each, 410 GB of disk space, 64 bit platform). Operating System is Red Hat Enterprise Linux. Application Server is IBM Websphere.
  • Database (Primary/Backup): The package selected above comes with local installation of database. Following were chosen for this application:
    • Microsoft SQL Server-Standard
    • Windows 2008 R2 6.1 (Operating System)
  • Scalability: Amazon EC2 services provide auto scaling which scales up automatically to maintain performance in case of spikes.
  • Pricing:
    • Application Server+Database(primary) – 3 year upfront option for $384 (Amazon EC2 offers various options but this is the cheapest)
    • Application Server+Database(Backup) – 3 year upfront option for $192
    • Projected operating budget for hardware/software for 3 years = $384 + $192= $576

Assumptions:
I had about 10 assumptions. I have put all assumptions that effected my design/hardware/software decisions.

Risks and Mitigation Plan:
I had about 12-15 risks and mitigations strategies listed. I have sorted the risks in the order of their importance so that the top risk is shown at the top.

Documentation:
I have provided some extensive write-up for each section. I wanted to make sure that all my thoughts were put in there as my main motto was to make sure that evaluator understands everything that I had in mind. A lot of documentation was done as I was doing UML diagrams to diversify my work.

Creating Jar file:
I have zipped all my files and changed the extension to .jar. (We can as well create a jar from command prompt – google it).

SCEA blogs:

Reference Material:

Questions I had and how I addressed them:

  • How detail should class diagram be?
    Pretty detail, but make sure that details like patterns, methods, method parameters are visible. I advice to not include any classes that would add clutter (DTO, Transfer objects, Value Objects etc.). Don’t compromise on quality of class diagram for other factors like restricting class diagram to one page.
  • Do I have to show jsps in class diagram?
    Yes.
  • Should I show DTO/Transfer Objects/Value Objects ?
    You have to decide if this makes any sense to show them. I didn’t show any DTO, Transfer Objects and Value Objects. I just mentioned them as parameters in methods and I did mention them in my write up for class diagram.
  • Should getter/setter methods in a class be shown?
    No.
  • What tool did I use for UML diagrams?
    MS Visio 2010
  • What format of images did I use for UML diagrams?
    I have converted all my UML diagrams to PNG format. I found this format to be more compact in size without any compromise in quality.
  • How did I convert UML diagrams to images?
    I have used SnagIt. SnagIt has settings to capture a scrolling page and later I have cut the unwanted area and saved the image in PNG format.

My other posts related to SCEA: SCEA/OCMJEA Experience (Step-1), SCEA/OCMJEA Essay