Search in sources :

Example 86 with BadRequestException

use of org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException in project charon by wso2.

the class PatchOperationUtil method doPatchReplaceOnPathWithFilters.

/*
     * This method is to do patch replace for level three attributes with a filter and path value present.
     * @param oldResource
     * @param copyOfOldResource
     * @param schema
     * @param decoder
     * @param operation
     * @param parts
     * @throws NotImplementedException
     * @throws BadRequestException
     * @throws CharonException
     * @throws JSONException
     * @throws InternalErrorException
     */
private static void doPatchReplaceOnPathWithFilters(AbstractSCIMObject oldResource, SCIMResourceTypeSchema schema, JSONDecoder decoder, PatchOperation operation, String[] parts) throws NotImplementedException, BadRequestException, CharonException, JSONException, InternalErrorException {
    if (parts.length != 1) {
        // currently we only support simple filters here.
        String[] filterParts = parts[1].split(" ");
        ExpressionNode expressionNode = new ExpressionNode();
        expressionNode.setAttributeValue(filterParts[0]);
        expressionNode.setOperation(filterParts[1]);
        expressionNode.setValue(filterParts[2]);
        if (expressionNode.getOperation().equalsIgnoreCase((SCIMConstants.OperationalConstants.EQ).trim())) {
            if (parts.length == 3) {
                parts[0] = parts[0] + parts[2];
            }
            String[] attributeParts = parts[0].split("[\\.]");
            if (attributeParts.length == 1) {
                doPatchReplaceWithFiltersForLevelOne(oldResource, attributeParts, expressionNode, operation, schema, decoder);
            } else if (attributeParts.length == 2) {
                doPatchReplaceWithFiltersForLevelTwo(oldResource, attributeParts, expressionNode, operation, schema, decoder);
            } else if (attributeParts.length == 3) {
                doPatchReplaceWithFiltersForLevelThree(oldResource, attributeParts, expressionNode, operation, schema, decoder);
            }
        } else {
            throw new NotImplementedException("Only Eq filter is supported");
        }
    }
}
Also used : ExpressionNode(org.wso2.charon3.core.utils.codeutils.ExpressionNode) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException)

Example 87 with BadRequestException

use of org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException in project charon by wso2.

the class PatchOperationUtil method doPatchReplaceOnResource.

/*
     *
     * @param oldResource
     * @param copyOfOldResource
     * @param schema
     * @param decoder
     * @param operation
     * @return
     * @throws CharonException
     */
