Search in sources :

Example 11 with ZipFile

use of net.lingala.zip4j.core.ZipFile in project tdi-studio-se by Talend.

the class Unzip method doUnzipWithAes.

// zip4j compress&decryption impl
public void doUnzipWithAes() throws Exception {
    File file = new File(sourceZip);
    if (password == null || "".equals(password)) {
        // To make sure the System.out.println message
        Thread.sleep(1000);
        // come before
        throw new RuntimeException("Please enter the password and try again..");
    }
    ZipFile zipFile = new ZipFile(sourceZip);
    if (checkArchive) {
        if (!zipFile.isValidZipFile()) {
            throw new RuntimeException("The file " + sourceZip + " is corrupted, process terminated...");
        }
    }
    if (zipFile.isEncrypted()) {
        zipFile.setPassword(password);
    }
    List fileHeaderList = zipFile.getFileHeaders();
    if (fileHeaderList == null) {
        return;
    }
    for (int i = 0; i < fileHeaderList.size(); i++) {
        FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
        String filename = fileHeader.getFileName();
        if (verbose) {
            System.out.println("Source file  : " + filename);
        }
        if (!extractPath) {
            filename = filename.replaceAll("\\\\", "/");
            filename = filename.substring(filename.lastIndexOf('/') + 1);
        }
        zipFile.extractFile(fileHeader, targetDir, null, filename);
    }
}
Also used : ZipFile(net.lingala.zip4j.core.ZipFile) List(java.util.List) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File) FileHeader(net.lingala.zip4j.model.FileHeader)

Example 12 with ZipFile

use of net.lingala.zip4j.core.ZipFile in project ddf by codice.

the class ExportCommand method executeWithSubject.

@Override
protected Object executeWithSubject() throws Exception {
    Filter filter = getFilter();
    transformer = getServiceByFilter(MetacardTransformer.class, String.format("(%s=%s)", "id", DEFAULT_TRANSFORMER_ID)).orElseThrow(() -> new CatalogCommandRuntimeException("Could not get " + DEFAULT_TRANSFORMER_ID + " transformer"));
    revisionFilter = initRevisionFilter();
    final File outputFile = initOutputFile(output);
    if (outputFile.exists()) {
        printErrorMessage(String.format("File [%s] already exists!", outputFile.getPath()));
        return null;
    }
    final File parentDirectory = outputFile.getParentFile();
    if (parentDirectory == null || !parentDirectory.isDirectory()) {
        printErrorMessage(String.format("Directory [%s] must exist.", output));
        console.println("If the directory does indeed exist, try putting the path in quotes.");
        return null;
    }
    String filename = FilenameUtils.getName(outputFile.getPath());
    if (StringUtils.isBlank(filename) || !filename.endsWith(".zip")) {
        console.println("Filename must end with '.zip' and not be blank");
        return null;
    }
    if (delete && !force) {
        console.println("This action will remove all exported metacards and content from the catalog. Are you sure you wish to continue? (y/N):");
        String input = getUserInputModifiable().toString();
        if (!input.matches("^[yY][eE]?[sS]?$")) {
            console.println("ABORTED EXPORT.");
            return null;
        }
    }
    SecurityLogger.audit("Called catalog:export command with path : {}", output);
    ZipFile zipFile = new ZipFile(outputFile);
    console.println("Starting metacard export...");
    Instant start = Instant.now();
    List<ExportItem> exportedItems = doMetacardExport(zipFile, filter);
    console.println("Metacards exported in: " + getFormattedDuration(start));
    console.println("Number of metacards exported: " + exportedItems.size());
    console.println();
    SecurityLogger.audit("Ids of exported metacards and content:\n{}", exportedItems.stream().map(ExportItem::getId).distinct().collect(Collectors.joining(", ", "[", "]")));
    console.println("Starting content export...");
    start = Instant.now();
    List<ExportItem> exportedContentItems = doContentExport(zipFile, exportedItems);
    console.println("Content exported in: " + getFormattedDuration(start));
    console.println("Number of content exported: " + exportedContentItems.size());
    console.println();
    if (delete) {
        doDelete(exportedItems, exportedContentItems);
    }
    if (!unsafe) {
        SecurityLogger.audit("Signing exported data. file: [{}]", zipFile.getFile().getName());
        console.println("Signing zip file...");
        start = Instant.now();
        jarSigner.signJar(zipFile.getFile(), System.getProperty("org.codice.ddf.system.hostname"), System.getProperty("javax.net.ssl.keyStorePassword"), System.getProperty("javax.net.ssl.keyStore"), System.getProperty("javax.net.ssl.keyStorePassword"));
        console.println("zip file signed in: " + getFormattedDuration(start));
    }
    console.println("Export complete.");
    console.println("Exported to: " + zipFile.getFile().getCanonicalPath());
    return null;
}
Also used : ExportItem(org.codice.ddf.commands.catalog.export.ExportItem) ZipFile(net.lingala.zip4j.core.ZipFile) Filter(org.opengis.filter.Filter) Instant(java.time.Instant) CatalogCommandRuntimeException(org.codice.ddf.commands.util.CatalogCommandRuntimeException) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File)

