Search in sources :

Example 76 with APIProductIdentifier

use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.

the class InMemoryAPIDeployer method unDeployAPI.

private void unDeployAPI(APIGatewayAdmin apiGatewayAdmin, DeployAPIInGatewayEvent gatewayEvent) throws AxisFault {
    if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled()) {
        GatewayAPIDTO gatewayAPIDTO = new GatewayAPIDTO();
        gatewayAPIDTO.setName(gatewayEvent.getName());
        gatewayAPIDTO.setVersion(gatewayEvent.getVersion());
        gatewayAPIDTO.setProvider(gatewayEvent.getProvider());
        gatewayAPIDTO.setTenantDomain(gatewayEvent.getTenantDomain());
        gatewayAPIDTO.setApiId(gatewayEvent.getUuid());
        setClientCertificatesToRemoveIntoGatewayDTO(gatewayAPIDTO);
        if (APIConstants.API_PRODUCT.equals(gatewayEvent.getApiType())) {
            APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(gatewayEvent.getProvider(), gatewayEvent.getName(), gatewayEvent.getVersion());
            Set<APIEvent> associatedApis = gatewayEvent.getAssociatedApis();
            for (APIEvent associatedApi : associatedApis) {
                GatewayUtils.setCustomSequencesToBeRemoved(apiProductIdentifier, associatedApi.getUuid(), gatewayAPIDTO);
                GatewayUtils.setEndpointsToBeRemoved(apiProductIdentifier, associatedApi.getUuid(), gatewayAPIDTO);
            }
        } else {
            API api = new API(new APIIdentifier(gatewayEvent.getProvider(), gatewayEvent.getName(), gatewayEvent.getVersion()));
            if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(gatewayEvent.getApiType())) {
                gatewayAPIDTO.setLocalEntriesToBeRemove(org.wso2.carbon.apimgt.impl.utils.GatewayUtils.addStringToList(gatewayEvent.getUuid().concat("_graphQL"), gatewayAPIDTO.getLocalEntriesToBeRemove()));
                DataHolder.getInstance().getApiToGraphQLSchemaDTOMap().remove(gatewayEvent.getUuid());
            }
            if (APIConstants.APITransportType.WS.toString().equalsIgnoreCase(gatewayEvent.getApiType())) {
                org.wso2.carbon.apimgt.gateway.utils.GatewayUtils.setWebsocketEndpointsToBeRemoved(gatewayAPIDTO, gatewayEvent.getTenantDomain());
            } else {
                GatewayUtils.setEndpointsToBeRemoved(gatewayAPIDTO.getName(), gatewayAPIDTO.getVersion(), gatewayAPIDTO);
            }
            GatewayUtils.setCustomSequencesToBeRemoved(api, gatewayAPIDTO);
        }
        gatewayAPIDTO.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(gatewayEvent.getUuid(), gatewayAPIDTO.getLocalEntriesToBeRemove()));
        apiGatewayAdmin.unDeployAPI(gatewayAPIDTO);
        DataHolder.getInstance().getApiToCertificatesMap().remove(gatewayEvent.getUuid());
        DataHolder.getInstance().removeKeyManagerToAPIMapping(gatewayAPIDTO.getApiId());
    }
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 77 with APIProductIdentifier

use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.

the class ApiMgtDAO method addAPIProductResourceMappings.

/**
 * Add api product url mappings to DB
 * - url templeates to product mappings (resource bundling) - AM_API_PRODUCT_MAPPING
 *
 * @param productResources
 * @param organization
 * @param connection
 * @throws APIManagementException
 */
