Search in sources :

Example 11 with OperationPolicyData

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

the class ApisApiServiceImpl method getOperationPolicyForAPIByPolicyId.

/**
 * Get the API specific operation policy specification by providing the policy ID
 *
 * @param apiId             API UUID
 * @param operationPolicyId UUID of the operation policy
 * @param messageContext    message context
 * @return Operation policy DTO as response
 */
@Override
public Response getOperationPolicyForAPIByPolicyId(String apiId, String operationPolicyId, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // validate whether api exists or not
        validateAPIExistence(apiId);
        OperationPolicyData existingPolicy = apiProvider.getAPISpecificOperationPolicyByPolicyId(operationPolicyId, apiId, organization, false);
        if (existingPolicy != null) {
            OperationPolicyDataDTO policyDataDTO = OperationPolicyMappingUtil.fromOperationPolicyDataToDTO(existingPolicy);
            return Response.ok().entity(policyDataDTO).build();
        } else {
            throw new APIMgtResourceNotFoundException("Couldn't retrieve an existing operation policy with ID: " + operationPolicyId + " for API " + apiId, ExceptionCodes.from(ExceptionCodes.OPERATION_POLICY_NOT_FOUND, operationPolicyId));
        }
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PATH_OPERATION_POLICIES, operationPolicyId, e, log);
        } else {
            String errorMessage = "Error while getting an API specific operation policy with ID :" + operationPolicyId + " for API " + apiId + " " + e.getMessage();
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (Exception e) {
        RestApiUtil.handleInternalServerError("An Error has occurred while getting the operation policy with ID " + operationPolicyId + "operation policy for API " + apiId, e, log);
    }
    return null;
}
Also used : OperationPolicyData(org.wso2.carbon.apimgt.api.model.OperationPolicyData) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) OperationPolicyDataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OperationPolicyDataDTO) JSONException(org.json.JSONException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SdkClientException(com.amazonaws.SdkClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException) CryptoException(org.wso2.carbon.core.util.CryptoException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException)

Example 12 with OperationPolicyData

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

the class ImportUtils method validateOperationPolicies.

public static Set<URITemplate> validateOperationPolicies(API api, APIProvider provider, String extractedFolderPath, Map<String, List<OperationPolicy>> extractedPoliciesMap, String tenantDomain) {
    String policyDirectory = extractedFolderPath + File.separator + ImportExportConstants.POLICIES_DIRECTORY;
    Set<URITemplate> uriTemplates = api.getUriTemplates();
    for (URITemplate uriTemplate : uriTemplates) {
        String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
        if (extractedPoliciesMap.containsKey(key)) {
            List<OperationPolicy> operationPolicies = extractedPoliciesMap.get(key);
            List<OperationPolicy> validatedOperationPolicies = new ArrayList<>();
            if (operationPolicies != null && !operationPolicies.isEmpty()) {
                for (OperationPolicy policy : operationPolicies) {
                    try {
                        OperationPolicySpecification policySpec = getOperationPolicySpecificationFromFile(policyDirectory, policy.getPolicyName());
                        OperationPolicyData operationPolicyData = new OperationPolicyData();
                        operationPolicyData.setSpecification(policySpec);
                        operationPolicyData.setOrganization(tenantDomain);
                        operationPolicyData.setApiUUID(api.getUuid());
                        OperationPolicyDefinition synapseDefinition = APIUtil.getOperationPolicyDefinitionFromFile(policyDirectory, policy.getPolicyName(), APIConstants.SYNAPSE_POLICY_DEFINITION_EXTENSION);
                        if (synapseDefinition != null) {
                            synapseDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.Synapse);
                            operationPolicyData.setSynapsePolicyDefinition(synapseDefinition);
                        }
                        OperationPolicyDefinition ccDefinition = APIUtil.getOperationPolicyDefinitionFromFile(policyDirectory, policy.getPolicyName(), APIConstants.CC_POLICY_DEFINITION_EXTENSION);
                        if (ccDefinition != null) {
                            ccDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.ChoreoConnect);
                            operationPolicyData.setCcPolicyDefinition(ccDefinition);
                        }
                        operationPolicyData.setMd5Hash(APIUtil.getMd5OfOperationPolicy(operationPolicyData));
                        String policyID = provider.importOperationPolicy(operationPolicyData, tenantDomain);
                        policy.setPolicyId(policyID);
                        validatedOperationPolicies.add(policy);
                    } catch (APIManagementException e) {
                        log.error(e);
                    }
                }
            }
            uriTemplate.setOperationPolicies(validatedOperationPolicies);
        }
    }
    return uriTemplates;
}
Also used : OperationPolicyData(org.wso2.carbon.apimgt.api.model.OperationPolicyData) OperationPolicyDefinition(org.wso2.carbon.apimgt.api.model.OperationPolicyDefinition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) OperationPolicySpecification(org.wso2.carbon.apimgt.api.model.OperationPolicySpecification)

