Search in sources :

Example 1 with ExceptionResponse

use of org.apache.cloudstack.api.response.ExceptionResponse in project cloudstack by apache.

the class ApiServer method getSerializedApiError.

@Override
public String getSerializedApiError(final ServerApiException ex, final Map<String, Object[]> apiCommandParams, final String responseType) {
    String responseName = null;
    Class<?> cmdClass = null;
    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(ex.getDescription());
        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;
}
Also used : ExceptionResponse(org.apache.cloudstack.api.response.ExceptionResponse) ExceptionProxyObject(com.cloud.utils.exception.ExceptionProxyObject) ResponseObject(org.apache.cloudstack.api.ResponseObject) ExceptionProxyObject(com.cloud.utils.exception.ExceptionProxyObject) AccountLimitException(com.cloud.exception.AccountLimitException) HttpException(org.apache.http.HttpException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InterruptedIOException(java.io.InterruptedIOException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) IOException(java.io.IOException) RequestLimitException(com.cloud.exception.RequestLimitException) URISyntaxException(java.net.URISyntaxException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ParseException(java.text.ParseException) EventBusException(org.apache.cloudstack.framework.events.EventBusException) UnavailableCommandException(com.cloud.exception.UnavailableCommandException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) OriginDeniedException(com.cloud.exception.OriginDeniedException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ConnectionClosedException(org.apache.http.ConnectionClosedException)

Example 2 with ExceptionResponse

use of org.apache.cloudstack.api.response.ExceptionResponse in project cloudstack by apache.

the class ApiResponseSerializer method toJSONSerializedString.

public static String toJSONSerializedString(ResponseObject result, StringBuilder log) {
    if (result != null && log != null) {
        Gson responseBuilder = ApiResponseGsonHelper.getBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create();
        Gson logBuilder = ApiResponseGsonHelper.getLogBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create();
        StringBuilder sb = new StringBuilder();
        sb.append("{\"").append(result.getResponseName()).append("\":");
        log.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);
                log.append("{\"").append(ApiConstants.COUNT).append("\":").append(count);
            }
            if ((responses != null) && !responses.isEmpty()) {
                String jsonStr = responseBuilder.toJson(responses.get(0));
                jsonStr = unescape(jsonStr);
                String logStr = logBuilder.toJson(responses.get(0));
                logStr = unescape(logStr);
                if (nonZeroCount) {
                    sb.append(",\"").append(responses.get(0).getObjectName()).append("\":[").append(jsonStr);
                    log.append(",\"").append(responses.get(0).getObjectName()).append("\":[").append(logStr);
                }
                for (int i = 1; i < ((ListResponse) result).getResponses().size(); i++) {
                    jsonStr = responseBuilder.toJson(responses.get(i));
                    jsonStr = unescape(jsonStr);
                    logStr = logBuilder.toJson(responses.get(i));
                    logStr = unescape(logStr);
                    sb.append(",").append(jsonStr);
                    log.append(",").append(logStr);
                }
                sb.append("]}");
                log.append("]}");
            } else {
                if (!nonZeroCount) {
                    sb.append("{");
                    log.append("{");
                }
                sb.append("}");
                log.append("}");
            }
        } else if (result instanceof SuccessResponse || result instanceof ExceptionResponse) {
            final String jsonErrorText = unescape(responseBuilder.toJson(result));
            sb.append(jsonErrorText);
            log.append(jsonErrorText);
        } else {
            String jsonStr = responseBuilder.toJson(result);
            if (jsonStr != null && !jsonStr.isEmpty()) {
                jsonStr = unescape(jsonStr);
                if (result instanceof AsyncJobResponse || result instanceof CreateCmdResponse || result instanceof AuthenticationCmdResponse) {
                    sb.append(jsonStr);
                } else {
                    sb.append("{\"").append(result.getObjectName()).append("\":").append(jsonStr).append("}");
                }
            } else {
                sb.append("{}");
            }
            String logStr = logBuilder.toJson(result);
            if (logStr != null && !logStr.isEmpty()) {
                logStr = unescape(logStr);
                if (result instanceof AsyncJobResponse || result instanceof CreateCmdResponse || result instanceof AuthenticationCmdResponse) {
                    log.append(logStr);
                } else {
                    log.append("{\"").append(result.getObjectName()).append("\":").append(logStr).append("}");
                }
            } else {
                log.append("{}");
            }
        }
        sb.append("}");
        log.append("}");
        return sb.toString();
    }
    return null;
}
Also used : SuccessResponse(org.apache.cloudstack.api.response.SuccessResponse) ExceptionResponse(org.apache.cloudstack.api.response.ExceptionResponse) ListResponse(org.apache.cloudstack.api.response.ListResponse) AsyncJobResponse(org.apache.cloudstack.api.response.AsyncJobResponse) Gson(com.google.gson.Gson) CreateCmdResponse(org.apache.cloudstack.api.response.CreateCmdResponse) AuthenticationCmdResponse(org.apache.cloudstack.api.response.AuthenticationCmdResponse)

