Search in sources :

Example 21 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project carbon-identity-framework by wso2.

the class ChallengeQuestionProcessor method setChallengesOfUser.

/**
 * @param userName
 * @param tenantId
 * @param challengesDTOs
 * @throws IdentityException
 */
public void setChallengesOfUser(String userName, int tenantId, UserChallengesDTO[] challengesDTOs) throws IdentityException {
    try {
        if (log.isDebugEnabled()) {
            log.debug("Challenge Question from the user profile.");
        }
        List<String> challengesUris = new ArrayList<String>();
        String challengesUrisValue = "";
        String separator = IdentityMgtConfig.getInstance().getChallengeQuestionSeparator();
        Map<String, String> oldClaims = new HashMap<String, String>();
        Map<String, String> newClaims = new HashMap<String, String>();
        String[] requestclaims = new String[challengesDTOs.length];
        int x = 0;
        for (UserChallengesDTO claimDto : challengesDTOs) {
            requestclaims[x++] = claimDto.getId();
        }
        // Getting user store manager here to reduce the calls for claim retrieval.
        // TODO need to put into a new method in a new release version. Used to avoid API changes in patch.
        org.wso2.carbon.user.core.UserStoreManager userStoreManager = null;
        RealmService realmService = IdentityMgtServiceComponent.getRealmService();
        try {
            if (realmService.getTenantUserRealm(tenantId) != null) {
                userStoreManager = (org.wso2.carbon.user.core.UserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager();
            }
        } catch (Exception e) {
            String msg = "Error retrieving the user store manager for the tenant";
            log.error(msg, e);
            throw IdentityException.error(msg, e);
        }
        if (userStoreManager != null) {
            oldClaims = userStoreManager.getUserClaimValues(userName, requestclaims, null);
        }
        if (!ArrayUtils.isEmpty(challengesDTOs)) {
            for (UserChallengesDTO dto : challengesDTOs) {
                if (dto.getId() != null && dto.getQuestion() != null && dto.getAnswer() != null) {
                    String oldClaimValue = oldClaims.get(dto.getId());
                    if ((oldClaimValue != null) && oldClaimValue.contains(separator)) {
                        String oldAnswer = oldClaimValue.split(separator)[1];
                        if (!oldAnswer.trim().equals(dto.getAnswer().trim())) {
                            String claimValue = dto.getQuestion().trim() + separator + Utils.doHash(dto.getAnswer().trim().toLowerCase());
                            if (!oldClaimValue.equals(claimValue)) {
                                newClaims.put(dto.getId().trim(), claimValue);
                            }
                        }
                    } else {
                        String claimValue = dto.getQuestion().trim() + separator + Utils.doHash(dto.getAnswer().trim().toLowerCase());
                        newClaims.put(dto.getId().trim(), claimValue);
                    }
                    challengesUris.add(dto.getId().trim());
                }
            }
            for (String challengesUri : challengesUris) {
                if ("".equals(challengesUrisValue)) {
                    challengesUrisValue = challengesUri;
                } else {
                    challengesUrisValue = challengesUrisValue + IdentityMgtConfig.getInstance().getChallengeQuestionSeparator() + challengesUri;
                }
            }
            newClaims.put("http://wso2.org/claims/challengeQuestionUris", challengesUrisValue);
            // Single call to save all challenge questions.
            userStoreManager.setUserClaimValues(userName, newClaims, UserCoreConstants.DEFAULT_PROFILE);
        }
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String msg = "No associated challenge question found for the user";
        throw IdentityException.error(msg, e);
    }
}
Also used : UserChallengesDTO(org.wso2.carbon.identity.mgt.dto.UserChallengesDTO) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) UserStoreException(org.wso2.carbon.user.core.UserStoreException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) IdentityException(org.wso2.carbon.identity.base.IdentityException) RealmService(org.wso2.carbon.user.core.service.RealmService)

Example 22 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project carbon-mediation by wso2.

the class OpenAPIProcessor method getUpdatedSwaggerFromApi.

