Search in sources :

Example 31 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class TemplateBuilderUtil method createAPIGatewayDTOtoPublishAPI.

private static GatewayAPIDTO createAPIGatewayDTOtoPublishAPI(Environment environment, APIProduct apiProduct, APITemplateBuilder builder, String tenantDomain, Map<String, APIDTO> associatedAPIsMap, List<ClientCertificateDTO> clientCertificatesDTOList) throws APITemplateException, XMLStreamException, APIManagementException {
    APIProductIdentifier id = apiProduct.getId();
    GatewayAPIDTO productAPIDto = new GatewayAPIDTO();
    productAPIDto.setProvider(id.getProviderName());
    productAPIDto.setApiId(apiProduct.getUuid());
    productAPIDto.setName(id.getName());
    productAPIDto.setVersion(id.getVersion());
    productAPIDto.setTenantDomain(tenantDomain);
    productAPIDto.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    String definition = apiProduct.getDefinition();
    productAPIDto.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(apiProduct.getUuid(), productAPIDto.getLocalEntriesToBeRemove()));
    GatewayContentDTO productLocalEntry = new GatewayContentDTO();
    productLocalEntry.setName(apiProduct.getUuid());
    productLocalEntry.setContent("<localEntry key=\"" + apiProduct.getUuid() + "\">" + definition.replaceAll("&(?!amp;)", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "</localEntry>");
    productAPIDto.setLocalEntriesToBeAdd(addGatewayContentToList(productLocalEntry, productAPIDto.getLocalEntriesToBeAdd()));
    setClientCertificatesToBeAdded(tenantDomain, productAPIDto, clientCertificatesDTOList);
    for (Map.Entry<String, APIDTO> apidtoEntry : associatedAPIsMap.entrySet()) {
        String apiExtractedPath = apidtoEntry.getKey();
        APIDTO apidto = apidtoEntry.getValue();
        API api = APIMappingUtil.fromDTOtoAPI(apidto, apidto.getProvider());
        api.setUuid(apidto.getId());
        GatewayUtils.setCustomSequencesToBeRemoved(apiProduct.getId(), api.getUuid(), productAPIDto);
        APITemplateBuilder apiTemplateBuilder = new APITemplateBuilderImpl(api, apiProduct);
        addEndpoints(api, apiTemplateBuilder, productAPIDto);
        setCustomSequencesToBeAdded(apiProduct, api, productAPIDto, apiExtractedPath, apidto);
        setAPIFaultSequencesToBeAdded(api, productAPIDto, apiExtractedPath, apidto);
        String prefix = id.getName() + "--v" + id.getVersion();
        setSecureVaultPropertyToBeAdded(prefix, api, productAPIDto);
    }
    productAPIDto.setApiDefinition(builder.getConfigStringForTemplate(environment));
    return productAPIDto;
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APITemplateBuilder(org.wso2.carbon.apimgt.impl.template.APITemplateBuilder) API(org.wso2.carbon.apimgt.api.model.API) Map(java.util.Map) HashMap(java.util.HashMap) APITemplateBuilderImpl(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APITemplateBuilderImpl) GatewayContentDTO(org.wso2.carbon.apimgt.api.gateway.GatewayContentDTO)

Example 32 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class AdditionalSubscriptionInfoMappingUtil method setSolaceEnvironmentDetailsForSubscription.

/**
 * Sets the solace environment details For Solace API subscription with the protocol details
 *
 * @param api          API object
 * @param tenantDomain Tenant Domain
 * @return List containing AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO
 * @throws APIManagementException if error occurred when retrieving protocols URLs
 */
private static List<AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO> setSolaceEnvironmentDetailsForSubscription(API api, String tenantDomain) throws APIManagementException {
    APIDTO apidto = APIMappingUtil.fromAPItoDTO(api, tenantDomain);
    Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    List<APIRevisionDeployment> revisionDeployments = apiConsumer.getAPIRevisionDeploymentListOfAPI(apidto.getId());
    List<AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO> solaceEndpointURLsList = new ArrayList<>();
    // Get revision list of APIs and check Solace deployment environment
    for (APIRevisionDeployment revisionDeployment : revisionDeployments) {
        if (revisionDeployment.isDisplayOnDevportal()) {
            if (gatewayEnvironments != null) {
                // Deployed environment
                Environment environment = gatewayEnvironments.get(revisionDeployment.getDeployment());
                if (environment != null) {
                    // Set solace environment details if deployment is in Solace broker
                    if (SolaceConstants.SOLACE_ENVIRONMENT.equalsIgnoreCase(environment.getProvider())) {
                        AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO solaceEnvironmentDTO = new AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO();
                        solaceEnvironmentDTO.setEnvironmentName(environment.getName());
                        solaceEnvironmentDTO.setEnvironmentDisplayName(environment.getDisplayName());
                        solaceEnvironmentDTO.setOrganizationName(environment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION));
                        // Get Solace endpoint URLs for provided protocols
                        solaceEnvironmentDTO.setSolaceURLs(mapSolaceURLsToStoreDTO(environment.getAdditionalProperties().get(SolaceConstants.SOLACE_ENVIRONMENT_ORGANIZATION), environment.getName(), apidto.getAsyncTransportProtocols()));
                        solaceEndpointURLsList.add(solaceEnvironmentDTO);
                    }
                }
            }
        }
    }
    return solaceEndpointURLsList;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO) AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdditionalSubscriptionInfoSolaceDeployedEnvironmentsDTO) ArrayList(java.util.ArrayList) Environment(org.wso2.carbon.apimgt.api.model.Environment) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 33 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class APIControllerUtil method handleMutualSslCertificates.

