Search in sources :

Example 71 with Tier

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

the class APIThrottleHandler method doRoleBasedAccessThrottling.

private boolean doRoleBasedAccessThrottling(MessageContext synCtx, ConfigurationContext cc) {
    boolean canAccess = true;
    ThrottleDataHolder dataHolder = (ThrottleDataHolder) cc.getPropertyNonReplicable(ThrottleConstants.THROTTLE_INFO_KEY);
    if (throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY) == null) {
        // skip role base throttling
        return true;
    }
    ConcurrentAccessController cac = null;
    if (isClusteringEnable) {
        // for clustered  env.,gets it from axis configuration context
        cac = (ConcurrentAccessController) cc.getProperty(key);
    }
    if (!synCtx.isResponse()) {
        // gets the remote caller role name
        AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
        String accessToken;
        String consumerKey;
        String authorizedUser;
        String roleID;
        String applicationId;
        String applicationTier;
        if (authContext != null) {
            // Although the method says getApiKey, what is actually returned is the Bearer header (accessToken)
            accessToken = authContext.getApiKey();
            consumerKey = authContext.getConsumerKey();
            authorizedUser = authContext.getUsername();
            roleID = authContext.getTier();
            applicationTier = authContext.getApplicationTier();
            applicationId = authContext.getApplicationId();
            if (accessToken == null || roleID == null) {
                log.warn("No consumer key or role information found on the request - " + "Throttling not applied");
                return true;
            }
        } else {
            log.warn("No authentication context information found on the request - " + "Throttling not applied");
            return true;
        }
        // Domain name based throttling
        // check whether a configuration has been defined for this role name or not
        // loads the ThrottleContext
        ThrottleContext resourceContext = throttle.getThrottleContext(RESOURCE_THROTTLE_KEY);
        if (resourceContext == null) {
            log.warn("Unable to load throttle context");
            return true;
        }
        // Loads the ThrottleConfiguration
        ThrottleConfiguration config = resourceContext.getThrottleConfiguration();
        if (config != null) {
            String applicationRoleId = null;
            // If an application level tier has been specified and it is not 'Unlimited'
            if (applicationTier != null && !APIConstants.UNLIMITED_TIER.equals(applicationTier)) {
                // Get the configuration role of the application
                // applicationRoleId = config.getConfigurationKeyOfCaller(applicationTier);
                applicationRoleId = applicationTier;
            }
            AccessInformation info = null;
            // If application level throttling is applied
            if (applicationRoleId != null) {
                ThrottleContext applicationThrottleContext = getApplicationThrottleContext(synCtx, dataHolder, applicationId);
                if (isClusteringEnable) {
                    applicationThrottleContext.setConfigurationContext(cc);
                    applicationThrottleContext.setThrottleId(id);
                }
                // First throttle by application
                try {
                    info = applicationRoleBasedAccessController.canAccess(applicationThrottleContext, applicationId, applicationRoleId);
                    if (log.isDebugEnabled()) {
                        log.debug("Throttle by Application " + applicationId);
                        log.debug("Allowed = " + (info != null ? info.isAccessAllowed() : "false"));
                    }
                } catch (ThrottleException e) {
                    log.warn("Exception occurred while performing role " + "based throttling", e);
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.APPLICATION_LIMIT_EXCEEDED);
                    return false;
                }
                // check for the permission for access
                if (info != null && !info.isAccessAllowed()) {
                    log.info("Exceeded the allocated quota in Application level.");
                    // if the access has denied by rate based throttling
                    if (cac != null) {
                        cac.incrementAndGet();
                        // set back if this is a clustered env
                        if (isClusteringEnable) {
                            cc.setProperty(key, cac);
                            resourceContext.setConfigurationContext(cc);
                            // replicate the current state of ConcurrentAccessController
                            try {
                                Replicator.replicate(cc, new String[] { key });
                            } catch (ClusteringFault clusteringFault) {
                                log.error("Error during replicating states", clusteringFault);
                            }
                        }
                    }
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.APPLICATION_LIMIT_EXCEEDED);
                    return false;
                }
            }
            // ---------------End of application level throttling------------
            // ==============================Start of Resource level throttling======================================
            // get throttling information for given request with resource path and http verb
            // VerbInfoDTO verbInfoDTO = null;
            // verbInfoDTO = validator.getVerbInfoDTOFromAPIData(apiContext, apiVersion, requestPath, httpMethod);
            VerbInfoDTO verbInfoDTO = (VerbInfoDTO) synCtx.getProperty(APIConstants.VERB_INFO_DTO);
            String resourceLevelRoleId = null;
            // no data related to verb information data
            if (verbInfoDTO == null) {
                log.warn("Error while getting throttling information for resource and http verb");
                return false;
            } else {
                // Not only we can proceed
                String resourceAndHTTPVerbThrottlingTier = verbInfoDTO.getThrottling();
                // If there no any tier then we need to set it as unlimited
                if (resourceAndHTTPVerbThrottlingTier == null) {
                    log.warn("Unable to find throttling information for resource and http verb. Throttling will " + "not apply");
                } else {
                    resourceLevelRoleId = resourceAndHTTPVerbThrottlingTier;
                }
                // adding consumerKey and authz_user combination instead of access token to resourceAndHTTPVerbKey
                // This avoids sending more than the permitted number of requests in a unit time by
                // regenerating the access token
                String resourceAndHTTPVerbKey = verbInfoDTO.getRequestKey() + '-' + consumerKey + ':' + authorizedUser;
                // if request not null then only we proceed
                if (resourceLevelRoleId != null) {
                    try {
                        // if application level throttling has passed
                        if (!APIConstants.UNLIMITED_TIER.equals(resourceLevelRoleId) && (info == null || info.isAccessAllowed())) {
                            // If this is a clustered env.
                            if (isClusteringEnable) {
                                resourceContext.setConfigurationContext(cc);
                                resourceContext.setThrottleId(id + "resource");
                            }
                            info = roleBasedAccessController.canAccess(resourceContext, resourceAndHTTPVerbKey, resourceAndHTTPVerbThrottlingTier);
                        }
                    } catch (ThrottleException e) {
                        log.warn("Exception occurred while performing resource" + "based throttling", e);
                        synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.RESOURCE_LIMIT_EXCEEDED);
                        return false;
                    }
                    // check for the permission for access
                    if (info != null && !info.isAccessAllowed()) {
                        log.info("Exceeded the allocated quota in Resource level.");
                        // if the access has denied by rate based throttling
                        if (cac != null) {
                            cac.incrementAndGet();
                            // set back if this is a clustered env
                            if (isClusteringEnable) {
                                cc.setProperty(key, cac);
                                // replicate the current state of ConcurrentAccessController
                                try {
                                    Replicator.replicate(cc, new String[] { key });
                                } catch (ClusteringFault clusteringFault) {
                                    log.error("Error during replicating states", clusteringFault);
                                }
                            }
                        }
                        if (isContinueOnThrottleReached(resourceAndHTTPVerbThrottlingTier)) {
                            // limit has reached.
                            if (synCtx.getProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY) == null) {
                                synCtx.setProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY, Boolean.TRUE);
                            }
                        } else {
                            synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.RESOURCE_LIMIT_EXCEEDED);
                            return false;
                        }
                    }
                } else {
                    log.warn("Unable to find the throttle policy for role.");
                }
            }
            // ==============================End of Resource level throttling=======================================
            // ---------------Start of API level throttling------------------
            // Domain name based throttling
            // check whether a configuration has been defined for this role name or not
            // loads the ThrottleContext
            ThrottleContext context = throttle.getThrottleContext(ThrottleConstants.ROLE_BASED_THROTTLE_KEY);
            String apiKey;
            if (context == null) {
                log.warn("Unable to load throttle context");
                return true;
            }
            // If this is a clustered env.
            // check for configuration role of the caller
            config = context.getThrottleConfiguration();
            String consumerRoleID = config.getConfigurationKeyOfCaller(roleID);
            if (isClusteringEnable) {
                context.setConfigurationContext(cc);
                context.setThrottleId(id);
            }
            try {
                String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
                String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
                apiContext = apiContext != null ? apiContext : "";
                apiVersion = apiVersion != null ? apiVersion : "";
                // adding consumerKey and authz_user combination instead of access token to apiKey
                // This avoids sending more than the permitted number of requests in a unit time by
                // regenerating the access token
                apiKey = apiContext + ':' + apiVersion + ':' + consumerKey + ':' + authorizedUser;
                // if application level throttling has passed
                if (!APIConstants.UNLIMITED_TIER.equals(roleID) && (info == null || info.isAccessAllowed())) {
                    // Throttle by access token
                    info = roleBasedAccessController.canAccess(context, apiKey, consumerRoleID);
                }
            } catch (ThrottleException e) {
                log.warn("Exception occurred while performing role " + "based throttling", e);
                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.API_LIMIT_EXCEEDED);
                return false;
            }
            // check for the permission for access
            if (info != null && !info.isAccessAllowed()) {
                log.info("Exceeded the allocated quota in API level.");
                // if the access has denied by rate based throttling
                if (cac != null) {
                    cac.incrementAndGet();
                    // set back if this is a clustered env
                    if (isClusteringEnable) {
                        cc.setProperty(key, cac);
                        // replicate the current state of ConcurrentAccessController
                        try {
                            Replicator.replicate(cc, new String[] { key });
                        } catch (ClusteringFault clusteringFault) {
                            log.error("Error during replicating states", clusteringFault);
                        }
                    }
                }
                if (isContinueOnThrottleReached(consumerRoleID)) {
                    // limit has reached.
                    if (synCtx.getProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY) == null) {
                        synCtx.setProperty(APIConstants.API_USAGE_THROTTLE_OUT_PROPERTY_KEY, Boolean.TRUE);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Request throttled at API level for throttle key" + apiKey + ". But role " + consumerRoleID + "allows to continue to serve requests");
                    }
                } else {
                    synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.API_LIMIT_EXCEEDED);
                    return false;
                }
            }
        }
    }
    // ---------------End of API level throttling------------------
    // ---------------Start of Hard throttling------------------
    ThrottleContext hardThrottleContext = throttle.getThrottleContext(APIThrottleConstants.HARD_THROTTLING_CONFIGURATION);
    try {
        String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
        String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
        apiContext = apiContext != null ? apiContext : "";
        apiVersion = apiVersion != null ? apiVersion : "";
        AuthenticationContext authContext = APISecurityUtils.getAuthenticationContext(synCtx);
        if (hardThrottleContext != null && authContext.getKeyType() != null) {
            String throttleKey = apiContext + ':' + apiVersion + ':' + authContext.getKeyType();
            AccessInformation info = null;
            if (isClusteringEnable) {
                hardThrottleContext.setConfigurationContext(cc);
            }
            if (APIConstants.API_KEY_TYPE_PRODUCTION.equals(authContext.getKeyType())) {
                hardThrottleContext.setThrottleId(id + APIThrottleConstants.PRODUCTION_HARD_LIMIT);
                info = roleBasedAccessController.canAccess(hardThrottleContext, throttleKey, APIThrottleConstants.PRODUCTION_HARD_LIMIT);
            } else if (APIConstants.API_KEY_TYPE_SANDBOX.equals(authContext.getKeyType())) {
                hardThrottleContext.setThrottleId(id + APIThrottleConstants.SANDBOX_HARD_LIMIT);
                info = roleBasedAccessController.canAccess(hardThrottleContext, throttleKey, APIThrottleConstants.SANDBOX_HARD_LIMIT);
            }
            if (log.isDebugEnabled()) {
                log.debug("Throttle by hard limit " + throttleKey);
                log.debug("Allowed = " + (info != null ? info.isAccessAllowed() : "false"));
            }
            if (info != null && !info.isAccessAllowed()) {
                synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.HARD_LIMIT_EXCEEDED);
                log.info("Hard Throttling limit exceeded.");
                return false;
            }
        }
    } catch (ThrottleException e) {
        log.warn("Exception occurred while performing role based throttling", e);
        synCtx.setProperty(APIThrottleConstants.THROTTLED_OUT_REASON, APIThrottleConstants.HARD_LIMIT_EXCEEDED);
        return false;
    }
    return canAccess;
}
Also used : ThrottleContext(org.apache.synapse.commons.throttle.core.ThrottleContext) ThrottleDataHolder(org.apache.synapse.commons.throttle.core.ThrottleDataHolder) AuthenticationContext(org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationContext) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) AccessInformation(org.apache.synapse.commons.throttle.core.AccessInformation) ThrottleException(org.apache.synapse.commons.throttle.core.ThrottleException) ThrottleConfiguration(org.apache.synapse.commons.throttle.core.ThrottleConfiguration) ConcurrentAccessController(org.apache.synapse.commons.throttle.core.ConcurrentAccessController) ClusteringFault(org.apache.axis2.clustering.ClusteringFault)

