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

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

Introduction

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

Prototype

public void setTime(long time) 

Source Link

Document

Sets the last modification time of the entry.

Usage

From source file:at.spardat.xma.xdelta.JarPatcher.java

/**
 * Apply delta.//from  w w w  .  ja v a  2  s.com
 *
 * @param patch the patch
 * @param source the source
 * @param output the output
 * @param list the list
 * @param prefix the prefix
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list,
        String prefix) throws IOException {
    String fileName = null;
    try {
        for (fileName = (next == null ? list.readLine()
                : next); fileName != null; fileName = (next == null ? list.readLine() : next)) {
            if (next != null)
                next = null;
            if (!fileName.startsWith(prefix)) {
                next = fileName;
                return;
            }
            int crcDelim = fileName.lastIndexOf(':');
            int crcStart = fileName.lastIndexOf('|');
            long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16);
            long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16);
            fileName = fileName.substring(prefix.length(), crcStart);
            if ("META-INF/file.list".equalsIgnoreCase(fileName))
                continue;
            if (fileName.contains("!")) {
                String[] embeds = fileName.split("\\!");
                ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc);
                File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip");
                File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip");
                Exception thrown = null;
                try (FileOutputStream out = new FileOutputStream(originalFile);
                        InputStream in = source.getInputStream(original)) {
                    int read = 0;
                    while (-1 < (read = in.read(buffer))) {
                        out.write(buffer, 0, read);
                    }
                    out.flush();
                    applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list,
                            prefix + embeds[0] + "!");
                } catch (Exception e) {
                    thrown = e;
                    throw e;
                } finally {
                    originalFile.delete();
                    try (FileInputStream in = new FileInputStream(outputFile)) {
                        if (thrown == null) {
                            ZipArchiveEntry outEntry = copyEntry(original);
                            output.putArchiveEntry(outEntry);
                            int read = 0;
                            while (-1 < (read = in.read(buffer))) {
                                output.write(buffer, 0, read);
                            }
                            output.flush();
                            output.closeArchiveEntry();
                        }
                    } finally {
                        outputFile.delete();
                    }
                }
            } else {
                try {
                    ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc);
                    if (patchEntry != null) { // new Entry
                        ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName);
                        output.putArchiveEntry(outputEntry);
                        if (!patchEntry.isDirectory()) {
                            try (InputStream in = patch.getInputStream(patchEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    output.write(buffer, 0, read);
                                }
                            }
                        }
                        closeEntry(output, outputEntry, crc);
                    } else {
                        ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc);
                        if (sourceEntry == null) {
                            throw new FileNotFoundException(
                                    fileName + " not found in " + sourceName + " or " + patchName);
                        }
                        if (sourceEntry.isDirectory()) {
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry);
                            output.putArchiveEntry(outputEntry);
                            closeEntry(output, outputEntry, crc);
                            continue;
                        }
                        patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc);
                        if (patchEntry != null) { // changed Entry
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry);
                            outputEntry.setTime(patchEntry.getTime());
                            output.putArchiveEntry(outputEntry);
                            byte[] sourceBytes = new byte[(int) sourceEntry.getSize()];
                            try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                                for (int erg = sourceStream
                                        .read(sourceBytes); erg < sourceBytes.length; erg += sourceStream
                                                .read(sourceBytes, erg, sourceBytes.length - erg))
                                    ;
                            }
                            InputStream patchStream = patch.getInputStream(patchEntry);
                            GDiffPatcher diffPatcher = new GDiffPatcher();
                            diffPatcher.patch(sourceBytes, patchStream, output);
                            patchStream.close();
                            outputEntry.setCrc(crc);
                            closeEntry(output, outputEntry, crc);
                        } else { // unchanged Entry
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry);
                            output.putArchiveEntry(outputEntry);
                            try (InputStream in = source.getInputStream(sourceEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    output.write(buffer, 0, read);
                                }
                            }
                            output.flush();
                            closeEntry(output, outputEntry, crc);
                        }
                    }
                } catch (PatchException pe) {
                    IOException ioe = new IOException();
                    ioe.initCause(pe);
                    throw ioe;
                }
            }
        }
    } catch (Exception e) {
        System.err.println(prefix + fileName);
        throw e;
    } finally {
        source.close();
        output.close();
    }
}

From source file:com.naryx.tagfusion.expression.function.file.Zip.java

/**
 * Performing Zip() operation/* w ww  . j a  v  a2 s.  c om*/
 * 
 * @param session
 * @param zipfile
 * @param src
 * @param recurse
 * @param prefixx
 * @param compLvl
 * @param filter
 * @param overwrite
 * @param newpath
 * @throws cfmRunTimeException
 * @throws IOException
 */
