001
014
015 package com.liferay.portal.jsonwebservice;
016
017 import com.liferay.portal.kernel.json.JSONFactoryUtil;
018 import com.liferay.portal.kernel.json.JSONSerializable;
019 import com.liferay.portal.kernel.json.JSONSerializer;
020 import com.liferay.portal.kernel.util.GetterUtil;
021
022 import java.lang.reflect.InvocationTargetException;
023
024 import java.util.HashMap;
025 import java.util.Map;
026
027
030 public class JSONRPCResponse implements JSONSerializable {
031
032 public JSONRPCResponse(
033 JSONRPCRequest jsonRpcRequest, Object result, Exception exception) {
034
035 _id = jsonRpcRequest.getId();
036
037 _jsonrpc = GetterUtil.getString(jsonRpcRequest.getJsonrpc());
038
039 if (!_jsonrpc.equals("2.0")) {
040 _error = new Error(-32700, "Invalid JSON RPC version " + _jsonrpc);
041 }
042 else if (exception == null) {
043 _result = result;
044 }
045 else {
046 int code = -32603;
047
048 String message = null;
049
050 if (exception instanceof InvocationTargetException) {
051 code = -32602;
052
053 Throwable cause = exception.getCause();
054
055 message = cause.toString();
056 }
057 else {
058 message = exception.toString();
059 }
060
061 if (message == null) {
062 message = exception.toString();
063 }
064
065 _error = new Error(code, message);
066 }
067 }
068
069 public String toJSONString() {
070 Map<String, Object> response = new HashMap<String, Object>();
071
072 if (_error != null) {
073 response.put("error", _error);
074 }
075
076 if (_id != null) {
077 response.put("id", _id);
078 }
079
080 if (_jsonrpc != null) {
081 response.put("jsonrpc", "2.0");
082 }
083
084 if (_result != null) {
085 response.put("result", _result);
086 }
087
088 JSONSerializer jsonSerializer = JSONFactoryUtil.createJSONSerializer();
089
090 jsonSerializer.exclude("*.class");
091 jsonSerializer.include("error", "result");
092
093 return jsonSerializer.serialize(response);
094 }
095
096 public class Error {
097
098 public Error(int code, String message) {
099 _code = code;
100 _message = message;
101 }
102
103 public int getCode() {
104 return _code;
105 }
106
107 public String getMessage() {
108 return _message;
109 }
110
111 private int _code;
112 private String _message;
113
114 }
115
116 private Error _error;
117 private Integer _id;
118 private String _jsonrpc;
119 private Object _result;
120
121 }