Search in sources :

Example 21 with QuotaPolicy

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

the class ApiMgtDAO method getPipelines.

/**
 * Retrieves list of pipelines for the policy with policy Id: <code>policyId</code>
 *
 * @param policyId policy id of the pipelines
 * @return list of pipelines
 * @throws APIManagementException
 */
private ArrayList<Pipeline> getPipelines(int policyId) throws APIManagementException {
    Connection connection = null;
    PreparedStatement pipelinesStatement = null;
    ResultSet resultSet = null;
    ArrayList<Pipeline> pipelines = new ArrayList<Pipeline>();
    try {
        connection = APIMgtDBUtil.getConnection();
        pipelinesStatement = connection.prepareStatement(SQLConstants.ThrottleSQLConstants.GET_PIPELINES_SQL);
        int unitTime = 0;
        int quota = 0;
        int pipelineId = -1;
        String timeUnit = null;
        String quotaUnit = null;
        String description;
        pipelinesStatement.setInt(1, policyId);
        resultSet = pipelinesStatement.executeQuery();
        while (resultSet.next()) {
            Pipeline pipeline = new Pipeline();
            ArrayList<Condition> conditions = null;
            QuotaPolicy quotaPolicy = new QuotaPolicy();
            quotaPolicy.setType(resultSet.getString(ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE));
            timeUnit = resultSet.getString(ThrottlePolicyConstants.COLUMN_TIME_UNIT);
            quotaUnit = resultSet.getString(ThrottlePolicyConstants.COLUMN_QUOTA_UNIT);
            unitTime = resultSet.getInt(ThrottlePolicyConstants.COLUMN_UNIT_TIME);
            quota = resultSet.getInt(ThrottlePolicyConstants.COLUMN_QUOTA);
            pipelineId = resultSet.getInt(ThrottlePolicyConstants.COLUMN_CONDITION_ID);
            description = resultSet.getString(ThrottlePolicyConstants.COLUMN_DESCRIPTION);
            if (PolicyConstants.REQUEST_COUNT_TYPE.equals(quotaPolicy.getType())) {
                RequestCountLimit requestCountLimit = new RequestCountLimit();
                requestCountLimit.setUnitTime(unitTime);
                requestCountLimit.setTimeUnit(timeUnit);
                requestCountLimit.setRequestCount(quota);
                quotaPolicy.setLimit(requestCountLimit);
            } else if (PolicyConstants.BANDWIDTH_TYPE.equals(quotaPolicy.getType())) {
                BandwidthLimit bandwidthLimit = new BandwidthLimit();
                bandwidthLimit.setUnitTime(unitTime);
                bandwidthLimit.setTimeUnit(timeUnit);
                bandwidthLimit.setDataUnit(quotaUnit);
                bandwidthLimit.setDataAmount(quota);
                quotaPolicy.setLimit(bandwidthLimit);
            }
            conditions = getConditions(pipelineId);
            pipeline.setConditions(conditions);
            pipeline.setQuotaPolicy(quotaPolicy);
            pipeline.setId(pipelineId);
            pipeline.setDescription(description);
            pipelines.add(pipeline);
        }
    } catch (SQLException e) {
        handleException("Failed to get pipelines for policyId: " + policyId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(pipelinesStatement, connection, resultSet);
    }
    return pipelines;
}
Also used : QueryParameterCondition(org.wso2.carbon.apimgt.api.model.policy.QueryParameterCondition) Condition(org.wso2.carbon.apimgt.api.model.policy.Condition) IPCondition(org.wso2.carbon.apimgt.api.model.policy.IPCondition) HeaderCondition(org.wso2.carbon.apimgt.api.model.policy.HeaderCondition) JWTClaimsCondition(org.wso2.carbon.apimgt.api.model.policy.JWTClaimsCondition) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) Pipeline(org.wso2.carbon.apimgt.api.model.policy.Pipeline) ResultSet(java.sql.ResultSet) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) BandwidthLimit(org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit)

Example 22 with QuotaPolicy

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

the class APIProviderImplTest method getPolicyAppLevel.