Example 13 with ZipFile

use of net.lingala.zip4j.core.ZipFile in project ddf by codice.

the class ZipCompression method transform.

/**
     * Transforms a SourceResponse with a list of {@link Metacard}s into a {@link BinaryContent} item
     * with an {@link InputStream}.  This transformation expects a key-value pair "fileName"-zipFileName to be present.
     *
     * @param upstreamResponse - a SourceResponse with a list of {@link Metacard}s to compress
     * @param arguments        - a map of arguments to use for processing.  This method expects "fileName" to be set
     * @return - a {@link BinaryContent} item with the {@link InputStream} for the Zip file
     * @throws CatalogTransformerException when the transformation fails
     */
@Override
public BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException {
    if (upstreamResponse == null || CollectionUtils.isEmpty(upstreamResponse.getResults())) {
        throw new CatalogTransformerException("No Metacards were found to transform.");
    }
    if (MapUtils.isEmpty(arguments) || !arguments.containsKey(ZipDecompression.FILE_PATH)) {
        throw new CatalogTransformerException("No 'filePath' argument found in arguments map.");
    }
    ZipFile zipFile;
    String filePath = (String) arguments.get(ZipDecompression.FILE_PATH);
    try {
        zipFile = new ZipFile(filePath);
    } catch (ZipException e) {
        LOGGER.debug("Unable to create zip file with path : {}", filePath, e);
        throw new CatalogTransformerException(String.format("Unable to create zip file at %s", filePath), e);
    }
    List<Result> resultList = upstreamResponse.getResults();
    Map<String, Resource> resourceMap = new HashMap<>();
    resultList.stream().map(Result::getMetacard).forEach(metacard -> {
        ZipParameters zipParameters = new ZipParameters();
        zipParameters.setSourceExternalStream(true);
        zipParameters.setFileNameInZip(METACARD_PATH + metacard.getId());
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(new MetacardImpl(metacard));
            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            zipFile.addStream(inputStream, zipParameters);
            if (hasLocalResources(metacard)) {
                resourceMap.putAll(getAllMetacardContent(metacard));
            }
        } catch (IOException | ZipException e) {
            LOGGER.debug("Failed to add metacard with id {}.", metacard.getId(), e);
        }
    });
    resourceMap.forEach((filename, resource) -> {
        try {
            ZipParameters zipParameters = new ZipParameters();
            zipParameters.setSourceExternalStream(true);
            zipParameters.setFileNameInZip(filename);
            zipFile.addStream(resource.getInputStream(), zipParameters);
        } catch (ZipException e) {
            LOGGER.debug("Failed to add resource with id {} to zip.", resource.getName(), e);
        }
    });
    BinaryContent binaryContent;
    try {
        InputStream fileInputStream = new ZipInputStream(new FileInputStream(zipFile.getFile()));
        binaryContent = new BinaryContentImpl(fileInputStream);
        jarSigner.signJar(zipFile.getFile(), System.getProperty("org.codice.ddf.system.hostname"), System.getProperty("javax.net.ssl.keyStorePassword"), System.getProperty("javax.net.ssl.keyStore"), System.getProperty("javax.net.ssl.keyStorePassword"));
    } catch (FileNotFoundException e) {
        throw new CatalogTransformerException("Unable to get ZIP file from ZipInputStream.", e);
    }
    return binaryContent;
}
Also used : HashMap(java.util.HashMap) ZipInputStream(java.util.zip.ZipInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Resource(ddf.catalog.resource.Resource) FileNotFoundException(java.io.FileNotFoundException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) ZipException(net.lingala.zip4j.exception.ZipException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) BinaryContentImpl(ddf.catalog.data.impl.BinaryContentImpl) ObjectOutputStream(java.io.ObjectOutputStream) BinaryContent(ddf.catalog.data.BinaryContent) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) FileInputStream(java.io.FileInputStream) Result(ddf.catalog.data.Result) ZipParameters(net.lingala.zip4j.model.ZipParameters) ZipInputStream(java.util.zip.ZipInputStream) ZipFile(net.lingala.zip4j.core.ZipFile) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 14 with ZipFile