Example 3 with ExceptionResponse

use of org.apache.cloudstack.api.response.ExceptionResponse in project cloudstack by apache.

the class ApiServer method getSerializedApiError.

@Override
public String getSerializedApiError(final int errorCode, final String errorText, final Map<String, Object[]> apiCommandParams, final String responseType) {
    String responseName = null;
    Class<?> cmdClass = null;
    String responseText = null;
    try {
        if (apiCommandParams == null || apiCommandParams.isEmpty()) {
            responseName = "errorresponse";
        } else {
            final Object cmdObj = apiCommandParams.get(ApiConstants.COMMAND);
            // cmd name can be null when "command" parameter is missing in 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(errorCode);
        apiResponse.setErrorText(errorText);
        apiResponse.setResponseName(responseName);
        SerializationContext.current().setUuidTranslation(true);
        responseText = ApiResponseSerializer.toSerializedString(apiResponse, responseType);
    } catch (final Exception e) {
        s_logger.error("Exception responding to http request", e);
    }
    return responseText;
}
Also used : ExceptionResponse(org.apache.cloudstack.api.response.ExceptionResponse) ExceptionProxyObject(com.cloud.utils.exception.ExceptionProxyObject) ResponseObject(org.apache.cloudstack.api.ResponseObject) AccountLimitException(com.cloud.exception.AccountLimitException) HttpException(org.apache.http.HttpException) InsufficientCapacityException(com.cloud.exception.InsufficientCapacityException) ServerApiException(org.apache.cloudstack.api.ServerApiException) ResourceUnavailableException(com.cloud.exception.ResourceUnavailableException) InterruptedIOException(java.io.InterruptedIOException) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) IOException(java.io.IOException) RequestLimitException(com.cloud.exception.RequestLimitException) URISyntaxException(java.net.URISyntaxException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) ResourceAllocationException(com.cloud.exception.ResourceAllocationException) ParseException(java.text.ParseException) EventBusException(org.apache.cloudstack.framework.events.EventBusException) UnavailableCommandException(com.cloud.exception.UnavailableCommandException) ConfigurationException(javax.naming.ConfigurationException) PermissionDeniedException(com.cloud.exception.PermissionDeniedException) OriginDeniedException(com.cloud.exception.OriginDeniedException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ConnectionClosedException(org.apache.http.ConnectionClosedException)

Example 4 with ExceptionResponse

use of org.apache.cloudstack.api.response.ExceptionResponse in project cloudstack by apache.

the class ApiAsyncJobDispatcher method runJob.

@Override
public void runJob(final AsyncJob job) {
    BaseAsyncCmd cmdObj = null;
    try {
        Class<?> cmdClass = Class.forName(job.getCmd());
        cmdObj = (BaseAsyncCmd) cmdClass.newInstance();
        cmdObj = ComponentContext.inject(cmdObj);
        cmdObj.configure();
        cmdObj.setJob(job);
        Type mapType = new TypeToken<Map<String, String>>() {
        }.getType();
        Gson gson = ApiGsonHelper.getBuilder().create();
        Map<String, String> params = gson.fromJson(job.getCmdInfo(), mapType);
        // whenever we deserialize, the UserContext needs to be updated
        String userIdStr = params.get("ctxUserId");
        String acctIdStr = params.get("ctxAccountId");
        String contextDetails = params.get("ctxDetails");
        Long userId = null;
        Account accountObject = null;
        if (cmdObj instanceof BaseAsyncCreateCmd) {
            BaseAsyncCreateCmd create = (BaseAsyncCreateCmd) cmdObj;
            create.setEntityId(Long.parseLong(params.get("id")));
            create.setEntityUuid(params.get("uuid"));
        }
        User user = null;
        if (userIdStr != null) {
            userId = Long.parseLong(userIdStr);
            user = _entityMgr.findById(User.class, userId);
        }
        if (acctIdStr != null) {
            accountObject = _entityMgr.findById(Account.class, Long.parseLong(acctIdStr));
        }
        CallContext ctx = CallContext.register(user, accountObject);
        if (contextDetails != null) {
            Type objectMapType = new TypeToken<Map<Object, Object>>() {
            }.getType();
            ctx.putContextParameters((Map<Object, Object>) gson.fromJson(contextDetails, objectMapType));
        }
        try {
            // dispatch could ultimately queue the job
            _dispatcher.dispatch(cmdObj, params, true);
            // serialize this to the async job table
            _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.SUCCEEDED, 0, ApiSerializerHelper.toSerializedString(cmdObj.getResponseObject()));
        } catch (InvalidParameterValueException ipve) {
            throw new ServerApiException(ApiErrorCode.PARAM_ERROR, ipve.getMessage());
        } finally {
            CallContext.unregister();
        }
    } catch (Throwable e) {
        String errorMsg = null;
        int errorCode = ApiErrorCode.INTERNAL_ERROR.getHttpCode();
        if (!(e instanceof ServerApiException)) {
            s_logger.error("Unexpected exception while executing " + job.getCmd(), e);
            errorMsg = e.getMessage();
        } else {
            ServerApiException sApiEx = (ServerApiException) e;
            errorMsg = sApiEx.getDescription();
            errorCode = sApiEx.getErrorCode().getHttpCode();
        }
        ExceptionResponse response = new ExceptionResponse();
        response.setErrorCode(errorCode);
        response.setErrorText(errorMsg);
        response.setResponseName((cmdObj == null) ? "unknowncommandresponse" : cmdObj.getCommandName());
        // FIXME:  setting resultCode to ApiErrorCode.INTERNAL_ERROR is not right, usually executors have their exception handling
        // and we need to preserve that as much as possible here
        _asyncJobMgr.completeAsyncJob(job.getId(), JobInfo.Status.FAILED, ApiErrorCode.INTERNAL_ERROR.getHttpCode(), ApiSerializerHelper.toSerializedString(response));
    }
}
Also used : Account(com.cloud.user.Account) User(com.cloud.user.User) ExceptionResponse(org.apache.cloudstack.api.response.ExceptionResponse) BaseAsyncCreateCmd(org.apache.cloudstack.api.BaseAsyncCreateCmd) Gson(com.google.gson.Gson) CallContext(org.apache.cloudstack.context.CallContext) BaseAsyncCmd(org.apache.cloudstack.api.BaseAsyncCmd) Type(java.lang.reflect.Type) ServerApiException(org.apache.cloudstack.api.ServerApiException) InvalidParameterValueException(com.cloud.exception.InvalidParameterValueException) Map(java.util.Map)

