Search in sources :

Example 1 with FileBasedApiImportExportManager

use of org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager in project carbon-apimgt by wso2.

the class APIImportExportTestCase method testApiExport.

private void testApiExport(String exportDir) throws Exception {
    String api1Id = UUID.randomUUID().toString();
    Endpoint api1SandBoxEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("abcd").build();
    Endpoint api1ProdEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("cdef").build();
    API api1 = createApi("provider1", api1Id, "testapi1", "1.0.0", "Test API 1 - version 1.0.0", createEndpointTypeToIdMap(api1SandBoxEndpointId, api1ProdEndpointId)).build();
    String api1Doc1Id = UUID.randomUUID().toString();
    DocumentInfo api1Doc1Info = createAPIDoc(api1Doc1Id, "api1doc1", "", "API 1 DOC 1", DocumentInfo.DocType.HOWTO, "other type", DocumentInfo.SourceType.INLINE, "", DocumentInfo.Visibility.PRIVATE);
    String api1Doc2Id = UUID.randomUUID().toString();
    DocumentInfo api1Doc2Info = createAPIDoc(api1Doc2Id, "api1doc2.pdf", "api1doc2.pdf", "API 1 DOC 2", DocumentInfo.DocType.PUBLIC_FORUM, "other type", DocumentInfo.SourceType.FILE, "", DocumentInfo.Visibility.API_LEVEL);
    String api1Doc3Id = UUID.randomUUID().toString();
    DocumentInfo api1Doc3Info = createAPIDoc(api1Doc3Id, "api1doc3", "", "API 1 DOC 3", DocumentInfo.DocType.OTHER, "other type", DocumentInfo.SourceType.OTHER, "", DocumentInfo.Visibility.API_LEVEL);
    Set<DocumentInfo> api1DocumentInfo = new HashSet<>();
    api1DocumentInfo.add(api1Doc1Info);
    api1DocumentInfo.add(api1Doc2Info);
    api1DocumentInfo.add(api1Doc3Info);
    // contents for documents
    DocumentContent api1Doc1Content = createDocContent(api1Doc1Info, "Sample inline content for API1 DOC 1", null);
    DocumentContent api1Doc2Content = createDocContent(api1Doc2Info, "", api1Doc2Stream);
    DocumentContent api1Doc3Content = createDocContent(api1Doc3Info, "", null);
    Set<DocumentContent> api1DocContent = new HashSet<>();
    api1DocContent.add(api1Doc1Content);
    api1DocContent.add(api1Doc2Content);
    api1DocContent.add(api1Doc3Content);
    APIDetails api1Details = new APIDetails(api1, api1Definition);
    api1Details.setGatewayConfiguration(api1GatewayConfig);
    api1Details.addDocumentInformation(api1DocumentInfo);
    api1Details.addDocumentContents(api1DocContent);
    api1Details.setThumbnailStream(getClass().getClassLoader().getResourceAsStream("api1_thumbnail.png"));
    Endpoint api1SandboxEndpoint = createEndpoint(api1SandBoxEndpointId.getId(), "api1SandBoxEndpoint", "SANDBOX", "{'type':'http','url':'http://localhost:8280'}", "{'enabled':'true','type':'basic','properties':{'username':'admin','password':'admin'}}", 10l);
    Endpoint api1ProdEndpoint = createEndpoint(api1ProdEndpointId.getId(), "api1ProdEndpoint", "PRODUCTION", "{'type':'http','url':'http://localhost:8280'}", "{'enabled':'true','type':'basic','properties':{'username':'admin','password':'admin'}}", 10l);
    api1Details.addEndpoint(api1SandboxEndpoint);
    api1Details.addEndpoint(api1ProdEndpoint);
    String api2Id = UUID.randomUUID().toString();
    Endpoint api2SandBoxEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("abcd").build();
    Endpoint api2ProdEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("cdef").build();
    API api2 = createApi("provider2", api2Id, "testapi2", "3.0.0", "Test API 2 - version 3.0.0", createEndpointTypeToIdMap(api2SandBoxEndpointId, api2ProdEndpointId)).build();
    List<API> apis = new ArrayList<>();
    apis.add(api1);
    apis.add(api2);
    String api2Doc1Id = UUID.randomUUID().toString();
    DocumentInfo api2Doc1Info = createAPIDoc(api2Doc1Id, "api2doc1", "", "API 2 DOC 1", DocumentInfo.DocType.API_MESSAGE_FORMAT, "other type", DocumentInfo.SourceType.INLINE, "", DocumentInfo.Visibility.API_LEVEL);
    String api2Doc2Id = UUID.randomUUID().toString();
    DocumentInfo api2Doc2Info = createAPIDoc(api2Doc2Id, "api2doc2", "", "API 2 DOC 2", DocumentInfo.DocType.PUBLIC_FORUM, "other type", DocumentInfo.SourceType.URL, "http://api2.org/documentation/1", DocumentInfo.Visibility.PRIVATE);
    Set<DocumentInfo> api2DocumentInfo = new HashSet<>();
    api2DocumentInfo.add(api2Doc1Info);
    api2DocumentInfo.add(api2Doc2Info);
    DocumentContent api2Doc1Content = createDocContent(api2Doc1Info, "Sample inline content for API2 DOC 1", null);
    DocumentContent api2Doc2Content = createDocContent(api2Doc2Info, "", null);
    Set<DocumentContent> api2DocContent = new HashSet<>();
    api2DocContent.add(api2Doc1Content);
    api2DocContent.add(api2Doc2Content);
    APIDetails api2Details = new APIDetails(api2, api2Definition);
    api2Details.setGatewayConfiguration(api2GatewayConfig);
    api2Details.addDocumentInformation(api2DocumentInfo);
    api2Details.addDocumentContents(api2DocContent);
    api2Details.setThumbnailStream(getClass().getClassLoader().getResourceAsStream("api2_thumbnail.jpg"));
    Endpoint api2SandboxEndpoint = createEndpoint(api2SandBoxEndpointId.getId(), "api2SandBoxEndpoint", "SANDBOX", "{'type':'http','url':'http://localhost:8280'}", "{'enabled':'true','type':'basic','properties':{'username':'admin','password':'admin'}}", 20l);
    Endpoint api2ProdEndpoint = createEndpoint(api2ProdEndpointId.getId(), "api2ProdEndpoint", "PRODUCTION", "{'type':'http','url':'http://localhost:8280'}", "{'enabled':'true','type':'basic','properties':{'username':'admin','password':'admin'}}", 20l);
    api2Details.addEndpoint(api2SandboxEndpoint);
    api2Details.addEndpoint(api2ProdEndpoint);
    Set<APIDetails> apiDetailsSet = new HashSet<>();
    apiDetailsSet.add(api1Details);
    apiDetailsSet.add(api2Details);
    // mock the method calls for retrieving APIs
    Mockito.when(apiPublisher.getAPIbyUUID(api1Id)).thenReturn(api1);
    Mockito.when(apiPublisher.getAPIbyUUID(api2Id)).thenReturn(api2);
    // export
    FileBasedApiImportExportManager importExportManager = new FileBasedApiImportExportManager(apiPublisher, exportDir);
    String exportedApiDirName = "exported-apis";
    String exportedApiDirPath = importExportManager.exportAPIs(apiDetailsSet, exportedApiDirName);
    String exportedApiArchiveFilePath = importExportManager.createArchiveFromExportedApiArtifacts(exportedApiDirPath, exportDir, exportedApiDirName);
    // check if two APIs are written to the file system
    String unzipPath = importExportRootDirectory + File.separator + "unzipped-export-archive";
    APIFileUtils.extractArchive(exportedApiArchiveFilePath, unzipPath);
    Assert.assertEquals(APIFileUtils.getDirectoryList(unzipPath).size() == 2, true, "Exported API count is not equal to 2");
    Mockito.when(apiPublisher.isAPIExists(api2Id)).thenReturn(true);
}
Also used : APIDetails(org.wso2.carbon.apimgt.core.models.APIDetails) ArrayList(java.util.ArrayList) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) API(org.wso2.carbon.apimgt.core.models.API) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo) HashSet(java.util.HashSet)

