org.wso2.carbon.apimgt.api.model.Tier Java Examples

The following examples show how to use org.wso2.carbon.apimgt.api.model.Tier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAllTiers() throws APIManagementException {
    Map<String, Tier> tierMap = new HashMap<String, Tier>();
    Tier tier1 = new Tier("tier1");
    Tier tier2 = new Tier("tier2");
    tierMap.put("Gold", tier1);
    tierMap.put("Silver", tier2);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getAllTiers()).thenReturn(tierMap);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(null, null, null, null);
    abstractAPIManager.tenantId = -1;
    Assert.assertEquals(abstractAPIManager.getAllTiers().size(), 2);
    abstractAPIManager.tenantId = -1234;
    abstractAPIManager.tenantDomain = SAMPLE_TENANT_DOMAIN_1;
    PowerMockito.when(APIUtil.getAllTiers(Mockito.anyInt())).thenReturn(tierMap);
    Assert.assertEquals(abstractAPIManager.getAllTiers().size(), 2);
}
 
Example #2
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
 *
 * @return Set<Tier>
 */
public Set<Tier> getTiers() throws APIManagementException {
    Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());

    Map<String, Tier> tierMap;
    if (!APIUtil.isAdvanceThrottlingEnabled()) {
        if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
            tierMap = APIUtil.getTiers();
        } else {
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId, true);
            tierMap = APIUtil.getTiers(tenantId);
            endTenantFlow();
        }
        tiers.addAll(tierMap.values());
    } else {
        tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
        tiers.addAll(tierMap.values());
    }

    return tiers;
}
 
Example #3
Source File: ThrottlingPolicyMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Fills the tier information on TierDTO
 *
 * @param throttlingPolicyDTO Object Containing throttling policy DTOs
 * @param throttlingPolicy    Throttling Policy object
 * @return ThrottlingPolicyDTO with permission info
 */
public static ThrottlingPolicyDTO setTierPermissions(ThrottlingPolicyDTO throttlingPolicyDTO, Tier throttlingPolicy) {

    ThrottlingPolicyPermissionInfoDTO tierPermission = new ThrottlingPolicyPermissionInfoDTO();

    // If no permission found for the tier, the default permission will be applied
    if (throttlingPolicy.getTierPermission() == null ||
            throttlingPolicy.getTierPermission().getPermissionType() == null) {
        tierPermission.setType(ThrottlingPolicyPermissionInfoDTO.TypeEnum.valueOf("ALLOW"));
        List<String> roles = new ArrayList<>();
        roles.add("Internal/everyone");
        tierPermission.setRoles(roles);
    } else {
        String permissionType = throttlingPolicy.getTierPermission().getPermissionType();
        tierPermission.setType(ThrottlingPolicyPermissionInfoDTO.TypeEnum.valueOf(permissionType));
        tierPermission.setRoles(Arrays.asList(throttlingPolicy.getTierPermission().getRoles()));
    }
    throttlingPolicyDTO.setThrottlingPolicyPermissions(tierPermission);

    return throttlingPolicyDTO;
}
 
Example #4
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Set<Tier> getAllTiers() throws APIManagementException {
    Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
    Map<String, Tier> tierMap;

    if (tenantId == MultitenantConstants.INVALID_TENANT_ID) {
        tierMap = APIUtil.getAllTiers();
    } else {
        boolean isTenantFlowStarted = false;
        try {
            if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                startTenantFlow(tenantDomain);
                isTenantFlowStarted = true;
            }
            tierMap = APIUtil.getAllTiers(tenantId);
        } finally {
            if (isTenantFlowStarted) {
                endTenantFlow();
            }
        }
    }

    tiers.addAll(tierMap.values());
    return tiers;
}
 
Example #5
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Add default application on the first time a subscriber is added to the database
 *
 * @param subscriber Subscriber
 * @throws APIManagementException if an error occurs while adding default application
 */
