Search in sources :

Example 71 with ApiPolicy

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

the class APIProviderImplTest method testGetAPIPolicyByUUID.

@Test
public void testGetAPIPolicyByUUID() throws APIManagementException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    APIPolicy apiPolicy = Mockito.mock(APIPolicy.class);
    Mockito.when(apimgtDAO.getAPIPolicyByUUID("1111")).thenReturn(apiPolicy, null);
    apiProvider.getAPIPolicyByUUID("1111");
    try {
        assertNotNull(apiProvider.getAPIPolicyByUUID("1111"));
    } catch (APIManagementException e) {
        assertEquals("Advanced Policy: 1111 was not found.", e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 72 with ApiPolicy

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

the class APIProviderImplTest method testGetAPIPolicy.

@Test
public void testGetAPIPolicy() throws APIManagementException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    PowerMockito.when(APIUtil.getTenantId("testUser")).thenReturn(1111);
    APIPolicy apiPolicy = Mockito.mock(APIPolicy.class);
    Mockito.when(apimgtDAO.getAPIPolicy("testPolicy", 1111)).thenReturn(apiPolicy);
    assertNotNull(apiProvider.getAPIPolicy("testUser", "testPolicy"));
}
Also used : APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 73 with ApiPolicy

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

the class APIProviderImplTest method getPolicyAPILevelPerUser.

private APIPolicy getPolicyAPILevelPerUser() {
    APIPolicy policy = new APIPolicy("custom1");
    policy.setUserLevel(PolicyConstants.PER_USER);
    policy.setDescription("Description");
    // policy.setPolicyLevel("api");
    policy.setTenantDomain("carbon.super");
    RequestCountLimit defaultLimit = new RequestCountLimit();
    defaultLimit.setTimeUnit("min");
    defaultLimit.setUnitTime(5);
    defaultLimit.setRequestCount(400);
    QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
    defaultQuotaPolicy.setLimit(defaultLimit);
    defaultQuotaPolicy.setType("RequestCount");
    policy.setDefaultQuotaPolicy(defaultQuotaPolicy);
    List<Pipeline> pipelines;
    Pipeline p;
    QuotaPolicy quotaPolicy;
    List<Condition> condition;
    RequestCountLimit countlimit;
    Condition cond;
    pipelines = new ArrayList<Pipeline>();
    // /////////pipeline item start//////
    p = new Pipeline();
    quotaPolicy = new QuotaPolicy();
    quotaPolicy.setType("RequestCount");
    countlimit = new RequestCountLimit();
    countlimit.setTimeUnit("min");
    countlimit.setUnitTime(5);
    countlimit.setRequestCount(100);
    quotaPolicy.setLimit(countlimit);
    condition = new ArrayList<Condition>();
    HTTPVerbCondition verbCond = new HTTPVerbCondition();
    verbCond.setHttpVerb("POST");
    condition.add(verbCond);
    p.setQuotaPolicy(quotaPolicy);
    p.setConditions(condition);
    pipelines.add(p);
    // /////////pipeline item end//////
    policy.setPipelines(pipelines);
    return policy;
}
Also used : HTTPVerbCondition(org.wso2.carbon.apimgt.api.model.policy.HTTPVerbCondition) Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline) HTTPVerbCondition(org.wso2.carbon.apimgt.api.model.policy.HTTPVerbCondition)

Example 74 with ApiPolicy

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

the class ThrottlePolicyTemplateBuilder method getThrottlePolicyForAPILevelDefault.

/**
 * Generate default policy for API level throttling
 *
 * @param policy Policy with level 'api'. Policy can have multiple pipelines and a default condition which will be
 *               used as else condition
 * @return the generated execution plan for the policy
 * @throws APITemplateException if failed to generate policy
 */
