forked from AnythingLinux/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiResponseSerializer.java
More file actions
333 lines (297 loc) · 14.4 KB
/
ApiResponseSerializer.java
File metadata and controls
333 lines (297 loc) · 14.4 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.api.response;
import com.cloud.api.ApiDBUtils;
import com.cloud.api.ApiResponseGsonHelper;
import com.cloud.api.ApiServer;
import com.cloud.utils.encoding.URLEncoder;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.exception.ExceptionProxyObject;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.ResponseObject;
import org.apache.cloudstack.api.response.*;
import org.apache.log4j.Logger;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ApiResponseSerializer {
private static final Logger s_logger = Logger.getLogger(ApiResponseSerializer.class.getName());
public static String toSerializedString(ResponseObject result, String responseType) {
s_logger.trace("===Serializing Response===");
if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
return toJSONSerializedString(result);
} else {
return toXMLSerializedString(result);
}
}
private static final Pattern s_unicodeEscapePattern = Pattern.compile("\\\\u([0-9A-Fa-f]{4})");
public static String unescape(String escaped) {
String str = escaped;
Matcher matcher = s_unicodeEscapePattern.matcher(str);
while (matcher.find()) {
str = str.replaceAll("\\" + matcher.group(0), Character.toString((char) Integer.parseInt(matcher.group(1), 16)));
}
return str;
}
public static String toJSONSerializedString(ResponseObject result) {
if (result != null) {
Gson gson = ApiResponseGsonHelper.getBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create();
StringBuilder sb = new StringBuilder();
sb.append("{ \"").append(result.getResponseName()).append("\" : ");
if (result instanceof ListResponse) {
List<? extends ResponseObject> responses = ((ListResponse) result).getResponses();
Integer count = ((ListResponse) result).getCount();
boolean nonZeroCount = (count != null && count.longValue() != 0);
if (nonZeroCount) {
sb.append("{ \"").append(ApiConstants.COUNT).append("\":").append(count);
}
if ((responses != null) && !responses.isEmpty()) {
String jsonStr = gson.toJson(responses.get(0));
jsonStr = unescape(jsonStr);
if (nonZeroCount) {
sb.append(" ,\"").append(responses.get(0).getObjectName()).append("\" : [ ").append(jsonStr);
}
for (int i = 1; i < ((ListResponse) result).getResponses().size(); i++) {
jsonStr = gson.toJson(responses.get(i));
jsonStr = unescape(jsonStr);
sb.append(", ").append(jsonStr);
}
sb.append(" ] }");
} else {
if (!nonZeroCount){
sb.append("{");
}
sb.append(" }");
}
} else if (result instanceof SuccessResponse) {
sb.append("{ \"success\" : \"").append(((SuccessResponse) result).getSuccess()).append("\"} ");
} else if (result instanceof ExceptionResponse) {
String jsonErrorText = gson.toJson((ExceptionResponse) result);
jsonErrorText = unescape(jsonErrorText);
sb.append(jsonErrorText);
} else {
String jsonStr = gson.toJson(result);
if ((jsonStr != null) && !"".equals(jsonStr)) {
jsonStr = unescape(jsonStr);
if (result instanceof AsyncJobResponse || result instanceof CreateCmdResponse) {
sb.append(jsonStr);
} else {
sb.append(" { \"").append(result.getObjectName()).append("\" : ").append(jsonStr).append(" } ");
}
} else {
sb.append("{ }");
}
}
sb.append(" }");
return sb.toString();
}
return null;
}
private static String toXMLSerializedString(ResponseObject result) {
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sb.append("<").append(result.getResponseName()).append(" cloud-stack-version=\"").append(ApiDBUtils.getVersion()).append("\">");
if (result instanceof ListResponse) {
Integer count = ((ListResponse) result).getCount();
if (count != null && count != 0) {
sb.append("<").append(ApiConstants.COUNT).append(">").append(((ListResponse) result).getCount()).
append("</").append(ApiConstants.COUNT).append(">");
}
List<? extends ResponseObject> responses = ((ListResponse) result).getResponses();
if ((responses != null) && !responses.isEmpty()) {
for (ResponseObject obj : responses) {
serializeResponseObjXML(sb, obj);
}
}
} else {
if (result instanceof CreateCmdResponse || result instanceof AsyncJobResponse) {
serializeResponseObjFieldsXML(sb, result);
} else {
serializeResponseObjXML(sb, result);
}
}
sb.append("</").append(result.getResponseName()).append(">");
return sb.toString();
}
private static void serializeResponseObjXML(StringBuilder sb, ResponseObject obj) {
if (!(obj instanceof SuccessResponse) && !(obj instanceof ExceptionResponse)) {
sb.append("<").append(obj.getObjectName()).append(">");
}
serializeResponseObjFieldsXML(sb, obj);
if (!(obj instanceof SuccessResponse) && !(obj instanceof ExceptionResponse)) {
sb.append("</").append(obj.getObjectName()).append(">");
}
}
public static Field[] getFlattenFields(Class<?> clz) {
List<Field> fields = new ArrayList<Field>();
fields.addAll(Arrays.asList(clz.getDeclaredFields()));
if (clz.getSuperclass() != null) {
fields.addAll(Arrays.asList(getFlattenFields(clz.getSuperclass())));
}
return fields.toArray(new Field[] {});
}
private static void serializeResponseObjFieldsXML(StringBuilder sb, ResponseObject obj) {
boolean isAsync = false;
if (obj instanceof AsyncJobResponse)
isAsync = true;
//Field[] fields = obj.getClass().getDeclaredFields();
Field[] fields = getFlattenFields(obj.getClass());
for (Field field : fields) {
if ((field.getModifiers() & Modifier.TRANSIENT) != 0) {
continue; // skip transient fields
}
SerializedName serializedName = field.getAnnotation(SerializedName.class);
if (serializedName == null) {
continue; // skip fields w/o serialized name
}
field.setAccessible(true);
Object fieldValue = null;
try {
fieldValue = field.get(obj);
} catch (IllegalArgumentException e) {
throw new CloudRuntimeException("how illegal is it?", e);
} catch (IllegalAccessException e) {
throw new CloudRuntimeException("come on...we set accessible already", e);
}
if (fieldValue != null) {
if (fieldValue instanceof ResponseObject) {
ResponseObject subObj = (ResponseObject) fieldValue;
if (isAsync) {
sb.append("<jobresult>");
}
serializeResponseObjXML(sb, subObj);
if (isAsync) {
sb.append("</jobresult>");
}
} else if (fieldValue instanceof Collection<?>) {
Collection<?> subResponseList = (Collection<Object>) fieldValue;
boolean usedUuidList = false;
for (Object value : subResponseList) {
if (value instanceof ResponseObject) {
ResponseObject subObj = (ResponseObject) value;
if (serializedName != null) {
subObj.setObjectName(serializedName.value());
}
serializeResponseObjXML(sb, subObj);
} else if (value instanceof ExceptionProxyObject) {
// Only exception reponses carry a list of
// ExceptionProxyObject objects.
ExceptionProxyObject idProxy = (ExceptionProxyObject) value;
// If this is the first IdentityProxy field
// encountered, put in a uuidList tag.
if (!usedUuidList) {
sb.append("<" + serializedName.value() + ">");
usedUuidList = true;
}
sb.append("<" + "uuid" + ">" + idProxy.getUuid() + "</" + "uuid" + ">");
// Append the new descriptive property also.
String idFieldName = idProxy.getDescription();
if (idFieldName != null) {
sb.append("<" + "uuidProperty" + ">" + idFieldName + "</" + "uuidProperty" + ">");
}
}
}
if (usedUuidList) {
// close the uuidList.
sb.append("</").append(serializedName.value()).append(">");
}
} else if (fieldValue instanceof Date) {
sb.append("<").append(serializedName.value()).append(">").append(BaseCmd.getDateString((Date) fieldValue)).
append("</").append(serializedName.value()).append(">");
} else {
String resultString = escapeSpecialXmlChars(fieldValue.toString());
if (!(obj instanceof ExceptionResponse)) {
resultString = encodeParam(resultString);
}
sb.append("<").append(serializedName.value()).append(">").append(resultString).append("</").append(serializedName.value()).append(">");
}
}
}
}
private static Method getGetMethod(Object o, String propName) {
Method method = null;
String methodName = getGetMethodName("get", propName);
try {
method = o.getClass().getMethod(methodName);
} catch (SecurityException e1) {
s_logger.error("Security exception in getting ResponseObject " + o.getClass().getName() + " get method for property: " + propName);
} catch (NoSuchMethodException e1) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("ResponseObject " + o.getClass().getName() + " does not have " + methodName + "() method for property: " + propName
+ ", will check is-prefixed method to see if it is boolean property");
}
}
if (method != null)
return method;
methodName = getGetMethodName("is", propName);
try {
method = o.getClass().getMethod(methodName);
} catch (SecurityException e1) {
s_logger.error("Security exception in getting ResponseObject " + o.getClass().getName() + " get method for property: " + propName);
} catch (NoSuchMethodException e1) {
s_logger.warn("ResponseObject " + o.getClass().getName() + " does not have " + methodName + "() method for property: " + propName);
}
return method;
}
private static String getGetMethodName(String prefix, String fieldName) {
StringBuffer sb = new StringBuffer(prefix);
if (fieldName.length() >= prefix.length() && fieldName.substring(0, prefix.length()).equals(prefix)) {
return fieldName;
} else {
sb.append(fieldName.substring(0, 1).toUpperCase());
sb.append(fieldName.substring(1));
}
return sb.toString();
}
private static String escapeSpecialXmlChars(String originalString) {
char[] origChars = originalString.toCharArray();
StringBuilder resultString = new StringBuilder();
for (char singleChar : origChars) {
if (singleChar == '"') {
resultString.append(""");
} else if (singleChar == '\'') {
resultString.append("'");
} else if (singleChar == '<') {
resultString.append("<");
} else if (singleChar == '>') {
resultString.append(">");
} else if (singleChar == '&') {
resultString.append("&");
} else {
resultString.append(singleChar);
}
}
return resultString.toString();
}
private static String encodeParam(String value) {
if (!ApiServer.encodeApiResponse) {
return value;
}
try {
return new URLEncoder().encode(value).replaceAll("\\+", "%20");
} catch (Exception e) {
s_logger.warn("Unable to encode: " + value, e);
}
return value;
}
}