Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts

Wednesday, November 7, 2012

Restful Web Services Java, MySQL and JSON

Today we are going to build another restful web service in eclipse using gson library. When client makes a request, the application queries the database and produces response in JSON format. This JSON can be parsed with most of the programming languages.
We will see how various clients can consume this web service in the second part of the tutorial.

Download Source Code

Download Source Code
Project Architecture



Create a new dynamic web project in Eclipse and add jersy, gson library to WEB-INF/lib.

course.java
We utilize this class when we wanna bind data after querying database.

[sourcecode language="java"]
package dto;

public class Course
{
private int id;
private String name;
private String duration;
private double fee;

public Course()
{

}

public Course(int id, String name, String duration, double fee)
{
super();
this.id = id;
this.name = name;
this.duration = duration;
this.fee = fee;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getDuration()
{
return duration;
}

public void setDuration(String duration)
{
this.duration = duration;
}

public double getFee()
{
return fee;
}

public void setFee(double fee)
{
this.fee = fee;
}

@Override
public String toString()
{
return "Course [id=" + id + ", name=" + name + ", duration=" + duration
+ ", fee=" + fee + "]";
}

}

[/sourcecode]

 

Database.java

[sourcecode language="java"]
package dao;

import java.sql.Connection;
import java.sql.DriverManager;

public class Database
{
public Connection getConnection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/codezone4";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "");
return connection;
} catch (Exception e)
{
throw e;
}

}

}

[/sourcecode]

Access.java

[sourcecode language="java"]
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import dto.Course;

public class Access
{
public ArrayList<Course> getCourses(Connection con) throws SQLException
{
ArrayList<Course> courseList = new ArrayList<Course>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM courses");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Course courseObj = new Course();
courseObj.setId(rs.getInt("id"));
courseObj.setName(rs.getString("name"));
courseObj.setDuration(rs.getString("duration"));
courseObj.setFee(rs.getDouble("fee"));
courseList.add(courseObj);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return courseList;

}
}

[/sourcecode]

AccessManager.java

[sourcecode language="java"]
package model;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import dao.Access;
import dao.Database;
import dto.Course;

public class AccessManager
{
public ArrayList<Course> getCourses() throws Exception
{
ArrayList<Course> courseList = new ArrayList<Course>();
Database db = new Database();
Connection con = db.getConnection();
Access access = new Access();
courseList = access.getCourses(con);
return courseList;
}
}

[/sourcecode]



CourseService.java

[sourcecode language="java"]
package webService;

import java.util.ArrayList;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import com.google.gson.Gson;

import model.AccessManager;

import dto.Course;

@Path("/courseService")
public class CourseService
{
@GET
@Path("/courses")
@Produces("application/json")
public String courses()
{
String courses = null;
ArrayList<Course> courseList = new ArrayList<Course>();
try
{
courseList = new AccessManager().getCourses();
Gson gson = new Gson();
courses = gson.toJson(courseList);
} catch (Exception e)
{
e.printStackTrace();
}
return courses;
}
}

[/sourcecode]

web.xml

[sourcecode language="xml"]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RestProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Course Service</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Course Service</servlet-name>
<url-pattern>/Rest/*</url-pattern>
</servlet-mapping>
</web-app>
[/sourcecode]

Run the application in server.
visit following URL :
http://localhost:8440/RestProject/Rest/courseService/courses
The port number in the URL depends on your server settings.
You will see the JSON response.

 

Help make a developer's life happy and strong.


Donate Button with Credit Cards

Monday, November 5, 2012

Java Restful Web Services(JAX-RS) Using Jersy

This tutorial demonstrates how to build a Java Restful web service in Eclipse using Jersy plugin.

Download project

REST(Representational State Transfer) is an architectural style. This is not a standard whereas SOAP is standardized. RESTful web services are based on HTTP protocol and its methods PUT, GET, POST, and DELETE. They do not require XML SOAP messages or WSDL service definitions.

REST can be considered similar to a client-server architecture. There 's a REST server waiting for the requests from REST clients.

Requirements :

Main Topics



  1. Install Jersy plugin

  2. Create resource

  3. Create client

  4. Configure web.xml



1. Install Jersy plugin


Create new dynamic web project. Add  following jars from the downloaded Jersey zip file to WEB-INF/lib. Add them to project Build Path.

1. Create resource


[sourcecode language="java"]
package com.res;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

//Sets the path to base URL + /hello
@Path("/hello")
public class Hello {

// This method is called if TEXT_PLAIN is request
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}

// This method is called if XMLis request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}

// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}

}
[/sourcecode]

3. Create client


[sourcecode language="java"]
package com.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class client {

/**
* @param args
*/
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
// Fluent interfaces
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
// Get plain text
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
// Get XML
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));
// The HTML
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));
}

