Search in sources :

Example 11 with APIPolicy

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

the class ThrottlerUtil method addDefaultAdvancedThrottlePolicies.

/**
 * Deploy default throttle polices at startup
 *
 * @throws APIManagementException throws if any exception occured
 */
public static void addDefaultAdvancedThrottlePolicies() throws APIManagementException {
    int[] requestCount = new int[] { 50, 20, 10, Integer.MAX_VALUE };
    // Adding application level throttle policies
    String[] appPolicies = new String[] { ThrottleConstants.DEFAULT_APP_POLICY_FIFTY_REQ_PER_MIN, ThrottleConstants.DEFAULT_APP_POLICY_TWENTY_REQ_PER_MIN, ThrottleConstants.DEFAULT_APP_POLICY_TEN_REQ_PER_MIN, ThrottleConstants.DEFAULT_APP_POLICY_UNLIMITED };
    String[] appPolicyDecs = new String[] { ThrottleConstants.DEFAULT_APP_POLICY_LARGE_DESC, ThrottleConstants.DEFAULT_APP_POLICY_MEDIUM_DESC, ThrottleConstants.DEFAULT_APP_POLICY_SMALL_DESC, ThrottleConstants.DEFAULT_APP_POLICY_UNLIMITED_DESC };
    PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
    String policyName;
    // Add application level throttle policies
    for (int i = 0; i < appPolicies.length; i++) {
        policyName = appPolicies[i];
        if (!isPolicyExist(APIMgtAdminService.PolicyLevel.application, policyName)) {
            ApplicationPolicy applicationPolicy = new ApplicationPolicy(policyName);
            applicationPolicy.setUuid(UUID.randomUUID().toString());
            applicationPolicy.setDisplayName(policyName);
            applicationPolicy.setDescription(appPolicyDecs[i]);
            applicationPolicy.setDeployed(true);
            QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
            RequestCountLimit requestCountLimit = new RequestCountLimit(ThrottleConstants.TIME_UNIT_MINUTE, 1, requestCount[i]);
            defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
            defaultQuotaPolicy.setLimit(requestCountLimit);
            applicationPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
            policyDAO.addApplicationPolicy(applicationPolicy);
        }
    }
    // Adding Subscription level policies
    int[] requestCountSubPolicies = new int[] { 5000, 2000, 1000, 500, Integer.MAX_VALUE };
    String[] subPolicies = new String[] { ThrottleConstants.DEFAULT_SUB_POLICY_GOLD, ThrottleConstants.DEFAULT_SUB_POLICY_SILVER, ThrottleConstants.DEFAULT_SUB_POLICY_BRONZE, ThrottleConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED, ThrottleConstants.DEFAULT_SUB_POLICY_UNLIMITED };
    String[] subPolicyDecs = new String[] { ThrottleConstants.DEFAULT_SUB_POLICY_GOLD_DESC, ThrottleConstants.DEFAULT_SUB_POLICY_SILVER_DESC, ThrottleConstants.DEFAULT_SUB_POLICY_BRONZE_DESC, ThrottleConstants.DEFAULT_SUB_POLICY_UNAUTHENTICATED_DESC, ThrottleConstants.DEFAULT_SUB_POLICY_UNLIMITED_DESC };
    for (int i = 0; i < subPolicies.length; i++) {
        policyName = subPolicies[i];
        if (!isPolicyExist(APIMgtAdminService.PolicyLevel.subscription, policyName)) {
            SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy(policyName);
            subscriptionPolicy.setUuid(UUID.randomUUID().toString());
            subscriptionPolicy.setDisplayName(policyName);
            subscriptionPolicy.setDescription(subPolicyDecs[i]);
            subscriptionPolicy.setDeployed(true);
            QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
            RequestCountLimit requestCountLimit = new RequestCountLimit(ThrottleConstants.TIME_UNIT_MINUTE, 1, requestCountSubPolicies[i]);
            defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
            defaultQuotaPolicy.setLimit(requestCountLimit);
            subscriptionPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
            subscriptionPolicy.setStopOnQuotaReach(true);
            subscriptionPolicy.setBillingPlan(ThrottleConstants.BILLING_PLAN_FREE);
            policyDAO.addSubscriptionPolicy(subscriptionPolicy);
        }
    }
    // Adding Resource level policies
    String[] apiPolicies = new String[] { ThrottleConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN, ThrottleConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN, ThrottleConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, ThrottleConstants.DEFAULT_API_POLICY_UNLIMITED };
    String[] apiPolicyDecs = new String[] { ThrottleConstants.DEFAULT_API_POLICY_ULTIMATE_DESC, ThrottleConstants.DEFAULT_API_POLICY_PLUS_DESC, ThrottleConstants.DEFAULT_API_POLICY_BASIC_DESC, ThrottleConstants.DEFAULT_API_POLICY_UNLIMITED_DESC };
    int[] requestCountApiPolicies = new int[] { 50000, 20000, 10000, Integer.MAX_VALUE };
    for (int i = 0; i < apiPolicies.length; i++) {
        policyName = apiPolicies[i];
        if (!isPolicyExist(APIMgtAdminService.PolicyLevel.api, policyName)) {
            APIPolicy apiPolicy = new APIPolicy(policyName);
            apiPolicy.setUuid(UUID.randomUUID().toString());
            apiPolicy.setDisplayName(policyName);
            apiPolicy.setDescription(apiPolicyDecs[i]);
            apiPolicy.setUserLevel(ThrottleConstants.API_POLICY_API_LEVEL);
            apiPolicy.setDeployed(true);
            QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
            RequestCountLimit requestCountLimit = new RequestCountLimit(ThrottleConstants.TIME_UNIT_MINUTE, 1, requestCountApiPolicies[i]);
            defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
            defaultQuotaPolicy.setLimit(requestCountLimit);
            apiPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
            policyDAO.addApiPolicy(apiPolicy);
        }
    }
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO)