private ApplicationPolicy getPolicyAppLevel() {
    ApplicationPolicy policy = new ApplicationPolicy("gold");
    policy.setDescription("Description");
    policy.setTenantDomain("carbon.super");
    RequestCountLimit defaultLimit = new RequestCountLimit();
    defaultLimit.setTimeUnit("min");
    defaultLimit.setUnitTime(5);
    defaultLimit.setRequestCount(1000);
    QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
    defaultQuotaPolicy.setLimit(defaultLimit);
    defaultQuotaPolicy.setType("RequestCount");
    policy.setDefaultQuotaPolicy(defaultQuotaPolicy);
    return policy;
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy)

Example 23 with QuotaPolicy

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

the class APIUtil method addDefaultSuperTenantAdvancedThrottlePolicies.

public static void addDefaultSuperTenantAdvancedThrottlePolicies() throws APIManagementException {
    int tenantId = MultitenantConstants.SUPER_TENANT_ID;
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    /* Check if 'Unlimited' policy is available in AM_POLICY_APPLICATION table, to determine whether the default policies are loaded 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 server startup");
        return;
    }
    long[] requestCount = new long[] { 50, 20, 10, 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];
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_APP, tenantId, policyName)) {
            ApplicationPolicy applicationPolicy = new ApplicationPolicy(policyName);
            applicationPolicy.setDisplayName(policyName);
            applicationPolicy.setDescription(appPolicyDecs[i]);
            applicationPolicy.setTenantId(tenantId);
            applicationPolicy.setDeployed(true);
            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);
            apiMgtDAO.addApplicationPolicy(applicationPolicy);
        }
    }
    // Adding Subscription level policies
    long[] requestCountSubPolicies = new long[] { 5000, 2000, 1000, 500, 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];
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
            SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
            subscriptionPolicy.setDisplayName(policyName);
            subscriptionPolicy.setDescription(subPolicyDecs[i]);
            subscriptionPolicy.setTenantId(tenantId);
            subscriptionPolicy.setDeployed(true);
            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);
            apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
        }
    }
    // 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];
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
            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);
            apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
        }
    }
    // 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];
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_SUB, tenantId, policyName)) {
            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]);
            apiMgtDAO.addSubscriptionPolicy(subscriptionPolicy);
        }
    }
    // 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 };
    long[] requestCountApiPolicies = new long[] { 50000, 20000, 10000, Integer.MAX_VALUE };
    for (int i = 0; i < apiPolicies.length; i++) {
        policyName = apiPolicies[i];
        if (!apiMgtDAO.isPolicyExist(PolicyConstants.POLICY_LEVEL_API, tenantId, policyName)) {
            APIPolicy apiPolicy = new APIPolicy(policyName);
            apiPolicy.setDisplayName(policyName);
            apiPolicy.setDescription(apiPolicyDecs[i]);
            apiPolicy.setTenantId(tenantId);
            apiPolicy.setUserLevel(APIConstants.API_POLICY_API_LEVEL);
            apiPolicy.setDeployed(true);
            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);
            apiMgtDAO.addAPIPolicy(apiPolicy);
        }
    }
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) EventCountLimit(org.wso2.carbon.apimgt.api.model.policy.EventCountLimit) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 24 with QuotaPolicy

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

the class APIUtilTest method testGetAPIForPublishing.

@Test
public void testGetAPIForPublishing() throws Exception {
    API expectedAPI = getUniqueAPI();
    final String provider = expectedAPI.getId().getProviderName();
    final String tenantDomain = org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    final int tenantId = -1234;
    GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
    Registry registry = Mockito.mock(Registry.class);
    ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
    Resource resource = Mockito.mock(Resource.class);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
    SubscriptionPolicy policy = Mockito.mock(SubscriptionPolicy.class);
    SubscriptionPolicy[] policies = new SubscriptionPolicy[] { policy };
    QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
    RequestCountLimit limit = Mockito.mock(RequestCountLimit.class);
    PowerMockito.mockStatic(ApiMgtDAO.class);
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
    Mockito.when(apiMgtDAO.getAPIID(Mockito.any(String.class))).thenReturn(123);
    Mockito.when(artifact.getId()).thenReturn("");
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn(provider);
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT)).thenReturn("15");
    Mockito.when(MultitenantUtils.getTenantDomain(provider)).thenReturn(tenantDomain);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
    String artifactPath = "";
    Mockito.when(GovernanceUtils.getArtifactPath(registry, "")).thenReturn(artifactPath);
    Mockito.when(registry.get(artifactPath)).thenReturn(resource);
    Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());
    Mockito.when(resource.getCreatedTime()).thenReturn(expectedAPI.getLastUpdated());
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
    Mockito.when(apiMgtDAO.getSubscriptionPolicies(tenantId)).thenReturn(policies);
    Mockito.when(policy.getPolicyName()).thenReturn("policy");
    Mockito.when(policy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
    Mockito.when(quotaPolicy.getLimit()).thenReturn(limit);
    Mockito.when(registry.getTags(artifactPath)).thenReturn(getTagsFromSet(expectedAPI.getTags()));
    HashMap<String, String> urlPatterns = getURLTemplatePattern(expectedAPI.getUriTemplates());
    Mockito.when(apiMgtDAO.getURITemplatesPerAPIAsString(Mockito.any(String.class))).thenReturn(urlPatterns);
    CORSConfiguration corsConfiguration = expectedAPI.getCorsConfiguration();
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS)).thenReturn(corsConfiguration.getAccessControlAllowHeaders().toString());
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS)).thenReturn(corsConfiguration.getAccessControlAllowMethods().toString());
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN)).thenReturn(corsConfiguration.getAccessControlAllowOrigins().toString());
    Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)).thenReturn("{\"production_endpoints\":{\"url\":\"http://www.mocky.io/v2/5b21fe0f2e00002a00e313fe\"," + "\"config\":null,\"template_not_supported\":false}," + "\"sandbox_endpoints\":{\"url\":\"http://www.mocky.io/v2/5b21fe0f2e00002a00e313fe\"," + "\"config\":null,\"template_not_supported\":false},\"endpoint_type\":\"http\"}");
    API api = APIUtil.getAPIForPublishing(artifact, registry);
    Assert.assertNotNull(api);
    Set<String> testEnvironmentList = new HashSet<String>();
    testEnvironmentList.add("PRODUCTION");
    testEnvironmentList.add("SANDBOX");
    Assert.assertThat(SetUtils.isEqualSet(api.getEnvironmentList(), testEnvironmentList), is(true));
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) Resource(org.wso2.carbon.registry.core.Resource) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIUtil.getOAuthConfigurationFromTenantRegistry(org.wso2.carbon.apimgt.impl.utils.APIUtil.getOAuthConfigurationFromTenantRegistry) Registry(org.wso2.carbon.registry.core.Registry) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) RealmService(org.wso2.carbon.user.core.service.RealmService) API(org.wso2.carbon.apimgt.api.model.API) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) HashSet(java.util.HashSet) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 25 with QuotaPolicy

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

the class APIUtilTest method testGetAPIWithGovernanceArtifactAdvancedThrottlingDisabled.

@Test
public void testGetAPIWithGovernanceArtifactAdvancedThrottlingDisabled() throws Exception {
    System.setProperty("carbon.home", APIUtilTest.class.getResource("/").getFile());
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID);
        API expectedAPI = getUniqueAPI();
        final String provider = expectedAPI.getId().getProviderName();
        final String tenantDomain = org.wso2.carbon.utils.multitenancy.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        final int tenantId = -1234;
        System.setProperty("carbon.home", "");
        File siteConfFile = new File(Thread.currentThread().getContextClassLoader().getResource("tenant-conf.json").getFile());
        String tenantConfValue = FileUtils.readFileToString(siteConfFile);
        GovernanceArtifact artifact = Mockito.mock(GovernanceArtifact.class);
        Registry registry = Mockito.mock(Registry.class);
        ApiMgtDAO apiMgtDAO = Mockito.mock(ApiMgtDAO.class);
        Resource resource = Mockito.mock(Resource.class);
        ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
        RealmService realmService = Mockito.mock(RealmService.class);
        TenantManager tenantManager = Mockito.mock(TenantManager.class);
        APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
        APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
        ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
        SubscriptionPolicy policy = Mockito.mock(SubscriptionPolicy.class);
        SubscriptionPolicy[] policies = new SubscriptionPolicy[] { policy };
        QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
        RequestCountLimit limit = Mockito.mock(RequestCountLimit.class);
        RegistryService registryService = Mockito.mock(RegistryService.class);
        UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
        APIMConfigService apimConfigService = Mockito.mock(APIMConfigService.class);
        Mockito.when(serviceReferenceHolder.getApimConfigService()).thenReturn(apimConfigService);
        Mockito.when(apimConfigService.getTenantConfig(tenantDomain)).thenReturn(tenantConfValue);
        PowerMockito.mockStatic(ApiMgtDAO.class);
        PowerMockito.mockStatic(GovernanceUtils.class);
        PowerMockito.mockStatic(MultitenantUtils.class);
        PowerMockito.mockStatic(ServiceReferenceHolder.class);
        Mockito.when(ApiMgtDAO.getInstance()).thenReturn(apiMgtDAO);
        Mockito.when(apiMgtDAO.getAPIID(Mockito.any(String.class))).thenReturn(123);
        Mockito.when(apiMgtDAO.getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, provider)).thenReturn(new String[] { "Unlimited" });
        Mockito.when(artifact.getId()).thenReturn("");
        Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER)).thenReturn(provider);
        Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT)).thenReturn("15");
        Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_TIER)).thenReturn("Unlimited");
        Mockito.when(MultitenantUtils.getTenantDomain(provider)).thenReturn(tenantDomain);
        Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
        Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
        Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
        Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
        Mockito.when(tenantManager.getTenantId(tenantDomain)).thenReturn(tenantId);
        Mockito.when(registryService.getConfigSystemRegistry(tenantId)).thenReturn(userRegistry);
        String artifactPath = "";
        Mockito.when(GovernanceUtils.getArtifactPath(registry, "")).thenReturn(artifactPath);
        Mockito.when(registry.get(artifactPath)).thenReturn(resource);
        Mockito.when(resource.getLastModified()).thenReturn(expectedAPI.getLastUpdated());
        Mockito.when(resource.getCreatedTime()).thenReturn(expectedAPI.getLastUpdated());
        Mockito.when(resource.getContent()).thenReturn(tenantConfValue.getBytes());
        Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
        Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
        Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
        Mockito.when(apiMgtDAO.getSubscriptionPolicies(tenantId)).thenReturn(policies);
        Mockito.when(policy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
        Mockito.when(quotaPolicy.getLimit()).thenReturn(limit);
        Mockito.when(registry.getTags(artifactPath)).thenReturn(getTagsFromSet(expectedAPI.getTags()));
        ArrayList<URITemplate> urlList = getURLTemplateList(expectedAPI.getUriTemplates());
        Mockito.when(apiMgtDAO.getAllURITemplates(Mockito.anyString(), Mockito.anyString())).thenReturn(urlList);
        CORSConfiguration corsConfiguration = expectedAPI.getCorsConfiguration();
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS)).thenReturn(corsConfiguration.getAccessControlAllowHeaders().toString());
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_METHODS)).thenReturn(corsConfiguration.getAccessControlAllowMethods().toString());
        Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN)).thenReturn(corsConfiguration.getAccessControlAllowOrigins().toString());
        API api = APIUtil.getAPI(artifact);
        Assert.assertNotNull(api);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) Resource(org.wso2.carbon.registry.core.Resource) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIUtil.getOAuthConfigurationFromTenantRegistry(org.wso2.carbon.apimgt.impl.utils.APIUtil.getOAuthConfigurationFromTenantRegistry) Registry(org.wso2.carbon.registry.core.Registry) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) RealmService(org.wso2.carbon.user.core.service.RealmService) API(org.wso2.carbon.apimgt.api.model.API) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File) 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)

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