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 @Override
070 public String toJSONString() {
071 Map<String, Object> response = new HashMap<String, Object>();
072
073 if (_error != null) {
074 response.put("error", _error);
075 }
076
077 if (_id != null) {
078 response.put("id", _id);
079 }
080
081 if (_jsonrpc != null) {
082 response.put("jsonrpc", "2.0");
083 }
084
085 if (_result != null) {
086 response.put("result", _result);
087 }
088
089 JSONSerializer jsonSerializer = JSONFactoryUtil.createJSONSerializer();
090
091 jsonSerializer.exclude("*.class");
092 jsonSerializer.include("error", "result");
093
094 return jsonSerializer.serialize(response);
095 }
096
097 public class Error {
098
099 public Error(int code, String message) {
100 _code = code;
101 _message = message;
102 }
103
104 public int getCode() {
105 return _code;
106 }
107
108 public String getMessage() {
109 return _message;
110 }
111
112 private int _code;
113 private String _message;
114
115 }
116
117 private Error _error;
118 private Integer _id;
119 private String _jsonrpc;
120 private Object _result;
121
122 }