Search in sources :

Example 11 with DocumentDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO 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 12 with DocumentDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO 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 13 with DocumentDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO 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 14 with DocumentDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO 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 15 with DocumentDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO 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

DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)13 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)12 DocumentDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.DocumentDTO)12 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)11 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)11 Response (javax.ws.rs.core.Response)9 Test (org.junit.Test)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)9 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)9 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)9 DocumentDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO)9 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)5 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)4 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)4 HashMap (java.util.HashMap)3 APIInfo (org.wso2.carbon.apimgt.api.model.APIInfo)3 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)3 DocumentDTO (org.wso2.carbon.apimgt.rest.api.store.dto.DocumentDTO)3