/**
 * Update a given swagger definition of the Synapse API.
 *
 * @param existingSwagger swagger definition needs to be updated.
 * @param isJSONIn        input swagger data type JSON / YAML.
 * @param isJSONOut       output swagger data type JSON / YAML.
 * @return updated swagger definition as string.
 */
public String getUpdatedSwaggerFromApi(String existingSwagger, boolean isJSONIn, boolean isJSONOut) throws APIGenException {
    if (api == null) {
        throw new APIGenException("Provided API is null");
    }
    if (StringUtils.isEmpty(existingSwagger)) {
        throw new APIGenException("Provided swagger definition is empty");
    }
    if (isJSONIn) {
        JsonNode jsonNodeTree = null;
        try {
            jsonNodeTree = new ObjectMapper().readTree(existingSwagger);
            existingSwagger = new YAMLMapper().writeValueAsString(jsonNodeTree);
        } catch (JsonProcessingException e) {
            throw new APIGenException("Error occurred while converting the swagger to YAML format", e);
        }
    }
    OpenAPIV3Parser apiv3Parser = new OpenAPIV3Parser();
    SwaggerParseResult swaggerParseResult = apiv3Parser.readContents(existingSwagger);
    OpenAPI openAPI = swaggerParseResult.getOpenAPI();
    Paths paths = openAPI.getPaths();
    Paths newPaths = new Paths();
    final Map<String, Object> dataMap = GenericApiObjectDefinition.getPathMap(api);
    for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
        boolean pathItemExists = false;
        PathItem pathItem;
        if (paths.containsKey(entry.getKey())) {
            pathItem = paths.get(entry.getKey());
            pathItemExists = true;
        } else {
            pathItem = new PathItem();
        }
        Map<String, Object> methodMap = (Map<String, Object>) entry.getValue();
        List<String> newMethodsList = new ArrayList<>();
        for (Map.Entry<String, Object> methodEntry : methodMap.entrySet()) {
            Operation operation = null;
            boolean operationExists = false;
            if (pathItemExists) {
                newMethodsList.add(methodEntry.getKey());
                switch(methodEntry.getKey()) {
                    case OPERATION_HTTP_GET:
                        operation = pathItem.getGet();
                        break;
                    case OPERATION_HTTP_POST:
                        operation = pathItem.getPost();
                        break;
                    case OPERATION_HTTP_DELETE:
                        operation = pathItem.getDelete();
                        break;
                    case OPERATION_HTTP_PUT:
                        operation = pathItem.getPut();
                        break;
                    case OPERATION_HTTP_HEAD:
                        operation = pathItem.getHead();
                        break;
                    case OPERATION_HTTP_PATCH:
                        operation = pathItem.getPatch();
                        break;
                    case OPERATION_HTTP_OPTIONS:
                        operation = pathItem.getOptions();
                }
            }
            if (operation == null) {
                operation = new Operation();
            } else {
                operationExists = true;
            }
            Object[] paramArr = (Object[]) ((Map<String, Object>) methodEntry.getValue()).get(PARAMETERS);
            if (operationExists) {
                List<Parameter> parameters = operation.getParameters();
                List<Parameter> newParameter = new ArrayList<>();
                if (paramArr != null && paramArr.length > 0) {
                    for (Object o : paramArr) {
                        String paramType = (String) ((Map<String, Object>) o).get(PARAMETER_IN);
                        String paramName = (String) ((Map<String, Object>) o).get(PARAMETER_NAME);
                        Optional<Parameter> existing = null;
                        switch(paramType) {
                            case PARAMETER_IN_PATH:
                                existing = parameters.stream().filter(c -> c.getName().equals(paramName) && c instanceof PathParameter).findFirst();
                                break;
                            case PARAMETER_IN_QUERY:
                                existing = parameters.stream().filter(c -> c.getName().equals(paramName) && c instanceof QueryParameter).findFirst();
                                break;
                        }
                        if (existing == null || !existing.isPresent()) {
                            // if we found parameter do not update
                            updatePathQueryAndBodyParams(operation, paramType, paramName, newParameter);
                        } else {
                            newParameter.add(existing.get());
                        }
                        updateDefaultResponseAndPathItem(pathItem, operation, methodEntry, operationExists);
                    }
                } else {
                    // no parameters defined ( default resource in the API )
                    updateDefaultResponseAndPathItem(pathItem, operation, methodEntry, operationExists);
                }
                // remove deleted parameters from swagger
                if (newParameter.size() > 0) {
                    parameters.removeIf(c -> !newParameter.contains(c));
                }
            } else {
                populateParameters(pathItem, methodMap);
            }
        }
        if (pathItemExists) {
            // Remove additional methods
            List<String> allMethodsList = Arrays.asList(new String[] { "get", "post", "put", "delete", "head", "options", "patch" });
            List<String> differences = allMethodsList.stream().filter(element -> !newMethodsList.contains(element)).collect(Collectors.toList());
            for (String method : differences) {
                switch(method) {
                    case OPERATION_HTTP_GET:
                        pathItem.setGet(null);
                        break;
                    case OPERATION_HTTP_POST:
                        pathItem.setPost(null);
                        break;
                    case OPERATION_HTTP_DELETE:
                        pathItem.setDelete(null);
                        break;
                    case OPERATION_HTTP_PUT:
                        pathItem.setPut(null);
                        break;
                    case OPERATION_HTTP_HEAD:
                        pathItem.setHead(null);
                        break;
                    case OPERATION_HTTP_PATCH:
                        pathItem.setPatch(null);
                        break;
                    case OPERATION_HTTP_OPTIONS:
                        pathItem.setOptions(null);
                        break;
                }
            }
        }
        newPaths.put(entry.getKey(), pathItem);
    }
    // Adding the new path map
    openAPI.setPaths(newPaths);
    updateInfoSection(openAPI);
    try {
        updateServersSection(openAPI);
    } catch (AxisFault axisFault) {
        throw new APIGenException("Error occurred while getting host details", axisFault);
    }
    try {
        if (isJSONOut) {
            return Json.mapper().writeValueAsString(openAPI);
        }
        return Yaml.mapper().writeValueAsString(openAPI);
    } catch (JsonProcessingException e) {
        throw new APIGenException("Error occurred while creating the output JAML/JSON", e);
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) Arrays(java.util.Arrays) OPERATION_HTTP_PATCH(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_PATCH) Yaml(io.swagger.v3.core.util.Yaml) URL(java.net.URL) Parameter(io.swagger.v3.oas.models.parameters.Parameter) Operation(io.swagger.v3.oas.models.Operation) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) URLBasedVersionStrategy(org.apache.synapse.api.version.URLBasedVersionStrategy) PROTOCOL_HTTP_ONLY(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PROTOCOL_HTTP_ONLY) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Content(io.swagger.v3.oas.models.media.Content) API(org.apache.synapse.api.API) PROTOCOL_HTTP(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PROTOCOL_HTTP) MediaType(io.swagger.v3.oas.models.media.MediaType) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody) Paths(io.swagger.v3.oas.models.Paths) Collectors(java.util.stream.Collectors) OPERATION_HTTP_PUT(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_PUT) PARAMETER_IN_BODY(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_IN_BODY) List(java.util.List) Server(io.swagger.v3.oas.models.servers.Server) StringSchema(io.swagger.v3.oas.models.media.StringSchema) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) PARAMETER_IN_PATH(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_IN_PATH) Optional(java.util.Optional) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) AxisFault(org.apache.axis2.AxisFault) LogFactory(org.apache.commons.logging.LogFactory) OPERATION_HTTP_HEAD(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_HEAD) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PROTOCOL_HTTP_AND_HTTPS(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PROTOCOL_HTTP_AND_HTTPS) PARAMETERS(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETERS) Json(io.swagger.v3.core.util.Json) PARAMETER_NAME(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_NAME) HashMap(java.util.HashMap) OPERATION_HTTP_OPTIONS(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_OPTIONS) ArrayList(java.util.ArrayList) OpenAPI(io.swagger.v3.oas.models.OpenAPI) OPERATION_HTTP_GET(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_GET) Schema(io.swagger.v3.oas.models.media.Schema) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) OPERATION_HTTP_DELETE(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_DELETE) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) PARAMETER_IN(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_IN) MalformedURLException(java.net.MalformedURLException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PathItem(io.swagger.v3.oas.models.PathItem) Info(io.swagger.v3.oas.models.info.Info) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PARAMETER_IN_QUERY(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PARAMETER_IN_QUERY) PROTOCOL_HTTPS(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.PROTOCOL_HTTPS) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) Log(org.apache.commons.logging.Log) OPERATION_HTTP_POST(org.wso2.carbon.mediation.commons.rest.api.swagger.SwaggerConstants.OPERATION_HTTP_POST) AxisFault(org.apache.axis2.AxisFault) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) Operation(io.swagger.v3.oas.models.Operation) OpenAPIV3Parser(io.swagger.v3.parser.OpenAPIV3Parser) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) PathItem(io.swagger.v3.oas.models.PathItem) Paths(io.swagger.v3.oas.models.Paths) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) YAMLMapper(com.fasterxml.jackson.dataformat.yaml.YAMLMapper) SwaggerParseResult(io.swagger.v3.parser.core.models.SwaggerParseResult) Parameter(io.swagger.v3.oas.models.parameters.Parameter) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) HashMap(java.util.HashMap)