private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8440/Success").build();
}

}
[/sourcecode]

4. Configure web.xml


[sourcecode language="java"]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Success</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.res</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
[/sourcecode]

web.xml is tricky!
[Extracted from : http://www.javahotchocolate.com/tutorials/restful.html]
The display name. It can be anything, but it's

what goes first thing in the URL (browser address

line) after the protocol (http) and domain-

name:port-number. Note that I'm not using

anything that looks like a package name here. I

don't even have to use the Eclipse project name.

Obviously, it cannot contain a space.

The servlet name. It can have spaces in it, but it's

used in another place and the two must be identical.

The servlet name doesn't show up outside this file,

but this file uses it to find the appropriate mapping

definition.

The servlet container class. This pertains to the

framework you're using. Here, we're using Jersey, so

we're sure to name that class which comes out of

the user library (set of Jersey JARs) we used.

The servlet container class parameter name, as

dictated (in this instance) by the REST servlet

container or framework in use.

The value of the preceding parameter. It must be

the package name that contains at least and at most

one (JAXB) servlet (.java file). There may be more

than one such servlet, but if so, the other(s) must be

in a different Java package.

The servlet name must be identical to the one

already specified above. As noted, if there are two

servlets, there are two servlet definitions and two,

separate servlet mapping definitions.

The URL pattern. It starts with '/' and ends with

'/*' and can be any legitimate directory-like

identifier (without spaces). It is the penultimate

element of the URL, just before the class name path.

web.xml:




Fun



Jersey REST Service
com.sun.jersey.spi.container.servlet.ServletCo

ntainer

com.sun.jersey.config.property.packages


de.vogella.jersey.first

1




Fun with REST
com.sun.jersey.spi.container.servlet.ServletCo

ntainer

com.sun.jersey.config.property.packages


com.etretatlogiciels.fun

1




Jersey REST Service
/rest/*



Fun with REST
/fun/*


Friday, November 2, 2012

Java SOAP Web Service With Apache Axis2 in Eclipse

Web Service

Today we are going to build a SOAP based Java web service. We are using AXIS2 which serves as a SOAP implementation. I assume that you have already installed Java JDK in to your machine.

Requirements :

1) Eclipse EE – Download
2) Apache Tomcat - Download
3) Apache Axis2 Binary Distribution - Download
4) Apache Axis2 WAR Distribution - Download

While installing these programs, consider about default ports. There may be port conflicts if you neglect this fact. This becomes an issue only if you are allocating ports which are already used by previously installed programs. For an instance, there may be a port conflict when attempting to install Tomcat server using port 8080 in a machine where Oracle 10g is installed. Both of these use port 8080 by default. So you may change the ports as necessary during or after the installation.

Please note that there may be various compatibility issues when using Eclipse and Apache Tomcat with Axis2 to build our web service. Most of the problems can be minimized with Netbeans. GlassFish server supports out of the box in many occasions with Netbeans.
Let's deal with Netbeans at a later time.

I'm using Eclipse Indigo, Apache Tomcat 6 and Axis2 for this tutorial.

Extract Apache Axis2 Binary Distribution. Create an Environment Variable as AXIS2_HOME. Get the path to Axis2 installation directory and use it as the value of AXIS2_HOME Environment Variable. (something like C:\Program Files\axis2-1.6.2)

Extract Axis2 WAR Distribution and copy axis2.war file to Tomcat server webapps directory.

Now you are ready to go ahead with this tutorial. First check our road map.
1. Setup Development Environment in Eclipse.
2. Create Web Service.
3. Deploy web service.
4. Create a client who consumes Web Service.

1. Setup Development Environment in Eclipse.


Now you need to configure Eclipse for Tomcat server and Axis2.
Open Eclipse IDE and go to Window >> Preferences
Add new server runtime environment.



Select your Tomcat server version and click Next. Browse your Tomcat installation directory in next window.



Now configure Axis2 in Axis2 preferences under Web Services category. Browse your Axis2 installation directory. You should see this message if this is fine.
"Axis2 runtime loaded successfully"



Select Server and Runtime. Make sure your server runtime is selected. Web service runtime should be Apache Axis2.



 

2. Create Web Service.


First create a new Dynamic Web Project (File >> New >> Other) and choose Web >> Dynamic Web Project. Enter project settings in the first window.
Select the target runtime that we configured earlier.
You should modify the configuration so that Axis2 is included into the project.



Remeber to put a tick on Axis2 web services



Click Next>>Next and Finish. Now Eclipse will load the project.
Now it's time to create web service class. This class can contain some methods which are exposed to outside. The clients are going to consume this web service class. First we create a Plain Old Java Class and convert it into a web service. Right click on project and select New>> Class



Add a public method to this class.

[sourcecode language="java"]
package com.codezone4;

public class MyService
{
public String testMethod(String param)
{
return "Read " + param;
}
}
[/sourcecode]

To expose this file as a web service right click on the Java file and select Web Services >> Create Web Service
or
select File >> New >> Other and choose Web Service.
You can can add web service using one of above methods.

We use bottom-up approach as web service type. Select the class which acts as the web service(that we just created). Make sure your configurations are correct.



Click Next. Make sure Generate a default service.xml file is selected and click Next. Now you are asked to Start Server. Do it!
Then Click Next and Finish the dialog.
Now you should be able to reach your web service through your browser. Tomcat server is started and you gonna run your web service in Tomcat.
Right click on your project and select Run as >> Run on server.

You may see the below screen through your Eclipse web browser. Alternatively you can copy the following URL into your web browser bar.
http://localhost:8440/HelloWorldWebService/
This port number 8888 depends on your Tomcat configuarations.



Go to Services. Under Available Services you will find your own service. Click on MyService link (You will find your web service class name here).
Can you see bunch of beautiful xml? This is your WSDL(Web Service Description Language). The clients who consume your service communicate with this WSDL to access the functionality of the web service.
Copy the URL for WSDL file.
You can validate this file at a later time when you create the client. To do that enable WSDL validation for all files in Eclipse preferences. This option can be found under web service category.

Obviously you can play with your web service without a real client using Web Service Explorer tool in Eclipse. Click that icon



This will launch a screen similar to the following.



Click WSDL page icon. On the next screen, click WSDL Main under navigation section.
Enter your WSDL URL into the box and click Go. On the left you will see a hierarchical representation of your web service. Play around with this for a while and test your web service with different inputs....


3. Deploy web service.



In current situation, the web service can only be run within Eclipse. So we are going to deploy it to Tomcat server. First create .aar (Axis Archive)
Got to your web service directory using command prompt.
Eg. C:\Users\AAA\Documents\Eclipse\HelloWorldWebService\WebContent\WEB-INF\services\MyService

Enter following command to create .aar file.
jar cvf HelloWorldWebService.aar com META-INF
This will generate .aar file in your web service directory. Now wanna upload this file using the Administration panel in Axis2. You can enter this area using Axis home page Administration link.
username : admin
password : axis2

Or else you can simply copy the .aar file and paste into Tomcat webapps\axis2\WEB-INF\services directory.

To verify your deployment first stop Tomcat server in Eclipse. Click on red, small rectangular button on Servers panel to stop Tomcat.
Next go to Tomcat bin directory and find startup.bat file. Run this file to start Tomcat. If you are using Mac run startup.sh file.
Then go to your web service URL.
http://localhost:8440/HelloWorldWebService/

 

4. Create a Web service client



Select File >> New >> Other and choose Web Service Client.
Enter WSDL URL into the box. Here you can browse for WSDL and validate if needed.



This will generate two new classes called MyServiceStub.java and MyServiceCallbackHandler.java. Now we can create client. Create new class called TestClient.java and paste following code.

[sourcecode language="java"]
package com.codezone4;

import java.rmi.RemoteException;
import com.codezone4.MyServiceStub.TestMethod;
import com.codezone4.MyServiceStub.TestMethodResponse;

public class TestClient {

public static void main(String[] args) throws RemoteException {
MyServiceStub stub = new MyServiceStub();
TestMethod method = new TestMethod();
method.setParam(" Cheers!");
TestMethodResponse response = stub.testMethod(method);
System.out.println(response.get_return());

}

}

[/sourcecode]

Run this client as a Java application. Observe the output in console. You should see the message that resulted from remote method call if everything worked fine.

I think you enjoy this web service tut. Please leave a comment.
Happy coding!

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...