Search in sources :

Example 16 with InvalidArgumentException

use of org.alfresco.rest.framework.core.exceptions.InvalidArgumentException in project alfresco-remote-api by Alfresco.

the class RecognizedParamsExtractor method getSort.

/**
 * Takes the Sort parameter as a String and parses it into a List of SortColumn objects.
 * The format is a comma seperated list of "columnName sortDirection",
 * e.g. "name DESC, age ASC".  It is not case sensitive and the sort direction is optional
 * It default to sort ASCENDING.
 *
 * @param sortParams - String passed in on the request
 * @return - the sort columns or an empty list if the params were invalid.
 */
default List<SortColumn> getSort(String sortParams) {
    if (sortParams != null) {
        StringTokenizer st = new StringTokenizer(sortParams, ",");
        List<SortColumn> sortedColumns = new ArrayList<SortColumn>(st.countTokens());
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            StringTokenizer columnDesc = new StringTokenizer(token, " ");
            if (columnDesc.countTokens() <= 2) {
                String columnName = columnDesc.nextToken();
                String sortOrder = SortColumn.ASCENDING;
                if (columnDesc.hasMoreTokens()) {
                    String sortDef = columnDesc.nextToken().toUpperCase();
                    if (SortColumn.ASCENDING.equals(sortDef) || SortColumn.DESCENDING.equals(sortDef)) {
                        sortOrder = sortDef;
                    } else {
                        rpeLogger().debug("Invalid sort order direction (" + sortDef + ").  Valid values are " + SortColumn.ASCENDING + " or " + SortColumn.DESCENDING + ".");
                        throw new InvalidArgumentException("Unknown sort order direction '" + sortDef + "', expected asc or desc");
                    }
                }
                sortedColumns.add(new SortColumn(columnName, SortColumn.ASCENDING.equals(sortOrder)));
            } else {
                rpeLogger().debug("Invalid sort order definition (" + token + ")");
                throw new InvalidArgumentException("Unknown sort order definition '" + token + "', expected 'field1,field2' or 'field1 asc,field2 desc' or similar");
            }
        // filteredProperties.add();
        }
        // BeanPropertiesFilter filter = new BeanPropertiesFilter(filteredProperties);
        return sortedColumns;
    }
    return Collections.emptyList();
}
Also used : StringTokenizer(java.util.StringTokenizer) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ArrayList(java.util.ArrayList) SortColumn(org.alfresco.rest.framework.resource.parameters.SortColumn)

Example 17 with InvalidArgumentException

use of org.alfresco.rest.framework.core.exceptions.InvalidArgumentException in project alfresco-remote-api by Alfresco.

the class ResourceWebScriptPost method extractObjFromJson.

/**
 * If the @WebApiParam has been used and set allowMultiple to false then this will get a single entry.  It
 * should error if an array is passed in.
 * @param resourceMeta ResourceMetadata
 * @param req WebScriptRequest
 * @return Either an object
 */
private Object extractObjFromJson(ResourceMetadata resourceMeta, ResourceOperation operation, WebScriptRequest req) {
    if (operation == null) {
        return null;
    }
    Class<?> objType = resourceMeta.getObjectType(operation);
    boolean isTypeOperation = resourceMeta.getType().equals(ResourceMetadata.RESOURCE_TYPE.OPERATION);
    List<ResourceParameter> params = operation.getParameters();
    if (!params.isEmpty()) {
        for (ResourceParameter resourceParameter : params) {
            // POST to collection may or may not support List as json body, Operations don't support a List as json body
            boolean notMultiple = ((!resourceParameter.isAllowMultiple()) || isTypeOperation);
            if (ResourceParameter.KIND.HTTP_BODY_OBJECT.equals(resourceParameter.getParamType()) && notMultiple) {
                // Only allow 1 value.
                try {
                    Object jsonContent = null;
                    if (objType != null) {
                        // check if the body is optional and is not provided
                        if (!resourceParameter.isRequired() && Integer.valueOf(req.getHeader("content-length")) <= 0) {
                            // in some cases the body is optional and the json doesn't need to be extracted
                            return null;
                        } else {
                            jsonContent = extractJsonContent(req, assistant.getJsonHelper(), objType);
                        }
                    }
                    if (isTypeOperation) {
                        return jsonContent;
                    } else {
                        return Arrays.asList(jsonContent);
                    }
                } catch (InvalidArgumentException iae) {
                    if (iae.getMessage().contains("START_ARRAY") && iae.getMessage().contains("line: 1, column: 1")) {
                        throw new UnsupportedResourceOperationException("Only 1 entity is supported in the HTTP request body");
                    } else {
                        throw iae;
                    }
                }
            }
        }
    }
    if (objType == null) {
        return null;
    }
    if (isTypeOperation) {
        // Operations don't support a List as json body
        return extractJsonContent(req, assistant.getJsonHelper(), objType);
    } else {
        return extractJsonContentAsList(req, assistant.getJsonHelper(), objType);
    }
}
Also used : ResourceParameter(org.alfresco.rest.framework.core.ResourceParameter) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) UnsupportedResourceOperationException(org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException)

