Search in sources :

Example 16 with ClientCertificateDTO

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

the class ApisApiServiceImpl method updateAPIClientCertificateByAlias.

@Override
public Response updateAPIClientCertificateByAlias(String alias, String apiId, InputStream certificateInputStream, Attachment certificateDetail, String tier, MessageContext messageContext) {
    try {
        // validate if api exists
        validateAPIExistence(apiId);
        ContentDisposition contentDisposition;
        String fileName;
        String base64EncodedCert = null;
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        api.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(api.getStatus());
        String userName = RestApiCommonUtil.getLoggedInUsername();
        int tenantId = APIUtil.getInternalOrganizationId(organization);
        ClientCertificateDTO clientCertificateDTO = CertificateRestApiUtils.preValidateClientCertificate(alias, api.getId(), organization);
        if (certificateDetail != null) {
            contentDisposition = certificateDetail.getContentDisposition();
            fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
            if (StringUtils.isNotBlank(fileName)) {
                base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
            }
        }
        if (StringUtils.isEmpty(base64EncodedCert) && StringUtils.isEmpty(tier)) {
            return Response.ok().entity("Client Certificate is not updated for alias " + alias).build();
        }
        int responseCode = apiProvider.updateClientCertificate(base64EncodedCert, alias, clientCertificateDTO.getApiIdentifier(), tier, tenantId, organization);
        if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
            // Handle api product case.
            if (API_PRODUCT_TYPE.equals(api.getType())) {
                APIIdentifier apiIdentifier = api.getId();
                APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
                APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
                apiProduct.setOrganization(organization);
                apiProvider.updateAPIProduct(apiProduct);
            } else {
                apiProvider.updateAPI(api);
            }
            ClientCertMetadataDTO clientCertMetadataDTO = new ClientCertMetadataDTO();
            clientCertMetadataDTO.setAlias(alias);
            clientCertMetadataDTO.setApiId(api.getUUID());
            clientCertMetadataDTO.setTier(clientCertificateDTO.getTierName());
            URI updatedCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
            return Response.ok(updatedCertUri).entity(clientCertMetadataDTO).build();
        } else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Error while updating the client certificate for the alias " + alias + " due to an internal " + "server error", log);
        } else if (ResponseCode.CERTIFICATE_NOT_FOUND.getResponseCode() == responseCode) {
            RestApiUtil.handleResourceNotFoundError("", log);
        } else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
            RestApiUtil.handleBadRequest("Error while updating the client certificate for the alias " + alias + " Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while updating the client certificate for the alias " + alias + " due to an internal " + "server error", e, log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("Error while encoding client certificate for the alias " + alias, e, log);
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", e, log);
    } catch (FaultGatewaysException e) {
        RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
    }
    return null;
}
Also used : FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 17 with ClientCertificateDTO

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

the class ApisApiServiceImpl method getAPIClientCertificates.

