Search in sources :

Example 46 with ApiTypeWrapper

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

the class APIConsumerImpl method checkSubscriptionAllowed.

/**
 * Check if the specified subscription is allowed for the logged in user
 *
 * @param apiTypeWrapper Api Type wrapper that contains either an API or API Product
 * @throws APIManagementException if the subscription allow check was failed. If the user is not allowed to add the
 *                                subscription, this will throw an instance of APIMgtAuthorizationFailedException with the reason as the message
 */
private void checkSubscriptionAllowed(ApiTypeWrapper apiTypeWrapper) throws APIManagementException {
    Set<Tier> tiers;
    String subscriptionAvailability;
    String subscriptionAllowedTenants;
    if (apiTypeWrapper.isAPIProduct()) {
        APIProduct product = apiTypeWrapper.getApiProduct();
        tiers = product.getAvailableTiers();
        subscriptionAvailability = product.getSubscriptionAvailability();
        subscriptionAllowedTenants = product.getSubscriptionAvailableTenants();
    } else {
        API api = apiTypeWrapper.getApi();
        String apiSecurity = api.getApiSecurity();
        if (apiSecurity != null && !apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) && !apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
            String msg = "Subscription is not allowed for API " + apiTypeWrapper.toString() + ". To access the API, " + "please use the client certificate";
            throw new APIMgtAuthorizationFailedException(msg);
        }
        tiers = api.getAvailableTiers();
        subscriptionAvailability = api.getSubscriptionAvailability();
        subscriptionAllowedTenants = api.getSubscriptionAvailableTenants();
    }
    String apiOrganization = apiTypeWrapper.getOrganization();
    // Tenant based validation for subscription
    boolean subscriptionAllowed = false;
    if (!organization.equals(apiOrganization)) {
        if (APIConstants.SUBSCRIPTION_TO_ALL_TENANTS.equals(subscriptionAvailability)) {
            subscriptionAllowed = true;
        } else if (APIConstants.SUBSCRIPTION_TO_SPECIFIC_TENANTS.equals(subscriptionAvailability)) {
            if (subscriptionAllowedTenants != null) {
                String[] allowedTenants = subscriptionAllowedTenants.split(",");
                for (String tenant : allowedTenants) {
                    if (tenant != null && tenantDomain.equals(tenant.trim())) {
                        subscriptionAllowed = true;
                        break;
                    }
                }
            }
        }
    } else {
        subscriptionAllowed = true;
    }
    if (!subscriptionAllowed) {
        throw new APIMgtAuthorizationFailedException("Subscription is not allowed for " + userNameWithoutChange);
    }
    // check whether the specified tier is within the allowed tiers for the API
    Iterator<Tier> iterator = tiers.iterator();
    boolean isTierAllowed = false;
    List<String> allowedTierList = new ArrayList<>();
    while (iterator.hasNext()) {
        Tier t = iterator.next();
        if (t.getName() != null && (t.getName()).equals(apiTypeWrapper.getTier())) {
            isTierAllowed = true;
        }
        allowedTierList.add(t.getName());
    }
    if (!isTierAllowed) {
        String msg = "Tier " + apiTypeWrapper.getTier() + " is not allowed for API/API Product " + apiTypeWrapper + ". Only " + Arrays.toString(allowedTierList.toArray()) + " Tiers are allowed.";
        throw new APIManagementException(msg, ExceptionCodes.from(ExceptionCodes.SUBSCRIPTION_TIER_NOT_ALLOWED, apiTypeWrapper.getTier(), username));
    }
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ArrayList(java.util.ArrayList) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 47 with ApiTypeWrapper

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

the class APIConsumerImpl method getAPIorAPIProductByUUIDWithoutPermissionCheck.

/**
 * Used to retrieve API/API Products without performing the visibility permission checks
 * @param uuid
 * @param organization
 * @return
 * @throws APIManagementException
 */
