Search in sources :

Example 11 with RestAPIException

use of com.haulmont.restapi.exception.RestAPIException in project cuba by cuba-platform.

the class EntitiesMetadataControllerManager method getView.

public String getView(String entityName, String viewName) {
    MetaClass metaClass = restControllersUtils.getMetaClass(entityName);
    View view = viewRepository.findView(metaClass, viewName);
    if (view == null) {
        throw new RestAPIException("View not found", String.format("View %s for metaClass %s not found", viewName, entityName), HttpStatus.NOT_FOUND);
    }
    return viewSerializationAPI.toJson(view);
}
Also used : MetaClass(com.haulmont.chile.core.model.MetaClass) RestAPIException(com.haulmont.restapi.exception.RestAPIException) View(com.haulmont.cuba.core.global.View)

Example 12 with RestAPIException

use of com.haulmont.restapi.exception.RestAPIException in project cuba by cuba-platform.

the class EnumsControllerManager method getEnumInfo.

public EnumInfo getEnumInfo(String enumClassName) {
    Class<?> enumClass;
    try {
        enumClass = Class.forName(enumClassName);
    } catch (ClassNotFoundException e) {
        throw new RestAPIException("Enum not found", "Enum with class name " + enumClassName + " not found", HttpStatus.NOT_FOUND);
    }
    List<EnumValueInfo> enumValues = new ArrayList<>();
    Object[] enumConstants = enumClass.getEnumConstants();
    for (Object enumConstant : enumConstants) {
        Enum enumValue = (Enum) enumConstant;
        EnumValueInfo enumValueInfo = new EnumValueInfo(enumValue.name(), ((EnumClass) enumValue).getId(), messages.getMessage(enumValue));
        enumValues.add(enumValueInfo);
    }
    return new EnumInfo(enumClass.getName(), enumValues);
}
Also used : EnumValueInfo(com.haulmont.restapi.data.EnumValueInfo) EnumInfo(com.haulmont.restapi.data.EnumInfo) ArrayList(java.util.ArrayList) RestAPIException(com.haulmont.restapi.exception.RestAPIException)

Example 13 with RestAPIException

use of com.haulmont.restapi.exception.RestAPIException in project cuba by cuba-platform.

the class QueriesControllerManager method _getCount.

