Search in sources :

Example 26 with URITemplate

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

the class OAS2Parser method getURITemplates.

/**
 * This method returns URI templates according to the given swagger file
 *
 * @param resourceConfigsJSON swaggerJSON
 * @return URI Templates
 * @throws APIManagementException
 */
@Override
public Set<URITemplate> getURITemplates(String resourceConfigsJSON) throws APIManagementException {
    Swagger swagger = getSwagger(resourceConfigsJSON);
    Set<URITemplate> urlTemplates = new LinkedHashSet<>();
    Set<Scope> scopes = getScopes(resourceConfigsJSON);
    String oauth2SchemeKey = getOAuth2SecuritySchemeKey(swagger);
    for (String pathString : swagger.getPaths().keySet()) {
        Path path = swagger.getPath(pathString);
        Map<HttpMethod, Operation> operationMap = path.getOperationMap();
        for (Map.Entry<HttpMethod, Operation> entry : operationMap.entrySet()) {
            Operation operation = entry.getValue();
            URITemplate template = new URITemplate();
            template.setHTTPVerb(entry.getKey().name().toUpperCase());
            template.setHttpVerbs(entry.getKey().name().toUpperCase());
            template.setUriTemplate(pathString);
            List<String> opScopes = getScopeOfOperations(oauth2SchemeKey, operation);
            if (!opScopes.isEmpty()) {
                if (opScopes.size() == 1) {
                    String firstScope = opScopes.get(0);
                    if (StringUtils.isNotBlank(firstScope)) {
                        Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
                        if (scope == null) {
                            throw new APIManagementException("Scope '" + firstScope + "' not found.");
                        }
                        template.setScope(scope);
                        template.setScopes(scope);
                    }
                } else {
                    template = OASParserUtil.setScopesToTemplate(template, opScopes, scopes);
                }
            }
            Map<String, Object> extensions = operation.getVendorExtensions();
            if (extensions != null) {
                if (extensions.containsKey(APIConstants.SWAGGER_X_AUTH_TYPE)) {
                    String authType = (String) extensions.get(APIConstants.SWAGGER_X_AUTH_TYPE);
                    template.setAuthType(authType);
                    template.setAuthTypes(authType);
                } else {
                    template.setAuthType("Any");
                    template.setAuthTypes("Any");
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_THROTTLING_TIER)) {
                    String throttlingTier = (String) extensions.get(APIConstants.SWAGGER_X_THROTTLING_TIER);
                    template.setThrottlingTier(throttlingTier);
                    template.setThrottlingTiers(throttlingTier);
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_MEDIATION_SCRIPT)) {
                    String mediationScript = (String) extensions.get(APIConstants.SWAGGER_X_MEDIATION_SCRIPT);
                    template.setMediationScript(mediationScript);
                    template.setMediationScripts(template.getHTTPVerb(), mediationScript);
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                    template.setAmznResourceName((String) extensions.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                }
                if (extensions.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                    template.setAmznResourceTimeout(((Long) extensions.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                }
            }
            urlTemplates.add(template);
        }
    }
    return urlTemplates;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Operation(io.swagger.models.Operation) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Swagger(io.swagger.models.Swagger) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Example 27 with URITemplate

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

the class AsyncApiParser method buildURITemplate.

private URITemplate buildURITemplate(String target, String verb, Aai20Operation operation, Set<Scope> scopes, Aai20ChannelItem channel) throws APIManagementException {
    URITemplate template = new URITemplate();
    template.setHTTPVerb(verb);
    template.setHttpVerbs(verb);
    template.setUriTemplate(target);
    Extension authTypeExtension = channel.getExtension(APIConstants.SWAGGER_X_AUTH_TYPE);
    if (authTypeExtension != null && authTypeExtension.value instanceof String) {
        template.setAuthType(authTypeExtension.value.toString());
    }
    List<String> opScopes = getScopeOfOperations(operation);
    if (!opScopes.isEmpty()) {
        if (opScopes.size() == 1) {
            String firstScope = opScopes.get(0);
            Scope scope = APIUtil.findScopeByKey(scopes, firstScope);
            if (scope == null) {
                throw new APIManagementException("Scope '" + firstScope + "' not found.");
            }
            template.setScope(scope);
            template.setScopes(scope);
        } else {
            for (String scopeName : opScopes) {
                Scope scope = APIUtil.findScopeByKey(scopes, scopeName);
                if (scope == null) {
                    throw new APIManagementException("Resource Scope '" + scopeName + "' not found.");
                }
                template.setScopes(scope);
            }
        }
    }
    return template;
}
Also used : Extension(io.apicurio.datamodels.core.models.Extension) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate)

Example 28 with URITemplate

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

the class RegistryPersistenceUtilTestCase method testcreateAPIArtifactContent.

@Test
public void testcreateAPIArtifactContent() throws APIPersistenceException, APIManagementException, RegistryException {
    API api = new API(new APIIdentifier("pubuser", "TestAPI", "1.0"));
    Set<Tier> availableTiers = new HashSet<Tier>();
    availableTiers.add(new Tier("Unlimited"));
    availableTiers.add(new Tier("Gold"));
    api.setAvailableTiers(availableTiers);
    Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
    URITemplate template = new URITemplate();
    template.setHTTPVerb("GET");
    template.setUriTemplate("/test");
    template.setAuthType("None");
    uriTemplates.add(template);
    api.setUriTemplates(uriTemplates);
    List<APICategory> categories = new ArrayList<APICategory>();
    APICategory category = new APICategory();
    category.setName("testcategory");
    categories.add(category);
    api.setApiCategories(categories);
    List<Label> gatewayLabels = new ArrayList<Label>();
    Label label = new Label();
    label.setName("TestLabel");
    gatewayLabels.add(label);
    GenericArtifact genericArtifact = new GenericArtifactImpl(new QName("", "TestAPI", ""), "application/vnd.wso2-api+xml");
    genericArtifact.setAttribute("URITemplate", "/test");
    GenericArtifact retArtifact = RegistryPersistenceUtil.createAPIArtifactContent(genericArtifact, api);
    Assert.assertEquals("API name does not match", api.getId().getApiName(), retArtifact.getAttribute("overview_name"));
    Assert.assertEquals("API version does not match", api.getId().getVersion(), retArtifact.getAttribute("overview_version"));
    Assert.assertEquals("API provider does not match", api.getId().getProviderName(), retArtifact.getAttribute("overview_provider"));
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) Tier(org.wso2.carbon.apimgt.api.model.Tier) QName(javax.xml.namespace.QName) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) Label(org.wso2.carbon.apimgt.api.model.Label) GenericArtifactImpl(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) HashSet(java.util.HashSet) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 29 with URITemplate

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

