summaryrefslogtreecommitdiffstats
path: root/wso2/wso2bpel-ext/wso2bpel-core/BPEL4RESTLight/src/main/java/org/opentosca/bpel4restlight/rest/LowLevelRestApi.java
blob: c522ca95fd1fb65cce3a3c8c04c0c299a0ce444a (plain)
1
2
3
4
5
6
7
8
9
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/*******************************************************************************
 * Copyright (c) 2012-2013 University of Stuttgart.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and the Apache License 2.0 which both accompany this distribution,
 * and are available at http://www.eclipse.org/legal/epl-v10.html
 * and http://www.apache.org/licenses/LICENSE-2.0
 *******************************************************************************/
/*
 * Modifications Copyright 2016-2017 ZTE Corporation.
 */
 /**
 * This static-class eases HTTP-method execution by self-managed fault-handling
 * and automated Response-information processing
 */
package org.opentosca.bpel4restlight.rest;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;


public class LowLevelRestApi {
	
  protected static final Log log = LogFactory.getLog(LowLevelRestApi.class);
	// Local HttpClient used for every communication (Singleton implementation)
//	private static HttpClient httpClient = new HttpClient();
	
	/**
	 * Executes a passed HttpMethod (Method type is either PUT, POST, GET or
	 * DELETE) and returns a HttpResponseMessage
	 * 
	 * @param method Method to execute
	 * @return HttpResponseMessage which contains all information about the
	 *         execution
	 */
	public static HttpResponseMessage executeHttpMethod(HttpMethod method) {
		
		HttpResponseMessage responseMessage = null;
		
		try {
			log.debug("Method invocation on URI: \n");
			log.debug(method.getURI().toString());
			
			// Execute Request
			HttpClient httpClient = new HttpClient();
			httpClient.executeMethod(method);
			responseMessage = LowLevelRestApi.extractResponseInformation(method);
			
		} catch (Exception e) {
		  log.error("call rest error:", e);
		} finally {
			// Release Connection anyway
			method.releaseConnection();
		}
		
		// Extract response information and return
		return responseMessage;
	}
	
	/**
	 * Extracts the response information from an executed HttpMethod
	 * 
	 * @param method Executed Method
	 * @return Packaged response information
	 */
	private static HttpResponseMessage extractResponseInformation(HttpMethod method) {
		// Create and return HttpResponseMethod
		HttpResponseMessage responseMessage = new HttpResponseMessage();
		responseMessage.setStatusCode(method.getStatusCode());
		try {
			responseMessage.setResponseBody(getResponseBody(method));
		} catch (Exception e) {
		    log.error(e);
		}
		return responseMessage;
		
	}
	
	/**
	 * getResponseBody 
	 * 
	 * get response body info, if response body is a json object, then translate json object to xml
	 * if the rest request failed, i.e. the response body is a 404 error page, then response the body with header <root>
	 * @param method
	 * @return
	 * @throws ParseException
	 */
	private static String getResponseBody(HttpMethod method) throws ParseException
	{
	  String result = null;
	  try {
	    result = method.getResponseBodyAsString();
		log.debug("result:");
		log.debug(result);
	  } catch (IOException e) {
	    log.error(e);
	  }
	  
	  Header header = method.getRequestHeader("Accept");
	  if ("application/json".equals(header.getValue())) {
	    StringBuilder sb = new StringBuilder();
	    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
	    sb.append("<root>");
	    if(result != null && !"".equals(result)) {
	      /**
		  if(result.startsWith("<html>")) {
	        sb.append("<![CDATA[");
	        sb.append(result);
	        sb.append("]]>");
	      } else {
	        Object json = new JSONParser().parse(result);
	        json2Xml(sb, "obj", json);
	      }
		  */
		  
		  try {
			Object json = new JSONParser().parse(result);
	        json2Xml(sb, "obj", json);
		  } catch (Exception e) {
			log.error(e);
			sb.append("<![CDATA[");
	        sb.append(result);
	        sb.append("]]>");
		  }
	    }
	    sb.append("</root>");
	    
		log.debug("responseBody:");
		log.debug(sb.toString());
	    return sb.toString();
	  }
	  return result;
	}
	
	
	@SuppressWarnings("unchecked")
	public static void json2Xml(StringBuilder sb, String key,  Object jsonObject) {
	  if(jsonObject == null) {
	    sb.append("<error>empty</error>");
	    return;
	  }
	  
	  if(jsonObject instanceof JSONArray) {
	    JSONArray array = (JSONArray) jsonObject;
	    sb.append("<").append(key).append("s").append(">");
	    for(int i=0, len=array.size(); i<len; i++) {
	      json2Xml(sb, key, array.get(i));
	    }
	    sb.append("</").append(key).append("s").append(">");
	    
	    return;
	  } else if(jsonObject instanceof JSONObject) {
	    sb.append("<").append(key).append(">");
	    JSONObject json = (JSONObject) jsonObject;
	    for(Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>)json.entrySet()) {
	      json2Xml(sb, entry.getKey(), entry.getValue());
	    }
	    sb.append("</").append(key).append(">");
	    return;
	  } else {
	    sb.append("<").append(key).append(">");
	    sb.append("<![CDATA[");
	    sb.append(jsonObject.toString());
	    sb.append("]]>");
	    sb.append("</").append(key).append(">");
	    
	    return;
	  }
	}
	
}