private static AbstractSCIMObject doPatchReplaceOnResource(AbstractSCIMObject oldResource, AbstractSCIMObject copyOfOldResource, SCIMResourceTypeSchema schema, JSONDecoder decoder, PatchOperation operation) throws CharonException {
    try {
        AbstractSCIMObject attributeHoldingSCIMObject = decoder.decode(operation.getValues().toString(), schema);
        if (oldResource != null) {
            for (String attributeName : attributeHoldingSCIMObject.getAttributeList().keySet()) {
                Attribute oldAttribute = oldResource.getAttribute(attributeName);
                if (oldAttribute != null) {
                    // if the attribute is there, append it.
                    if (oldAttribute.getMultiValued()) {
                        // this is multivalued complex case.
                        MultiValuedAttribute attributeValue = (MultiValuedAttribute) attributeHoldingSCIMObject.getAttribute(attributeName);
                        if (oldAttribute.getMutability().equals(SCIMDefinitions.Mutability.IMMUTABLE) || oldAttribute.getMutability().equals(SCIMDefinitions.Mutability.READ_ONLY)) {
                            throw new BadRequestException("Immutable or Read-Only attributes can not be modified.", ResponseCodeConstants.MUTABILITY);
                        } else {
                            // delete the old attribute
                            oldResource.deleteAttribute(attributeName);
                            // replace with new attribute
                            oldResource.setAttribute(attributeValue);
                        }
                    } else if (oldAttribute.getType().equals(SCIMDefinitions.DataType.COMPLEX)) {
                        // this is the complex attribute case.
                        Map<String, Attribute> subAttributeList = ((ComplexAttribute) attributeHoldingSCIMObject.getAttribute(attributeName)).getSubAttributesList();
                        for (Map.Entry<String, Attribute> subAttrib : subAttributeList.entrySet()) {
                            Attribute subAttribute = oldAttribute.getSubAttribute(subAttrib.getKey());
                            if (subAttribute != null) {
                                if (subAttribute.getType().equals(SCIMDefinitions.DataType.COMPLEX)) {
                                    if (subAttribute.getMultiValued()) {
                                        // extension schema is the only one who reaches here.
                                        MultiValuedAttribute attributeSubValue = (MultiValuedAttribute) ((ComplexAttribute) attributeHoldingSCIMObject.getAttribute(attributeName)).getSubAttribute(subAttrib.getKey());
                                        if (subAttribute.getMutability().equals(SCIMDefinitions.Mutability.IMMUTABLE) || subAttribute.getMutability().equals(SCIMDefinitions.Mutability.READ_ONLY)) {
                                            throw new BadRequestException("Immutable or Read-Only attributes can not be modified.", ResponseCodeConstants.MUTABILITY);
                                        } else {
                                            // delete the old attribute
                                            ((ComplexAttribute) (oldAttribute)).removeSubAttribute(subAttribute.getName());
                                            // replace with new attribute
                                            ((ComplexAttribute) (oldAttribute)).setSubAttribute(attributeSubValue);
                                        }
                                    } else {
                                        // extension schema is the only one who reaches here.
                                        Map<String, Attribute> subSubAttributeList = ((ComplexAttribute) (attributeHoldingSCIMObject.getAttribute(attributeName).getSubAttribute(subAttrib.getKey()))).getSubAttributesList();
                                        for (Map.Entry<String, Attribute> subSubAttrb : subSubAttributeList.entrySet()) {
                                            Attribute subSubAttribute = oldAttribute.getSubAttribute(subAttrib.getKey()).getSubAttribute(subSubAttrb.getKey());
                                            if (subSubAttribute != null) {
                                                if (subSubAttribute.getMultiValued()) {
                                                    if (subSubAttribute.getMutability().equals(SCIMDefinitions.Mutability.IMMUTABLE) || subSubAttribute.getMutability().equals(SCIMDefinitions.Mutability.READ_ONLY)) {
                                                        throw new BadRequestException("Immutable or Read-Only attributes " + "can not be modified.", ResponseCodeConstants.MUTABILITY);
                                                    } else {
                                                        // delete the old attribute
                                                        ((ComplexAttribute) (oldAttribute.getSubAttribute(subAttrib.getKey()))).removeSubAttribute(subSubAttribute.getName());
                                                        // replace with new attribute
                                                        ((ComplexAttribute) (oldAttribute.getSubAttribute(subAttrib.getKey()))).setSubAttribute(subSubAttribute);
                                                    }
                                                } else {
                                                    ((SimpleAttribute) subSubAttribute).setValue(((SimpleAttribute) subSubAttrb.getValue()));
                                                }
                                            } else {
                                                ((ComplexAttribute) (subAttribute)).setSubAttribute(subSubAttrb.getValue());
                                            }
                                        }
                                    }
                                } else {
                                    if (subAttribute.getMutability().equals(SCIMDefinitions.Mutability.IMMUTABLE) || subAttribute.getMutability().equals(SCIMDefinitions.Mutability.READ_ONLY)) {
                                        throw new BadRequestException("Immutable or Read-Only " + "attributes can not be modified.", ResponseCodeConstants.MUTABILITY);
                                    } else {
                                        // delete the old attribute
                                        ((ComplexAttribute) (oldAttribute)).removeSubAttribute(subAttribute.getName());
                                        // replace with new attribute
                                        ((ComplexAttribute) (oldAttribute)).setSubAttribute(subAttributeList.get(subAttribute.getName()));
                                    }
                                }
                            } else {
                                // add the attribute
                                ((ComplexAttribute) oldAttribute).setSubAttribute(subAttrib.getValue());
                            }
                        }
                    } else {
                        if (oldAttribute.getMutability().equals(SCIMDefinitions.Mutability.IMMUTABLE) || oldAttribute.getMutability().equals(SCIMDefinitions.Mutability.READ_ONLY)) {
                            throw new BadRequestException("Immutable or Read-Only attributes can not be modified.", ResponseCodeConstants.MUTABILITY);
                        } else {
                            // this is the simple attribute case.replace the value
                            ((SimpleAttribute) oldAttribute).setValue(((SimpleAttribute) attributeHoldingSCIMObject.getAttribute(oldAttribute.getName())).getValue());
                        }
                    }
                } else {
                    // add the attribute
                    oldResource.setAttribute(attributeHoldingSCIMObject.getAttributeList().get(attributeName));
                }
            }
            AbstractSCIMObject validatedResource = ServerSideValidator.validateUpdatedSCIMObject(copyOfOldResource, oldResource, schema);
            return validatedResource;
        } else {
            throw new CharonException("Error in getting the old resource.");
        }
    } catch (BadRequestException | CharonException e) {
        throw new CharonException("Error in performing the add operation", e);
    }
}
Also used : AbstractSCIMObject(org.wso2.charon3.core.objects.AbstractSCIMObject) MultiValuedAttribute(org.wso2.charon3.core.attributes.MultiValuedAttribute) SimpleAttribute(org.wso2.charon3.core.attributes.SimpleAttribute) ComplexAttribute(org.wso2.charon3.core.attributes.ComplexAttribute) Attribute(org.wso2.charon3.core.attributes.Attribute) SimpleAttribute(org.wso2.charon3.core.attributes.SimpleAttribute) ComplexAttribute(org.wso2.charon3.core.attributes.ComplexAttribute) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) CharonException(org.wso2.charon3.core.exceptions.CharonException) Map(java.util.Map) MultiValuedAttribute(org.wso2.charon3.core.attributes.MultiValuedAttribute)

