Search in sources :

Example 46 with BadRequestException

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

the class ApiProductsApiServiceImpl method updateAPIProductDocument.

@Override
public Response updateAPIProductDocument(String apiProductId, String documentId, DocumentDTO body, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String sourceUrl = body.getSourceUrl();
        Documentation oldDocument = apiProvider.getDocumentation(apiProductId, documentId, organization);
        // validation checks for existence of the document
        if (oldDocument == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, documentId, log);
            return null;
        }
        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);
            return null;
        }
        if (body.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
            RestApiUtil.handleBadRequest("Invalid document sourceUrl Format", log);
            return null;
        }
        // overriding some properties
        body.setName(oldDocument.getName());
        Documentation newDocumentation = DocumentationMappingUtil.fromDTOtoDocumentation(body);
        // this will fail if user does not have access to the API or the API does not exist
        APIProductIdentifier apiIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, organization);
        newDocumentation.setFilePath(oldDocument.getFilePath());
        newDocumentation.setId(oldDocument.getId());
        apiProvider.updateDocumentation(apiProductId, newDocumentation, organization);
        // retrieve the updated documentation
        newDocumentation = apiProvider.getDocumentation(apiProductId, documentId, organization);
        return Response.ok().entity(DocumentationMappingUtil.fromDocumentationToDTO(newDocumentation)).build();
    } catch (APIManagementException e) {
        // Auth failure occurs when cross tenant accessing APIs. 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 updating document : " + documentId + " of API Product " + apiProductId, e, log);
        } else {
            String errorMessage = "Error while updating the document " + documentId + " for API Product : " + 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) BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 47 with BadRequestException

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

the class ApisApiServiceImpl method updateAPIDocument.

/**
 * Updates an existing document of an API
 *
 * @param apiId      API identifier
 * @param documentId document identifier
 * @param body       updated document DTO
 * @param ifMatch    If-match header value
 * @return updated document DTO as response
 */
@Override
public Response updateAPIDocument(String apiId, String documentId, DocumentDTO body, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        String sourceUrl = body.getSourceUrl();
        Documentation oldDocument = apiProvider.getDocumentation(apiId, documentId, organization);
        // validation checks for existence of the document
        if (body.getType() == null) {
            throw new BadRequestException();
        }
        if (oldDocument == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_DOCUMENTATION, documentId, log);
            return null;
        }
        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);
            return null;
        }
        if (body.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
            RestApiUtil.handleBadRequest("Invalid document sourceUrl Format", log);
            return null;
        }
        // overriding some properties
        body.setName(oldDocument.getName());
        Documentation newDocumentation = DocumentationMappingUtil.fromDTOtoDocumentation(body);
        newDocumentation.setFilePath(oldDocument.getFilePath());
        newDocumentation.setId(documentId);
        newDocumentation = apiProvider.updateDocumentation(apiId, newDocumentation, organization);
        return Response.ok().entity(DocumentationMappingUtil.fromDocumentationToDTO(newDocumentation)).build();
    } catch (APIManagementException e) {
        // Auth failure occurs when cross tenant accessing APIs. 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, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while updating document : " + documentId + " of API " + apiId, e, log);
        } else {
            String errorMessage = "Error while updating the document " + documentId + " for API : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 48 with BadRequestException

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

the class RestApiUtil method handleBadRequest.

/**
 * Logs the error, builds a BadRequestException with specified details and throws it
 *
 * @param msg error message
 * @param log Log instance
 * @throws BadRequestException If 400 bad request comes.
 */
public static void handleBadRequest(String msg, Logger log) throws BadRequestException {
    BadRequestException badRequestException = buildBadRequestException(msg);
    log.error(msg);
    throw badRequestException;
}
Also used : BadRequestException(org.wso2.carbon.apimgt.rest.api.common.exception.BadRequestException)

Example 49 with BadRequestException

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

the class BadRequestExceptionTestCase method testGetMessage.

@Test
public void testGetMessage() throws Exception {
    ErrorDTO errorDTO = new ErrorDTO();
    errorDTO.setDescription(testMessage);
    BadRequestException badRequestException = new BadRequestException(errorDTO);
    String message = badRequestException.getMessage();
    Assert.assertEquals(message, testMessage);
}
Also used : ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) BadRequestException(org.wso2.carbon.apimgt.rest.api.common.exception.BadRequestException) Test(org.testng.annotations.Test)

