Search in sources :

Example 21 with ClientCertificateDTO

use of org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO in project carbon-apimgt by wso2.

the class APIControllerUtil method handleClientCertificates.

/**
 * This method will be used to generate ClientCertificates and meta information related to client certs.
 *
 * @param certificates  JsonArray of client-certificates
 * @param identifier    API Identifier/API Product Identifier of the imported API/API Product
 * @param pathToArchive String of the archive project
 * @throws IOException            If an error occurs when generating new certs and yaml file or when moving certs
 * @throws APIManagementException If an error while generating new directory
 */
private static void handleClientCertificates(JsonArray certificates, Identifier identifier, String pathToArchive) throws IOException, APIManagementException {
    APIIdentifier apiIdentifier = new APIIdentifier(identifier.getProviderName(), identifier.getName(), identifier.getVersion());
    List<ClientCertificateDTO> certs = new ArrayList<>();
    for (JsonElement certificate : certificates) {
        JsonObject certObject = certificate.getAsJsonObject();
        String alias = certObject.get(ImportExportConstants.ALIAS_JSON_KEY).getAsString();
        ClientCertificateDTO cert = new ClientCertificateDTO();
        cert.setApiIdentifier(apiIdentifier);
        cert.setAlias(alias);
        cert.setTierName(certObject.get(ImportExportConstants.CERTIFICATE_TIER_NAME_PROPERTY).getAsString());
        String certName = certObject.get(ImportExportConstants.CERTIFICATE_PATH_PROPERTY).getAsString();
        cert.setCertificate(certName);
        certs.add(cert);
        // check and create a directory
        String clientCertificatesDirectory = pathToArchive + ImportExportConstants.CLIENT_CERTIFICATES_DIRECTORY_PATH;
        if (!CommonUtil.checkFileExistence(clientCertificatesDirectory)) {
            try {
                CommonUtil.createDirectory(clientCertificatesDirectory);
            } catch (APIImportExportException e) {
                throw new APIManagementException(e);
            }
        }
        // copy certs file from certificates
        String userCertificatesTempDirectory = pathToArchive + ImportExportConstants.DEPLOYMENT_DIRECTORY + ImportExportConstants.CERTIFICATE_DIRECTORY;
        String sourcePath = userCertificatesTempDirectory + File.separator + certName;
        String destinationPath = clientCertificatesDirectory + File.separator + certName;
        if (Files.notExists(Paths.get(sourcePath))) {
            String errorMessage = "The mentioned certificate file " + certName + " is not in the certificates directory";
            throw new APIManagementException(errorMessage, ExceptionCodes.ERROR_READING_PARAMS_FILE);
        }
        CommonUtil.moveFile(sourcePath, destinationPath);
    }
    JsonElement jsonElement = new Gson().toJsonTree(certs);
    // generate meta-data yaml file
    String metadataFilePath = pathToArchive + ImportExportConstants.CLIENT_CERTIFICATES_META_DATA_FILE_PATH;
    try {
        if (CommonUtil.checkFileExistence(metadataFilePath + ImportExportConstants.YAML_EXTENSION)) {
            File oldFile = new File(metadataFilePath + ImportExportConstants.YAML_EXTENSION);
            oldFile.delete();
        }
        if (CommonUtil.checkFileExistence(metadataFilePath + ImportExportConstants.JSON_EXTENSION)) {
            File oldFile = new File(metadataFilePath + ImportExportConstants.JSON_EXTENSION);
            oldFile.delete();
        }
        CommonUtil.writeDtoToFile(metadataFilePath, ExportFormat.JSON, ImportExportConstants.TYPE_CLIENT_CERTIFICATES, jsonElement);
    } catch (APIImportExportException e) {
        throw new APIManagementException(e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) File(java.io.File)

Example 22 with ClientCertificateDTO

use of org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO in project carbon-apimgt by wso2.

the class CertificateRestApiUtils method getPaginatedClientCertificates.

/**
 * To get the paginated list of client certificates.
 *
 * @param clientCertificateDTOList Client certificate list.
 * @param limit                    Limit
 * @param offset                   Offset
 * @param query                    query
 * @return paginated list of client certificates.
 */
public static ClientCertificatesDTO getPaginatedClientCertificates(List<ClientCertificateDTO> clientCertificateDTOList, int limit, int offset, String query) {
    if (log.isDebugEnabled()) {
        log.debug(String.format("Filter the client certificates based on the pagination parameters, limit = %d and" + "offset = %d", limit, offset));
    }
    int certCount = clientCertificateDTOList.size();
    List<ClientCertMetadataDTO> clientCertificateList = new ArrayList<>();
    ClientCertificatesDTO certificatesDTO = new ClientCertificatesDTO();
    certificatesDTO.setCount(certCount > limit ? limit : certCount);
    // If the provided offset value exceeds the offset, reset the offset to default.
    if (offset > certCount) {
        offset = RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    }
    // Select only the set of Certificates which matches the given limit and offset values.
    int start = offset;
    int end = certCount > start + limit ? start + limit : certCount;
    for (int i = start; i < end; i++) {
        ClientCertMetadataDTO clientCertMetadataDTO = new ClientCertMetadataDTO();
        ClientCertificateDTO clientCertificateDTO = clientCertificateDTOList.get(i);
        clientCertMetadataDTO.setAlias(clientCertificateDTO.getAlias());
        clientCertMetadataDTO.setApiId(clientCertificateDTO.getApiIdentifier().toString());
        clientCertMetadataDTO.setTier(clientCertificateDTO.getTierName());
        clientCertificateList.add(clientCertMetadataDTO);
    }
    Map<String, Integer> paginatedParams = RestApiCommonUtil.getPaginationParams(offset, limit, certCount);
    String paginatedPrevious = "";
    String paginatedNext = "";
    if (paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET) != null) {
        paginatedPrevious = getCertificatesPaginatedURL(RestApiConstants.CLIENT_CERTS_GET_PAGINATED_URL, paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_PREVIOUS_LIMIT), query);
    }
    if (paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET) != null) {
        paginatedNext = getCertificatesPaginatedURL(RestApiConstants.CLIENT_CERTS_GET_PAGINATED_URL, paginatedParams.get(RestApiConstants.PAGINATION_NEXT_OFFSET), paginatedParams.get(RestApiConstants.PAGINATION_NEXT_LIMIT), query);
    }
    certificatesDTO.setCount(clientCertificateList.size());
    certificatesDTO.setCertificates(clientCertificateList);
    return certificatesDTO;
}
Also used : ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) ArrayList(java.util.ArrayList) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) ClientCertificatesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertificatesDTO)

