Search in sources :

Example 71 with APIPolicy

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

the class APIUtilTierTest method testGetTiersFromApiPolicies.

@Test
public void testGetTiersFromApiPolicies() throws Exception {
    System.setProperty("carbon.home", APIUtilRolesTest.class.getResource("/").getFile());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("abc.com");
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(1);
        String policyLevel = PolicyConstants.POLICY_LEVEL_API;
        int tenantId = 1;
        ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(tenantId);
        ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();
        PowerMockito.mockStatic(ServiceReferenceHolder.class);
        ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
        RealmService realmService = Mockito.mock(RealmService.class);
        TenantManager tenantManager = Mockito.mock(TenantManager.class);
        Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
        Mockito.when(tenantManager.getDomain(1)).thenReturn("abc.com");
        Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
        Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
        Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
        Mockito.when(apimConfigService.getTenantConfig("abc.com")).thenReturn(IOUtils.toString(tenantConf));
        APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
        APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
        ThrottleProperties throttleProperties = new ThrottleProperties();
        throttleProperties.setEnableUnlimitedTier(true);
        Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
        APIPolicy[] policies = generateApiPolicies(tiersReturned);
        Mockito.when(apiMgtDAO.getAPIPolicies(tenantId)).thenReturn(policies);
        Map<String, Tier> tiersFromPolicies = APIUtil.getTiersFromPolicies(policyLevel, tenantId);
        Mockito.verify(apiMgtDAO, Mockito.only()).getAPIPolicies(tenantId);
        for (APIPolicy policy : policies) {
            Tier tier = tiersFromPolicies.get(policy.getPolicyName());
            Assert.assertNotNull(tier);
            Assert.assertEquals(policy.getPolicyName(), tier.getName());
            Assert.assertEquals(policy.getDescription(), tier.getDescription());
        }
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) Tier(org.wso2.carbon.apimgt.api.model.Tier) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) Matchers.anyString(org.mockito.Matchers.anyString) RealmService(org.wso2.carbon.user.core.service.RealmService) ApiMgtDAOMockCreator(org.wso2.carbon.apimgt.impl.ApiMgtDAOMockCreator) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) APIMConfigService(org.wso2.carbon.apimgt.impl.config.APIMConfigService) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 72 with APIPolicy

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

the class APIMgtDAOTest method testGetApiPolicy.

@Test
public void testGetApiPolicy() throws APIManagementException {
    String policyName = "TestGetAPIPolicy";
    apiMgtDAO.addAPIPolicy((APIPolicy) getPolicyAPILevelPerUser(policyName));
    APIPolicy apiPolicy = apiMgtDAO.getAPIPolicy(policyName, -1234);
    assertNotNull(apiPolicy);
    assertEquals(apiPolicy.getPolicyName(), policyName);
    APIPolicy apiPolicyFromUUId = apiMgtDAO.getAPIPolicyByUUID(apiPolicy.getUUID());
    assertNotNull(apiPolicyFromUUId);
    assertEquals(apiPolicyFromUUId.getPolicyName(), policyName);
    apiMgtDAO.setPolicyDeploymentStatus(PolicyConstants.POLICY_LEVEL_API, apiPolicy.getPolicyName(), -1234, true);
    assertTrue(apiMgtDAO.isPolicyDeployed(PolicyConstants.POLICY_LEVEL_API, -1234, apiPolicy.getPolicyName()));
    assertTrue(apiMgtDAO.getPolicyNames(PolicyConstants.POLICY_LEVEL_API, "admin").length > 0);
    assertTrue(apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_API, -1234, apiPolicy.getPolicyName()));
}
Also used : APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 73 with APIPolicy

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

the class SubscriptionValidationDataUtil method fromApiPolicyToApiPolicyListDTO.

