Example usage for java.util.zip ZipEntry setTime

List of usage examples for java.util.zip ZipEntry setTime

Introduction

In this page you can find the example usage for java.util.zip ZipEntry setTime.

Prototype

public void setTime(long time) 

Source Link

Document

Sets the last modification time of the entry.

Usage

From source file:edu.mit.lib.bagit.Filler.java

private void fillZip(File dirFile, String relBase, ZipOutputStream zout) throws IOException {
    for (File file : dirFile.listFiles()) {
        String relPath = relBase + File.separator + file.getName();
        if (file.isDirectory()) {
            fillZip(file, relPath, zout);
        } else {//from www  .  j av  a2 s  .c  o  m
            ZipEntry entry = new ZipEntry(relPath);
            entry.setTime(0L);
            zout.putNextEntry(entry);
            Files.copy(file.toPath(), zout);
            zout.closeEntry();
        }
    }
}

From source file:nl.nn.adapterframework.webcontrol.action.BrowseExecute.java

private void exportMessage(IMessageBrowser mb, String id, ReceiverBase receiver,
        ZipOutputStream zipOutputStream) {
    IListener listener = null;//from   w  w w  .j a v  a  2 s .co m
    if (receiver != null) {
        listener = receiver.getListener();
    }
    try {
        Object rawmsg = mb.browseMessage(id);
        IMessageBrowsingIteratorItem msgcontext = mb.getContext(id);
        try {
            String msg = null;
            String msgId = msgcontext.getId();
            String msgMid = msgcontext.getOriginalId();
            String msgCid = msgcontext.getCorrelationId();
            HashMap context = new HashMap();
            if (listener != null) {
                msg = listener.getStringFromRawMessage(rawmsg, context);
            } else {
                msg = (String) rawmsg;
            }
            if (StringUtils.isEmpty(msg)) {
                msg = "<no message found>";
            }
            if (msgId == null) {
                msgId = "";
            }
            if (msgMid == null) {
                msgMid = "";
            }
            if (msgCid == null) {
                msgCid = "";
            }
            String filename = "msg_" + id + "_id[" + msgId.replace(':', '-') + "]" + "_mid["
                    + msgMid.replace(':', '-') + "]" + "_cid[" + msgCid.replace(':', '-') + "]";
            ZipEntry zipEntry = new ZipEntry(filename + ".txt");

            String sentDateString = (String) context.get(IPipeLineSession.tsSentKey);
            if (StringUtils.isNotEmpty(sentDateString)) {
                try {
                    Date sentDate = DateUtils.parseToDate(sentDateString, DateUtils.FORMAT_FULL_GENERIC);
                    zipEntry.setTime(sentDate.getTime());
                } catch (Throwable e) {
                    error(", ", "errors.generic", "Could not set date for message [" + id + "]", e);
                }
            } else {
                Date insertDate = msgcontext.getInsertDate();
                if (insertDate != null) {
                    zipEntry.setTime(insertDate.getTime());
                }
            }
            //            String comment=msgcontext.getCommentString();
            //            if (StringUtils.isNotEmpty(comment)) {
            //               zipEntry.setComment(comment);
            //            }

            zipOutputStream.putNextEntry(zipEntry);
            String encoding = Misc.DEFAULT_INPUT_STREAM_ENCODING;
            if (msg.startsWith("<?xml")) {
                int lastpos = msg.indexOf("?>");
                if (lastpos > 0) {
                    String prefix = msg.substring(6, lastpos);
                    int encodingStartPos = prefix.indexOf("encoding=\"");
                    if (encodingStartPos > 0) {
                        int encodingEndPos = prefix.indexOf('"', encodingStartPos + 10);
                        if (encodingEndPos > 0) {
                            encoding = prefix.substring(encodingStartPos + 10, encodingEndPos);
                            log.debug("parsed encoding [" + encoding + "] from prefix [" + prefix + "]");
                        }
                    }
                }
            }
            zipOutputStream.write(msg.getBytes(encoding));

            if (listener != null && listener instanceof IBulkDataListener) {
                IBulkDataListener bdl = (IBulkDataListener) listener;
                String bulkfilename = bdl.retrieveBulkData(rawmsg, msg, context);

                zipOutputStream.closeEntry();

                File bulkfile = new File(bulkfilename);

                zipEntry = new ZipEntry(filename + "_" + bulkfile.getName());
                zipEntry.setTime(bulkfile.lastModified());
                zipOutputStream.putNextEntry(zipEntry);
                StreamUtil.copyStream(new FileInputStream(bulkfile), zipOutputStream, 32000);
                bulkfile.delete();
            }
            zipOutputStream.closeEntry();
        } finally {
            msgcontext.release();
        }
    } catch (Throwable e) {
        error(", ", "errors.generic", "Could not export message with id [" + id + "]", e);
    }
}

