Wednesday, December 29, 2010

Restful webservices with Eclipse

Java file place it in the same package

package name.brucephillips.hellows.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;

/**
 * Defines a RESTful web service
 * that can be called by using
 * the URI /hello
 *
 * @author Bruce Phillips
 *
 */
@Path("/hello")
public class HelloResource {

    /**
     * Processes HTTP get requests
     * that have no parameters
     * for example /hello
     * @return "Hello"
     */
    @GET
    @Produces("text/plain")
    public String getMessage() {
       
        // Return plain text
        return "Hello";
       
    }//end method getMessage
   
    /**
     * Processes HTTP get requests
     * that have a username parameter
     * for example /hello/Bruce
     * @param userName
     * @return "Hello {userName}"
     */
    @GET
    @Path("{username}")
    @Produces("text/plain")
    public String getMessage(@PathParam("username") String userName) {
       
        return "Hello " + userName;
       
    }//end overloaded method getMessage
   
    /**
     * Processes HTTP post requests
     * that have sent a form parameter
     * named name
     * @param name
     * @return "Hello {name}"
     */
    @POST
    @Consumes("application/x-www-form-urlencoded")
    @Produces("text/plain")
    public String postMessage(@FormParam("name") String name) {
        System.out.println("In here");
        return "Hello " + name;
       
    }//end method postMessage
  
   
   
}//end class HelloResource




web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>helloWS</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Jersey Web Application</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>name.brucephillips.hellows.resources</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
</web-app>

index.jsp
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Hello Home Page</title>
</head>
<body>
<h3>Example RESTful Web Service</h3>

<p>Click on a link to call one of the helloWS methods and view the response.</p>

<p><a href="services/hello">Plain Hello</a></p>

<p><a href="services/hello/Bruce">Hello Bruce</a></p>

<p>Enter your name and click the button to get a personal hello.</p>

<form method="post" action="services/hello">

<p>Name: <input type="text" name="name" /></p>

<p><input type="submit" name="submit" value="Submit" /></p>

</form>

<h3>References</h3>

<ol>
<li><a href="http://wikis.sun.com/display/Jersey/Main" target="_blank">Jersey: RESTful Web services made easy</a></li>
<li><a href="http://docs.sun.com/app/docs/doc/820-4867/6nga7f5mk?l=en&a=view" target="_blank">RESTful Web Services Developer's Guide</a></li>
<li><a href="https://jsr311.dev.java.net/nonav/releases/1.0/index.html?overview-summary.html" target="_blank">jsr311-api 1.0 API</a></li>
<li><a href="http://lqd.hybird.org/journal/?p=123" target="_blank">Hacking Jersey/JAX-RS to run RESTful web services on Google AppEngine/Java</a></li>
<li><a href="http://www.brucephillips.name/restful/helloWS.zip" target="_blank">Zipped Eclipse Maven Project</a></li>
</ol>


</body>
</html>


Add the jar files

asm-3.1.jar
jersey-core-1.1.0-ea.jar
jersey-server-1.1.0-ea.jar
jsr311-api-1.1.jar

Make sure the jar version are the same....



In this article I would like to describe how to get your RESTful webservice to output XML. RESTful doesnt output as much detail as the SOAP specification, but it gives you enough data to work with, assuming you know what the data types are.
Firstly, create a class that represents your output. Remember the import!
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class userData {
    public String firstname;
    public String lastname;
    public String idnumber;
    public String pin;
    public int status;
}
Then we can start coding the webservice. I’m not going to go into detail, but am just going to put in the specifics that are relevant for this article
import java.util.ArrayList;
import java.util.List;
 
@Path("airtime_functions")
public class airtime {
    @GET
    @Path("get_users")
    @Produces("application/xml")
    public List<userData> get_users(@QueryParam("user_id") String user_id)
    {
        List<userData> retUser = new ArrayList<userData>();
        try
        {
            errorMsg = "";
            con = getJNDIConnection();
            stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            String sql = "SELECT * from users where user_id = ?";
            PreparedStatement prest = con.prepareStatement(sql);
            prest.setString(1, user_id);
            prest.execute();
            rs = prest.getResultSet();
            while (rs.next())
            {
                userData toReturn = new userData();
                toReturn.firstname = rs.getString("firstname");
                toReturn.idnumber = rs.getString("idnumber");
                toReturn.lastname = rs.getString("surname");
                toReturn.pin = rs.getString("pin");
                toReturn.status = rs.getInt("status");
                retUser.add(toReturn);
            }
            con.close();
            return retUser;
        } catch (Exception e)
        {
            userData toReturn = new userData();
            toReturn.firstname = "Error: " + e;
            toReturn.idnumber = "";
            toReturn.lastname = "";
            toReturn.pin = "";
            toReturn.status = 0;
            retUser.add(toReturn);
            return retUser;
        }
    }

No comments:

Post a Comment