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