protected void zipOperation(cfSession session, ZipArchiveOutputStream zipOut, File src, boolean recurse,
        String prefix, int compLvl, FilenameFilter filter, String newpath) throws cfmRunTimeException {
    if (src != null) {
        FileInputStream nextFileIn;
        ZipArchiveEntry nextEntry = null;
        byte[] buffer = new byte[4096];
        int readBytes;
        zipOut.setLevel(compLvl);

        try {
            List<File> files = new ArrayList<File>();
            int srcDirLen;
            if (src.isFile()) {
                String parentPath = src.getParent();
                srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1;
                files.add(src);

            } else {
                String parentPath = src.getAbsolutePath();
                srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1;
                getFiles(src, files, recurse, filter);
            }

            int noFiles = files.size();
            File nextFile;
            boolean isDir;
            for (int i = 0; i < noFiles; i++) {
                nextFile = (File) files.get(i);

                isDir = nextFile.isDirectory();

                if (noFiles == 1 && newpath != null) {
                    // NEWPATH
                    nextEntry = new ZipArchiveEntry(newpath.replace('\\', '/') + (isDir ? "/" : ""));
                } else {
                    // PREFIX
                    nextEntry = new ZipArchiveEntry(
                            prefix + nextFile.getAbsolutePath().substring(srcDirLen).replace('\\', '/')
                                    + (isDir ? "/" : ""));
                }

                try {
                    zipOut.putArchiveEntry(nextEntry);
                } catch (IOException e) {
                    throwException(session,
                            "Failed to add entry to zip file [" + nextEntry + "]. Reason: " + e.getMessage());
                }

                if (!isDir) {
                    nextEntry.setTime(nextFile.lastModified());
                    nextFileIn = new FileInputStream(nextFile);
                    try {
                        while (nextFileIn.available() > 0) {
                            readBytes = nextFileIn.read(buffer);
                            zipOut.write(buffer, 0, readBytes);
                        }
                        zipOut.flush();
                    } catch (IOException e) {
                        throwException(session, "Failed to write entry [" + nextEntry
                                + "] to zip file. Reason: " + e.getMessage());
                    } finally {
                        // nextEntry close
                        StreamUtil.closeStream(nextFileIn);
                    }
                }
                zipOut.closeArchiveEntry();
            }
        } catch (IOException ioe) {
            throwException(session, "Failed to create zip file: " + ioe.getMessage());
        }
    }
}

From source file:at.spardat.xma.xdelta.JarDelta.java