public String getThrottlePolicyForAPILevelDefault(ApiPolicy policy) throws APITemplateException {
    if (log.isDebugEnabled()) {
        log.debug("Generating default policy for API Level :" + policy.toString());
    }
    Set<String> conditionsSet = new HashSet<>();
    try {
        VelocityEngine velocityengine = new VelocityEngine();
        APIUtil.initializeVelocityContext(velocityengine);
        velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        velocityengine.init();
        Template template = velocityengine.getTemplate(getTemplatePathForAPIDefaultPolicy());
        StringWriter writer;
        VelocityContext context;
        List<APIPolicyConditionGroup> conditionGroups = policy.getConditionGroups();
        JSONArray policyConditionJson = new JSONArray();
        if (conditionGroups != null) {
            for (APIPolicyConditionGroup conditionGroup : conditionGroups) {
                if (conditionGroup.getDefaultLimit() == null) {
                    continue;
                }
                policyConditionJson.add(getPolicyConditionJson(conditionGroup.getCondition()));
                String conditionString = getPolicyConditionForDefault(conditionGroup.getCondition());
                if (!StringUtils.isEmpty(conditionString)) {
                    conditionsSet.add(conditionString);
                }
            }
        }
        context = new VelocityContext();
        setConstantContext(context);
        context.put("policy", policy);
        context.put("quotaPolicy", policy.getDefaultLimit());
        context.put("evaluatedConditions", new String(Base64.encodeBase64(policyConditionJson.toJSONString().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
        String conditionSetString = getConditionForDefault(conditionsSet);
        if (!StringUtils.isEmpty(conditionSetString)) {
            context.put("condition", " AND " + conditionSetString);
        } else {
            context.put("condition", "");
        }
        writer = new StringWriter();
        template.merge(context, writer);
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + writer.toString());
        }
        return writer.toString();
    } catch (VelocityException e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) APIPolicyConditionGroup(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.APIPolicyConditionGroup) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) JSONArray(org.json.simple.JSONArray) VelocityException(org.apache.velocity.exception.VelocityException) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) HashSet(java.util.HashSet) Template(org.apache.velocity.Template)

Example 75 with ApiPolicy

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

the class ThrottlePolicyTemplateBuilder method getThrottlePolicyForAPILevel.

/**
 * Generate policy for API level throttling
 *
 * @param policy Policy with level 'api'. Policy can have multiple pipelines and a default condition which will be
 *               used as else condition
 * @return a Map containing a set of policies for each condition group
 * @throws APITemplateException if failed to generate policy
 */
public Map<String, String> getThrottlePolicyForAPILevel(ApiPolicy policy) throws APITemplateException {
    if (log.isDebugEnabled()) {
        log.debug("Generating policy for API Level :" + policy.toString());
    }
    Map<String, String> policyArray = new HashMap<>();
    try {
        VelocityEngine velocityengine = new VelocityEngine();
        APIUtil.initializeVelocityContext(velocityengine);
        velocityengine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
        velocityengine.init();
        Template template = velocityengine.getTemplate(getTemplatePathForAPI());
        StringWriter writer;
        VelocityContext context;
        if (policy.getConditionGroups() != null) {
            for (APIPolicyConditionGroup conditionGroup : policy.getConditionGroups()) {
                if (conditionGroup.getDefaultLimit() == null) {
                    continue;
                }
                context = new VelocityContext();
                setConstantContext(context);
                context.put("policy", policy);
                context.put("quotaPolicy", conditionGroup.getDefaultLimit());
                context.put("pipeline", "condition_" + conditionGroup.getConditionGroupId());
                String conditionString = getPolicyCondition(conditionGroup.getCondition());
                JSONArray conditions = new JSONArray();
                conditions.add(getPolicyConditionJson(conditionGroup.getCondition()));
                context.put("condition", " AND " + conditionString);
                context.put("evaluatedConditions", new String(Base64.encodeBase64(conditions.toJSONString().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
                writer = new StringWriter();
                template.merge(context, writer);
                if (log.isDebugEnabled()) {
                    log.debug("Policy : " + writer.toString());
                }
                String policyName = policy.getTenantDomain() + APIConstants.DELEM_UNDERSCORE + PolicyConstants.POLICY_LEVEL_RESOURCE + APIConstants.DELEM_UNDERSCORE + policy.getName() + APIConstants.THROTTLE_POLICY_CONDITION + conditionGroup.getConditionGroupId();
                policyArray.put(policyName, writer.toString());
            }
        }
    } catch (VelocityException e) {
        log.error("Velocity Error", e);
        throw new APITemplateException("Velocity Error", e);
    }
    return policyArray;
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) APIPolicyConditionGroup(org.wso2.carbon.apimgt.throttle.policy.deployer.dto.APIPolicyConditionGroup) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) JSONArray(org.json.simple.JSONArray) VelocityException(org.apache.velocity.exception.VelocityException) APITemplateException(org.wso2.carbon.apimgt.impl.template.APITemplateException) Template(org.apache.velocity.Template)

Aggregations

APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)87 Test (org.testng.annotations.Test)44 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)40 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)39 ArrayList (java.util.ArrayList)38 API (org.wso2.carbon.apimgt.core.models.API)33 APIPolicy (org.wso2.carbon.apimgt.api.model.policy.APIPolicy)30 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)27 HashMap (java.util.HashMap)25 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)22 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)22 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)22 APIBuilder (org.wso2.carbon.apimgt.core.models.API.APIBuilder)21 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)20 HashSet (java.util.HashSet)19 Test (org.junit.Test)19 QuotaPolicy (org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy)19 ApplicationPolicy (org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)17 PreparedStatement (java.sql.PreparedStatement)15