Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry.

Prototype

public ZipArchiveEntry(ZipArchiveEntry entry) throws ZipException 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:org.sead.nds.repository.BagGenerator.java

private void createFileFromURL(final String name, final String uri)
        throws IOException, ExecutionException, InterruptedException {

    ZipArchiveEntry archiveEntry = new ZipArchiveEntry(name);
    archiveEntry.setMethod(ZipEntry.DEFLATED);
    InputStreamSupplier supp = RO.getInputStreamSupplier(uri);
    addEntry(archiveEntry, supp);//from  ww w. java2  s  .  c o m
}

From source file:org.sead.nds.repository.BagGenerator.java

private boolean createFileFromLocalSource(String name, String hashtype, String childHash) throws IOException {
    InputStreamSupplier supp = lcProvider.getSupplierFor(hashtype, childHash);
    if (supp != null) {
        ZipArchiveEntry archiveEntry = new ZipArchiveEntry(name);
        archiveEntry.setMethod(ZipEntry.DEFLATED);
        addEntry(archiveEntry, supp);/* w  w  w  .j  a v  a2s  .  co  m*/
        return true;
    }
    return false;
}

From source file:org.seasr.meandre.components.tools.io.WriteArchive.java

@Override
public void executeCallBack(ComponentContext cc) throws Exception {
    componentInputCache.storeIfAvailable(cc, IN_LOCATION);
    componentInputCache.storeIfAvailable(cc, IN_FILE_NAME);
    componentInputCache.storeIfAvailable(cc, IN_DATA);

    if (archiveStream == null && componentInputCache.hasData(IN_LOCATION)) {
        Object input = componentInputCache.retrieveNext(IN_LOCATION);
        if (input instanceof StreamDelimiter)
            throw new ComponentExecutionException(
                    String.format("Stream delimiters should not arrive on port '%s'!", IN_LOCATION));

        String location = DataTypeParser.parseAsString(input)[0];
        if (appendExtension)
            location += String.format(".%s", archiveFormat);
        outputFile = getLocation(location, defaultFolder);
        File parentDir = outputFile.getParentFile();

        if (!parentDir.exists()) {
            if (parentDir.mkdirs())
                console.finer("Created directory: " + parentDir);
        } else if (!parentDir.isDirectory())
            throw new IOException(parentDir.toString() + " must be a directory!");

        if (appendTimestamp) {
            String name = outputFile.getName();
            String timestamp = new SimpleDateFormat(timestampFormat).format(new Date());

            int pos = name.lastIndexOf(".");
            if (pos < 0)
                name += "_" + timestamp;
            else/*w w  w  .j a  v  a 2  s.co m*/
                name = String.format("%s_%s%s", name.substring(0, pos), timestamp, name.substring(pos));

            outputFile = new File(parentDir, name);
        }

        console.fine(String.format("Writing file %s", outputFile));

        if (archiveFormat.equals("zip")) {
            archiveStream = new ZipArchiveOutputStream(outputFile);
            ((ZipArchiveOutputStream) archiveStream).setLevel(Deflater.BEST_COMPRESSION);
        }

        else

        if (archiveFormat.equals("tar") || archiveFormat.equals("tgz")) {
            OutputStream fileStream = new BufferedOutputStream(new FileOutputStream(outputFile));
            if (archiveFormat.equals("tgz"))
                fileStream = new GzipCompressorOutputStream(fileStream);
            archiveStream = new TarArchiveOutputStream(fileStream);
        }
    }

    // Return if we haven't received a zip or tar location yet
    if (archiveStream == null)
        return;

    while (componentInputCache.hasDataAll(new String[] { IN_FILE_NAME, IN_DATA })) {
        Object inFileName = componentInputCache.retrieveNext(IN_FILE_NAME);
        Object inData = componentInputCache.retrieveNext(IN_DATA);

        // check for StreamInitiator
        if (inFileName instanceof StreamInitiator || inData instanceof StreamInitiator) {
            if (inFileName instanceof StreamInitiator && inData instanceof StreamInitiator) {
                StreamInitiator siFileName = (StreamInitiator) inFileName;
                StreamInitiator siData = (StreamInitiator) inData;

                if (siFileName.getStreamId() != siData.getStreamId())
                    throw new ComponentExecutionException("Unequal stream ids received!!!");

                if (siFileName.getStreamId() == streamId)
                    isStreaming = true;
                else
                    // Forward the delimiter(s)
                    cc.pushDataComponentToOutput(OUT_LOCATION, siFileName);

                continue;
            } else
                throw new ComponentExecutionException("Unbalanced StreamDelimiter received!");
        }

        // check for StreamTerminator
        if (inFileName instanceof StreamTerminator || inData instanceof StreamTerminator) {
            if (inFileName instanceof StreamTerminator && inData instanceof StreamTerminator) {
                StreamTerminator stFileName = (StreamTerminator) inFileName;
                StreamTerminator stData = (StreamTerminator) inData;

                if (stFileName.getStreamId() != stData.getStreamId())
                    throw new ComponentExecutionException("Unequal stream ids received!!!");

                if (stFileName.getStreamId() == streamId) {
                    // end of stream reached
                    closeArchiveAndPushOutput();
                    isStreaming = false;
                    break;
                } else {
                    // Forward the delimiter(s)
                    if (isStreaming)
                        console.warning(
                                "Likely streaming error - received StreamTerminator for a different stream id than the current active stream! - forwarding it");
                    cc.pushDataComponentToOutput(OUT_LOCATION, stFileName);
                    continue;
                }
            } else
                throw new ComponentExecutionException("Unbalanced StreamDelimiter received!");
        }

        byte[] entryData = null;

        if (inData instanceof byte[] || inData instanceof Bytes)
            entryData = DataTypeParser.parseAsByteArray(inData);

        else

        if (inData instanceof Document) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DOMUtils.writeXML((Document) inData, baos, outputProperties);
            entryData = baos.toByteArray();
        }

        else
            entryData = DataTypeParser.parseAsString(inData)[0].getBytes("UTF-8");

        String entryName = DataTypeParser.parseAsString(inFileName)[0];

        console.fine(String.format("Adding %s entry: %s", archiveFormat.toUpperCase(), entryName));

        ArchiveEntry entry = null;
        if (archiveFormat.equals("zip"))
            entry = new ZipArchiveEntry(entryName);

        else

        if (archiveFormat.equals("tar") || archiveFormat.equals("tgz")) {
            entry = new TarArchiveEntry(entryName);
            ((TarArchiveEntry) entry).setSize(entryData.length);
        }

        archiveStream.putArchiveEntry(entry);
        archiveStream.write(entryData);
        archiveStream.closeArchiveEntry();

        if (!isStreaming) {
            closeArchiveAndPushOutput();
            break;
        }
    }
}

