Search in sources :

Example 21 with Tier

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

the class AbstractAPIManager method getAllTiers.

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;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) TreeSet(java.util.TreeSet) TierNameComparator(org.wso2.carbon.apimgt.impl.utils.TierNameComparator)

Example 22 with Tier

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

the class AbstractAPIManager method getTiers.

/**
 * 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 = APIUtil.getTiersFromPolicies(PolicyConstants.POLICY_LEVEL_SUB, tenantId);
    tiers.addAll(tierMap.values());
    return tiers;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) TreeSet(java.util.TreeSet) TierNameComparator(org.wso2.carbon.apimgt.impl.utils.TierNameComparator)

Example 23 with Tier

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

the class APIUtil method getTiersFromPolicies.

public static Map<String, Tier> getTiersFromPolicies(String policyLevel, int tenantId) throws APIManagementException {
    Map<String, Tier> tierMap = new TreeMap<String, Tier>();
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    Policy[] policies;
    if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
        policies = apiMgtDAO.getSubscriptionPolicies(tenantId);
    } else if (PolicyConstants.POLICY_LEVEL_API.equalsIgnoreCase(policyLevel)) {
        policies = apiMgtDAO.getAPIPolicies(tenantId);
    } else if (PolicyConstants.POLICY_LEVEL_APP.equalsIgnoreCase(policyLevel)) {
        policies = apiMgtDAO.getApplicationPolicies(tenantId);
    } else {
        throw new APIManagementException("No such a policy type : " + policyLevel);
    }
    for (Policy policy : policies) {
        if (!APIConstants.UNLIMITED_TIER.equalsIgnoreCase(policy.getPolicyName())) {
            Tier tier = new Tier(policy.getPolicyName());
            tier.setDescription(policy.getDescription());
            tier.setDisplayName(policy.getDisplayName());
            Limit limit = policy.getDefaultQuotaPolicy().getLimit();
            tier.setTimeUnit(limit.getTimeUnit());
            tier.setUnitTime(limit.getUnitTime());
            tier.setQuotaPolicyType(policy.getDefaultQuotaPolicy().getType());
            // If the policy is a subscription policy
            if (policy instanceof SubscriptionPolicy) {
                SubscriptionPolicy subscriptionPolicy = (SubscriptionPolicy) policy;
                tier.setRateLimitCount(subscriptionPolicy.getRateLimitCount());
                tier.setRateLimitTimeUnit(subscriptionPolicy.getRateLimitTimeUnit());
                setBillingPlanAndCustomAttributesToTier(subscriptionPolicy, tier);
                if (StringUtils.equals(subscriptionPolicy.getBillingPlan(), APIConstants.COMMERCIAL_TIER_PLAN)) {
                    tier.setMonetizationAttributes(subscriptionPolicy.getMonetizationPlanProperties());
                }
            }
            if (limit instanceof RequestCountLimit) {
                RequestCountLimit countLimit = (RequestCountLimit) limit;
                tier.setRequestsPerMin(countLimit.getRequestCount());
                tier.setRequestCount(countLimit.getRequestCount());
            } else if (limit instanceof BandwidthLimit) {
                BandwidthLimit bandwidthLimit = (BandwidthLimit) limit;
                tier.setRequestsPerMin(bandwidthLimit.getDataAmount());
                tier.setRequestCount(bandwidthLimit.getDataAmount());
                tier.setBandwidthDataUnit(bandwidthLimit.getDataUnit());
            } else {
                EventCountLimit eventCountLimit = (EventCountLimit) limit;
                tier.setRequestCount(eventCountLimit.getEventCount());
                tier.setRequestsPerMin(eventCountLimit.getEventCount());
            }
            if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
                tier.setTierPlan(((SubscriptionPolicy) policy).getBillingPlan());
            }
            tierMap.put(policy.getPolicyName(), tier);
        } else {
            if (APIUtil.isEnabledUnlimitedTier()) {
                Tier tier = new Tier(policy.getPolicyName());
                tier.setDescription(policy.getDescription());
                tier.setDisplayName(policy.getDisplayName());
                tier.setRequestsPerMin(Integer.MAX_VALUE);
                tier.setRequestCount(Integer.MAX_VALUE);
                if (isUnlimitedTierPaid(getTenantDomainFromTenantId(tenantId))) {
                    tier.setTierPlan(APIConstants.COMMERCIAL_TIER_PLAN);
                } else {
                    tier.setTierPlan(APIConstants.BILLING_PLAN_FREE);
                }
                tierMap.put(policy.getPolicyName(), tier);
            }
        }
    }
    if (PolicyConstants.POLICY_LEVEL_SUB.equalsIgnoreCase(policyLevel)) {
        tierMap.remove(APIConstants.UNAUTHENTICATED_TIER);
    }
    return tierMap;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.api.model.policy.ApplicationPolicy) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy) QuotaPolicy(org.wso2.carbon.apimgt.api.model.policy.QuotaPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.api.model.policy.Policy) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) Tier(org.wso2.carbon.apimgt.api.model.Tier) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) TreeMap(java.util.TreeMap) EventCountLimit(org.wso2.carbon.apimgt.api.model.policy.EventCountLimit) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) Limit(org.wso2.carbon.apimgt.api.model.policy.Limit) EventCountLimit(org.wso2.carbon.apimgt.api.model.policy.EventCountLimit) BandwidthLimit(org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit) RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) BandwidthLimit(org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit)

Example 24 with Tier

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

the class ApplicationRegistrationApprovalWorkflowExecutor method execute.

/**
 * Execute the Application Creation workflow approval process.
 *
 * @param workflowDTO
 */
