Search in sources :

Example 11 with GlobalPolicy

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

the class PolicyUtilTest method testUpdatePolicy_GlobalType.

@Test
public void testUpdatePolicy_GlobalType() throws ExecutionPlanConfigurationException, ExecutionPlanDependencyValidationException {
    Mockito.when(eventProcessorService.getActiveExecutionPlan(Mockito.anyString())).thenReturn("EXECUTION_PLAN");
    GlobalPolicy policy = TestUtil.getPolicyGlobalLevel();
    GlobalPolicyEvent policyEvent = new GlobalPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), -1234, policy.getTenantDomain(), policy.getId(), policy.getName());
    PolicyUtil.deployPolicy(policy, policyEvent);
    Mockito.verify(eventProcessorService, Mockito.times(1)).editActiveExecutionPlan(Mockito.anyString(), Mockito.anyString());
}
Also used : GlobalPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.GlobalPolicy) GlobalPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.GlobalPolicyEvent) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 12 with GlobalPolicy

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

the class PolicyRetriever method getGlobalPolicy.

/**
 * Get a global policy given the name.
 *
 * @param policyName   policy name
 * @param tenantDomain tenant domain
 * @return global policy
 * @throws ThrottlePolicyDeployerException if failure occurs
 */
public GlobalPolicy getGlobalPolicy(String policyName, String tenantDomain) throws ThrottlePolicyDeployerException {
    String path = APIConstants.SubscriptionValidationResources.GLOBAL_POLICIES + "?policyName=" + policyName;
    GlobalPolicyList globalPolicyList = getPolicies(path, tenantDomain, GlobalPolicyList.class);
    if (globalPolicyList.getList() != null && !globalPolicyList.getList().isEmpty()) {
        return globalPolicyList.getList().get(0);
    }
    return null;
}
Also used : GlobalPolicyList(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.GlobalPolicyList)

Example 13 with GlobalPolicy

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

the class TestUtil method getPolicyGlobalLevel.

/**
 * Generate a dummy Global Policy object
 *
 * @return an Global Policy
 */
public static GlobalPolicy getPolicyGlobalLevel() {
    GlobalPolicy globalPolicy = new GlobalPolicy();
    globalPolicy.setId(1);
    globalPolicy.setTenantId(-1234);
    globalPolicy.setTenantDomain("carbon.super");
    globalPolicy.setName("policy1");
    globalPolicy.setQuotaType("requestCount");
    QuotaPolicy defaultLimit = new QuotaPolicy();
    defaultLimit.setQuotaType("requestCount");
    RequestCountLimit requestCountLimit = new RequestCountLimit();
    requestCountLimit.setRequestCount(1);
    requestCountLimit.setTimeUnit("min");
    requestCountLimit.setUnitTime(1);
    defaultLimit.setRequestCount(requestCountLimit);
    globalPolicy.setDefaultLimit(defaultLimit);
    globalPolicy.setSiddhiQuery("FROM   RequestStream SELECT   userId,   " + "(userId == 'admin@carbon.super') AS isEligible,   " + "str :concat('admin@carbon.super', '') as throttleKey INSERT INTO   " + "EligibilityStream; FROM   EligibilityStream [isEligible==true] " + "#throttler:timeBatch(1 min) SELECT throttleKey, (count(userId) >= 15) " + "as isThrottled, expiryTimeStamp group by throttleKey INSERT ALL EVENTS " + "into ResultStream;");
    globalPolicy.setKeyTemplate("$userId:$apiContext:$apiVersion");
    return globalPolicy;
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.RequestCountLimit) GlobalPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.GlobalPolicy) QuotaPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.QuotaPolicy)

Example 14 with GlobalPolicy

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

the class APIProviderImpl method addPolicy.

/**
 * Deploy policy to global CEP and persist the policy object
 *
 * @param policy policy object
 */