/**
 * Compute delta.// w  w  w . ja va 2s  . c o  m
 *
 * @param source the source
 * @param target the target
 * @param output the output
 * @param list the list
 * @param prefix the prefix
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void computeDelta(ZipFile source, ZipFile target, ZipArchiveOutputStream output, PrintWriter list,
        String prefix) throws IOException {
    try {
        for (Enumeration<ZipArchiveEntry> enumer = target.getEntries(); enumer.hasMoreElements();) {
            calculatedDelta = null;
            ZipArchiveEntry targetEntry = enumer.nextElement();
            ZipArchiveEntry sourceEntry = findBestSource(source, target, targetEntry);
            String nextEntryName = prefix + targetEntry.getName();
            if (sourceEntry != null && zipFilesPattern.matcher(sourceEntry.getName()).matches()
                    && !equal(sourceEntry, targetEntry)) {
                nextEntryName += "!";
            }
            nextEntryName += "|" + Long.toHexString(targetEntry.getCrc());
            if (sourceEntry != null) {
                nextEntryName += ":" + Long.toHexString(sourceEntry.getCrc());
            } else {
                nextEntryName += ":0";
            }
            list.println(nextEntryName);
            if (targetEntry.isDirectory()) {
                if (sourceEntry == null) {
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    output.closeArchiveEntry();
                }
            } else {
                if (sourceEntry == null || sourceEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE
                        || targetEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE) { // new Entry od. alter Eintrag od. neuer Eintrag leer
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    try (InputStream in = target.getInputStream(targetEntry)) {
                        int read = 0;
                        while (-1 < (read = in.read(buffer))) {
                            output.write(buffer, 0, read);
                        }
                        output.flush();
                    }
                    output.closeArchiveEntry();
                } else {
                    if (!equal(sourceEntry, targetEntry)) {
                        if (zipFilesPattern.matcher(sourceEntry.getName()).matches()) {
                            File embeddedTarget = File.createTempFile("jardelta-tmp", ".zip");
                            File embeddedSource = File.createTempFile("jardelta-tmp", ".zip");
                            try (FileOutputStream out = new FileOutputStream(embeddedSource);
                                    InputStream in = source.getInputStream(sourceEntry);
                                    FileOutputStream out2 = new FileOutputStream(embeddedTarget);
                                    InputStream in2 = target.getInputStream(targetEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    out.write(buffer, 0, read);
                                }
                                out.flush();
                                read = 0;
                                while (-1 < (read = in2.read(buffer))) {
                                    out2.write(buffer, 0, read);
                                }
                                out2.flush();
                                computeDelta(new ZipFile(embeddedSource), new ZipFile(embeddedTarget), output,
                                        list, prefix + sourceEntry.getName() + "!");
                            } finally {
                                embeddedSource.delete();
                                embeddedTarget.delete();
                            }
                        } else {
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(
                                    prefix + targetEntry.getName() + ".gdiff");
                            outputEntry.setTime(targetEntry.getTime());
                            outputEntry.setComment("" + targetEntry.getCrc());
                            output.putArchiveEntry(outputEntry);
                            if (calculatedDelta != null) {
                                output.write(calculatedDelta);
                                output.flush();
                            } else {
                                try (ByteArrayOutputStream outbytes = new ByteArrayOutputStream()) {
                                    Delta d = new Delta();
                                    DiffWriter diffWriter = new GDiffWriter(new DataOutputStream(outbytes));
                                    int sourceSize = (int) sourceEntry.getSize();
                                    byte[] sourceBytes = new byte[sourceSize];
                                    try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                                        for (int erg = sourceStream.read(
                                                sourceBytes); erg < sourceBytes.length; erg += sourceStream
                                                        .read(sourceBytes, erg, sourceBytes.length - erg))
                                            ;
                                    }
                                    d.compute(sourceBytes, target.getInputStream(targetEntry), diffWriter);
                                    output.write(outbytes.toByteArray());
                                }
                            }
                            output.closeArchiveEntry();
                        }
                    }
                }
            }
        }
    } finally {
        source.close();
        target.close();
    }
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Writes the SignedDoc to an output file
 * and automatically calculates DataFile sizes
 * and digests/*w  w w .j a  va2  s. c  o  m*/
 * @param outputFile output file name
 * @param fTempSdoc temporrary file, copy of original for copying items
 * @throws DigiDocException for all errors
 */