From source file:org.jumpmind.symmetric.file.FileSyncZipDataWriter.java

public void end(Batch batch, boolean inError) {

    try {//from  w ww .  jav  a2s  .c  o  m
        if (!inError) {
            if (zos == null) {
                zos = new ZipOutputStream(stagedResource.getOutputStream());
            }

            Map<String, LastEventType> entries = new HashMap<String, LastEventType>();
            StringBuilder script = new StringBuilder("fileList = new HashMap();\n");
            for (FileSnapshot snapshot : snapshotEvents) {
                FileTriggerRouter triggerRouter = fileSyncService.getFileTriggerRouter(snapshot.getTriggerId(),
                        snapshot.getRouterId());
                if (triggerRouter != null) {
                    StringBuilder command = new StringBuilder("\n");
                    LastEventType eventType = snapshot.getLastEventType();

                    FileTrigger fileTrigger = triggerRouter.getFileTrigger();

                    String targetBaseDir = ((triggerRouter.getTargetBaseDir() == null) ? null
                            : triggerRouter.getTargetBaseDir().replace('\\', '/'));
                    if (StringUtils.isBlank(targetBaseDir)) {
                        targetBaseDir = ((fileTrigger.getBaseDir() == null) ? null
                                : fileTrigger.getBaseDir().replace('\\', '/'));
                    }
                    targetBaseDir = StringEscapeUtils.escapeJava(targetBaseDir);

                    command.append("targetBaseDir = \"").append(targetBaseDir).append("\";\n");
                    command.append("processFile = true;\n");
                    command.append("sourceFileName = \"").append(snapshot.getFileName()).append("\";\n");
                    command.append("targetRelativeDir = \"");
                    if (!snapshot.getRelativeDir().equals(".")) {
                        command.append(StringEscapeUtils.escapeJava(snapshot.getRelativeDir()));
                        command.append("\";\n");
                    } else {
                        command.append("\";\n");
                    }
                    command.append("targetFileName = sourceFileName;\n");
                    command.append("sourceFilePath = \"");
                    command.append(StringEscapeUtils.escapeJava(snapshot.getRelativeDir())).append("\";\n");

                    StringBuilder entryName = new StringBuilder(Long.toString(batch.getBatchId()));
                    entryName.append("/");
                    if (!snapshot.getRelativeDir().equals(".")) {
                        entryName.append(snapshot.getRelativeDir()).append("/");
                    }
                    entryName.append(snapshot.getFileName());

                    File file = fileTrigger.createSourceFile(snapshot);
                    if (file.isDirectory()) {
                        entryName.append("/");
                    }

                    if (StringUtils.isNotBlank(fileTrigger.getBeforeCopyScript())) {
                        command.append(fileTrigger.getBeforeCopyScript()).append("\n");
                    }

                    command.append("if (processFile) {\n");
                    String targetFile = "targetBaseDir + \"/\" + targetRelativeDir + \"/\" + targetFileName";

                    switch (eventType) {
                    case CREATE:
                    case MODIFY:
                        if (file.exists()) {
                            command.append("  File targetBaseDirFile = new File(targetBaseDir);\n");
                            command.append("  if (!targetBaseDirFile.exists()) {\n");
                            command.append("    targetBaseDirFile.mkdirs();\n");
                            command.append("  }\n");
                            command.append("  java.io.File sourceFile = new java.io.File(batchDir + \"/\"");
                            if (!snapshot.getRelativeDir().equals(".")) {
                                command.append(" + sourceFilePath + \"/\"");
                            }
                            command.append(" + sourceFileName");
                            command.append(");\n");

                            command.append("  java.io.File targetFile = new java.io.File(");
                            command.append(targetFile);
                            command.append(");\n");

                            // no need to copy directory if it already exists
                            command.append("  if (targetFile.exists() && targetFile.isDirectory()) {\n");
                            command.append("      processFile = false;\n");
                            command.append("  }\n");

                            // conflict resolution
                            FileConflictStrategy conflictStrategy = triggerRouter.getConflictStrategy();
                            if (conflictStrategy == FileConflictStrategy.TARGET_WINS
                                    || conflictStrategy == FileConflictStrategy.MANUAL) {
                                command.append("  if (targetFile.exists() && !targetFile.isDirectory()) {\n");
                                command.append(
                                        "    long targetChecksum = org.apache.commons.io.FileUtils.checksumCRC32(targetFile);\n");
                                command.append("    if (targetChecksum != " + snapshot.getOldCrc32Checksum()
                                        + "L) {\n");
                                if (conflictStrategy == FileConflictStrategy.MANUAL) {
                                    command.append(
                                            "      throw new org.jumpmind.symmetric.file.FileConflictException(targetFileName + \" was in conflict \");\n");
                                } else {
                                    command.append("      processFile = false;\n");
                                }
                                command.append("    }\n");
                                command.append("  }\n");
                            }

                            command.append("  if (processFile) {\n");
                            command.append("    if (sourceFile.isDirectory()) {\n");
                            command.append(
                                    "      org.apache.commons.io.FileUtils.copyDirectory(sourceFile, targetFile, true);\n");
                            command.append("    } else {\n");
                            command.append(
                                    "      org.apache.commons.io.FileUtils.copyFile(sourceFile, targetFile, true);\n");
                            command.append("    }\n");
                            command.append("  }\n");
                            command.append("  fileList.put(").append(targetFile).append(",\"");
                            command.append(eventType.getCode());
                            command.append("\");\n");
                        }
                        break;
                    case DELETE:
                        command.append("  org.apache.commons.io.FileUtils.deleteQuietly(new java.io.File(");
                        command.append(targetFile);
                        command.append("));\n");
                        command.append("  fileList.put(").append(targetFile).append(",\"");
                        command.append(eventType.getCode());
                        command.append("\");\n");
                        break;
                    default:
                        break;
                    }

                    if (StringUtils.isNotBlank(fileTrigger.getAfterCopyScript())) {
                        command.append(fileTrigger.getAfterCopyScript()).append("\n");
                    }

                    LastEventType previousEventForEntry = entries.get(entryName.toString());
                    boolean process = true;
                    if (previousEventForEntry != null) {
                        if ((previousEventForEntry == eventType)
                                || (previousEventForEntry == LastEventType.CREATE
                                        && eventType == LastEventType.MODIFY)) {
                            process = false;
                        }
                    }

                    if (process) {
                        if (eventType != LastEventType.DELETE) {
                            if (file.exists()) {
                                byteCount += file.length();
                                ZipEntry entry = new ZipEntry(entryName.toString());
                                entry.setSize(file.length());
                                entry.setTime(file.lastModified());
                                zos.putNextEntry(entry);
                                if (file.isFile()) {
                                    FileInputStream fis = new FileInputStream(file);
                                    try {
                                        IOUtils.copy(fis, zos);
                                    } finally {
                                        IOUtils.closeQuietly(fis);
                                    }
                                }
                                zos.closeEntry();
                                entries.put(entryName.toString(), eventType);
                            } else {
                                log.warn(
                                        "Could not find the {} file to package for synchronization.  Skipping it.",
                                        file.getAbsolutePath());
                            }
                        }

                        command.append("}\n\n");
                        script.append(command.toString());

                    }

                } else {
                    log.error(
                            "Could not locate the file trigger ({}) router ({}) to process a snapshot event.  The event will be ignored",
                            snapshot.getTriggerId(), snapshot.getRouterId());
                }
            }

            script.append("return fileList;\n");
            ZipEntry entry = new ZipEntry(batch.getBatchId() + "/sync.bsh");
            zos.putNextEntry(entry);
            IOUtils.write(script.toString(), zos);
            zos.closeEntry();

            entry = new ZipEntry(batch.getBatchId() + "/batch-info.txt");
            zos.putNextEntry(entry);
            IOUtils.write(batch.getChannelId(), zos);
            zos.closeEntry();

        }
    } catch (IOException e) {
        throw new IoException(e);
    }

}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