Example 5 with ExceptionResponse

use of org.apache.cloudstack.api.response.ExceptionResponse in project cloudstack by apache.

the class ApiResponseSerializer method serializeResponseObjFieldsXML.

private static void serializeResponseObjFieldsXML(StringBuilder sb, StringBuilder log, ResponseObject obj) {
    boolean isAsync = false;
    if (obj instanceof AsyncJobResponse)
        isAsync = true;
    Field[] fields = getFlattenFields(obj.getClass());
    for (Field field : fields) {
        if ((field.getModifiers() & Modifier.TRANSIENT) != 0) {
            // skip transient fields
            continue;
        }
        SerializedName serializedName = field.getAnnotation(SerializedName.class);
        if (serializedName == null) {
            // skip fields w/o serialized name
            continue;
        }
        boolean logField = true;
        Param param = field.getAnnotation(Param.class);
        if (param != null) {
            RoleType[] allowedRoles = param.authorized();
            if (allowedRoles.length > 0) {
                boolean permittedParameter = false;
                Account caller = CallContext.current().getCallingAccount();
                for (RoleType allowedRole : allowedRoles) {
                    if (allowedRole.getAccountType() == 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);
        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>");
                    log.append("<jobresult>");
                }
                serializeResponseObjXML(sb, log, subObj);
                if (isAsync) {
                    sb.append("</jobresult>");
                    log.append("</jobresult>");
                }
            } else if (fieldValue instanceof Collection<?>) {
                Collection<?> subResponseList = (Collection<?>) 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, log, subObj);
                    } else if (value instanceof ExceptionProxyObject) {
                        // Only exception reponses carry a list of
                        // ExceptionProxyObject objects.
                        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.
                        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(">");
                }
            }
        }
    }
}
Also used : Account(com.cloud.user.Account) ExceptionResponse(org.apache.cloudstack.api.response.ExceptionResponse) RoleType(org.apache.cloudstack.acl.RoleType) AsyncJobResponse(org.apache.cloudstack.api.response.AsyncJobResponse) SerializedName(com.google.gson.annotations.SerializedName) Date(java.util.Date) Field(java.lang.reflect.Field) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) Param(com.cloud.serializer.Param) ResponseObject(org.apache.cloudstack.api.ResponseObject) Collection(java.util.Collection) ExceptionProxyObject(com.cloud.utils.exception.ExceptionProxyObject) ResponseObject(org.apache.cloudstack.api.ResponseObject) ExceptionProxyObject(com.cloud.utils.exception.ExceptionProxyObject)