private void addDefaultApplicationForSubscriber(Subscriber subscriber) throws APIManagementException {
    Application defaultApp = new Application(APIConstants.DEFAULT_APPLICATION_NAME, subscriber);
    if (APIUtil.isEnabledUnlimitedTier()) {
        defaultApp.setTier(APIConstants.UNLIMITED_TIER);
    } else {
        Map<String, Tier> throttlingTiers = APIUtil.getTiers(APIConstants.TIER_APPLICATION_TYPE,
                getTenantDomain(subscriber.getName()));
        Set<Tier> tierValueList = new HashSet<Tier>(throttlingTiers.values());
        List<Tier> sortedTierList = APIUtil.sortTiers(tierValueList);
        defaultApp.setTier(sortedTierList.get(0).getName());
    }
    //application will not be shared within the group
    defaultApp.setGroupId("");
    defaultApp.setTokenType(APIConstants.TOKEN_TYPE_JWT);
    apiMgtDAO.addApplication(defaultApp, subscriber.getName());
}
 
Example #6
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
 *
 * @return Set<Tier>
 */
public Set<Tier> getTiers(String tenantDomain) throws APIManagementException {

    Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());
    Map<String, Tier> tierMap;
    if (!APIUtil.isAdvanceThrottlingEnabled()) {
        startTenantFlow(tenantDomain);
        int requestedTenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        if (requestedTenantId == MultitenantConstants.SUPER_TENANT_ID
                || requestedTenantId == MultitenantConstants.INVALID_TENANT_ID) {
            tierMap = APIUtil.getTiers();
        } else {
            tierMap = APIUtil.getTiers(requestedTenantId);
        }
        tiers.addAll(tierMap.values());
        endTenantFlow();
    } else {
        tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
        tiers.addAll(tierMap.values());
    }
    return tiers;
}
 
Example #7
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of pre-defined # {@link org.wso2.carbon.apimgt.api.model.Tier} in the system.
 *
 * @param tierType type of the tiers (api,resource ot application)
 * @param username current logged user
 * @return Set<Tier> return list of tier names
 * @throws APIManagementException APIManagementException if failed to get the predefined tiers
 */
public Set<Tier> getTiers(int tierType, String username) throws APIManagementException {
    Set<Tier> tiers = new TreeSet<Tier>(new TierNameComparator());

    String tenantDomain = getTenantDomain(username);
    Map<String, Tier> tierMap;
    if (!APIUtil.isAdvanceThrottlingEnabled()) {
        tierMap = APIUtil.getTiers(tierType, tenantDomain);
        tiers.addAll(tierMap.values());
    } else {
        int tenantIdFromUsername = APIUtil.getTenantId(username);
        if (tierType == APIConstants.TIER_API_TYPE) {
            tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantIdFromUsername);
        } else if (tierType == APIConstants.TIER_RESOURCE_TYPE) {
            tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_API, tenantIdFromUsername);
        } else if (tierType == APIConstants.TIER_APPLICATION_TYPE) {
            tierMap = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_APP, tenantIdFromUsername);
        } else {
            throw new APIManagementException("No such a tier type : " + tierType);
        }
        tiers.addAll(tierMap.values());
    }

    return tiers;
}
 
Example #8
Source File: ThrottlingPoliciesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all the Tiers
 *
 * @param policyLevel   tier level (api/application or resource)
 * @param limit max number of objects returns
 * @param offset starting index
 * @param ifNoneMatch If-None-Match header value
 * @return Response object containing resulted tiers
 */
@Override
public Response getAllThrottlingPolicies(String policyLevel, Integer limit, Integer offset,
        String ifNoneMatch,MessageContext messageContext) {
    //pre-processing
    //setting default limit and offset if they are null
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;

    List<Tier> tierList = getThrottlingPolicyList(policyLevel);
    ThrottlingPolicyListDTO policyListDTO = ThrottlingPolicyMappingUtil
            .fromTierListToDTO(tierList, policyLevel, limit, offset);

    //todo: set total counts properly
    ThrottlingPolicyMappingUtil.setPaginationParams(policyListDTO, policyLevel, limit, offset, tierList.size());
    return Response.ok().entity(policyListDTO).build();
}
 
Example #9
Source File: ThrottlingPolicyMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a List object of Tiers into a DTO
 *
 * @param tiers  a list of Tier objects
 * @param limit  max number of objects returned
 * @param offset starting index
 * @return ThrottlingPolicyListDTO object containing ThrottlingPolicyDTOs
 */