Example 50 with BadRequestException

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

the class JSONDecoder method buildComplexValue.

/*
     * To build a complex type value of a Multi Valued Attribute. (eg. Email with value,type,primary as sub attributes
     *
     * @param attributeSchema
     * @param jsonObject
     * @return ComplexAttribute
     */
private ComplexAttribute buildComplexValue(AttributeSchema attributeSchema, JSONObject jsonObject) throws CharonException, BadRequestException {
    ComplexAttribute complexAttribute = new ComplexAttribute(attributeSchema.getName());
    Map<String, Attribute> subAttributesMap = new HashMap<String, Attribute>();
    List<SCIMAttributeSchema> subAttributeSchemas = ((SCIMAttributeSchema) attributeSchema).getSubAttributeSchemas();
    for (SCIMAttributeSchema subAttributeSchema : subAttributeSchemas) {
        Object subAttributeValue = jsonObject.opt(subAttributeSchema.getName());
        // setting up a name for the complex attribute for the reference purpose
        if (subAttributeSchema.getName().equals(SCIMConstants.CommonSchemaConstants.VALUE)) {
            // (value,type) pair is considered as a primary key for each entry
            if (subAttributeValue != null) {
                Object subAttributeValueForType = jsonObject.opt(SCIMConstants.CommonSchemaConstants.TYPE);
                if (subAttributeValueForType != null) {
                    complexAttribute.setName(attributeSchema.getName() + "_" + subAttributeValue + "_" + subAttributeValueForType);
                } else {
                    complexAttribute.setName(attributeSchema.getName() + "_" + subAttributeValue + "_" + SCIMConstants.DEFAULT);
                }
            } else {
                Object subAttributeValueFortype = jsonObject.opt(SCIMConstants.CommonSchemaConstants.TYPE);
                if (subAttributeValueFortype != null) {
                    complexAttribute.setName(attributeSchema.getName() + "_" + SCIMConstants.DEFAULT + "_" + subAttributeValueFortype);
                } else {
                    complexAttribute.setName(attributeSchema.getName() + "_" + SCIMConstants.DEFAULT + "_" + SCIMConstants.DEFAULT);
                }
            }
        }
        if (subAttributeValue != null) {
            if (subAttributeSchema.getMultiValued()) {
                if (subAttributeValue instanceof JSONArray) {
                    MultiValuedAttribute multiValuedAttribute = buildPrimitiveMultiValuedAttribute(subAttributeSchema, (JSONArray) subAttributeValue);
                    // let the attribute factory to set the sub attribute of a complex
                    // attribute to detect schema violations.
                    multiValuedAttribute = (MultiValuedAttribute) DefaultAttributeFactory.createAttribute(subAttributeSchema, multiValuedAttribute);
                    subAttributesMap.put(subAttributeSchema.getName(), multiValuedAttribute);
                } else {
                    throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
                }
            } else {
                if (subAttributeValue instanceof String || subAttributeValue instanceof Boolean || subAttributeValue instanceof Integer) {
                    SimpleAttribute simpleAttribute = buildSimpleAttribute(subAttributeSchema, subAttributeValue);
                    // let the attribute factory to set the sub attribute of a complex
                    // attribute to detect schema violations.
                    simpleAttribute = (SimpleAttribute) DefaultAttributeFactory.createAttribute(subAttributeSchema, simpleAttribute);
                    subAttributesMap.put(subAttributeSchema.getName(), simpleAttribute);
                } else {
                    throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
                }
            }
        }
    }
    complexAttribute.setSubAttributesList(subAttributesMap);
    return (ComplexAttribute) DefaultAttributeFactory.createAttribute(attributeSchema, complexAttribute);
}
Also used : 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) HashMap(java.util.HashMap) SimpleAttribute(org.wso2.charon3.core.attributes.SimpleAttribute) ComplexAttribute(org.wso2.charon3.core.attributes.ComplexAttribute) SCIMAttributeSchema(org.wso2.charon3.core.schema.SCIMAttributeSchema) JSONArray(org.json.JSONArray) MultiValuedAttribute(org.wso2.charon3.core.attributes.MultiValuedAttribute) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) AbstractSCIMObject(org.wso2.charon3.core.objects.AbstractSCIMObject) JSONObject(org.json.JSONObject) SCIMObject(org.wso2.charon3.core.objects.SCIMObject)

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