Aggregations

ExceptionResponse (org.apache.cloudstack.api.response.ExceptionResponse)5 InvalidParameterValueException (com.cloud.exception.InvalidParameterValueException)3 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)3 ExceptionProxyObject (com.cloud.utils.exception.ExceptionProxyObject)3 ResponseObject (org.apache.cloudstack.api.ResponseObject)3 ServerApiException (org.apache.cloudstack.api.ServerApiException)3 AccountLimitException (com.cloud.exception.AccountLimitException)2 CloudAuthenticationException (com.cloud.exception.CloudAuthenticationException)2 InsufficientCapacityException (com.cloud.exception.InsufficientCapacityException)2 OriginDeniedException (com.cloud.exception.OriginDeniedException)2 PermissionDeniedException (com.cloud.exception.PermissionDeniedException)2 RequestLimitException (com.cloud.exception.RequestLimitException)2 ResourceAllocationException (com.cloud.exception.ResourceAllocationException)2 ResourceUnavailableException (com.cloud.exception.ResourceUnavailableException)2 UnavailableCommandException (com.cloud.exception.UnavailableCommandException)2 Account (com.cloud.user.Account)2 Gson (com.google.gson.Gson)2 IOException (java.io.IOException)2 InterruptedIOException (java.io.InterruptedIOException)2 URISyntaxException (java.net.URISyntaxException)2