protected void writeSkinZipEntries(String prefix, File dir, ZipOutputStream out) throws IOException {
    if (dir.isDirectory()) {
        if (prefix.length() > 0) {
            prefix = prefix + "/";
        }/*  ww w  . j a v a2  s.c  om*/
        File[] myChildren = dir.listFiles();
        for (File myFile : myChildren) {
            if (myFile.isFile()) {
                writeZipEntry(prefix, out, myFile);
            } else {
                ZipEntry mySkinFile = new ZipEntry(prefix + myFile.getName() + "/");
                mySkinFile.setTime(myFile.lastModified());
                out.putNextEntry(mySkinFile);
                out.write(new byte[0]);
                out.closeEntry();
                writeSkinZipEntries(prefix + myFile.getName(), myFile, out);
            }
        }
    }
}

From source file:org.codehaus.plexus.archiver.zip.ZipArchiverTest.java

public void testZipStuff() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    // name the file inside the zip  file
    final File oddFile = new File("src/test/resources/zip-timestamp/file-with-odd-time.txt");
    final File evenFile = new File("src/test/resources/zip-timestamp/file-with-even-time.txt");
    final ZipEntry oddZe = new ZipEntry(oddFile.getName());
    oddZe.setTime(oddFile.lastModified());
    zos.putNextEntry(oddZe);/*from w w w .ja  v  a  2  s .com*/
    final ZipEntry evenZe = new ZipEntry(evenFile.getName());
    evenZe.setTime(evenFile.lastModified());
    zos.putNextEntry(evenZe);
    zos.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ZipInputStream zipInputStream = new ZipInputStream(bais);
    final java.util.zip.ZipEntry oddEntry = zipInputStream.getNextEntry();
    System.out.println("oddEntry.getTime() = " + new Date(oddEntry.getTime()).toString());
    System.out.println("oddEntry.getName() = " + oddEntry.getName());
    final java.util.zip.ZipEntry evenEntry = zipInputStream.getNextEntry();
    System.out.println("evenEntry.getName() = " + evenEntry.getName());
    System.out.println("evenEntry.getTime() = " + new Date(evenEntry.getTime()).toString());
}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

