Search in sources :

Example 56 with BadRequestException

use of org.wso2.charon3.core.exceptions.BadRequestException in project charon by wso2.

the class JSONDecoder method decodeBulkData.

/**
 * Decode BulkRequestData Json Sting.
 *
 * @param bulkResourceString
 * @return BulkRequestData Object
 */
public BulkRequestData decodeBulkData(String bulkResourceString) throws BadRequestException {
    BulkRequestData bulkRequestDataObject = new BulkRequestData();
    List<BulkRequestContent> usersEndpointOperationList = new ArrayList<BulkRequestContent>();
    List<BulkRequestContent> groupsEndpointOperationList = new ArrayList<BulkRequestContent>();
    int failOnErrorsAttribute = 0;
    List<String> schemas = new ArrayList<String>();
    JSONObject decodedObject = null;
    try {
        decodedObject = new JSONObject(new JSONTokener(bulkResourceString));
        // prepare the schema list
        JSONArray membersAttributeSchemas = (JSONArray) decodedObject.opt(SCIMConstants.CommonSchemaConstants.SCHEMAS);
        for (int i = 0; i < membersAttributeSchemas.length(); i++) {
            schemas.add(membersAttributeSchemas.get(i).toString());
        }
        bulkRequestDataObject.setSchemas(schemas);
        // get [operations] from the Json String and prepare the request List
        JSONArray membersAttributeOperations = (JSONArray) decodedObject.opt(SCIMConstants.OperationalConstants.OPERATIONS);
        for (int i = 0; i < membersAttributeOperations.length(); i++) {
            JSONObject member = (JSONObject) membersAttributeOperations.get(i);
            // Request path - /Users or /Groups
            String requestType = member.optString(SCIMConstants.OperationalConstants.PATH);
            if (requestType == null) {
                throw new BadRequestException("Missing required attribute : path", ResponseCodeConstants.INVALID_SYNTAX);
            }
            // Request method  - POST,PUT..etc
            String requestMethod = member.optString(SCIMConstants.OperationalConstants.METHOD);
            if (requestMethod == null) {
                throw new BadRequestException("Missing required attribute : method", ResponseCodeConstants.INVALID_SYNTAX);
            }
            // Request version
            String requestVersion = member.optString(SCIMConstants.OperationalConstants.VERSION);
            if (requestMethod.equals(SCIMConstants.OperationalConstants.POST)) {
                if (!member.optString(SCIMConstants.OperationalConstants.BULK_ID).equals("") && member.optString(SCIMConstants.OperationalConstants.BULK_ID) != null) {
                    setRequestData(requestType, requestMethod, requestVersion, member, usersEndpointOperationList, groupsEndpointOperationList);
                } else {
                    String error = "JSON string could not be decoded properly.Required " + "attribute BULK_ID is missing in the request";
                    logger.error(error);
                    throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE);
                }
            } else {
                setRequestData(requestType, requestMethod, requestVersion, member, usersEndpointOperationList, groupsEndpointOperationList);
            }
        }
        // extract [failOnErrors] attribute from Json string
        failOnErrorsAttribute = decodedObject.optInt(SCIMConstants.OperationalConstants.FAIL_ON_ERRORS);
        bulkRequestDataObject.setFailOnErrors(failOnErrorsAttribute);
        bulkRequestDataObject.setUserOperationRequests(usersEndpointOperationList);
        bulkRequestDataObject.setGroupOperationRequests(groupsEndpointOperationList);
    } catch (JSONException e1) {
        String error = "JSON string could not be decoded properly.";
        logger.error(error);
        throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
    }
    return bulkRequestDataObject;
}
Also used : JSONTokener(org.json.JSONTokener) BulkRequestData(org.wso2.charon3.core.objects.bulk.BulkRequestData) JSONObject(org.json.JSONObject) BulkRequestContent(org.wso2.charon3.core.objects.bulk.BulkRequestContent) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) JSONException(org.json.JSONException)

Example 57 with BadRequestException

use of org.wso2.charon3.core.exceptions.BadRequestException in project charon by wso2.

the class JSONDecoder method decode.