Example 72 with Tier

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

the class APIMappingUtil method fromDTOtoAPIProduct.

public static APIProduct fromDTOtoAPIProduct(APIProductDTO dto, String provider) throws APIManagementException {
    APIProduct product = new APIProduct();
    APIProductIdentifier id = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), dto.getName(), // todo: replace this with dto.getVersion
    APIConstants.API_PRODUCT_VERSION);
    product.setID(id);
    product.setUuid(dto.getId());
    product.setDescription(dto.getDescription());
    String context = dto.getContext();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    context = context.startsWith("/") ? context : ("/" + context);
    String providerDomain = MultitenantUtils.getTenantDomain(provider);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(providerDomain) && dto.getId() == null) {
        // Create tenant aware context for API
        context = "/t/" + providerDomain + context;
    }
    product.setType(APIConstants.API_PRODUCT_IDENTIFIER_TYPE.replaceAll("\\s", ""));
    product.setContext(context);
    context = checkAndSetVersionParam(context);
    product.setContextTemplate(context);
    List<String> apiProductTags = dto.getTags();
    Set<String> tagsToReturn = new HashSet<>(apiProductTags);
    product.addTags(tagsToReturn);
    if (dto.isEnableSchemaValidation() != null) {
        product.setEnableSchemaValidation(dto.isEnableSchemaValidation());
    }
    product.setEnableStore(true);
    if (dto.isResponseCachingEnabled() != null && dto.isResponseCachingEnabled()) {
        product.setResponseCache(APIConstants.ENABLED);
    } else {
        product.setResponseCache(APIConstants.DISABLED);
    }
    if (dto.getCacheTimeout() != null) {
        product.setCacheTimeout(dto.getCacheTimeout());
    } else {
        product.setCacheTimeout(APIConstants.API_RESPONSE_CACHE_TIMEOUT);
    }
    if (dto.getBusinessInformation() != null) {
        product.setBusinessOwner(dto.getBusinessInformation().getBusinessOwner());
        product.setBusinessOwnerEmail(dto.getBusinessInformation().getBusinessOwnerEmail());
        product.setTechnicalOwner(dto.getBusinessInformation().getTechnicalOwner());
        product.setTechnicalOwnerEmail(dto.getBusinessInformation().getTechnicalOwnerEmail());
    }
    Set<Tier> apiTiers = new HashSet<>();
    List<String> tiersFromDTO = dto.getPolicies();
    if (dto.getVisibility() != null) {
        product.setVisibility(mapVisibilityFromDTOtoAPIProduct(dto.getVisibility()));
    }
    if (dto.getVisibleRoles() != null) {
        String visibleRoles = StringUtils.join(dto.getVisibleRoles(), ',');
        product.setVisibleRoles(visibleRoles);
    }
    if (dto.getVisibleTenants() != null) {
        String visibleTenants = StringUtils.join(dto.getVisibleTenants(), ',');
        product.setVisibleTenants(visibleTenants);
    }
    List<String> accessControlRoles = dto.getAccessControlRoles();
    if (accessControlRoles == null || accessControlRoles.isEmpty()) {
        product.setAccessControl(APIConstants.NO_ACCESS_CONTROL);
        product.setAccessControlRoles("null");
    } else {
        product.setAccessControlRoles(StringUtils.join(accessControlRoles, ',').toLowerCase());
        product.setAccessControl(APIConstants.API_RESTRICTED_VISIBILITY);
    }
    for (String tier : tiersFromDTO) {
        apiTiers.add(new Tier(tier));
    }
    product.setAvailableTiers(apiTiers);
    product.setProductLevelPolicy(dto.getApiThrottlingPolicy());
    product.setGatewayVendor(dto.getGatewayVendor());
    if (dto.getSubscriptionAvailability() != null) {
        product.setSubscriptionAvailability(mapSubscriptionAvailabilityFromDTOtoAPIProduct(dto.getSubscriptionAvailability()));
    }
    List<APIInfoAdditionalPropertiesDTO> additionalProperties = dto.getAdditionalProperties();
    if (additionalProperties != null) {
        for (APIInfoAdditionalPropertiesDTO property : additionalProperties) {
            if (property.isDisplay()) {
                product.addProperty(property.getName() + APIConstants.API_RELATED_CUSTOM_PROPERTIES_SURFIX, property.getValue());
            } else {
                product.addProperty(property.getName(), property.getValue());
            }
        }
    }
    if (dto.getSubscriptionAvailableTenants() != null) {
        product.setSubscriptionAvailableTenants(StringUtils.join(dto.getSubscriptionAvailableTenants(), ","));
    }
    String transports = StringUtils.join(dto.getTransport(), ',');
    product.setTransports(transports);
    List<APIProductResource> productResources = new ArrayList<APIProductResource>();
    Set<String> verbResourceCombo = new HashSet<>();
    for (ProductAPIDTO res : dto.getApis()) {
        List<APIOperationsDTO> productAPIOperationsDTO = res.getOperations();
        for (APIOperationsDTO resourceItem : productAPIOperationsDTO) {
            if (!verbResourceCombo.add(resourceItem.getVerb() + resourceItem.getTarget())) {
                throw new APIManagementException("API Product resource: " + resourceItem.getTarget() + ", with verb: " + resourceItem.getVerb() + " , is duplicated for id " + id, ExceptionCodes.from(ExceptionCodes.API_PRODUCT_DUPLICATE_RESOURCE, resourceItem.getTarget(), resourceItem.getVerb()));
            }
            URITemplate template = new URITemplate();
            template.setHTTPVerb(resourceItem.getVerb());
            template.setHttpVerbs(resourceItem.getVerb());
            template.setResourceURI(resourceItem.getTarget());
            template.setUriTemplate(resourceItem.getTarget());
            template.setOperationPolicies(OperationPolicyMappingUtil.fromDTOToAPIOperationPoliciesList(resourceItem.getOperationPolicies()));
            APIProductResource resource = new APIProductResource();
            resource.setApiId(res.getApiId());
            resource.setUriTemplate(template);
            productResources.add(resource);
        }
    }
    Set<Scope> scopes = getScopes(dto);
    product.setScopes(scopes);
    APICorsConfigurationDTO apiCorsConfigurationDTO = dto.getCorsConfiguration();
    CORSConfiguration corsConfiguration;
    if (apiCorsConfigurationDTO != null) {
        corsConfiguration = new CORSConfiguration(apiCorsConfigurationDTO.isCorsConfigurationEnabled(), apiCorsConfigurationDTO.getAccessControlAllowOrigins(), apiCorsConfigurationDTO.isAccessControlAllowCredentials(), apiCorsConfigurationDTO.getAccessControlAllowHeaders(), apiCorsConfigurationDTO.getAccessControlAllowMethods());
    } else {
        corsConfiguration = APIUtil.getDefaultCorsConfiguration();
    }
    product.setCorsConfiguration(corsConfiguration);
    product.setProductResources(productResources);
    product.setApiSecurity(getSecurityScheme(dto.getSecurityScheme()));
    product.setAuthorizationHeader(dto.getAuthorizationHeader());
    // attach api categories to API model
    setAPICategoriesToModel(dto, product, provider);
    return product;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ArrayList(java.util.ArrayList) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APICorsConfigurationDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APICorsConfigurationDTO) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) CORSConfiguration(org.wso2.carbon.apimgt.api.model.CORSConfiguration) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIOperationsDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIOperationsDTO) APIInfoAdditionalPropertiesDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIInfoAdditionalPropertiesDTO) ProductAPIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ProductAPIDTO) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 73 with Tier

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