public void addAPIProductResourceMappings(List<APIProductResource> productResources, String organization, Connection connection) throws APIManagementException {
    String addProductResourceMappingSql = SQLConstants.ADD_PRODUCT_RESOURCE_MAPPING_SQL;
    boolean isNewConnection = false;
    try {
        if (connection == null) {
            connection = APIMgtDBUtil.getConnection();
            isNewConnection = true;
        }
        Set<String> usedClonedPolicies = new HashSet<>();
        Map<String, String> clonedPoliciesMap = new HashMap<>();
        // add the duplicate resources in each API in the API product.
        for (APIProductResource apiProductResource : productResources) {
            APIProductIdentifier productIdentifier = apiProductResource.getProductIdentifier();
            String uuid;
            if (productIdentifier.getUUID() != null) {
                uuid = productIdentifier.getUUID();
            } else {
                uuid = getUUIDFromIdentifier(productIdentifier, organization, connection);
            }
            int productId = getAPIID(uuid, connection);
            int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(productIdentifier.getProviderName()));
            String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
            URITemplate uriTemplateOriginal = apiProductResource.getUriTemplate();
            int urlMappingId = uriTemplateOriginal.getId();
            // Adding to AM_API_URL_MAPPING table
            PreparedStatement getURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_URL_MAPPINGS_WITH_SCOPE_BY_URL_MAPPING_ID);
            getURLMappingsStatement.setInt(1, urlMappingId);
            List<URITemplate> urlMappingList = new ArrayList<>();
            try (ResultSet rs = getURLMappingsStatement.executeQuery()) {
                while (rs.next()) {
                    URITemplate uriTemplate = new URITemplate();
                    uriTemplate.setHTTPVerb(rs.getString("HTTP_METHOD"));
                    uriTemplate.setAuthType(rs.getString("AUTH_SCHEME"));
                    uriTemplate.setUriTemplate(rs.getString("URL_PATTERN"));
                    uriTemplate.setThrottlingTier(rs.getString("THROTTLING_TIER"));
                    String script = null;
                    InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
                    if (mediationScriptBlob != null) {
                        script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
                    }
                    uriTemplate.setMediationScript(script);
                    if (!StringUtils.isEmpty(rs.getString("SCOPE_NAME"))) {
                        Scope scope = new Scope();
                        scope.setKey(rs.getString("SCOPE_NAME"));
                        uriTemplate.setScope(scope);
                    }
                    if (rs.getInt("API_ID") != 0) {
                        // Adding api id to uri template id just to store value
                        uriTemplate.setId(rs.getInt("API_ID"));
                    }
                    List<OperationPolicy> operationPolicies = getOperationPoliciesOfURITemplate(urlMappingId);
                    uriTemplate.setOperationPolicies(operationPolicies);
                    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);
                }
            }
            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, String.valueOf(productId));
                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_URL_MAPPINGS_ID);
            PreparedStatement insertScopeResourceMappingStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_SCOPE_RESOURCE_MAPPING);
            PreparedStatement insertProductResourceMappingStatement = connection.prepareStatement(addProductResourceMappingSql);
            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") });
            for (URITemplate urlMapping : uriTemplateMap.values()) {
                getRevisionedURLMappingsStatement.setInt(1, urlMapping.getId());
                getRevisionedURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
                getRevisionedURLMappingsStatement.setString(3, urlMapping.getAuthType());
                getRevisionedURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
                getRevisionedURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
                getRevisionedURLMappingsStatement.setString(6, String.valueOf(productId));
                if (!urlMapping.getScopes().isEmpty()) {
                    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, productId);
                        insertProductResourceMappingStatement.setInt(2, rs.getInt(1));
                        insertProductResourceMappingStatement.setString(3, "Current API");
                        insertProductResourceMappingStatement.addBatch();
                    }
                }
                try (ResultSet rs = getRevisionedURLMappingsStatement.executeQuery()) {
                    while (rs.next()) {
                        for (OperationPolicy policy : urlMapping.getOperationPolicies()) {
                            if (!clonedPoliciesMap.keySet().contains(policy.getPolicyId())) {
                                OperationPolicyData existingPolicy = getAPISpecificOperationPolicyByPolicyID(policy.getPolicyId(), uuid, tenantDomain, false);
                                String clonedPolicyId = policy.getPolicyId();
                                if (existingPolicy != null) {
                                    if (existingPolicy.isClonedPolicy()) {
                                        usedClonedPolicies.add(clonedPolicyId);
                                    }
                                } else {
                                    // Even though the policy ID attached is not in the API specific policy list for the product uuid,
                                    // it can be from the dependent API and we need to verify that it has not been previously cloned
                                    // for the product before cloning again.
                                    clonedPolicyId = getClonedPolicyIdForCommonPolicyId(connection, policy.getPolicyId(), uuid);
                                    if (clonedPolicyId == null) {
                                        clonedPolicyId = cloneOperationPolicy(connection, policy.getPolicyId(), uuid, null);
                                    }
                                    usedClonedPolicies.add(clonedPolicyId);
                                // usedClonedPolicies set will not contain used API specific policies that are not cloned.
                                // TODO: discuss whether we need to clone API specific policies as well
                                }
                                // Updated policies map will record the updated policy ID for the used policy ID.
                                // If the policy has been cloned to the API specific policy list, we need to use the
                                // updated policy Id.
                                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();
        }
    } catch (SQLException e) {
        handleException("Error while adding API product Resources", e);
    } finally {
        if (isNewConnection) {
            APIMgtDBUtil.closeAllConnections(null, connection, null);
        }
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) PreparedStatement(java.sql.PreparedStatement) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) OperationPolicyData(org.wso2.carbon.apimgt.api.model.OperationPolicyData) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) ResultSet(java.sql.ResultSet) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 78 with APIProductIdentifier