public static ApiPolicyListDTO fromApiPolicyToApiPolicyListDTO(List<APIPolicy> model) {
    ApiPolicyListDTO apiPolicyListDTO = new ApiPolicyListDTO();
    if (model != null) {
        for (APIPolicy apiPolicyModel : model) {
            ApiPolicyDTO policyDTO = new ApiPolicyDTO();
            policyDTO.setName(apiPolicyModel.getName());
            policyDTO.setQuotaType(apiPolicyModel.getQuotaType());
            policyDTO.setTenantId(apiPolicyModel.getTenantId());
            policyDTO.setTenantDomain(apiPolicyModel.getTenantDomain());
            policyDTO.setApplicableLevel(apiPolicyModel.getApplicableLevel());
            policyDTO.setDefaultLimit(getThrottleLimitDTO(apiPolicyModel));
            apiPolicyListDTO.getList().add(policyDTO);
            List<APIPolicyConditionGroup> retrievedGroups = apiPolicyModel.getConditionGroups();
            List<ApiPolicyConditionGroupDTO> condGroups = new ArrayList<ApiPolicyConditionGroupDTO>();
            for (APIPolicyConditionGroup retGroup : retrievedGroups) {
                ApiPolicyConditionGroupDTO group = new ApiPolicyConditionGroupDTO();
                group.setConditionGroupId(retGroup.getConditionGroupId());
                group.setQuotaType(retGroup.getQuotaType());
                group.setDefaultLimit(getThrottleLimitDTO(retGroup));
                group.setPolicyId(retGroup.getPolicyId());
                List<org.wso2.carbon.apimgt.internal.service.dto.ConditionDTO> condition = new ArrayList<org.wso2.carbon.apimgt.internal.service.dto.ConditionDTO>();
                List<ConditionDTO> retrievedConditions = retGroup.getConditionDTOS();
                for (ConditionDTO retrievedCondition : retrievedConditions) {
                    org.wso2.carbon.apimgt.internal.service.dto.ConditionDTO conditionDTO = new org.wso2.carbon.apimgt.internal.service.dto.ConditionDTO();
                    conditionDTO.setConditionType(retrievedCondition.getConditionType());
                    conditionDTO.setIsInverted(retrievedCondition.isInverted());
                    conditionDTO.setName(retrievedCondition.getConditionName());
                    conditionDTO.setValue(retrievedCondition.getConditionValue());
                    condition.add(conditionDTO);
                }
                group.setCondition(condition);
                condGroups.add(group);
            }
            policyDTO.setConditionGroups(condGroups);
        }
        apiPolicyListDTO.setCount(model.size());
    } else {
        apiPolicyListDTO.setCount(0);
    }
    return apiPolicyListDTO;
}
Also used : APIPolicyConditionGroup(org.wso2.carbon.apimgt.api.model.subscription.APIPolicyConditionGroup) ArrayList(java.util.ArrayList) ApiPolicyConditionGroupDTO(org.wso2.carbon.apimgt.internal.service.dto.ApiPolicyConditionGroupDTO) ApiPolicyDTO(org.wso2.carbon.apimgt.internal.service.dto.ApiPolicyDTO) ConditionDTO(org.wso2.carbon.apimgt.api.dto.ConditionDTO) APIPolicy(org.wso2.carbon.apimgt.api.model.subscription.APIPolicy) ApiPolicyListDTO(org.wso2.carbon.apimgt.internal.service.dto.ApiPolicyListDTO)

Example 74 with APIPolicy

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

the class ApiPoliciesApiServiceImpl method apiPoliciesGet.

public Response apiPoliciesGet(String xWSO2Tenant, String policyName, MessageContext messageContext) {
    SubscriptionValidationDAO subscriptionValidationDAO = new SubscriptionValidationDAO();
    xWSO2Tenant = SubscriptionValidationDataUtil.validateTenantDomain(xWSO2Tenant, messageContext);
    if (StringUtils.isNotEmpty(xWSO2Tenant)) {
        if (APIConstants.CHAR_ASTERIX.equals(xWSO2Tenant)) {
            return Response.ok().entity(SubscriptionValidationDataUtil.fromApiPolicyToApiPolicyListDTO(subscriptionValidationDAO.getAllApiPolicies())).build();
        } else if (StringUtils.isNotEmpty(policyName)) {
            List<APIPolicy> model = new ArrayList<>();
            APIPolicy apiPolicy = subscriptionValidationDAO.getApiPolicyByNameForTenant(policyName, xWSO2Tenant);
            if (apiPolicy != null) {
                model.add(apiPolicy);
            }
            return Response.ok().entity(SubscriptionValidationDataUtil.fromApiPolicyToApiPolicyListDTO(model)).build();
        } else {
            return Response.ok().entity(SubscriptionValidationDataUtil.fromApiPolicyToApiPolicyListDTO(subscriptionValidationDAO.getAllApiPolicies(xWSO2Tenant))).build();
        }
    } else {
        if (StringUtils.isNotEmpty(policyName)) {
            return Response.status(Response.Status.BAD_REQUEST.getStatusCode(), "X-WSo2-Tenant header is missing.").build();
        }
    }
    return Response.ok().entity(SubscriptionValidationDataUtil.fromApiPolicyToApiPolicyListDTO(subscriptionValidationDAO.getAllApiPolicies())).build();
}
Also used : ArrayList(java.util.ArrayList) List(java.util.List) APIPolicy(org.wso2.carbon.apimgt.api.model.subscription.APIPolicy) SubscriptionValidationDAO(org.wso2.carbon.apimgt.impl.dao.SubscriptionValidationDAO)

Example 75 with APIPolicy

use of org.wso2.carbon.apimgt.api.model.subscription.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)

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