protected String _getCount(String entityName, String queryName, String version, Map<String, String> params) {
    entityName = restControllerUtils.transformEntityNameIfRequired(entityName, version, JsonTransformationDirection.FROM_VERSION);
    LoadContext<Entity> ctx;
    try {
        ctx = createQueryLoadContext(entityName, queryName, null, null, params);
    } catch (ClassNotFoundException | ParseException e) {
        throw new RestAPIException("Error on executing the query", e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
    long count = dataManager.getCount(ctx);
    return String.valueOf(count);
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) RestAPIException(com.haulmont.restapi.exception.RestAPIException) ParseException(java.text.ParseException)

Example 14 with RestAPIException

use of com.haulmont.restapi.exception.RestAPIException in project cuba by cuba-platform.

the class QueriesControllerManager method createQueryLoadContext.

protected LoadContext<Entity> createQueryLoadContext(String entityName, String queryName, @Nullable Integer limit, @Nullable Integer offset, Map<String, String> params) throws ClassNotFoundException, ParseException {
    MetaClass metaClass = restControllerUtils.getMetaClass(entityName);
    checkCanReadEntity(metaClass);
    RestQueriesConfiguration.QueryInfo queryInfo = restQueriesConfiguration.getQuery(entityName, queryName);
    if (queryInfo == null) {
        throw new RestAPIException("Query not found", String.format("Query with name %s for entity %s not found", queryName, entityName), HttpStatus.NOT_FOUND);
    }
    LoadContext<Entity> ctx = new LoadContext<>(metaClass);
    LoadContext.Query query = new LoadContext.Query(queryInfo.getJpql());
    if (limit != null) {
        query.setMaxResults(limit);
    } else {
        query.setMaxResults(persistenceManagerClient.getMaxFetchUI(entityName));
    }
    if (offset != null) {
        query.setFirstResult(offset);
    }
    for (RestQueriesConfiguration.QueryParamInfo paramInfo : queryInfo.getParams()) {
        String paramName = paramInfo.getName();
        String requestParamValue = params.get(paramName);
        if (requestParamValue == null) {
            throw new RestAPIException("Query parameter not found", String.format("Query parameter %s not found", paramName), HttpStatus.BAD_REQUEST);
        }
        Class<?> clazz = ClassUtils.forName(paramInfo.getType(), getClass().getClassLoader());
        Object objectParamValue = toObject(clazz, requestParamValue);
        query.setParameter(paramName, objectParamValue);
    }
    if (queryInfo.getJpql().contains(":session$userId")) {
        query.setParameter("session$userId", userSessionSource.currentOrSubstitutedUserId());
    }
    if (queryInfo.getJpql().contains(":session$userLogin")) {
        query.setParameter("session$userLogin", userSessionSource.getUserSession().getCurrentOrSubstitutedUser().getLoginLowerCase());
    }
    query.setCacheable(queryInfo.isCacheable());
    ctx.setQuery(query);
    ctx.setView(queryInfo.getViewName());
    return ctx;
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) MetaClass(com.haulmont.chile.core.model.MetaClass) RestQueriesConfiguration(com.haulmont.restapi.config.RestQueriesConfiguration) RestAPIException(com.haulmont.restapi.exception.RestAPIException)

Example 15 with RestAPIException

use of com.haulmont.restapi.exception.RestAPIException in project cuba by cuba-platform.

the class ServicesControllerManager method _invokeServiceMethod.

@Nullable
protected ServiceCallResult _invokeServiceMethod(String serviceName, String methodName, List<String> paramNames, List<String> paramValuesStr, String modelVersion) {
    Object service = AppBeans.get(serviceName);
    RestServicesConfiguration.RestMethodInfo restMethodInfo = restServicesConfiguration.getRestMethodInfo(serviceName, methodName, paramNames);
    if (restMethodInfo == null) {
        throw new RestAPIException("Service method not found", serviceName + "." + methodName + "(" + paramNames.stream().collect(Collectors.joining(",")) + ")", HttpStatus.NOT_FOUND);
    }
    Method serviceMethod = restMethodInfo.getMethod();
    List<Object> paramValues = new ArrayList<>();
    Type[] types = restMethodInfo.getMethod().getGenericParameterTypes();
    for (int i = 0; i < types.length; i++) {
        int idx = i;
        try {
            idx = paramNames.indexOf(restMethodInfo.getParams().get(i).getName());
            paramValues.add(restParseUtils.toObject(types[i], paramValuesStr.get(idx), modelVersion));
        } catch (Exception e) {
            log.error("Error on parsing service param value", e);
            throw new RestAPIException("Invalid parameter value", "Invalid parameter value for " + paramNames.get(idx), HttpStatus.BAD_REQUEST);
        }
    }
    Object methodResult;
    try {
        methodResult = serviceMethod.invoke(service, paramValues.toArray());
    } catch (InvocationTargetException | IllegalAccessException ex) {
        if (ex.getCause() instanceof ValidationException) {
            throw (ValidationException) ex.getCause();
        } else {
            log.error("Error on service method invoke", ex.getCause());
            throw new RestAPIException("Error on service method invoke", "", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    if (methodResult == null) {
        return null;
    }
    Class<?> methodReturnType = serviceMethod.getReturnType();
    if (Entity.class.isAssignableFrom(methodReturnType)) {
        Entity entity = (Entity) methodResult;
        restControllerUtils.applyAttributesSecurity(entity);
        String entityJson = entitySerializationAPI.toJson(entity, null, EntitySerializationOption.SERIALIZE_INSTANCE_NAME);
        entityJson = restControllerUtils.transformJsonIfRequired(entity.getMetaClass().getName(), modelVersion, JsonTransformationDirection.TO_VERSION, entityJson);
        return new ServiceCallResult(entityJson, true);
    } else if (Collection.class.isAssignableFrom(methodReturnType)) {
        Class returnTypeArgument = getMethodReturnTypeArgument(serviceMethod);
        if ((returnTypeArgument != null && Entity.class.isAssignableFrom(returnTypeArgument)) || isEntitiesCollection((Collection) methodResult)) {
            Collection<? extends Entity> entities = (Collection<? extends Entity>) methodResult;
            entities.forEach(entity -> restControllerUtils.applyAttributesSecurity(entity));
            String entitiesJson = entitySerializationAPI.toJson(entities, null, EntitySerializationOption.SERIALIZE_INSTANCE_NAME);
            if (returnTypeArgument != null) {
                MetaClass metaClass = metadata.getClass(returnTypeArgument);
                if (metaClass != null) {
                    entitiesJson = restControllerUtils.transformJsonIfRequired(metaClass.getName(), modelVersion, JsonTransformationDirection.TO_VERSION, entitiesJson);
                } else {
                    log.error("MetaClass for service collection parameter type {} not found", returnTypeArgument);
                }
            }
            return new ServiceCallResult(entitiesJson, true);
        } else {
            return new ServiceCallResult(restParseUtils.serialize(methodResult), true);
        }
    } else {
        Datatype<?> datatype = Datatypes.get(methodReturnType);
        if (datatype != null) {
            return new ServiceCallResult(datatype.format(methodResult), false);
        } else {
            return new ServiceCallResult(restParseUtils.serialize(methodResult), true);
        }
    }
}
Also used : JsonObject(com.google.gson.JsonObject) java.util(java.util) LoggerFactory(org.slf4j.LoggerFactory) JsonParser(com.google.gson.JsonParser) AppBeans(com.haulmont.cuba.core.global.AppBeans) MetaClass(com.haulmont.chile.core.model.MetaClass) Metadata(com.haulmont.cuba.core.global.Metadata) JsonTransformationDirection(com.haulmont.restapi.transform.JsonTransformationDirection) JsonElement(com.google.gson.JsonElement) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) EntitySerializationOption(com.haulmont.cuba.core.app.serialization.EntitySerializationOption) Datatype(com.haulmont.chile.core.datatypes.Datatype) RestControllerUtils(com.haulmont.restapi.common.RestControllerUtils) ParseException(java.text.ParseException) Method(java.lang.reflect.Method) Nullable(javax.annotation.Nullable) Logger(org.slf4j.Logger) RestAPIException(com.haulmont.restapi.exception.RestAPIException) Datatypes(com.haulmont.chile.core.datatypes.Datatypes) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) EntitySerializationAPI(com.haulmont.cuba.core.app.serialization.EntitySerializationAPI) HttpStatus(org.springframework.http.HttpStatus) Component(org.springframework.stereotype.Component) ParameterizedType(java.lang.reflect.ParameterizedType) RestParseUtils(com.haulmont.restapi.common.RestParseUtils) ValidationException(javax.validation.ValidationException) Type(java.lang.reflect.Type) RestServicesConfiguration(com.haulmont.restapi.config.RestServicesConfiguration) Entity(com.haulmont.cuba.core.entity.Entity) Entity(com.haulmont.cuba.core.entity.Entity) ValidationException(javax.validation.ValidationException) Method(java.lang.reflect.Method) ParseException(java.text.ParseException) RestAPIException(com.haulmont.restapi.exception.RestAPIException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ValidationException(javax.validation.ValidationException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Datatype(com.haulmont.chile.core.datatypes.Datatype) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) MetaClass(com.haulmont.chile.core.model.MetaClass) RestAPIException(com.haulmont.restapi.exception.RestAPIException) JsonObject(com.google.gson.JsonObject) MetaClass(com.haulmont.chile.core.model.MetaClass) RestServicesConfiguration(com.haulmont.restapi.config.RestServicesConfiguration) Nullable(javax.annotation.Nullable)

Aggregations

RestAPIException (com.haulmont.restapi.exception.RestAPIException)19 MetaClass (com.haulmont.chile.core.model.MetaClass)8 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 JsonObject (com.google.gson.JsonObject)4 Entity (com.haulmont.cuba.core.entity.Entity)4 RestFilterParseException (com.haulmont.restapi.service.filter.RestFilterParseException)4 IOException (java.io.IOException)4 EntityImportException (com.haulmont.cuba.core.app.importexport.EntityImportException)3 FileDescriptor (com.haulmont.cuba.core.entity.FileDescriptor)3 ParseException (java.text.ParseException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Datatype (com.haulmont.chile.core.datatypes.Datatype)2 EntityImportView (com.haulmont.cuba.core.app.importexport.EntityImportView)2 EntitySerializationOption (com.haulmont.cuba.core.app.serialization.EntitySerializationOption)2 Swagger (io.swagger.models.Swagger)2 InputStream (java.io.InputStream)2 Method (java.lang.reflect.Method)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)1