use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.

the class ApiMgtDAO method getAPISubscriptionCountByAPI.

public long getAPISubscriptionCountByAPI(Identifier identifier) throws APIManagementException {
    String sqlQuery = SQLConstants.GET_API_SUBSCRIPTION_COUNT_BY_API_SQL;
    String artifactType = APIConstants.API_IDENTIFIER_TYPE;
    if (identifier instanceof APIProductIdentifier) {
        artifactType = APIConstants.API_PRODUCT_IDENTIFIER_TYPE;
    }
    long subscriptions = 0;
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement ps = connection.prepareStatement(sqlQuery)) {
        ps.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        ps.setString(2, identifier.getName());
        ps.setString(3, identifier.getVersion());
        try (ResultSet result = ps.executeQuery()) {
            while (result.next()) {
                subscriptions = result.getLong("SUB_ID");
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get subscription count for " + artifactType, e);
    }
    return subscriptions;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 79 with APIProductIdentifier

use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier 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)

Example 80 with APIProductIdentifier

use of org.wso2.carbon.apimgt.api.model.APIProductIdentifier in project carbon-apimgt by wso2.

the class ApiMgtDAO method addAPIProduct.

public void addAPIProduct(APIProduct apiProduct, String organization) throws APIManagementException {
    Connection connection = null;
    PreparedStatement prepStmtAddAPIProduct = null;
    PreparedStatement prepStmtAddScopeEntry = null;
    if (log.isDebugEnabled()) {
        log.debug("addAPIProduct() : " + apiProduct.toString() + " for organization " + organization);
    }
    APIProductIdentifier identifier = apiProduct.getId();
    ResultSet rs = null;
    int productId = 0;
    int scopeId = 0;
    try {
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        String queryAddAPIProduct = SQLConstants.ADD_API_PRODUCT;
        prepStmtAddAPIProduct = connection.prepareStatement(queryAddAPIProduct, new String[] { "api_id" });
        prepStmtAddAPIProduct.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        prepStmtAddAPIProduct.setString(2, identifier.getName());
        prepStmtAddAPIProduct.setString(3, identifier.getVersion());
        prepStmtAddAPIProduct.setString(4, apiProduct.getContext());
        prepStmtAddAPIProduct.setString(5, apiProduct.getProductLevelPolicy());
        prepStmtAddAPIProduct.setString(6, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        prepStmtAddAPIProduct.setTimestamp(7, new Timestamp(System.currentTimeMillis()));
        prepStmtAddAPIProduct.setString(8, APIConstants.API_PRODUCT);
        prepStmtAddAPIProduct.setString(9, apiProduct.getUuid());
        prepStmtAddAPIProduct.setString(10, apiProduct.getState());
        prepStmtAddAPIProduct.setString(11, organization);
        prepStmtAddAPIProduct.setString(12, apiProduct.getGatewayVendor());
        prepStmtAddAPIProduct.setString(13, apiProduct.getVersionTimestamp());
        prepStmtAddAPIProduct.execute();
        rs = prepStmtAddAPIProduct.getGeneratedKeys();
        if (rs.next()) {
            productId = rs.getInt(1);
        }
        // breaks the flow if product is not added to the db correctly
        if (productId == 0) {
            throw new APIManagementException("Error while adding API product " + apiProduct.getUuid());
        }
        addAPIProductResourceMappings(apiProduct.getProductResources(), apiProduct.getOrganization(), connection);
        String tenantUserName = MultitenantUtils.getTenantAwareUsername(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        recordAPILifeCycleEvent(productId, null, APIStatus.CREATED.toString(), tenantUserName, tenantId, connection);
        connection.commit();
    } catch (SQLException e) {
        handleException("Error while adding API product " + identifier.getName() + " of provider " + APIUtil.replaceEmailDomainBack(identifier.getProviderName()), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmtAddAPIProduct, null, null);
        APIMgtDBUtil.closeAllConnections(prepStmtAddScopeEntry, connection, null);
    }
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp)

Aggregations

APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)91 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)48 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)33 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)22 PreparedStatement (java.sql.PreparedStatement)19 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)19 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)19 Connection (java.sql.Connection)18 ArrayList (java.util.ArrayList)18 ResultSet (java.sql.ResultSet)17 SQLException (java.sql.SQLException)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 API (org.wso2.carbon.apimgt.api.model.API)14 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)14 HashSet (java.util.HashSet)13 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)13 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)13 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)13 Tier (org.wso2.carbon.apimgt.api.model.Tier)12 PublisherAPIProduct (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)12