About Sunil Gulabani

Sunil Gulabani is a JAVA software engineer and Cloud Technology Savvy. He has developed enterprise solutions using Java(EE), Apache Solr, GWT, GWT-P, SmartGWT, Restlet and Hibernate.

Restlet Framework – Hello World Example

Restlet is a lightweight, comprehensive, open source REST framework for the Java platform. Restlet is suitable for both server and client Web applications. It supports major Internet transport, data format, and service description standards like HTTP and HTTPS, SMTP, XML, JSON, Atom, and WADL. A GWT port of the client-side library is also available. (Reference: http://en.wikipedia.org/wiki/Restlet)

Hello World Example

 
 
 

  • Project Structure

Selection_021

  • RestletApplication.java
package com.restlet.demo.application;

import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;

import com.restlet.demo.resource.HelloWorldResource;

public class RestletApplication extends Application{ 
    public synchronized Restlet createInboundRoot() {
        Router router = new Router(getContext());
        router.attach("/helloWorld",HelloWorldResource.class );
        return router;
    }
}
  • ResponseParseFactory.java
package com.restlet.demo.core;

import java.util.LinkedHashMap;

import org.apache.log4j.Logger;
import org.json.simple.JSONValue;

public class ResponseParseFactory {

 static Logger logger = Logger.getLogger(ResponseParseFactory.class);

 @SuppressWarnings({ "rawtypes", "unchecked" })
 public String getFailureJsonString(String msg){
  String jsonString = "";
  LinkedHashMap list = new LinkedHashMap();
  list.put("response_status", "false");

  list.put("result", msg+"");
  jsonString = JSONValue.toJSONString(list);
  logger.info(jsonString);
  return jsonString;
 }

 @SuppressWarnings({ "rawtypes", "unchecked" })
 public String getSuccessJsonString(String msg){
  String jsonString = "";
  LinkedHashMap list = new LinkedHashMap();
  list.put("response_status","true");

  list.put("result", msg);
  jsonString = JSONValue.toJSONString(list);
  logger.info(jsonString);
  return jsonString;
 }
}
  • BaseResource.java
package com.restlet.demo.resource;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Parameter;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

import com.restlet.demo.core.ResponseParseFactory;

public abstract class BaseResource extends ServerResource{

  protected ResponseParseFactory parseFactory = null;
  protected Logger logger = Logger.getLogger(BaseResource.class);
  String jsonString="";

 @SuppressWarnings("rawtypes")
 @Post("json")
 public Representation doPost(Representation entity){
  Map json =null;
  jsonString = "";
  parseFactory = new ResponseParseFactory();
  try {
   JsonRepresentation represent = new JsonRepresentation(entity);
   JSONObject jsonobject = represent.getJsonObject();
   JSONParser parser = new JSONParser();
   String jsonText = jsonobject.toString();
   json = (Map) parser.parse(jsonText);
   jsonString = processRequest(json,"post");
  } catch (Exception e) {
   e.printStackTrace();
   jsonString = parseFactory.getFailureJsonString(e.getMessage());
  }
  return new StringRepresentation(jsonString, MediaType.APPLICATION_JSON);
 }

 @SuppressWarnings("rawtypes")
 @Get
 public Representation doGet(){
  Map json =null;
  parseFactory = new ResponseParseFactory();
  jsonString = "";
  try {
   json = getMapFromParam(getRequest().getResourceRef().getQueryAsForm());
   parseFactory = new ResponseParseFactory();
   jsonString = processRequest(json,"get");

  } catch (Exception e) {
   e.printStackTrace();
   jsonString = parseFactory.getFailureJsonString(e.getMessage());
  }
  return new StringRepresentation(jsonString, MediaType.APPLICATION_JSON);
 }

 public abstract String processRequest(Map json,String method);

 public static Map<String, String> getMapFromParam(Form form) {
  Map<String, String> map = new HashMap<String, String>();
  for (Parameter parameter : form) {
   map.put(parameter.getName(), parameter.getValue());
  }
  return map;
 }

}
  • HelloWorldResource.java
package com.restlet.demo.resource;

import java.util.Map;

import com.restlet.demo.core.ResponseParseFactory;

public class HelloWorldResource extends BaseResource {

 public String processRequest(Map json, String method) {
  String returnString = "" ;
  returnString = new ResponseParseFactory().getSuccessJsonString("Hello " + json.get("user"));
  return returnString;
 }
}
  • log4j.properties
# -----------------------------
# Appender to write to console.
# -----------------------------
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.appender.CONSOLE.file =${catalina.base}/logs/regularLogging.log
log4j.appender.CONSOLE.MaxFileSize=100KB

# ---------------------------------------------
# Appender to write to application log.
# ---------------------------------------------
log4j.appender.APPLICATIONLOG=org.apache.log4j.DailyRollingFileAppender
log4j.appender.APPLICATIONLOG.File=${catalina.base}/logs/restlet-demo.log
log4j.appender.APPLICATIONLOG.DatePattern='.'yyyy-MM-dd
#log4j.appender.APPLICATIONLOG.File=/home/devphp/public_html/restletframework/logs/APPLICATION-LOG.log
log4j.appender.APPLICATIONLOG.Encoding=UTF-8
log4j.appender.APPLICATIONLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.APPLICATIONLOG.layout.ConversionPattern=%d [%5p]: %m%n

# Turn off root logging.
#log4j.rootLogger=info, APPLICATIONLOG
log4j.rootLogger=info, CONSOLE , APPLICATIONLOG
  • web.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>RestletDemo</display-name>
 <servlet>
  <servlet-name>RestletServlet</servlet-name>
  <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
  <init-param>
   <param-name>org.restlet.application</param-name>
   <param-value>com.restlet.demo.application.RestletApplication</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>RestletServlet</servlet-name>
  <url-pattern>/service/*</url-pattern>
 </servlet-mapping>
</web-app>

 

  • Calling Hello World Web Service

Selection_022
 

Reference: Restlet Framework – Hello World Example from our JCG partner Sunil Gulabani at the Sunil Gulabani blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "Restlet Framework – Hello World Example"

  1. Shai says:

    Can you do some sample code about how Restlet leverages the following methods and what exactly is going on with and how they are instantiated:

    Context, Dictionary, createInboundRoot vs createRoot, Component, Handle (Request request, Response response, etc.)

    Thanks

Leave a Reply


one × 6 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close