Search in sources :

Example 46 with APIProductIdentifier

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

the class PublisherCommonUtils method updateApiProduct.

/**
 * Update an API Product.
 *
 * @param originalAPIProduct    Existing API Product
 * @param apiProductDtoToUpdate New API Product DTO to update
 * @param apiProvider           API Provider
 * @param username              Username
 * @throws APIManagementException If an error occurs while retrieving and updating an existing API Product
 * @throws FaultGatewaysException If an error occurs while updating an existing API Product
 */
public static APIProduct updateApiProduct(APIProduct originalAPIProduct, APIProductDTO apiProductDtoToUpdate, APIProvider apiProvider, String username, String orgId) throws APIManagementException, FaultGatewaysException {
    List<String> apiSecurity = apiProductDtoToUpdate.getSecurityScheme();
    // validation for tiers
    List<String> tiersFromDTO = apiProductDtoToUpdate.getPolicies();
    if (apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) || apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
        if (tiersFromDTO == null || tiersFromDTO.isEmpty()) {
            throw new APIManagementException("No tier defined for the API Product", ExceptionCodes.TIER_CANNOT_BE_NULL);
        }
    }
    // check whether the added API Products's tiers are all valid
    Set<Tier> definedTiers = apiProvider.getTiers();
    List<String> invalidTiers = PublisherCommonUtils.getInvalidTierNames(definedTiers, tiersFromDTO);
    if (!invalidTiers.isEmpty()) {
        throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
    }
    if (apiProductDtoToUpdate.getAdditionalProperties() != null) {
        String errorMessage = PublisherCommonUtils.validateAdditionalProperties(apiProductDtoToUpdate.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, originalAPIProduct.getId().getName(), originalAPIProduct.getId().getVersion()));
        }
    }
    APIProduct product = APIMappingUtil.fromDTOtoAPIProduct(apiProductDtoToUpdate, username);
    product.setState(originalAPIProduct.getState());
    // We do not allow to modify provider,name,version  and uuid. Set the origial value
    APIProductIdentifier productIdentifier = originalAPIProduct.getId();
    product.setID(productIdentifier);
    product.setUuid(originalAPIProduct.getUuid());
    product.setOrganization(orgId);
    Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider.updateAPIProduct(product);
    apiProvider.updateAPIProductSwagger(originalAPIProduct.getUuid(), apiToProductResourceMapping, product, orgId);
    // preserve monetization status in the update flow
    apiProvider.configureMonetizationInAPIProductArtifact(product);
    return apiProvider.getAPIProduct(productIdentifier);
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) API(org.wso2.carbon.apimgt.api.model.API) List(java.util.List) ArrayList(java.util.ArrayList)

Example 47 with APIProductIdentifier

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

the class APIMappingUtil method fromAPIToInfoDTO.

/**
 * Creates a minimal DTO representation of an API Product object
 *
 * @param apiProduct API Product object
 * @return a minimal representation DTO
 * @throws APIManagementException
 */
static APIInfoDTO fromAPIToInfoDTO(APIProduct apiProduct, String organization) throws APIManagementException {
    APIInfoDTO apiInfoDTO = new APIInfoDTO();
    apiInfoDTO.setDescription(apiProduct.getDescription());
    apiInfoDTO.setContext(apiProduct.getContext());
    apiInfoDTO.setId(apiProduct.getUuid());
    APIProductIdentifier apiId = apiProduct.getId();
    apiInfoDTO.setName(apiId.getName());
    apiInfoDTO.setVersion(apiId.getVersion());
    apiInfoDTO.setProvider(apiId.getProviderName());
    apiInfoDTO.setLifeCycleStatus(apiProduct.getState());
    apiInfoDTO.setType(APIType.API_PRODUCT.toString());
    apiInfoDTO.setAvgRating(String.valueOf(apiProduct.getRating()));
    String providerName = apiProduct.getId().getProviderName();
    apiInfoDTO.setProvider(APIUtil.replaceEmailDomainBack(providerName));
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    Set<String> deniedTiers = apiConsumer.getDeniedTiers(organization);
    Map<String, Tier> tierMap = APIUtil.getTiers(organization);
    setThrottlePoliciesAndMonetization(apiProduct, apiInfoDTO, deniedTiers, tierMap);
    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(apiProduct.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(apiProduct.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(apiProduct.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(apiProduct.getTechnicalOwnerEmail());
    apiInfoDTO.setBusinessInformation(apiBusinessInformationDTO);
    if (!StringUtils.isBlank(apiProduct.getThumbnailUrl())) {
        apiInfoDTO.setThumbnailUri(apiProduct.getThumbnailUrl());
    }
    // Since same APIInfoDTO is used for listing APIProducts in StoreUI set default AdvertisedInfo to the DTO
    AdvertiseInfoDTO advertiseInfoDTO = new AdvertiseInfoDTO();
    advertiseInfoDTO.setAdvertised(false);
    apiInfoDTO.setAdvertiseInfo(advertiseInfoDTO);
    String apiTenant = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiProduct.getId().getProviderName()));
    String subscriptionAvailability = apiProduct.getSubscriptionAvailability();
    String subscriptionAllowedTenants = apiProduct.getSubscriptionAvailableTenants();
    apiInfoDTO.setIsSubscriptionAvailable(isSubscriptionAvailable(apiTenant, subscriptionAvailability, subscriptionAllowedTenants));
    return apiInfoDTO;
}
Also used : APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIBusinessInformationDTO) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) AdvertiseInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.AdvertiseInfoDTO) Tier(org.wso2.carbon.apimgt.api.model.Tier) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) APIInfoDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIInfoDTO)