public AbstractSCIMObject decode(String scimResourceString, SCIMResourceTypeSchema schema) throws CharonException, BadRequestException {
    try {
        JSONObject decodedJsonObj = new JSONObject(new JSONTokener(scimResourceString));
        AbstractSCIMObject scimObject = null;
        if (schema.getSchemasList().contains(SCIMConstants.GROUP_CORE_SCHEMA_URI)) {
            scimObject = (AbstractSCIMObject) decodeResource(decodedJsonObj.toString(), schema, new Group());
        } else {
            scimObject = (AbstractSCIMObject) decodeResource(decodedJsonObj.toString(), schema, new User());
        }
        return scimObject;
    } catch (JSONException | InternalErrorException | CharonException e) {
        throw new CharonException("Error in decoding the request", e);
    } catch (BadRequestException e) {
        throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
    }
}
Also used : JSONTokener(org.json.JSONTokener) AbstractSCIMObject(org.wso2.charon3.core.objects.AbstractSCIMObject) Group(org.wso2.charon3.core.objects.Group) User(org.wso2.charon3.core.objects.User) JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) CharonException(org.wso2.charon3.core.exceptions.CharonException)

Example 58 with BadRequestException

use of org.wso2.charon3.core.exceptions.BadRequestException in project charon by wso2.

the class JSONEncoder method encodeSCIMException.

/*
     * encode scim exceptions
     * @param exception
     * @return
     */
public String encodeSCIMException(AbstractCharonException exception) {
    // outer most json object
    JSONObject rootErrorObject = new JSONObject();
    // JSON Object containing the error code and error message
    JSONObject errorObject = new JSONObject();
    try {
        // construct error object with details in the exception
        errorObject.put(ResponseCodeConstants.SCHEMAS, exception.getSchemas());
        if (exception instanceof BadRequestException) {
            errorObject.put(ResponseCodeConstants.SCIM_TYPE, ((BadRequestException) (exception)).getScimType());
        }
        errorObject.put(ResponseCodeConstants.DETAIL, String.valueOf(exception.getDetail()));
        errorObject.put(ResponseCodeConstants.STATUS, String.valueOf(exception.getStatus()));
        // construct the full json obj.
        rootErrorObject = errorObject;
    } catch (JSONException e) {
        // usually errors occur rarely when encoding exceptions. and no need to pass them to clients.
        // sufficient to log them in server side back end.
        logger.error("SCIMException encoding error");
    }
    return rootErrorObject.toString();
}
Also used : JSONObject(org.json.JSONObject) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) JSONException(org.json.JSONException)

Example 59 with BadRequestException

use of org.wso2.charon3.core.exceptions.BadRequestException in project charon by wso2.

the class BulkResourceManager method processBulkData.

public SCIMResponse processBulkData(String data, UserManager userManager) {
    BulkResponseData bulkResponseData;
    try {
        // Get encoder and decoder from AbstractResourceEndpoint
        encoder = getEncoder();
        decoder = getDecoder();
        BulkRequestData bulkRequestDataObject;
        // decode the request
        bulkRequestDataObject = decoder.decodeBulkData(data);
        bulkRequestProcessor.setFailOnError(bulkRequestDataObject.getFailOnErrors());
        bulkRequestProcessor.setUserManager(userManager);
        // Get bulk response data
        bulkResponseData = bulkRequestProcessor.processBulkRequests(bulkRequestDataObject);
        // encode the BulkResponseData object
        String finalEncodedResponse = encoder.encodeBulkResponseData(bulkResponseData);
        // careate SCIM response message
        Map<String, String> responseHeaders = new HashMap<String, String>();
        // add location header
        responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
        // create the final response
        return new SCIMResponse(ResponseCodeConstants.CODE_OK, finalEncodedResponse, responseHeaders);
    } catch (CharonException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (BadRequestException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    }
}
Also used : BulkRequestData(org.wso2.charon3.core.objects.bulk.BulkRequestData) HashMap(java.util.HashMap) BulkResponseData(org.wso2.charon3.core.objects.bulk.BulkResponseData) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) CharonException(org.wso2.charon3.core.exceptions.CharonException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse)

Example 60 with BadRequestException

use of org.wso2.charon3.core.exceptions.BadRequestException in project charon by wso2.

