* @return the jSON response
*/
public static JSONResponse invoke(final Object destination,
final JSONRequest request, final RequestParams requestParams,
final Authorizor auth) {
final JSONResponse resp = new JSONResponse(request.getId(), null);
try {
final CallTuple tuple = NamespaceUtil.get(destination,
request.getMethod());
final Object realDest = tuple.getDestination();
final AnnotatedMethod annotatedMethod = tuple.getMethod();
if (!isAvailable(annotatedMethod, realDest, requestParams, auth)) {
throw new JSONRPCException(
JSONRPCException.CODE.METHOD_NOT_FOUND,
"Method '"
+ request.getMethod()
+ "' not found. The method does not exist or you are not authorized.");
}
final MethodHandle methodHandle = annotatedMethod.getMethodHandle();
final Method method = annotatedMethod.getActualMethod();
Object result;
if (useMethodHandles) {
final Object[] params = castParams(realDest,
request.getParams(), annotatedMethod.getParams(),
requestParams);
result = methodHandle.invokeExact(params);
} else {
final Object[] params = castParams(request.getParams(),
annotatedMethod.getParams(), requestParams);
result = method.invoke(realDest, params);
}
if (result == null) {
result = JOM.createNullNode();
}
resp.setResult(result);
} catch (final JSONRPCException err) {
resp.setError(err);
// TODO: Can this be reduced to Exception? Which Errors do we want
// to catch?
} catch (final Throwable err) {
final Throwable cause = err.getCause();
if (cause instanceof JSONRPCException) {
resp.setError((JSONRPCException) cause);
} else {
if (err instanceof InvocationTargetException && cause != null) {
LOG.log(Level.WARNING,
"Exception raised, returning its cause as JSONRPCException. Request:"
+ request, cause);
final JSONRPCException jsonError = new JSONRPCException(
JSONRPCException.CODE.INTERNAL_ERROR,
getMessage(cause), cause);
jsonError.setData(cause);
resp.setError(jsonError);
} else {
LOG.log(Level.WARNING,
"Exception raised, returning it as JSONRPCException. Request:"
+ request, err);
final JSONRPCException jsonError = new JSONRPCException(
JSONRPCException.CODE.INTERNAL_ERROR,
getMessage(err), err);
jsonError.setData(err);
resp.setError(jsonError);
}
}
}
return resp;
}