@Override
public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Executing Application registration Workflow..");
    }
    ApplicationRegistrationWorkflowDTO appRegDTO = (ApplicationRegistrationWorkflowDTO) workflowDTO;
    Application application = appRegDTO.getApplication();
    String message = "Approve request to create " + appRegDTO.getKeyType() + " keys for " + application.getName() + " from application creator - " + appRegDTO.getUserName() + " with throttling tier - " + application.getTier();
    workflowDTO.setWorkflowDescription(message);
    workflowDTO.setProperties("keyType", appRegDTO.getKeyType());
    workflowDTO.setProperties("applicationName", application.getName());
    workflowDTO.setProperties("userName", appRegDTO.getUserName());
    workflowDTO.setProperties("applicationTier", application.getTier());
    super.execute(workflowDTO);
    return new GeneralWorkflowResponse();
}
Also used : ApplicationRegistrationWorkflowDTO(org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 25 with Tier

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

the class RegistryPersistenceUtil method getAPI.

/**
 * This Method is different from getAPI method, as this one returns
 * URLTemplates without aggregating duplicates. This is to be used for building synapse config.
 *
 * @param artifact
 * @param registry
 * @return API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 */
public static API getAPI(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion, artifact.getId());
        api = new API(apiIdentifier);
        // set uuid
        api.setUuid(artifact.getId());
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        // String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR
        // + RegistryPersistenceUtil.replaceEmailDomain(api.getId().getProviderName())
        // + RegistryConstants.PATH_SEPARATOR + api.getId().getName() + RegistryConstants.PATH_SEPARATOR
        // + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_KEY;
        Resource apiResource = registry.get(artifactPath);
        api = setResourceProperties(api, apiResource, artifactPath);
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set url
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
        api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
        api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
        api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
        api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
        if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD).equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
            api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
        } else {
            // If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
            api.setEndpointUTPassword(apiResource.getProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY));
        }
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
        api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
        api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
        api.setSandboxMaxTps(artifact.getAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS));
        api.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
        api.setAsyncTransportProtocols(artifact.getAttribute(APIConstants.ASYNC_API_TRANSPORT_PROTOCOLS));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            String strCacheTimeout = artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT);
            if (strCacheTimeout != null && !strCacheTimeout.isEmpty()) {
                cacheTimeout = Integer.parseInt(strCacheTimeout);
            }
        } catch (NumberFormatException e) {
            if (log.isWarnEnabled()) {
                log.warn("Error while retrieving cache timeout from the registry for " + apiIdentifier);
            }
        // ignore the exception and use default cache timeout value
        }
        api.setCacheTimeout(cacheTimeout);
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiExternalProductionEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT));
        api.setApiExternalSandboxEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT));
        api.setAdvertiseOnlyAPIVendor(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY_API_VENDOR));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Set<Tier> availableTiers = new HashSet<Tier>();
        if (tiers != null) {
            String[] tiersArray = tiers.split("\\|\\|");
            for (String tierName : tiersArray) {
                availableTiers.add(new Tier(tierName));
            }
        }
        api.setAvailableTiers(availableTiers);
        // This contains the resolved context
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        // We set the context template here
        api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
        api.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
        api.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
        api.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        api.setTags(tags);
        api.setLastUpdated(apiResource.getLastModified());
        api.setCreatedTime(String.valueOf(apiResource.getCreatedTime().getTime()));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setEnvironments(getEnvironments(artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS)));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        api.setWebsubSubscriptionConfiguration(getWebsubSubscriptionConfigurationFromArtifact(artifact));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        // set data and status related to monetization
        api.setMonetizationEnabled(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
        String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
        api.setWsUriMapping(getWsUriMappingFromArtifact(artifact));
        api.setAudience(artifact.getAttribute(APIConstants.API_OVERVIEW_AUDIENCE));
        api.setVersionTimestamp(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP));
        // set selected clusters which API needs to be deployed
        String deployments = artifact.getAttribute(APIConstants.API_OVERVIEW_DEPLOYMENTS);
        if (StringUtils.isNotBlank(monetizationInfo)) {
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
            api.setMonetizationProperties(jsonObj);
        }
        api.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
        // get endpoint config string from artifact, parse it as a json and set the environment list configured with
        // non empty URLs to API object
        String keyManagers = artifact.getAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS);
        if (StringUtils.isNotEmpty(keyManagers)) {
            api.setKeyManagers(new Gson().fromJson(keyManagers, List.class));
        } else {
            api.setKeyManagers(Arrays.asList(APIConstants.API_LEVEL_ALL_KEY_MANAGERS));
        }
        try {
            api.setEnvironmentList(extractEnvironmentListForAPI(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
        } catch (ParseException e) {
            String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        } catch (ClassCastException e) {
            String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        }
    } catch (GovernanceException e) {
        String msg = "Failed to get API for artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of API Provider";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Failed to get parse monetization information.";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) Resource(org.wso2.carbon.registry.core.Resource) Gson(com.google.gson.Gson) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) List(java.util.List) ArrayList(java.util.ArrayList) Tag(org.wso2.carbon.registry.core.Tag) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet)

Aggregations

Tier (org.wso2.carbon.apimgt.api.model.Tier)108 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 ArrayList (java.util.ArrayList)42 Test (org.junit.Test)40 HashSet (java.util.HashSet)39 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)37 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)37 API (org.wso2.carbon.apimgt.api.model.API)33 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)32 HashMap (java.util.HashMap)28 Application (org.wso2.carbon.apimgt.api.model.Application)26 Test (org.testng.annotations.Test)22 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)22 Application (org.wso2.carbon.apimgt.core.models.Application)22 LinkedHashSet (java.util.LinkedHashSet)21 JSONObject (org.json.simple.JSONObject)20 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)20 ApplicationDAO (org.wso2.carbon.apimgt.core.dao.ApplicationDAO)20 Policy (org.wso2.carbon.apimgt.core.models.policy.Policy)20 BeforeTest (org.testng.annotations.BeforeTest)19