From source file:org.sigmah.server.file.impl.BackupArchiveJob.java

/**
 * <p>/*from   w  ww . j a  va2s. c om*/
 * Recursively browses the given {@code root} repository elements to populate the given {@code zipOutputStream} with
 * corresponding files.
 * </p>
 * <p>
 * If a referenced file cannot be found in the storage folder, it will be ignored (a {@code WARN} log is generated).
 * </p>
 * 
 * @param root
 *          The root repository element.
 * @param zipOutputStream
 *          The stream to populate with files hierarchy.
 * @param actualPath
 *          The current repository path.
 */
private void zipRepository(final RepositoryElement root, final ZipArchiveOutputStream zipOutputStream,
        final String actualPath) {

    final String path = (actualPath.equals("") ? root.getName() : actualPath + "/" + root.getName());

    if (root instanceof FileElement) {

        final FileElement file = (FileElement) root;
        final String fileStorageId = file.getStorageId();

        if (fileStorageProvider.exists(fileStorageId)) {
            try (final InputStream is = new BufferedInputStream(fileStorageProvider.open(fileStorageId),
                    ResponseHelper.BUFFER_SIZE)) {

                zipOutputStream.putArchiveEntry(new ZipArchiveEntry(path));

                final byte data[] = new byte[ResponseHelper.BUFFER_SIZE];

                while ((is.read(data)) != -1) {
                    zipOutputStream.write(data);
                }

                zipOutputStream.closeArchiveEntry();

            } catch (final IOException e) {
                LOG.warn("File '" + fileStorageId + "' cannot be found ; continuing with next file.", e);
            }
        } else {
            LOG.warn("File '{0}' does not exists on the server ; continuing with next file.", fileStorageId);
        }

    } else if (root instanceof FolderElement) {

        final FolderElement folder = (FolderElement) root;

        for (final RepositoryElement element : folder.getChildren()) {
            zipRepository(element, zipOutputStream, path);
        }
    }
}

From source file:org.silverpeas.core.util.ZipUtil.java

/**
 * Compress a file into a zip file.//www . ja va2  s.  com
 *
 * @param filePath
 * @param zipFilePath
 * @return
 * @throws IOException
 */
public static long compressFile(String filePath, String zipFilePath) throws IOException {
    try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(zipFilePath));
            InputStream in = new FileInputStream(filePath)) {
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding(Charsets.UTF_8.name());
        String entryName = FilenameUtils.getName(filePath);
        entryName = entryName.replace(File.separatorChar, '/');
        zos.putArchiveEntry(new ZipArchiveEntry(entryName));
        IOUtils.copy(in, zos);
        zos.closeArchiveEntry();
        return new File(zipFilePath).length();
    }
}