Example 23 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project carbon-mediation by wso2.

the class CacheMediatorFactory method createSpecificMediator.

/**
 * {@inheritDoc}
 */
protected Mediator createSpecificMediator(OMElement elem, Properties properties) {
    if (!CachingConstants.CACHE_Q.equals(elem.getQName())) {
        handleException("Unable to create the cache mediator. Unexpected element as the cache mediator configuration");
    }
    CacheMediator cache = new CacheMediator(cacheManager);
    OMAttribute collectorAttr = elem.getAttribute(ATT_COLLECTOR);
    if (collectorAttr != null && collectorAttr.getAttributeValue() != null) {
        if ("true".equals(collectorAttr.getAttributeValue())) {
            cache.setCollector(true);
            OMAttribute scopeAttribute = elem.getAttribute(ATT_SCOPE);
            if (scopeAttribute != null && scopeAttribute.getAttributeValue() != null) {
                cache.setScope(scopeAttribute.getAttributeValue().trim());
            }
        } else if ("false".equals(collectorAttr.getAttributeValue())) {
            cache.setCollector(false);
            OMAttribute timeoutAttr = elem.getAttribute(ATT_TIMEOUT);
            if (timeoutAttr != null && timeoutAttr.getAttributeValue() != null) {
                cache.setTimeout(Long.parseLong(timeoutAttr.getAttributeValue().trim()));
            } else {
                cache.setTimeout(CachingConstants.DEFAULT_TIMEOUT);
            }
            OMAttribute maxMessageSizeAttr = elem.getAttribute(ATT_MAX_MSG_SIZE);
            if (maxMessageSizeAttr != null && maxMessageSizeAttr.getAttributeValue() != null) {
                cache.setMaxMessageSize(Integer.parseInt(maxMessageSizeAttr.getAttributeValue().trim()));
            } else {
                cache.setMaxMessageSize(-1);
            }
            OMAttribute idAttribute = elem.getAttribute(ATT_ID);
            if (idAttribute != null && idAttribute.getAttributeValue() != null) {
                cache.setId(idAttribute.getAttributeValue().trim());
            }
            OMAttribute hashGeneratorAttribute = elem.getAttribute(ATT_HASH_GENERATOR);
            if (hashGeneratorAttribute != null && hashGeneratorAttribute.getAttributeValue() != null) {
                cache.setHashGenerator(hashGeneratorAttribute.getAttributeValue().trim());
            }
            OMAttribute scopeAttribute = elem.getAttribute(ATT_SCOPE);
            if (scopeAttribute != null && scopeAttribute.getAttributeValue() != null) {
                cache.setScope(scopeAttribute.getAttributeValue().trim());
            }
            String className = null;
            OMElement protocolElem = elem.getFirstChildWithName(PROTOCOL_Q);
            Map<String, Object> props = new HashMap<>();
            if (protocolElem != null) {
                OMAttribute typeAttr = protocolElem.getAttribute(ATT_TYPE);
                if (typeAttr != null && typeAttr.getAttributeValue() != null) {
                    OMElement hashGeneratorElem = protocolElem.getFirstChildWithName(HASH_GENERATOR_Q);
                    if (hashGeneratorElem != null) {
                        className = hashGeneratorElem.getText();
                    }
                    String protocolType = typeAttr.getAttributeValue().toUpperCase().trim();
                    cache.setProtocolType(protocolType);
                    if (CachingConstants.HTTP_PROTOCOL_TYPE.equals(protocolType)) {
                        OMElement methodElem = protocolElem.getFirstChildWithName(HTTP_METHODS_TO_CACHE_Q);
                        if (methodElem != null) {
                            String[] methods = methodElem.getText().split(",");
                            if (!"".equals(methods[0])) {
                                for (int i = 0; i < methods.length; i++) {
                                    methods[i] = methods[i].toUpperCase().trim();
                                    if (!(PassThroughConstants.HTTP_POST.equals(methods[i]) || PassThroughConstants.HTTP_GET.equals(methods[i]) || PassThroughConstants.HTTP_HEAD.equals(methods[i]) || PassThroughConstants.HTTP_PUT.equals(methods[i]) || PassThroughConstants.HTTP_DELETE.equals(methods[i]) || PassThroughConstants.HTTP_OPTIONS.equals(methods[i]) || PassThroughConstants.HTTP_CONNECT.equals(methods[i]) || "PATCH".equals(methods[i]) || CachingConstants.ALL.equals(methods[i]))) {
                                        handleException("Unexpected method type: " + methods[i]);
                                    }
                                }
                                cache.setHTTPMethodsToCache(methods);
                            }
                        } else {
                            cache.setHTTPMethodsToCache(CachingConstants.ALL);
                        }
                        OMElement headersToIncludeInHash = protocolElem.getFirstChildWithName(HEADERS_TO_INCLUDE_IN_HASH_Q);
                        if (headersToIncludeInHash != null) {
                            String[] headers = headersToIncludeInHash.getText().split(",");
                            for (int i = 0; i < headers.length; i++) {
                                headers[i] = headers[i].trim();
                            }
                            cache.setHeadersToIncludeInHash(headers);
                        } else {
                            cache.setHeadersToIncludeInHash("");
                        }
                        OMElement headersToExcludeInHash = protocolElem.getFirstChildWithName(HEADERS_TO_EXCLUDE_IN_HASH_Q);
                        if (headersToExcludeInHash != null) {
                            String[] headers = headersToExcludeInHash.getText().split(",");
                            for (int i = 0; i < headers.length; i++) {
                                headers[i] = headers[i].trim();
                            }
                            cache.setHeadersToExcludeInHash(headers);
                        } else {
                            cache.setHeadersToExcludeInHash("");
                        }
                        OMElement responseCodesElem = protocolElem.getFirstChildWithName(RESPONSE_CODES_Q);
                        if (responseCodesElem != null) {
                            String responses = responseCodesElem.getText();
                            if (!"".equals(responses) && responses != null) {
                                cache.setResponseCodes(responses);
                            }
                        } else {
                            cache.setResponseCodes(CachingConstants.ANY_RESPONSE_CODE);
                        }
                        OMElement enableCacheControlElem = protocolElem.getFirstChildWithName(ENABLE_CACHE_CONTROL_Q);
                        if (enableCacheControlElem != null) {
                            String cacheControlElemText = enableCacheControlElem.getText();
                            if (StringUtils.isNotEmpty(cacheControlElemText)) {
                                cache.setCacheControlEnabled(Boolean.parseBoolean(cacheControlElemText));
                            }
                        } else {
                            cache.setCacheControlEnabled(CachingConstants.DEFAULT_ENABLE_CACHE_CONTROL);
                        }
                        OMElement addAgeHeaderElem = protocolElem.getFirstChildWithName(INCLUDE_AGE_HEADER_Q);
                        if (addAgeHeaderElem != null) {
                            String addAgeHeaderElemText = addAgeHeaderElem.getText();
                            if (StringUtils.isNotEmpty(addAgeHeaderElemText)) {
                                cache.setAddAgeHeaderEnabled(Boolean.parseBoolean(addAgeHeaderElemText));
                            }
                        } else {
                            cache.setCacheControlEnabled(CachingConstants.DEFAULT_ADD_AGE_HEADER);
                        }
                        props.put(CachingConstants.INCLUDED_HEADERS_PROPERTY, cache.getHeadersToIncludeInHash());
                        props.put(CachingConstants.EXCLUDED_HEADERS_PROPERTY, cache.getHeadersToExcludeInHash());
                    }
                } else {
                    cache.setProtocolType(CachingConstants.HTTP_PROTOCOL_TYPE);
                }
            } else {
                OMAttribute hashGeneratorAttr = elem.getAttribute(ATT_HASH_GENERATOR);
                if (hashGeneratorAttr != null && hashGeneratorAttr.getAttributeValue() != null) {
                    className = hashGeneratorAttr.getAttributeValue();
                }
            }
            if (className != null && !"".equals(className)) {
                try {
                    Class generator = Class.forName(className);
                    Object o = generator.newInstance();
                    if (o instanceof DigestGenerator) {
                        cache.setDigestGenerator((DigestGenerator) o);
                    } else {
                        handleException("Specified class for the hashGenerator is not a " + "DigestGenerator. It *must* implement " + "org.wso2.carbon.mediator.cache.digest.DigestGenerator interface");
                    }
                } catch (ClassNotFoundException e) {
                    handleException("Unable to load the hash generator class", e);
                } catch (IllegalAccessException e) {
                    handleException("Unable to access the hash generator class", e);
                } catch (InstantiationException e) {
                    handleException("Unable to instantiate the hash generator class", e);
                }
            } else {
                cache.setDigestGenerator(CachingConstants.DEFAULT_HASH_GENERATOR);
            }
            props.put(CachingConstants.PERMANENTLY_EXCLUDED_HEADERS_STRING, CachingConstants.PERMANENTLY_EXCLUDED_HEADERS);
            cache.getDigestGenerator().init(props);
            OMElement onCacheHitElem = elem.getFirstChildWithName(ON_CACHE_HIT_Q);
            if (onCacheHitElem != null) {
                OMAttribute sequenceAttr = onCacheHitElem.getAttribute(ATT_SEQUENCE);
                if (sequenceAttr != null && sequenceAttr.getAttributeValue() != null) {
                    cache.setOnCacheHitRef(sequenceAttr.getAttributeValue());
                } else if (onCacheHitElem.getFirstElement() != null) {
                    cache.setOnCacheHitSequence(new SequenceMediatorFactory().createAnonymousSequence(onCacheHitElem, properties));
                }
            } else {
                cache.setOnCacheHitRef(null);
                cache.setOnCacheHitSequence(null);
            }
            OMElement implElem = elem.getFirstChildWithName(IMPLEMENTATION_Q);
            if (implElem != null) {
                OMAttribute sizeAttr = implElem.getAttribute(ATT_SIZE);
                if (sizeAttr != null && sizeAttr.getAttributeValue() != null) {
                    cache.setInMemoryCacheSize(Integer.parseInt(sizeAttr.getAttributeValue().trim()));
                } else {
                    cache.setInMemoryCacheSize(-1);
                }
                OMAttribute typeAttribute = implElem.getAttribute(ATT_TYPE);
                if (typeAttribute != null && typeAttribute.getAttributeValue() != null) {
                    cache.setImplementationType(typeAttribute.getAttributeValue().trim());
                }
            }
        } else {
            handleException("The value for collector has to be either true or false");
        }
    } else {
        handleException("The collector attribute must be specified");
    }
    addAllCommentChildrenToList(elem, cache.getCommentsList());
    return cache;
}
Also used : OMElement(org.apache.axiom.om.OMElement) DigestGenerator(org.wso2.carbon.mediator.cache.digest.DigestGenerator) SequenceMediatorFactory(org.apache.synapse.config.xml.SequenceMediatorFactory) OMAttribute(org.apache.axiom.om.OMAttribute) HashMap(java.util.HashMap) Map(java.util.Map)

