Search in sources :

Example 71 with APIProduct

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

the class PublisherCommonUtils method addAPIProductWithGeneratedSwaggerDefinition.

/**
 * Add API Product with the generated swagger from the DTO.
 *
 * @param apiProductDTO API Product DTO
 * @param username      Username
 * @param organization Identifier of the organization
 * @return Created API Product object
 * @throws APIManagementException Error while creating the API Product
 * @throws FaultGatewaysException Error while adding the API Product to gateway
 */
public static APIProduct addAPIProductWithGeneratedSwaggerDefinition(APIProductDTO apiProductDTO, String username, String organization) throws APIManagementException, FaultGatewaysException {
    username = StringUtils.isEmpty(username) ? RestApiCommonUtil.getLoggedInUsername() : username;
    APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
    // if not add product
    String provider = apiProductDTO.getProvider();
    String context = apiProductDTO.getContext();
    if (!StringUtils.isBlank(provider) && !provider.equals(username)) {
        if (!APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN)) {
            if (log.isDebugEnabled()) {
                log.debug("User " + username + " does not have admin permission (" + APIConstants.Permissions.APIM_ADMIN + ") hence provider (" + provider + ") overridden with current user (" + username + ")");
            }
            provider = username;
        }
    } else {
        // Set username in case provider is null or empty
        provider = username;
    }
    List<String> tiersFromDTO = apiProductDTO.getPolicies();
    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 (apiProductDTO.getAdditionalProperties() != null) {
        String errorMessage = PublisherCommonUtils.validateAdditionalProperties(apiProductDTO.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, apiProductDTO.getName()));
        }
    }
    if (apiProductDTO.getVisibility() == null) {
        // set the default visibility to PUBLIC
        apiProductDTO.setVisibility(APIProductDTO.VisibilityEnum.PUBLIC);
    }
    if (apiProductDTO.getAuthorizationHeader() == null) {
        apiProductDTO.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
    }
    if (apiProductDTO.getAuthorizationHeader() == null) {
        apiProductDTO.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
    }
    // Remove the /{version} from the context.
    if (context.endsWith("/" + RestApiConstants.API_VERSION_PARAM)) {
        context = context.replace("/" + RestApiConstants.API_VERSION_PARAM, "");
    }
    // Make sure context starts with "/". ex: /pizzaProduct
    context = context.startsWith("/") ? context : ("/" + context);
    // Check whether the context already exists
    if (apiProvider.isContextExist(context)) {
        throw new APIManagementException("Error occurred while adding API Product. API Product with the context " + context + " already " + "exists.", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_CONTEXT_ALREADY_EXISTS, context));
    }
    // Set default gatewayVendor
    if (apiProductDTO.getGatewayVendor() == null) {
        apiProductDTO.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
    }
    APIProduct productToBeAdded = APIMappingUtil.fromDTOtoAPIProduct(apiProductDTO, provider);
    productToBeAdded.setOrganization(organization);
    if (!APIConstants.PROTOTYPED.equals(productToBeAdded.getState())) {
        productToBeAdded.setState(APIConstants.CREATED);
    }
    APIProductIdentifier createdAPIProductIdentifier = productToBeAdded.getId();
    Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider.addAPIProductWithoutPublishingToGateway(productToBeAdded);
    APIProduct createdProduct = apiProvider.getAPIProduct(createdAPIProductIdentifier);
    apiProvider.addAPIProductSwagger(createdProduct.getUuid(), apiToProductResourceMapping, createdProduct, organization);
    createdProduct = apiProvider.getAPIProduct(createdAPIProductIdentifier);
    return createdProduct;
}
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) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 72 with APIProduct

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

the class ApiProductsApiServiceImpl method getAPIProductSwagger.

@Override
public Response getAPIProductSwagger(String apiProductId, String accept, String ifNoneMatch, MessageContext messageContext) {
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
        APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
        APIProduct retrievedProduct = apiProvider.getAPIProductbyUUID(apiProductId, tenantDomain);
        if (retrievedProduct == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, log);
        }
        String apiSwagger = apiProvider.getOpenAPIDefinition(apiProductId, tenantDomain);
        if (StringUtils.isEmpty(apiSwagger)) {
            apiSwagger = "";
        }
        return Response.ok().entity(apiSwagger).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API Product from Id  : " + apiProductId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 73 with APIProduct

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

the class ApiProductsApiServiceImpl method getAllAPIProducts.