Example 23 with ClientCertificateDTO

use of org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO in project carbon-apimgt by wso2.

the class ExportUtils method getClientCertificateContentAndMetaData.

/**
 * Get Client Certificate MetaData and Certificate detail and build JSON list.
 *
 * @param clientCertificateDTOs client certificates list DTOs
 * @param certDirectoryPath     directory path to export the certificates
 * @return list of certificate detail JSON objects
 */
private static JsonArray getClientCertificateContentAndMetaData(List<ClientCertificateDTO> clientCertificateDTOs, String certDirectoryPath) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonArray certificatesList = new JsonArray();
    clientCertificateDTOs.forEach(metadataDTO -> {
        try {
            String certificateContent = metadataDTO.getCertificate();
            String certificateContentEncoded = APIConstants.BEGIN_CERTIFICATE_STRING.concat(System.lineSeparator()).concat(certificateContent).concat(System.lineSeparator()).concat(APIConstants.END_CERTIFICATE_STRING);
            CommonUtil.writeFile(certDirectoryPath + File.separator + metadataDTO.getAlias() + ".crt", certificateContentEncoded);
            // Add the file name to the Certificate Metadata
            metadataDTO.setCertificate(metadataDTO.getAlias() + ".crt");
            JsonObject certificateMetadata = (JsonObject) gson.toJsonTree(metadataDTO);
            certificatesList.add(certificateMetadata);
        } catch (APIImportExportException e) {
            log.error("Error while writing the certificate content. For alias: " + metadataDTO.getAlias(), e);
        }
    });
    return certificatesList;
}
Also used : JsonArray(com.google.gson.JsonArray) GsonBuilder(com.google.gson.GsonBuilder) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject)