Example 24 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project product-is by wso2.

the class SCIM2UserTestCase method testUpdateUserWhenExternalClaimDeleted.

@Test(dependsOnMethods = "testGetUser")
public void testUpdateUserWhenExternalClaimDeleted() throws Exception {
    AutomationContext context = new AutomationContext("IDENTITY", testUserMode);
    backendURL = context.getContextUrls().getBackEndUrl();
    loginLogoutClient = new LoginLogoutClient(context);
    sessionCookie = loginLogoutClient.login();
    HttpPost postRequest = new HttpPost(getPath());
    postRequest.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
    postRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    JSONObject rootObject = new JSONObject();
    JSONArray schemas = new JSONArray();
    rootObject.put(SCHEMAS_ATTRIBUTE, schemas);
    JSONObject names = new JSONObject();
    names.put(FAMILY_NAME_ATTRIBUTE, "udaranga");
    names.put(GIVEN_NAME_ATTRIBUTE, "buddhima");
    rootObject.put(NAME_ATTRIBUTE, names);
    rootObject.put(USER_NAME_ATTRIBUTE, "wso2is");
    JSONObject emailWork = new JSONObject();
    emailWork.put(TYPE_PARAM, EMAIL_TYPE_WORK_ATTRIBUTE);
    emailWork.put(VALUE_PARAM, EMAIL_TYPE_WORK_CLAIM_VALUE);
    JSONObject emailHome = new JSONObject();
    emailHome.put(TYPE_PARAM, EMAIL_TYPE_HOME_ATTRIBUTE);
    emailHome.put(VALUE_PARAM, EMAIL_TYPE_HOME_CLAIM_VALUE);
    JSONArray emails = new JSONArray();
    emails.add(emailWork);
    emails.add(emailHome);
    rootObject.put(EMAILS_ATTRIBUTE, emails);
    rootObject.put(PASSWORD_ATTRIBUTE, PASSWORD);
    StringEntity entity = new StringEntity(rootObject.toString());
    postRequest.setEntity(entity);
    HttpResponse postResponse = client.execute(postRequest);
    assertEquals(postResponse.getStatusLine().getStatusCode(), 201, "User has not been created in patch process successfully.");
    Object responseObj = JSONValue.parse(EntityUtils.toString(postResponse.getEntity()));
    EntityUtils.consume(postResponse.getEntity());
    String userId = ((JSONObject) responseObj).get(ID_ATTRIBUTE).toString();
    assertNotNull(userId);
    String userResourcePath = getPath() + "/" + userId;
    claimMetadataManagementServiceClient = new ClaimMetadataManagementServiceClient(backendURL, sessionCookie);
    claimMetadataManagementServiceClient.removeExternalClaim("urn:ietf:params:scim:schemas:core:2.0:User", "urn:ietf:params:scim:schemas:core:2.0:User:name.honorificSuffix");
    HttpPatch request = new HttpPatch(userResourcePath);
    StringEntity params = new StringEntity("{\"schemas\":[\"urn:ietf:params:scim:api:messages:2.0:PatchOp\"]," + "\"Operations\":[{\"op\":\"replace\",\"path\":\"name\",\"value\":{\"givenName\":\"mahela\"," + "\"familyName\":\"jayaxxxx\"}}]}");
    request.setEntity(params);
    request.addHeader(HttpHeaders.AUTHORIZATION, getAuthzHeader());
    request.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    HttpResponse response = client.execute(request);
    assertEquals(response.getStatusLine().getStatusCode(), 200, "User has not been updated successfully.");
    Object responseObjAfterPatch = JSONValue.parse(EntityUtils.toString(response.getEntity()));
    EntityUtils.consume(response.getEntity());
    String updatedGivenName = ((JSONObject) responseObjAfterPatch).get(NAME_ATTRIBUTE).toString();
    assertTrue(updatedGivenName.contains("mahela"));
}
Also used : AutomationContext(org.wso2.carbon.automation.engine.context.AutomationContext) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) LoginLogoutClient(org.wso2.carbon.integration.common.utils.LoginLogoutClient) ClaimMetadataManagementServiceClient(org.wso2.identity.integration.common.clients.claim.metadata.mgt.ClaimMetadataManagementServiceClient) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) HttpResponse(org.apache.http.HttpResponse) JSONObject(org.json.simple.JSONObject) HttpPatch(org.apache.http.client.methods.HttpPatch) Test(org.testng.annotations.Test) ISIntegrationTest(org.wso2.identity.integration.common.utils.ISIntegrationTest)