Example 2 with FileBasedApiImportExportManager

use of org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager in project carbon-apimgt by wso2.

the class ExportApiServiceImpl method exportApisGet.

/**
 * Exports an existing API
 *
 * @param query       Search query
 * @param limit       maximum APIs to export
 * @param offset      Starting position of the search
 * @param request     ms4j request object
 * @return Zip file containing the exported APIs
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response exportApisGet(String query, Integer limit, Integer offset, Request request) throws NotFoundException {
    APIPublisher publisher = null;
    String exportedFilePath, zippedFilePath = null;
    Set<APIDetails> apiDetails;
    String exportedApiDirName = "exported-apis";
    String pathToExportDir = System.getProperty("java.io.tmpdir") + File.separator + "exported-api-archives-" + UUID.randomUUID().toString();
    try {
        publisher = RestAPIPublisherUtil.getApiPublisher(RestApiUtil.getLoggedInUsername(request));
        FileBasedApiImportExportManager importExportManager = new FileBasedApiImportExportManager(publisher, pathToExportDir);
        apiDetails = importExportManager.getAPIDetails(limit, offset, query);
        if (apiDetails.isEmpty()) {
            // 404
            String errorMsg = "No APIs found for query " + query;
            log.error(errorMsg);
            HashMap<String, String> paramList = new HashMap<>();
            paramList.put("query", query);
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(ExceptionCodes.API_NOT_FOUND, paramList);
            return Response.status(Response.Status.NOT_FOUND).entity(errorDTO).build();
        }
        exportedFilePath = importExportManager.exportAPIs(apiDetails, exportedApiDirName);
        zippedFilePath = importExportManager.createArchiveFromExportedApiArtifacts(exportedFilePath, pathToExportDir, exportedApiDirName);
    } catch (APIManagementException e) {
        String errorMessage = "Error while exporting APIs";
        log.error(errorMessage, e);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
    File exportedApiArchiveFile = new File(zippedFilePath);
    Response.ResponseBuilder responseBuilder = Response.status(Response.Status.OK).entity(exportedApiArchiveFile);
    responseBuilder.header("Content-Disposition", "attachment; filename=\"" + exportedApiArchiveFile.getName() + "\"");
    Response response = responseBuilder.build();
    return response;
}
Also used : Response(javax.ws.rs.core.Response) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) APIDetails(org.wso2.carbon.apimgt.core.models.APIDetails) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) FileBasedApiImportExportManager(org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager) File(java.io.File)

Example 3 with FileBasedApiImportExportManager

use of org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager in project carbon-apimgt by wso2.

the class ImportApiServiceImpl method importApisPut.

/**
 * Imports an updates a set of existing APIs which have been exported as a zip file
 *
 * @param fileInputStream content stream of the zip file which contains exported API(s)
 * @param fileDetail      meta information of the zip file
 * @param provider        provider of the API (if it needs to be updated)
 * @param request         ms4j request object
 * @return List of APIs that were imported
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response importApisPut(InputStream fileInputStream, FileInfo fileDetail, String provider, Request request) throws NotFoundException {
    APIPublisher publisher = null;
    try {
        publisher = RestAPIPublisherUtil.getApiPublisher(RestApiUtil.getLoggedInUsername(request));
        FileBasedApiImportExportManager importManager = new FileBasedApiImportExportManager(publisher, System.getProperty("java.io.tmpdir") + File.separator + "imported-api-archives-" + UUID.randomUUID().toString());
        APIListDTO apiList = importManager.importAPIs(fileInputStream, provider);
        return Response.status(Response.Status.OK).entity(apiList).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while importing the APIs";
        log.error(errorMessage, e);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) APIListDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIListDTO) FileBasedApiImportExportManager(org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager)

Example 4 with FileBasedApiImportExportManager

use of org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager in project carbon-apimgt by wso2.

the class ImportApiServiceImpl method importApisPost.

/**
 * Imports a set of new APIs which have been exported as a zip file
 *
 * @param fileInputStream content stream of the zip file which contains exported API(s)
 * @param fileDetail      meta information of the zip file
 * @param provider        provider of the API (if it needs to be updated)
 * @param request         ms4j request object
 * @return List of APIs that were imported
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response importApisPost(InputStream fileInputStream, FileInfo fileDetail, String provider, Request request) throws NotFoundException {
    APIPublisher publisher = null;
    try {
        publisher = RestAPIPublisherUtil.getApiPublisher(RestApiUtil.getLoggedInUsername(request));
        FileBasedApiImportExportManager importManager = new FileBasedApiImportExportManager(publisher, System.getProperty("java.io.tmpdir") + File.separator + "imported-api-archives-" + UUID.randomUUID().toString());
        APIListDTO apiList = importManager.importAndCreateAPIs(fileInputStream, provider);
        return Response.status(Response.Status.OK).entity(apiList).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while importing the APIs";
        log.error(errorMessage, e);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) APIListDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIListDTO) FileBasedApiImportExportManager(org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager)

Example 5 with FileBasedApiImportExportManager

use of org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager in project carbon-apimgt by wso2.

the class FileBasedApiImportExportManager method exportAPIs.

/**
 * Export a given set of APIs to the file system as a zip archive.
 * The export root location is given by {@link FileBasedApiImportExportManager#path}/exported-apis.
 *
 * @param apiDetailSet        Set of {@link APIDetails} objects to be exported
 * @param exportDirectoryName Name of the directory to do the export
 * @return Path to the directory  with exported artifacts
 * @throws APIMgtEntityImportExportException if an error occurred while exporting APIs to file system or
 *                                           no APIs are exported successfully
 */