Example 24 with ClientCertificateDTO

use of org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO in project carbon-apimgt by wso2.

the class TemplateBuilderUtil method getAPITemplateBuilder.

public static APITemplateBuilderImpl getAPITemplateBuilder(API api, String tenantDomain, List<ClientCertificateDTO> clientCertificateDTOS, List<SoapToRestMediationDto> soapToRestInMediationDtos, List<SoapToRestMediationDto> soapToRestMediationDtos) throws APIManagementException {
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    APITemplateBuilderImpl vtb = new APITemplateBuilderImpl(api, soapToRestInMediationDtos, soapToRestMediationDtos);
    Map<String, String> latencyStatsProperties = new HashMap<String, String>();
    latencyStatsProperties.put(APIConstants.API_UUID, api.getUUID());
    if (!APIUtil.isStreamingApi(api)) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIMgtLatencyStatsHandler", latencyStatsProperties);
    }
    Map<String, String> corsProperties = new HashMap<String, String>();
    corsProperties.put(APIConstants.CORSHeaders.IMPLEMENTATION_TYPE_HANDLER_VALUE, api.getImplementation());
    // Get authorization header from the API object or from the tenant registry
    String authorizationHeader;
    if (!StringUtils.isBlank(api.getAuthorizationHeader())) {
        authorizationHeader = api.getAuthorizationHeader();
    } else {
        // Retrieves the auth configuration from tenant registry or api-manager.xml if not available
        // in tenant registry
        authorizationHeader = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.AUTHORIZATION_HEADER);
    }
    if (!StringUtils.isBlank(authorizationHeader)) {
        corsProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    if (!(APIConstants.APITransportType.WS.toString().equals(api.getType()))) {
        if (api.getCorsConfiguration() != null && api.getCorsConfiguration().isCorsConfigurationEnabled()) {
            CORSConfiguration corsConfiguration = api.getCorsConfiguration();
            if (corsConfiguration.getAccessControlAllowHeaders() != null) {
                StringBuilder allowHeaders = new StringBuilder();
                for (String header : corsConfiguration.getAccessControlAllowHeaders()) {
                    allowHeaders.append(header).append(',');
                }
                if (allowHeaders.length() != 0) {
                    allowHeaders.deleteCharAt(allowHeaders.length() - 1);
                    corsProperties.put(APIConstants.CORSHeaders.ALLOW_HEADERS_HANDLER_VALUE, allowHeaders.toString());
                }
            }
            if (corsConfiguration.getAccessControlAllowOrigins() != null) {
                StringBuilder allowOrigins = new StringBuilder();
                for (String origin : corsConfiguration.getAccessControlAllowOrigins()) {
                    allowOrigins.append(origin).append(',');
                }
                if (allowOrigins.length() != 0) {
                    allowOrigins.deleteCharAt(allowOrigins.length() - 1);
                    corsProperties.put(APIConstants.CORSHeaders.ALLOW_ORIGIN_HANDLER_VALUE, allowOrigins.toString());
                }
            }
            if (corsConfiguration.getAccessControlAllowMethods() != null) {
                StringBuilder allowedMethods = new StringBuilder();
                for (String methods : corsConfiguration.getAccessControlAllowMethods()) {
                    allowedMethods.append(methods).append(',');
                }
                if (allowedMethods.length() != 0) {
                    allowedMethods.deleteCharAt(allowedMethods.length() - 1);
                    corsProperties.put(APIConstants.CORSHeaders.ALLOW_METHODS_HANDLER_VALUE, allowedMethods.toString());
                }
            }
            if (corsConfiguration.isAccessControlAllowCredentials()) {
                corsProperties.put(APIConstants.CORSHeaders.ALLOW_CREDENTIALS_HANDLER_VALUE, String.valueOf(corsConfiguration.isAccessControlAllowCredentials()));
            }
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
        } else if (APIUtil.isCORSEnabled()) {
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
        }
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIStatusHandler", Collections.emptyMap());
    }
    Map<String, String> clientCertificateObject = null;
    CertificateMgtUtils certificateMgtUtils = CertificateMgtUtils.getInstance();
    if (clientCertificateDTOS != null) {
        clientCertificateObject = new HashMap<>();
        for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOS) {
            clientCertificateObject.put(certificateMgtUtils.getUniqueIdentifierOfCertificate(clientCertificateDTO.getCertificate()), clientCertificateDTO.getTierName());
        }
    }
    Map<String, String> authProperties = new HashMap<>();
    if (!StringUtils.isBlank(authorizationHeader)) {
        authProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
    }
    String apiSecurity = api.getApiSecurity();
    String apiLevelPolicy = api.getApiLevelPolicy();
    authProperties.put(APIConstants.API_SECURITY, apiSecurity);
    authProperties.put(APIConstants.API_LEVEL_POLICY, apiLevelPolicy);
    if (clientCertificateObject != null) {
        authProperties.put(APIConstants.CERTIFICATE_INFORMATION, clientCertificateObject.toString());
    }
    // Get RemoveHeaderFromOutMessage from tenant registry or api-manager.xml
    String removeHeaderFromOutMessage = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE);
    if (!StringUtils.isBlank(removeHeaderFromOutMessage)) {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, removeHeaderFromOutMessage);
    } else {
        authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE_DEFAULT);
    }
    authProperties.put(APIConstants.API_UUID, api.getUUID());
    authProperties.put("keyManagers", String.join(",", api.getKeyManagers()));
    if (APIConstants.GRAPHQL_API.equals(api.getType())) {
        Map<String, String> apiUUIDProperty = new HashMap<String, String>();
        apiUUIDProperty.put(APIConstants.API_UUID, api.getUUID());
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.graphQL.GraphQLAPIHandler", apiUUIDProperty);
    }
    if (APIConstants.APITransportType.WEBSUB.toString().equals(api.getType())) {
        authProperties.put(APIConstants.WebHookProperties.EVENT_RECEIVING_RESOURCE_PATH, APIConstants.WebHookProperties.DEFAULT_SUBSCRIPTION_RESOURCE_PATH);
        authProperties.put(APIConstants.WebHookProperties.TOPIC_QUERY_PARAM_NAME, APIConstants.WebHookProperties.DEFAULT_TOPIC_QUERY_PARAM_NAME);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.streaming.webhook.WebhookApiHandler", authProperties);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.streaming.webhook." + "WebhooksExtensionHandler", Collections.emptyMap());
    } else if (APIConstants.APITransportType.SSE.toString().equals(api.getType())) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.streaming.sse.SseApiHandler", authProperties);
    } else if (!(APIConstants.APITransportType.WS.toString().equals(api.getType()))) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler", authProperties);
    }
    if (APIConstants.GRAPHQL_API.equals(api.getType())) {
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.graphQL.GraphQLQueryAnalysisHandler", Collections.emptyMap());
    }
    if (!APIUtil.isStreamingApi(api)) {
        Map<String, String> properties = new HashMap<String, String>();
        if (api.getProductionMaxTps() != null) {
            properties.put("productionMaxCount", api.getProductionMaxTps());
        }
        if (api.getSandboxMaxTps() != null) {
            properties.put("sandboxMaxCount", api.getSandboxMaxTps());
        }
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler", properties);
        properties = new HashMap<String, String>();
        properties.put("configKey", APIConstants.GA_CONF_KEY);
        vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtGoogleAnalyticsTrackingHandler", properties);
        String extensionHandlerPosition = getExtensionHandlerPosition(tenantDomain);
        if ("top".equalsIgnoreCase(extensionHandlerPosition)) {
            vtb.addHandlerPriority("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap(), 2);
        } else {
            vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap());
        }
    }
    return vtb;
}
Also used : CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) HashMap(java.util.HashMap) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) CertificateMgtUtils(org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils) APITemplateBuilderImpl(org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template.APITemplateBuilderImpl)

