Search in sources :

Example 61 with ApiPolicy

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

the class PublisherCommonUtils method prepareToCreateAPIByDTO.

/**
 * Prepares the API Model object to be created using the DTO object.
 *
 * @param body        APIDTO of the API
 * @param apiProvider API Provider
 * @param username    Username
 * @param organization  Organization Identifier
 * @return API object to be created
 * @throws APIManagementException Error while creating the API
 */
public static API prepareToCreateAPIByDTO(APIDTO body, APIProvider apiProvider, String username, String organization) throws APIManagementException {
    String context = body.getContext();
    // Make sure context starts with "/". ex: /pizza
    context = context.startsWith("/") ? context : ("/" + context);
    if (body.getAccessControlRoles() != null) {
        String errorMessage = PublisherCommonUtils.validateUserRoles(body.getAccessControlRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    if (body.getAdditionalProperties() != null) {
        String errorMessage = PublisherCommonUtils.validateAdditionalProperties(body.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, body.getName(), body.getVersion()));
        }
    }
    if (body.getContext() == null) {
        throw new APIManagementException("Parameter: \"context\" cannot be null", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    } else if (body.getContext().endsWith("/")) {
        throw new APIManagementException("Context cannot end with '/' character", ExceptionCodes.INVALID_CONTEXT);
    }
    if (apiProvider.isApiNameWithDifferentCaseExist(body.getName())) {
        throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists.", ExceptionCodes.from(ExceptionCodes.API_NAME_ALREADY_EXISTS, body.getName()));
    }
    if (body.getAuthorizationHeader() == null) {
        body.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
    }
    if (body.getAuthorizationHeader() == null) {
        body.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
    }
    if (body.getVisibility() == APIDTO.VisibilityEnum.RESTRICTED && body.getVisibleRoles().isEmpty()) {
        throw new APIManagementException("Valid roles should be added under 'visibleRoles' to restrict " + "the visibility", ExceptionCodes.USER_ROLES_CANNOT_BE_NULL);
    }
    if (body.getVisibleRoles() != null) {
        String errorMessage = PublisherCommonUtils.validateRoles(body.getVisibleRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    // Get all existing versions of  api been adding
    List<String> apiVersions = apiProvider.getApiVersionsMatchingApiNameAndOrganization(body.getName(), username, organization);
    if (apiVersions.size() > 0) {
        // If any previous version exists
        for (String version : apiVersions) {
            if (version.equalsIgnoreCase(body.getVersion())) {
                // If version already exists
                if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
                    throw new APIManagementException("Error occurred while " + "adding the API. A duplicate API already exists for " + context + " in the organization : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
                } else {
                    throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists with different context" + context + " in the organization" + " : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
                }
            }
        }
    } else {
        // If no any previous version exists
        if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
            throw new APIManagementException("Error occurred while adding the API. A duplicate API context already exists for " + context + " in the organization" + " : " + organization, ExceptionCodes.from(ExceptionCodes.API_CONTEXT_ALREADY_EXISTS, context));
        }
    }
    // Check if the user has admin permission before applying a different provider than the current user
    String provider = body.getProvider();
    if (!StringUtils.isBlank(provider) && !provider.equals(username)) {
        if (!APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN)) {
            if (log.isDebugEnabled()) {
                log.debug("User " + username + " does not have admin permission (" + APIConstants.Permissions.APIM_ADMIN + ") hence provider (" + provider + ") overridden with current user (" + username + ")");
            }
            provider = username;
        } else {
            if (!APIUtil.isUserExist(provider)) {
                throw new APIManagementException("Specified provider " + provider + " not exist.", ExceptionCodes.PARAMETER_NOT_PROVIDED);
            }
        }
    } else {
        // Set username in case provider is null or empty
        provider = username;
    }
    List<String> tiersFromDTO = body.getPolicies();
    // check whether the added API's tiers are all valid
    Set<Tier> definedTiers = apiProvider.getTiers();
    List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
    if (invalidTiers.size() > 0) {
        throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
    }
    APIPolicy apiPolicy = apiProvider.getAPIPolicy(username, body.getApiThrottlingPolicy());
    if (apiPolicy == null && body.getApiThrottlingPolicy() != null) {
        throw new APIManagementException("Specified policy " + body.getApiThrottlingPolicy() + " is invalid", ExceptionCodes.UNSUPPORTED_THROTTLE_LIMIT_TYPE);
    }
    API apiToAdd = APIMappingUtil.fromDTOtoAPI(body, provider);
    // only allow CREATED as the stating state for the new api if not status is PROTOTYPED
    if (!APIConstants.PROTOTYPED.equals(apiToAdd.getStatus())) {
        apiToAdd.setStatus(APIConstants.CREATED);
    }
    if (!apiToAdd.isAdvertiseOnly() || StringUtils.isBlank(apiToAdd.getApiOwner())) {
        // we are setting the api owner as the logged in user until we support checking admin privileges and
        // assigning the owner as a different user
        apiToAdd.setApiOwner(provider);
    }
    if (body.getKeyManagers() instanceof List) {
        apiToAdd.setKeyManagers((List<String>) body.getKeyManagers());
    } else if (body.getKeyManagers() == null) {
        apiToAdd.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    } else {
        throw new APIManagementException("KeyManagers value need to be an array");
    }
    // Set default gatewayVendor
    if (body.getGatewayVendor() == null) {
        apiToAdd.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
    }
    apiToAdd.setOrganization(organization);
    return apiToAdd;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) API(org.wso2.carbon.apimgt.api.model.API) List(java.util.List) ArrayList(java.util.ArrayList) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy)