public void addPolicy(Policy policy) throws APIManagementException {
    if (policy instanceof APIPolicy) {
        APIPolicy apiPolicy = (APIPolicy) policy;
        // Check if there's a policy exists before adding the new policy
        Policy existingPolicy = getAPIPolicy(userNameWithoutChange, apiPolicy.getPolicyName());
        if (existingPolicy != null) {
            handleException("Advanced Policy with name " + apiPolicy.getPolicyName() + " already exists");
        }
        apiPolicy.setUserLevel(PolicyConstants.ACROSS_ALL);
        apiPolicy = apiMgtDAO.addAPIPolicy(apiPolicy);
        List<Integer> addedConditionGroupIds = new ArrayList<>();
        for (Pipeline pipeline : apiPolicy.getPipelines()) {
            addedConditionGroupIds.add(pipeline.getId());
        }
        APIPolicyEvent apiPolicyEvent = new APIPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_CREATE.name(), tenantId, apiPolicy.getTenantDomain(), apiPolicy.getPolicyId(), apiPolicy.getPolicyName(), apiPolicy.getDefaultQuotaPolicy().getType(), addedConditionGroupIds, null);
        APIUtil.sendNotification(apiPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof ApplicationPolicy) {
        ApplicationPolicy appPolicy = (ApplicationPolicy) policy;
        // Check if there's a policy exists before adding the new policy
        Policy existingPolicy = getApplicationPolicy(userNameWithoutChange, appPolicy.getPolicyName());
        if (existingPolicy != null) {
            handleException("Application Policy with name " + appPolicy.getPolicyName() + " already exists");
        }
        apiMgtDAO.addApplicationPolicy(appPolicy);
        // policy id is not set. retrieving policy to get the id.
        ApplicationPolicy retrievedPolicy = apiMgtDAO.getApplicationPolicy(appPolicy.getPolicyName(), tenantId);
        ApplicationPolicyEvent applicationPolicyEvent = new ApplicationPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_CREATE.name(), tenantId, appPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), appPolicy.getPolicyName(), appPolicy.getDefaultQuotaPolicy().getType());
        APIUtil.sendNotification(applicationPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof SubscriptionPolicy) {
        SubscriptionPolicy subPolicy = (SubscriptionPolicy) policy;
        // Check if there's a policy exists before adding the new policy
        Policy existingPolicy = getSubscriptionPolicy(userNameWithoutChange, subPolicy.getPolicyName());
        if (existingPolicy != null) {
            handleException("Subscription Policy with name " + subPolicy.getPolicyName() + " already exists");
        }
        apiMgtDAO.addSubscriptionPolicy(subPolicy);
        String monetizationPlan = subPolicy.getMonetizationPlan();
        Map<String, String> monetizationPlanProperties = subPolicy.getMonetizationPlanProperties();
        if (StringUtils.isNotBlank(monetizationPlan) && MapUtils.isNotEmpty(monetizationPlanProperties)) {
            createMonetizationPlan(subPolicy);
        }
        // policy id is not set. retrieving policy to get the id.
        SubscriptionPolicy retrievedPolicy = apiMgtDAO.getSubscriptionPolicy(subPolicy.getPolicyName(), tenantId);
        SubscriptionPolicyEvent subscriptionPolicyEvent = new SubscriptionPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_CREATE.name(), tenantId, subPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), subPolicy.getPolicyName(), subPolicy.getDefaultQuotaPolicy().getType(), subPolicy.getRateLimitCount(), subPolicy.getRateLimitTimeUnit(), subPolicy.isStopOnQuotaReach(), subPolicy.getGraphQLMaxDepth(), subPolicy.getGraphQLMaxComplexity(), subPolicy.getSubscriberCount());
        APIUtil.sendNotification(subscriptionPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof GlobalPolicy) {
        GlobalPolicy globalPolicy = (GlobalPolicy) policy;
        // checking if policy already exist
        Policy existingPolicy = getGlobalPolicy(globalPolicy.getPolicyName());
        if (existingPolicy != null) {
            throw new APIManagementException("Policy name already exists");
        }
        apiMgtDAO.addGlobalPolicy(globalPolicy);
        publishKeyTemplateEvent(globalPolicy.getKeyTemplate(), "add");
        GlobalPolicy retrievedPolicy = apiMgtDAO.getGlobalPolicy(globalPolicy.getPolicyName());
        GlobalPolicyEvent globalPolicyEvent = new GlobalPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_CREATE.name(), tenantId, globalPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), globalPolicy.getPolicyName());
        APIUtil.sendNotification(globalPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else {
        String msg = "Policy type " + policy.getClass().getName() + " is not supported";
        log.error(msg);
        throw new UnsupportedPolicyTypeException(msg);
    }
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) OperationPolicy(org.wso2.carbon.apimgt.api.model.OperationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.api.model.policy.Policy) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) ArrayList(java.util.ArrayList) ApplicationPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationPolicyEvent) SubscriptionPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionPolicyEvent) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) GlobalPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.GlobalPolicyEvent)