public static ThrottlingPolicyListDTO fromTierListToDTO(List<Tier> tiers, String tierLevel, int limit, int offset) {
    ThrottlingPolicyListDTO throttlingPolicyListDTO = new ThrottlingPolicyListDTO();
    List<ThrottlingPolicyDTO> ThrottlingPolicyDTOs = throttlingPolicyListDTO.getList();
    if (ThrottlingPolicyDTOs == null) {
        ThrottlingPolicyDTOs = new ArrayList<>();
        throttlingPolicyListDTO.setList(ThrottlingPolicyDTOs);
    }

    //identifying the proper start and end indexes
    int size = tiers.size();
    int start = offset < size && offset >= 0 ? offset : Integer.MAX_VALUE;
    int end = offset + limit - 1 <= size - 1 ? offset + limit - 1 : size - 1;

    for (int i = start; i <= end; i++) {
        Tier tier = tiers.get(i);
        ThrottlingPolicyDTOs.add(fromTierToDTO(tier, tierLevel));
    }
    throttlingPolicyListDTO.setCount(ThrottlingPolicyDTOs.size());
    return throttlingPolicyListDTO;
}
 
Example #10
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetAllTiersForTenant() throws APIManagementException {

    Mockito.when(privilegedCarbonContext.getTenantId()).thenReturn(-1234, -1, 1);
    Map<String, Tier> tierMap = new HashMap<String, Tier>();
    Tier tier1 = new Tier("tier1");
    Tier tier2 = new Tier("tier2");
    tierMap.put("Gold", tier1);
    tierMap.put("Silver", tier2);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getAllTiers()).thenReturn(tierMap);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(null, null, null, null);
    Assert.assertEquals(abstractAPIManager.getAllTiers(SAMPLE_TENANT_DOMAIN_1).size(), 2);
    PowerMockito.when(APIUtil.getAllTiers(Mockito.anyInt())).thenReturn(tierMap);
    Assert.assertEquals(abstractAPIManager.getAllTiers(SAMPLE_TENANT_DOMAIN_1).size(), 2);
    Assert.assertEquals(abstractAPIManager.getAllTiers(SAMPLE_TENANT_DOMAIN_1).size(), 2); // verify the next branch
}
 
Example #11
Source File: RestApiUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether the list of tiers are valid given the all valid tiers
 *
 * @param allTiers All defined tiers
 * @param currentTiers tiers to check if they are a subset of defined tiers
 * @return null if there are no invalid tiers or returns the set of invalid tiers if there are any
 */
public static List<String> getInvalidTierNames(Set<Tier> allTiers, List<String> currentTiers) {
    List<String> invalidTiers = new ArrayList<>();
    for (String tierName : currentTiers) {
        boolean isTierValid = false;
        for (Tier definedTier : allTiers) {
            if (tierName.equals(definedTier.getName())) {
                isTierValid = true;
                break;
            }
        }
        if (!isTierValid) {
            invalidTiers.add(tierName);
        }
    }
    return invalidTiers;
}
 
Example #12
Source File: ThrottlingPoliciesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response throttlingPoliciesPolicyLevelGet(
        String policyLevel, Integer limit, Integer offset, String ifNoneMatch, String xWSO2Tenant,
        MessageContext messageContext) {
    //pre-processing
    //setting default limit and offset if they are null
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;

    List<Tier> throttlingPolicyList = getThrottlingPolicyList(policyLevel, xWSO2Tenant);
    ThrottlingPolicyListDTO tierListDTO = ThrottlingPolicyMappingUtil.fromTierListToDTO(throttlingPolicyList,
            policyLevel, limit, offset);
    ThrottlingPolicyMappingUtil.setPaginationParams(tierListDTO, policyLevel, limit, offset,
            throttlingPolicyList.size());
    return Response.ok().entity(tierListDTO).build();
}
 
