Search in sources :

Example 66 with QuotaPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.QuotaPolicy in project carbon-apimgt by wso2.

the class TestUtil method getPolicyAPILevel.

/**
 * Generate a dummy API Policy object
 *
 * @return an API Policy
 */
public static ApiPolicy getPolicyAPILevel() {
    ApiPolicy apiPolicy = new ApiPolicy();
    apiPolicy.setId(1);
    apiPolicy.setTenantId(-1234);
    apiPolicy.setTenantDomain("carbon.super");
    apiPolicy.setName("policy1");
    apiPolicy.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);
    apiPolicy.setDefaultLimit(defaultLimit);
    apiPolicy.setApplicableLevel("apiLevel");
    List<APIPolicyConditionGroup> conditionGroups = new ArrayList<>();
    APIPolicyConditionGroup conditionGroup1 = new APIPolicyConditionGroup();
    conditionGroup1.setPolicyId(1);
    conditionGroup1.setQuotaType("requestCount");
    conditionGroup1.setConditionGroupId(1);
    Set<Condition> conditions = new HashSet<>();
    Condition condition1 = new Condition();
    condition1.setConditionType("IPSpecific");
    condition1.setName("IPSpecific");
    condition1.setValue("127.0.0.1");
    condition1.setInverted(false);
    conditions.add(condition1);
    conditionGroup1.setCondition(conditions);
    QuotaPolicy defaultLimitCondGroup1 = new QuotaPolicy();
    defaultLimitCondGroup1.setQuotaType("requestCount");
    RequestCountLimit requestCountLimitCondGroup1 = new RequestCountLimit();
    requestCountLimitCondGroup1.setRequestCount(1);
    requestCountLimitCondGroup1.setTimeUnit("min");
    requestCountLimitCondGroup1.setUnitTime(1);
    defaultLimitCondGroup1.setRequestCount(requestCountLimitCondGroup1);
    conditionGroup1.setDefaultLimit(defaultLimitCondGroup1);
    conditionGroups.add(conditionGroup1);
    apiPolicy.setConditionGroups(conditionGroups);
    return apiPolicy;
}
Also used : Condition(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.Condition) RequestCountLimit(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.RequestCountLimit) APIPolicyConditionGroup(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.APIPolicyConditionGroup) ApiPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApiPolicy) ArrayList(java.util.ArrayList) QuotaPolicy(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.QuotaPolicy) HashSet(java.util.HashSet)

Example 67 with QuotaPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.QuotaPolicy in project carbon-apimgt by wso2.

the class ThrottlePolicyTemplateBuilder method getThrottlePolicyForAppLevel.

/**
 * Generate application level policy
 *
 * @param policy policy with level 'app'. Multiple pipelines are not allowed. Can define more than one condition
 *               as set of conditions. all these conditions should be passed as a single pipeline
 * @return the generated execution plan for the policy
 * @throws APITemplateException if failed to generate policy
 */
public String getThrottlePolicyForAppLevel(ApplicationPolicy policy) throws APITemplateException {
    StringWriter writer = new StringWriter();
    if (log.isDebugEnabled()) {
        log.debug("Generating policy for app level :" + policy.toString());
    }
    try {
        VelocityEngine velocityengine = new VelocityEngine();
        APIUtil.initializeVelocityContext(velocityengine);
        velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        velocityengine.init();
        Template template = velocityengine.getTemplate(getTemplatePathForApplication());
        VelocityContext context = new VelocityContext();
        setConstantContext(context);
        context.put("policy", policy);
        context.put("quotaPolicy", policy.getDefaultLimit());
        template.merge(context, writer);
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + writer.toString());
        }
    } catch (VelocityException e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }
    return writer.toString();
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) VelocityException(org.apache.velocity.exception.VelocityException) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) Template(org.apache.velocity.Template)

Example 68 with QuotaPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.QuotaPolicy in project carbon-apimgt by wso2.