/**
 * This method will be used to generate ClientCertificates and meta information related to client certs.
 *
 * @param envParams             Env params object with required parameters
 * @param importedApiDto        Imported API DTO (this will be null for API Products)
 * @param importedApiProductDto Imported API Product DTO (this will be null for APIs)
 * @param identifier            API Identifier/API Product Identifier of the imported API/API Product
 * @param pathToArchive         String of the archive project
 * @throws APIManagementException If an error while generating client certificate information
 */
private static void handleMutualSslCertificates(JsonObject envParams, APIDTO importedApiDto, APIProductDTO importedApiProductDto, Identifier identifier, String pathToArchive) throws APIManagementException {
    JsonElement clientCertificates = envParams.get(ImportExportConstants.MUTUAL_SSL_CERTIFICATES_FIELD);
    if (clientCertificates != null) {
        try {
            List<String> apiSecurity = (importedApiDto != null) ? importedApiDto.getSecurityScheme() : importedApiProductDto.getSecurityScheme();
            if (!apiSecurity.isEmpty()) {
                if (!apiSecurity.contains(ImportExportConstants.MUTUAL_SSL_ENABLED)) {
                    // if the apiSecurity field does not have mutualssl type, append it
                    apiSecurity.add(ImportExportConstants.MUTUAL_SSL_ENABLED);
                }
            } else {
                // if the apiSecurity field is empty, assign the value as "mutualssl"
                apiSecurity.add(ImportExportConstants.MUTUAL_SSL_ENABLED);
            }
            if (importedApiDto != null) {
                importedApiDto.securityScheme(apiSecurity);
            } else {
                importedApiProductDto.securityScheme(apiSecurity);
            }
            String jsonString = clientCertificates.toString();
            handleClientCertificates(new JsonParser().parse(jsonString).getAsJsonArray(), identifier, pathToArchive);
        } catch (IOException e) {
            // Error is logged and when generating certificate details and certs in the archive
            String errorMessage = "Error while generating meta information of client certificates from path.";
            throw new APIManagementException(errorMessage, e, ExceptionCodes.ERROR_READING_PARAMS_FILE);
        }
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) IOException(java.io.IOException) JsonParser(com.google.gson.JsonParser)

Example 34 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class PublisherCommonUtils method getFieldOverriddenAPIDTO.

/**
 * Get the API DTO object in which the API field values are overridden with the user passed new values.
 *
 * @throws APIManagementException
 */
private static APIDTO getFieldOverriddenAPIDTO(APIDTO apidto, API originalAPI, String[] tokenScopes) throws APIManagementException {
    APIDTO originalApiDTO;
    APIDTO updatedAPIDTO;
    try {
        originalApiDTO = APIMappingUtil.fromAPItoDTO(originalAPI);
        Field[] fields = APIDTO.class.getDeclaredFields();
        ObjectMapper mapper = new ObjectMapper();
        String newApiDtoJsonString = mapper.writeValueAsString(apidto);
        JSONParser parser = new JSONParser();
        JSONObject newApiDtoJson = (JSONObject) parser.parse(newApiDtoJsonString);
        String originalApiDtoJsonString = mapper.writeValueAsString(originalApiDTO);
        JSONObject originalApiDtoJson = (JSONObject) parser.parse(originalApiDtoJsonString);
        for (Field field : fields) {
            Scope[] fieldAnnotatedScopes = field.getAnnotationsByType(Scope.class);
            String originalElementValue = mapper.writeValueAsString(originalApiDtoJson.get(field.getName()));
            String newElementValue = mapper.writeValueAsString(newApiDtoJson.get(field.getName()));
            if (!StringUtils.equals(originalElementValue, newElementValue)) {
                originalApiDtoJson = overrideDTOValues(originalApiDtoJson, newApiDtoJson, field, tokenScopes, fieldAnnotatedScopes);
            }
        }
        updatedAPIDTO = mapper.readValue(originalApiDtoJson.toJSONString(), APIDTO.class);
    } catch (IOException | ParseException e) {
        String msg = "Error while processing API DTO json strings";
        throw new APIManagementException(msg, e, ExceptionCodes.JSON_PARSE_ERROR);
    }
    return updatedAPIDTO;
}
Also used : IOException(java.io.IOException) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) Field(java.lang.reflect.Field) JSONObject(org.json.simple.JSONObject) Scope(org.wso2.carbon.apimgt.rest.api.common.annotations.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 35 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDTO in project carbon-apimgt by wso2.

the class PublisherCommonUtils method encryptEndpointSecurityOAuthCredentials.

/**
 * This method will encrypt the OAuth 2.0 API Key and API Secret
 *
 * @param endpointConfig         endpoint configuration of API
 * @param cryptoUtil             cryptography util
 * @param oldProductionApiSecret existing production API secret
 * @param oldSandboxApiSecret    existing sandbox API secret
 * @param apidto                 API DTO
 * @throws CryptoException        if an error occurs while encrypting and base64 encode
 * @throws APIManagementException if an error occurs due to a problem in the endpointConfig payload
 */
public static void encryptEndpointSecurityOAuthCredentials(Map endpointConfig, CryptoUtil cryptoUtil, String oldProductionApiSecret, String oldSandboxApiSecret, APIDTO apidto) throws CryptoException, APIManagementException {
    // OAuth 2.0 backend protection: API Key and API Secret encryption
    String customParametersString;
    if (endpointConfig != null) {
        if ((endpointConfig.get(APIConstants.ENDPOINT_SECURITY) != null)) {
            Map endpointSecurity = (Map) endpointConfig.get(APIConstants.ENDPOINT_SECURITY);
            if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION) != null) {
                Map endpointSecurityProduction = (Map) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION);
                String productionEndpointType = (String) endpointSecurityProduction.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                // Change default value of customParameters JSONObject to String
                if (!(endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) instanceof String)) {
                    LinkedHashMap<String, String> customParametersHashMap = (LinkedHashMap<String, String>) endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                    customParametersString = JSONObject.toJSONString(customParametersHashMap);
                } else if (endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                    customParametersString = (String) endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                } else {
                    customParametersString = "{}";
                }
                endpointSecurityProduction.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParametersString);
                if (APIConstants.OAuthConstants.OAUTH.equals(productionEndpointType)) {
                    if (endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null && StringUtils.isNotBlank(endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString())) {
                        String apiSecret = endpointSecurityProduction.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                        String encryptedApiSecret = cryptoUtil.encryptAndBase64Encode(apiSecret.getBytes());
                        endpointSecurityProduction.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, encryptedApiSecret);
                    } else if (StringUtils.isNotBlank(oldProductionApiSecret)) {
                        endpointSecurityProduction.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, oldProductionApiSecret);
                    } else {
                        String errorMessage = "Client secret is not provided for production endpoint security";
                        throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.INVALID_ENDPOINT_CREDENTIALS, errorMessage));
                    }
                }
                endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_PRODUCTION, endpointSecurityProduction);
                endpointConfig.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                apidto.setEndpointConfig(endpointConfig);
            }
            if (endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX) != null) {
                Map endpointSecuritySandbox = (Map) endpointSecurity.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX);
                String sandboxEndpointType = (String) endpointSecuritySandbox.get(APIConstants.OAuthConstants.ENDPOINT_SECURITY_TYPE);
                // Change default value of customParameters JSONObject to String
                if (!(endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) instanceof String)) {
                    Map<String, String> customParametersHashMap = (Map<String, String>) endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                    customParametersString = JSONObject.toJSONString(customParametersHashMap);
                } else if (endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS) != null) {
                    customParametersString = (String) endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS);
                } else {
                    customParametersString = "{}";
                }
                endpointSecuritySandbox.put(APIConstants.OAuthConstants.OAUTH_CUSTOM_PARAMETERS, customParametersString);
                if (APIConstants.OAuthConstants.OAUTH.equals(sandboxEndpointType)) {
                    if (endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET) != null && StringUtils.isNotBlank(endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString())) {
                        String apiSecret = endpointSecuritySandbox.get(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET).toString();
                        String encryptedApiSecret = cryptoUtil.encryptAndBase64Encode(apiSecret.getBytes());
                        endpointSecuritySandbox.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, encryptedApiSecret);
                    } else if (StringUtils.isNotBlank(oldSandboxApiSecret)) {
                        endpointSecuritySandbox.put(APIConstants.OAuthConstants.OAUTH_CLIENT_SECRET, oldSandboxApiSecret);
                    } else {
                        String errorMessage = "Client secret is not provided for sandbox endpoint security";
                        throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.INVALID_ENDPOINT_CREDENTIALS, errorMessage));
                    }
                }
                endpointSecurity.put(APIConstants.OAuthConstants.ENDPOINT_SECURITY_SANDBOX, endpointSecuritySandbox);
                endpointConfig.put(APIConstants.ENDPOINT_SECURITY, endpointSecurity);
                apidto.setEndpointConfig(endpointConfig);
            }
        }
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)29 HashMap (java.util.HashMap)28 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)27 ArrayList (java.util.ArrayList)25 API (org.wso2.carbon.apimgt.api.model.API)25 IOException (java.io.IOException)18 API (org.wso2.carbon.apimgt.core.models.API)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)15 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO)15 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)14 File (java.io.File)12 Response (javax.ws.rs.core.Response)12 Map (java.util.Map)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)11 Test (org.junit.Test)10 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)10 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)10 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)10 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)10