Search in sources :

Example 6 with RestAPIException

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

the class EntitiesControllerManager method searchEntities.

public EntitiesSearchResult searchEntities(String entityName, String filterJson, @Nullable String viewName, @Nullable Integer limit, @Nullable Integer offset, @Nullable String sort, @Nullable Boolean returnNulls, @Nullable Boolean returnCount, @Nullable Boolean dynamicAttributes, @Nullable String modelVersion) {
    if (filterJson == null) {
        throw new RestAPIException("Cannot parse entities filter", "Entities filter cannot be null", HttpStatus.BAD_REQUEST);
    }
    entityName = restControllerUtils.transformEntityNameIfRequired(entityName, modelVersion, JsonTransformationDirection.FROM_VERSION);
    MetaClass metaClass = restControllerUtils.getMetaClass(entityName);
    checkCanReadEntity(metaClass);
    RestFilterParseResult filterParseResult;
    try {
        filterParseResult = restFilterParser.parse(filterJson, metaClass);
    } catch (RestFilterParseException e) {
        throw new RestAPIException("Cannot parse entities filter", e.getMessage(), HttpStatus.BAD_REQUEST, e);
    }
    String jpqlWhere = filterParseResult.getJpqlWhere().replace("{E}", "e");
    Map<String, Object> queryParameters = filterParseResult.getQueryParameters();
    String queryString = "select e from " + entityName + " e where " + jpqlWhere;
    String json = _loadEntitiesList(queryString, viewName, limit, offset, sort, returnNulls, dynamicAttributes, modelVersion, metaClass, queryParameters);
    Long count = null;
    if (BooleanUtils.isTrue(returnCount)) {
        LoadContext ctx = LoadContext.create(metaClass.getJavaClass()).setQuery(LoadContext.createQuery(queryString).setParameters(queryParameters));
        count = dataManager.getCount(ctx);
    }
    return new EntitiesSearchResult(json, count);
}
Also used : RestFilterParseResult(com.haulmont.restapi.service.filter.RestFilterParseResult) MetaClass(com.haulmont.chile.core.model.MetaClass) EntitiesSearchResult(com.haulmont.restapi.data.EntitiesSearchResult) RestAPIException(com.haulmont.restapi.exception.RestAPIException) JsonObject(com.google.gson.JsonObject) RestFilterParseException(com.haulmont.restapi.service.filter.RestFilterParseException)

Example 7 with RestAPIException

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

the class QueriesControllerManager method _executeQuery.