the class ApisApiServiceImpl method addAPIClientCertificate.

@Override
public Response addAPIClientCertificate(String apiId, InputStream certificateInputStream, Attachment certificateDetail, String alias, String tier, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        ContentDisposition contentDisposition = certificateDetail.getContentDisposition();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
        if (StringUtils.isEmpty(alias) || StringUtils.isEmpty(apiId)) {
            RestApiUtil.handleBadRequest("The alias and/ or apiId should not be empty", log);
        }
        if (StringUtils.isBlank(fileName)) {
            RestApiUtil.handleBadRequest("Certificate addition failed. Proper Certificate file should be provided", log);
        }
        // validate if api exists
        validateAPIExistence(apiId);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        api.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(api.getStatus());
        String userName = RestApiCommonUtil.getLoggedInUsername();
        String base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
        int responseCode = apiProvider.addClientCertificate(userName, api.getId(), base64EncodedCert, alias, tier, organization);
        if (log.isDebugEnabled()) {
            log.debug(String.format("Add certificate operation response code : %d", responseCode));
        }
        if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
            // Handle api product case.
            if (API_PRODUCT_TYPE.equals(api.getType())) {
                APIIdentifier apiIdentifier = api.getId();
                APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
                APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
                apiProduct.setOrganization(organization);
                apiProvider.updateAPIProduct(apiProduct);
            } else {
                apiProvider.updateAPI(api);
            }
            ClientCertMetadataDTO certificateDTO = new ClientCertMetadataDTO();
            certificateDTO.setAlias(alias);
            certificateDTO.setApiId(apiId);
            certificateDTO.setTier(tier);
            URI createdCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
            return Response.created(createdCertUri).entity(certificateDTO).build();
        } else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Internal server error while adding the client certificate to " + "API " + apiId, log);
        } else if (ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode() == responseCode) {
            RestApiUtil.handleResourceAlreadyExistsError("The alias '" + alias + "' already exists in the trust store.", log);
        } else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
            RestApiUtil.handleBadRequest("Error while adding the certificate to the API " + apiId + ". " + "Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("APIManagement exception while adding the certificate to the API " + apiId + " due to an internal " + "server error", e, log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("IOException while generating the encoded certificate for the API " + apiId, e, log);
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", e, log);
    } catch (FaultGatewaysException e) {
        RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
    }
    return null;
}
Also used : FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 74 with Tier

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