Example 88 with BadRequestException

use of org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException in project charon by wso2.

the class AbstractSCIMObject method setCreatedDate.

/*
     * set the created date and time of the resource
     *
     * @param createdDate
     */
public void setCreatedDate(Date createdDate) throws CharonException, BadRequestException {
    // create the created date attribute as defined in schema.
    SimpleAttribute createdDateAttribute = new SimpleAttribute(SCIMConstants.CommonSchemaConstants.CREATED, createdDate);
    createdDateAttribute = (SimpleAttribute) DefaultAttributeFactory.createAttribute(SCIMSchemaDefinitions.CREATED, createdDateAttribute);
    // check meta complex attribute already exist.
    if (getMetaAttribute() != null) {
        ComplexAttribute metaAttribute = getMetaAttribute();
        // check created date attribute already exist
        if (metaAttribute.isSubAttributeExist(createdDateAttribute.getName())) {
            // TODO:log info level log that created date already set and can't set again.
            String error = "Read only meta attribute is tried to modify";
            throw new CharonException(error);
        } else {
            metaAttribute.setSubAttribute(createdDateAttribute);
        }
    } else {
        // create meta attribute and set the sub attribute Created Date.
        createMetaAttribute();
        getMetaAttribute().setSubAttribute(createdDateAttribute);
    }
}
Also used : SimpleAttribute(org.wso2.charon3.core.attributes.SimpleAttribute) ComplexAttribute(org.wso2.charon3.core.attributes.ComplexAttribute) CharonException(org.wso2.charon3.core.exceptions.CharonException)

Example 89 with BadRequestException

use of org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException in project charon by wso2.

the class DefaultAttributeFactory method createAttribute.

/*
     * Returns the defined type of attribute with the user defined value
     * included and necessary attribute characteristics set
     * @param attributeSchema - Attribute schema
     * @param attribute - attribute
     * @return Attribute
     */