the class ThrottlePolicyTemplateBuilder method getThrottlePolicyForSubscriptionLevel.

/**
 * Generate policy for subscription level
 *
 * @param policy policy with level 'sub'. Multiple pipelines are not allowed. Can define more than one condition
 *               as set of conditions. all these conditions should be passed as a single pipeline
 * @return the generated execution plan for the policy
 * @throws APITemplateException if failed to generate policy
 */
public String getThrottlePolicyForSubscriptionLevel(SubscriptionPolicy policy) throws APITemplateException {
    StringWriter writer = new StringWriter();
    if (log.isDebugEnabled()) {
        log.debug("Generating policy for subscription Level :" + policy.toString());
    }
    try {
        VelocityEngine velocityengine = new VelocityEngine();
        velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        APIUtil.initializeVelocityContext(velocityengine);
        velocityengine.init();
        Template template;
        if (PolicyConstants.EVENT_COUNT_TYPE.equals(policy.getDefaultLimit().getQuotaType())) {
            template = velocityengine.getTemplate(getTemplatePathForAsyncSubscription());
        } else {
            template = velocityengine.getTemplate(getTemplatePathForSubscription());
        }
        VelocityContext context = new VelocityContext();
        setConstantContext(context);
        context.put("policy", policy);
        context.put("quotaPolicy", policy.getDefaultLimit());
        template.merge(context, writer);
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + writer.toString());
        }
    } catch (VelocityException e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }
    return writer.toString();
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) VelocityException(org.apache.velocity.exception.VelocityException) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) Template(org.apache.velocity.Template)

Example 69 with QuotaPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.QuotaPolicy in project carbon-apimgt by wso2.

the class APIUtil method addDefaultTenantAdvancedThrottlePolicies.

