use of com.cloud.legacymodel.exceptions.ExceptionProxyObject in project cosmic by MissionCriticalCloud.
the class ApiServer method getSerializedApiError.
@Override
public String getSerializedApiError(final ServerApiException ex, final Map<String, Object[]> apiCommandParams, final String responseType) {
String responseName = null;
final Class<?> cmdClass;
String responseText = null;
if (ex == null) {
// this call should not be invoked with null exception
return getSerializedApiError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Some internal error happened", apiCommandParams, responseType);
}
try {
if (ex.getErrorCode() == ApiErrorCode.UNSUPPORTED_ACTION_ERROR || apiCommandParams == null || apiCommandParams.isEmpty()) {
responseName = "errorresponse";
} else {
final Object cmdObj = apiCommandParams.get(ApiConstants.COMMAND);
// the request
if (cmdObj != null) {
final String cmdName = ((String[]) cmdObj)[0];
cmdClass = getCmdClass(cmdName);
if (cmdClass != null) {
responseName = ((BaseCmd) cmdClass.newInstance()).getCommandName();
} else {
responseName = "errorresponse";
}
}
}
final ExceptionResponse apiResponse = new ExceptionResponse();
apiResponse.setErrorCode(ex.getErrorCode().getHttpCode());
apiResponse.setErrorText(ExceptionUtils.getRootCauseMessage(ex));
apiResponse.setResponseName(responseName);
final ArrayList<ExceptionProxyObject> idList = ex.getIdProxyList();
if (idList != null) {
for (int i = 0; i < idList.size(); i++) {
apiResponse.addProxyObject(idList.get(i));
}
}
// Also copy over the cserror code and the function/layer in which
// it was thrown.
apiResponse.setCSErrorCode(ex.getCSErrorCode());
SerializationContext.current().setUuidTranslation(true);
responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType);
} catch (final Exception e) {
s_logger.error("Exception responding to http request", e);
}
return responseText;
}
use of com.cloud.legacymodel.exceptions.ExceptionProxyObject in project cosmic by MissionCriticalCloud.
the class ApiResponseSerializer method serializeResponseObjFieldsXML.
private static void serializeResponseObjFieldsXML(final StringBuilder sb, final StringBuilder log, final ResponseObject obj) {
boolean isAsync = false;
if (obj instanceof AsyncJobResponse) {
isAsync = true;
}
final Field[] fields = getFlattenFields(obj.getClass());
for (final Field field : fields) {
if ((field.getModifiers() & Modifier.TRANSIENT) != 0) {
// skip transient fields
continue;
}
final SerializedName serializedName = field.getAnnotation(SerializedName.class);
if (serializedName == null) {
// skip fields w/o serialized name
continue;
}
boolean logField = true;
final Param param = field.getAnnotation(Param.class);
if (param != null) {
final RoleType[] allowedRoles = param.authorized();
if (allowedRoles.length > 0) {
boolean permittedParameter = false;
final Account caller = CallContext.current().getCallingAccount();
for (final RoleType allowedRole : allowedRoles) {
if (allowedRole.getValue() == caller.getType()) {
permittedParameter = true;
break;
}
}
if (!permittedParameter) {
s_logger.trace("Ignoring parameter " + param.name() + " as the caller is not authorized to see it");
continue;
}
}
if (param.isSensitive()) {
logField = false;
}
}
field.setAccessible(true);
final Object fieldValue;
try {
fieldValue = field.get(obj);
} catch (final IllegalArgumentException e) {
throw new CloudRuntimeException("how illegal is it?", e);
} catch (final IllegalAccessException e) {
throw new CloudRuntimeException("come on...we set accessible already", e);
}
if (fieldValue != null) {
if (fieldValue instanceof ResponseObject) {
final ResponseObject subObj = (ResponseObject) fieldValue;
if (isAsync) {
sb.append("<jobresult>");
log.append("<jobresult>");
}
serializeResponseObjXML(sb, log, subObj);
if (isAsync) {
sb.append("</jobresult>");
log.append("</jobresult>");
}
} else if (fieldValue instanceof Collection<?>) {
final Collection<?> subResponseList = (Collection<?>) fieldValue;
boolean usedUuidList = false;
for (final Object value : subResponseList) {
if (value instanceof ResponseObject) {
final ResponseObject subObj = (ResponseObject) value;
if (serializedName != null) {
subObj.setObjectName(serializedName.value());
}
serializeResponseObjXML(sb, log, subObj);
} else if (value instanceof ExceptionProxyObject) {
// Only exception reponses carry a list of
// ExceptionProxyObject objects.
final ExceptionProxyObject idProxy = (ExceptionProxyObject) value;
// encountered, put in a uuidList tag.
if (!usedUuidList) {
sb.append("<" + serializedName.value() + ">");
log.append("<" + serializedName.value() + ">");
usedUuidList = true;
}
sb.append("<" + "uuid" + ">" + idProxy.getUuid() + "</" + "uuid" + ">");
log.append("<" + "uuid" + ">" + idProxy.getUuid() + "</" + "uuid" + ">");
// Append the new descriptive property also.
final String idFieldName = idProxy.getDescription();
if (idFieldName != null) {
sb.append("<" + "uuidProperty" + ">" + idFieldName + "</" + "uuidProperty" + ">");
log.append("<" + "uuidProperty" + ">" + idFieldName + "</" + "uuidProperty" + ">");
}
} else if (value instanceof String) {
sb.append("<").append(serializedName.value()).append(">").append(value).append("</").append(serializedName.value()).append(">");
if (logField) {
log.append("<").append(serializedName.value()).append(">").append(value).append("</").append(serializedName.value()).append(">");
}
}
}
if (usedUuidList) {
// close the uuidList.
sb.append("</").append(serializedName.value()).append(">");
log.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(">");
log.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(">");
if (logField) {
log.append("<").append(serializedName.value()).append(">").append(resultString).append("</").append(serializedName.value()).append(">");
}
}
}
}
}
use of com.cloud.legacymodel.exceptions.ExceptionProxyObject in project cosmic by MissionCriticalCloud.
the class ApiServer method handleRequest.
@Override
public String handleRequest(final Map params, final String responseType, final StringBuilder auditTrailSb) throws ServerApiException {
checkCharacterInkParams(params);
final String response;
String[] command = null;
try {
command = (String[]) params.get("command");
if (command == null) {
s_logger.error("invalid request, no command sent");
if (s_logger.isTraceEnabled()) {
s_logger.trace("dumping request parameters");
for (final Object key : params.keySet()) {
final String keyStr = (String) key;
final String[] value = (String[]) params.get(key);
s_logger.trace(" key: " + keyStr + ", value: " + ((value == null) ? "'null'" : value[0]));
}
}
throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, "Invalid request, no command sent");
} else {
// Don't allow Login/Logout APIs to go past this point
if (_authManager.getAPIAuthenticator(command[0]) != null) {
return null;
}
final Map<String, String> paramMap = new HashMap<>();
final Set keys = params.keySet();
final Iterator keysIter = keys.iterator();
while (keysIter.hasNext()) {
final String key = (String) keysIter.next();
if ("command".equalsIgnoreCase(key)) {
continue;
}
final String[] value = (String[]) params.get(key);
paramMap.put(key, value[0]);
}
final Class<?> cmdClass = getCmdClass(command[0]);
if (cmdClass != null) {
final APICommand annotation = cmdClass.getAnnotation(APICommand.class);
if (annotation == null) {
s_logger.error("No APICommand annotation found for class " + cmdClass.getCanonicalName());
throw new CloudRuntimeException("No APICommand annotation found for class " + cmdClass.getCanonicalName());
}
BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance();
cmdObj = ComponentContext.inject(cmdObj);
cmdObj.configure();
cmdObj.setFullUrlParams(paramMap);
cmdObj.setResponseType(responseType);
cmdObj.setHttpMethod(paramMap.get(ApiConstants.HTTPMETHOD).toString());
// This is where the command is either serialized, or directly dispatched
final StringBuilder log = new StringBuilder();
response = queueCommand(cmdObj, paramMap, log);
buildAuditTrail(auditTrailSb, command[0], log.toString());
} else {
final String errorString = "Unknown API command: " + command[0];
s_logger.warn(errorString);
auditTrailSb.append(" " + errorString);
throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, errorString);
}
}
} catch (final InvalidParameterValueException ex) {
s_logger.info(ex.getMessage());
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
} catch (final IllegalArgumentException ex) {
s_logger.info(ex.getMessage());
throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ex.getMessage(), ex);
} catch (final PermissionDeniedException ex) {
final ArrayList<ExceptionProxyObject> idList = ex.getIdProxyList();
if (idList != null) {
final StringBuffer buf = new StringBuffer();
for (final ExceptionProxyObject obj : idList) {
buf.append(obj.getDescription());
buf.append(":");
buf.append(obj.getUuid());
buf.append(" ");
}
s_logger.info("PermissionDenied: " + ex.getMessage() + " on objs: [" + buf.toString() + "]");
} else {
s_logger.info("PermissionDenied: " + ex.getMessage());
}
throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, ex.getMessage(), ex);
} catch (final AccountLimitException ex) {
s_logger.info(ex.getMessage());
throw new ServerApiException(ApiErrorCode.ACCOUNT_RESOURCE_LIMIT_ERROR, ex.getMessage(), ex);
} catch (final InsufficientCapacityException ex) {
s_logger.info(ex.getMessage());
String errorMsg = ex.getMessage();
if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
// hide internal details to non-admin user for security reason
errorMsg = BaseCmd.USER_ERROR_MESSAGE;
}
throw new ServerApiException(ApiErrorCode.INSUFFICIENT_CAPACITY_ERROR, errorMsg, ex);
} catch (final ResourceAllocationException ex) {
s_logger.info(ex.getMessage());
throw new ServerApiException(ApiErrorCode.RESOURCE_ALLOCATION_ERROR, ex.getMessage(), ex);
} catch (final ResourceUnavailableException ex) {
s_logger.info(ex.getMessage());
String errorMsg = ex.getMessage();
if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
// hide internal details to non-admin user for security reason
errorMsg = BaseCmd.USER_ERROR_MESSAGE;
}
throw new ServerApiException(ApiErrorCode.RESOURCE_UNAVAILABLE_ERROR, errorMsg, ex);
} catch (final ServerApiException ex) {
s_logger.info(ex.getDescription());
throw ex;
} catch (final Exception ex) {
s_logger.error("Unhandled exception executing api command: " + ((command == null) ? "null" : printCommand(command)), ex);
String errorMsg = ex.getMessage();
if (!_accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())) {
// hide internal details to non-admin user for security reason
errorMsg = BaseCmd.USER_ERROR_MESSAGE;
}
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg, ex);
}
return response;
}
Aggregations