public String exportAPIs(Set<APIDetails> apiDetailSet, String exportDirectoryName) throws APIMgtEntityImportExportException {
    // this is the base directory for the archive. after export happens, this directory will
    // be archived to be sent as a application/zip response to the client
    String apiArtifactsBaseDirectoryPath = path + File.separator + exportDirectoryName;
    try {
        APIFileUtils.createDirectory(apiArtifactsBaseDirectoryPath);
    } catch (APIMgtDAOException e) {
        String errorMsg = "Unable to create directory for export API at :" + apiArtifactsBaseDirectoryPath;
        throw new APIMgtEntityImportExportException(errorMsg, e);
    }
    for (APIDetails apiDetails : apiDetailSet) {
        // derive the folder structure
        String apiExportDirectory = APIFileUtils.getAPIBaseDirectory(apiArtifactsBaseDirectoryPath, new FileApi(apiDetails.getApi()));
        API exportAPI = apiDetails.getApi();
        try {
            // create per-api export directory
            APIFileUtils.createDirectory(apiExportDirectory);
            // export API definition
            APIFileUtils.exportApiDefinitionToFileSystem(new FileApi(exportAPI), apiExportDirectory);
            // export swagger definition
            APIFileUtils.exportSwaggerDefinitionToFileSystem(apiDetails.getSwaggerDefinition(), exportAPI, apiExportDirectory);
            // export gateway configs
            APIFileUtils.exportGatewayConfigToFileSystem(apiDetails.getGatewayConfiguration(), exportAPI, apiExportDirectory);
            if (apiDetails.getEndpoints() != null && !apiDetails.getEndpoints().isEmpty()) {
                exportEndpointsToFileSystem(apiDetails.getEndpoints(), exportAPI, apiExportDirectory);
            }
        } catch (APIMgtDAOException e) {
            // no need to throw, log
            log.error("Error in exporting API: " + exportAPI.getName() + ", version: " + apiDetails.getApi().getVersion(), e);
            // cleanup the API directory
            try {
                APIFileUtils.deleteDirectory(path);
            } catch (APIMgtDAOException e1) {
                log.warn("Unable to remove directory " + path);
            }
            // skip this API
            continue;
        }
        // as exported correctly.
        if (apiDetails.getThumbnailStream() != null) {
            try {
                APIFileUtils.exportThumbnailToFileSystem(apiDetails.getThumbnailStream(), apiExportDirectory);
            } catch (APIMgtDAOException warn) {
                // log the warning without throwing
                log.warn("Error in exporting thumbnail to file system for api: " + exportAPI.getName() + ", version: " + exportAPI.getVersion());
            }
        }
        exportDocumentationToFileSystem(apiDetails.getAllDocumentInformation(), apiDetails, apiExportDirectory);
        log.info("Successfully exported API: " + exportAPI.getName() + ", version: " + exportAPI.getVersion());
    }
    // if the directory is empty, no APIs have been exported!
    try {
        if (APIFileUtils.getDirectoryList(apiArtifactsBaseDirectoryPath).isEmpty()) {
            // cleanup the archive root directory
            APIFileUtils.deleteDirectory(path);
            String errorMsg = "No APIs exported successfully";
            throw new APIMgtEntityImportExportException(errorMsg, ExceptionCodes.API_EXPORT_ERROR);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Unable to find API definitions at: " + apiArtifactsBaseDirectoryPath;
        log.error(errorMsg, e);
        throw new APIMgtEntityImportExportException(errorMsg, ExceptionCodes.API_IMPORT_ERROR);
    }
    return apiArtifactsBaseDirectoryPath;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIDetails(org.wso2.carbon.apimgt.core.models.APIDetails) API(org.wso2.carbon.apimgt.core.models.API) APIMgtEntityImportExportException(org.wso2.carbon.apimgt.core.exception.APIMgtEntityImportExportException) FileApi(org.wso2.carbon.apimgt.core.models.FileApi)

Aggregations

APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)3 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)3 APIDetails (org.wso2.carbon.apimgt.core.models.APIDetails)3 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)3 FileBasedApiImportExportManager (org.wso2.carbon.apimgt.rest.api.publisher.utils.FileBasedApiImportExportManager)3 API (org.wso2.carbon.apimgt.core.models.API)2 APIListDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.APIListDTO)2 File (java.io.File)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Response (javax.ws.rs.core.Response)1 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)1 APIMgtEntityImportExportException (org.wso2.carbon.apimgt.core.exception.APIMgtEntityImportExportException)1 DocumentContent (org.wso2.carbon.apimgt.core.models.DocumentContent)1 DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)1 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)1 FileApi (org.wso2.carbon.apimgt.core.models.FileApi)1