Search in sources :

Example 21 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class ApiProductsApiServiceImpl method exportAPIProduct.

/**
 * Exports an API Product from API Manager. Meta information, API Product icon, documentation, client certificates
 * and dependent APIs are exported. This service generates a zipped archive which contains all the above mentioned
 * resources for a given API Product.
 *
 * @param name           Name of the API Product that needs to be exported
 * @param version        Version of the API Product that needs to be exported
 * @param providerName   Provider name of the API Product that needs to be exported
 * @param format         Format of output documents. Can be YAML or JSON
 * @param preserveStatus Preserve API Product status on export
 * @param messageContext Message Context
 * @return Zipped file containing exported API Product
 * @throws APIManagementException
 */
@Override
public Response exportAPIProduct(String name, String version, String providerName, String revisionNumber, String format, Boolean preserveStatus, Boolean exportLatestRevision, MessageContext messageContext) throws APIManagementException {
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    // If not specified status is preserved by default
    preserveStatus = preserveStatus == null || preserveStatus;
    // Default export format is YAML
    ExportFormat exportFormat = StringUtils.isNotEmpty(format) ? ExportFormat.valueOf(format.toUpperCase()) : ExportFormat.YAML;
    ImportExportAPI importExportAPI = APIImportExportUtil.getImportExportAPI();
    try {
        File file = importExportAPI.exportAPIProduct(null, name, version, providerName, revisionNumber, exportFormat, preserveStatus, true, true, exportLatestRevision, organization);
        return Response.ok(file).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"").build();
    } catch (APIImportExportException e) {
        throw new APIManagementException("Error while exporting " + RestApiConstants.RESOURCE_API_PRODUCT, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) ExportFormat(org.wso2.carbon.apimgt.impl.importexport.ExportFormat) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 22 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class CommonUtil method extractArchive.

/**
 * This method decompresses API the archive.
 *
 * @param sourceFile  The archive containing the API
 * @param destination location of the archive to be extracted
 * @return Name of the extracted directory
 * @throws APIImportExportException If the decompressing fails
 */
public static String extractArchive(File sourceFile, String destination) throws APIImportExportException {
    String archiveName = null;
    try (ZipFile zip = new ZipFile(sourceFile)) {
        Enumeration zipFileEntries = zip.entries();
        int index = 0;
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            // This index variable is used to get the extracted folder name; that is root directory
            if (index == 0) {
                archiveName = currentEntry.substring(0, currentEntry.indexOf(ImportExportConstants.ZIP_FILE_SEPARATOR));
                --index;
            }
            File destinationFile = new File(destination, currentEntry);
            File destinationParent = destinationFile.getParentFile();
            String canonicalizedDestinationFilePath = destinationFile.getCanonicalPath();
            if (!canonicalizedDestinationFilePath.startsWith(new File(destination).getCanonicalPath())) {
                String errorMessage = "Attempt to upload invalid zip archive with file at " + currentEntry + ". File path is outside target directory";
                throw new APIImportExportException(errorMessage);
            }
            // create the parent directory structure
            if (destinationParent.mkdirs()) {
                log.info("Creation of folder is successful. Directory Name : " + destinationParent.getName());
            }
            if (!entry.isDirectory()) {
                // write the current file to the destination
                try (InputStream zipInputStream = zip.getInputStream(entry);
                    BufferedInputStream inputStream = new BufferedInputStream(zipInputStream);
                    FileOutputStream outputStream = new FileOutputStream(destinationFile)) {
                    IOUtils.copy(inputStream, outputStream);
                }
            }
        }
        return archiveName;
    } catch (IOException e) {
        String errorMessage = "Failed to extract the archive (zip) file. ";
        throw new APIImportExportException(errorMessage, e);
    }
}
Also used : Enumeration(java.util.Enumeration) ZipFile(java.util.zip.ZipFile) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ZipEntry(java.util.zip.ZipEntry) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) ZipFile(java.util.zip.ZipFile) File(java.io.File)

Example 23 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class RuntimeArtifactGeneratorUtil method generateMetadataArtifact.