public static void addDefaultTenantAdvancedThrottlePolicies(String tenantDomain, int tenantId) throws APIManagementException {
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    /* Check if 'Unlimited' policy is available in AM_POLICY_APPLICATION table, to determine whether the default policies are written into the database at lease once.
           If yes, default policies won't be added to database again.
        */
    if (apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_APP, tenantId, APIConstants.DEFAULT_APP_POLICY_UNLIMITED)) {
        log.debug("Default Throttling Policies are not written into the database again, as they were added once, at initial tenant loading");
        return;
    }
    Map<String, Long> defualtLimits = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getThrottleProperties().getDefaultThrottleTierLimits();
    long tenPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN) ? defualtLimits.get(APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN) : 10;
    long twentyPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN) ? defualtLimits.get(APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN) : 20;
    long fiftyPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN) ? defualtLimits.get(APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN) : 50;
    long[] requestCount = new long[] { fiftyPerMinTier, twentyPerMinTier, tenPerMinTier, Integer.MAX_VALUE };
    // Adding application level throttle policies
    String[] appPolicies = new String[] { APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN, APIConstants.DEFAULT_APP_POLICY_UNLIMITED };
    String[] appPolicyDecs = new String[] { APIConstants.DEFAULT_APP_POLICY_LARGE_DESC, APIConstants.DEFAULT_APP_POLICY_MEDIUM_DESC, APIConstants.DEFAULT_APP_POLICY_SMALL_DESC, APIConstants.DEFAULT_APP_POLICY_UNLIMITED_DESC };
    String policyName;
    // Add application level throttle policies
    for (int i = 0; i < appPolicies.length; i++) {
        policyName = appPolicies[i];
        boolean needDeployment = false;
        ApplicationPolicy applicationPolicy = new ApplicationPolicy(policyName);
        applicationPolicy.setDisplayName(policyName);
        applicationPolicy.setDescription(appPolicyDecs[i]);
        applicationPolicy.setTenantId(tenantId);
        applicationPolicy.setDeployed(false);
        applicationPolicy.setTenantDomain(tenantDomain);
        QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
        RequestCountLimit requestCountLimit = new RequestCountLimit();
        requestCountLimit.setRequestCount(requestCount[i]);
        requestCountLimit.setUnitTime(1);
        requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
        defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
        defaultQuotaPolicy.setLimit(requestCountLimit);
        applicationPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_APP, tenantId, policyName)) {
            apiMgtDAO.addApplicationPolicy(applicationPolicy);
            needDeployment = true;
        }
        if (!apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_APP, tenantId, policyName)) {
            needDeployment = true;
        }
        if (needDeployment) {
            if (!APIConstants.DEFAULT_APP_POLICY_UNLIMITED.equalsIgnoreCase(policyName)) {
                ApplicationPolicy retrievedPolicy = apiMgtDAO.getApplicationPolicy(policyName, tenantId);
                ApplicationPolicyEvent applicationPolicyEvent = new ApplicationPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_CREATE.name(), tenantId, retrievedPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), retrievedPolicy.getPolicyName(), retrievedPolicy.getDefaultQuotaPolicy().getType());
                APIUtil.sendNotification(applicationPolicyEvent, APIConstants.NotifierType.POLICY.name());
            }
        }
    }
    long bronzeTierLimit = defualtLimits.containsKey(APIConstants.DEFAULT_SUB_POLICY_BRONZE) ? defualtLimits.get(APIConstants.DEFAULT_SUB_POLICY_BRONZE) : 1000;
    long silverTierLimit = defualtLimits.containsKey(APIConstants.DEFAULT_SUB_POLICY_SILVER) ? defualtLimits.get(APIConstants.DEFAULT_SUB_POLICY_SILVER) : 2000;
    long goldTierLimit = defualtLimits.containsKey(APIConstants.DEFAULT_SUB_POLICY_GOLD) ? defualtLimits.get(APIConstants.DEFAULT_SUB_POLICY_GOLD) : 5000;
    long unauthenticatedTierLimit = defualtLimits.containsKey(APIConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN) ? defualtLimits.get(APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED) : 500;
    // Adding Subscription level policies
    long[] requestCountSubPolicies = new long[] { goldTierLimit, silverTierLimit, bronzeTierLimit, unauthenticatedTierLimit, Integer.MAX_VALUE };
    String[] subPolicies = new String[] { APIConstants.DEFAULT_SUB_POLICY_GOLD, APIConstants.DEFAULT_SUB_POLICY_SILVER, APIConstants.DEFAULT_SUB_POLICY_BRONZE, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED, APIConstants.DEFAULT_SUB_POLICY_UNLIMITED };
    String[] subPolicyDecs = new String[] { APIConstants.DEFAULT_SUB_POLICY_GOLD_DESC, APIConstants.DEFAULT_SUB_POLICY_SILVER_DESC, APIConstants.DEFAULT_SUB_POLICY_BRONZE_DESC, APIConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED_DESC, APIConstants.DEFAULT_SUB_POLICY_UNLIMITED_DESC };
    for (int i = 0; i < subPolicies.length; i++) {
        policyName = subPolicies[i];
        boolean needDeployment = false;
        SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
        subscriptionPolicy.setDisplayName(policyName);
        subscriptionPolicy.setDescription(subPolicyDecs[i]);
        subscriptionPolicy.setTenantId(tenantId);
        subscriptionPolicy.setDeployed(false);
        subscriptionPolicy.setTenantDomain(tenantDomain);
        QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
        RequestCountLimit requestCountLimit = new RequestCountLimit();
        requestCountLimit.setRequestCount(requestCountSubPolicies[i]);
        requestCountLimit.setUnitTime(1);
        requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
        defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
        defaultQuotaPolicy.setLimit(requestCountLimit);
        subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
        subscriptionPolicy.setStopOnQuotaReach(true);
        subscriptionPolicy.setBillingPlan(APIConstants.BILLING_PLAN_FREE);
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
            apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
            needDeployment = true;
        }
        if (!apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
            needDeployment = true;
        }
        if (needDeployment) {
            if (!APIConstants.DEFAULT_SUB_POLICY_UNLIMITED.equalsIgnoreCase(policyName)) {
                SubscriptionPolicy retrievedPolicy = apiMgtDAO.getSubscriptionPolicy(policyName, tenantId);
                deployRetrievedSubscriptionPolicy(tenantId, retrievedPolicy);
            }
        }
    }
    // Adding Event based subscription level policies for async policies (WS & SSE)
    long[] eventCountSubPolicyValues = new long[] { 50000, 25000, 5000, Integer.MAX_VALUE };
    String[] eventCountSubPolicyNames = new String[] { APIConstants.DEFAULT_SUB_POLICY_ASYNC_GOLD, APIConstants.DEFAULT_SUB_POLICY_ASYNC_SILVER, APIConstants.DEFAULT_SUB_POLICY_ASYNC_BRONZE, APIConstants.DEFAULT_SUB_POLICY_ASYNC_UNLIMITED };
    String[] eventCountSubPolicyDescriptions = new String[] { APIConstants.DEFAULT_SUB_POLICY_ASYNC_GOLD_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_SILVER_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_BRONZE_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_UNLIMITED_DESC };
    for (int i = 0; i < eventCountSubPolicyNames.length; i++) {
        policyName = eventCountSubPolicyNames[i];
        boolean needDeployment = false;
        SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
        subscriptionPolicy.setDisplayName(policyName);
        subscriptionPolicy.setDescription(eventCountSubPolicyDescriptions[i]);
        subscriptionPolicy.setTenantId(tenantId);
        subscriptionPolicy.setDeployed(true);
        QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
        EventCountLimit eventCountLimit = new EventCountLimit();
        eventCountLimit.setEventCount(eventCountSubPolicyValues[i]);
        eventCountLimit.setUnitTime(1);
        eventCountLimit.setTimeUnit(APIConstants.TIME_UNIT_DAY);
        defaultQuotaPolicy.setType(PolicyConstants.EVENT_COUNT_TYPE);
        defaultQuotaPolicy.setLimit(eventCountLimit);
        subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
        subscriptionPolicy.setStopOnQuotaReach(true);
        subscriptionPolicy.setBillingPlan(APIConstants.BILLING_PLAN_FREE);
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
            apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
            needDeployment = true;
        }
        if (!apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
            needDeployment = true;
        }
        if (needDeployment) {
            SubscriptionPolicy retrievedPolicy = apiMgtDAO.getSubscriptionPolicy(policyName, tenantId);
            deployRetrievedSubscriptionPolicy(tenantId, retrievedPolicy);
        }
    }
    // Adding Event based Webhooks API specific policies (WEBSUB)
    long[] eventCountWHSubPolicyValues = new long[] { 10000, 5000, 1000, Integer.MAX_VALUE };
    int[] subscriptionCountValues = new int[] { 1000, 500, 100, Integer.MAX_VALUE };
    String[] eventCountWHSubPolicyNames = new String[] { APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_GOLD, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_SILVER, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_BRONZE, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_UNLIMITED };
    String[] eventCountWHSubPolicyDescriptions = new String[] { APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_GOLD_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_SILVER_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_BRONZE_DESC, APIConstants.DEFAULT_SUB_POLICY_ASYNC_WH_UNLIMITED_DESC };
    for (int i = 0; i < eventCountWHSubPolicyNames.length; i++) {
        policyName = eventCountWHSubPolicyNames[i];
        boolean needDeployment = false;
        SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
        subscriptionPolicy.setDisplayName(policyName);
        subscriptionPolicy.setDescription(eventCountWHSubPolicyDescriptions[i]);
        subscriptionPolicy.setTenantId(tenantId);
        subscriptionPolicy.setDeployed(true);
        QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
        EventCountLimit eventCountLimit = new EventCountLimit();
        eventCountLimit.setEventCount(eventCountWHSubPolicyValues[i]);
        eventCountLimit.setUnitTime(1);
        eventCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MONTH);
        defaultQuotaPolicy.setType(PolicyConstants.EVENT_COUNT_TYPE);
        defaultQuotaPolicy.setLimit(eventCountLimit);
        subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
        subscriptionPolicy.setStopOnQuotaReach(true);
        subscriptionPolicy.setBillingPlan(APIConstants.BILLING_PLAN_FREE);
        subscriptionPolicy.setSubscriberCount(subscriptionCountValues[i]);
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
            apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
            needDeployment = true;
        }
        if (!apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
            needDeployment = true;
        }
        if (needDeployment) {
            SubscriptionPolicy retrievedPolicy = apiMgtDAO.getSubscriptionPolicy(policyName, tenantId);
            deployRetrievedSubscriptionPolicy(tenantId, retrievedPolicy);
        }
    }
    long tenThousandPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN) ? defualtLimits.get(APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN) : 10000;
    long twentyThousandPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN) ? defualtLimits.get(APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN) : 20000;
    long fiftyThousandPerMinTier = defualtLimits.containsKey(APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN) ? defualtLimits.get(APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN) : 50000;
    long[] requestCountAPIPolicies = new long[] { fiftyThousandPerMinTier, twentyThousandPerMinTier, tenThousandPerMinTier, Integer.MAX_VALUE };
    // Adding Resource level policies
    String[] apiPolicies = new String[] { APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_UNLIMITED };
    String[] apiPolicyDecs = new String[] { APIConstants.DEFAULT_API_POLICY_ULTIMATE_DESC, APIConstants.DEFAULT_API_POLICY_PLUS_DESC, APIConstants.DEFAULT_API_POLICY_BASIC_DESC, APIConstants.DEFAULT_API_POLICY_UNLIMITED_DESC };
    for (int i = 0; i < apiPolicies.length; i++) {
        boolean needDeployment = false;
        policyName = apiPolicies[i];
        APIPolicy apiPolicy = new APIPolicy(policyName);
        apiPolicy.setDisplayName(policyName);
        apiPolicy.setDescription(apiPolicyDecs[i]);
        apiPolicy.setTenantId(tenantId);
        apiPolicy.setUserLevel(APIConstants.API_POLICY_API_LEVEL);
        apiPolicy.setDeployed(false);
        apiPolicy.setTenantDomain(tenantDomain);
        QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
        RequestCountLimit requestCountLimit = new RequestCountLimit();
        requestCountLimit.setRequestCount(requestCountAPIPolicies[i]);
        requestCountLimit.setUnitTime(1);
        requestCountLimit.setTimeUnit(APIConstants.TIME_UNIT_MINUTE);
        defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
        defaultQuotaPolicy.setLimit(requestCountLimit);
        apiPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_API, tenantId, policyName)) {
            apiMgtDAO.addAPIPolicy(apiPolicy);
        }
        if (!apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_API, tenantId, policyName)) {
            needDeployment = true;
        }
        if (needDeployment) {
            if (!APIConstants.DEFAULT_API_POLICY_UNLIMITED.equalsIgnoreCase(policyName)) {
                APIPolicy retrievedPolicy = apiMgtDAO.getAPIPolicy(policyName, tenantId);
                List<Integer> addedConditionGroupIds = new ArrayList<>();
                for (Pipeline pipeline : retrievedPolicy.getPipelines()) {
                    addedConditionGroupIds.add(pipeline.getId());
                }
                APIPolicyEvent apiPolicyEvent = new APIPolicyEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.POLICY_CREATE.name(), tenantId, retrievedPolicy.getTenantDomain(), retrievedPolicy.getPolicyId(), retrievedPolicy.getPolicyName(), retrievedPolicy.getDefaultQuotaPolicy().getType(), addedConditionGroupIds, null);
                APIUtil.sendNotification(apiPolicyEvent, APIConstants.NotifierType.POLICY.name());
            }
        }
    }
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) ArrayList(java.util.ArrayList) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) ApplicationPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.ApplicationPolicyEvent) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline) BigInteger(java.math.BigInteger) EventCountLimit(org.wso2.carbon.apimgt.api.model.policy.EventCountLimit) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) APIPolicyEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIPolicyEvent) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy)