Example #13
Source File: ApisApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response apisApiIdSubscriptionPoliciesGet(String apiId, String ifNoneMatch, String xWSO2Tenant,
                                                 MessageContext messageContext) {
    APIDTO apiInfo = getAPIByAPIId(apiId, xWSO2Tenant);
    List<Tier> availableThrottlingPolicyList = new ThrottlingPoliciesApiServiceImpl()
            .getThrottlingPolicyList(ThrottlingPolicyDTO.PolicyLevelEnum.SUBSCRIPTION.toString(), xWSO2Tenant);

    if (apiInfo != null ) {
        List<APITiersDTO> apiTiers = apiInfo.getTiers();
        if (apiTiers != null && !apiTiers.isEmpty()) {
            List<Tier> apiThrottlingPolicies = new ArrayList<>();
            for (Tier policy : availableThrottlingPolicyList) {
                if (apiTiers.contains(policy.getName())) {
                    apiThrottlingPolicies.add(policy);
                }
            }
            return Response.ok().entity(apiThrottlingPolicies).build();
        }
    }
    return null;
}
 
Example #14
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTiers() throws APIManagementException {
    Map<String, Tier> tierMap1 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap2 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap3 = new HashMap<String, Tier>();
    Tier tier1 = new Tier("tier1");
    Tier tier2 = new Tier("tier2");
    Tier tier3 = new Tier("tier3");
    tierMap1.put("Gold", tier1);
    tierMap2.put("Gold", tier1);
    tierMap2.put("Silver", tier2);
    tierMap3.put("Gold", tier1);
    tierMap3.put("Silver", tier2);
    tierMap3.put("Platinum", tier3);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getTiers()).thenReturn(tierMap1);
    PowerMockito.when(APIUtil.getTiers(Mockito.anyInt())).thenReturn(tierMap2);
    PowerMockito.when(APIUtil.isAdvanceThrottlingEnabled()).thenReturn(false, false, true);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(null, null, null, null);
    abstractAPIManager.tenantId = -1;
    Assert.assertEquals(abstractAPIManager.getTiers().size(), 1);
    abstractAPIManager.tenantId = -1234;
    Assert.assertEquals(abstractAPIManager.getTiers().size(), 2);
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt())).thenReturn(tierMap3);
    Assert.assertEquals(abstractAPIManager.getTiers().size(), 3);
}
 
Example #15
Source File: ThrottlingPolicyMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a List object of Tiers into a DTO
 *
 * @param throttlingPolicyList a list of Tier objects
 * @param policyLevel          the policy level(eg: application or subscription)
 * @param limit                max number of objects returned
 * @param offset               starting index
 * @return TierListDTO object containing TierDTOs
 */
public static ThrottlingPolicyListDTO fromTierListToDTO(List<Tier> throttlingPolicyList, String policyLevel, int limit,
                                                        int offset) {

    ThrottlingPolicyListDTO throttlingPolicyListDTO = new ThrottlingPolicyListDTO();
    List<ThrottlingPolicyDTO> throttlingPolicyDTOs = throttlingPolicyListDTO.getList();
    if (throttlingPolicyDTOs == null) {
        throttlingPolicyDTOs = new ArrayList<>();
        throttlingPolicyListDTO.setList(throttlingPolicyDTOs);
    }

    //identifying the proper start and end indexes
    int size = throttlingPolicyList.size();
    int start = offset < size && offset >= 0 ? offset : Integer.MAX_VALUE;
    int end = offset + limit - 1 <= size - 1 ? offset + limit - 1 : size - 1;

    for (int i = start; i <= end; i++) {
        Tier tier = throttlingPolicyList.get(i);
        throttlingPolicyDTOs.add(fromTierToDTO(tier, policyLevel));
    }
    throttlingPolicyListDTO.setCount(throttlingPolicyDTOs.size());
    return throttlingPolicyListDTO;
}
 