Example 62 with ApiPolicy

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

the class APIUtilTierTest method mockPolicyRetrieval.

private void mockPolicyRetrieval(ApiMgtDAO apiMgtDAO) throws Exception {
    QuotaPolicy quotaPolicy = Mockito.mock(QuotaPolicy.class);
    ApplicationPolicy applicationPolicy = Mockito.mock(ApplicationPolicy.class);
    SubscriptionPolicy subscriptionPolicy = Mockito.mock(SubscriptionPolicy.class);
    APIPolicy apiPolicy = Mockito.mock(APIPolicy.class);
    Mockito.when(applicationPolicy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
    Mockito.when(subscriptionPolicy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
    Mockito.when(apiPolicy.getDefaultQuotaPolicy()).thenReturn(quotaPolicy);
    Mockito.when(apiMgtDAO.getApplicationPolicy(anyString(), anyInt())).thenReturn(applicationPolicy);
    Mockito.when(apiMgtDAO.getSubscriptionPolicy(anyString(), anyInt())).thenReturn(subscriptionPolicy);
    Mockito.when(apiMgtDAO.getAPIPolicy(anyString(), anyInt())).thenReturn(apiPolicy);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    Map<String, List<Notifier>> notifierMap = Mockito.mock(Map.class);
    List<Notifier> notifierList = new ArrayList<>();
    Mockito.when(notifierMap.get(any())).thenReturn(notifierList);
    Mockito.when(serviceReferenceHolder.getNotifiersMap()).thenReturn(notifierMap);
    APIManagerConfigurationService apiManagerConfigurationService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class);
    Map<String, Long> defaultLimits = new HashMap<>();
    Mockito.when(throttleProperties.getDefaultThrottleTierLimits()).thenReturn(defaultLimits);
    Mockito.when(apiManagerConfiguration.getThrottleProperties()).thenReturn(throttleProperties);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigurationService);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) APIManagerConfigurationService(org.wso2.carbon.apimgt.impl.APIManagerConfigurationService) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) List(java.util.List) ArrayList(java.util.ArrayList) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) Notifier(org.wso2.carbon.apimgt.impl.notifier.Notifier) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties)

Example 63 with ApiPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.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 64 with ApiPolicy

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

the class SubscriptionDataLoaderImpl method loadAllAPIPolicies.

@Override
public List<ApiPolicy> loadAllAPIPolicies(String tenantDomain) throws DataLoadingException {
    String apiPoliciesEP = APIConstants.SubscriptionValidationResources.API_POLICIES;
    List<ApiPolicy> apiPolicies = new ArrayList<>();
    String responseString = null;
    try {
        responseString = invokeService(apiPoliciesEP, tenantDomain);
    } catch (IOException e) {
        String msg = "Error while executing the http client " + apiPoliciesEP;
        log.error(msg, e);
        throw new DataLoadingException(msg, e);
    }
    if (responseString != null && !responseString.isEmpty()) {
        apiPolicies = (new Gson().fromJson(responseString, APIPolicyList.class)).getList();
    }
    return apiPolicies;
}
Also used : DataLoadingException(org.wso2.carbon.apimgt.keymgt.model.exception.DataLoadingException) APIPolicyList(org.wso2.carbon.apimgt.keymgt.model.entity.APIPolicyList) ApiPolicy(org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) IOException(java.io.IOException)

Example 65 with ApiPolicy

use of org.wso2.carbon.apimgt.throttle.policy.deployer.dto.ApiPolicy 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)

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