Search in sources :

Example 6 with DocumentationContent

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

the class PublisherCommonUtils method addDocumentationContent.

/**
 * Add documentation content of inline and markdown documents.
 *
 * @param documentation Documentation
 * @param apiProvider   API Provider
 * @param apiId         API/API Product UUID
 * @param documentId    Document ID
 * @param organization  Identifier of the organization
 * @param inlineContent Inline content string
 * @throws APIManagementException If an error occurs while adding the documentation content
 */
public static void addDocumentationContent(Documentation documentation, APIProvider apiProvider, String apiId, String documentId, String organization, String inlineContent) throws APIManagementException {
    DocumentationContent content = new DocumentationContent();
    content.setSourceType(DocumentationContent.ContentSourceType.valueOf(documentation.getSourceType().toString()));
    content.setTextContent(inlineContent);
    apiProvider.addDocumentationContent(apiId, documentId, organization, content);
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent)

Example 7 with DocumentationContent

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

the class ApisApiServiceImpl method apisApiIdDocumentsDocumentIdContentGet.

/**
 * Retrieves the content of the document
 *
 * @param apiId           API ID
 * @param documentId      Document ID
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @param request         msf4j request object
 * @return content of the document
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisApiIdDocumentsDocumentIdContentGet(String apiId, String documentId, String ifNoneMatch, String ifModifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String existingFingerprint = apisApiIdDocumentsDocumentIdContentGetFingerprint(apiId, documentId, ifNoneMatch, ifModifiedSince, request);
        if (!StringUtils.isEmpty(ifNoneMatch) && !StringUtils.isEmpty(existingFingerprint) && ifNoneMatch.contains(existingFingerprint)) {
            return Response.notModified().build();
        }
        DocumentContent documentationContent = apiStore.getDocumentationContent(documentId);
        DocumentInfo documentInfo = documentationContent.getDocumentInfo();
        if (DocumentInfo.SourceType.FILE.equals(documentInfo.getSourceType())) {
            String filename = documentInfo.getFileName();
            return Response.ok(documentationContent.getFileContent()).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_TYPE).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"").header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
        } else if (DocumentInfo.SourceType.INLINE.equals(documentInfo.getSourceType())) {
            String content = documentationContent.getInlineContent();
            return Response.ok(content).header(RestApiConstants.HEADER_CONTENT_TYPE, MediaType.TEXT_PLAIN).header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
        } else if (DocumentInfo.SourceType.URL.equals(documentInfo.getSourceType())) {
            String sourceUrl = documentInfo.getSourceURL();
            return Response.seeOther(new URI(sourceUrl)).header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving document " + documentId + " of the API " + apiId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving source URI location of " + documentId;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 8 with DocumentationContent

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

the class ApisApiServiceImpl method getAPIDocumentContentByDocumentId.

/**
 * Retrieves the content of a document
 *
 * @param apiId       API identifier
 * @param documentId  document identifier
 * @param ifNoneMatch If-None-Match header value
 * @return Content of the document/ either inline/file or source url as a redirection
 */
@Override
public Response getAPIDocumentContentByDocumentId(String apiId, String documentId, String ifNoneMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        DocumentationContent docContent = apiProvider.getDocumentationContent(apiId, documentId, organization);
        if (docContent == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_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, APIConstants.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) {
        // 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 retrieving document : " + documentId + " of API " + apiId, e, log);
        } else {
            String errorMessage = "Error while retrieving document " + documentId + " of the API " + apiId;
            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) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI)

Example 9 with DocumentationContent

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

the class ExportUtils method addDocumentationToArchive.

/**
 * Retrieve documentation for the exporting API or API Product and store it in the archive directory.
 * FILE, INLINE, MARKDOWN and URL documentations are handled.
 *
 * @param archivePath  File path to export the documents
 * @param identifier   ID of the requesting API or API Product
 * @param exportFormat Format for export
 * @param apiProvider  API Provider
 * @param type         Type of the Project (whether an API or an API Product)
 * @throws APIImportExportException If an error occurs while retrieving documents from the
 *                                  registry or storing in the archive directory
 * @throws APIManagementException   If an error occurs while retrieving document details
 */
