Search in sources :

Example 1 with OperationPolicySpecification

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

the class ApiMgtDAO method addOperationPolicyContent.

/**
 * This method is used to populate AM_OPERATION_POLICY table. This will return the policy ID.
 *
 * @param connection DB connection
 * @param policyData Unique Identifier of API
 * @return UUID of the newly created policy
 * @throws SQLException
 */
private String addOperationPolicyContent(Connection connection, OperationPolicyData policyData) throws SQLException {
    OperationPolicySpecification policySpecification = policyData.getSpecification();
    String dbQuery = SQLConstants.OperationPolicyConstants.ADD_OPERATION_POLICY;
    String policyUUID = UUID.randomUUID().toString();
    PreparedStatement statement = connection.prepareStatement(dbQuery);
    statement.setString(1, policyUUID);
    statement.setString(2, policySpecification.getName());
    statement.setString(3, policySpecification.getDisplayName());
    statement.setString(4, policySpecification.getDescription());
    statement.setString(5, policySpecification.getApplicableFlows().toString());
    statement.setString(6, policySpecification.getSupportedGateways().toString());
    statement.setString(7, policySpecification.getSupportedApiTypes().toString());
    statement.setBinaryStream(8, new ByteArrayInputStream(APIUtil.getPolicyAttributesAsString(policySpecification).getBytes()));
    statement.setString(9, policyData.getOrganization());
    statement.setString(10, policySpecification.getCategory().toString());
    statement.setBoolean(11, policySpecification.isMultipleAllowed());
    statement.setString(12, policyData.getMd5Hash());
    statement.executeUpdate();
    statement.close();
    if (policyData.getSynapsePolicyDefinition() != null) {
        addOperationPolicyDefinition(connection, policyUUID, policyData.getSynapsePolicyDefinition());
    }
    if (policyData.getCcPolicyDefinition() != null) {
        addOperationPolicyDefinition(connection, policyUUID, policyData.getCcPolicyDefinition());
    }
    return policyUUID;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) PreparedStatement(java.sql.PreparedStatement) OperationPolicySpecification(org.wso2.carbon.apimgt.api.model.OperationPolicySpecification)

Example 2 with OperationPolicySpecification

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

the class APIProviderImpl method validateAppliedPolicyWithSpecification.