Example 48 with APIProductIdentifier

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

the class SubscriptionsApiServiceImpl method subscriptionsSubscriptionIdPut.

/**
 * Update already created subscriptions with the details specified in the body parameter
 *
 * @param body new subscription details
 * @return newly added subscription as a SubscriptionDTO if successful
 */
@Override
public Response subscriptionsSubscriptionIdPut(String subscriptionId, SubscriptionDTO body, String xWSO2Tenant, MessageContext messageContext) {
    String username = RestApiCommonUtil.getLoggedInUsername();
    APIConsumer apiConsumer;
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        apiConsumer = RestApiCommonUtil.getConsumer(username);
        String applicationId = body.getApplicationId();
        String currentThrottlingPolicy = body.getThrottlingPolicy();
        String requestedThrottlingPolicy = body.getRequestedThrottlingPolicy();
        SubscribedAPI subscribedAPI = apiConsumer.getSubscriptionByUUID(subscriptionId);
        // Check whether the subscription status is not empty and also not blocked
        if (body.getStatus() != null && subscribedAPI != null) {
            if ("BLOCKED".equals(body.getStatus().value()) || "ON_HOLD".equals(body.getStatus().value()) || "REJECTED".equals(body.getStatus().value()) || "BLOCKED".equals(subscribedAPI.getSubStatus()) || "ON_HOLD".equals(subscribedAPI.getSubStatus()) || "REJECTED".equals(subscribedAPI.getSubStatus())) {
                RestApiUtil.handleBadRequest("Cannot update subscriptions with provided or existing status", log);
                return null;
            }
        } else {
            RestApiUtil.handleBadRequest("Request must contain status of the subscription", log);
            return null;
        }
        // this will throw a APIMgtResourceNotFoundException
        if (body.getApiId() != null) {
            if (!RestAPIStoreUtils.isUserAccessAllowedForAPIByUUID(body.getApiId(), organization)) {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, body.getApiId(), log);
            }
        } else {
            RestApiUtil.handleBadRequest("Request must contain either apiIdentifier or apiProductIdentifier and the relevant type", log);
            return null;
        }
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application == null) {
            // required application not found
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            return null;
        }
        if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
            // application access failure occurred
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
        ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(body.getApiId(), organization);
        apiTypeWrapper.setTier(body.getThrottlingPolicy());
        SubscriptionResponse subscriptionResponse = apiConsumer.updateSubscription(apiTypeWrapper, username, application, subscriptionId, currentThrottlingPolicy, requestedThrottlingPolicy);
        SubscribedAPI addedSubscribedAPI = apiConsumer.getSubscriptionByUUID(subscriptionResponse.getSubscriptionUUID());
        SubscriptionDTO addedSubscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(addedSubscribedAPI, organization);
        WorkflowResponse workflowResponse = subscriptionResponse.getWorkflowResponse();
        if (workflowResponse instanceof HttpWorkflowResponse) {
            String payload = workflowResponse.getJSONPayload();
            addedSubscriptionDTO.setRedirectionParams(payload);
        }
        return Response.ok(new URI(RestApiConstants.RESOURCE_PATH_SUBSCRIPTIONS + "/" + addedSubscribedAPI.getUUID())).entity(addedSubscriptionDTO).build();
    } catch (APIMgtAuthorizationFailedException e) {
        // this occurs when the api:application:tier mapping is not allowed. The reason for the message is taken from
        // the message of the exception e
        RestApiUtil.handleAuthorizationFailure(e.getMessage(), e, log);
    } catch (SubscriptionAlreadyExistingException e) {
        RestApiUtil.handleResourceAlreadyExistsError("Specified subscription already exists for API " + body.getApiId() + ", for application " + body.getApplicationId(), e, log);
    } catch (APIManagementException | URISyntaxException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            // this happens when the specified API identifier does not exist
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, body.getApiId(), e, log);
        } else {
            // unhandled exception
            RestApiUtil.handleInternalServerError("Error while adding the subscription API:" + body.getApiId() + ", application:" + body.getApplicationId() + ", tier:" + body.getThrottlingPolicy(), e, log);
        }
    }
    return null;
}
Also used : ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.HttpWorkflowResponse) SubscriptionAlreadyExistingException(org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) WorkflowResponse(org.wso2.carbon.apimgt.api.WorkflowResponse) HttpWorkflowResponse(org.wso2.carbon.apimgt.impl.workflow.HttpWorkflowResponse) SubscriptionResponse(org.wso2.carbon.apimgt.api.model.SubscriptionResponse) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) Application(org.wso2.carbon.apimgt.api.model.Application) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.SubscriptionDTO)

