Search in sources :

Example 81 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class ApiProductsApiServiceImpl method getAPIProductDocumentContent.

@Override
public Response getAPIProductDocumentContent(String apiProductId, String documentId, String accept, String ifNoneMatch, MessageContext messageContext) {
    Documentation documentation;
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // this will fail if user does not have access to the API Product or the API Product does not exist
        APIProductIdentifier productIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, organization);
        // documentation = apiProvider.getProductDocumentation(documentId, tenantDomain);
        DocumentationContent docContent = apiProvider.getDocumentationContent(apiProductId, documentId, organization);
        if (docContent == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, documentId, log);
            return null;
        }
        // gets the content depending on the type of the document
        if (docContent.getSourceType().equals(DocumentationContent.ContentSourceType.FILE)) {
            String contentType = docContent.getResourceFile().getContentType();
            contentType = contentType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : contentType;
            String name = docContent.getResourceFile().getName();
            return Response.ok(docContent.getResourceFile().getContent()).header(RestApiConstants.HEADER_CONTENT_TYPE, contentType).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + name + "\"").build();
        } else if (docContent.getSourceType().equals(DocumentationContent.ContentSourceType.INLINE) || docContent.getSourceType().equals(DocumentationContent.ContentSourceType.MARKDOWN)) {
            String content = docContent.getTextContent();
            return Response.ok(content).header(RestApiConstants.HEADER_CONTENT_TYPE, DOCUMENTATION_INLINE_CONTENT_TYPE).build();
        } else if (docContent.getSourceType().equals(DocumentationContent.ContentSourceType.URL)) {
            String sourceUrl = docContent.getTextContent();
            return Response.seeOther(new URI(sourceUrl)).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_PRODUCT_DOCUMENTATION, apiProductId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving document : " + documentId + " of API Product " + apiProductId, e, log);
        } else {
            String errorMessage = "Error while retrieving document " + documentId + " of the API Product" + apiProductId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving source URI location of " + documentId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI)

Example 82 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class ApiProductsApiServiceImpl method updateAPIProductDocument.

@Override
public Response updateAPIProductDocument(String apiProductId, String documentId, DocumentDTO body, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        String sourceUrl = body.getSourceUrl();
        Documentation oldDocument = apiProvider.getDocumentation(apiProductId, documentId, organization);
        // validation checks for existence of the document
        if (oldDocument == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, documentId, log);
            return null;
        }
        if (body.getType() == null) {
            throw new BadRequestException();
        }
        if (body.getType() == DocumentDTO.TypeEnum.OTHER && org.apache.commons.lang3.StringUtils.isBlank(body.getOtherTypeName())) {
            // check otherTypeName for not null if doc type is OTHER
            RestApiUtil.handleBadRequest("otherTypeName cannot be empty if type is OTHER.", log);
            return null;
        }
        if (body.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
            RestApiUtil.handleBadRequest("Invalid document sourceUrl Format", log);
            return null;
        }
        // overriding some properties
        body.setName(oldDocument.getName());
        Documentation newDocumentation = DocumentationMappingUtil.fromDTOtoDocumentation(body);
        // this will fail if user does not have access to the API or the API does not exist
        APIProductIdentifier apiIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, organization);
        newDocumentation.setFilePath(oldDocument.getFilePath());
        newDocumentation.setId(oldDocument.getId());
        apiProvider.updateDocumentation(apiProductId, newDocumentation, organization);
        // retrieve the updated documentation
        newDocumentation = apiProvider.getDocumentation(apiProductId, documentId, organization);
        return Response.ok().entity(DocumentationMappingUtil.fromDocumentationToDTO(newDocumentation)).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 updating document : " + documentId + " of API Product " + apiProductId, e, log);
        } else {
            String errorMessage = "Error while updating the document " + documentId + " for API Product : " + apiProductId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 83 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method addAPIDocumentContent.

/**
 * Add content to a document. Content can be inline or File
 *
 * @param apiId         API identifier
 * @param documentId    document identifier
 * @param inputStream   file input stream
 * @param fileDetail    file details as Attachment
 * @param inlineContent inline content for the document
 * @param ifMatch       If-match header value
 * @return updated document as DTO
 */
@Override
public Response addAPIDocumentContent(String apiId, String documentId, String ifMatch, InputStream inputStream, Attachment fileDetail, String inlineContent, MessageContext messageContext) {
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        if (inputStream != 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(apiId, documentId, organization);
        if (documentation == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_DOCUMENTATION, documentId, log);
            return null;
        }
        // add content depending on the availability of either input stream or inline content
        if (inputStream != null) {
            if (!documentation.getSourceType().equals(Documentation.DocumentSourceType.FILE)) {
                RestApiUtil.handleBadRequest("Source type of document " + documentId + " is not FILE", log);
            }
            String filename = fileDetail.getContentDisposition().getFilename();
            if (APIUtil.isSupportedFileType(filename)) {
                RestApiPublisherUtils.attachFileToDocument(apiId, documentation, inputStream, fileDetail, organization);
            } else {
                RestApiUtil.handleBadRequest("Unsupported extension type of document file: " + filename, log);
            }
        } else if (inlineContent != null) {
            if (!documentation.getSourceType().equals(Documentation.DocumentSourceType.INLINE) && !documentation.getSourceType().equals(Documentation.DocumentSourceType.MARKDOWN)) {
                RestApiUtil.handleBadRequest("Source type of document " + documentId + " is not INLINE " + "or MARKDOWN", log);
            }
            PublisherCommonUtils.addDocumentationContent(documentation, apiProvider, apiId, 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(apiId, documentId, organization);
        DocumentDTO documentDTO = DocumentationMappingUtil.fromDocumentationToDTO(updatedDoc);
        String uriString = RestApiConstants.RESOURCE_PATH_DOCUMENT_CONTENT.replace(RestApiConstants.APIID_PARAM, apiId).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, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while adding content to the document: " + documentId + " of API " + apiId, 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(inputStream);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) 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 84 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method exportAPI.

/**
 * Exports an API from API Manager for a given API using the ApiId. ID. Meta information, API icon, documentation,
 * WSDL and sequences are exported. This service generates a zipped archive which contains all the above mentioned
 * resources for a given API.
 *
 * @param apiId          UUID of an API
 * @param name           Name of the API that needs to be exported
 * @param version        Version of the API that needs to be exported
 * @param providerName   Provider name of the API that needs to be exported
 * @param format         Format of output documents. Can be YAML or JSON
 * @param preserveStatus Preserve API status on export
 * @return
 */
@Override
public Response exportAPI(String apiId, String name, String version, String revisionNum, String providerName, String format, Boolean preserveStatus, Boolean exportLatestRevision, MessageContext messageContext) throws APIManagementException {
    // If not specified status is preserved by default
    preserveStatus = preserveStatus == null || preserveStatus;
    // Default export format is YAML
    ExportFormat exportFormat = StringUtils.isNotEmpty(format) ? ExportFormat.valueOf(format.toUpperCase()) : ExportFormat.YAML;
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        ImportExportAPI importExportAPI = APIImportExportUtil.getImportExportAPI();
        File file = importExportAPI.exportAPI(apiId, name, version, revisionNum, providerName, preserveStatus, exportFormat, Boolean.TRUE, Boolean.FALSE, exportLatestRevision, StringUtils.EMPTY, organization);
        return Response.ok(file).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"").build();
    } catch (APIImportExportException e) {
        throw new APIManagementException("Error while exporting " + RestApiConstants.RESOURCE_API, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) ExportFormat(org.wso2.carbon.apimgt.impl.importexport.ExportFormat) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 85 with Documentation

use of org.wso2.carbon.apimgt.persistence.dto.Documentation in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method updateAPIDocument.

/**
 * Updates an existing document of an API
 *
 * @param apiId      API identifier
 * @param documentId document identifier
 * @param body       updated document DTO
 * @param ifMatch    If-match header value
 * @return updated document DTO as response
 */
@Override
public Response updateAPIDocument(String apiId, String documentId, DocumentDTO body, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        String sourceUrl = body.getSourceUrl();
        Documentation oldDocument = apiProvider.getDocumentation(apiId, documentId, organization);
        // validation checks for existence of the document
        if (body.getType() == null) {
            throw new BadRequestException();
        }
        if (oldDocument == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_DOCUMENTATION, documentId, log);
            return null;
        }
        if (body.getType() == DocumentDTO.TypeEnum.OTHER && org.apache.commons.lang3.StringUtils.isBlank(body.getOtherTypeName())) {
            // check otherTypeName for not null if doc type is OTHER
            RestApiUtil.handleBadRequest("otherTypeName cannot be empty if type is OTHER.", log);
            return null;
        }
        if (body.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
            RestApiUtil.handleBadRequest("Invalid document sourceUrl Format", log);
            return null;
        }
        // overriding some properties
        body.setName(oldDocument.getName());
        Documentation newDocumentation = DocumentationMappingUtil.fromDTOtoDocumentation(body);
        newDocumentation.setFilePath(oldDocument.getFilePath());
        newDocumentation.setId(documentId);
        newDocumentation = apiProvider.updateDocumentation(apiId, newDocumentation, organization);
        return Response.ok().entity(DocumentationMappingUtil.fromDocumentationToDTO(newDocumentation)).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, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while updating document : " + documentId + " of API " + apiId, e, log);
        } else {
            String errorMessage = "Error while updating the document " + documentId + " for API : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) BadRequestException(org.wso2.carbon.apimgt.rest.api.util.exception.BadRequestException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Aggregations

Documentation (org.wso2.carbon.apimgt.api.model.Documentation)56 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 Test (org.testng.annotations.Test)38 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)34 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)33 DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)32 ArrayList (java.util.ArrayList)29 Resource (org.wso2.carbon.registry.core.Resource)27 HashMap (java.util.HashMap)26 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)26 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)24 API (org.wso2.carbon.apimgt.api.model.API)23 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)23 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)22 Test (org.junit.Test)18 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)18 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)18 Registry (org.wso2.carbon.registry.core.Registry)18 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 DocumentationPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException)17