Search in sources :

Example 96 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class APIMgtGatewayCacheMessageListener method handleResourceCacheInvalidationMessage.

private void handleResourceCacheInvalidationMessage(JSONObject jsonValue) throws ParseException {
    String apiContext = (String) jsonValue.get("apiContext");
    String apiVersion = (String) jsonValue.get("apiVersion");
    JSONArray resources = (JSONArray) jsonValue.get("resources");
    List<ResourceCacheInvalidationDto> resourceCacheInvalidationDtoList = new ArrayList<>();
    for (Object resource : resources) {
        JSONObject uriTemplate = (JSONObject) resource;
        String resourceURLContext = (String) uriTemplate.get("resourceURLContext");
        String httpVerb = (String) uriTemplate.get("httpVerb");
        ResourceCacheInvalidationDto uriTemplateDto = new ResourceCacheInvalidationDto();
        uriTemplateDto.setHttpVerb(httpVerb);
        uriTemplateDto.setResourceURLContext(resourceURLContext);
        resourceCacheInvalidationDtoList.add(uriTemplateDto);
    }
    ServiceReferenceHolder.getInstance().getCacheInvalidationService().invalidateResourceCache(apiContext, apiVersion, resourceCacheInvalidationDtoList.toArray(new ResourceCacheInvalidationDto[0]));
}
Also used : JSONObject(org.json.simple.JSONObject) ResourceCacheInvalidationDto(org.wso2.carbon.apimgt.api.dto.ResourceCacheInvalidationDto) JSONArray(org.json.simple.JSONArray) ArrayList(java.util.ArrayList) JSONObject(org.json.simple.JSONObject)

Example 97 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class APIGatewayAdmin method convert.

private org.wso2.carbon.apimgt.gateway.dto.APIData convert(APIData data) {
    if (data == null) {
        return null;
    }
    org.wso2.carbon.apimgt.gateway.dto.APIData apiData = new org.wso2.carbon.apimgt.gateway.dto.APIData();
    apiData.setContext(data.getContext());
    apiData.setFileName(data.getFileName());
    apiData.setHost(data.getHost());
    apiData.setName(data.getName());
    apiData.setPort(data.getPort());
    ResourceData[] resources = data.getResources();
    List<org.wso2.carbon.apimgt.gateway.dto.ResourceData> resList = new ArrayList<org.wso2.carbon.apimgt.gateway.dto.ResourceData>();
    if (resources != null && resources.length > 0) {
        for (ResourceData res : resources) {
            if (res == null) {
                continue;
            }
            org.wso2.carbon.apimgt.gateway.dto.ResourceData resource = convert(res);
            resList.add(resource);
        }
        apiData.setResources(resList.toArray(new org.wso2.carbon.apimgt.gateway.dto.ResourceData[0]));
    }
    return apiData;
}
Also used : ResourceData(org.wso2.carbon.rest.api.ResourceData) ArrayList(java.util.ArrayList) APIData(org.wso2.carbon.rest.api.APIData)

Example 98 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class ApiMgtDAO method addURITemplates.

/**
 * Add URI Templates to database with resource scope mappings by passing the DB connection.
 *
 * @param apiId      API Id
 * @param api        API
 * @param tenantId   tenant Id
 * @param connection Existing DB Connection
 * @throws SQLException If a SQL error occurs while adding URI Templates
 */
