Search in sources :

Example 1 with OperationPolicyDefinition

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

the class ApiMgtDAO method getPolicyDefinitionForPolicyId.

private List<OperationPolicyDefinition> getPolicyDefinitionForPolicyId(Connection connection, String policyId) throws SQLException {
    List<OperationPolicyDefinition> operationPolicyDefinitions = new ArrayList<>();
    String dbQuery = SQLConstants.OperationPolicyConstants.GET_OPERATION_POLICY_DEFINITION_FROM_POLICY_ID;
    PreparedStatement statement = connection.prepareStatement(dbQuery);
    statement.setString(1, policyId);
    ResultSet rs = statement.executeQuery();
    while (rs.next()) {
        String policyDefinitionString;
        OperationPolicyDefinition policyDefinition = new OperationPolicyDefinition();
        try (InputStream policyDefinitionStream = rs.getBinaryStream("POLICY_DEFINITION")) {
            policyDefinitionString = IOUtils.toString(policyDefinitionStream);
            policyDefinition.setContent(policyDefinitionString);
            policyDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.valueOf(rs.getString("GATEWAY_TYPE")));
            policyDefinition.setMd5Hash(rs.getString("DEFINITION_MD5"));
            operationPolicyDefinitions.add(policyDefinition);
        } catch (IOException e) {
            log.error("Error while converting policy definition for the policy", e);
        }
    }
    rs.close();
    statement.close();
    return operationPolicyDefinitions;
}
Also used : OperationPolicyDefinition(org.wso2.carbon.apimgt.api.model.OperationPolicyDefinition) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException)

Example 2 with OperationPolicyDefinition

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

the class APIUtil method loadCommonOperationPolicies.

/**
 * Load the common policies for the organization at the first startup. This will only copy the policies to the
 * database if the total policies for this organization is zero.
 *
 * @param organization organization name
 */
public static void loadCommonOperationPolicies(String organization) throws APIManagementException {
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    int policyCount = apiMgtDAO.getOperationPolicyCount(organization);
    if (policyCount == 0) {
        String policySpecLocation = CarbonUtils.getCarbonHome() + File.separator + APIConstants.COMMON_OPERATION_POLICY_SPECIFICATIONS_LOCATION;
        String policyDefinitionLocation = CarbonUtils.getCarbonHome() + File.separator + APIConstants.COMMON_OPERATION_POLICY_DEFINITIONS_LOCATION;
        File policiesDir = new File(policySpecLocation);
        File[] files = policiesDir.listFiles();
        if (files != null) {
            for (File file : files) {
                String jsonContent;
                try {
                    jsonContent = FileUtils.readFileToString(file);
                    OperationPolicySpecification policySpec = getValidatedOperationPolicySpecification(jsonContent);
                    if (policySpec != null) {
                        OperationPolicyData policyData = new OperationPolicyData();
                        policyData.setSpecification(policySpec);
                        policyData.setOrganization(organization);
                        OperationPolicyDefinition synapsePolicyDefinition = getOperationPolicyDefinitionFromFile(policyDefinitionLocation, policySpec.getName(), APIConstants.SYNAPSE_POLICY_DEFINITION_EXTENSION);
                        if (synapsePolicyDefinition != null) {
                            synapsePolicyDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.Synapse);
                            policyData.setSynapsePolicyDefinition(synapsePolicyDefinition);
                        }
                        OperationPolicyDefinition ccPolicyDefinition = getOperationPolicyDefinitionFromFile(policyDefinitionLocation, policySpec.getName(), APIConstants.CC_POLICY_DEFINITION_EXTENSION);
                        if (ccPolicyDefinition != null) {
                            ccPolicyDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.ChoreoConnect);
                            policyData.setCcPolicyDefinition(ccPolicyDefinition);
                        }
                        policyData.setMd5Hash(getMd5OfOperationPolicy(policyData));
                        apiMgtDAO.addCommonOperationPolicy(policyData);
                        log.info("Common operation policy " + policySpec.getName() + "_" + policySpec.getVersion() + " was added to the organization " + organization + " successfully");
                    }
                } catch (IOException | APIManagementException e) {
                    log.error("Invalid policy specification for file " + file.getName() + ".Hence skipped from importing as a common operation policy.", e);
                }
            }
        }
    }
}
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) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) IOException(java.io.IOException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) OperationPolicySpecification(org.wso2.carbon.apimgt.api.model.OperationPolicySpecification)

