Java Code Examples for org.wso2.carbon.apimgt.impl.utils.APIUtil#getTiers()

The following examples show how to use org.wso2.carbon.apimgt.impl.utils.APIUtil#getTiers() . 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: 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 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: 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 4
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 5
Source File: ThrottlingPoliciesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the throttling policies which belongs to the given policy level
 * @param policyLevel
 * @return list of throttling policies
 */
public List<Tier> getThrottlingPolicyList(String policyLevel) {
    try {
        List<Tier> tierList = new ArrayList<>();
        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();

        if (StringUtils.isBlank(policyLevel)) {
            RestApiUtil.handleBadRequest("policyLevel cannot be empty", log);
        }

        //retrieves the tier based on the given tier-level
        if (ThrottlingPolicyDTO.PolicyLevelEnum.SUBSCRIPTION.toString().equals(policyLevel)) {
            Map<String, Tier> apiTiersMap = APIUtil.getTiers(APIConstants.TIER_API_TYPE, tenantDomain);
            if (apiTiersMap != null) {
                tierList.addAll(apiTiersMap.values());
            }
        } else if (ThrottlingPolicyDTO.PolicyLevelEnum.API.toString().equals(policyLevel)) {
            Map<String, Tier> resourceTiersMap =
                    APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, tenantDomain);
            if (resourceTiersMap != null) {
                tierList.addAll(resourceTiersMap.values());
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(
                    "policyLevel should be one of " +
                            Arrays.toString(ThrottlingPolicyDTO.PolicyLevelEnum.values()), log);
        }
        return tierList;
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving tiers";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 6
Source File: ThrottlingPoliciesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the matched throttling policy to the given policy name
 *
 * @param policyName name of the throttling policy
 * @param policyLevel   throttling policy level (subscription or api)
 * @param ifNoneMatch If-None-Match header value
 * @return ThrottlingPolicyDTO matched to the given throttling policy name
 */
@Override
public Response getThrottlingPolicyByName(String policyName, String policyLevel, String ifNoneMatch,
        MessageContext messageContext) {
    try {
        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
        ThrottlingPolicyDTO.PolicyLevelEnum policyLevelEnum;
        Tier foundTier = null;

        if (StringUtils.isBlank(policyLevel)) {
            RestApiUtil.handleBadRequest("policyLevel cannot be empty", log);
        }

        //retrieves the tier based on the given tier-level
        if (ThrottlingPolicyDTO.PolicyLevelEnum.SUBSCRIPTION.toString().equals(policyLevel)) {
            foundTier = APIUtil.getTierFromCache(policyName, tenantDomain);
            policyLevelEnum = ThrottlingPolicyDTO.PolicyLevelEnum.SUBSCRIPTION;
        } else if (ThrottlingPolicyDTO.PolicyLevelEnum.API.toString().equals(policyLevel)) {
            Map<String, Tier> resourceTiersMap =
                    APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, tenantDomain);
            policyLevelEnum = ThrottlingPolicyDTO.PolicyLevelEnum.API;
            if (resourceTiersMap != null) {
                foundTier = RestApiUtil.findTier(resourceTiersMap.values(), policyName);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(
                    "policyLevel should be one of " + Arrays.toString(ThrottlingPolicyDTO.PolicyLevelEnum.values()),
                    log);
            return null;
        }

        //returns if the tier is found, otherwise send 404
        if (foundTier != null) {
            return Response.ok()
                    .entity(ThrottlingPolicyMappingUtil.fromTierToDTO(foundTier, policyLevelEnum.toString()))
                    .build();
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_THROTTLING_POLICY, policyName, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving throttling policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 7
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new application
 *
 * @param body        request body containing application details
 * @return 201 response if successful
 */
@Override
public Response applicationsPost(ApplicationDTO body, MessageContext messageContext){
    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();

        //validate the tier specified for the application
        String tierName = body.getThrottlingPolicy();
        if (tierName == null) {
            RestApiUtil.handleBadRequest("Throttling tier cannot be null", log);
        }

        Map<String, Tier> appTierMap = APIUtil.getTiers(APIConstants.TIER_APPLICATION_TYPE, tenantDomain);
        if (appTierMap == null || RestApiUtil.findTier(appTierMap.values(), tierName) == null) {
            RestApiUtil.handleBadRequest("Specified tier " + tierName + " is invalid", log);
        }

        Object applicationAttributesFromUser = body.getAttributes();
        Map<String, String> applicationAttributes =
                new ObjectMapper().convertValue(applicationAttributesFromUser, Map.class);
        if (applicationAttributes != null) {
            body.setAttributes(applicationAttributes);
        }

        //subscriber field of the body is not honored. It is taken from the context
        Application application = ApplicationMappingUtil.fromDTOtoApplication(body, username);

        int applicationId = apiConsumer.addApplication(application, username);

        //retrieves the created application and send as the response
        Application createdApplication = apiConsumer.getApplicationById(applicationId);
        ApplicationDTO createdApplicationDTO = ApplicationMappingUtil.fromApplicationtoDTO(createdApplication);

        //to be set as the Location header
        URI location = new URI(RestApiConstants.RESOURCE_PATH_APPLICATIONS + "/" +
                createdApplicationDTO.getApplicationId());
        return Response.created(location).entity(createdApplicationDTO).build();
    } catch (APIManagementException | URISyntaxException e) {
        if (RestApiUtil.isDueToResourceAlreadyExists(e)) {
            RestApiUtil.handleResourceAlreadyExistsError(
                    "An application already exists with name " + body.getName(), e,
                    log);
        } else if (RestApiUtil.isDueToApplicationNameWhiteSpaceValidation(e)) {
            RestApiUtil.handleBadRequest("Application name cannot contain leading or trailing white spaces", log);
        } else if (RestApiUtil.isDueToApplicationNameWithInvalidCharacters(e)) {
            RestApiUtil.handleBadRequest("Application name cannot contain invalid characters", log);
        } else {
            RestApiUtil.handleInternalServerError("Error while adding a new application for the user " + username,
                    e, log);
        }
    }
    return null;
}