private void addURITemplates(int apiId, API api, int tenantId, Connection connection) throws SQLException, APIManagementException {
    String dbProductName = connection.getMetaData().getDatabaseProductName();
    String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
    try (PreparedStatement uriMappingPrepStmt = connection.prepareStatement(SQLConstants.ADD_URL_MAPPING_SQL, new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "URL_MAPPING_ID") });
        PreparedStatement uriScopeMappingPrepStmt = connection.prepareStatement(SQLConstants.ADD_API_RESOURCE_SCOPE_MAPPING);
        PreparedStatement operationPolicyMappingPrepStmt = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING)) {
        Map<String, String> updatedPoliciesMap = new HashMap<>();
        Set<String> usedClonedPolicies = new HashSet<String>();
        for (URITemplate uriTemplate : api.getUriTemplates()) {
            uriMappingPrepStmt.setInt(1, apiId);
            uriMappingPrepStmt.setString(2, uriTemplate.getHTTPVerb());
            uriMappingPrepStmt.setString(3, uriTemplate.getAuthType());
            uriMappingPrepStmt.setString(4, uriTemplate.getUriTemplate());
            // If API policy is available then set it for all the resources.
            if (StringUtils.isEmpty(api.getApiLevelPolicy())) {
                uriMappingPrepStmt.setString(5, (StringUtils.isEmpty(uriTemplate.getThrottlingTier())) ? APIConstants.UNLIMITED_TIER : uriTemplate.getThrottlingTier());
            } else {
                uriMappingPrepStmt.setString(5, (StringUtils.isEmpty(api.getApiLevelPolicy())) ? APIConstants.UNLIMITED_TIER : api.getApiLevelPolicy());
            }
            InputStream is = null;
            if (uriTemplate.getMediationScript() != null) {
                is = new ByteArrayInputStream(uriTemplate.getMediationScript().getBytes(Charset.defaultCharset()));
            }
            if (connection.getMetaData().getDriverName().contains("PostgreSQL") || connection.getMetaData().getDatabaseProductName().contains("DB2")) {
                if (uriTemplate.getMediationScript() != null) {
                    uriMappingPrepStmt.setBinaryStream(6, is, uriTemplate.getMediationScript().getBytes(Charset.defaultCharset()).length);
                } else {
                    uriMappingPrepStmt.setBinaryStream(6, is, 0);
                }
            } else {
                uriMappingPrepStmt.setBinaryStream(6, is);
            }
            uriMappingPrepStmt.execute();
            int uriMappingId = -1;
            try (ResultSet resultIdSet = uriMappingPrepStmt.getGeneratedKeys()) {
                while (resultIdSet.next()) {
                    uriMappingId = resultIdSet.getInt(1);
                }
            }
            if (uriMappingId != -1) {
                for (Scope uriTemplateScope : uriTemplate.retrieveAllScopes()) {
                    String scopeKey = uriTemplateScope.getKey();
                    if (log.isDebugEnabled()) {
                        log.debug("Adding scope to resource mapping for scope key: " + scopeKey + " and URL mapping Id: " + uriMappingId);
                    }
                    uriScopeMappingPrepStmt.setString(1, scopeKey);
                    uriScopeMappingPrepStmt.setInt(2, uriMappingId);
                    uriScopeMappingPrepStmt.setInt(3, tenantId);
                    uriScopeMappingPrepStmt.addBatch();
                }
                if (uriTemplate.getOperationPolicies() != null) {
                    for (OperationPolicy policy : uriTemplate.getOperationPolicies()) {
                        if (!updatedPoliciesMap.keySet().contains(policy.getPolicyId())) {
                            OperationPolicyData existingPolicy = getAPISpecificOperationPolicyByPolicyID(policy.getPolicyId(), api.getUuid(), 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,
                                // it can be a common policy and we need to verify that it has not been previously cloned
                                // for the API before cloning again.
                                clonedPolicyId = getClonedPolicyIdForCommonPolicyId(connection, policy.getPolicyId(), api.getUuid());
                                if (clonedPolicyId == null) {
                                    clonedPolicyId = cloneOperationPolicy(connection, policy.getPolicyId(), api.getUuid(), 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.
                            updatedPoliciesMap.put(policy.getPolicyId(), clonedPolicyId);
                        }
                        Gson gson = new Gson();
                        String paramJSON = gson.toJson(policy.getParameters());
                        if (log.isDebugEnabled()) {
                            log.debug("Adding operation policy " + policy.getPolicyName() + " for API " + api.getId().getApiName() + " to URL mapping Id " + uriMappingId);
                        }
                        operationPolicyMappingPrepStmt.setInt(1, uriMappingId);
                        operationPolicyMappingPrepStmt.setString(2, updatedPoliciesMap.get(policy.getPolicyId()));
                        operationPolicyMappingPrepStmt.setString(3, policy.getDirection());
                        operationPolicyMappingPrepStmt.setString(4, paramJSON);
                        operationPolicyMappingPrepStmt.setInt(5, policy.getOrder());
                        operationPolicyMappingPrepStmt.addBatch();
                    }
                }
            }
            uriTemplate.setId(uriMappingId);
        }
        // end URITemplate list iteration
        uriScopeMappingPrepStmt.executeBatch();
        operationPolicyMappingPrepStmt.executeBatch();
        cleanUnusedClonedOperationPolicies(connection, usedClonedPolicies, api.getUuid());
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) PreparedStatement(java.sql.PreparedStatement) OperationPolicyData(org.wso2.carbon.apimgt.api.model.OperationPolicyData) Scope(org.wso2.carbon.apimgt.api.model.Scope) ByteArrayInputStream(java.io.ByteArrayInputStream) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) ResultSet(java.sql.ResultSet) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 99 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class APIAuthenticationAdminClient method invalidateResourceCache.

public void invalidateResourceCache(String apiContext, String apiVersion, Set<URITemplate> uriTemplates) {
    JSONObject api = new JSONObject();
    api.put("apiContext", apiContext);
    api.put("apiVersion", apiVersion);
    JSONArray resources = new JSONArray();
    for (URITemplate uriTemplate : uriTemplates) {
        JSONObject resource = new JSONObject();
        resource.put("resourceURLContext", uriTemplate.getUriTemplate());
        resource.put("httpVerb", uriTemplate.getHTTPVerb());
        resources.add(resource);
    }
    api.put("resources", resources);
    Object[] objectData = new Object[] { APIConstants.RESOURCE_CACHE_NAME, StringEscapeUtils.escapeJava(api.toJSONString()) };
    log.debug("Sending Resource Invalidation Message");
    publishEvent(objectData);
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) JSONObject(org.json.simple.JSONObject)

Example 100 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class WSO2APIPublisher method evaluateImportAPIResponse.

/**
 * Check whether successful response is received for API Import service call.
 *
 * @param response HTTP response received for API Import request
 * @return Successful or not
 * @throws APIManagementException If an error occurs while checking the response
 */
private Boolean evaluateImportAPIResponse(CloseableHttpResponse response) throws APIManagementException {
    HttpEntity entity;
    String responseString;
    try {
        // If API is imported successfully, return true
        entity = response.getEntity();
        responseString = EntityUtils.toString(entity);
        // release all resources held by the responseHttpEntity
        EntityUtils.consume(entity);
        if (evaluateResponseStatus(response) && StringUtils.containsIgnoreCase(responseString, APIConstants.RestApiConstants.IMPORT_API_SUCCESS)) {
            if (log.isDebugEnabled()) {
                log.debug("Import API service call received successful response: " + responseString);
            }
            return true;
        } else {
            String errorMessage = "Import API service call received unsuccessful response: " + responseString + " status: " + response.getStatusLine().getStatusCode();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
    } catch (IOException e) {
        String errorMessage = "Error while evaluating HTTP response";
        throw new APIManagementException(errorMessage, e);
    } finally {
        closeHTTPResponse(response);
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) IOException(java.io.IOException)

Aggregations

ArrayList (java.util.ArrayList)49 Test (org.testng.annotations.Test)41 HashMap (java.util.HashMap)30 File (java.io.File)26 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)21 IOException (java.io.IOException)20 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)20 FileInputStream (java.io.FileInputStream)19 Map (java.util.Map)17 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)16 JSONObject (org.json.simple.JSONObject)15 Resource (org.wso2.carbon.registry.core.Resource)15 List (java.util.List)14 Scope (org.wso2.carbon.apimgt.core.models.Scope)14 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)13 API (org.wso2.carbon.apimgt.api.model.API)12 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)12 API (org.wso2.carbon.apimgt.core.models.API)12 Collection (org.wso2.carbon.registry.core.Collection)12