private ApiTypeWrapper getAPIorAPIProductByUUIDWithoutPermissionCheck(String uuid, String organization) throws APIManagementException {
    try {
        Organization org = new Organization(organization);
        DevPortalAPI devPortalApi = apiPersistenceInstance.getDevPortalAPI(org, uuid);
        if (devPortalApi != null) {
            if (APIConstants.API_PRODUCT.equalsIgnoreCase(devPortalApi.getType())) {
                APIProduct apiProduct = APIMapper.INSTANCE.toApiProduct(devPortalApi);
                apiProduct.setID(new APIProductIdentifier(devPortalApi.getProviderName(), devPortalApi.getApiName(), devPortalApi.getVersion()));
                populateAPIProductInformation(uuid, organization, apiProduct);
                return new ApiTypeWrapper(apiProduct);
            } else {
                API api = APIMapper.INSTANCE.toApi(devPortalApi);
                populateDevPortalAPIInformation(uuid, organization, api);
                populateDefaultVersion(api);
                api = addTiersToAPI(api, organization);
                return new ApiTypeWrapper(api);
            }
        } else {
            String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (APIPersistenceException | OASPersistenceException | ParseException e) {
        String msg = "Failed to get API";
        throw new APIManagementException(msg, e);
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) ParseException(org.json.simple.parser.ParseException)

Example 48 with ApiTypeWrapper

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

the class APIProviderImpl method changeLifeCycle.

private void changeLifeCycle(API api, String currentState, String targetState, Map<String, Boolean> checklist) throws APIManagementException, FaultGatewaysException {
    String oldStatus = currentState.toUpperCase();
    String newStatus = (targetState != null) ? targetState.toUpperCase() : targetState;
    boolean isCurrentCreatedOrPrototyped = APIConstants.CREATED.equals(oldStatus) || APIConstants.PROTOTYPED.equals(oldStatus);
    boolean isStateTransitionToPublished = isCurrentCreatedOrPrototyped && APIConstants.PUBLISHED.equals(newStatus);
    if (newStatus != null) {
        // custom state to default api state
        if (isStateTransitionToPublished) {
            Set<Tier> tiers = api.getAvailableTiers();
            String endPoint = api.getEndpointConfig();
            String apiSecurity = api.getApiSecurity();
            boolean isOauthProtected = apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2);
            if (APIConstants.API_TYPE_WEBSUB.equals(api.getType()) || endPoint != null && endPoint.trim().length() > 0 || api.isAdvertiseOnly() && (api.getApiExternalProductionEndpoint() != null || api.getApiExternalSandboxEndpoint() != null)) {
                if ((isOauthProtected && (tiers == null || tiers.size() == 0)) && !api.isAdvertiseOnly()) {
                    throw new APIManagementException("Failed to publish service to API store. No Tiers selected");
                }
            } else {
                throw new APIManagementException("Failed to publish service to API store. No endpoint selected");
            }
        }
        // push the state change to gateway
        Map<String, String> failedGateways = propergateAPIStatusChangeToGateways(newStatus, api);
        if (APIConstants.PUBLISHED.equals(newStatus) || !oldStatus.equals(newStatus)) {
            // if the API is websocket and if default version is selected, update the other versions
            if (APIConstants.APITransportType.WS.toString().equals(api.getType()) && api.isDefaultVersion()) {
                Set<String> versions = getAPIVersions(api.getId().getProviderName(), api.getId().getName(), api.getOrganization());
                for (String version : versions) {
                    if (version.equals(api.getId().getVersion())) {
                        continue;
                    }
                    String uuid = APIUtil.getUUIDFromIdentifier(new APIIdentifier(api.getId().getProviderName(), api.getId().getName(), version), api.getOrganization());
                    API otherApi = getLightweightAPIByUUID(uuid, api.getOrganization());
                    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, otherApi.getId().getApiName(), otherApi.getId().getId(), otherApi.getUuid(), version, api.getType(), otherApi.getContext(), otherApi.getId().getProviderName(), otherApi.getStatus());
                    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
                }
            }
        }
        if (log.isDebugEnabled()) {
            String logMessage = "Publish changed status to the Gateway. API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + ", API Context: " + api.getContext() + ", New Status : " + newStatus;
            log.debug(logMessage);
        }
        // update api related information for state change
        updateAPIforStateChange(api, currentState, newStatus);
        if (log.isDebugEnabled()) {
            String logMessage = "API related information successfully updated. API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + ", API Context: " + api.getContext() + ", New Status : " + newStatus;
            log.debug(logMessage);
        }
    } else {
        throw new APIManagementException("Invalid Lifecycle status for default APIExecutor :" + targetState);
    }
    boolean deprecateOldVersions = false;
    boolean makeKeysForwardCompatible = true;
    // If the API status is CREATED/PROTOTYPED ,check for check list items of lifecycle
    if (isCurrentCreatedOrPrototyped) {
        if (checklist != null) {
            if (checklist.containsKey(APIConstants.DEPRECATE_CHECK_LIST_ITEM)) {
                deprecateOldVersions = checklist.get(APIConstants.DEPRECATE_CHECK_LIST_ITEM);
            }
            if (checklist.containsKey(APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM)) {
                makeKeysForwardCompatible = !checklist.get(APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM);
            }
        }
    }
    if (isStateTransitionToPublished) {
        if (makeKeysForwardCompatible) {
            makeAPIKeysForwardCompatible(api);
        }
        if (deprecateOldVersions) {
            String provider = APIUtil.replaceEmailDomain(api.getId().getProviderName());
            String apiName = api.getId().getName();
            List<API> apiList = getAPIVersionsByProviderAndName(provider, apiName, api.getOrganization());
            APIVersionComparator versionComparator = new APIVersionComparator();
            for (API oldAPI : apiList) {
                if (oldAPI.getId().getApiName().equals(api.getId().getApiName()) && versionComparator.compare(oldAPI, api) < 0 && (APIConstants.PUBLISHED.equals(oldAPI.getStatus()))) {
                    changeLifeCycleStatus(tenantDomain, new ApiTypeWrapper(oldAPI), APIConstants.API_LC_ACTION_DEPRECATE, null);
                }
            }
        }
    }
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)

Example 49 with ApiTypeWrapper

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

the class RegistryPersistenceImpl method getDevPortalAPI.

@Override
public DevPortalAPI getDevPortalAPI(Organization org, String apiId) throws APIPersistenceException {
    boolean tenantFlowStarted = false;
    try {
        String tenantDomain = org.getName();
        RegistryHolder holder = getRegistry(tenantDomain);
        Registry registry = holder.getRegistry();
        tenantFlowStarted = holder.isTenantFlowStarted();
        GenericArtifact apiArtifact = getAPIArtifact(apiId, registry);
        if (apiArtifact != null) {
            API api = RegistryPersistenceUtil.getApiForPublishing(registry, apiArtifact);
            String definitionPath = 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_OAS_DEFINITION_RESOURCE_NAME;
            if (registry.resourceExists(definitionPath)) {
                Resource apiDocResource = registry.get(definitionPath);
                String apiDocContent = new String((byte[]) apiDocResource.getContent(), Charset.defaultCharset());
                api.setSwaggerDefinition(apiDocContent);
            }
            String apiTenantDomain = MultitenantUtils.getTenantDomain(RegistryPersistenceUtil.replaceEmailDomainBack(api.getId().getProviderName()));
            if (APIConstants.API_GLOBAL_VISIBILITY.equals(api.getVisibility())) {
                // return new ApiTypeWrapper(api);
                return APIMapper.INSTANCE.toDevPortalApi(api);
            }
            if (tenantDomain == null || !tenantDomain.equals(apiTenantDomain)) {
                throw new APIPersistenceException("User does not have permission to view API : " + api.getId().getApiName());
            }
            return APIMapper.INSTANCE.toDevPortalApi(api);
        } else {
            return null;
        }
    } catch (RegistryException | APIManagementException e) {
        String msg = "Failed to get API";
        throw new APIPersistenceException(msg, e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 50 with ApiTypeWrapper

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

the class ApisApiServiceImpl method getAllCommentsOfAPI.

@Override
public Response getAllCommentsOfAPI(String apiId, String xWSO2Tenant, Integer limit, Integer offset, Boolean includeCommenterInfo, MessageContext messageContext) throws APIManagementException {
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    try {
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiId, organization);
        String parentCommentID = null;
        CommentList comments = apiConsumer.getComments(apiTypeWrapper, parentCommentID, limit, offset);
        CommentListDTO commentDTO = CommentMappingUtil.fromCommentListToDTO(comments, includeCommenterInfo);
        String uriString = RestApiConstants.RESOURCE_PATH_APIS + "/" + apiId + RestApiConstants.RESOURCE_PATH_COMMENTS;
        URI uri = new URI(uriString);
        return Response.ok(uri).entity(commentDTO).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else {
            RestApiUtil.handleInternalServerError("Failed to get comments of API " + apiId, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving comments content location for API " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Aggregations

ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)41 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)38 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)25 API (org.wso2.carbon.apimgt.api.model.API)24 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)24 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)16 URI (java.net.URI)14 URISyntaxException (java.net.URISyntaxException)14 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)14 Application (org.wso2.carbon.apimgt.api.model.Application)14 ArrayList (java.util.ArrayList)13 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)11 Tier (org.wso2.carbon.apimgt.api.model.Tier)10 Comment (org.wso2.carbon.apimgt.api.model.Comment)9 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)9 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 SubscriptionAlreadyExistingException (org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException)7 Identifier (org.wso2.carbon.apimgt.api.model.Identifier)7