Search in sources :

Example 16 with DocumentContent

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

the class FileBasedApiImportExportManager method exportDocumentationToFileSystem.

/**
 * Writes the given List of {@link DocumentInfo} objects to the file system
 *
 * @param documentInfo   list of {@link DocumentInfo} objects
 * @param apiDetails     {@link APIDetails} instance, to which the documents are related to
 * @param exportLocation file system location to which documents will be written
 */
private void exportDocumentationToFileSystem(Set<DocumentInfo> documentInfo, APIDetails apiDetails, String exportLocation) {
    if (documentInfo == null || documentInfo.isEmpty()) {
        log.debug("No documentation found for API with api: " + apiDetails.getApi().getName() + ", " + "version: " + apiDetails.getApi().getVersion());
        return;
    }
    // create Documents root directory
    String documentsBaseDirectory = exportLocation + File.separator + DOCUMENTS_ROOT_DIRECTORY;
    try {
        APIFileUtils.createDirectory(documentsBaseDirectory);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        for (DocumentInfo aDocumentInfo : documentInfo) {
            // create the root directory for each document
            String apiExportDir = documentsBaseDirectory + File.separator + aDocumentInfo.getId();
            APIFileUtils.createDirectory(apiExportDir);
            // for each document, write a DocumentInfo to a separate json file
            String apiDocMetaFileLocation = apiExportDir + File.separator + DOCUMENTATION_DEFINITION_FILE;
            APIFileUtils.createFile(apiDocMetaFileLocation);
            APIFileUtils.writeToFile(apiDocMetaFileLocation, gson.toJson(aDocumentInfo));
            // if the document's SourceType is FILE, retrieve and write the content to a file
            DocumentContent content;
            if (aDocumentInfo.getSourceType().equals(DocumentInfo.SourceType.FILE)) {
                content = apiDetails.getDocumentContent(aDocumentInfo.getId());
                if (content != null) {
                    APIFileUtils.createFile(apiExportDir + File.separator + content.getDocumentInfo().getFileName());
                    APIFileUtils.writeStreamToFile(apiExportDir + File.separator + content.getDocumentInfo().getFileName(), content.getFileContent());
                    // modify the document metadata to contain the file name
                    DocumentInfo modifiedDocInfo = new DocumentInfo.Builder(aDocumentInfo).fileName(content.getDocumentInfo().getFileName()).build();
                    APIFileUtils.writeToFile(apiDocMetaFileLocation, gson.toJson(modifiedDocInfo));
                }
            } else if (aDocumentInfo.getSourceType().equals(DocumentInfo.SourceType.INLINE)) {
                content = apiDetails.getDocumentContent(aDocumentInfo.getId());
                if (content != null) {
                    APIFileUtils.createFile(apiExportDir + File.separator + content.getDocumentInfo().getName());
                    APIFileUtils.writeToFile(apiExportDir + File.separator + content.getDocumentInfo().getName(), content.getInlineContent());
                    // modify the document metadata to contain the inline content name
                    DocumentInfo modifiedDocInfo = new DocumentInfo.Builder(aDocumentInfo).name(content.getDocumentInfo().getName()).build();
                    APIFileUtils.writeToFile(apiDocMetaFileLocation, gson.toJson(modifiedDocInfo));
                }
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error in exporting documents to file system for api: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion());
        // cleanup
        try {
            APIFileUtils.deleteDirectory(path);
        } catch (APIMgtDAOException ignore) {
            log.warn("Unable to remove directory " + path);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully exported documentation for api: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion());
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) GsonBuilder(com.google.gson.GsonBuilder) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) GsonBuilder(com.google.gson.GsonBuilder) Gson(com.google.gson.Gson) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 17 with DocumentContent

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

the class ApiImportExportManager method updateAPIDetails.

/**
 * Updates the API details
 *
 * @param apiDetails {@link APIDetails} instance
 * @throws APIManagementException if an error occurs while updating API details
 */
void updateAPIDetails(APIDetails apiDetails) throws APIManagementException {
    // update everything
    String swaggerDefinition = apiDetails.getSwaggerDefinition();
    String gatewayConfig = apiDetails.getGatewayConfiguration();
    Map<String, Endpoint> endpointTypeToIdMap = new HashMap<>();
    // endpoints
    for (Endpoint endpoint : apiDetails.getEndpoints()) {
        try {
            apiPublisher.updateEndpoint(endpoint);
            endpointTypeToIdMap.put(endpoint.getType(), endpoint);
        } catch (APIManagementException e) {
            // skip updating this API, log and continue
            log.error("Error while updating the endpoint with id: " + endpoint.getId() + ", type: " + endpoint.getType() + " for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion());
        }
    }
    API.APIBuilder apiBuilder = new API.APIBuilder(apiDetails.getApi());
    apiPublisher.updateAPI(apiBuilder.apiDefinition(swaggerDefinition).gatewayConfig(gatewayConfig).endpoint(endpointTypeToIdMap));
    // docs
    try {
        Set<DocumentInfo> documentInfo = apiDetails.getAllDocumentInformation();
        for (DocumentInfo aDocInfo : documentInfo) {
            apiPublisher.updateDocumentation(aDocInfo.getId(), aDocInfo);
        }
        Collection<DocumentContent> docContents = apiDetails.getDocumentContents();
        for (DocumentContent docContent : docContents) {
            // update documentation
            if (docContent.getDocumentInfo().getSourceType().equals(DocumentInfo.SourceType.FILE)) {
                apiPublisher.uploadDocumentationFile(docContent.getDocumentInfo().getId(), docContent.getFileContent(), URLConnection.guessContentTypeFromStream(docContent.getFileContent()));
            } else if (docContent.getDocumentInfo().getSourceType().equals(DocumentInfo.SourceType.INLINE)) {
                apiPublisher.addDocumentationContent(docContent.getDocumentInfo().getId(), docContent.getInlineContent());
            }
        }
    } catch (APIManagementException e) {
        // no need to throw, log and continue
        log.error("Error while adding Document details for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
    } catch (IOException e) {
        // no need to throw, log and continue
        log.error("Error while retrieving content type of the File documentation of API : " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
    }
    // update thumbnail
    try {
        apiPublisher.saveThumbnailImage(apiDetails.getApi().getId(), apiDetails.getThumbnailStream(), "thumbnail");
    } catch (APIManagementException e) {
        // no need to throw, log and continue
        log.error("Error while updating thumbnail for API: " + apiDetails.getApi().getName() + ", version: " + apiDetails.getApi().getVersion(), e);
    }
}
Also used : HashMap(java.util.HashMap) IOException(java.io.IOException) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) API(org.wso2.carbon.apimgt.core.models.API) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 18 with DocumentContent

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

the class ApiImportExportManager method getAPIDetails.

/**
 * Retrieves all API details of the APIs for the given search query. API details consist of:
 *      1. API {@link org.wso2.carbon.apimgt.core.models.API}
 *      2. Document Info {@link org.wso2.carbon.apimgt.core.models.DocumentInfo}
 *      3. Document Content {@link org.wso2.carbon.apimgt.core.models.DocumentContent}
 *      4. Swagger Definition
 *      5. Gateway Definition
 *      6. Thumbnail content
 *
 * @param limit number of max results
 * @param offset starting location when returning a limited set of results
 * @param query searchQuery
 * @return {@link APIDetails} instance
 * @throws APIManagementException if an error occurs while retrieving API details
 */
public Set<APIDetails> getAPIDetails(Integer limit, Integer offset, String query) throws APIManagementException {
    Set<APIDetails> apiDetailSet = new HashSet<>();
    // search for APIs
    List<API> apis = apiPublisher.searchAPIs(limit, offset, query);
    if (apis == null || apis.isEmpty()) {
        // no APIs found, return
        return apiDetailSet;
    }
    // iterate and collect all information
    for (API api : apis) {
        api = apiPublisher.getAPIbyUUID(api.getId());
        // get endpoints at API Level
        Map<String, Endpoint> endpoints = api.getEndpoint();
        if (endpoints.isEmpty()) {
            log.error("No Endpoints found for api: " + api.getName() + ", version: " + api.getVersion());
        // skip this API
        // continue;
        }
        Set<Endpoint> endpointSet = new HashSet<>();
        for (Map.Entry<String, Endpoint> endpointEntry : endpoints.entrySet()) {
            if (APIMgtConstants.GLOBAL_ENDPOINT.equals(endpointEntry.getValue().getApplicableLevel())) {
                Endpoint endpoint = new Endpoint.Builder(apiPublisher.getEndpoint(endpointEntry.getValue().getId())).id("").build();
                endpoints.replace(endpointEntry.getKey(), endpoint);
                endpointSet.add(endpoint);
            }
        }
        // get Endpoints at Resource Level
        Map<String, UriTemplate> uriTemplateMap = api.getUriTemplates();
        uriTemplateMap.forEach((k, v) -> {
            UriTemplate.UriTemplateBuilder uriTemplateBuilder = new UriTemplate.UriTemplateBuilder(v);
            Map<String, Endpoint> resourceEndpoints = uriTemplateBuilder.getEndpoint();
            resourceEndpoints.forEach((type, value) -> {
                Endpoint endpoint = null;
                if (APIMgtConstants.GLOBAL_ENDPOINT.equals(value.getApplicableLevel())) {
                    try {
                        endpoint = new Endpoint.Builder(apiPublisher.getEndpoint(value.getId())).id("").build();
                        endpointSet.add(endpoint);
                    } catch (APIManagementException e) {
                        log.error("Error in getting endpoints for Resource: " + v.getTemplateId(), e);
                    }
                } else {
                    endpoint = new Endpoint.Builder(value).id("").build();
                }
                resourceEndpoints.replace(type, endpoint);
            });
            uriTemplateMap.replace(k, uriTemplateBuilder.endpoint(resourceEndpoints).build());
        });
        api = new API.APIBuilder(api).endpoint(endpoints).uriTemplates(uriTemplateMap).build();
        // get swagger definition
        String swaggerDefinition;
        try {
            swaggerDefinition = apiPublisher.getApiSwaggerDefinition(api.getId());
        } catch (APIManagementException e) {
            log.error("Error in getting Swagger configuration for api: " + api.getName() + ", version: " + api.getVersion(), e);
            // skip this API
            continue;
        }
        // get gateway configuration
        String gatewayConfig;
        try {
            gatewayConfig = apiPublisher.getApiGatewayConfig(api.getId());
        } catch (APIManagementException e) {
            log.error("Error in getting gateway configuration for api: " + api.getName() + ", version: " + api.getVersion(), e);
            // skip this API
            continue;
        }
        // get doc information
        List<DocumentInfo> documentInfo = null;
        try {
            documentInfo = apiPublisher.getAllDocumentation(api.getId(), 0, Integer.MAX_VALUE);
        } catch (APIManagementException e) {
            log.error("Error in getting documentation content for api: " + api.getName() + ", version: " + api.getVersion(), e);
        // no need to skip the API as docs don't affect API functionality
        }
        Set<DocumentContent> documentContents = new HashSet<>();
        if (documentInfo != null && !documentInfo.isEmpty()) {
            // iterate and collect document content
            for (DocumentInfo aDocumentInfo : documentInfo) {
                try {
                    documentContents.add(apiPublisher.getDocumentationContent(aDocumentInfo.getId()));
                } catch (APIManagementException e) {
                    log.error("Error in getting documentation content for api: " + api.getName() + ", version: " + api.getVersion() + ", doc id: " + aDocumentInfo.getId(), e);
                // no need to skip the API as docs don't affect API functionality
                }
            }
        }
        // get thumbnail
        InputStream thumbnailStream = null;
        try {
            thumbnailStream = apiPublisher.getThumbnailImage(api.getId());
        } catch (APIManagementException e) {
            log.error("Error in getting thumbnail for api: " + api.getName() + ", version: " + api.getVersion(), e);
        // no need to skip the API as thumbnail don't affect API functionality
        }
        // search operation returns a summary of APIs, need to get all details of APIs
        APIDetails apiDetails = new APIDetails(api, swaggerDefinition);
        apiDetails.setGatewayConfiguration(gatewayConfig);
        apiDetails.setEndpoints(endpointSet);
        if (documentInfo != null && !documentInfo.isEmpty()) {
            apiDetails.addDocumentInformation(documentInfo);
        }
        if (!documentContents.isEmpty()) {
            apiDetails.addDocumentContents(documentContents);
        }
        if (thumbnailStream != null) {
            apiDetails.setThumbnailStream(thumbnailStream);
        }
        apiDetailSet.add(apiDetails);
    }
    return apiDetailSet;
}
Also used : InputStream(java.io.InputStream) APIDetails(org.wso2.carbon.apimgt.core.models.APIDetails) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 19 with DocumentContent

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

the class ApisApiServiceImplTestCase method testApisApiIdDocumentsDocumentIdContentGetFile.

@Test
public void testApisApiIdDocumentsDocumentIdContentGetFile() throws Exception {
    String fileName = "mytext.txt";
    printTestMethodName();
    ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
    APIPublisher apiPublisher = Mockito.mock(APIPublisherImpl.class);
    PowerMockito.mockStatic(RestAPIPublisherUtil.class);
    PowerMockito.when(RestAPIPublisherUtil.getApiPublisher(USER)).thenReturn(apiPublisher);
    String api1Id = UUID.randomUUID().toString();
    String documentId = UUID.randomUUID().toString();
    DocumentInfo documentInfo = SampleTestObjectCreator.createDefaultDocumentationInfo().sourceType(DocumentInfo.SourceType.FILE).fileName(fileName).build();
    DocumentContent documentContent = DocumentContent.newDocumentContent().documentInfo(documentInfo).build();
    Mockito.doReturn(documentContent).doThrow(new IllegalArgumentException()).when(apiPublisher).getDocumentationContent(documentId);
    Response response = apisApiService.apisApiIdDocumentsDocumentIdContentGet(api1Id, documentId, null, null, getRequest());
    assertEquals(response.getStatus(), 200);
    assertTrue(response.getStringHeaders().get("Content-Disposition").toString().contains(fileName));
}
Also used : WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Response(javax.ws.rs.core.Response) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 20 with DocumentContent

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

the class ApisApiServiceImplTestCase method testApisApiIdDocumentsDocumentIdContentGetInline.

@Test
public void testApisApiIdDocumentsDocumentIdContentGetInline() throws Exception {
    String inlineContent = "INLINE CONTENT";
    printTestMethodName();
    ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
    APIPublisher apiPublisher = Mockito.mock(APIPublisherImpl.class);
    PowerMockito.mockStatic(RestAPIPublisherUtil.class);
    PowerMockito.when(RestAPIPublisherUtil.getApiPublisher(USER)).thenReturn(apiPublisher);
    String api1Id = UUID.randomUUID().toString();
    String documentId = UUID.randomUUID().toString();
    DocumentInfo documentInfo = SampleTestObjectCreator.createDefaultDocumentationInfo().build();
    DocumentContent documentContent = DocumentContent.newDocumentContent().inlineContent(inlineContent).documentInfo(documentInfo).build();
    Mockito.doReturn(documentContent).doThrow(new IllegalArgumentException()).when(apiPublisher).getDocumentationContent(documentId);
    Response response = apisApiService.apisApiIdDocumentsDocumentIdContentGet(api1Id, documentId, null, null, getRequest());
    assertEquals(response.getStatus(), 200);
    assertEquals(inlineContent, response.getEntity().toString());
}
Also used : WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Response(javax.ws.rs.core.Response) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

DocumentContent (org.wso2.carbon.apimgt.core.models.DocumentContent)16 DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)16 API (org.wso2.carbon.apimgt.core.models.API)9 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)9 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)7 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)7 APIDetails (org.wso2.carbon.apimgt.core.models.APIDetails)7 HashMap (java.util.HashMap)5 ArrayList (java.util.ArrayList)4 HashSet (java.util.HashSet)4 Test (org.testng.annotations.Test)4 DocumentationPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException)4 InputStream (java.io.InputStream)3 Response (javax.ws.rs.core.Response)3 Test (org.junit.Test)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)3 DocumentContent (org.wso2.carbon.apimgt.persistence.dto.DocumentContent)3 IOException (java.io.IOException)2