public void writeToStream(OutputStream os/*, File fTempSdoc*/) throws DigiDocException {
    DigiDocException ex1 = validateFormatAndVersion();
    if (ex1 != null)
        throw ex1;
    try {
        DigiDocXmlGenFactory genFac = new DigiDocXmlGenFactory(this);
        if (m_format.equals(SignedDoc.FORMAT_BDOC)) {
            ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
            zos.setEncoding("UTF-8");
            if (m_logger.isDebugEnabled())
                m_logger.debug("OS: " + ((os != null) ? "OK" : "NULL"));
            // write mimetype
            if (m_logger.isDebugEnabled())
                m_logger.debug("Writing: " + MIMET_FILE_NAME);
            ZipArchiveEntry ze = new ZipArchiveEntry(MIMET_FILE_NAME);
            if (m_comment == null)
                m_comment = DigiDocGenFactory.getUserInfo(m_format, m_version);
            ze.setComment(m_comment);
            ze.setMethod(ZipArchiveEntry.STORED);
            java.util.zip.CRC32 crc = new java.util.zip.CRC32();
            if (m_version.equals(BDOC_VERSION_1_0)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_10.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_10.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_1_1)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_11.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_11.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_2_1)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_20.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_20.getBytes());
            }
            ze.setCrc(crc.getValue());
            zos.putArchiveEntry(ze);
            if (m_version.equals(BDOC_VERSION_1_0)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_10.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_1_1)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_11.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_2_1)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_20.getBytes());
            }
            zos.closeArchiveEntry();
            // write manifest.xml
            if (m_logger.isDebugEnabled())
                m_logger.debug("Writing: " + MANIF_FILE_NAME);
            ze = new ZipArchiveEntry(MANIF_DIR_META_INF);
            ze = new ZipArchiveEntry(MANIF_FILE_NAME);
            ze.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
            zos.putArchiveEntry(ze);
            //if(m_logger.isDebugEnabled())
            //   m_logger.debug("Writing manif:\n" + m_manifest.toString());
            zos.write(m_manifest.toXML());
            zos.closeArchiveEntry();
            // write data files
            for (int i = 0; i < countDataFiles(); i++) {
                DataFile df = getDataFile(i);
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing DF: " + df.getFileName() + " content: " + df.getContentType()
                            + " df-cache: "
                            + ((df.getDfCacheFile() != null) ? df.getDfCacheFile().getAbsolutePath() : "NONE"));
                InputStream is = null;
                if (df.hasAccessToDataFile())
                    is = df.getBodyAsStream();
                else
                    is = findDataFileAsStream(df.getFileName());
                if (is != null) {
                    File dfFile = new File(df.getFileName());
                    String fileName = dfFile.getName();
                    ze = new ZipArchiveEntry(fileName);
                    if (df.getComment() == null)
                        df.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
                    ze.setComment(df.getComment());
                    ze.setSize(dfFile.length());
                    ze.setTime(
                            (df.getLastModDt() != null) ? df.getLastModDt().getTime() : dfFile.lastModified());
                    zos.putArchiveEntry(ze);
                    byte[] data = new byte[2048];
                    int nRead = 0, nTotal = 0;
                    crc = new java.util.zip.CRC32();
                    while ((nRead = is.read(data)) > 0) {
                        zos.write(data, 0, nRead);
                        nTotal += nRead;
                        crc.update(data, 0, nRead);
                    }
                    ze.setSize(nTotal);
                    ze.setCrc(crc.getValue());
                    zos.closeArchiveEntry();
                    is.close();
                }
            }
            for (int i = 0; i < countSignatures(); i++) {
                Signature sig = getSignature(i);
                String sFileName = sig.getPath();
                if (sFileName == null) {
                    if (m_version.equals(BDOC_VERSION_2_1))
                        sFileName = SIG_FILE_NAME_20 + (i + 1) + ".xml";
                    else
                        sFileName = SIG_FILE_NAME + (i + 1) + ".xml";
                }
                if (!sFileName.startsWith("META-INF"))
                    sFileName = "META-INF/" + sFileName;
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing SIG: " + sFileName + " orig: "
                            + ((sig.getOrigContent() != null) ? "OK" : "NULL"));
                ze = new ZipArchiveEntry(sFileName);
                if (sig.getComment() == null)
                    sig.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
                ze.setComment(sig.getComment());
                String sSig = null;
                if (sig.getOrigContent() != null)
                    sSig = new String(sig.getOrigContent(), "UTF-8");
                else
                    sSig = sig.toString();
                if (sSig != null && !sSig.startsWith("<?xml"))
                    sSig = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + sSig;
                byte[] sdata = sSig.getBytes("UTF-8");
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing SIG: " + sFileName + " xml:\n---\n "
                            + ((sSig != null) ? sSig : "NULL") + "\n---\n ");
                ze.setSize(sdata.length);
                crc = new java.util.zip.CRC32();
                crc.update(sdata);
                ze.setCrc(crc.getValue());
                zos.putArchiveEntry(ze);
                zos.write(sdata);
                zos.closeArchiveEntry();
            }
            zos.close();
        } else if (m_format.equals(SignedDoc.FORMAT_DIGIDOC_XML)) { // ddoc format
            os.write(xmlHeader().getBytes());
            for (int i = 0; i < countDataFiles(); i++) {
                DataFile df = getDataFile(i);
                df.writeToFile(os);
                os.write("\n".getBytes());
            }
            for (int i = 0; i < countSignatures(); i++) {
                Signature sig = getSignature(i);
                if (sig.getOrigContent() != null)
                    os.write(sig.getOrigContent());
                else
                    os.write(genFac.signatureToXML(sig));
                os.write("\n".getBytes());
            }
            os.write(xmlTrailer().getBytes());
        }
    } catch (DigiDocException ex) {
        throw ex; // allready handled
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_WRITE_FILE);
    }
}

