Search in sources :

Example 11 with InternalErrorException

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

the class ServiceProviderConfigResourceManager method getServiceProviderConfig.

private SCIMResponse getServiceProviderConfig() {
    JSONEncoder encoder = null;
    try {
        // obtain the json encoder
        encoder = getEncoder();
        // obtain the json decoder
        JSONDecoder decoder = getDecoder();
        // get the service provider config schema
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getServiceProviderConfigResourceSchema();
        // create a string in json format with relevant values
        String scimObjectString = encoder.buildServiceProviderConfigJsonBody(CharonConfiguration.getInstance().getConfig());
        // decode the SCIM service provider config object, encoded in the submitted payload.
        AbstractSCIMObject serviceProviderConfigObject = (AbstractSCIMObject) decoder.decodeResource(scimObjectString, schema, new AbstractSCIMObject());
        // encode the newly created SCIM service provider config object and add id attribute to Location header.
        String encodedObject;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        if (serviceProviderConfigObject != null) {
            // create a deep copy of the service provider config object since we are going to change it.
            AbstractSCIMObject copiedObject = (AbstractSCIMObject) CopyUtil.deepCopy(serviceProviderConfigObject);
            encodedObject = encoder.encodeSCIMObject(copiedObject);
            // add location header
            responseHeaders.put(SCIMConstants.LOCATION_HEADER, getResourceEndpointURL(SCIMConstants.SERVICE_PROVIDER_CONFIG_ENDPOINT));
            responseHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
        } else {
            String error = "Newly created User resource is null.";
            throw new InternalErrorException(error);
        }
        // put the uri of the service provider config object in the response header parameter.
        return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedObject, responseHeaders);
    } catch (CharonException e) {
        return encodeSCIMException(e);
    } catch (BadRequestException e) {
        return encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return encodeSCIMException(e);
    } catch (NotFoundException e) {
        return encodeSCIMException(e);
    } catch (JSONException e) {
        return null;
    }
}
Also used : AbstractSCIMObject(org.wso2.charon3.core.objects.AbstractSCIMObject) HashMap(java.util.HashMap) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) JSONException(org.json.JSONException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) JSONDecoder(org.wso2.charon3.core.encoder.JSONDecoder) 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)

Example 12 with InternalErrorException

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

the class UserResourceManager method updateWithPUT.

/*
     * To update the user by giving entire attribute set
     *
     * @param existingId
     * @param scimObjectString
     * @param usermanager
     * @return
     */