Example 49 with APIProductIdentifier

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

the class SearchResultMappingUtil method fromAPIToAPIResultDTO.

/**
 * Get API result representation for content search
 * @param apiProduct API product
 * @return APISearchResultDTO
 */
public static APISearchResultDTO fromAPIToAPIResultDTO(APIProduct apiProduct) {
    APISearchResultDTO apiResultDTO = new APISearchResultDTO();
    apiResultDTO.setId(apiProduct.getUuid());
    APIProductIdentifier apiId = apiProduct.getId();
    apiResultDTO.setName(apiId.getName());
    apiResultDTO.setVersion(apiId.getVersion());
    apiResultDTO.setProvider(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
    String context = apiProduct.getContextTemplate();
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    apiResultDTO.setContext(context);
    apiResultDTO.setAvgRating(String.valueOf(apiProduct.getRating()));
    APIBusinessInformationDTO apiBusinessInformationDTO = new APIBusinessInformationDTO();
    apiBusinessInformationDTO.setBusinessOwner(apiProduct.getBusinessOwner());
    apiBusinessInformationDTO.setBusinessOwnerEmail(apiProduct.getBusinessOwnerEmail());
    apiBusinessInformationDTO.setTechnicalOwner(apiProduct.getTechnicalOwner());
    apiBusinessInformationDTO.setTechnicalOwnerEmail(apiProduct.getTechnicalOwnerEmail());
    apiResultDTO.setBusinessInformation(apiBusinessInformationDTO);
    apiResultDTO.setType(SearchResultDTO.TypeEnum.API);
    apiResultDTO.setTransportType(apiProduct.getType());
    apiResultDTO.setDescription(apiProduct.getDescription());
    apiResultDTO.setStatus(apiProduct.getState());
    apiResultDTO.setThumbnailUri(apiProduct.getThumbnailUrl());
    return apiResultDTO;
}
Also used : APIBusinessInformationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIBusinessInformationDTO) APISearchResultDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APISearchResultDTO) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier)

Example 50 with APIProductIdentifier

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

the class AbstractAPIManager method getAPIProduct.

/**
 * Get API Product by product identifier
 *
 * @param identifier APIProductIdentifier
 * @return API product identified by provider identifier
 * @throws APIManagementException
 */
public APIProduct getAPIProduct(APIProductIdentifier identifier) throws APIManagementException {
    String apiProductPath = APIUtil.getAPIProductPath(identifier);
    Registry registry;
    try {
        String productTenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
        int productTenantId = getTenantManager().getTenantId(productTenantDomain);
        if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(productTenantDomain)) {
            APIUtil.loadTenantRegistry(productTenantId);
        }
        if (this.tenantDomain == null || !this.tenantDomain.equals(productTenantDomain)) {
            // cross tenant scenario
            registry = getRegistryService().getGovernanceUserRegistry(getTenantAwareUsername(APIUtil.replaceEmailDomainBack(identifier.getProviderName())), productTenantId);
        } else {
            registry = this.registry;
        }
        GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY);
        Resource productResource = registry.get(apiProductPath);
        String artifactId = productResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + apiProductPath);
        }
        GenericArtifact productArtifact = artifactManager.getGenericArtifact(artifactId);
        APIProduct apiProduct = APIUtil.getAPIProduct(productArtifact, registry);
        return apiProduct;
    } catch (RegistryException e) {
        String msg = "Failed to get API Product from : " + apiProductPath;
        throw new APIManagementException(msg, e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String msg = "Failed to get API Product from : " + apiProductPath;
        throw new APIManagementException(msg, e);
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Aggregations

APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)91 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)48 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)33 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)22 PreparedStatement (java.sql.PreparedStatement)19 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)19 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)19 Connection (java.sql.Connection)18 ArrayList (java.util.ArrayList)18 ResultSet (java.sql.ResultSet)17 SQLException (java.sql.SQLException)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 API (org.wso2.carbon.apimgt.api.model.API)14 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)14 HashSet (java.util.HashSet)13 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)13 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)13 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)13 Tier (org.wso2.carbon.apimgt.api.model.Tier)12 PublisherAPIProduct (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)12