the class ApiMgtDAO method restoreAPIRevision.

/**
 * Restore API revision database records as the Current API of an API
 *
 * @param apiRevision content of the revision
 * @throws APIManagementException if an error occurs when restoring an API revision
 */
public void restoreAPIRevision(APIRevision apiRevision) throws APIManagementException {
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try {
            connection.setAutoCommit(false);
            // 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);
            // Removing related Current API entries from AM_API_URL_MAPPING table
            PreparedStatement removeURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_CURRENT_API_ENTRIES_IN_AM_API_URL_MAPPING_BY_API_ID);
            removeURLMappingsStatement.setInt(1, apiId);
            removeURLMappingsStatement.executeUpdate();
            // Restoring to AM_API_URL_MAPPING table
            PreparedStatement getURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_URL_MAPPINGS_WITH_SCOPE_AND_PRODUCT_ID_BY_REVISION_UUID);
            getURLMappingsStatement.setInt(1, apiId);
            getURLMappingsStatement.setString(2, apiRevision.getRevisionUUID());
            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 {
                    uriTemplateMap.put(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb(), urlMapping);
                }
            }
            setOperationPoliciesToURITemplatesMap(apiRevision.getRevisionUUID(), uriTemplateMap);
            PreparedStatement insertURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_URL_MAPPINGS_CURRENT_API);
            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.addBatch();
            }
            insertURLMappingsStatement.executeBatch();
            // Add to AM_API_RESOURCE_SCOPE_MAPPING table and to AM_API_PRODUCT_MAPPING
            PreparedStatement getCurrentAPIURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_CURRENT_API_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);
            PreparedStatement deleteOutdatedOperationPolicyStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.DELETE_OPERATION_POLICY_BY_POLICY_ID);
            Map<String, String> restoredPolicyMap = new HashMap<>();
            Set<String> usedClonedPolicies = new HashSet<String>();
            for (URITemplate urlMapping : uriTemplateMap.values()) {
                if (urlMapping.getScopes() != null) {
                    getCurrentAPIURLMappingsStatement.setInt(1, apiId);
                    getCurrentAPIURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
                    getCurrentAPIURLMappingsStatement.setString(3, urlMapping.getAuthType());
                    getCurrentAPIURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
                    getCurrentAPIURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
                    try (ResultSet rs = getCurrentAPIURLMappingsStatement.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();
                            }
                        }
                    }
                }
                if (urlMapping.getId() != 0) {
                    getCurrentAPIURLMappingsStatement.setInt(1, apiId);
                    getCurrentAPIURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
                    getCurrentAPIURLMappingsStatement.setString(3, urlMapping.getAuthType());
                    getCurrentAPIURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
                    getCurrentAPIURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
                    try (ResultSet rs = getCurrentAPIURLMappingsStatement.executeQuery()) {
                        while (rs.next()) {
                            insertProductResourceMappingStatement.setInt(1, urlMapping.getId());
                            insertProductResourceMappingStatement.setInt(2, rs.getInt(1));
                            insertProductResourceMappingStatement.addBatch();
                        }
                    }
                }
                if (!urlMapping.getOperationPolicies().isEmpty()) {
                    getCurrentAPIURLMappingsStatement.setInt(1, apiId);
                    getCurrentAPIURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
                    getCurrentAPIURLMappingsStatement.setString(3, urlMapping.getAuthType());
                    getCurrentAPIURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
                    getCurrentAPIURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
                    try (ResultSet rs = getCurrentAPIURLMappingsStatement.executeQuery()) {
                        while (rs.next()) {
                            for (OperationPolicy policy : urlMapping.getOperationPolicies()) {
                                if (!restoredPolicyMap.keySet().contains(policy.getPolicyName())) {
                                    String restoredPolicyId = restoreOperationPolicyRevision(connection, apiRevision.getApiUUID(), policy.getPolicyId(), apiRevision.getId(), 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.
                                    restoredPolicyMap.put(policy.getPolicyName(), restoredPolicyId);
                                    usedClonedPolicies.add(restoredPolicyId);
                                }
                                Gson gson = new Gson();
                                String paramJSON = gson.toJson(policy.getParameters());
                                insertOperationPolicyMappingStatement.setInt(1, rs.getInt(1));
                                insertOperationPolicyMappingStatement.setString(2, restoredPolicyMap.get(policy.getPolicyName()));
                                insertOperationPolicyMappingStatement.setString(3, policy.getDirection());
                                insertOperationPolicyMappingStatement.setString(4, paramJSON);
                                insertOperationPolicyMappingStatement.setInt(5, policy.getOrder());
                                insertOperationPolicyMappingStatement.addBatch();
                            }
                        }
                    }
                }
            }
            insertScopeResourceMappingStatement.executeBatch();
            insertProductResourceMappingStatement.executeBatch();
            insertOperationPolicyMappingStatement.executeBatch();
            deleteOutdatedOperationPolicyStatement.executeBatch();
            cleanUnusedClonedOperationPolicies(connection, usedClonedPolicies, apiRevision.getApiUUID());
            // 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();
            restoreAPIRevisionMetaDataToWorkingCopy(connection, apiRevision.getApiUUID(), apiRevision.getRevisionUUID());
            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) 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) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 30 with URITemplate

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