From source file:org.silverpeas.core.util.ZipUtil.java

/**
 * Mthode compressant un dossier de faon rcursive au format zip.
 *
 * @param folderToZip - dossier  compresser
 * @param zipFile - fichier zip  creer/*from  w  ww. j  a  v  a  2 s .c  om*/
 * @return la taille du fichier zip gnr en octets
 * @throws FileNotFoundException
 * @throws IOException
 */
public static long compressPathToZip(File folderToZip, File zipFile) throws IOException {
    try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(zipFile))) {
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding(Charsets.UTF_8.name());
        Collection<File> folderContent = FileUtils.listFiles(folderToZip, null, true);
        for (File file : folderContent) {
            String entryName = file.getPath().substring(folderToZip.getParent().length() + 1);
            entryName = FilenameUtils.separatorsToUnix(entryName);
            zos.putArchiveEntry(new ZipArchiveEntry(entryName));
            try (InputStream in = new FileInputStream(file)) {
                IOUtils.copy(in, zos);
                zos.closeArchiveEntry();
            }
        }
    }
    return zipFile.length();
}

From source file:org.silverpeas.core.util.ZipUtil.java

/**
 * Mthode permettant la cration et l'organisation d'un fichier zip en lui passant directement un
 * flux d'entre//from  w  w w.ja v  a  2  s  . c  o m
 *
 * @param inputStream - flux de donnes  enregistrer dans le zip
 * @param filePathNameToCreate - chemin et nom du fichier port par les donnes du flux dans le
 * zip
 * @param outfilename - chemin et nom du fichier zip  creer ou complter
 * @throws IOException
 */
public static void compressStreamToZip(InputStream inputStream, String filePathNameToCreate, String outfilename)
        throws IOException {
    try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(outfilename))) {
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding("UTF-8");
        zos.putArchiveEntry(new ZipArchiveEntry(filePathNameToCreate));
        IOUtils.copy(inputStream, zos);
        zos.closeArchiveEntry();
    }
}

From source file:org.springframework.boot.gradle.tasks.bundling.BootZipCopyAction.java

private Spec<FileTreeElement> writeLoaderClasses(ZipArchiveOutputStream out) {
    try (ZipInputStream in = new ZipInputStream(
            getClass().getResourceAsStream("/META-INF/loader/spring-boot-loader.jar"))) {
        Set<String> entries = new HashSet<>();
        java.util.zip.ZipEntry entry;
        while ((entry = in.getNextEntry()) != null) {
            if (entry.isDirectory() && !entry.getName().startsWith("META-INF/")) {
                writeDirectory(new ZipArchiveEntry(entry), out);
                entries.add(entry.getName());
            } else if (entry.getName().endsWith(".class")) {
                writeClass(new ZipArchiveEntry(entry), in, out);
            }//from www .j  a  va  2 s .  com
        }
        return (element) -> {
            String path = element.getRelativePath().getPathString();
            if (element.isDirectory() && !path.endsWith(("/"))) {
                path += "/";
            }
            return entries.contains(path);
        };
    } catch (IOException ex) {
        throw new GradleException("Failed to write loader classes", ex);
    }
}

From source file:org.structr.web.function.CreateArchiveFunction.java

private void addFileToZipArchive(String path, File file, ArchiveOutputStream aps) throws IOException {

    logger.info("Adding File \"{}\" to new archive...", path);

    ZipArchiveEntry entry = new ZipArchiveEntry(path);
    aps.putArchiveEntry(entry);//from w  ww  . ja  v  a 2 s .co  m

    try (final InputStream in = file.getInputStream()) {

        IOUtils.copy(in, aps);
    }

    aps.closeArchiveEntry();
}

From source file:org.trustedanalytics.servicebroker.gearpump.service.file.FileHelper.java

public static byte[] prepareZipFile(byte[] zipFileTestContent) throws IOException {
    ByteArrayOutputStream byteOutput = null;
    ZipArchiveOutputStream zipOutput = null;
    try {/*from www.  j ava  2 s  .  co  m*/
        byteOutput = new ByteArrayOutputStream();
        zipOutput = new ZipArchiveOutputStream(byteOutput);
        ZipArchiveEntry entry = new ZipArchiveEntry(FILE_NAME);
        entry.setSize(zipFileTestContent.length);
        addArchiveEntry(zipOutput, entry, zipFileTestContent);
    } finally {
        zipOutput.close();
        byteOutput.close();
    }

    return byteOutput.toByteArray();
}