private boolean validateAppliedPolicyWithSpecification(OperationPolicySpecification policySpecification, OperationPolicy appliedPolicy, API api) throws APIManagementException {
    // Validate the policy applied direction
    if (!policySpecification.getApplicableFlows().contains(appliedPolicy.getDirection())) {
        if (log.isDebugEnabled()) {
            log.debug("The policy " + policySpecification.getName() + " is not support in the " + appliedPolicy.getDirection() + " flow. Hence skipped.");
        }
        throw new APIManagementException(policySpecification.getName() + " cannot be used in the " + appliedPolicy.getDirection() + " flow.", ExceptionCodes.OPERATION_POLICY_NOT_ALLOWED_IN_THE_APPLIED_FLOW);
    }
    // Validate the API type
    if (!policySpecification.getSupportedApiTypes().contains(api.getType())) {
        if (log.isDebugEnabled()) {
            log.debug("The policy " + policySpecification.getName() + " cannot be used for the " + api.getType() + " API type.");
        }
        throw new APIManagementException(policySpecification.getName() + " cannot be used for the " + api.getType() + " API type.", ExceptionCodes.OPERATION_POLICY_NOT_ALLOWED_IN_THE_APPLIED_FLOW);
    }
    // Validate policy Attributes
    if (policySpecification.getPolicyAttributes() != null) {
        for (OperationPolicySpecAttribute attribute : policySpecification.getPolicyAttributes()) {
            if (attribute.isRequired()) {
                Object appliedPolicyAttribute = appliedPolicy.getParameters().get(attribute.getName());
                if (appliedPolicyAttribute != null) {
                    if (attribute.getValidationRegex() != null) {
                        Pattern pattern = Pattern.compile(attribute.getValidationRegex(), Pattern.CASE_INSENSITIVE);
                        Matcher matcher = pattern.matcher((String) appliedPolicyAttribute);
                        if (!matcher.matches()) {
                            throw new APIManagementException("Policy attribute " + attribute.getName() + " regex validation error.", ExceptionCodes.INVALID_OPERATION_POLICY_PARAMETERS);
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Required policy attribute " + attribute.getName() + " is not found for the the policy " + policySpecification.getName());
                    }
                    throw new APIManagementException("Required policy attribute " + attribute.getName() + " is not found for the the policy " + policySpecification.getName() + appliedPolicy.getDirection() + " flow.", ExceptionCodes.MISSING_MANDATORY_POLICY_ATTRIBUTES);
                }
            }
        }
    }
    return true;
}
Also used : OperationPolicySpecAttribute(org.wso2.carbon.apimgt.api.model.OperationPolicySpecAttribute) Pattern(java.util.regex.Pattern) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Matcher(java.util.regex.Matcher) JSONObject(org.json.simple.JSONObject)

Example 3 with OperationPolicySpecification

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

the class APIUtil method getValidatedOperationPolicySpecification.

/**
 * Get the validated policy specification object from a provided policy string. Validation is done against the
 * policy schema
 *
 * @param policySpecAsString  Policy specification as a string
 * @return OperationPolicySpecification object
 * @throws APIManagementException If the policy schema validation fails
 */
public static OperationPolicySpecification getValidatedOperationPolicySpecification(String policySpecAsString) throws APIManagementException {
    Schema schema = APIUtil.retrieveOperationPolicySpecificationJsonSchema();
    if (schema != null) {
        try {
            org.json.JSONObject uploadedConfig = new org.json.JSONObject(policySpecAsString);
            schema.validate(uploadedConfig);
        } catch (ValidationException e) {
            List<String> errors = e.getAllMessages();
            String errorMessage = errors.size() + " validation error(s) found. Error(s) :" + errors.toString();
            throw new APIManagementException("Policy specification validation failure. " + errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_OPERATION_POLICY_SPECIFICATION, errorMessage));
        }
        return new Gson().fromJson(policySpecAsString, OperationPolicySpecification.class);
    }
    return null;
}
Also used : ValidationException(org.everit.json.schema.ValidationException) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Schema(org.everit.json.schema.Schema) Gson(com.google.gson.Gson) SolrDocumentList(org.apache.solr.common.SolrDocumentList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 4 with OperationPolicySpecification

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

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

the class ImportUtils method getOperationPolicySpecificationFromFile.

public static OperationPolicySpecification getOperationPolicySpecificationFromFile(String extractedFolderPath, String policyName) throws APIManagementException {
    try {
        String jsonContent = getFileContentAsJson(extractedFolderPath + File.separator + policyName);
        if (jsonContent == null) {
            return null;
        }
        // Retrieving the field "data" in deployment_environments.yaml
        JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
        return APIUtil.getValidatedOperationPolicySpecification(configElement.toString());
    } catch (IOException e) {
        throw new APIManagementException("Error while reading policy specification info from path: " + extractedFolderPath, e, ExceptionCodes.ERROR_READING_META_DATA);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) IOException(java.io.IOException) JsonParser(com.google.gson.JsonParser)

Aggregations

OperationPolicySpecification (org.wso2.carbon.apimgt.api.model.OperationPolicySpecification)13 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)8 ArrayList (java.util.ArrayList)6 OperationPolicyData (org.wso2.carbon.apimgt.api.model.OperationPolicyData)6 OperationPolicyDefinition (org.wso2.carbon.apimgt.api.model.OperationPolicyDefinition)5 IOException (java.io.IOException)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 PreparedStatement (java.sql.PreparedStatement)3 OperationPolicy (org.wso2.carbon.apimgt.api.model.OperationPolicy)3 OperationPolicySpecAttribute (org.wso2.carbon.apimgt.api.model.OperationPolicySpecAttribute)3 OperationPolicyDataDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.OperationPolicyDataDTO)3 Gson (com.google.gson.Gson)2 URI (java.net.URI)2 Connection (java.sql.Connection)2 SQLException (java.sql.SQLException)2 HashMap (java.util.HashMap)2 List (java.util.List)2 JSONObject (org.json.simple.JSONObject)2 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2