From source file:org.apache.ant.compress.taskdefs.Zip.java

public Zip() {
    setFactory(new ZipStreamFactory() {
        public ArchiveOutputStream getArchiveStream(OutputStream stream, String encoding) throws IOException {
            ZipArchiveOutputStream o = (ZipArchiveOutputStream) super.getArchiveStream(stream, encoding);
            configure(o);//w w w  .j a va  2  s. c om
            return o;
        }

        public ArchiveOutputStream getArchiveOutputStream(File f, String encoding) throws IOException {
            ZipArchiveOutputStream o = (ZipArchiveOutputStream) super.getArchiveOutputStream(f, encoding);
            configure(o);
            return o;
        }
    });
    setEntryBuilder(new ArchiveBase.EntryBuilder() {
        public ArchiveEntry buildEntry(ArchiveBase.ResourceWithFlags r) {
            boolean isDir = r.getResource().isDirectory();
            ZipArchiveEntry ent = new ZipArchiveEntry(r.getName());
            ent.setTime(round(r.getResource().getLastModified(), 2000));
            ent.setSize(isDir ? 0 : r.getResource().getSize());

            if (!isDir && r.getCollectionFlags().hasModeBeenSet()) {
                ent.setUnixMode(r.getCollectionFlags().getMode());
            } else if (isDir && r.getCollectionFlags().hasDirModeBeenSet()) {
                ent.setUnixMode(r.getCollectionFlags().getDirMode());
            } else if (r.getResourceFlags().hasModeBeenSet()) {
                ent.setUnixMode(r.getResourceFlags().getMode());
            } else {
                ent.setUnixMode(isDir ? ArchiveFileSet.DEFAULT_DIR_MODE : ArchiveFileSet.DEFAULT_FILE_MODE);
            }

            if (r.getResourceFlags().getZipExtraFields() != null) {
                ent.setExtraFields(r.getResourceFlags().getZipExtraFields());
            }

            if (keepCompression && r.getResourceFlags().hasCompressionMethod()) {
                ent.setMethod(r.getResourceFlags().getCompressionMethod());
            }

            return ent;
        }
    });
    setFileSetBuilder(new ArchiveBase.FileSetBuilder() {
        public ArchiveFileSet buildFileSet(Resource dest) {
            ArchiveFileSet afs = new ZipFileSet();
            afs.setSrcResource(dest);
            return afs;
        }
    });
}