public static Attribute createAttribute(AttributeSchema attributeSchema, AbstractAttribute attribute) throws CharonException, BadRequestException {
    attribute.setMutability(attributeSchema.getMutability());
    attribute.setRequired(attributeSchema.getRequired());
    attribute.setReturned(attributeSchema.getReturned());
    attribute.setCaseExact(attributeSchema.getCaseExact());
    attribute.setMultiValued(attributeSchema.getMultiValued());
    attribute.setDescription(attributeSchema.getDescription());
    attribute.setUniqueness(attributeSchema.getUniqueness());
    attribute.setURI(attributeSchema.getURI());
    // Default attribute factory knows about SCIMAttribute schema
    try {
        // set data type of the attribute value, if simple attribute
        if (attribute instanceof SimpleAttribute) {
            return createSimpleAttribute(attributeSchema, (SimpleAttribute) attribute);
        } else {
            attribute.setType(attributeSchema.getType());
        }
        return attribute;
    } catch (CharonException e) {
        String error = "Unknown attribute schema.";
        throw new CharonException(error);
    } catch (BadRequestException e) {
        String error = "Violation in attribute schema. DataType doesn't match that of the value.";
        throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE);
    }
}
Also used : BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) CharonException(org.wso2.charon3.core.exceptions.CharonException)

Example 90 with BadRequestException

use of org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException in project carbon-apimgt by wso2.

the class ApiProductsApiServiceImpl method addAPIProductDocument.

@Override
public Response addAPIProductDocument(String apiProductId, DocumentDTO body, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        if (body.getType() == null) {
            throw new BadRequestException();
        }
        if (body.getType() == DocumentDTO.TypeEnum.OTHER && org.apache.commons.lang3.StringUtils.isBlank(body.getOtherTypeName())) {
            // check otherTypeName for not null if doc type is OTHER
            RestApiUtil.handleBadRequest("otherTypeName cannot be empty if type is OTHER.", log);
        }
        String sourceUrl = body.getSourceUrl();
        if (body.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
            RestApiUtil.handleBadRequest("Invalid document sourceUrl Format", log);
        }
        Documentation documentation = DocumentationMappingUtil.fromDTOtoDocumentation(body);
        String documentName = body.getName();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // this will fail if user does not have access to the API Product or the API Product does not exist
        APIProductIdentifier productIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, organization);
        if (apiProvider.isDocumentationExist(apiProductId, documentName, organization)) {
            String errorMessage = "Requested document '" + documentName + "' already exists";
            RestApiUtil.handleResourceAlreadyExistsError(errorMessage, log);
        }
        documentation = apiProvider.addDocumentation(apiProductId, documentation, organization);
        DocumentDTO newDocumentDTO = DocumentationMappingUtil.fromDocumentationToDTO(documentation);
        String uriString = RestApiConstants.RESOURCE_PATH_PRODUCT_DOCUMENTS_DOCUMENT_ID.replace(RestApiConstants.APIPRODUCTID_PARAM, apiProductId).replace(RestApiConstants.DOCUMENTID_PARAM, documentation.getId());
        URI uri = new URI(uriString);
        return Response.created(uri).entity(newDocumentDTO).build();
    } catch (APIManagementException e) {
        // Auth failure occurs when cross tenant accessing API Products. Sends 404, since we don't need to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while adding documents of API : " + apiProductId, e, log);
        } else {
            String errorMessage = "Error while adding the document for API : " + apiProductId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving location for document " + body.getName() + " of API " + apiProductId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) DocumentDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO) BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI)

Aggregations

BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)63 CharonException (org.wso2.charon3.core.exceptions.CharonException)31 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)30 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)27 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)23 HashMap (java.util.HashMap)22 Attribute (org.wso2.charon3.core.attributes.Attribute)20 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)19 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)19 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)19 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)18 JSONObject (org.json.JSONObject)16 AbstractSCIMObject (org.wso2.charon3.core.objects.AbstractSCIMObject)16 JSONException (org.json.JSONException)15 JSONEncoder (org.wso2.charon3.core.encoder.JSONEncoder)15 JSONDecoder (org.wso2.charon3.core.encoder.JSONDecoder)14 NotImplementedException (org.wso2.charon3.core.exceptions.NotImplementedException)14 User (org.wso2.charon3.core.objects.User)12 JSONArray (org.json.JSONArray)11 BadRequestException (org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException)10