Search in sources :

Example 31 with Patch

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

the class ServerUserStoreService method buildResponseForPatchReplace.

/**
 * Construct the response for patch replace.
 *
 * @param userStoreDTO {@link UserStoreDTO}.
 * @param propertyDTOS array of {@link PropertyDTO}.
 * @return UserStoreResponse.
 */
private UserStoreResponse buildResponseForPatchReplace(UserStoreDTO userStoreDTO, PropertyDTO[] propertyDTOS) {
    UserStoreResponse userStoreResponseDTO = new UserStoreResponse();
    userStoreResponseDTO.setId((base64URLEncodeId(userStoreDTO.getDomainId())));
    userStoreResponseDTO.setName(userStoreDTO.getDomainId());
    userStoreResponseDTO.setTypeId(base64URLEncodeId(Objects.requireNonNull(getUserStoreTypeName(userStoreDTO.getClassName()))));
    userStoreResponseDTO.setTypeName(getUserStoreTypeName(userStoreDTO.getClassName()));
    userStoreResponseDTO.setDescription(userStoreDTO.getDescription());
    userStoreResponseDTO.setProperties(patchUserStoreProperties(propertyDTOS));
    return userStoreResponseDTO;
}
Also used : UserStoreResponse(org.wso2.carbon.identity.api.server.userstore.v1.model.UserStoreResponse)

Example 32 with Patch

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

the class ServerIdpManagementService method patchIDP.

/**
 * Updates only root level attributes of IDP.
 *
 * @param identityProviderId Identity Provider resource ID.
 * @param patchRequest       Patch request in Json Patch notation See
 *                           <a href="https://tools.ietf.org/html/rfc6902">https://tools.ietf
 *                           .org/html/rfc6902</a>.
 *                           We support only Patch 'replace' operation on root level attributes of an Identity
 *                           Provider.
 */
public IdentityProviderResponse patchIDP(String identityProviderId, List<Patch> patchRequest) {
    try {
        IdentityProvider identityProvider = IdentityProviderServiceHolder.getIdentityProviderManager().getIdPByResourceId(identityProviderId, ContextLoader.getTenantDomainFromContext(), true);
        if (identityProvider == null) {
            throw handleException(Response.Status.NOT_FOUND, Constants.ErrorMessage.ERROR_CODE_IDP_NOT_FOUND, identityProviderId);
        }
        IdentityProvider idpToUpdate = createIdPClone(identityProvider);
        processPatchRequest(patchRequest, idpToUpdate);
        IdentityProvider updatedIdP = IdentityProviderServiceHolder.getIdentityProviderManager().updateIdPByResourceId(identityProviderId, idpToUpdate, ContextLoader.getTenantDomainFromContext());
        return createIDPResponse(updatedIdP);
    } catch (IdentityProviderManagementException e) {
        throw handleIdPException(e, Constants.ErrorMessage.ERROR_CODE_ERROR_RETRIEVING_IDP, identityProviderId);
    }
}
Also used : IdentityProvider(org.wso2.carbon.identity.application.common.model.IdentityProvider) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 33 with Patch

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

the class ServerConfigManagementService method processPatchRequest.

/**
 * Evaluate the list of patch operations and update the root level attributes of the ServerConfig accordingly.
 *
 * @param patchRequest List of patch operations.
 * @param idpToUpdate  Resident Identity Provider to be updated.
 */