Example 70 with QuotaPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.QuotaPolicy in project carbon-apimgt by wso2.

the class CommonThrottleMappingUtil method fromQuotaPolicyToDTO.

/**
 * Converts a Quota Policy object into a Throttle Limit DTO object
 *
 * @param quotaPolicy Quota Policy object
 * @return Throttle Limit DTO object derived from the Quota Policy object
 * @throws UnsupportedThrottleLimitTypeException
 */
public static ThrottleLimitDTO fromQuotaPolicyToDTO(QuotaPolicy quotaPolicy) throws UnsupportedThrottleLimitTypeException {
    ThrottleLimitDTO defaultLimitType = new ThrottleLimitDTO();
    if (PolicyConstants.REQUEST_COUNT_TYPE.equals(quotaPolicy.getType())) {
        RequestCountLimit requestCountLimit = (RequestCountLimit) quotaPolicy.getLimit();
        defaultLimitType.setType(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT);
        defaultLimitType.setRequestCount(fromRequestCountLimitToDTO(requestCountLimit));
    } else if (PolicyConstants.BANDWIDTH_TYPE.equals(quotaPolicy.getType())) {
        BandwidthLimit bandwidthLimit = (BandwidthLimit) quotaPolicy.getLimit();
        defaultLimitType.setType(ThrottleLimitDTO.TypeEnum.BANDWIDTHLIMIT);
        defaultLimitType.setBandwidth(fromBandwidthLimitToDTO(bandwidthLimit));
    } else if (PolicyConstants.EVENT_COUNT_TYPE.equals(quotaPolicy.getType())) {
        EventCountLimit eventCountLimit = (EventCountLimit) quotaPolicy.getLimit();
        defaultLimitType.setType(ThrottleLimitDTO.TypeEnum.EVENTCOUNTLIMIT);
        defaultLimitType.setEventCount(fromEventCountLimitToDTO(eventCountLimit));
    } else {
        String msg = "Throttle limit type " + quotaPolicy.getType() + " is not supported";
        throw new UnsupportedThrottleLimitTypeException(msg);
    }
    return defaultLimitType;
}
Also used : UnsupportedThrottleLimitTypeException(org.wso2.carbon.apimgt.api.UnsupportedThrottleLimitTypeException) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) EventCountLimit(org.wso2.carbon.apimgt.api.model.policy.EventCountLimit) ThrottleLimitDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.ThrottleLimitDTO) BandwidthLimit(org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit)

Aggregations

QuotaPolicy (org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy)34 QuotaPolicy (org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy)27 RequestCountLimit (org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit)24 RequestCountLimit (org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit)23 BandwidthLimit (org.wso2.carbon.apimgt.core.models.policy.BandwidthLimit)16 ArrayList (java.util.ArrayList)13 BandwidthLimit (org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit)12 SubscriptionPolicy (org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy)12 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)10 APIPolicy (org.wso2.carbon.apimgt.api.model.policy.APIPolicy)9 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)9 EventCountLimit (org.wso2.carbon.apimgt.api.model.policy.EventCountLimit)7 Test (org.testng.annotations.Test)6 ApplicationPolicy (org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy)6 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)6 ApiMgtDAO (org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO)6 Test (org.junit.Test)5 Matchers.anyString (org.mockito.Matchers.anyString)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)5 Pipeline (org.wso2.carbon.apimgt.api.model.policy.Pipeline)5