@Override
public Response getAPIClientCertificates(String apiId, Integer limit, Integer offset, String alias, MessageContext messageContext) {
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    List<ClientCertificateDTO> certificates = new ArrayList<>();
    String query = CertificateRestApiUtils.buildQueryString("alias", alias, "apiId", apiId);
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        int tenantId = APIUtil.getInternalOrganizationId(organization);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        int totalCount = apiProvider.getClientCertificateCount(tenantId);
        if (totalCount > 0) {
            APIIdentifier apiIdentifier = null;
            if (StringUtils.isNotEmpty(apiId)) {
                API api = apiProvider.getAPIbyUUID(apiId, organization);
                apiIdentifier = api.getId();
            }
            certificates = apiProvider.searchClientCertificates(tenantId, alias, apiIdentifier, organization);
        }
        ClientCertificatesDTO certificatesDTO = CertificateRestApiUtils.getPaginatedClientCertificates(certificates, limit, offset, query);
        PaginationDTO paginationDTO = new PaginationDTO();
        paginationDTO.setLimit(limit);
        paginationDTO.setOffset(offset);
        paginationDTO.setTotal(totalCount);
        certificatesDTO.setPagination(paginationDTO);
        return Response.status(Response.Status.OK).entity(certificatesDTO).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving the client certificates.", e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) PaginationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ClientCertificatesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertificatesDTO) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 18 with ClientCertificateDTO

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

the class ApiMgtDAO method addAPIRevision.

/**
 * Adds an API 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 addAPIRevision(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 ID
            APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID());
            int apiId = getAPIID(apiRevision.getApiUUID(), connection);
            int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiIdentifier.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);
            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 product 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);
                }
            }
            setOperationPoliciesToURITemplatesMap(apiRevision.getApiUUID(), uriTemplateMap);
            PreparedStatement insertURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_URL_MAPPINGS);
            for (URITemplate urlMapping : uriTemplateMap.values()) {
                insertURLMappingsStatement.setInt(1, apiId);
                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_RESOURCE_MAPPING);
            PreparedStatement insertOperationPolicyMappingStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING);
            Map<String, String> clonedPolicyMap = new HashMap<>();
            for (URITemplate urlMapping : uriTemplateMap.values()) {
                getRevisionedURLMappingsStatement.setInt(1, apiId);
                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());
                try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
                    while (rs.next()) {
                        if (urlMapping.getScopes() != null) {
                            for (Scope scope : urlMapping.getScopes()) {
                                insertScopeResourceMappingStatement.setString(1, scope.getKey());
                                insertScopeResourceMappingStatement.setInt(2, rs.getInt(1));
                                insertScopeResourceMappingStatement.setInt(3, tenantId);
                                insertScopeResourceMappingStatement.addBatch();
                            }
                        }
                        if (urlMapping.getId() != 0) {
                            insertProductResourceMappingStatement.setInt(1, urlMapping.getId());
                            insertProductResourceMappingStatement.setInt(2, rs.getInt(1));
                            insertProductResourceMappingStatement.addBatch();
                        }
                        if (urlMapping.getOperationPolicies().size() > 0) {
                            for (OperationPolicy policy : urlMapping.getOperationPolicies()) {
                                if (!clonedPolicyMap.keySet().contains(policy.getPolicyId())) {
                                    // Since we are creating a new revision, if the policy is not found in the policy map,
                                    // we have to clone the policy.
                                    String clonedPolicyId = revisionOperationPolicy(connection, policy.getPolicyId(), apiRevision.getApiUUID(), apiRevision.getRevisionUUID(), tenantDomain);
                                    // policy ID is stored in a map as same policy can be applied to multiple operations
                                    // and we only need to create the policy once.
                                    clonedPolicyMap.put(policy.getPolicyId(), clonedPolicyId);
                                }
                                Gson gson = new Gson();
                                String paramJSON = gson.toJson(policy.getParameters());
                                insertOperationPolicyMappingStatement.setInt(1, rs.getInt(1));
                                insertOperationPolicyMappingStatement.setString(2, clonedPolicyMap.get(policy.getPolicyId()));
                                insertOperationPolicyMappingStatement.setString(3, policy.getDirection());
                                insertOperationPolicyMappingStatement.setString(4, paramJSON);
                                insertOperationPolicyMappingStatement.setInt(5, policy.getOrder());
                                insertOperationPolicyMappingStatement.addBatch();
                            }
                        }
                    }
                }
            }
            insertScopeResourceMappingStatement.executeBatch();
            insertProductResourceMappingStatement.executeBatch();
            insertOperationPolicyMappingStatement.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 UUID " + apiRevision.getApiUUID(), e);
        }
    } catch (SQLException e) {
        handleException("Failed to add API Revision entry of API 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) Scope(org.wso2.carbon.apimgt.api.model.Scope) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) ResultSet(java.sql.ResultSet) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO)

Example 19 with ClientCertificateDTO

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

the class ApiMgtDAO method restoreAPIProductRevision.

/**
 * Restore API Product revision database records as the Current API Product of an API Product
 *
 * @param apiRevision content of the revision
 * @throws APIManagementException if an error occurs when restoring an API revision
 */
public void restoreAPIProductRevision(APIRevision apiRevision) throws APIManagementException {
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try {
            connection.setAutoCommit(false);
            // Retrieve API 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);
            // Remove Current API Product entries from AM_API_URL_MAPPING table
            PreparedStatement removeURLMappingsFromCurrentAPIProduct = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_CURRENT_API_PRODUCT_ENTRIES_IN_AM_API_URL_MAPPING);
            removeURLMappingsFromCurrentAPIProduct.setString(1, Integer.toString(apiId));
            removeURLMappingsFromCurrentAPIProduct.executeUpdate();
            // Copy Revision resources
            PreparedStatement getURLMappingsFromRevisionedAPIProduct = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_API_PRODUCT_REVISION_URL_MAPPINGS_BY_REVISION_UUID);
            getURLMappingsFromRevisionedAPIProduct.setString(1, apiRevision.getRevisionUUID());
            Map<String, URITemplate> urlMappingList = new HashMap<>();
            try (ResultSet rs = getURLMappingsFromRevisionedAPIProduct.executeQuery()) {
                String key, httpMethod, urlPattern;
                while (rs.next()) {
                    String script = null;
                    URITemplate uriTemplate = new URITemplate();
                    httpMethod = rs.getString("HTTP_METHOD");
                    urlPattern = rs.getString("URL_PATTERN");
                    uriTemplate.setHTTPVerb(httpMethod);
                    uriTemplate.setAuthType(rs.getString("AUTH_SCHEME"));
                    uriTemplate.setUriTemplate(rs.getString("URL_PATTERN"));
                    uriTemplate.setThrottlingTier(rs.getString("THROTTLING_TIER"));
                    InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
                    if (mediationScriptBlob != null) {
                        script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
                    }
                    uriTemplate.setMediationScript(script);
                    if (rs.getInt("API_ID") != 0) {
                        // Adding product id to uri template id just to store value
                        uriTemplate.setId(rs.getInt("API_ID"));
                    }
                    key = urlPattern + httpMethod;
                    urlMappingList.put(key, uriTemplate);
                }
            }
            // Populate Scope Mappings
            PreparedStatement getScopeMappingsFromRevisionedAPIProduct = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_API_PRODUCT_REVISION_SCOPE_MAPPINGS_BY_REVISION_UUID);
            getScopeMappingsFromRevisionedAPIProduct.setString(1, apiRevision.getRevisionUUID());
            try (ResultSet rs = getScopeMappingsFromRevisionedAPIProduct.executeQuery()) {
                while (rs.next()) {
                    String key = rs.getString("URL_PATTERN") + rs.getString("HTTP_METHOD");
                    if (urlMappingList.containsKey(key)) {
                        URITemplate uriTemplate = urlMappingList.get(key);
                        Scope scope = new Scope();
                        scope.setKey(rs.getString("SCOPE_NAME"));
                        uriTemplate.setScope(scope);
                        uriTemplate.setScopes(scope);
                    }
                }
            }
            setAPIProductOperationPoliciesToURITemplatesMap(apiRevision.getRevisionUUID(), urlMappingList);
            PreparedStatement insertURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_URL_MAPPINGS);
            for (URITemplate urlMapping : urlMappingList.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, Integer.toString(apiId));
                insertURLMappingsStatement.addBatch();
            }
            insertURLMappingsStatement.executeBatch();
            // Insert Scope Mappings and operation policy mappings
            PreparedStatement getRevisionedURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_REVISIONED_URL_MAPPINGS_ID);
            PreparedStatement addResourceScopeMapping = connection.prepareStatement(SQLConstants.ADD_API_RESOURCE_SCOPE_MAPPING);
            PreparedStatement addOperationPolicyStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING);
            Map<String, String> clonedPoliciesMap = new HashMap<>();
            Set<String> usedClonedPolicies = new HashSet<String>();
            for (URITemplate urlMapping : urlMappingList.values()) {
                getRevisionedURLMappingsStatement.setInt(1, urlMapping.getId());
                getRevisionedURLMappingsStatement.setString(2, Integer.toString(apiId));
                getRevisionedURLMappingsStatement.setString(3, urlMapping.getHTTPVerb());
                getRevisionedURLMappingsStatement.setString(4, urlMapping.getAuthType());
                getRevisionedURLMappingsStatement.setString(5, urlMapping.getUriTemplate());
                getRevisionedURLMappingsStatement.setString(6, urlMapping.getThrottlingTier());
                try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
                    if (rs.next()) {
                        int newURLMappingId = rs.getInt("URL_MAPPING_ID");
                        if (urlMapping.getScopes() != null && urlMapping.getScopes().size() > 0) {
                            for (Scope scope : urlMapping.getScopes()) {
                                addResourceScopeMapping.setString(1, scope.getKey());
                                addResourceScopeMapping.setInt(2, newURLMappingId);
                                addResourceScopeMapping.setInt(3, tenantId);
                                addResourceScopeMapping.addBatch();
                            }
                        }
                        if (urlMapping.getOperationPolicies().size() > 0) {
                            for (OperationPolicy policy : urlMapping.getOperationPolicies()) {
                                if (!clonedPoliciesMap.keySet().contains(policy.getPolicyName())) {
                                    String policyId = restoreOperationPolicyRevision(connection, apiRevision.getApiUUID(), policy.getPolicyId(), apiRevision.getId(), tenantDomain);
                                    clonedPoliciesMap.put(policy.getPolicyName(), policyId);
                                    usedClonedPolicies.add(policyId);
                                }
                                Gson gson = new Gson();
                                String paramJSON = gson.toJson(policy.getParameters());
                                addOperationPolicyStatement.setInt(1, rs.getInt(1));
                                addOperationPolicyStatement.setString(2, clonedPoliciesMap.get(policy.getPolicyName()));
                                addOperationPolicyStatement.setString(3, policy.getDirection());
                                addOperationPolicyStatement.setString(4, paramJSON);
                                addOperationPolicyStatement.setInt(5, policy.getOrder());
                                addOperationPolicyStatement.executeUpdate();
                            }
                        }
                    }
                }
            }
            addResourceScopeMapping.executeBatch();
            cleanUnusedClonedOperationPolicies(connection, usedClonedPolicies, apiRevision.getApiUUID());
            // Get URL_MAPPING_IDs from table and add records to product mapping table
            PreparedStatement getURLMappingOfAPIProduct = connection.prepareStatement(SQLConstants.GET_URL_MAPPING_IDS_OF_API_PRODUCT_SQL);
            PreparedStatement insertProductResourceMappingStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_PRODUCT_REVISION_RESOURCE_MAPPING);
            getURLMappingOfAPIProduct.setString(1, Integer.toString(apiId));
            try (ResultSet rs = getURLMappingOfAPIProduct.executeQuery()) {
                while (rs.next()) {
                    insertProductResourceMappingStatement.setInt(1, apiId);
                    insertProductResourceMappingStatement.setInt(2, rs.getInt("URL_MAPPING_ID"));
                    insertProductResourceMappingStatement.setString(3, "Current API");
                    insertProductResourceMappingStatement.addBatch();
                }
                insertProductResourceMappingStatement.executeBatch();
            }
            // Restoring AM_API_CLIENT_CERTIFICATE table entries
            PreparedStatement removeClientCertificatesStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_CURRENT_API_ENTRIES_IN_AM_API_CLIENT_CERTIFICATE_BY_API_ID);
            removeClientCertificatesStatement.setInt(1, apiId);
            removeClientCertificatesStatement.executeUpdate();
            PreparedStatement getClientCertificatesStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_CLIENT_CERTIFICATES_BY_REVISION_UUID);
            getClientCertificatesStatement.setInt(1, apiId);
            getClientCertificatesStatement.setString(2, apiRevision.getRevisionUUID());
            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_AS_CURRENT_API);
            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, "Current API");
                insertClientCertificateStatement.addBatch();
            }
            insertClientCertificateStatement.executeBatch();
            // Restoring AM_GRAPHQL_COMPLEXITY table
            PreparedStatement removeGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_CURRENT_API_ENTRIES_IN_AM_GRAPHQL_COMPLEXITY_BY_API_ID);
            removeGraphQLComplexityStatement.setInt(1, apiId);
            removeGraphQLComplexityStatement.executeUpdate();
            PreparedStatement getGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_GRAPHQL_COMPLEXITY_BY_REVISION_UUID);
            List<CustomComplexityDetails> customComplexityDetailsList = new ArrayList<>();
            getGraphQLComplexityStatement.setInt(1, apiId);
            getGraphQLComplexityStatement.setString(2, apiRevision.getRevisionUUID());
            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_AS_CURRENT_API);
            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.addBatch();
            }
            insertGraphQLComplexityStatement.executeBatch();
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            handleException("Failed to restore API Revision entry of API UUID " + apiRevision.getApiUUID(), e);
        }
    } catch (SQLException e) {
        handleException("Failed to restore API Revision entry of API 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) 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) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 20 with ClientCertificateDTO

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

the class CertificateMgtDAO method getClientCertificates.

/**
 * Method to retrieve certificate metadata from db for specific tenant which matches alias or api identifier.
 * Both alias and api identifier are optional
 *
 * @param tenantId      : The id of the tenant which the certificate belongs to.
 * @param alias         : Alias for the certificate. (Optional)
 * @param apiIdentifier : The API which the certificate is mapped to. (Optional)
 * @param organization  : Organization
 * @return : A CertificateMetadataDTO object if the certificate is retrieved successfully, null otherwise.
 */
public List<ClientCertificateDTO> getClientCertificates(int tenantId, String alias, APIIdentifier apiIdentifier, String organization) throws CertificateManagementException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    List<ClientCertificateDTO> clientCertificateDTOS = new ArrayList<>();
    int apiId = 0;
    int index = 1;
    String selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT;
    if (StringUtils.isNotEmpty(alias) && apiIdentifier != null) {
        selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT_ALIAS_APIID;
    } else if (StringUtils.isNotEmpty(alias)) {
        selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT_ALIAS;
    } else if (apiIdentifier != null) {
        selectQuery = SQLConstants.ClientCertificateConstants.SELECT_CERTIFICATE_FOR_TENANT_APIID;
    }
    try {
        connection = APIMgtDBUtil.getConnection();
        if (apiIdentifier != null) {
            String apiUuid;
            if (apiIdentifier.getUUID() != null) {
                apiUuid = apiIdentifier.getUUID();
                APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiUuid);
                if (apiRevision != null && apiRevision.getApiUUID() != null) {
                    apiUuid = apiRevision.getApiUUID();
                }
            } else {
                apiUuid = ApiMgtDAO.getInstance().getUUIDFromIdentifier(apiIdentifier, organization);
            }
            apiId = ApiMgtDAO.getInstance().getAPIID(apiUuid, connection);
        }
        preparedStatement = connection.prepareStatement(selectQuery);
        preparedStatement.setBoolean(index, false);
        index++;
        preparedStatement.setInt(index, tenantId);
        index++;
        if (alias != null) {
            preparedStatement.setString(index, alias);
            index++;
        }
        if (apiIdentifier != null) {
            preparedStatement.setInt(index, apiId);
        }
        resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            alias = resultSet.getString("ALIAS");
            ClientCertificateDTO clientCertificateDTO = new ClientCertificateDTO();
            clientCertificateDTO.setTierName(resultSet.getString("TIER_NAME"));
            clientCertificateDTO.setAlias(alias);
            clientCertificateDTO.setCertificate(APIMgtDBUtil.getStringFromInputStream(resultSet.getBinaryStream("CERTIFICATE")));
            if (apiIdentifier == null) {
                apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(resultSet.getString("API_PROVIDER")), resultSet.getString("API_NAME"), resultSet.getString("API_VERSION"));
            }
            clientCertificateDTO.setApiIdentifier(apiIdentifier);
            clientCertificateDTOS.add(clientCertificateDTO);
        }
    } catch (SQLException e) {
        handleException("Error while searching client certificate details for the tenant " + tenantId, e);
    } catch (APIManagementException e) {
        handleException("API Management Exception while searching client certificate details for the tenant " + tenantId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
    }
    return clientCertificateDTOS;
}
Also used : APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

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