Example 25 with ClientCertificateDTO

use of org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO in project carbon-apimgt by wso2.

the class ApiMgtDAO method addAPIProductRevision.

/**
 * Adds an API Product revision record to the database
 *
 * @param apiRevision content of the revision
 * @throws APIManagementException if an error occurs when adding a new API revision
 */
public void addAPIProductRevision(APIRevision apiRevision) throws APIManagementException {
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try {
            connection.setAutoCommit(false);
            // Adding to AM_REVISION table
            PreparedStatement statement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.ADD_API_REVISION);
            statement.setInt(1, apiRevision.getId());
            statement.setString(2, apiRevision.getApiUUID());
            statement.setString(3, apiRevision.getRevisionUUID());
            statement.setString(4, apiRevision.getDescription());
            statement.setString(5, apiRevision.getCreatedBy());
            statement.setTimestamp(6, new Timestamp(System.currentTimeMillis()));
            statement.executeUpdate();
            // Retrieve API Product ID
            APIProductIdentifier apiProductIdentifier = APIUtil.getAPIProductIdentifierFromUUID(apiRevision.getApiUUID());
            int apiId = getAPIID(apiRevision.getApiUUID(), connection);
            int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiProductIdentifier.getProviderName()));
            String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
            // Adding to AM_API_URL_MAPPING table
            PreparedStatement getURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_URL_MAPPINGS_WITH_SCOPE_AND_PRODUCT_ID_BY_PRODUCT_ID);
            getURLMappingsStatement.setInt(1, apiId);
            List<URITemplate> urlMappingList = new ArrayList<>();
            try (ResultSet rs = getURLMappingsStatement.executeQuery()) {
                while (rs.next()) {
                    String script = null;
                    URITemplate uriTemplate = new URITemplate();
                    uriTemplate.setHTTPVerb(rs.getString(1));
                    uriTemplate.setAuthType(rs.getString(2));
                    uriTemplate.setUriTemplate(rs.getString(3));
                    uriTemplate.setThrottlingTier(rs.getString(4));
                    InputStream mediationScriptBlob = rs.getBinaryStream(5);
                    if (mediationScriptBlob != null) {
                        script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
                    }
                    uriTemplate.setMediationScript(script);
                    if (!StringUtils.isEmpty(rs.getString(6))) {
                        Scope scope = new Scope();
                        scope.setKey(rs.getString(6));
                        uriTemplate.setScope(scope);
                    }
                    if (rs.getInt(7) != 0) {
                        // Adding api id to uri template id just to store value
                        uriTemplate.setId(rs.getInt(7));
                    }
                    urlMappingList.add(uriTemplate);
                }
            }
            Map<String, URITemplate> uriTemplateMap = new HashMap<>();
            for (URITemplate urlMapping : urlMappingList) {
                if (urlMapping.getScope() != null) {
                    URITemplate urlMappingNew = urlMapping;
                    URITemplate urlMappingExisting = uriTemplateMap.get(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb());
                    if (urlMappingExisting != null && urlMappingExisting.getScopes() != null) {
                        if (!urlMappingExisting.getScopes().contains(urlMapping.getScope())) {
                            urlMappingExisting.setScopes(urlMapping.getScope());
                            uriTemplateMap.put(urlMappingExisting.getUriTemplate() + urlMappingExisting.getHTTPVerb(), urlMappingExisting);
                        }
                    } else {
                        urlMappingNew.setScopes(urlMapping.getScope());
                        uriTemplateMap.put(urlMappingNew.getUriTemplate() + urlMappingNew.getHTTPVerb(), urlMappingNew);
                    }
                } else if (urlMapping.getId() != 0) {
                    URITemplate urlMappingExisting = uriTemplateMap.get(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb());
                    if (urlMappingExisting == null) {
                        uriTemplateMap.put(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb(), urlMapping);
                    }
                } else {
                    uriTemplateMap.put(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb(), urlMapping);
                }
            }
            setAPIProductOperationPoliciesToURITemplatesMap(new Integer(apiId).toString(), uriTemplateMap);
            PreparedStatement insertURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_URL_MAPPINGS);
            for (URITemplate urlMapping : uriTemplateMap.values()) {
                insertURLMappingsStatement.setInt(1, urlMapping.getId());
                insertURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
                insertURLMappingsStatement.setString(3, urlMapping.getAuthType());
                insertURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
                insertURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
                insertURLMappingsStatement.setString(6, apiRevision.getRevisionUUID());
                insertURLMappingsStatement.addBatch();
            }
            insertURLMappingsStatement.executeBatch();
            // Add to AM_API_RESOURCE_SCOPE_MAPPING table and to AM_API_PRODUCT_MAPPING
            PreparedStatement getRevisionedURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_REVISIONED_URL_MAPPINGS_ID);
            PreparedStatement insertScopeResourceMappingStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_SCOPE_RESOURCE_MAPPING);
            PreparedStatement insertProductResourceMappingStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_PRODUCT_REVISION_RESOURCE_MAPPING);
            String dbProductName = connection.getMetaData().getDatabaseProductName();
            PreparedStatement insertOperationPolicyMappingStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "OPERATION_POLICY_MAPPING_ID") });
            Map<String, String> clonedPoliciesMap = new HashMap<>();
            for (URITemplate urlMapping : uriTemplateMap.values()) {
                getRevisionedURLMappingsStatement.setInt(1, urlMapping.getId());
                getRevisionedURLMappingsStatement.setString(2, apiRevision.getRevisionUUID());
                getRevisionedURLMappingsStatement.setString(3, urlMapping.getHTTPVerb());
                getRevisionedURLMappingsStatement.setString(4, urlMapping.getAuthType());
                getRevisionedURLMappingsStatement.setString(5, urlMapping.getUriTemplate());
                getRevisionedURLMappingsStatement.setString(6, urlMapping.getThrottlingTier());
                if (urlMapping.getScopes() != null) {
                    try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
                        while (rs.next()) {
                            for (Scope scope : urlMapping.getScopes()) {
                                insertScopeResourceMappingStatement.setString(1, scope.getKey());
                                insertScopeResourceMappingStatement.setInt(2, rs.getInt(1));
                                insertScopeResourceMappingStatement.setInt(3, tenantId);
                                insertScopeResourceMappingStatement.addBatch();
                            }
                        }
                    }
                }
                try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
                    while (rs.next()) {
                        insertProductResourceMappingStatement.setInt(1, apiId);
                        insertProductResourceMappingStatement.setInt(2, rs.getInt(1));
                        insertProductResourceMappingStatement.setString(3, apiRevision.getRevisionUUID());
                        insertProductResourceMappingStatement.addBatch();
                    }
                }
                try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
                    while (rs.next()) {
                        for (OperationPolicy policy : urlMapping.getOperationPolicies()) {
                            String clonedPolicyId = null;
                            if (!clonedPoliciesMap.keySet().contains(policy.getPolicyId())) {
                                // Since we are creating a new revision, we need to clone all the policies from current status.
                                // If the policy is not cloned from a previous policy, we have to clone.
                                clonedPolicyId = revisionOperationPolicy(connection, policy.getPolicyId(), apiRevision.getApiUUID(), apiRevision.getRevisionUUID(), tenantDomain);
                                clonedPoliciesMap.put(policy.getPolicyId(), clonedPolicyId);
                            }
                            Gson gson = new Gson();
                            String paramJSON = gson.toJson(policy.getParameters());
                            insertOperationPolicyMappingStatement.setInt(1, rs.getInt(1));
                            insertOperationPolicyMappingStatement.setString(2, clonedPoliciesMap.get(policy.getPolicyId()));
                            insertOperationPolicyMappingStatement.setString(3, policy.getDirection());
                            insertOperationPolicyMappingStatement.setString(4, paramJSON);
                            insertOperationPolicyMappingStatement.setInt(5, policy.getOrder());
                            insertOperationPolicyMappingStatement.executeUpdate();
                        }
                    }
                }
            }
            insertScopeResourceMappingStatement.executeBatch();
            insertProductResourceMappingStatement.executeBatch();
            // Adding to AM_API_CLIENT_CERTIFICATE
            PreparedStatement getClientCertificatesStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_CLIENT_CERTIFICATES);
            getClientCertificatesStatement.setInt(1, apiId);
            List<ClientCertificateDTO> clientCertificateDTOS = new ArrayList<>();
            try (ResultSet rs = getClientCertificatesStatement.executeQuery()) {
                while (rs.next()) {
                    ClientCertificateDTO clientCertificateDTO = new ClientCertificateDTO();
                    clientCertificateDTO.setAlias(rs.getString(1));
                    clientCertificateDTO.setCertificate(APIMgtDBUtil.getStringFromInputStream(rs.getBinaryStream(2)));
                    clientCertificateDTO.setTierName(rs.getString(3));
                    clientCertificateDTOS.add(clientCertificateDTO);
                }
            }
            PreparedStatement insertClientCertificateStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_CLIENT_CERTIFICATES);
            for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOS) {
                insertClientCertificateStatement.setInt(1, tenantId);
                insertClientCertificateStatement.setString(2, clientCertificateDTO.getAlias());
                insertClientCertificateStatement.setInt(3, apiId);
                insertClientCertificateStatement.setBinaryStream(4, getInputStream(clientCertificateDTO.getCertificate()));
                insertClientCertificateStatement.setBoolean(5, false);
                insertClientCertificateStatement.setString(6, clientCertificateDTO.getTierName());
                insertClientCertificateStatement.setString(7, apiRevision.getRevisionUUID());
                insertClientCertificateStatement.addBatch();
            }
            insertClientCertificateStatement.executeBatch();
            // Adding to AM_GRAPHQL_COMPLEXITY table
            PreparedStatement getGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_GRAPHQL_COMPLEXITY);
            List<CustomComplexityDetails> customComplexityDetailsList = new ArrayList<>();
            getGraphQLComplexityStatement.setInt(1, apiId);
            try (ResultSet rs1 = getGraphQLComplexityStatement.executeQuery()) {
                while (rs1.next()) {
                    CustomComplexityDetails customComplexityDetails = new CustomComplexityDetails();
                    customComplexityDetails.setType(rs1.getString("TYPE"));
                    customComplexityDetails.setField(rs1.getString("FIELD"));
                    customComplexityDetails.setComplexityValue(rs1.getInt("COMPLEXITY_VALUE"));
                    customComplexityDetailsList.add(customComplexityDetails);
                }
            }
            PreparedStatement insertGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_GRAPHQL_COMPLEXITY);
            for (CustomComplexityDetails customComplexityDetails : customComplexityDetailsList) {
                insertGraphQLComplexityStatement.setString(1, UUID.randomUUID().toString());
                insertGraphQLComplexityStatement.setInt(2, apiId);
                insertGraphQLComplexityStatement.setString(3, customComplexityDetails.getType());
                insertGraphQLComplexityStatement.setString(4, customComplexityDetails.getField());
                insertGraphQLComplexityStatement.setInt(5, customComplexityDetails.getComplexityValue());
                insertGraphQLComplexityStatement.setString(6, apiRevision.getRevisionUUID());
                insertGraphQLComplexityStatement.addBatch();
            }
            insertGraphQLComplexityStatement.executeBatch();
            updateLatestRevisionNumber(connection, apiRevision.getApiUUID(), apiRevision.getId());
            addAPIRevisionMetaData(connection, apiRevision.getApiUUID(), apiRevision.getRevisionUUID());
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            handleException("Failed to add API Revision entry of API Product UUID " + apiRevision.getApiUUID(), e);
        }
    } catch (SQLException e) {
        handleException("Failed to add API Revision entry of API Product UUID " + apiRevision.getApiUUID(), e);
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Connection(java.sql.Connection) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) CustomComplexityDetails(org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.CustomComplexityDetails) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Scope(org.wso2.carbon.apimgt.api.model.Scope) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) ResultSet(java.sql.ResultSet) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO)

Aggregations

ClientCertificateDTO (org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO)22 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)11 ArrayList (java.util.ArrayList)9 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)9 Gson (com.google.gson.Gson)7 HashMap (java.util.HashMap)7 API (org.wso2.carbon.apimgt.api.model.API)7 Connection (java.sql.Connection)6 SQLException (java.sql.SQLException)6 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)6 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)6 PreparedStatement (java.sql.PreparedStatement)5 ResultSet (java.sql.ResultSet)5 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)5 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)5 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 LinkedHashMap (java.util.LinkedHashMap)4 GatewayAPIDTO (org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO)4