Example 12 with APIPolicy

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

the class SampleTestObjectCreator method createDefaultAPIPolicy.

/**
 * create default api policy
 *
 * @return APIPolicy object is returned
 */
public static APIPolicy createDefaultAPIPolicy() {
    APIPolicy apiPolicy = new APIPolicy(SAMPLE_API_POLICY);
    apiPolicy.setUuid(UUID.randomUUID().toString());
    apiPolicy.setDisplayName(SAMPLE_API_POLICY);
    apiPolicy.setDescription(SAMPLE_API_POLICY_DESCRIPTION);
    apiPolicy.setUserLevel(APIMgtConstants.ThrottlePolicyConstants.API_LEVEL);
    QuotaPolicy defaultQuotaPolicy = new QuotaPolicy();
    defaultQuotaPolicy.setType(PolicyConstants.REQUEST_COUNT_TYPE);
    RequestCountLimit requestCountLimit = new RequestCountLimit(TIME_UNIT_SECONDS, 1000, 10000);
    defaultQuotaPolicy.setLimit(requestCountLimit);
    apiPolicy.setDefaultQuotaPolicy(defaultQuotaPolicy);
    apiPolicy.setPipelines(createDefaultPipelines());
    return apiPolicy;
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.core.models.policy.RequestCountLimit) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy)

Example 13 with APIPolicy

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

the class SampleTestObjectCreator method createDefaultSiddhiAppForAPIThrottlePolicy.

public static String createDefaultSiddhiAppForAPIThrottlePolicy() {
    APIPolicy apiPolicy = createDefaultAPIPolicy();
    String siddhiApp = "\n@App:name('resource_" + apiPolicy.getPolicyName() + "_condition_0')" + "\n@App:description('ExecutionPlan for resource_" + apiPolicy.getPolicyName() + "_condition_0')\n" + "\n@source(type='inMemory', topic='apim', @map(type='passThrough'))" + "\ndefine stream RequestStream (messageID string, appKey string, appTier string, " + "subscriptionKey string," + " apiKey string, apiTier string, subscriptionTier string, resourceKey string," + " resourceTier string, userId string,  apiContext string, apiVersion string, " + "appTenant string, apiTenant " + "string, appId string, apiName string, propertiesMap string);\n" + "\n@sink(type='jms', @map(type='text')," + "\nfactory.initial='org.wso2.andes.jndi.PropertiesFileInitialContextFactory'," + " provider.url='tcp://localhost:5672', " + "destination='TEST.FOO', connection.factory.type='topic'," + "\nconnection.factory.jndi.name='TopicConnectionFactory')" + "\ndefine stream GlobalThrottleStream (throttleKey string, isThrottled bool," + " expiryTimeStamp long);\n" + "\nFROM RequestStream" + "\nSELECT messageID, (resourceTier == 'SampleAPIPolicy' AND (regex:find('Chrome'," + "cast(map:get(propertiesMap,'Browser')," + "'string'))) AND (regex:find('attributed'," + "cast(map:get(propertiesMap,'/path/path2'),'string'))) AND " + "(cast(map:get(propertiesMap,'Location'),'string')=='Colombo'))" + " AS isEligible, str:concat(resourceKey," + "'_condition_0') AS throttleKey, propertiesMap" + "\nINSERT INTO EligibilityStream;\n" + "\nFROM EligibilityStream[isEligible==true]#throttler:timeBatch(1 s, 0)" + "\nselect throttleKey, (count(messageID) >= 1000) as isThrottled," + " expiryTimeStamp group by throttleKey" + "\nINSERT ALL EVENTS into ResultStream;\n" + "\nfrom ResultStream#throttler:emitOnStateChange(throttleKey, isThrottled)" + "\nselect *" + "\ninsert into GlobalThrottleStream;\n";
    return siddhiApp;
}
Also used : APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy)

