2c6bc94b7c76fd0048a6dda72901940481622f20
[vfc/nfvo/wfengine.git] / wso2bpel-ext / wso2bpel-core / BPEL4RESTLight / src / main / java / org / opentosca / bpel4restlight / rest / LowLevelRestApi.java
1 /**
2  * This static-class eases HTTP-method execution by self-managed fault-handling
3  * and automated Response-information processing
4  */
5 package org.opentosca.bpel4restlight.rest;
6
7 import java.io.IOException;
8 import java.util.Map;
9 import java.util.Set;
10
11 import org.apache.commons.httpclient.Header;
12 import org.apache.commons.httpclient.HttpClient;
13 import org.apache.commons.httpclient.HttpMethod;
14 import org.apache.commons.logging.Log;
15 import org.apache.commons.logging.LogFactory;
16 import org.json.simple.JSONArray;
17 import org.json.simple.JSONObject;
18 import org.json.simple.parser.JSONParser;
19 import org.json.simple.parser.ParseException;
20
21
22 public class LowLevelRestApi {
23         
24   protected static final Log log = LogFactory.getLog(LowLevelRestApi.class);
25         // Local HttpClient used for every communication (Singleton implementation)
26 //      private static HttpClient httpClient = new HttpClient();
27         
28         /**
29          * Executes a passed HttpMethod (Method type is either PUT, POST, GET or
30          * DELETE) and returns a HttpResponseMessage
31          * 
32          * @param method Method to execute
33          * @return HttpResponseMessage which contains all information about the
34          *         execution
35          */
36         public static HttpResponseMessage executeHttpMethod(HttpMethod method) {
37                 
38                 HttpResponseMessage responseMessage = null;
39                 
40                 try {
41                         log.debug("Method invocation on URI: \n");
42                         log.debug(method.getURI().toString());
43                         
44                         // Execute Request
45                         HttpClient httpClient = new HttpClient();
46                         httpClient.executeMethod(method);
47                         responseMessage = LowLevelRestApi.extractResponseInformation(method);
48                         
49                 } catch (Exception e) {
50                   log.error("call rest error:", e);
51                 } finally {
52                         // Release Connection anyway
53                         method.releaseConnection();
54                 }
55                 
56                 // Extract response information and return
57                 return responseMessage;
58         }
59         
60         /**
61          * Extracts the response information from an executed HttpMethod
62          * 
63          * @param method Executed Method
64          * @return Packaged response information
65          */
66         private static HttpResponseMessage extractResponseInformation(HttpMethod method) {
67                 // Create and return HttpResponseMethod
68                 HttpResponseMessage responseMessage = new HttpResponseMessage();
69                 responseMessage.setStatusCode(method.getStatusCode());
70                 try {
71                         responseMessage.setResponseBody(getResponseBody(method));
72                 } catch (Exception e) {
73                     log.error(e);
74                 }
75                 return responseMessage;
76                 
77         }
78         
79         /**
80          * getResponseBody 
81          * 
82          * get response body info, if response body is a json object, then translate json object to xml
83          * if the rest request failed, i.e. the response body is a 404 error page, then response the body with header <root>
84          * @param method
85          * @return
86          * @throws ParseException
87          */
88         private static String getResponseBody(HttpMethod method) throws ParseException
89         {
90           String result = null;
91           try {
92             result = method.getResponseBodyAsString();
93                 log.debug("result:");
94                 log.debug(result);
95           } catch (IOException e) {
96             log.error(e);
97           }
98           
99           Header header = method.getRequestHeader("Accept");
100           if ("application/json".equals(header.getValue())) {
101             StringBuilder sb = new StringBuilder();
102             sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
103             sb.append("<root>");
104             if(result != null && !"".equals(result)) {
105               /**
106                   if(result.startsWith("<html>")) {
107                 sb.append("<![CDATA[");
108                 sb.append(result);
109                 sb.append("]]>");
110               } else {
111                 Object json = new JSONParser().parse(result);
112                 json2Xml(sb, "obj", json);
113               }
114                   */
115                   
116                   try {
117                         Object json = new JSONParser().parse(result);
118                 json2Xml(sb, "obj", json);
119                   } catch (Exception e) {
120                         log.error(e);
121                         sb.append("<![CDATA[");
122                 sb.append(result);
123                 sb.append("]]>");
124                   }
125             }
126             sb.append("</root>");
127             
128                 log.debug("responseBody:");
129                 log.debug(sb.toString());
130             return sb.toString();
131           }
132           return result;
133         }
134         
135         
136         @SuppressWarnings("unchecked")
137         public static void json2Xml(StringBuilder sb, String key,  Object jsonObject) {
138           if(jsonObject == null) {
139             sb.append("<error>empty</error>");
140             return;
141           }
142           
143           if(jsonObject instanceof JSONArray) {
144             JSONArray array = (JSONArray) jsonObject;
145             sb.append("<").append(key).append("s").append(">");
146             for(int i=0, len=array.size(); i<len; i++) {
147               json2Xml(sb, key, array.get(i));
148             }
149             sb.append("</").append(key).append("s").append(">");
150             
151             return;
152           } else if(jsonObject instanceof JSONObject) {
153             sb.append("<").append(key).append(">");
154             JSONObject json = (JSONObject) jsonObject;
155             for(Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>)json.entrySet()) {
156               json2Xml(sb, entry.getKey(), entry.getValue());
157             }
158             sb.append("</").append(key).append(">");
159             return;
160           } else {
161             sb.append("<").append(key).append(">");
162             sb.append("<![CDATA[");
163             sb.append(jsonObject.toString());
164             sb.append("]]>");
165             sb.append("</").append(key).append(">");
166             
167             return;
168           }
169         }
170         
171 }