Example #16
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSubscribedAPIs() throws APIManagementException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper();
    apiConsumer.apiMgtDAO = apiMgtDAO;
    Set<SubscribedAPI> originalSubscribedAPIs = new HashSet<SubscribedAPI>();

    SubscribedAPI subscribedAPI = Mockito.mock(SubscribedAPI.class);
    originalSubscribedAPIs.add(subscribedAPI);
    Subscriber subscriber = new Subscriber("Subscriber");
    Tier tier = Mockito.mock(Tier.class);

    when(apiMgtDAO.getSubscribedAPIs(subscriber, "testID")).thenReturn(originalSubscribedAPIs);
    when(subscribedAPI.getTier()).thenReturn(tier);
    when(tier.getName()).thenReturn("tier");
    assertNotNull(apiConsumer.getSubscribedAPIs(subscriber, "testID"));
}
 
Example #17
Source File: APIUtilTierTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTiersFromAppPolicies() throws Exception {
    String policyLevel = PolicyConstants.POLICY_LEVEL_APP;
    int tenantId = 1;

    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(tenantId);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    ServiceReferenceHolderMockCreator serviceReferenceHolderMockCreator =
            daoMockHolder.getServiceReferenceHolderMockCreator();

    serviceReferenceHolderMockCreator.initRegistryServiceMockCreator(true, tenantConf);

    ApplicationPolicy[] policies = generateAppPolicies(tiersReturned);
    Mockito.when(apiMgtDAO.getApplicationPolicies(tenantId)).thenReturn(policies);

    Map<String, Tier> tiersFromPolicies = APIUtil.getTiersFromPolicies(policyLevel, tenantId);

    Mockito.verify(apiMgtDAO, Mockito.only()).getApplicationPolicies(tenantId);

    for (ApplicationPolicy policy : policies) {
        Tier tier = tiersFromPolicies.get(policy.getPolicyName());
        Assert.assertNotNull(tier);
        Assert.assertEquals(policy.getPolicyName(), tier.getName());
        Assert.assertEquals(policy.getDescription(), tier.getDescription());
    }
}
 
Example #18
Source File: APIUtilTierTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private Map<String, Tier> getDefinedTiers() {
    Map<String, Tier> definedTiers = new HashMap<String, Tier>();

    for (String tierName : validTierNames) {
        definedTiers.put(tierName, new Tier(tierName));
    }

    return definedTiers;
}
 
Example #19
Source File: APIUtilTierTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private Set<Tier> getRoundRobinTierString(String[] values) {
    Set<Tier> tiers = new HashSet<Tier>();
    for (int i = 0; i < values.length; ++i) {
        if (i % 2 == 0) {
            tiers.add(new Tier(values[i]));
        }
    }

    return tiers;
}
 
Example #20
Source File: APIUtilTierTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTiersFromApiPoliciesBandwidth() throws Exception {
    String policyLevel = PolicyConstants.POLICY_LEVEL_API;
    int tenantId = 1;

    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(tenantId);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    ServiceReferenceHolderMockCreator serviceReferenceHolderMockCreator =
            daoMockHolder.getServiceReferenceHolderMockCreator();

    serviceReferenceHolderMockCreator.initRegistryServiceMockCreator(true, tenantConf);

    APIPolicy[] policies = generateApiPoliciesBandwidth(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());
    }
}
 
Example #21
Source File: APIUtilTierTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTiersFromApiPolicies() throws Exception {
    String policyLevel = PolicyConstants.POLICY_LEVEL_API;
    int tenantId = 1;

    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(tenantId);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    ServiceReferenceHolderMockCreator serviceReferenceHolderMockCreator =
            daoMockHolder.getServiceReferenceHolderMockCreator();

    serviceReferenceHolderMockCreator.initRegistryServiceMockCreator(true, tenantConf);

    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());
    }
}
 
Example #22
Source File: APIConsumerImplTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubscribedAPIsWithApp() throws APIManagementException {
    APIConsumerImpl apiConsumer = new APIConsumerImplWrapper(apiMgtDAO);
    Set<SubscribedAPI> originalSubscribedAPIs = new HashSet<SubscribedAPI>();
    SubscribedAPI subscribedAPI = Mockito.mock(SubscribedAPI.class);
    originalSubscribedAPIs.add(subscribedAPI);
    Subscriber subscriber = new Subscriber("Subscriber");
    Tier tier = Mockito.mock(Tier.class);
    when(apiMgtDAO.getSubscribedAPIs(subscriber, "testApplication","testID")).
            thenReturn(originalSubscribedAPIs);
    when(subscribedAPI.getTier()).thenReturn(tier);
    when(tier.getName()).thenReturn("tier");
    assertNotNull(apiConsumer.getSubscribedAPIs(subscriber, "testApplication","testID"));
}
 