Example 15 with GlobalPolicy

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

the class APIProviderImpl method updatePolicy.

public void updatePolicy(Policy policy) throws APIManagementException {
    String oldKeyTemplate = null;
    String newKeyTemplate = null;
    if (policy instanceof APIPolicy) {
        APIPolicy apiPolicy = (APIPolicy) policy;
        apiPolicy.setUserLevel(PolicyConstants.ACROSS_ALL);
        // TODO this has done due to update policy method not deleting the second level entries when delete on cascade
        // TODO Need to fix appropriately
        List<Pipeline> pipelineList = apiPolicy.getPipelines();
        if (pipelineList != null && pipelineList.size() != 0) {
            Iterator<Pipeline> pipelineIterator = pipelineList.iterator();
            while (pipelineIterator.hasNext()) {
                Pipeline pipeline = pipelineIterator.next();
                if (!pipeline.isEnabled()) {
                    pipelineIterator.remove();
                } else {
                    if (pipeline.getConditions() != null && pipeline.getConditions().size() != 0) {
                        Iterator<Condition> conditionIterator = pipeline.getConditions().iterator();
                        while (conditionIterator.hasNext()) {
                            Condition condition = conditionIterator.next();
                            if (JavaUtils.isFalseExplicitly(condition.getConditionEnabled())) {
                                conditionIterator.remove();
                            }
                        }
                    } else {
                        pipelineIterator.remove();
                    }
                }
            }
        }
        APIPolicy existingPolicy = apiMgtDAO.getAPIPolicy(policy.getPolicyName(), policy.getTenantId());
        apiPolicy = apiMgtDAO.updateAPIPolicy(apiPolicy);
        // TODO rename level to  resource or appropriate name
        APIManagerConfiguration config = getAPIManagerConfiguration();
        if (log.isDebugEnabled()) {
            log.debug("Calling invalidation cache for API Policy for tenant ");
        }
        String policyContext = APIConstants.POLICY_CACHE_CONTEXT + "/t/" + apiPolicy.getTenantDomain() + "/";
        invalidateResourceCache(policyContext, null, Collections.EMPTY_SET);
        List<Integer> addedConditionGroupIds = new ArrayList<>();
        List<Integer> deletedConditionGroupIds = new ArrayList<>();
        for (Pipeline pipeline : existingPolicy.getPipelines()) {
            deletedConditionGroupIds.add(pipeline.getId());
        }
        for (Pipeline pipeline : apiPolicy.getPipelines()) {
            addedConditionGroupIds.add(pipeline.getId());
        }
        APIPolicyEvent apiPolicyEvent = new APIPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, apiPolicy.getTenantDomain(), apiPolicy.getPolicyId(), apiPolicy.getPolicyName(), apiPolicy.getDefaultQuotaPolicy().getType(), addedConditionGroupIds, deletedConditionGroupIds);
        APIUtil.sendNotification(apiPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof ApplicationPolicy) {
        ApplicationPolicy appPolicy = (ApplicationPolicy) policy;
        apiMgtDAO.updateApplicationPolicy(appPolicy);
        // policy id is not set. retrieving policy to get the id.
        ApplicationPolicy retrievedPolicy = apiMgtDAO.getApplicationPolicy(appPolicy.getPolicyName(), tenantId);
        ApplicationPolicyEvent applicationPolicyEvent = new ApplicationPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, appPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), appPolicy.getPolicyName(), appPolicy.getDefaultQuotaPolicy().getType());
        APIUtil.sendNotification(applicationPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof SubscriptionPolicy) {
        SubscriptionPolicy subPolicy = (SubscriptionPolicy) policy;
        apiMgtDAO.updateSubscriptionPolicy(subPolicy);
        String monetizationPlan = subPolicy.getMonetizationPlan();
        Map<String, String> monetizationPlanProperties = subPolicy.getMonetizationPlanProperties();
        // call the monetization extension point to create plans (if any)
        if (StringUtils.isNotBlank(monetizationPlan) && MapUtils.isNotEmpty(monetizationPlanProperties)) {
            updateMonetizationPlan(subPolicy);
        }
        // policy id is not set. retrieving policy to get the id.
        SubscriptionPolicy retrievedPolicy = apiMgtDAO.getSubscriptionPolicy(subPolicy.getPolicyName(), tenantId);
        SubscriptionPolicyEvent subscriptionPolicyEvent = new SubscriptionPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, subPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), subPolicy.getPolicyName(), subPolicy.getDefaultQuotaPolicy().getType(), subPolicy.getRateLimitCount(), subPolicy.getRateLimitTimeUnit(), subPolicy.isStopOnQuotaReach(), subPolicy.getGraphQLMaxDepth(), subPolicy.getGraphQLMaxComplexity(), subPolicy.getSubscriberCount());
        APIUtil.sendNotification(subscriptionPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else if (policy instanceof GlobalPolicy) {
        GlobalPolicy globalPolicy = (GlobalPolicy) policy;
        // getting key templates before updating database
        GlobalPolicy oldGlobalPolicy = apiMgtDAO.getGlobalPolicy(policy.getPolicyName());
        oldKeyTemplate = oldGlobalPolicy.getKeyTemplate();
        newKeyTemplate = globalPolicy.getKeyTemplate();
        apiMgtDAO.updateGlobalPolicy(globalPolicy);
        GlobalPolicy retrievedPolicy = apiMgtDAO.getGlobalPolicy(globalPolicy.getPolicyName());
        GlobalPolicyEvent globalPolicyEvent = new GlobalPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_UPDATE.name(), tenantId, globalPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), globalPolicy.getPolicyName());
        APIUtil.sendNotification(globalPolicyEvent, APIConstants.NotifierType.POLICY.name());
    } else {
        String msg = "Policy type " + policy.getClass().getName() + " is not supported";
        log.error(msg);
        throw new UnsupportedPolicyTypeException(msg);
    }
    // publishing keytemplate after update
    if (oldKeyTemplate != null && newKeyTemplate != null) {
        publishKeyTemplateEvent(oldKeyTemplate, "remove");
        publishKeyTemplateEvent(newKeyTemplate, "add");
    }
}
Also used : Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) GlobalPolicy(org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) ArrayList(java.util.ArrayList) ApplicationPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationPolicyEvent) SubscriptionPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionPolicyEvent) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline) APIPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) GlobalPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.GlobalPolicyEvent)

Aggregations

GlobalPolicy (org.wso2.carbon.apimgt.api.model.policy.GlobalPolicy)19 ArrayList (java.util.ArrayList)11 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 GlobalPolicy (org.wso2.carbon.apimgt.throttle.policy.deployer.dto.GlobalPolicy)9 InputStream (java.io.InputStream)7 GlobalPolicyEvent (org.wso2.carbon.apimgt.impl.notifier.events.GlobalPolicyEvent)7 Connection (java.sql.Connection)6 PreparedStatement (java.sql.PreparedStatement)6 SQLException (java.sql.SQLException)6 APIPolicy (org.wso2.carbon.apimgt.api.model.policy.APIPolicy)6 ApplicationPolicy (org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy)6 SubscriptionPolicy (org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy)6 ResultSet (java.sql.ResultSet)5 APIPolicyEvent (org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)4 ApplicationPolicyEvent (org.wso2.carbon.apimgt.impl.notifier.events.ApplicationPolicyEvent)4 SubscriptionPolicyEvent (org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionPolicyEvent)4