Example 14 with APIPolicy

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

the class SampleTestObjectCreator method createUniqueAPI.

public static API.APIBuilder createUniqueAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_FOOD);
    tags.add(TAG_BEVERAGE);
    Set<Policy> policies = new HashSet<>();
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
    businessInformation.setTechnicalOwner(NAME_BUSINESS_OWNER_2);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_2);
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setEnabled(true);
    corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
    corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowOrigins(Arrays.asList("*"));
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
    Map permissionMap = new HashMap();
    permissionMap.put(DEVELOPER_ROLE_ID, 6);
    permissionMap.put(ADMIN_ROLE_ID, 15);
    List<String> defaultLabels = getDefaultLabels();
    API.APIBuilder apiBuilder = new API.APIBuilder(UUID.randomUUID().toString(), UUID.randomUUID().toString(), API_VERSION).id(UUID.randomUUID().toString()).context(UUID.randomUUID().toString()).description("Get Food & Beverage Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).endpoint(Collections.emptyMap()).isResponseCachingEnabled(true).cacheTimeout(120).isDefaultVersion(true).apiPolicy(goldApiPolicy).transport(transport).tags(tags).labels(defaultLabels).policies(policies).visibility(API.Visibility.RESTRICTED).visibleRoles(new HashSet<>(Arrays.asList(CUSTOMER_ROLE, MANAGER_ROLE, EMPLOYEE_ROLE))).businessInformation(businessInformation).corsConfiguration(corsConfiguration).apiPermission(permissionJson).permissionMap(permissionMap).createdTime(LocalDateTime.now()).createdBy(API_CREATOR).uriTemplates(Collections.emptyMap()).apiDefinition(apiDefinition).lastUpdatedTime(LocalDateTime.now()).securityScheme(3).threatProtectionPolicies(threatProtectionPolicies);
    return apiBuilder;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) CustomPolicy(org.wso2.carbon.apimgt.core.models.policy.CustomPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) ThreatProtectionPolicy(org.wso2.carbon.apimgt.core.models.policy.ThreatProtectionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) HashMap(java.util.HashMap) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) Map(java.util.Map) HashedMap(org.apache.commons.collections.map.HashedMap) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 15 with APIPolicy

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

the class APIPublisherImplTestCase method testUpdateDescription.

@Test(description = "Test add api with production endpoint")
public void testUpdateDescription() throws APIManagementException {
    /**
     * this test method verify the API Add with correct API object get invoked correctly
     */
    Map<String, Endpoint> endpointMap = SampleTestObjectCreator.getMockEndpointMap();
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id(UUID.randomUUID().toString()).endpoint(endpointMap);
    apiBuilder.apiPermission("");
    apiBuilder.permissionMap(null);
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    Mockito.when(apiDAO.getAPI(apiBuilder.getId())).thenReturn(apiBuilder.build());
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, GOLD_TIER)).thenReturn(new SubscriptionPolicy(GOLD_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, SILVER_TIER)).thenReturn(new SubscriptionPolicy(SILVER_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, BRONZE_TIER)).thenReturn(new SubscriptionPolicy(BRONZE_TIER));
    APIPublisherImpl apiPublisher = getApiPublisherImpl(identityProvider, apiDAO, apiLifecycleManager, gatewaySourceGenerator, gateway, policyDAO);
    Mockito.when(apiDAO.getEndpoint(endpointMap.get(APIMgtConstants.PRODUCTION_ENDPOINT).getId())).thenReturn(endpointMap.get(APIMgtConstants.PRODUCTION_ENDPOINT));
    Mockito.when(apiDAO.getEndpoint(endpointMap.get(APIMgtConstants.SANDBOX_ENDPOINT).getId())).thenReturn(endpointMap.get(APIMgtConstants.SANDBOX_ENDPOINT));
    Mockito.when(apiDAO.getEndpointByName(endpointMap.get(APIMgtConstants.PRODUCTION_ENDPOINT).getName())).thenReturn(endpointMap.get(APIMgtConstants.PRODUCTION_ENDPOINT));
    Mockito.when(apiDAO.getEndpointByName(endpointMap.get(APIMgtConstants.SANDBOX_ENDPOINT).getName())).thenReturn(endpointMap.get(APIMgtConstants.SANDBOX_ENDPOINT));
    Mockito.when(apiDAO.getApiSwaggerDefinition(apiBuilder.getId())).thenReturn(SampleTestObjectCreator.apiDefinition);
    apiBuilder.description("aaaaaa");
    apiPublisher.updateAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).updateAPI(apiBuilder.getId(), apiBuilder.build());
}
Also used : APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) Test(org.testng.annotations.Test)

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