protected String _executeQuery(String entityName, String queryName, @Nullable Integer limit, @Nullable Integer offset, @Nullable String viewName, @Nullable Boolean returnNulls, @Nullable Boolean dynamicAttributes, @Nullable String version, Map<String, String> params) {
    LoadContext<Entity> ctx;
    entityName = restControllerUtils.transformEntityNameIfRequired(entityName, version, JsonTransformationDirection.FROM_VERSION);
    try {
        ctx = createQueryLoadContext(entityName, queryName, limit, offset, params);
    } catch (ClassNotFoundException | ParseException e) {
        throw new RestAPIException("Error on executing the query", e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
    ctx.setLoadDynamicAttributes(BooleanUtils.isTrue(dynamicAttributes));
    // override default view defined in queries config
    if (!Strings.isNullOrEmpty(viewName)) {
        MetaClass metaClass = restControllerUtils.getMetaClass(entityName);
        restControllerUtils.getView(metaClass, viewName);
        ctx.setView(viewName);
    }
    List<Entity> entities = dataManager.loadList(ctx);
    entities.forEach(entity -> restControllerUtils.applyAttributesSecurity(entity));
    List<EntitySerializationOption> serializationOptions = new ArrayList<>();
    serializationOptions.add(EntitySerializationOption.SERIALIZE_INSTANCE_NAME);
    if (BooleanUtils.isTrue(returnNulls))
        serializationOptions.add(EntitySerializationOption.SERIALIZE_NULLS);
    String json = entitySerializationAPI.toJson(entities, ctx.getView(), serializationOptions.toArray(new EntitySerializationOption[0]));
    json = restControllerUtils.transformJsonIfRequired(entityName, version, JsonTransformationDirection.TO_VERSION, json);
    return json;
}
Also used : Entity(com.haulmont.cuba.core.entity.Entity) EntitySerializationOption(com.haulmont.cuba.core.app.serialization.EntitySerializationOption) MetaClass(com.haulmont.chile.core.model.MetaClass) RestAPIException(com.haulmont.restapi.exception.RestAPIException) ParseException(java.text.ParseException)

Example 8 with RestAPIException

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

the class DatatypesControllerManager method getDatatypesJson.

public String getDatatypesJson() {
    JsonArray jsonArray = new JsonArray();
    try {
        for (String id : datatypes.getIds()) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("id", id);
            // for backward compatibility
            jsonObject.addProperty("name", id);
            Datatype datatype = datatypes.get(id);
            if (datatype instanceof ParameterizedDatatype) {
                Map<String, Object> parameters = ((ParameterizedDatatype) datatype).getParameters();
                for (Map.Entry<String, Object> entry : parameters.entrySet()) {
                    jsonObject.addProperty(entry.getKey(), entry.getValue().toString());
                }
            }
            jsonArray.add(jsonObject);
        }
    } catch (Exception e) {
        log.error("Fail to get datatype settings", e);
        throw new RestAPIException("Fail to get datatype settings", e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return jsonArray.toString();
}
Also used : JsonArray(com.google.gson.JsonArray) ParameterizedDatatype(com.haulmont.chile.core.datatypes.ParameterizedDatatype) JsonObject(com.google.gson.JsonObject) RestAPIException(com.haulmont.restapi.exception.RestAPIException) JsonObject(com.google.gson.JsonObject) Map(java.util.Map) RestAPIException(com.haulmont.restapi.exception.RestAPIException) Datatype(com.haulmont.chile.core.datatypes.Datatype) ParameterizedDatatype(com.haulmont.chile.core.datatypes.ParameterizedDatatype)

Example 9 with RestAPIException

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

the class EntitiesControllerManager method updateEntity.

public CreatedEntityInfo updateEntity(String entityJson, String entityName, String entityId, String modelVersion) {
    String transformedEntityName = restControllerUtils.transformEntityNameIfRequired(entityName, modelVersion, JsonTransformationDirection.FROM_VERSION);
    MetaClass metaClass = restControllerUtils.getMetaClass(transformedEntityName);
    checkCanUpdateEntity(metaClass);
    Object id = getIdFromString(entityId, metaClass);
    LoadContext loadContext = new LoadContext(metaClass).setId(id);
    @SuppressWarnings("unchecked") Entity existingEntity = dataManager.load(loadContext);
    checkEntityIsNotNull(transformedEntityName, entityId, existingEntity);
    entityJson = restControllerUtils.transformJsonIfRequired(entityName, modelVersion, JsonTransformationDirection.FROM_VERSION, entityJson);
    Entity entity;
    try {
        entity = entitySerializationAPI.entityFromJson(entityJson, metaClass);
    } catch (Exception e) {
        throw new RestAPIException("Cannot deserialize an entity from JSON", "", HttpStatus.BAD_REQUEST, e);
    }
    if (entity instanceof BaseGenericIdEntity) {
        // noinspection unchecked
        ((BaseGenericIdEntity) entity).setId(id);
    }
    EntityImportView entityImportView = entityImportViewBuilderAPI.buildFromJson(entityJson, metaClass);
    Collection<Entity> importedEntities;
    try {
        importedEntities = entityImportExportService.importEntities(Collections.singletonList(entity), entityImportView, true);
        importedEntities.forEach(it -> restControllerUtils.applyAttributesSecurity(it));
    } catch (EntityImportException e) {
        throw new RestAPIException("Entity update failed", e.getMessage(), HttpStatus.BAD_REQUEST, e);
    }
    // the main entity that will be returned
    return getMainEntityInfo(importedEntities, metaClass, modelVersion);
}
Also used : EntityImportView(com.haulmont.cuba.core.app.importexport.EntityImportView) MetaClass(com.haulmont.chile.core.model.MetaClass) EntityImportException(com.haulmont.cuba.core.app.importexport.EntityImportException) RestAPIException(com.haulmont.restapi.exception.RestAPIException) JsonObject(com.google.gson.JsonObject) RestFilterParseException(com.haulmont.restapi.service.filter.RestFilterParseException) EntityImportException(com.haulmont.cuba.core.app.importexport.EntityImportException) RestAPIException(com.haulmont.restapi.exception.RestAPIException)

Example 10 with RestAPIException

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

the class EntitiesControllerManager method getIdFromString.

private Object getIdFromString(String entityId, MetaClass metaClass) {
    try {
        if (BaseDbGeneratedIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
            if (BaseIdentityIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
                return IdProxy.of(Long.valueOf(entityId));
            } else if (BaseIntIdentityIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
                return IdProxy.of(Integer.valueOf(entityId));
            } else {
                Class<?> clazz = metaClass.getJavaClass();
                while (clazz != null) {
                    Method[] methods = clazz.getDeclaredMethods();
                    for (Method method : methods) {
                        if (method.getName().equals("getDbGeneratedId")) {
                            Class<?> idClass = method.getReturnType();
                            if (Long.class.isAssignableFrom(idClass)) {
                                return Long.valueOf(entityId);
                            } else if (Integer.class.isAssignableFrom(idClass)) {
                                return Integer.valueOf(entityId);
                            } else if (Short.class.isAssignableFrom(idClass)) {
                                return Long.valueOf(entityId);
                            } else if (UUID.class.isAssignableFrom(idClass)) {
                                return UUID.fromString(entityId);
                            }
                        }
                    }
                    clazz = clazz.getSuperclass();
                }
            }
            throw new UnsupportedOperationException("Unsupported ID type in entity " + metaClass.getName());
        } else {
            // noinspection unchecked
            Method getIdMethod = metaClass.getJavaClass().getMethod("getId");
            Class<?> idClass = getIdMethod.getReturnType();
            if (UUID.class.isAssignableFrom(idClass)) {
                return UUID.fromString(entityId);
            } else if (Integer.class.isAssignableFrom(idClass)) {
                return Integer.valueOf(entityId);
            } else if (Long.class.isAssignableFrom(idClass)) {
                return Long.valueOf(entityId);
            } else {
                return entityId;
            }
        }
    } catch (Exception e) {
        throw new RestAPIException("Invalid entity ID", String.format("Cannot convert %s into valid entity ID", entityId), HttpStatus.BAD_REQUEST, e);
    }
}
Also used : RestAPIException(com.haulmont.restapi.exception.RestAPIException) MetaClass(com.haulmont.chile.core.model.MetaClass) Method(java.lang.reflect.Method) RestFilterParseException(com.haulmont.restapi.service.filter.RestFilterParseException) EntityImportException(com.haulmont.cuba.core.app.importexport.EntityImportException) RestAPIException(com.haulmont.restapi.exception.RestAPIException)

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