From source file:org.callimachusproject.io.CarOutputStream.java

private synchronized void putArchiveEntry(String name, long time, String type, MetaTypeExtraField mtype)
        throws IOException {
    if (!closed.add(name))
        throw new IllegalStateException("Entry has already been added: " + name);
    ZipArchiveEntry entry = new ZipArchiveEntry(name);
    entry.setTime(time);
    entry.addExtraField(mtype);/* ww w.j  a v a  2s.com*/
    if (type != null) {
        entry.addExtraField(new ContentTypeExtraField(type));
    }
    zipStream.putArchiveEntry(entry);
}

From source file:org.codehaus.mojo.unix.maven.zip.ZipUnixPackage.java

private BasicPackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>> directory(
        Directory directory) {//from  w w  w .  j  a  va 2  s .c o m
    F2<UnixFsObject, ZipArchiveOutputStream, IoEffect> f = new F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>() {
        public IoEffect f(final UnixFsObject file, final ZipArchiveOutputStream zos) {
            return new IoEffect() {
                public void run() throws IOException {
                    String path = file.path.isBase() ? "." : file.path.asAbsolutePath("./") + "/";

                    ZipArchiveEntry entry = new ZipArchiveEntry(path);
                    entry.setSize(file.size);
                    entry.setTime(file.lastModified.toDateTime().getMillis());
                    if (file.attributes.mode.isSome()) {
                        entry.setUnixMode(file.attributes.mode.some().toInt());
                    }
                    zos.putArchiveEntry(entry);
                    zos.closeArchiveEntry();
                }
            };
        }
    };

    return basicPackageFSO(directory, f);
}

From source file:org.codehaus.mojo.unix.maven.zip.ZipUnixPackage.java

private BasicPackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>> file(
        final Fs<?> fromFile, UnixFsObject file) {
    F2<UnixFsObject, ZipArchiveOutputStream, IoEffect> f = new F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>() {
        public IoEffect f(final UnixFsObject file, final ZipArchiveOutputStream zos) {
            return new IoEffect() {
                public void run() throws IOException {
                    InputStream inputStream = null;
                    BufferedReader reader = null;
                    try {
                        P2<InputStream, Option<Long>> p = filtersAndLineEndingHandingInputStream(file,
                                fromFile.inputStream());

                        inputStream = p._1();

                        long size = p._2().orSome(file.size);

                        ZipArchiveEntry entry = new ZipArchiveEntry(file.path.asAbsolutePath("./"));
                        entry.setSize(size);
                        entry.setTime(file.lastModified.toDateTime().getMillis());
                        if (file.attributes.mode.isSome()) {
                            entry.setUnixMode(file.attributes.mode.some().toInt());
                        }/*  w  w  w .  j  a  va  2  s . c  o m*/

                        zos.putArchiveEntry(entry);
                        copy(inputStream, zos, 1024 * 128);
                        zos.closeArchiveEntry();
                    } finally {
                        IOUtil.close(inputStream);
                        IOUtil.close(reader);
                    }
                }
            };
        }
    };

    return basicPackageFSO(file, f);
}

From source file:org.dspace.content.packager.AbstractMETSDisseminator.java

/**
 * Make a Zipped up METS package for the given DSpace Object
 *
 * @param context DSpace Context//  w w w .ja v  a 2s.c o m
 * @param dso The DSpace Object
 * @param params Parameters to the Packager script
 * @param pkg Package output stream
 * @throws PackageValidationException
 * @throws AuthorizeException
 * @throws SQLException
 * @throws IOException
 */