@Override
public Response getAllAPIProducts(Integer limit, Integer offset, String query, String accept, String ifNoneMatch, MessageContext messageContext) {
    List<APIProduct> allMatchedProducts = new ArrayList<>();
    APIProductListDTO apiProductListDTO;
    // setting default limit and offset values if they are not set
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    query = query == null ? "" : query;
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
        if (log.isDebugEnabled()) {
            log.debug("API Product list request by " + username);
        }
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        Map<String, Object> result = apiProvider.searchPaginatedAPIProducts(query, tenantDomain, offset, limit);
        Set<APIProduct> apiProducts = (Set<APIProduct>) result.get("products");
        allMatchedProducts.addAll(apiProducts);
        apiProductListDTO = APIMappingUtil.fromAPIProductListtoDTO(allMatchedProducts);
        // Add pagination section in the response
        Object totalLength = result.get("length");
        Integer length = 0;
        if (totalLength != null) {
            length = (Integer) totalLength;
        }
        APIMappingUtil.setPaginationParams(apiProductListDTO, query, offset, limit, length);
        return Response.ok().entity(apiProductListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API Products ";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIProductListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIProductListDTO) Set(java.util.Set) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 74 with APIProduct

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

the class ApiProductsApiServiceImpl method addAPIProductDocumentContent.

@Override
public Response addAPIProductDocumentContent(String apiProductId, String documentId, String ifMatch, InputStream fileInputStream, Attachment fileDetail, String inlineContent, MessageContext messageContext) {
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        APIProduct product = apiProvider.getAPIProductbyUUID(apiProductId, organization);
        APIProductIdentifier productIdentifier = product.getId();
        if (fileInputStream != null && inlineContent != null) {
            RestApiUtil.handleBadRequest("Only one of 'file' and 'inlineContent' should be specified", log);
        }
        // retrieves the document and send 404 if not found
        Documentation documentation = apiProvider.getDocumentation(apiProductId, documentId, organization);
        if (documentation == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, documentId, log);
            return null;
        }
        // add content depending on the availability of either input stream or inline content
        if (fileInputStream != null) {
            if (!documentation.getSourceType().equals(Documentation.DocumentSourceType.FILE)) {
                RestApiUtil.handleBadRequest("Source type of product document " + documentId + " is not FILE", log);
            }
            RestApiPublisherUtils.attachFileToProductDocument(apiProductId, documentation, fileInputStream, fileDetail, organization);
        } else if (inlineContent != null) {
            if (!documentation.getSourceType().equals(Documentation.DocumentSourceType.INLINE) && !documentation.getSourceType().equals(Documentation.DocumentSourceType.MARKDOWN)) {
                RestApiUtil.handleBadRequest("Source type of product document " + documentId + " is not INLINE " + "or MARKDOWN", log);
            }
            PublisherCommonUtils.addDocumentationContent(documentation, apiProvider, apiProductId, documentId, organization, inlineContent);
        } else {
            RestApiUtil.handleBadRequest("Either 'file' or 'inlineContent' should be specified", log);
        }
        // retrieving the updated doc and the URI
        Documentation updatedDoc = apiProvider.getDocumentation(apiProductId, documentId, organization);
        DocumentDTO documentDTO = DocumentationMappingUtil.fromDocumentationToDTO(updatedDoc);
        String uriString = RestApiConstants.RESOURCE_PATH_PRODUCT_DOCUMENT_CONTENT.replace(RestApiConstants.APIPRODUCTID_PARAM, apiProductId).replace(RestApiConstants.DOCUMENTID_PARAM, documentId);
        URI uri = new URI(uriString);
        return Response.created(uri).entity(documentDTO).build();
    } catch (APIManagementException e) {
        // Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while adding content to the document: " + documentId + " of API Product " + apiProductId, e, log);
        } else {
            RestApiUtil.handleInternalServerError("Failed to add content to the document " + documentId, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving document content location : " + documentId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
    return null;
}
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) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) DocumentDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI)

Example 75 with APIProduct

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

the class ApiProductsApiServiceImpl method deleteAPIProduct.

@Override
public Response deleteAPIProduct(String apiProductId, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String username = RestApiCommonUtil.getLoggedInUsername();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProductIdentifier apiProductIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, organization);
        if (log.isDebugEnabled()) {
            log.debug("Delete API Product request: Id " + apiProductId + " by " + username);
        }
        APIProduct apiProduct = apiProvider.getAPIProductbyUUID(apiProductId, organization);
        if (apiProduct == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, log);
        }
        boolean isAPIPublishedOrDeprecated = APIStatus.PUBLISHED.getStatus().equals(apiProduct.getState()) || APIStatus.DEPRECATED.getStatus().equals(apiProduct.getState());
        List<SubscribedAPI> apiUsages = apiProvider.getAPIProductUsageByAPIProductId(apiProductIdentifier);
        if (isAPIPublishedOrDeprecated && (apiUsages != null && apiUsages.size() > 0)) {
            RestApiUtil.handleConflict("Cannot remove the API " + apiProductIdentifier + " as active subscriptions exist", log);
        }
        apiProduct.setOrganization(organization);
        apiProvider.deleteAPIProduct(apiProduct);
        return Response.ok().build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while deleting API Product : " + apiProductId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)71 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)52 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)51 API (org.wso2.carbon.apimgt.api.model.API)37 ArrayList (java.util.ArrayList)31 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)22 PublisherAPIProduct (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)22 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)21 Tier (org.wso2.carbon.apimgt.api.model.Tier)21 HashMap (java.util.HashMap)19 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)19 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)18 JSONObject (org.json.simple.JSONObject)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)16 HashSet (java.util.HashSet)15 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)15 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)14 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)14 ParseException (org.json.simple.parser.ParseException)12