private void writeZipEntry(String prefix, ZipOutputStream out, File file)
        throws IOException, FileNotFoundException {
    ZipEntry mySkinFile = new ZipEntry(prefix + file.getName());
    mySkinFile.setSize(file.length());/*from  w ww .j ava 2  s  . co  m*/
    mySkinFile.setTime(file.lastModified());
    out.putNextEntry(mySkinFile);

    byte[] buf = new byte[1024];
    InputStream in = new FileInputStream(file);
    try {
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    } finally {
        in.close();
    }
    // Complete the entry
    out.closeEntry();
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

@Override
public void doDump(OutputStream out) throws IOException {
    final ZipOutputStream zout = new ZipOutputStream(out);
    final int cutLength = this.repositoryRoot.toString().length() + 1;

    Files.walkFileTree(this.repositoryRoot, new SimpleFileVisitor<Path>() {

        @Override/*from   ww w .j a va 2  s .  c om*/
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            if (dir.endsWith(".git")) {
                return FileVisitResult.SKIP_SUBTREE;
            } else {
                return FileVisitResult.CONTINUE;
            }
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            String name = file.toString().substring(cutLength);
            ZipEntry ze = new ZipEntry(name);
            try {
                ze.setTime(Files.getLastModifiedTime(file).toMillis());
                ze.setSize(Files.size(file));
                zout.putNextEntry(ze);
                Files.copy(file, zout);
                zout.closeEntry();
            } catch (IOException e) {
                FilebasedRepository.logger.debug(e.getMessage());
            }
            return FileVisitResult.CONTINUE;
        }
    });
    zout.close();
}

