Search in sources :

Example 61 with ApplicationPolicy

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

the class PolicyUtil method deployPolicy.

/**
 * Deploy the given throttle policy in the Traffic Manager.
 *
 * @param policy      policy object
 * @param policyEvent policy event object which was triggered
 */
public static void deployPolicy(Policy policy, PolicyEvent policyEvent) {
    EventProcessorService eventProcessorService = ServiceReferenceHolder.getInstance().getEventProcessorService();
    ThrottlePolicyTemplateBuilder policyTemplateBuilder = new ThrottlePolicyTemplateBuilder();
    Map<String, String> policiesToDeploy = new HashMap<>();
    List<String> policiesToUndeploy = new ArrayList<>();
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(APIConstants.SUPER_TENANT_DOMAIN, true);
        String policyFile;
        String policyString;
        if (Policy.PolicyType.SUBSCRIPTION.equals(policy.getType()) && policy instanceof SubscriptionPolicy) {
            // Add Subscription policy
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_SUB, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForSubscriptionLevel((SubscriptionPolicy) policy);
            policiesToDeploy.put(policyFile, policyString);
        } else if (Policy.PolicyType.APPLICATION.equals(policy.getType()) && policy instanceof ApplicationPolicy) {
            // Add Application policy
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_APP, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForAppLevel((ApplicationPolicy) policy);
            policiesToDeploy.put(policyFile, policyString);
        } else if (Policy.PolicyType.API.equals(policy.getType()) && policy instanceof ApiPolicy) {
            // Add API policy
            policiesToDeploy = policyTemplateBuilder.getThrottlePolicyForAPILevel((ApiPolicy) policy);
            String defaultPolicy = policyTemplateBuilder.getThrottlePolicyForAPILevelDefault((ApiPolicy) policy);
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, policy.getTenantDomain(), PolicyConstants.POLICY_LEVEL_RESOURCE, policy.getName());
            String defaultPolicyName = policyFile + APIConstants.THROTTLE_POLICY_DEFAULT;
            policiesToDeploy.put(defaultPolicyName, defaultPolicy);
            if (policyEvent instanceof APIPolicyEvent) {
                List<Integer> deletedConditionGroupIds = ((APIPolicyEvent) policyEvent).getDeletedConditionGroupIds();
                // Undeploy removed condition groups
                if (deletedConditionGroupIds != null) {
                    for (int conditionGroupId : deletedConditionGroupIds) {
                        policiesToUndeploy.add(policyFile + APIConstants.THROTTLE_POLICY_CONDITION + conditionGroupId);
                    }
                }
            }
        } else if (Policy.PolicyType.GLOBAL.equals(policy.getType()) && policy instanceof GlobalPolicy) {
            // Add Global policy
            GlobalPolicy globalPolicy = (GlobalPolicy) policy;
            policyFile = String.join(APIConstants.DELEM_UNDERSCORE, PolicyConstants.POLICY_LEVEL_GLOBAL, policy.getName());
            policyString = policyTemplateBuilder.getThrottlePolicyForGlobalLevel(globalPolicy);
            policiesToDeploy.put(policyFile, policyString);
        }
        // Undeploy removed policies
        undeployPolicies(policiesToUndeploy);
        for (Map.Entry<String, String> pair : policiesToDeploy.entrySet()) {
            String policyPlanName = pair.getKey();
            String flowString = pair.getValue();
            String executionPlan = null;
            try {
                executionPlan = eventProcessorService.getActiveExecutionPlan(policyPlanName);
            } catch (ExecutionPlanConfigurationException e) {
                // Deploy new policies
                eventProcessorService.deployExecutionPlan(flowString);
            }
            if (executionPlan != null) {
                // Update existing policies
                eventProcessorService.editActiveExecutionPlan(flowString, policyPlanName);
            }
        }
    } catch (APITemplateException e) {
        log.error("Error in creating execution plan", e);
    } catch (ExecutionPlanConfigurationException | ExecutionPlanDependencyValidationException e) {
        log.error("Error in deploying execution plan", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : HashMap(java.util.HashMap) GlobalPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.GlobalPolicy) ArrayList(java.util.ArrayList) ApiPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApiPolicy) ExecutionPlanConfigurationException(org.wso2.carbon.event.processor.core.exception.ExecutionPlanConfigurationException) EventProcessorService(org.wso2.carbon.event.processor.core.EventProcessorService) ExecutionPlanDependencyValidationException(org.wso2.carbon.event.processor.core.exception.ExecutionPlanDependencyValidationException) SubscriptionPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.SubscriptionPolicy) APIPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent) ApplicationPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApplicationPolicy) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 62 with ApplicationPolicy

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