the class ThrottlingPoliciesApiServiceImpl method getAllThrottlingPolicies.

/**
 * 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, false);
    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();
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ThrottlingPolicyListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ThrottlingPolicyListDTO)

Example 75 with Tier

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

the class ApplicationsApiServiceImpl method preProcessAndAddApplication.

/**
 * Preprocess and add the application
 *
 * @param username       Username
 * @param applicationDto Application DTO
 * @param organization   Identifier of an organization
 * @return Created application
 */
private Application preProcessAndAddApplication(String username, ApplicationDTO applicationDto, String organization) throws APIManagementException {
    APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
    // validate the tier specified for the application
    String tierName = applicationDto.getThrottlingPolicy();
    if (tierName == null) {
        RestApiUtil.handleBadRequest("Throttling tier cannot be null", log);
    }
    Object applicationAttributesFromUser = applicationDto.getAttributes();
    Map<String, String> applicationAttributes = new ObjectMapper().convertValue(applicationAttributesFromUser, Map.class);
    if (applicationAttributes != null) {
        applicationDto.setAttributes(applicationAttributes);
    }
    // we do not honor tokenType sent in the body and
    // all the applications created will of 'JWT' token type
    applicationDto.setTokenType(ApplicationDTO.TokenTypeEnum.JWT);
    // subscriber field of the body is not honored. It is taken from the context
    Application application = ApplicationMappingUtil.fromDTOtoApplication(applicationDto, username);
    int applicationId = apiConsumer.addApplication(application, username, organization);
    // retrieves the created application and send as the response
    return apiConsumer.getApplicationById(applicationId);
}
Also used : JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

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