private void processPatchRequest(List<Patch> patchRequest, IdentityProvider idpToUpdate) {
    if (CollectionUtils.isEmpty(patchRequest)) {
        return;
    }
    for (Patch patch : patchRequest) {
        String path = patch.getPath();
        Patch.OperationEnum operation = patch.getOperation();
        String value = patch.getValue();
        // We support only 'REPLACE', 'ADD' and 'REMOVE' patch operations.
        if (operation == Patch.OperationEnum.REPLACE) {
            if (path.matches(Constants.HOME_REALM_PATH_REGEX) && path.split(Constants.PATH_SEPERATOR).length == 3) {
                int index = Integer.parseInt(path.split(Constants.PATH_SEPERATOR)[2]);
                String[] homeRealmArr = StringUtils.split(idpToUpdate.getHomeRealmId(), ",");
                if (ArrayUtils.isNotEmpty(homeRealmArr) && (index >= 0) && (index < homeRealmArr.length)) {
                    List<String> homeRealmIds = Arrays.asList(homeRealmArr);
                    homeRealmIds.set(index, value);
                    idpToUpdate.setHomeRealmId(StringUtils.join(homeRealmIds, ","));
                } else {
                    throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Invalid index in 'path' attribute");
                }
            } else {
                switch(path) {
                    case Constants.IDLE_SESSION_PATH:
                        updateIdPProperty(idpToUpdate, IdentityApplicationConstants.SESSION_IDLE_TIME_OUT, value);
                        break;
                    case Constants.REMEMBER_ME_PATH:
                        updateIdPProperty(idpToUpdate, IdentityApplicationConstants.REMEMBER_ME_TIME_OUT, value);
                        break;
                    default:
                        throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Unsupported value for 'path' attribute");
                }
            }
        } else if (operation == Patch.OperationEnum.ADD && path.matches(Constants.HOME_REALM_PATH_REGEX) && path.split(Constants.PATH_SEPERATOR).length == 3) {
            List<String> homeRealmIds;
            int index = Integer.parseInt(path.split(Constants.PATH_SEPERATOR)[2]);
            String[] homeRealmArr = StringUtils.split(idpToUpdate.getHomeRealmId(), ",");
            if (ArrayUtils.isNotEmpty(homeRealmArr) && (index >= 0) && index <= homeRealmArr.length) {
                homeRealmIds = new ArrayList<>(Arrays.asList(homeRealmArr));
                homeRealmIds.add(index, value);
            } else if (index == 0) {
                homeRealmIds = new ArrayList<>();
                homeRealmIds.add(value);
            } else {
                throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Invalid index in 'path' attribute");
            }
            idpToUpdate.setHomeRealmId(StringUtils.join(homeRealmIds, ","));
        } else if (operation == Patch.OperationEnum.REMOVE && path.matches(Constants.HOME_REALM_PATH_REGEX) && path.split(Constants.PATH_SEPERATOR).length == 3) {
            List<String> homeRealmIds;
            int index = Integer.parseInt(path.split(Constants.PATH_SEPERATOR)[2]);
            String[] homeRealmArr = StringUtils.split(idpToUpdate.getHomeRealmId(), ",");
            if (ArrayUtils.isNotEmpty(homeRealmArr) && (index >= 0) && index < homeRealmArr.length) {
                homeRealmIds = new ArrayList<>(Arrays.asList(homeRealmArr));
                homeRealmIds.remove(index);
            } else {
                throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Invalid index in 'path' attribute");
            }
            idpToUpdate.setHomeRealmId(StringUtils.join(homeRealmIds, ","));
        } else {
            // Throw an error if any other patch operations are sent in the request.
            throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Unsupported patch operation");
        }
    }
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) CORSPatch(org.wso2.carbon.identity.api.server.configs.v1.model.CORSPatch) Patch(org.wso2.carbon.identity.api.server.configs.v1.model.Patch)

Example 34 with Patch

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

the class PersistenceHelper method getSampleAPIArtifact.