public SCIMResponse updateWithPUT(String existingId, String scimObjectString, UserManager userManager, String attributes, String excludeAttributes) {
    // needs to validate the incoming object. eg: id can not be set by the consumer.
    JSONEncoder encoder = null;
    JSONDecoder decoder = null;
    try {
        // obtain the json encoder
        encoder = getEncoder();
        // obtain the json decoder.
        decoder = getDecoder();
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema();
        // get the URIs of required attributes which must be given a value
        Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs((SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes);
        // decode the SCIM User object, encoded in the submitted payload.
        User user = (User) decoder.decodeResource(scimObjectString, schema, new User());
        User updatedUser = null;
        if (userManager != null) {
            // retrieve the old object
            User oldUser = userManager.getUser(existingId, ResourceManagerUtil.getAllAttributeURIs(schema));
            if (oldUser != null) {
                User validatedUser = (User) ServerSideValidator.validateUpdatedSCIMObject(oldUser, user, schema);
                updatedUser = userManager.updateUser(validatedUser, requiredAttributes);
            } else {
                String error = "No user exists with the given id: " + existingId;
                throw new NotFoundException(error);
            }
        } else {
            String error = "Provided user manager handler is null.";
            throw new InternalErrorException(error);
        }
        // encode the newly created SCIM user object and add id attribute to Location header.
        String encodedUser;
        Map<String, String> httpHeaders = new HashMap<String, String>();
        if (updatedUser != null) {
            // create a deep copy of the user object since we are going to change it.
            User copiedUser = (User) CopyUtil.deepCopy(updatedUser);
            // need to remove password before returning
            ServerSideValidator.validateReturnedAttributes(copiedUser, attributes, excludeAttributes);
            encodedUser = encoder.encodeSCIMObject(copiedUser);
            // add location header
            httpHeaders.put(SCIMConstants.LOCATION_HEADER, getResourceEndpointURL(SCIMConstants.USER_ENDPOINT) + "/" + updatedUser.getId());
            httpHeaders.put(SCIMConstants.CONTENT_TYPE_HEADER, SCIMConstants.APPLICATION_JSON);
        } else {
            String error = "Updated User resource is null.";
            throw new CharonException(error);
        }
        // put the uri of the User object in the response header parameter.
        return new SCIMResponse(ResponseCodeConstants.CODE_OK, encodedUser, httpHeaders);
    } catch (NotFoundException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (BadRequestException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (CharonException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (InternalErrorException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    } catch (NotImplementedException e) {
        return AbstractResourceManager.encodeSCIMException(e);
    }
}
Also used : User(org.wso2.charon3.core.objects.User) 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) 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)

Example 13 with InternalErrorException

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

the class UserResourceManager method listWithPOST.

/*
     * this facilitates the querying using HTTP POST
     * @param resourceString
     * @param usermanager
     * @return
     */
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();
        // unless configured returns core-user schema or else returns extended user schema)
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema();
        // create the search request object
        SearchRequest searchRequest = decoder.decodeSearchRequestBody(resourceString, schema);
        searchRequest.setCount(ResourceManagerUtil.processCount(searchRequest.getCountStr()));
        searchRequest.setStartIndex(ResourceManagerUtil.processCount(searchRequest.getStartIndexStr()));
        // 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> returnedUsers;
        int totalResults = 0;
        // API user should pass a usermanager usermanager to UserResourceEndpoint.
        if (userManager != null) {
            List<Object> tempList = userManager.listUsersWithPost(searchRequest, requiredAttributes);
            totalResults = (int) tempList.get(0);
            tempList.remove(0);
            returnedUsers = tempList;
            for (Object user : returnedUsers) {
                // perform service provider side validation.
                ServerSideValidator.validateRetrievedSCIMObjectInList((User) user, schema, searchRequest.getAttributesAsString(), searchRequest.getExcludedAttributesAsString());
            }
            // create a listed resource object out of the returned users list.
            ListedResource listedResource = createListedResource(returnedUsers, 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)

Example 14 with InternalErrorException

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

the class UserResourceManager method listWithGET.

/*
     * To list all the resources of resource endpoint.
     *
     * @param usermanager
     * @param filter
     * @param startIndex
     * @param count
     * @param sortBy
     * @param sortOrder
     * @param attributes
     * @param excludeAttributes
     * @return
     */
public SCIMResponse listWithGET(UserManager userManager, String filter, int startIndex, int count, String sortBy, String sortOrder, String attributes, String excludeAttributes) {
    FilterTreeManager filterTreeManager = null;
    Node rootNode = null;
    JSONEncoder encoder = null;
    try {
        // According to SCIM 2.0 spec minus values will be considered as 0
        if (count < 0) {
            count = 0;
        }
        // According to SCIM 2.0 spec minus values will be considered as 1
        if (startIndex < 1) {
            startIndex = 1;
        }
        if (sortOrder != null) {
            if (!(sortOrder.equalsIgnoreCase(SCIMConstants.OperationalConstants.ASCENDING) || sortOrder.equalsIgnoreCase(SCIMConstants.OperationalConstants.DESCENDING))) {
                String error = " Invalid sortOrder value is specified";
                throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE);
            }
        }
        // ascending.
        if (sortOrder == null && sortBy != null) {
            sortOrder = SCIMConstants.OperationalConstants.ASCENDING;
        }
        // unless configured returns core-user schema or else returns extended user schema)
        SCIMResourceTypeSchema schema = SCIMResourceSchemaManager.getInstance().getUserResourceSchema();
        if (filter != null) {
            filterTreeManager = new FilterTreeManager(filter, schema);
            rootNode = filterTreeManager.buildTree();
        }
        // obtain the json encoder
        encoder = getEncoder();
        // get the URIs of required attributes which must be given a value
        Map<String, Boolean> requiredAttributes = ResourceManagerUtil.getOnlyRequiredAttributesURIs((SCIMResourceTypeSchema) CopyUtil.deepCopy(schema), attributes, excludeAttributes);
        List<Object> returnedUsers;
        int totalResults = 0;
        // API user should pass a usermanager usermanager to UserResourceEndpoint.
        if (userManager != null) {
            List<Object> tempList = userManager.listUsersWithGET(rootNode, startIndex, count, sortBy, sortOrder, requiredAttributes);
            totalResults = (int) tempList.get(0);
            tempList.remove(0);
            returnedUsers = tempList;
            for (Object user : returnedUsers) {
                // perform service provider side validation.
                ServerSideValidator.validateRetrievedSCIMObjectInList((User) user, schema, attributes, excludeAttributes);
            }
            // create a listed resource object out of the returned users list.
            ListedResource listedResource = createListedResource(returnedUsers, startIndex, 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);
    } catch (IOException e) {
        String error = "Error in tokenization of the input filter";
        CharonException charonException = new CharonException(error);
        return AbstractResourceManager.encodeSCIMException(charonException);
    }
}
Also used : HashMap(java.util.HashMap) Node(org.wso2.charon3.core.utils.codeutils.Node) NotImplementedException(org.wso2.charon3.core.exceptions.NotImplementedException) NotFoundException(org.wso2.charon3.core.exceptions.NotFoundException) InternalErrorException(org.wso2.charon3.core.exceptions.InternalErrorException) IOException(java.io.IOException) FilterTreeManager(org.wso2.charon3.core.utils.codeutils.FilterTreeManager) 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)

Example 15 with InternalErrorException

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

the class JSONDecoder method decodeResource.

/**
 * Decode the resource string sent in the SCIM request payload.
 *
 * @param scimResourceString - json encoded string of user info
 * @param resourceSchema     - SCIM defined user schema
 * @param scimObject         - a container holding the attributes and schema list
 * @return SCIMObject
 */
public SCIMObject decodeResource(String scimResourceString, ResourceTypeSchema resourceSchema, AbstractSCIMObject scimObject) throws BadRequestException, CharonException, InternalErrorException {
    try {
        // decode the string into json representation
        JSONObject decodedJsonObj = new JSONObject(new JSONTokener(scimResourceString));
        // get the attribute schemas list from the schema that defines the given resource
        List<AttributeSchema> attributeSchemas = resourceSchema.getAttributesList();
        // set the schemas in scimobject
        for (int i = 0; i < resourceSchema.getSchemasList().size(); i++) {
            scimObject.setSchema(resourceSchema.getSchemasList().get(i));
        }
        // iterate through the schema and extract the attributes.
        for (AttributeSchema attributeSchema : attributeSchemas) {
            // obtain the user defined value for given key- attribute schema name
            Object attributeValObj = decodedJsonObj.opt(attributeSchema.getName());
            if (attributeValObj == null) {
                // user may define the attribute by its fully qualified uri
                attributeValObj = decodedJsonObj.opt(attributeSchema.getURI());
            }
            SCIMDefinitions.DataType attributeSchemaDataType = attributeSchema.getType();
            if (attributeSchemaDataType.equals(STRING) || attributeSchemaDataType.equals(BINARY) || attributeSchemaDataType.equals(BOOLEAN) || attributeSchemaDataType.equals(DATE_TIME) || attributeSchemaDataType.equals(DECIMAL) || attributeSchemaDataType.equals(INTEGER) || attributeSchemaDataType.equals(REFERENCE)) {
                if (!attributeSchema.getMultiValued()) {
                    if (attributeValObj instanceof String || attributeValObj instanceof Boolean || attributeValObj instanceof Integer || attributeValObj == null) {
                        // If an attribute is passed without a value, no need to save it.
                        if (attributeValObj == null) {
                            continue;
                        }
                        // if the corresponding schema data type is String/Boolean/Binary/Decimal/Integer/DataTime
                        // or Reference, it is a SimpleAttribute.
                        scimObject.setAttribute(buildSimpleAttribute(attributeSchema, attributeValObj), resourceSchema);
                    } else {
                        logger.error("Error decoding the simple attribute");
                        throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
                    }
                } else {
                    if (attributeValObj instanceof JSONArray || attributeValObj == null) {
                        // If an attribute is passed without a value, no need to save it.
                        if (attributeValObj == null) {
                            continue;
                        }
                        scimObject.setAttribute(buildPrimitiveMultiValuedAttribute(attributeSchema, (JSONArray) attributeValObj), resourceSchema);
                    } else {
                        logger.error("Error decoding the primitive multivalued attribute");
                        throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
                    }
                }
            } else if (attributeSchemaDataType.equals(COMPLEX)) {
                if (attributeSchema.getMultiValued() == true) {
                    if (attributeValObj instanceof JSONArray || attributeValObj == null) {
                        if (attributeValObj == null) {
                            continue;
                        }
                        // if the corresponding json value object is JSONArray, it is a MultiValuedAttribute.
                        scimObject.setAttribute(buildComplexMultiValuedAttribute(attributeSchema, (JSONArray) attributeValObj), resourceSchema);
                    } else {
                        logger.error("Error decoding the complex multivalued attribute");
                        throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
                    }
                } else if (attributeSchema.getMultiValued() == false) {
                    if (attributeValObj instanceof JSONObject || attributeValObj == null) {
                        if (attributeValObj == null) {
                            continue;
                        }
                        // if the corresponding json value object is JSONObject, it is a ComplexAttribute.
                        scimObject.setAttribute(buildComplexAttribute(attributeSchema, (JSONObject) attributeValObj), resourceSchema);
                    } else {
                        logger.error("Error decoding the complex attribute");
                        throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
                    }
                }
            }
        }
        return scimObject;
    } catch (JSONException e) {
        logger.error("json error in decoding the resource");
        throw new BadRequestException(ResponseCodeConstants.INVALID_SYNTAX);
    }
}
Also used : JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) SCIMDefinitions(org.wso2.charon3.core.schema.SCIMDefinitions) JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) AttributeSchema(org.wso2.charon3.core.schema.AttributeSchema) SCIMAttributeSchema(org.wso2.charon3.core.schema.SCIMAttributeSchema) 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)25 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)20 CharonException (org.wso2.charon3.core.exceptions.CharonException)19 HashMap (java.util.HashMap)17 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)16 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)16 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)15 JSONDecoder (org.wso2.charon3.core.encoder.JSONDecoder)14 JSONEncoder (org.wso2.charon3.core.encoder.JSONEncoder)12 NotImplementedException (org.wso2.charon3.core.exceptions.NotImplementedException)12 JSONException (org.json.JSONException)9 JSONObject (org.json.JSONObject)8 User (org.wso2.charon3.core.objects.User)8 AbstractSCIMObject (org.wso2.charon3.core.objects.AbstractSCIMObject)7 AttributeSchema (org.wso2.charon3.core.schema.AttributeSchema)6 JSONArray (org.json.JSONArray)5 Attribute (org.wso2.charon3.core.attributes.Attribute)5 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)5 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)5 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)5