public static RuntimeArtifactDto generateMetadataArtifact(String tenantDomain, String apiId, String gatewayLabel) throws APIManagementException {
    List<APIRuntimeArtifactDto> gatewayArtifacts = getRuntimeArtifacts(apiId, gatewayLabel, tenantDomain);
    if (gatewayArtifacts != null) {
        try {
            MetadataDescriptorDto metadataDescriptorDto = new MetadataDescriptorDto();
            Map<String, ApiMetadataProjectDto> deploymentsMap = new HashMap<>();
            // "tempDirectory" is the root artifact directory
            File tempDirectory = CommonUtil.createTempDirectory(null);
            for (APIRuntimeArtifactDto apiRuntimeArtifactDto : gatewayArtifacts) {
                if (apiRuntimeArtifactDto.isFile()) {
                    String fileName = apiRuntimeArtifactDto.getApiId().concat("-").concat(apiRuntimeArtifactDto.getRevision());
                    ApiMetadataProjectDto apiProjectDto = deploymentsMap.get(fileName);
                    if (apiProjectDto == null) {
                        apiProjectDto = new ApiMetadataProjectDto();
                        deploymentsMap.put(fileName, apiProjectDto);
                        apiProjectDto.setApiFile(fileName);
                        apiProjectDto.setEnvironments(new HashSet<>());
                        apiProjectDto.setOrganizationId(apiRuntimeArtifactDto.getOrganization());
                        apiProjectDto.setVersion(apiRuntimeArtifactDto.getVersion());
                        apiProjectDto.setApiContext(apiRuntimeArtifactDto.getContext());
                    }
                    EnvironmentDto environment = new EnvironmentDto();
                    environment.setName(apiRuntimeArtifactDto.getLabel());
                    environment.setVhost(apiRuntimeArtifactDto.getVhost());
                    apiProjectDto.getEnvironments().add(environment);
                }
            }
            metadataDescriptorDto.setMetadataDescriptor(new HashSet<>(deploymentsMap.values()));
            String descriptorFile = Paths.get(tempDirectory.getAbsolutePath(), APIConstants.GatewayArtifactConstants.DEPLOYMENT_DESCRIPTOR_FILE).toString();
            CommonUtil.writeDtoToFile(descriptorFile, ExportFormat.JSON, APIConstants.GatewayArtifactConstants.DEPLOYMENT_DESCRIPTOR_FILE_TYPE, metadataDescriptorDto);
            RuntimeArtifactDto runtimeArtifactDto = new RuntimeArtifactDto();
            runtimeArtifactDto.setArtifact(new File(descriptorFile.concat(APIConstants.JSON_FILE_EXTENSION)));
            runtimeArtifactDto.setFile(true);
            return runtimeArtifactDto;
        } catch (APIImportExportException | IOException e) {
            throw new APIManagementException("Error while Generating API artifact", e);
        }
    } else {
        throw new APIManagementException("No API Artifacts", ExceptionCodes.NO_API_ARTIFACT_FOUND);
    }
}
Also used : MetadataDescriptorDto(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.dto.MetadataDescriptorDto) HashMap(java.util.HashMap) EnvironmentDto(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.dto.EnvironmentDto) RuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.RuntimeArtifactDto) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) IOException(java.io.IOException) ApiMetadataProjectDto(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.dto.ApiMetadataProjectDto) APIRuntimeArtifactDto(org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) File(java.io.File)

Example 24 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class WSO2APIPublisherTestCase method testFailureWhileExportingAPI.