public static GenericArtifact getSampleAPIArtifact() throws GovernanceException {
    GenericArtifact artifact = new GenericArtifactWrapper(new QName("", "PizzaShackAPI", ""), "application/vnd.wso2-api+xml");
    artifact.setAttribute("overview_endpointSecured", "false");
    artifact.setAttribute("overview_transports", "http,https");
    artifact.setAttribute("URITemplate_authType3", "Application & Application User");
    artifact.setAttribute("overview_wadl", null);
    artifact.setAttribute("URITemplate_authType4", "Application & Application User");
    artifact.setAttribute("overview_authorizationHeader", "Authorization");
    artifact.setAttribute("URITemplate_authType1", "Application & Application User");
    artifact.setAttribute("overview_visibleTenants", null);
    artifact.setAttribute("URITemplate_authType2", "Application & Application User");
    artifact.setAttribute("overview_wsdl", null);
    artifact.setAttribute("overview_apiSecurity", "oauth2,oauth_basic_auth_api_key_mandatory");
    artifact.setAttribute("URITemplate_authType0", "Application & Application User");
    artifact.setAttribute("overview_keyManagers", "[\"all\"]");
    artifact.setAttribute("overview_environments", "Default");
    artifact.setAttribute("overview_context", "/pizzashack/1.0.0");
    artifact.setAttribute("overview_visibility", "restricted");
    artifact.setAttribute("overview_isLatest", "true");
    artifact.setAttribute("overview_outSequence", "log_out_message");
    artifact.setAttribute("overview_provider", "admin");
    artifact.setAttribute("apiCategories_categoryName", "testcategory");
    artifact.setAttribute("overview_thumbnail", "/registry/resource/_system/governance/apimgt/applicationdata/provider/admin/PizzaShackAPI/1.0.0/icon");
    artifact.setAttribute("overview_contextTemplate", "/pizzashack/{version}");
    artifact.setAttribute("overview_description", "This is a simple API for Pizza Shack online pizza delivery store.");
    artifact.setAttribute("overview_technicalOwner", "John Doe");
    artifact.setAttribute("overview_type", "HTTP");
    artifact.setAttribute("overview_technicalOwnerEmail", "architecture@pizzashack.com");
    artifact.setAttribute("URITemplate_httpVerb4", "DELETE");
    artifact.setAttribute("overview_inSequence", "log_in_message");
    artifact.setAttribute("URITemplate_httpVerb2", "GET");
    artifact.setAttribute("URITemplate_httpVerb3", "PUT");
    artifact.setAttribute("URITemplate_httpVerb0", "POST");
    artifact.setAttribute("URITemplate_httpVerb1", "GET");
    artifact.setAttribute("labels_labelName", "gwlable");
    artifact.setAttribute("overview_businessOwner", "Jane Roe");
    artifact.setAttribute("overview_version", "1.0.0");
    artifact.setAttribute("overview_endpointConfig", "{\"endpoint_type\":\"http\",\"sandbox_endpoints\":{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}," + "\"endpoint_security\":{\"production\":{\"password\":\"admin\",\"tokenUrl\":null,\"clientId\":null," + "\"clientSecret\":null,\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":\"BASIC\"," + "\"grantType\":null,\"enabled\":true,\"uniqueIdentifier\":null,\"username\":\"admin\"}," + "\"sandbox\":{\"password\":null,\"tokenUrl\":null,\"clientId\":null,\"clientSecret\":null," + "\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":null,\"grantType\":null,\"enabled\":false," + "\"uniqueIdentifier\":null,\"username\":null}},\"production_endpoints\":" + "{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}}");
    artifact.setAttribute("overview_tier", "Bronze||Silver||Gold||Unlimited");
    artifact.setAttribute("overview_sandboxTps", "1000");
    artifact.setAttribute("overview_apiOwner", null);
    artifact.setAttribute("overview_businessOwnerEmail", "marketing@pizzashack.com");
    artifact.setAttribute("isMonetizationEnabled", "false");
    artifact.setAttribute("overview_implementation", "ENDPOINT");
    artifact.setAttribute("overview_deployments", "null");
    artifact.setAttribute("overview_redirectURL", null);
    artifact.setAttribute("monetizationProperties", "{}");
    artifact.setAttribute("overview_name", "PizzaShackAPI");
    artifact.setAttribute("overview_subscriptionAvailability", "current_tenant");
    artifact.setAttribute("overview_productionTps", "1000");
    artifact.setAttribute("overview_cacheTimeout", "300");
    artifact.setAttribute("overview_visibleRoles", "admin,internal/subscriber");
    artifact.setAttribute("overview_testKey", null);
    artifact.setAttribute("overview_corsConfiguration", "{\"corsConfigurationEnabled\":true,\"accessControlAllowOrigins\":[\"*\"]," + "\"accessControlAllowCredentials\":false,\"accessControlAllowHeaders\":[\"authorization\"," + "\"Access-Control-Allow-Origin\",\"Content-Type\",\"SOAPAction\",\"apikey\",\"testKey\"]," + "\"accessControlAllowMethods\":[\"GET\",\"PUT\",\"POST\",\"DELETE\",\"PATCH\",\"OPTIONS\"]}");
    artifact.setAttribute("overview_advertiseOnly", "false");
    artifact.setAttribute("overview_versionType", "context");
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setAttribute("overview_endpointPpassword", null);
    artifact.setAttribute("overview_tenants", null);
    artifact.setAttribute("overview_endpointAuthDigest", "false");
    artifact.setAttribute("overview_faultSequence", "json_fault");
    artifact.setAttribute("overview_responseCaching", "Enabled");
    artifact.setAttribute("URITemplate_urlPattern4", "/order/{orderId}");
    artifact.setAttribute("overview_isDefaultVersion", "true");
    artifact.setAttribute("URITemplate_urlPattern2", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern3", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern0", "/order");
    artifact.setAttribute("URITemplate_urlPattern1", "/menu");
    artifact.setAttribute("overview_enableStore", "true");
    artifact.setAttribute("overview_enableSchemaValidation", "true");
    artifact.setAttribute("overview_endpointUsername", null);
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setId("88e758b7-6924-4e9f-8882-431070b6492b");
    artifact.setAttribute("overview_audience", "PUBLIC");
    return artifact;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) QName(javax.xml.namespace.QName) GenericArtifactWrapper(org.wso2.carbon.apimgt.persistence.GenericArtifactWrapper)

Example 35 with Patch

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

the class SolaceAdminApis method patchClientIdForApplication.

/**
 * Patch client ID for Solace application
 *
 * @param organization name of the Organization
 * @param application  Application object to be renamed
 * @param consumerKey  Consumer key to be used when patching
 * @param consumerSecret Consumer secret to be used when patching
 * @return CloseableHttpResponse of the PATCH call
 */
public CloseableHttpResponse patchClientIdForApplication(String organization, Application application, String consumerKey, String consumerSecret) {
    URL serviceEndpointURL = new URL(baseUrl);
    HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
    HttpPatch httpPatch = new HttpPatch(baseUrl + "/" + organization + "/developers/" + developerUserName + "/apps/" + application.getUUID());
    httpPatch.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedCredentials());
    httpPatch.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    org.json.JSONObject requestBody = buildRequestBodyForClientIdPatch(application, consumerKey, consumerSecret);
    StringEntity params = null;
    try {
        params = new StringEntity(requestBody.toString());
        httpPatch.setEntity(params);
        return APIUtil.executeHTTPRequest(httpPatch, httpClient);
    } catch (IOException | APIManagementException e) {
        log.error(e.getMessage());
    }
    return null;
}
Also used : StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) IOException(java.io.IOException) URL(org.apache.axis2.util.URL) HttpPatch(org.apache.http.client.methods.HttpPatch)

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