Example #23
Source File: APIUtilTierTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private String getTiersAsString(Set<Tier> tiers) {
    StringBuilder builder = new StringBuilder();

    for (Tier tier : tiers) {
        builder.append(tier.getName());
        builder.append("||");
    }

    return builder.toString();
}
 
Example #24
Source File: TierNameComparatorTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompareEquals() {
    TierNameComparator tierNameComparator = new TierNameComparator();
    Tier tier1 = new Tier("GOLD");
    tier1.setDisplayName("GOLD");
    Tier tier2 = new Tier("GOLD");
    tier2.setDisplayName("GOLD");
    int result = tierNameComparator.compare(tier1, tier2);
    Assert.assertEquals(0, result);
}
 
Example #25
Source File: TierNameComparatorTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompareNotEquals() {
    TierNameComparator tierNameComparator = new TierNameComparator();
    Tier tier1 = new Tier("GOLD");
    tier1.setDisplayName("GOLD");
    Tier tier2 = new Tier("SILVER");
    tier2.setDisplayName("SILVER");
    int result = tierNameComparator.compare(tier1, tier2);
    Assert.assertNotEquals(0, result);
}
 
Example #26
Source File: TierNameComparatorTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompareWhenDisplayNameNotSetEquals() {
    TierNameComparator tierNameComparator = new TierNameComparator();
    Tier tier1 = new Tier("GOLD");
    Tier tier2 = new Tier("GOLD");
    int result = tierNameComparator.compare(tier1, tier2);
    Assert.assertEquals(0, result);
}
 
Example #27
Source File: TierNameComparatorTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompareWhenDisplayNameNotSetNotEquals() {
    TierNameComparator tierNameComparator = new TierNameComparator();
    Tier tier1 = new Tier("GOLD");
    Tier tier2 = new Tier("SILVER");
    int result = tierNameComparator.compare(tier1, tier2);
    Assert.assertNotEquals(0, result);
}
 
Example #28
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTiersForTenant() throws APIManagementException {
    Mockito.when(privilegedCarbonContext.getTenantId()).thenReturn(-1234, -1, 1);
    Map<String, Tier> tierMap1 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap2 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap3 = new HashMap<String, Tier>();
    Tier tier1 = new Tier("tier1");
    Tier tier2 = new Tier("tier2");
    Tier tier3 = new Tier("tier3");
    tierMap1.put("Gold", tier1);
    tierMap2.put("Gold", tier1);
    tierMap2.put("Silver", tier2);
    tierMap3.put("Gold", tier1);
    tierMap3.put("Silver", tier2);
    tierMap3.put("Platinum", tier3);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getTiers()).thenReturn(tierMap1);
    PowerMockito.when(APIUtil.getTiers(Mockito.anyInt())).thenReturn(tierMap2);
    PowerMockito.when(APIUtil.isAdvanceThrottlingEnabled()).thenReturn(false, false, false, true);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(null, null, null, null);
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 1);
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 1); //verify next branch of if
    // condition
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 2);
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt())).thenReturn(tierMap3);
    Assert.assertEquals(abstractAPIManager.getTiers(SAMPLE_TENANT_DOMAIN_1).size(), 3);
}
 