@Test
public void testFailureWhileExportingAPI() throws Exception {
    // Error path - When exporting API failed
    Mockito.when(APIImportExportUtil.getImportExportAPI()).thenReturn(importExportAPI);
    PowerMockito.doThrow(new APIImportExportException("Error while exporting API")).when(importExportAPI).exportAPI(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyBoolean(), Matchers.any(ExportFormat.class), Matchers.anyBoolean(), Matchers.anyBoolean(), Matchers.anyBoolean(), Matchers.anyString(), Matchers.anyString());
    try {
        wso2APIPublisher.publishToStore(api, store);
        Assert.fail("APIManagement exception not thrown for error scenario");
    } catch (APIManagementException e) {
        String errorMsg = "Error while exporting API: " + api.getId().getApiName() + " version: " + api.getId().getVersion();
        Assert.assertEquals(errorMsg, e.getMessage());
    }
    PowerMockito.doThrow(new UserStoreException("Error in getting the tenant id with tenant domain: " + tenantDomain + ".")).when(tenantManager).getTenantId(tenantDomain);
    try {
        wso2APIPublisher.publishToStore(api, store);
        Assert.fail("APIManagement exception not thrown for error scenario");
    } catch (APIManagementException e) {
        String errorMsg = "Error while getting tenantId for tenant domain: " + tenantDomain + " when exporting API:" + api.getId().getApiName() + " version: " + api.getId().getVersion();
        Assert.assertEquals(errorMsg, e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) ExportFormat(org.wso2.carbon.apimgt.impl.importexport.ExportFormat) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 25 with APIImportExportException

use of org.wso2.carbon.apimgt.impl.importexport.APIImportExportException in project carbon-apimgt by wso2.

the class ExportUtils method exportApplication.

/**
 * Export a given Application to a file system as zip archive.
 * The export root location is given by {@link @path}/exported-application.
 *
 * @param exportApplication Application{@link Application} to be exported
 * @param apiConsumer       API Consumer
 * @param exportFormat      Format to export
 * @param withKeys          Export the Application with keys or not
 * @return Path to the exported directory with exported artifacts
 * @throws APIManagementException If an error occurs while exporting an application to a file system
 */
public static File exportApplication(Application exportApplication, APIConsumer apiConsumer, ExportFormat exportFormat, Boolean withKeys) throws APIManagementException {
    String archivePath = null;
    String exportApplicationBasePath;
    String appName = exportApplication.getName();
    String appOwner = exportApplication.getOwner();
    try {
        // Creates a temporary directory to store the exported application artifact
        File exportFolder = createTempApplicationDirectory(appName, appOwner);
        exportApplicationBasePath = exportFolder.toString();
        archivePath = exportApplicationBasePath.concat(File.separator + appOwner.replace(File.separator, "#") + "-" + appName);
    } catch (APIImportExportException e) {
        throw new APIManagementException("Unable to create the temporary directory to export the Application", e);
    }
    ExportedApplication applicationDtoToExport = createApplicationDTOToExport(exportApplication, apiConsumer, withKeys);
    try {
        createDirectory(archivePath);
        // Export application details
        CommonUtil.writeDtoToFile(archivePath + File.separator + ImportExportConstants.TYPE_APPLICATION, exportFormat, ImportExportConstants.TYPE_APPLICATION, applicationDtoToExport);
        CommonUtil.archiveDirectory(exportApplicationBasePath);
        FileUtils.deleteQuietly(new File(exportApplicationBasePath));
        return new File(exportApplicationBasePath + APIConstants.ZIP_FILE_EXTENSION);
    } catch (IOException | APIImportExportException e) {
        throw new APIManagementException("Error while exporting Application: " + exportApplication.getName(), e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) IOException(java.io.IOException) File(java.io.File)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)30 APIImportExportException (org.wso2.carbon.apimgt.impl.importexport.APIImportExportException)30 IOException (java.io.IOException)24 File (java.io.File)20 Gson (com.google.gson.Gson)11 JsonObject (com.google.gson.JsonObject)10 ResourceFile (org.wso2.carbon.apimgt.api.model.ResourceFile)10 JsonArray (com.google.gson.JsonArray)9 JsonElement (com.google.gson.JsonElement)9 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)8 API (org.wso2.carbon.apimgt.api.model.API)6 GsonBuilder (com.google.gson.GsonBuilder)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 FileOutputStream (java.io.FileOutputStream)5 InputStream (java.io.InputStream)5 ArrayList (java.util.ArrayList)5 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)5 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)4 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)4 JsonParser (com.google.gson.JsonParser)3