Example 13 with OperationPolicyData

use of org.wso2.carbon.apimgt.api.model.OperationPolicyData 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 14 with OperationPolicyData

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

the class OperationPolicyMappingUtil method fromOperationPolicyDataListToDTO.

public static OperationPolicyDataListDTO fromOperationPolicyDataListToDTO(List<OperationPolicyData> policyDataList, int offset, int limit) {
    List<OperationPolicyDataDTO> operationPolicyList = new ArrayList<>();
    if (policyDataList == null) {
        policyDataList = new ArrayList<>();
    }
    int size = policyDataList.size();
    int start = offset < size && offset >= 0 ? offset : Integer.MAX_VALUE;
    int end = Math.min(offset + limit - 1, size - 1);
    for (int i = start; i <= end; i++) {
        operationPolicyList.add(fromOperationPolicyDataToDTO(policyDataList.get(i)));
    }
    PaginationDTO paginationDTO = new PaginationDTO();
    paginationDTO.setLimit(limit);
    paginationDTO.setOffset(offset);
    paginationDTO.setTotal(size);
    OperationPolicyDataListDTO dataListDTO = new OperationPolicyDataListDTO();
    dataListDTO.setList(operationPolicyList);
    dataListDTO.setCount(operationPolicyList.size());
    dataListDTO.setPagination(paginationDTO);
    return dataListDTO;
}
Also used : OperationPolicyDataListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OperationPolicyDataListDTO) ArrayList(java.util.ArrayList) PaginationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.PaginationDTO) OperationPolicyDataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OperationPolicyDataDTO)

Example 15 with OperationPolicyData

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

the class OperationPolicyMappingUtil method fromOperationPolicyDataToDTO.

public static OperationPolicyDataDTO fromOperationPolicyDataToDTO(OperationPolicyData policyData) {
    OperationPolicyDataDTO policyDataDTO = new OperationPolicyDataDTO();
    OperationPolicySpecification policySpecification = policyData.getSpecification();
    policyDataDTO.setId(policyData.getPolicyId());
    policyDataDTO.setMd5(policyData.getMd5Hash());
    policyDataDTO.setIsAPISpecific(policyData.isApiSpecificPolicy());
    policyDataDTO.setName(policySpecification.getName());
    policyDataDTO.setDisplayName(policySpecification.getDisplayName());
    policyDataDTO.setDescription(policySpecification.getDescription());
    policyDataDTO.setSupportedGateways(policySpecification.getSupportedGateways());
    policyDataDTO.setSupportedApiTypes(policySpecification.getSupportedApiTypes());
    policyDataDTO.setApplicableFlows(policySpecification.getApplicableFlows());
    policyDataDTO.setMultipleAllowed(policySpecification.isMultipleAllowed());
    policyDataDTO.setCategory(policySpecification.getCategory().toString());
    if (policySpecification.getPolicyAttributes() != null) {
        List<OperationPolicySpecAttributeDTO> specAttributeDtoList = new ArrayList<>();
        for (OperationPolicySpecAttribute specAttribute : policySpecification.getPolicyAttributes()) {
            OperationPolicySpecAttributeDTO specAttributeDTO = fromOperationPolicySpecAttributesToDTO(specAttribute);
            specAttributeDtoList.add(specAttributeDTO);
        }
        policyDataDTO.setPolicyAttributes(specAttributeDtoList);
    }
    return policyDataDTO;
}
Also used : OperationPolicySpecAttribute(org.wso2.carbon.apimgt.api.model.OperationPolicySpecAttribute) ArrayList(java.util.ArrayList) OperationPolicySpecAttributeDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OperationPolicySpecAttributeDTO) OperationPolicyDataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OperationPolicyDataDTO) OperationPolicySpecification(org.wso2.carbon.apimgt.api.model.OperationPolicySpecification)

Aggregations

OperationPolicyData (org.wso2.carbon.apimgt.api.model.OperationPolicyData)25 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)17 PreparedStatement (java.sql.PreparedStatement)11 OperationPolicySpecification (org.wso2.carbon.apimgt.api.model.OperationPolicySpecification)11 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)10 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)10 ResultSet (java.sql.ResultSet)8 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 APIImportExportException (org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)7 OperationPolicy (org.wso2.carbon.apimgt.api.model.OperationPolicy)6 OperationPolicyDataDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OperationPolicyDataDTO)6 SdkClientException (com.amazonaws.SdkClientException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 MalformedURLException (java.net.MalformedURLException)5 URISyntaxException (java.net.URISyntaxException)5 UnknownHostException (java.net.UnknownHostException)5 SQLException (java.sql.SQLException)5 JSONException (org.json.JSONException)5 ParseException (org.json.simple.parser.ParseException)5