Example #29
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTiersForTierType() throws APIManagementException {
    Map<String, Tier> tierMap1 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap2 = new HashMap<String, Tier>();
    Map<String, Tier> tierMap3 = new HashMap<String, Tier>();
    Tier tier1 = new Tier("tier1");
    Tier tier2 = new Tier("tier2");
    Tier tier3 = new Tier("tier3");
    tierMap1.put("Gold", tier1);
    tierMap2.put("Gold", tier1);
    tierMap2.put("Silver", tier2);
    tierMap3.put("Gold", tier1);
    tierMap3.put("Silver", tier2);
    tierMap3.put("Platinum", tier3);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getTiers(Mockito.anyInt(), Mockito.anyString())).thenReturn(tierMap1);
    PowerMockito.when(APIUtil.getTenantId(Mockito.anyString())).thenReturn(-1234);
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt()))
            .thenReturn(tierMap1, tierMap2, tierMap3);
    PowerMockito.when(APIUtil.isAdvanceThrottlingEnabled()).thenReturn(false, true, true, true, true);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(null, null, null, null);
    Assert.assertEquals(abstractAPIManager.getTiers(0, API_PROVIDER).size(), 1);
    Assert.assertEquals(abstractAPIManager.getTiers(0, API_PROVIDER).size(), 1); //verify next branch of if
    // condition
    Assert.assertEquals(abstractAPIManager.getTiers(1, API_PROVIDER).size(), 2);
    PowerMockito.when(APIUtil.getTiersFromPolicies(Mockito.anyString(), Mockito.anyInt())).thenReturn(tierMap3);
    Assert.assertEquals(abstractAPIManager.getTiers(2, API_PROVIDER).size(), 3);
    try {
        abstractAPIManager.getTiers(3, API_PROVIDER);
        Assert.fail("Exception not thrown undefined tier type");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("No such a tier type : "));
    }
}
 
Example #30
Source File: ThrottlingPolicyMappingUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a Tier object into TierDTO
 *
 * @param throttlingPolicy Tier object
 * @param tierLevel        tier level (api/application or resource)
 * @return TierDTO corresponds to Tier object
 */
public static ThrottlingPolicyDTO fromTierToDTO(Tier throttlingPolicy, String tierLevel) {

    ThrottlingPolicyDTO dto = new ThrottlingPolicyDTO();
    dto.setName(throttlingPolicy.getName());
    dto.setDescription(throttlingPolicy.getDescription());
    dto.setRequestCount(throttlingPolicy.getRequestCount());
    dto.setUnitTime(throttlingPolicy.getUnitTime());
    dto.setStopOnQuotaReach(throttlingPolicy.isStopOnQuotaReached());
    dto.setPolicyLevel(ThrottlingPolicyDTO.PolicyLevelEnum.valueOf(tierLevel.toUpperCase()));
    dto = setTierPermissions(dto, throttlingPolicy);
    if (throttlingPolicy.getTierPlan() != null) {
        dto.setTierPlan(ThrottlingPolicyDTO.TierPlanEnum.valueOf(throttlingPolicy.getTierPlan()));
    }
    if (throttlingPolicy.getTierAttributes() != null) {
        Map<String, String> additionalProperties = new HashMap<>();
        for (String key : throttlingPolicy.getTierAttributes().keySet()) {
            additionalProperties.put(key, throttlingPolicy.getTierAttributes().get(key).toString());
        }
        dto.setAttributes(additionalProperties);
    }
    MonetizationInfoDTO monetizationInfoDTO = new MonetizationInfoDTO();
    Map<String, String> monetizationAttributeMap = throttlingPolicy.getMonetizationAttributes();
    if (MapUtils.isNotEmpty(monetizationAttributeMap)) {
        monetizationInfoDTO.setBillingCycle(monetizationAttributeMap.get(APIConstants.Monetization.BILLING_CYCLE));
        monetizationInfoDTO.setCurrencyType(monetizationAttributeMap.get(APIConstants.Monetization.CURRENCY));
        if (StringUtils.isNotBlank(monetizationAttributeMap.get(APIConstants.Monetization.FIXED_PRICE))) {
            monetizationInfoDTO.setFixedPrice(monetizationAttributeMap.get(APIConstants.Monetization.FIXED_PRICE));
            monetizationInfoDTO.setBillingType(MonetizationInfoDTO.BillingTypeEnum.FIXEDPRICE);
        } else {
            monetizationInfoDTO.setPricePerRequest(monetizationAttributeMap.
                    get(APIConstants.Monetization.PRICE_PER_REQUEST));
            monetizationInfoDTO.setBillingType(MonetizationInfoDTO.BillingTypeEnum.DYNAMICRATE);
        }
    }
    dto.setMonetizationAttributes(monetizationInfoDTO);
    return dto;
}