the class PolicyDAOImpl method getSubscriptionPolicyById.

/**
 * Retrieves {@link SubscriptionPolicy} with policy uuid <code>uuid</code>
 * <p>This will retrieve complete details about the ApplicationPolicy with all pipelins and conditions.</p>
 *
 * @param uuid uuid of the policy to retrieve from the database
 * @return {@link SubscriptionPolicy}
 */
private SubscriptionPolicy getSubscriptionPolicyById(String uuid) throws SQLException, APIMgtDAOException {
    final String query = "SELECT NAME, UUID, QUOTA_TYPE, TIME_UNIT, UNIT_TIME, QUOTA, QUOTA_UNIT, DESCRIPTION, " + "DISPLAY_NAME, CUSTOM_ATTRIBUTES, IS_DEPLOYED, RATE_LIMIT_COUNT, RATE_LIMIT_TIME_UNIT, " + "STOP_ON_QUOTA_REACH, BILLING_PLAN FROM AM_SUBSCRIPTION_POLICY WHERE UUID = ?";
    try (Connection conn = DAOUtil.getConnection();
        PreparedStatement statement = conn.prepareStatement(query)) {
        statement.setString(1, uuid);
        statement.execute();
        try (ResultSet rs = statement.getResultSet()) {
            if (rs.next()) {
                return createSubscriptionPolicyFromResultSet(uuid, rs);
            } else {
                // not found
                String msg = "Subscription Policy not found for id: " + uuid;
                log.warn(msg);
                throw new APIMgtDAOException(msg, ExceptionCodes.POLICY_NOT_FOUND);
            }
        }
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 63 with ApplicationPolicy

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

the class PolicyDAOImpl method updateApplicationPolicy.

/**
 * updates an existing Application Policy
 *
 * @param applicationPolicy {@link Policy} instance
 * @param connection DB Connection instance
 * @throws SQLException if an error occurs while updating the API policy
 * @throws APIMgtDAOException if the uuid of the policy is not available
 */
private void updateApplicationPolicy(Policy applicationPolicy, Connection connection) throws SQLException {
    final String query = "UPDATE AM_APPLICATION_POLICY SET NAME = ?, DISPLAY_NAME = ?, DESCRIPTION = ?, " + "QUOTA_TYPE = ?, UNIT_TIME = ?, QUOTA = ?, QUOTA_UNIT = ?, TIME_UNIT = ?, LAST_UPDATED_TIME = ? " + "WHERE UUID = ?";
    Limit limit = applicationPolicy.getDefaultQuotaPolicy().getLimit();
    try (PreparedStatement statement = connection.prepareStatement(query)) {
        statement.setString(1, applicationPolicy.getPolicyName());
        statement.setString(2, applicationPolicy.getDisplayName());
        statement.setString(3, applicationPolicy.getDescription());
        statement.setString(4, applicationPolicy.getDefaultQuotaPolicy().getType());
        statement.setInt(5, applicationPolicy.getDefaultQuotaPolicy().getLimit().getUnitTime());
        setDefaultThrottlePolicyDetailsPreparedStmt(limit, statement);
        statement.setString(8, applicationPolicy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
        statement.setTimestamp(9, Timestamp.valueOf(LocalDateTime.now()));
        statement.setString(10, applicationPolicy.getUuid());
        statement.execute();
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) Limit(org.wso2.carbon.apimgt.core.models.policy.Limit) RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) BandwidthLimit(org.wso2.carbon.apimgt.core.models.policy.BandwidthLimit)

Example 64 with ApplicationPolicy

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

the class PolicyDAOImpl method updateApplicationPolicy.

@Override
public void updateApplicationPolicy(ApplicationPolicy policy) throws APIMgtDAOException {
    try (Connection connection = DAOUtil.getConnection()) {
        try {
            connection.setAutoCommit(false);
            updateApplicationPolicy(policy, connection);
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            String errorMessage = "Error in updating Application policy with name: " + policy.getPolicyName();
            log.error(errorMessage, e);
            throw new APIMgtDAOException(errorMessage, e);
        } finally {
            connection.setAutoCommit(DAOUtil.isAutoCommit());
        }
    } catch (SQLException e) {
        String errorMsg = "Error in obtaining DB connection";
        log.error(errorMsg, e);
        throw new APIMgtDAOException(errorMsg, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection)

Example 65 with ApplicationPolicy

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

the class PolicyDAOImpl method getSimplifiedPolicyByLevelAndName.

@Override
public Policy getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel policyLevel, String policyName) throws APIMgtDAOException, APIMgtResourceNotFoundException {
    Policy policy = null;
    final String apiPolicyQuery = "SELECT UUID,NAME FROM AM_API_POLICY WHERE NAME = ?";
    final String applicationPolicyQuery = "SELECT UUID,NAME FROM AM_APPLICATION_POLICY WHERE NAME = ?";
    final String subscriptionPolicyQuery = "SELECT UUID,NAME FROM AM_SUBSCRIPTION_POLICY WHERE NAME = ?";
    try (Connection connection = DAOUtil.getConnection()) {
        if (policyLevel.equals(APIMgtAdminService.PolicyLevel.api)) {
            try (PreparedStatement statement = connection.prepareStatement(apiPolicyQuery)) {
                statement.setString(1, policyName);
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        policy = new APIPolicy(resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_UUID), resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_NAME));
                    }
                }
            }
        } else if (policyLevel.equals(APIMgtAdminService.PolicyLevel.application)) {
            try (PreparedStatement statement = connection.prepareStatement(applicationPolicyQuery)) {
                statement.setString(1, policyName);
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        policy = new ApplicationPolicy(resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_UUID), resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_NAME));
                    }
                }
            }
        } else {
            try (PreparedStatement statement = connection.prepareStatement(subscriptionPolicyQuery)) {
                statement.setString(1, policyName);
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        policy = new SubscriptionPolicy(resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_UUID), resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_NAME));
                    }
                }
            }
        }
    } catch (SQLException e) {
        String msg = "Error while retrieving policies";
        log.error(msg, e);
        throw new APIMgtDAOException(msg, ExceptionCodes.APIMGT_DAO_EXCEPTION);
    }
    if (policy == null) {
        throw new APIMgtResourceNotFoundException("Policy " + policyLevel + "Couldn't found " + policyName, ExceptionCodes.POLICY_NOT_FOUND);
    }
    return policy;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) CustomPolicy(org.wso2.carbon.apimgt.core.models.policy.CustomPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) SQLException(java.sql.SQLException) ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException)

Aggregations

ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)56 Test (org.testng.annotations.Test)30 ApplicationPolicy (org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy)29 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)24 ArrayList (java.util.ArrayList)23 Test (org.junit.Test)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)18 Application (org.wso2.carbon.apimgt.core.models.Application)17 Connection (java.sql.Connection)16 PreparedStatement (java.sql.PreparedStatement)16 SQLException (java.sql.SQLException)16 ResultSet (java.sql.ResultSet)13 BeforeTest (org.testng.annotations.BeforeTest)13 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)13 ApplicationDAO (org.wso2.carbon.apimgt.core.dao.ApplicationDAO)13 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)13 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)13 APIPolicy (org.wso2.carbon.apimgt.api.model.policy.APIPolicy)12 SubscriptionPolicy (org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy)12