Example 3 with OperationPolicyDefinition

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

the class APIUtil method getOperationPolicyDefinitionFromFile.

/**
 * Read the operation policy definition from the provided path and return the definition object
 *
 * @param extractedFolderPath   Location of the policy definition
 * @param policyName            Name of the policy
 * @param fileExtension         Since there can be both synapse and choreo connect definitons, fileExtension is used
 *
 * @return OperationPolicyDefinition
 */
public static OperationPolicyDefinition getOperationPolicyDefinitionFromFile(String extractedFolderPath, String policyName, String fileExtension) throws APIManagementException {
    OperationPolicyDefinition policyDefinition = null;
    try {
        String fileName = extractedFolderPath + File.separator + policyName + fileExtension;
        if (checkFileExistence(fileName)) {
            if (log.isDebugEnabled()) {
                log.debug("Found policy definition file " + fileName);
            }
            String yamlContent = FileUtils.readFileToString(new File(fileName));
            policyDefinition = new OperationPolicyDefinition();
            policyDefinition.setContent(yamlContent);
            policyDefinition.setMd5Hash(getMd5OfOperationPolicyDefinition(policyDefinition));
        }
    } catch (IOException e) {
        throw new APIManagementException("Error while reading policy specification from path: " + extractedFolderPath, e, ExceptionCodes.ERROR_READING_META_DATA);
    }
    return policyDefinition;
}
Also used : OperationPolicyDefinition(org.wso2.carbon.apimgt.api.model.OperationPolicyDefinition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) IOException(java.io.IOException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 4 with OperationPolicyDefinition

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

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

the class ApisApiServiceImpl method addAPISpecificOperationPolicy.

/**
 * Add an API specific operation policy
 *
 * @param apiId                                  UUID of the API
 * @param policySpecFileInputStream              Input stream of the policy specification file
 * @param policySpecFileDetail                   Operation policy specification
 * @param synapsePolicyDefinitionFileInputStream Input stream of the synapse policy definition file
 * @param synapsePolicyDefinitionFileDetail      Synapse definition of the operation policy
 * @param ccPolicyDefinitionFileInputStream      Input stream of the choreo connect policy definition file
 * @param ccPolicyDefinitionFileDetail           Choreo connect definition of the operation policy
 * @param messageContext                         message context
 * @return Added Operation operation policy DTO as response
 */
@Override
public Response addAPISpecificOperationPolicy(String apiId, InputStream policySpecFileInputStream, Attachment policySpecFileDetail, InputStream synapsePolicyDefinitionFileInputStream, Attachment synapsePolicyDefinitionFileDetail, InputStream ccPolicyDefinitionFileInputStream, Attachment ccPolicyDefinitionFileDetail, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // validate if api exists
        validateAPIExistence(apiId);
        String jsonContent = "";
        OperationPolicyDefinition synapseDefinition = null;
        OperationPolicyDefinition ccPolicyDefinition = null;
        OperationPolicySpecification policySpecification;
        if (policySpecFileInputStream != null) {
            jsonContent = RestApiPublisherUtils.readInputStream(policySpecFileInputStream, policySpecFileDetail);
            String fileName = policySpecFileDetail.getDataHandler().getName();
            String fileContentType = URLConnection.guessContentTypeFromName(fileName);
            if (org.apache.commons.lang3.StringUtils.isBlank(fileContentType)) {
                fileContentType = policySpecFileDetail.getContentType().toString();
            }
            if (APIConstants.YAML_CONTENT_TYPE.equals(fileContentType)) {
                jsonContent = CommonUtil.yamlToJson(jsonContent);
            }
            policySpecification = APIUtil.getValidatedOperationPolicySpecification(jsonContent);
            OperationPolicyData operationPolicyData = new OperationPolicyData();
            operationPolicyData.setOrganization(organization);
            operationPolicyData.setApiUUID(apiId);
            operationPolicyData.setSpecification(policySpecification);
            if (synapsePolicyDefinitionFileInputStream != null) {
                String synapsePolicyDefinition = RestApiPublisherUtils.readInputStream(synapsePolicyDefinitionFileInputStream, synapsePolicyDefinitionFileDetail);
                synapseDefinition = new OperationPolicyDefinition();
                synapseDefinition.setContent(synapsePolicyDefinition);
                synapseDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.Synapse);
                synapseDefinition.setMd5Hash(APIUtil.getMd5OfOperationPolicyDefinition(synapseDefinition));
                operationPolicyData.setSynapsePolicyDefinition(synapseDefinition);
            }
            if (ccPolicyDefinitionFileInputStream != null) {
                String choreoConnectPolicyDefinition = RestApiPublisherUtils.readInputStream(ccPolicyDefinitionFileInputStream, ccPolicyDefinitionFileDetail);
                ccPolicyDefinition = new OperationPolicyDefinition();
                ccPolicyDefinition.setContent(choreoConnectPolicyDefinition);
                ccPolicyDefinition.setGatewayType(OperationPolicyDefinition.GatewayType.ChoreoConnect);
                ccPolicyDefinition.setMd5Hash(APIUtil.getMd5OfOperationPolicyDefinition(ccPolicyDefinition));
                operationPolicyData.setCcPolicyDefinition(ccPolicyDefinition);
            }
            operationPolicyData.setMd5Hash(APIUtil.getMd5OfOperationPolicy(operationPolicyData));
            OperationPolicyData existingPolicy = apiProvider.getAPISpecificOperationPolicyByPolicyName(policySpecification.getName(), apiId, null, organization, false);
            String policyID;
            if (existingPolicy == null) {
                policyID = apiProvider.addAPISpecificOperationPolicy(apiId, operationPolicyData, organization);
                if (log.isDebugEnabled()) {
                    log.debug("An API specific operation policy has been added for the API " + apiId + " with id " + policyID);
                }
            } else {
                throw new APIManagementException("An API specific operation policy found for the same name.");
            }
            operationPolicyData.setPolicyId(policyID);
            OperationPolicyDataDTO operationPolicyDataDTO = OperationPolicyMappingUtil.fromOperationPolicyDataToDTO(operationPolicyData);
            URI createdPolicyUri = new URI(RestApiConstants.REST_API_PUBLISHER_VERSION + RestApiConstants.RESOURCE_PATH_APIS + "/" + apiId + "/" + RestApiConstants.RESOURCE_PATH_OPERATION_POLICIES + "/" + policyID);
            return Response.created(createdPolicyUri).entity(operationPolicyDataDTO).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding an API specific operation policy." + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (Exception e) {
        RestApiUtil.handleInternalServerError("An error has occurred while adding an API specific " + "operation policy", e, log);
    }
    return null;
}
Also used : OperationPolicyDefinition(org.wso2.carbon.apimgt.api.model.OperationPolicyDefinition) OperationPolicyData(org.wso2.carbon.apimgt.api.model.OperationPolicyData) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) OperationPolicySpecification(org.wso2.carbon.apimgt.api.model.OperationPolicySpecification) 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)

Aggregations

OperationPolicyDefinition (org.wso2.carbon.apimgt.api.model.OperationPolicyDefinition)7 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)5 OperationPolicySpecification (org.wso2.carbon.apimgt.api.model.OperationPolicySpecification)5 IOException (java.io.IOException)4 OperationPolicyData (org.wso2.carbon.apimgt.api.model.OperationPolicyData)4 ArrayList (java.util.ArrayList)3 File (java.io.File)2 URI (java.net.URI)2 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 OperationPolicy (org.wso2.carbon.apimgt.api.model.OperationPolicy)2 ResourceFile (org.wso2.carbon.apimgt.api.model.ResourceFile)2 OperationPolicyDataDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OperationPolicyDataDTO)2 SdkClientException (com.amazonaws.SdkClientException)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 MalformedURLException (java.net.MalformedURLException)1 URISyntaxException (java.net.URISyntaxException)1 UnknownHostException (java.net.UnknownHostException)1