public static void addDocumentationToArchive(String archivePath, Identifier identifier, ExportFormat exportFormat, APIProvider apiProvider, String type) throws APIImportExportException, APIManagementException {
    String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
    List<Documentation> docList = StringUtils.equals(type, APIConstants.API_IDENTIFIER_TYPE) ? apiProvider.getAllDocumentation(identifier.getUUID(), tenantDomain) : apiProvider.getAllDocumentation(identifier);
    if (!docList.isEmpty()) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String docDirectoryPath = archivePath + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY;
        CommonUtil.createDirectory(docDirectoryPath);
        try {
            for (Documentation doc : docList) {
                // Retrieving the document again since objects in docList might have missing fields
                Documentation individualDocument = apiProvider.getDocumentation(identifier.getUUID(), doc.getId(), tenantDomain);
                String sourceType = individualDocument.getSourceType().name();
                String resourcePath = null;
                InputStream inputStream = null;
                String localFileName = null;
                String individualDocDirectoryPath = docDirectoryPath + File.separator + cleanFolderName(individualDocument.getName());
                CommonUtil.createDirectory(individualDocDirectoryPath);
                DocumentationContent documentationContent = apiProvider.getDocumentationContent(identifier.getUUID(), doc.getId(), tenantDomain);
                if (documentationContent != null) {
                    if (Documentation.DocumentSourceType.FILE.toString().equalsIgnoreCase(sourceType)) {
                        localFileName = individualDocument.getFilePath().substring(individualDocument.getFilePath().lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
                        inputStream = documentationContent.getResourceFile().getContent();
                        individualDocument.setFilePath(localFileName);
                    } else if (Documentation.DocumentSourceType.INLINE.toString().equalsIgnoreCase(sourceType) || Documentation.DocumentSourceType.MARKDOWN.toString().equalsIgnoreCase(sourceType)) {
                        // Inline/Markdown content file name would be same as the documentation name
                        localFileName = individualDocument.getName();
                        inputStream = new ByteArrayInputStream(documentationContent.getTextContent().getBytes());
                    }
                }
                CommonUtil.writeDtoToFile(individualDocDirectoryPath + ImportExportConstants.DOCUMENT_FILE_NAME, exportFormat, ImportExportConstants.TYPE_DOCUMENTS, DocumentationMappingUtil.fromDocumentationToDTO(individualDocument));
                if (inputStream != null) {
                    // Check whether resource exists in the registry
                    try (OutputStream outputStream = new FileOutputStream(individualDocDirectoryPath + File.separator + localFileName)) {
                        IOUtils.copy(inputStream, outputStream);
                    }
                } else {
                    // Log error and avoid throwing as we give capability to export document artifact without
                    // the content if does not exists
                    log.error("Documentation resource for API/API Product: " + identifier.getName() + " not found in " + resourcePath);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("Documentation retrieved successfully for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion());
            }
        } catch (IOException e) {
            throw new APIImportExportException("I/O error while writing documentation to file for API/API Product: " + identifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + identifier.getVersion(), e);
        }
    } else if (log.isDebugEnabled()) {
        log.debug("No documentation found for API/API Product: " + identifier + ". Skipping documentation export.");
    }
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) GsonBuilder(com.google.gson.GsonBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) Gson(com.google.gson.Gson) IOException(java.io.IOException)

Example 10 with DocumentationContent

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

the class APIProviderImpl method addDocumentationContent.

@Override
public void addDocumentationContent(String uuid, String docId, String organization, DocumentationContent content) throws APIManagementException {
    DocumentContent mappedContent = null;
    try {
        mappedContent = DocumentMapper.INSTANCE.toDocumentContent(content);
        DocumentContent doc = apiPersistenceInstance.addDocumentationContent(new Organization(organization), uuid, docId, mappedContent);
    } catch (DocumentationPersistenceException e) {
        throw new APIManagementException("Error while adding content to doc " + docId);
    }
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) DocumentContent(org.wso2.carbon.apimgt.persistence.dto.DocumentContent) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException)

Aggregations

DocumentationContent (org.wso2.carbon.apimgt.api.model.DocumentationContent)9 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 URI (java.net.URI)5 URISyntaxException (java.net.URISyntaxException)5 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)4 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)4 ResourceFile (org.wso2.carbon.apimgt.api.model.ResourceFile)3 InputStream (java.io.InputStream)2 HashMap (java.util.HashMap)2 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 API (org.wso2.carbon.apimgt.api.model.API)2 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)2 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)2 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)2 DocumentContent (org.wso2.carbon.apimgt.core.models.DocumentContent)2 DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)2 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)2 DocumentContent (org.wso2.carbon.apimgt.persistence.dto.DocumentContent)2 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)2