protected void writeZipPackage(Context context, DSpaceObject dso, PackageParameters params, OutputStream pkg)
        throws PackageValidationException, CrosswalkException, MetsException, AuthorizeException, SQLException,
        IOException {
    long lmTime = 0;
    if (dso.getType() == Constants.ITEM) {
        lmTime = ((Item) dso).getLastModified().getTime();
    }

    // map of extra streams to put in Zip (these are located during makeManifest())
    MdStreamCache extraStreams = new MdStreamCache();
    ZipArchiveOutputStream zip = new ZipArchiveOutputStream(pkg);
    zip.setComment("METS archive created by DSpace " + Util.getSourceVersion());
    Mets manifest = makeManifest(context, dso, params, extraStreams);

    // copy extra (metadata, license, etc) bitstreams into zip, update manifest
    if (extraStreams != null) {
        for (Map.Entry<MdRef, InputStream> ment : extraStreams.getMap().entrySet()) {
            MdRef ref = ment.getKey();

            // Both Deposit Licenses & CC Licenses which are referenced as "extra streams" may already be
            // included in our Package (if their bundles are already included in the <filSec> section of manifest).
            // So, do a special check to see if we need to link up extra License <mdRef> entries to the bitstream in the <fileSec>.
            // (this ensures that we don't accidentally add the same License file to our package twice)
            linkLicenseRefsToBitstreams(context, params, dso, ref);

            //If this 'mdRef' is NOT already linked up to a file in the package,
            // then its file must be missing.  So, we are going to add a new
            // file to the Zip package.
            if (ref.getXlinkHref() == null || ref.getXlinkHref().isEmpty()) {
                InputStream is = ment.getValue();

                // create a hopefully unique filename within the Zip
                String fname = gensym("metadata");
                // link up this 'mdRef' to point to that file
                ref.setXlinkHref(fname);
                if (log.isDebugEnabled()) {
                    log.debug("Writing EXTRA stream to Zip: " + fname);
                }
                //actually add the file to the Zip package
                ZipArchiveEntry ze = new ZipArchiveEntry(fname);
                if (lmTime != 0) {
                    ze.setTime(lmTime);
                } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged
                {
                    ze.setTime(DEFAULT_MODIFIED_DATE);
                }
                zip.putArchiveEntry(ze);
                Utils.copy(is, zip);
                zip.closeArchiveEntry();

                is.close();
            }
        }
    }

    // write manifest after metadata.
    ZipArchiveEntry me = new ZipArchiveEntry(METSManifest.MANIFEST_FILE);
    if (lmTime != 0) {
        me.setTime(lmTime);
    } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged
    {
        me.setTime(DEFAULT_MODIFIED_DATE);
    }

    zip.putArchiveEntry(me);

    // can only validate now after fixing up extraStreams
    // note: only validate METS if specified (default = true)
    if (params.getBooleanProperty("validate", true)) {
        manifest.validate(new MetsValidator());
    }
    manifest.write(new MetsWriter(zip));
    zip.closeArchiveEntry();

    //write any bitstreams associated with DSpace object to zip package
    addBitstreamsToZip(context, dso, params, zip);

    zip.close();

}

From source file:org.dspace.content.packager.AbstractMETSDisseminator.java

/**
 * Add Bitstreams associated with a given DSpace Object into an
 * existing ZipArchiveOutputStream/*from   w w  w .  jav  a2s.  c om*/
 * @param context DSpace Context
 * @param dso The DSpace Object
 * @param params Parameters to the Packager script
 * @param zip Zip output
 */