use of net.lingala.zip4j.core.ZipFile in project bamboobsc by billchen198318.

the class JReportUtils method selfTestDecompress4Upload.

public static String selfTestDecompress4Upload(String uploadOid) throws ServiceException, IOException, Exception {
    String extractDir = Constants.getWorkTmpDir() + "/" + JReportUtils.class.getSimpleName() + "/" + SimpleUtils.getUUIDStr() + "/";
    File realFile = UploadSupportUtils.getRealFile(uploadOid);
    try {
        ZipFile zipFile = new ZipFile(realFile);
        zipFile.extractAll(extractDir);
    } catch (Exception e) {
        throw e;
    } finally {
        realFile = null;
    }
    return extractDir;
}
Also used : ZipFile(net.lingala.zip4j.core.ZipFile) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File) JRException(net.sf.jasperreports.engine.JRException) IOException(java.io.IOException) ServiceException(com.netsteadfast.greenstep.base.exception.ServiceException)

Example 15 with ZipFile

use of net.lingala.zip4j.core.ZipFile in project bamboobsc by billchen198318.

the class BusinessProcessManagementUtils method decompressResource.

public static File[] decompressResource(File resourceZipFile) throws Exception {
    String extractDir = Constants.getWorkTmpDir() + "/" + BusinessProcessManagementUtils.class.getSimpleName() + "/" + SimpleUtils.getUUIDStr() + "/";
    ZipFile zipFile = new ZipFile(resourceZipFile);
    zipFile.extractAll(extractDir);
    File dir = new File(extractDir);
    return dir.listFiles();
}
Also used : ZipFile(net.lingala.zip4j.core.ZipFile) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File)

Aggregations

ZipFile (net.lingala.zip4j.core.ZipFile)17 ZipParameters (net.lingala.zip4j.model.ZipParameters)9 File (java.io.File)8 IOException (java.io.IOException)5 ZipException (net.lingala.zip4j.exception.ZipException)4 BinaryContent (ddf.catalog.data.BinaryContent)2 Result (ddf.catalog.data.Result)2 CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)2 Instant (java.time.Instant)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 ServiceException (com.netsteadfast.greenstep.base.exception.ServiceException)1 SysUploadVO (com.netsteadfast.greenstep.vo.SysUploadVO)1 ConverterRuntimeException (com.odysseusinc.arachne.portal.exception.ConverterRuntimeException)1 StorageException (ddf.catalog.content.StorageException)1 StorageProvider (ddf.catalog.content.StorageProvider)1 ContentItem (ddf.catalog.content.data.ContentItem)1 DeleteStorageRequestImpl (ddf.catalog.content.operation.impl.DeleteStorageRequestImpl)1 DeletedMetacard (ddf.catalog.core.versioning.DeletedMetacard)1