Example 18 with InvalidArgumentException

use of org.alfresco.rest.framework.core.exceptions.InvalidArgumentException in project alfresco-remote-api by Alfresco.

the class WebScriptOptionsMetaData method execute.

@Override
public void execute(final Api api, WebScriptRequest req, WebScriptResponse res) throws IOException {
    final Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    ResourceDictionary resourceDic = lookupDictionary.getDictionary();
    Map<String, ResourceWithMetadata> apiResources = resourceDic.getAllResources().get(api);
    if (apiResources == null) {
        throw new InvalidArgumentException(InvalidArgumentException.DEFAULT_INVALID_API);
    }
    String collectionName = templateVars.get(ResourceLocator.COLLECTION_RESOURCE);
    String resourceName = templateVars.get(ResourceLocator.RELATIONSHIP_RESOURCE);
    String resourceKey = ResourceDictionary.resourceKey(collectionName, resourceName);
    if (logger.isDebugEnabled()) {
        logger.debug("Locating resource :" + resourceKey);
    }
    ResourceWithMetadata resource = apiResources.get(resourceKey);
    if (resource == null) {
        // Get entity resource and check if we are referencing a property on it.
        resourceKey = ResourceDictionary.propertyResourceKey(collectionName, resourceName);
        resource = apiResources.get(resourceKey);
    }
    ResourceMetaDataWriter writer = chooseWriter(req);
    writer.writeMetaData(res.getOutputStream(), resource, apiResources);
}
Also used : InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ResourceDictionary(org.alfresco.rest.framework.core.ResourceDictionary) ResourceWithMetadata(org.alfresco.rest.framework.core.ResourceWithMetadata) ResourceMetaDataWriter(org.alfresco.rest.framework.metadata.ResourceMetaDataWriter)

Example 19 with InvalidArgumentException

use of org.alfresco.rest.framework.core.exceptions.InvalidArgumentException in project alfresco-remote-api by Alfresco.

the class MapBasedQueryWalker method getProperty.

/**
 * Get the property value, converted to the requested type.
 *
 * @param propertyName name of the parameter
 * @param type int
 * @param returnType type of object to return
 * @return the converted parameter value. Null, if the property has no
 *         value.
 * @throws IllegalArgumentException when no conversion for the given
 *             returnType is available or if returnType is null.
 * @throws InvalidArgumentException when conversion to the given type was
 *             not possible due to an error while converting
 */
@SuppressWarnings("unchecked")
public <T extends Object> T getProperty(String propertyName, int type, Class<T> returnType) {
    if (returnType == null) {
        throw new IllegalArgumentException("ReturnType cannot be null");
    }
    try {
        Object result = null;
        String stringValue = getProperty(propertyName, type);
        if (stringValue != null) {
            result = ConvertUtils.convert(stringValue, returnType);
            if ((result instanceof String) && (!returnType.equals(String.class))) {
                // If a string is returned, no converter has been found (for non-String return type)
                throw new IllegalArgumentException("Unable to convert parameter to type: " + returnType.getName());
            }
        }
        return (T) result;
    } catch (ConversionException ce) {
        // Conversion failed, wrap in Illegal
        throw new InvalidArgumentException("Query property value for '" + propertyName + "' should be a valid " + returnType.getSimpleName());
    }
}
Also used : ConversionException(org.apache.commons.beanutils.ConversionException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)

Example 20 with InvalidArgumentException

use of org.alfresco.rest.framework.core.exceptions.InvalidArgumentException in project alfresco-remote-api by Alfresco.

the class ProcessDefinitionsImpl method getProcessDefinitions.