Example 25 with Patch

use of org.wso2.carbon.identity.api.server.idp.v1.model.Patch in project product-is by wso2.

the class SCIM2CustomSchemaUserTestCase method testPatchRemoveUserAttributes.

@Test(dependsOnMethods = "testPatchReplaceUserAttributes", description = "Tests patch remove operation for custom" + " schema attributes with /Users api.")
public void testPatchRemoveUserAttributes() throws Exception {
    String body = readResource("scim2-custom-schema-patch-remove-attribute.json");
    Response response = getResponseOfPatch(userIdEndpointURL, body, SCIM_CONTENT_TYPE);
    ExtractableResponse<Response> extractableResponse = response.then().log().ifValidationFails().assertThat().statusCode(HttpStatus.SC_OK).and().assertThat().header(HttpHeaders.CONTENT_TYPE, SCIM_CONTENT_TYPE).extract();
    Assert.assertNotNull(extractableResponse);
    Object customSchema = extractableResponse.path(CUSTOM_SCHEMA_URI_WITH_ESCAPE_CHARS);
    assertNotNull(customSchema);
    Object country = ((LinkedHashMap) customSchema).get(COUNTRY_CLAIM_ATTRIBUTE_NAME);
    assertNull(country);
    LinkedHashMap manager = (LinkedHashMap) ((LinkedHashMap) customSchema).get(MANAGER_CLAIM_ATTRIBUTE_NAME);
    assertNotNull(manager);
    String managerEMail = manager.get(MANAGER_EMAIL_CLAIM_ATTRIBUTE_NAME).toString();
    assertEquals(managerEMail, MANAGER_EMAIL_LOCAL_CLAIM_VALUE_AFTER_REPLACE);
}
Also used : ExtractableResponse(io.restassured.response.ExtractableResponse) Response(io.restassured.response.Response) LinkedHashMap(java.util.LinkedHashMap) Test(org.testng.annotations.Test) SCIM2BaseTest(org.wso2.identity.integration.test.scim2.rest.api.SCIM2BaseTest)

Aggregations

BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)19 ArrayList (java.util.ArrayList)11 HashMap (java.util.HashMap)11 Test (org.testng.annotations.Test)11 JSONArray (org.json.JSONArray)9 JSONObject (org.json.JSONObject)9 Attribute (org.wso2.charon3.core.attributes.Attribute)9 ComplexAttribute (org.wso2.charon3.core.attributes.ComplexAttribute)9 MultiValuedAttribute (org.wso2.charon3.core.attributes.MultiValuedAttribute)9 SimpleAttribute (org.wso2.charon3.core.attributes.SimpleAttribute)9 CharonException (org.wso2.charon3.core.exceptions.CharonException)9 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)8 List (java.util.List)7 NotImplementedException (org.wso2.charon3.core.exceptions.NotImplementedException)7 LinkedHashMap (java.util.LinkedHashMap)6 Map (java.util.Map)6 JSONException (org.json.JSONException)6 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 AttributeSchema (org.wso2.charon3.core.schema.AttributeSchema)6 ExtractableResponse (io.restassured.response.ExtractableResponse)5