Search in sources :

Example 76 with Documentation

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

the class ImportUtils method addDocumentation.

/**
 * This method adds the documents to the imported API or API Product.
 *
 * @param pathToArchive  Location of the extracted folder of the API or API Product
 * @param apiTypeWrapper Imported API or API Product
 * @param organization  Identifier of an Organization
 */
private static void addDocumentation(String pathToArchive, ApiTypeWrapper apiTypeWrapper, APIProvider apiProvider, String organization) {
    String jsonContent = null;
    Identifier identifier = apiTypeWrapper.getId();
    String docDirectoryPath = pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY;
    File documentsFolder = new File(docDirectoryPath);
    File[] fileArray = documentsFolder.listFiles();
    String provider = (apiTypeWrapper.isAPIProduct()) ? apiTypeWrapper.getApiProduct().getId().getProviderName() : apiTypeWrapper.getApi().getId().getProviderName();
    String tenantDomain = MultitenantUtils.getTenantDomain(provider);
    try {
        // Remove all documents associated with the API before update
        List<Documentation> documents = apiProvider.getAllDocumentation(identifier);
        if (documents != null) {
            for (Documentation documentation : documents) {
                apiProvider.removeDocumentation(identifier, documentation.getId(), tenantDomain);
            }
        }
        if (documentsFolder.isDirectory() && fileArray != null) {
            // This loop locates the documents inside each repo
            for (File documentFile : fileArray) {
                String folderName = documentFile.getName();
                String individualDocumentFilePath = docDirectoryPath + File.separator + folderName;
                String pathToYamlFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.YAML_EXTENSION;
                String pathToJsonFile = individualDocumentFilePath + ImportExportConstants.DOCUMENT_FILE_NAME + ImportExportConstants.JSON_EXTENSION;
                // Load document file if exists
                if (CommonUtil.checkFileExistence(pathToYamlFile)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Found documents definition file " + pathToYamlFile);
                    }
                    String yamlContent = FileUtils.readFileToString(new File(pathToYamlFile));
                    jsonContent = CommonUtil.yamlToJson(yamlContent);
                } else if (CommonUtil.checkFileExistence(pathToJsonFile)) {
                    // load as a json fallback
                    if (log.isDebugEnabled()) {
                        log.debug("Found documents definition file " + pathToJsonFile);
                    }
                    jsonContent = FileUtils.readFileToString(new File(pathToJsonFile));
                }
                JsonElement configElement = new JsonParser().parse(jsonContent).getAsJsonObject().get(APIConstants.DATA);
                DocumentDTO documentDTO = new Gson().fromJson(configElement.getAsJsonObject(), DocumentDTO.class);
                // Add the documentation DTO
                Documentation documentation = apiTypeWrapper.isAPIProduct() ? PublisherCommonUtils.addDocumentationToAPI(documentDTO, apiTypeWrapper.getApiProduct().getUuid(), organization) : PublisherCommonUtils.addDocumentationToAPI(documentDTO, apiTypeWrapper.getApi().getUuid(), organization);
                // Adding doc content
                String docSourceType = documentation.getSourceType().toString();
                boolean docContentExists = Documentation.DocumentSourceType.INLINE.toString().equalsIgnoreCase(docSourceType) || Documentation.DocumentSourceType.MARKDOWN.toString().equalsIgnoreCase(docSourceType);
                String apiOrApiProductId = (!apiTypeWrapper.isAPIProduct()) ? apiTypeWrapper.getApi().getUuid() : apiTypeWrapper.getApiProduct().getUuid();
                if (docContentExists) {
                    try (FileInputStream inputStream = new FileInputStream(individualDocumentFilePath + File.separator + folderName)) {
                        String inlineContent = IOUtils.toString(inputStream, ImportExportConstants.CHARSET);
                        PublisherCommonUtils.addDocumentationContent(documentation, apiProvider, apiOrApiProductId, documentation.getId(), tenantDomain, inlineContent);
                    }
                } else if (ImportExportConstants.FILE_DOC_TYPE.equalsIgnoreCase(docSourceType)) {
                    String filePath = documentation.getFilePath();
                    try (FileInputStream inputStream = new FileInputStream(individualDocumentFilePath + File.separator + filePath)) {
                        String docExtension = FilenameUtils.getExtension(pathToArchive + File.separator + ImportExportConstants.DOCUMENT_DIRECTORY + File.separator + filePath);
                        PublisherCommonUtils.addDocumentationContentForFile(inputStream, docExtension, documentation.getFilePath(), apiProvider, apiOrApiProductId, documentation.getId(), tenantDomain);
                    } catch (FileNotFoundException e) {
                        // this error is logged and ignored because documents are optional in an API
                        log.error("Failed to locate the document files of the API/API Product: " + apiTypeWrapper.getId().getName(), e);
                        continue;
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        // this error is logged and ignored because documents are optional in an API
        log.error("Failed to locate the document files of the API/API Product: " + identifier.getName(), e);
    } catch (APIManagementException | IOException e) {
        // this error is logged and ignored because documents are optional in an API
        log.error("Failed to add Documentations to API/API Product: " + identifier.getName(), e);
    }
}
Also used : Documentation(org.wso2.carbon.apimgt.api.model.Documentation) FileNotFoundException(java.io.FileNotFoundException) Gson(com.google.gson.Gson) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) DocumentDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO) File(java.io.File) JsonParser(com.google.gson.JsonParser)

Example 77 with Documentation

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

the class RestApiPublisherUtils method attachFileToProductDocument.

/**
 * Attaches a file to the specified product document
 *
 * @param productId identifier of the API Product, the document belongs to
 * @param documentation Documentation object
 * @param inputStream input Stream containing the file
 * @param fileDetails file details object as cxf Attachment
 * @param organization organization of the API
 * @throws APIManagementException if unable to add the file
 */
public static void attachFileToProductDocument(String productId, Documentation documentation, InputStream inputStream, Attachment fileDetails, String organization) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String documentId = documentation.getId();
    String randomFolderName = RandomStringUtils.randomAlphanumeric(10);
    String tmpFolder = System.getProperty(RestApiConstants.JAVA_IO_TMPDIR) + File.separator + RestApiConstants.DOC_UPLOAD_TMPDIR + File.separator + randomFolderName;
    File docFile = new File(tmpFolder);
    boolean folderCreated = docFile.mkdirs();
    if (!folderCreated) {
        RestApiUtil.handleInternalServerError("Failed to add content to the document " + documentId, log);
    }
    InputStream docInputStream = null;
    try {
        ContentDisposition contentDisposition = fileDetails.getContentDisposition();
        String filename = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
        if (StringUtils.isBlank(filename)) {
            filename = RestApiConstants.DOC_NAME_DEFAULT + randomFolderName;
            log.warn("Couldn't find the name of the uploaded file for the document " + documentId + ". Using name '" + filename + "'");
        }
        // APIProductIdentifier productIdentifier = APIMappingUtil
        // .getAPIProductIdentifierFromUUID(productId, tenantDomain);
        RestApiUtil.transferFile(inputStream, filename, docFile.getAbsolutePath());
        docInputStream = new FileInputStream(docFile.getAbsolutePath() + File.separator + filename);
        String mediaType = fileDetails.getHeader(RestApiConstants.HEADER_CONTENT_TYPE);
        mediaType = mediaType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : mediaType;
        PublisherCommonUtils.addDocumentationContentForFile(docInputStream, mediaType, filename, apiProvider, productId, documentId, organization);
        docFile.deleteOnExit();
    } catch (FileNotFoundException e) {
        RestApiUtil.handleInternalServerError("Unable to read the file from path ", e, log);
    } finally {
        IOUtils.closeQuietly(docInputStream);
    }
}
Also used : ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 78 with Documentation

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