@Override
public CollectionWithPagingInfo<ProcessDefinition> getProcessDefinitions(Parameters parameters) {
    ProcessDefinitionQuery query = activitiProcessEngine.getRepositoryService().createProcessDefinitionQuery().processDefinitionCategoryNotEquals(WorkflowDeployer.CATEGORY_ALFRESCO_INTERNAL);
    MapBasedQueryWalker propertyWalker = new MapBasedQueryWalker(PROCESS_DEFINITION_COLLECTION_EQUALS_QUERY_PROPERTIES, PROCESS_DEFINITION_COLLECTION_MATCHES_QUERY_PROPERTIES);
    boolean keyQueryIncluded = false;
    if (parameters.getQuery() != null) {
        QueryHelper.walk(parameters.getQuery(), propertyWalker);
        // Property equals
        String categoryProperty = propertyWalker.getProperty("category", WhereClauseParser.EQUALS);
        if (categoryProperty != null) {
            query.processDefinitionCategory(categoryProperty);
        }
        String keyProperty = propertyWalker.getProperty("key", WhereClauseParser.EQUALS);
        if (keyProperty != null) {
            query.processDefinitionKey(getProcessDefinitionKey(keyProperty));
            keyQueryIncluded = true;
        }
        String nameProperty = propertyWalker.getProperty("name", WhereClauseParser.EQUALS);
        if (nameProperty != null) {
            query.processDefinitionName(nameProperty);
        }
        Integer versionProperty = propertyWalker.getProperty("version", WhereClauseParser.EQUALS, Integer.class);
        if (versionProperty != null) {
            query.processDefinitionVersion(versionProperty);
        }
        String deploymentProperty = propertyWalker.getProperty("deploymentId", WhereClauseParser.EQUALS);
        if (deploymentProperty != null) {
            query.deploymentId(deploymentProperty);
        }
        // Property matches
        String categoryMatchesProperty = propertyWalker.getProperty("category", WhereClauseParser.MATCHES);
        if (categoryMatchesProperty != null) {
            query.processDefinitionCategoryLike(categoryMatchesProperty);
        }
        String keyMatchesProperty = propertyWalker.getProperty("key", WhereClauseParser.MATCHES);
        if (keyMatchesProperty != null) {
            query.processDefinitionKeyLike(getProcessDefinitionKey(keyMatchesProperty));
            keyQueryIncluded = true;
        }
        String nameLikeProperty = propertyWalker.getProperty("name", WhereClauseParser.MATCHES);
        if (nameLikeProperty != null) {
            query.processDefinitionNameLike(nameLikeProperty);
        }
    }
    // Filter based on tenant, if required
    if (keyQueryIncluded == false && tenantService.isEnabled() && deployWorkflowsInTenant) {
        query.processDefinitionKeyLike("@" + TenantUtil.getCurrentDomain() + "@%");
    }
    List<SortColumn> sortList = parameters.getSorting();
    SortColumn sortColumn = null;
    if (sortList != null && sortList.size() > 0) {
        if (sortList.size() != 1) {
            throw new InvalidArgumentException("Only one orderBy parameter is supported");
        }
        sortColumn = sortList.get(0);
        switch(sortColumn.column) {
            case "id":
                query.orderByProcessDefinitionId();
                break;
            case "deploymentId":
                query.orderByDeploymentId();
                break;
            case "key":
                query.orderByProcessDefinitionKey();
                break;
            case "category":
                query.orderByProcessDefinitionCategory();
                break;
            case "version":
                query.orderByProcessDefinitionVersion();
                break;
            case "name":
                query.orderByProcessDefinitionName();
                break;
            default:
                throw new InvalidArgumentException("OrderBy " + sortColumn.column + " is not supported, supported items are " + PROCESS_DEFINITION_COLLECTION_SORT_PROPERTIES);
        }
        if (sortColumn.asc) {
            query.asc();
        } else {
            query.desc();
        }
    } else {
        query.orderByProcessDefinitionId().asc();
    }
    List<org.activiti.engine.repository.ProcessDefinition> processDefinitions = query.listPage(parameters.getPaging().getSkipCount(), parameters.getPaging().getMaxItems());
    int totalCount = (int) query.count();
    List<ProcessDefinition> page = new ArrayList<ProcessDefinition>(processDefinitions.size());
    for (org.activiti.engine.repository.ProcessDefinition processDefinition : processDefinitions) {
        page.add(createProcessDefinitionRest((ProcessDefinitionEntity) processDefinition));
    }
    return CollectionWithPagingInfo.asPaged(parameters.getPaging(), page, (page.size() + parameters.getPaging().getSkipCount()) < totalCount, totalCount);
}
Also used : ArrayList(java.util.ArrayList) ProcessDefinitionQuery(org.activiti.engine.repository.ProcessDefinitionQuery) ProcessDefinition(org.alfresco.rest.workflow.api.model.ProcessDefinition) SortColumn(org.alfresco.rest.framework.resource.parameters.SortColumn) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ProcessDefinitionEntity(org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity)

Aggregations

InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)124 NodeRef (org.alfresco.service.cmr.repository.NodeRef)36 QName (org.alfresco.service.namespace.QName)36 EntityNotFoundException (org.alfresco.rest.framework.core.exceptions.EntityNotFoundException)30 ConstraintViolatedException (org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException)22 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)20 PermissionDeniedException (org.alfresco.rest.framework.core.exceptions.PermissionDeniedException)16 Serializable (java.io.Serializable)11 SearchParameters (org.alfresco.service.cmr.search.SearchParameters)11 Paging (org.alfresco.rest.framework.resource.parameters.Paging)10 SortColumn (org.alfresco.rest.framework.resource.parameters.SortColumn)10 ApiException (org.alfresco.rest.framework.core.exceptions.ApiException)9 HashMap (java.util.HashMap)8 HashSet (java.util.HashSet)8 Params (org.alfresco.rest.framework.resource.parameters.Params)8 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)8 NotFoundException (org.alfresco.rest.framework.core.exceptions.NotFoundException)7 Pair (org.alfresco.util.Pair)7 List (java.util.List)6