Статьи

Restlet Framework — Пример Hello World

Restlet — это легкая, всеобъемлющая среда REST с открытым исходным кодом для платформы Java. Рестлет подходит как для серверных, так и для клиентских веб-приложений. Он поддерживает основные стандарты интернет-транспорта, формата данных и описания услуг, такие как HTTP и HTTPS, SMTP, XML, JSON, Atom и WADL. Порт GWT библиотеки на стороне клиента также доступен. (Ссылка: http://en.wikipedia.org/wiki/Restlet)

Пример Hello World

  • Структура проекта

Selection_021

  • RestletApplication.java
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
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
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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
01
02
03
04
05
06
07
08
09
10
11
12
13
14
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
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# -----------------------------
# 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
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
  <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>

 

  • Вызов веб-службы Hello World

Selection_022