the class PublisherCommonUtils method addDocumentationContentForFile.

/**
 * Add documentation content of files.
 *
 * @param inputStream  Input Stream
 * @param mediaType    Media type of the document
 * @param filename     File name
 * @param apiProvider  API Provider
 * @param apiId        API/API Product UUID
 * @param documentId   Document ID
 * @param organization organization of the API
 * @throws APIManagementException If an error occurs while adding the documentation file
 */
public static void addDocumentationContentForFile(InputStream inputStream, String mediaType, String filename, APIProvider apiProvider, String apiId, String documentId, String organization) throws APIManagementException {
    DocumentationContent content = new DocumentationContent();
    ResourceFile resourceFile = new ResourceFile(inputStream, mediaType);
    resourceFile.setName(filename);
    content.setResourceFile(resourceFile);
    content.setSourceType(DocumentationContent.ContentSourceType.FILE);
    apiProvider.addDocumentationContent(apiId, documentId, organization, content);
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile)

Example 79 with Documentation

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

the class PublisherCommonUtils method addDocumentationToAPI.

/**
 * Add document DTO.
 *
 * @param documentDto Document DTO
 * @param apiId       API UUID
 * @return Added documentation
 * @param organization  Identifier of an Organization
 * @throws APIManagementException If an error occurs when retrieving API Identifier,
 *                                when checking whether the documentation exists and when adding the documentation
 */
public static Documentation addDocumentationToAPI(DocumentDTO documentDto, String apiId, String organization) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    Documentation documentation = DocumentationMappingUtil.fromDTOtoDocumentation(documentDto);
    String documentName = documentDto.getName();
    if (documentDto.getType() == null) {
        throw new APIManagementException("Documentation type cannot be empty", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    if (documentDto.getType() == DocumentDTO.TypeEnum.OTHER && StringUtils.isBlank(documentDto.getOtherTypeName())) {
        // check otherTypeName for not null if doc type is OTHER
        throw new APIManagementException("otherTypeName cannot be empty if type is OTHER.", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    String sourceUrl = documentDto.getSourceUrl();
    if (documentDto.getSourceType() == DocumentDTO.SourceTypeEnum.URL && (org.apache.commons.lang3.StringUtils.isBlank(sourceUrl) || !RestApiCommonUtil.isURL(sourceUrl))) {
        throw new APIManagementException("Invalid document sourceUrl Format", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    }
    if (apiProvider.isDocumentationExist(apiId, documentName, organization)) {
        throw new APIManagementException("Requested document '" + documentName + "' already exists", ExceptionCodes.DOCUMENT_ALREADY_EXISTS);
    }
    documentation = apiProvider.addDocumentation(apiId, documentation, organization);
    return documentation;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 80 with Documentation

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

the class ApiProductsApiServiceImpl method deleteAPIProductDocument.

@Override
public Response deleteAPIProductDocument(String apiProductId, String documentId, String ifMatch, MessageContext messageContext) {
    Documentation documentation;
    try {
        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.getDocumentation(apiProductId, documentId, organization);
        if (documentation == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, documentId, log);
        }
        apiProvider.removeDocumentation(apiProductId, documentId, organization);
        return Response.ok().build();
    } catch (APIManagementException e) {
        // Auth failure occurs when cross tenant accessing API Products. 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 deleting : " + documentId + " of API Product " + apiProductId, e, log);
        } else {
            String errorMessage = "Error while retrieving 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) 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