From source file:org.codehaus.plexus.archiver.zip.AbstractZipArchiver.java

private void setTime(java.util.zip.ZipEntry zipEntry, long lastModified) {
    zipEntry.setTime(lastModified + (isJava7OrLower ? 1999 : 0));

    /*   Consider adding extended file stamp support.....
            // ww w .ja  v a 2 s .c  o  m
    X5455_ExtendedTimestamp ts =  new X5455_ExtendedTimestamp();
    ts.setModifyJavaTime(new Date(lastModified));
    if (zipEntry.getExtra() != null){
       // Uh-oh. What do we do now.
       throw new IllegalStateException("DIdnt expect to see xtradata here ?");
            
    }  else {
       zipEntry.setExtra(ts.getLocalFileDataData());
    }
      */
}

From source file:com.taobao.android.builder.tools.multidex.FastMultiDexer.java

protected void copyStream(InputStream inputStream, JarOutputStream jos, JarEntry ze, String pathName) {
    try {/*from  ww  w.ja  v a2s  . co m*/

        ZipEntry newEntry = new ZipEntry(pathName);
        // Make sure there is date and time set.
        if (ze.getTime() != -1) {
            newEntry.setTime(ze.getTime()); // If found set it into output file.
        }
        jos.putNextEntry(newEntry);
        IOUtils.copy(inputStream, jos);
        IOUtils.closeQuietly(inputStream);
    } catch (Exception e) {
        throw new GradleException("copy stream exception", e);
    }
}

From source file:org.zeroturnaround.zip.ZipsTest.java

public void testTransformationPreservesTimestamps() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File source = File.createTempFile("temp", ".zip");
    File destination = File.createTempFile("temp", ".zip");
    try {/*from  w w  w .j a  v a  2 s.c  o m*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(source));
        try {
            for (int i = 0; i < 2; i++) {
                // we need many entries, some are transformed, some just copied.
                ZipEntry e = new ZipEntry(name + (i == 0 ? "" : "" + i));
                // 5 seconds ago.
                e.setTime(System.currentTimeMillis() - 5000);
                zos.putNextEntry(e);
                zos.write(contents);
                zos.closeEntry();
            }
        } finally {
            IOUtils.closeQuietly(zos);
        }
        // Transform the ZIP file
        ZipEntryTransformer transformer = new ByteArrayZipEntryTransformer() {
            protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException {
                String s = new String(input);
                assertEquals(new String(contents), s);
                return s.toUpperCase().getBytes();
            }

            protected boolean preserveTimestamps() {
                // transformed entries preserve timestamps thanks to this.
                return true;
            }
        };
        Zips.get(source).destination(destination).preserveTimestamps().addTransformer(name, transformer)
                .process();

        final ZipFile zf = new ZipFile(source);
        try {
            Zips.get(destination).iterate(new ZipEntryCallback() {
                public void process(InputStream in, ZipEntry zipEntry) throws IOException {
                    String name = zipEntry.getName();
                    assertEquals("Timestapms differ at entry " + name, zf.getEntry(name).getTime(),
                            zipEntry.getTime());
                }
            });
        } finally {
            ZipUtil.closeQuietly(zf);
        }
        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(destination, name);
        assertNotNull(actual);
        assertEquals(new String(contents).toUpperCase(), new String(actual));
    } finally {
        FileUtils.deleteQuietly(source);
        FileUtils.deleteQuietly(destination);
    }

}