the class GroupResourceManager method listWithPOST.

/*
     * this facilitates the querying using HTTP POST
     * @param resourceString
     * @param usermanager
     * @return
     */
@Override
public SCIMResponse listWithPOST(String resourceString, UserManager userManager) {
    JSONEncoder encoder = null;
    JSONDecoder decoder = null;
    try {
        // obtain the json encoder
        encoder = getEncoder();
        // obtain the json decoder
        decoder = getDecoder();
        // return core group schema
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getGroupResourceSchema();
        // create the search request object
        SearchRequest searchRequest = decoder.decodeSearchRequestBody(resourceString, schema);
        searchRequest.setCount(ResourceManagerUtil.processCount(searchRequest.getCountStr()));
        searchRequest.setStartIndex(ResourceManagerUtil.processCount(searchRequest.getStartIndexStr()));
        if (searchRequest.getSchema() != null && !searchRequest.getSchema().equals(SCIMConstants.SEARCH_SCHEMA_URI)) {
            throw new BadRequestException("Provided schema is invalid", ResponseCodeConstants.INVALID_VALUE);
        }
        // check whether provided sortOrder is valid or not
        if (searchRequest.getSortOder() != null) {
            if (!(searchRequest.getSortOder().equalsIgnoreCase(SCIMConstants.OperationalConstants.ASCENDING) || searchRequest.getSortOder().equalsIgnoreCase(SCIMConstants.OperationalConstants.DESCENDING))) {
                String error = " Invalid sortOrder value is specified";
                throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE);
            }
        }
        // ascending.
        if (searchRequest.getSortOder() == null && searchRequest.getSortBy() != null) {
            searchRequest.setSortOder(SCIMConstants.OperationalConstants.ASCENDING);
        }
        // get the URIs of required attributes which must be given a value
        Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs((SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), searchRequest.getAttributesAsString(), searchRequest.getExcludedAttributesAsString());
        List<Object> returnedGroups;
        int totalResults = 0;
        // API user should pass a usermanager usermanager to UserResourceEndpoint.
        if (userManager != null) {
            List<Object> tempList = userManager.listGroupsWithPost(searchRequest, requiredAttributes);
            totalResults = (int) tempList.get(0);
            tempList.remove(0);
            returnedGroups = tempList;
            for (Object group : returnedGroups) {
                // perform service provider side validation.
                ServerSideValidator.validateRetrievedSCIMObjectInList((Group) group, schema, searchRequest.getAttributesAsString(), searchRequest.getExcludedAttributesAsString());
            }
            // create a listed resource object out of the returned users list.
            ListedResource listedResource = createListedResource(returnedGroups, searchRequest.getStartIndex(), totalResults);
            // convert the listed resource into specific format.
            String encodedListedResource = encoder.encodeSCIMObject(listedResource);
            // if there are any http headers to be added in the response header.
            Map<String, String> responseHeaders = new HashMap<String, String>();
            responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
            return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedListedResource, responseHeaders);
        } else {
            String error = "Provided user manager handler is null.";
            // throw internal server error.
            throw new InternalErrorException(error);
        }
    } catch (CharonException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (NotFoundException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (BadRequestException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (NotImplementedException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    }
}
Also used : SearchRequest(org.wso2.charon3.core.utils.codeutils.SearchRequest) HashMap(java.util.HashMap) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) JSONDecoder(org.wso2.charon3.core.encoder.JSONDecoder) ListedResource(org.wso2.charon3.core.objects.ListedResource) BadRequestException(org.wso2.charon3.core.exceptions.BadRequestException) JSONEncoder(org.wso2.charon3.core.encoder.JSONEncoder) SCIMResourceTypeSchema(org.wso2.charon3.core.schema.SCIMResourceTypeSchema) CharonException(org.wso2.charon3.core.exceptions.CharonException) SCIMResponse(org.wso2.charon3.core.protocol.SCIMResponse)

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 HashMap (java.util.HashMap)23 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)23 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 JSONException (org.json.JSONException)17 JSONObject (org.json.JSONObject)17 AbstractSCIMObject (org.wso2.charon3.core.objects.AbstractSCIMObject)16 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 ArrayList (java.util.ArrayList)9