protected void addBitstreamsToZip(Context context, DSpaceObject dso, PackageParameters params,
        ZipArchiveOutputStream zip)
        throws PackageValidationException, AuthorizeException, SQLException, IOException {
    // how to handle unauthorized bundle/bitstream:
    String unauth = (params == null) ? null : params.getProperty("unauthorized");

    // copy all non-meta bitstreams into zip
    if (dso.getType() == Constants.ITEM) {
        Item item = (Item) dso;

        //get last modified time
        long lmTime = ((Item) dso).getLastModified().getTime();

        Bundle bundles[] = item.getBundles();
        for (int i = 0; i < bundles.length; i++) {
            if (includeBundle(bundles[i])) {
                // unauthorized bundle?
                if (!AuthorizeManager.authorizeActionBoolean(context, bundles[i], Constants.READ)) {
                    if (unauth != null && (unauth.equalsIgnoreCase("skip"))) {
                        log.warn("Skipping Bundle[\"" + bundles[i].getName()
                                + "\"] because you are not authorized to read it.");
                        continue;
                    } else {
                        throw new AuthorizeException(
                                "Not authorized to read Bundle named \"" + bundles[i].getName() + "\"");
                    }
                }
                Bitstream[] bitstreams = bundles[i].getBitstreams();
                for (int k = 0; k < bitstreams.length; k++) {
                    boolean auth = AuthorizeManager.authorizeActionBoolean(context, bitstreams[k],
                            Constants.READ);
                    if (auth || (unauth != null && unauth.equalsIgnoreCase("zero"))) {
                        String zname = makeBitstreamURL(bitstreams[k], params);
                        ZipArchiveEntry ze = new ZipArchiveEntry(zname);
                        if (log.isDebugEnabled()) {
                            log.debug(new StringBuilder().append("Writing CONTENT stream of bitstream(")
                                    .append(bitstreams[k].getID()).append(") to Zip: ").append(zname)
                                    .append(", size=").append(bitstreams[k].getSize()).toString());
                        }
                        if (lmTime != 0) {
                            ze.setTime(lmTime);
                        } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged
                        {
                            ze.setTime(DEFAULT_MODIFIED_DATE);
                        }
                        ze.setSize(auth ? bitstreams[k].getSize() : 0);
                        zip.putArchiveEntry(ze);
                        if (auth) {
                            InputStream input = bitstreams[k].retrieve();
                            Utils.copy(input, zip);
                            input.close();
                        } else {
                            log.warn("Adding zero-length file for Bitstream, SID="
                                    + String.valueOf(bitstreams[k].getSequenceID())
                                    + ", not authorized for READ.");
                        }
                        zip.closeArchiveEntry();
                    } else if (unauth != null && unauth.equalsIgnoreCase("skip")) {
                        log.warn("Skipping Bitstream, SID=" + String.valueOf(bitstreams[k].getSequenceID())
                                + ", not authorized for READ.");
                    } else {
                        throw new AuthorizeException("Not authorized to read Bitstream, SID="
                                + String.valueOf(bitstreams[k].getSequenceID()));
                    }
                }
            }
        }
    }

    // Coll, Comm just add logo bitstream to content if there is one
    else if (dso.getType() == Constants.COLLECTION || dso.getType() == Constants.COMMUNITY) {
        Bitstream logoBs = dso.getType() == Constants.COLLECTION ? ((Collection) dso).getLogo()
                : ((Community) dso).getLogo();
        if (logoBs != null) {
            String zname = makeBitstreamURL(logoBs, params);
            ZipArchiveEntry ze = new ZipArchiveEntry(zname);
            if (log.isDebugEnabled()) {
                log.debug("Writing CONTENT stream of bitstream(" + String.valueOf(logoBs.getID()) + ") to Zip: "
                        + zname + ", size=" + String.valueOf(logoBs.getSize()));
            }
            ze.setSize(logoBs.getSize());
            //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged
            ze.setTime(DEFAULT_MODIFIED_DATE);
            zip.putArchiveEntry(ze);
            Utils.copy(logoBs.retrieve(), zip);
            zip.closeArchiveEntry();
        }
    }
}