the class ApiMgtDAO method addOperationPolicyMapping.

public void addOperationPolicyMapping(Set<URITemplate> uriTemplates) throws APIManagementException {
    if (uriTemplates != null && !uriTemplates.isEmpty()) {
        try (Connection connection = APIMgtDBUtil.getConnection()) {
            connection.setAutoCommit(false);
            try (PreparedStatement preparedStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING)) {
                for (URITemplate uriTemplate : uriTemplates) {
                    List<OperationPolicy> operationPolicies = uriTemplate.getOperationPolicies();
                    if (operationPolicies != null && !operationPolicies.isEmpty()) {
                        for (OperationPolicy operationPolicy : operationPolicies) {
                            Gson gson = new Gson();
                            String paramJSON = gson.toJson(operationPolicy.getParameters());
                            preparedStatement.setInt(1, uriTemplate.getId());
                            preparedStatement.setString(2, operationPolicy.getPolicyId());
                            preparedStatement.setString(3, operationPolicy.getDirection());
                            preparedStatement.setString(4, paramJSON);
                            preparedStatement.setInt(5, operationPolicy.getOrder());
                            preparedStatement.addBatch();
                        }
                    }
                }
                preparedStatement.executeBatch();
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        } catch (SQLException e) {
            throw new APIManagementException("Error while updating operation Policy mapping for API", e);
        }
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) Connection(java.sql.Connection) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) PreparedStatement(java.sql.PreparedStatement)

Aggregations

URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)122 HashMap (java.util.HashMap)71 ArrayList (java.util.ArrayList)67 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)42 Scope (org.wso2.carbon.apimgt.api.model.Scope)41 API (org.wso2.carbon.apimgt.api.model.API)38 UriTemplate (org.wso2.carbon.apimgt.core.models.UriTemplate)38 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)37 HashSet (java.util.HashSet)36 LinkedHashSet (java.util.LinkedHashSet)28 PreparedStatement (java.sql.PreparedStatement)25 ResultSet (java.sql.ResultSet)23 API (org.wso2.carbon.apimgt.core.models.API)22 Map (java.util.Map)21 Tier (org.wso2.carbon.apimgt.api.model.Tier)21 Connection (java.sql.Connection)20 OperationPolicy (org.wso2.carbon.apimgt.api.model.OperationPolicy)20 LinkedHashMap (java.util.LinkedHashMap)19 List (java.util.List)19 SQLException (java.sql.SQLException)16