Example usage for java.util.zip ZipEntry getTime

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

Introduction

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

Prototype

public long getTime() 

Source Link

Document

Returns the last modification time of the entry.

Usage

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 {/*w w  w. j a  va  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);
    }

}

From source file:org.dbgl.util.FileUtils.java

public static void extractEntry(final ZipFile zf, final ZipEntry srcEntry, final File dstFile,
        final ProgressNotifyable prog) throws IOException {
    File foundDstFile = null, temporarilyRenamedFile = null;
    if (PlatformUtils.IS_WINDOWS && dstFile.getName().contains("~")) {
        foundDstFile = dstFile.getCanonicalFile();
        if (!foundDstFile.getName().equals(dstFile.getName()) && foundDstFile.exists()) {
            temporarilyRenamedFile = getUniqueFileName(foundDstFile);
            foundDstFile.renameTo(temporarilyRenamedFile);
        }/*w  ww  .j  av a2s.c o m*/
    }

    if (dstFile.exists())
        throw new IOException(
                Settings.getInstance().msg("general.error.filetobeextractedexists", new Object[] { dstFile }));
    if (srcEntry.isDirectory()) {
        if (!dstFile.exists())
            createDir(dstFile);
    } else {
        if (dstFile.getParentFile() != null)
            createDir(dstFile.getParentFile());
        FileOutputStream fos = new FileOutputStream(dstFile);
        InputStream is = zf.getInputStream(srcEntry);
        byte[] readBuffer = new byte[ZIP_BUFFER];
        int bytesIn;
        while ((bytesIn = is.read(readBuffer)) != -1)
            fos.write(readBuffer, 0, bytesIn);
        fos.flush();
        fos.close();
        is.close();
        byte[] extra = srcEntry.getExtra();
        if ((extra != null) && (extra.length == 1) && (extra[0] == 1))
            fileSetReadOnly(dstFile);
    }
    fileSetLastModified(dstFile, srcEntry.getTime());

    if (foundDstFile != null && temporarilyRenamedFile != null)
        temporarilyRenamedFile.renameTo(foundDstFile);

    prog.incrProgress((int) (srcEntry.getSize() / 1024));
}

From source file:net.solarnetwork.node.backup.DefaultBackupManager.java

@Override
public void importBackupArchive(InputStream archive) throws IOException {
    final ZipInputStream zin = new ZipInputStream(archive);
    while (true) {
        final ZipEntry entry = zin.getNextEntry();
        if (entry == null) {
            break;
        }//from   w  ww.j a v  a2s .c  o  m
        final String path = entry.getName();
        log.debug("Restoring backup resource {}", path);
        final int providerIndex = path.indexOf('/');
        if (providerIndex != -1) {
            final String providerKey = path.substring(0, providerIndex);
            for (BackupResourceProvider provider : resourceProviders) {
                if (providerKey.equals(provider.getKey())) {
                    provider.restoreBackupResource(new BackupResource() {

                        @Override
                        public String getBackupPath() {
                            return path.substring(providerIndex + 1);
                        }

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return new FilterInputStream(zin) {

                                @Override
                                public void close() throws IOException {
                                    // don't close me
                                }

                            };
                        }

                        @Override
                        public long getModificationDate() {
                            return entry.getTime();
                        }

                    });
                    break;
                }
            }
        }
    }
}

From source file:de.xirp.plugin.PluginManager.java

/**
 * Extracts files from the plugins jar.//ww w.j a  va2s. c o m
 * 
 * @param info
 *            the information about the plugin
 * @param destination
 *            destination for extraction
 * @param comparer
 *            comparer which returns <code>0</code> if an
 *            element from the jar should be extracted
 * @param replace
 *            string of the elements path which should be deleted
 * @param deleteOnExit
 *            <code>true</code> if the extracted files should be
 *            deleted on exit of the application.
 * @return <code>false</code> if an error occurred while
 *         extraction
 */
private static boolean extractFromJar(PluginInfo info, String destination, Comparable<String> comparer,
        String replace, boolean deleteOnExit) {
    if (logClass.isTraceEnabled()) {
        logClass.trace(Constants.LINE_SEPARATOR + "Extracting for Plugin: " + info.getDefaultName() //$NON-NLS-1$
                + " to path " + destination + Constants.LINE_SEPARATOR); //$NON-NLS-1$
    }
    ZipInputStream zip = null;
    FileInputStream in = null;
    try {
        in = new FileInputStream(info.getAbsoluteJarPath());
        zip = new ZipInputStream(in);

        ZipEntry entry = null;
        while ((entry = zip.getNextEntry()) != null) {
            // relative name with slashes to separate dirnames.
            String elementName = entry.getName();
            // Check if it's an entry within Plugin Dir.
            // Only need to extract these

            if (comparer.compareTo(elementName) == 0) {
                // Remove Help Dir Name, because we don't like
                // to extract this parent dir
                elementName = elementName.replaceFirst(replace + JAR_SEPARATOR, "").trim(); //$NON-NLS-1$ 

                if (!elementName.equalsIgnoreCase("")) { //$NON-NLS-1$
                    // if parent dir for File does not exist,
                    // create
                    // it
                    File elementFile = new File(destination, elementName);
                    if (!elementFile.exists()) {
                        elementFile.getParentFile().mkdirs();
                        if (deleteOnExit) {
                            DeleteManager.deleteOnShutdown(elementFile);
                        }
                    }

                    // Only extract files, directorys are created
                    // above with mkdirs
                    if (!entry.isDirectory()) {
                        FileOutputStream fos = new FileOutputStream(elementFile);
                        byte[] buf = new byte[1024];
                        int len;
                        while ((len = zip.read(buf)) > 0) {
                            fos.write(buf, 0, len);
                        }
                        fos.close();
                        elementFile.setLastModified(entry.getTime());
                    }
                    logClass.trace("Extracted: " + elementName + Constants.LINE_SEPARATOR); //$NON-NLS-1$
                }
            }
            zip.closeEntry();
        }

    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
        return false;
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logClass.error("Error: " + e.getMessage() + Constants.LINE_SEPARATOR, e); //$NON-NLS-1$
            }
        }
    }

    return true;
}

From source file:me.piebridge.bible.Bible.java

private boolean unpackZip(File path) throws IOException {
    if (path == null || !path.isFile()) {
        return false;
    }/*w  ww  . j a va2s. co m*/

    File dirpath = getExternalFilesDirWrapper();

    // bibledata-zh-cn-version.zip
    String filename = path.getAbsolutePath();
    int sep = filename.lastIndexOf("-");
    if (sep != -1) {
        filename = filename.substring(sep + 1, filename.length() - 4);
    }
    filename += ".sqlite3";

    InputStream is = new FileInputStream(path);
    long fileSize = path.length();
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    try {
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            long zeSize = ze.getCompressedSize();
            // zip is incomplete
            if (fileSize < zeSize) {
                break;
            }
            String zename = ze.getName();
            if (zename == null || !zename.endsWith((".sqlite3"))) {
                continue;
            }
            sep = zename.lastIndexOf(File.separator);
            if (sep != -1) {
                zename = zename.substring(sep + 1);
            }
            File file;
            String version = zename.toLowerCase(Locale.US).replace(".sqlite3", "");
            if (versionpaths.containsKey(version)) {
                file = new File(versionpaths.get(version));
            } else {
                file = new File(dirpath, zename);
            }
            if (file.exists() && file.lastModified() > ze.getTime()
                    && file.lastModified() > path.lastModified()) {
                continue;
            }
            Log.d(TAG, "unpacking " + file.getAbsoluteFile());
            int length;
            File tmpfile = new File(dirpath, zename + ".tmp");
            OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpfile));
            byte[] buffer = new byte[8192];
            int zero = 0;
            while ((length = zis.read(buffer)) != -1) {
                if (length == 0) {
                    ++zero;
                    if (zero > 3) {
                        break;
                    }
                } else {
                    zero = 0;
                }
                os.write(buffer, 0, length);
            }
            os.close();
            if (zero > 3) {
                return false;
            } else {
                tmpfile.renameTo(file);
                path.delete();
                return true;
            }
        }
    } finally {
        is.close();
        zis.close();
    }
    return false;
}

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

/**
 * Compares meta-data of two ZIP entries.
 * <p>/*from w  w w . jav a 2 s  .  c o  m*/
 * Two entries are considered the same if
 * <ol>
 * <li>both entries exist,</li>
 * <li>both entries are either directories or files,</li>
 * <li>both entries have the same size,</li>
 * <li>both entries have the same CRC.</li>
 * </ol>
 *
 * @param path
 *          name of the entries.
 * @param e1
 *          first entry (required).
 * @param e2
 *          second entry (may be <code>null</code>).
 * @return <code>true</code> if no difference was found.
 */
private static boolean metaDataEquals(String path, ZipEntry e1, ZipEntry e2) throws IOException {
    // Check if the same entry exists in the second archive
    if (e2 == null) {
        log.debug("Entry '{}' removed.", path);
        return false;
    }

    // Check the directory flag
    if (e1.isDirectory()) {
        if (e2.isDirectory()) {
            return true; // Let's skip the directory as there is nothing to compare
        } else {
            log.debug("Entry '{}' not a directory any more.", path);
            return false;
        }
    } else if (e2.isDirectory()) {
        log.debug("Entry '{}' now a directory.", path);
        return false;
    }

    // Check the size
    long size1 = e1.getSize();
    long size2 = e2.getSize();
    if (size1 != -1 && size2 != -1 && size1 != size2) {
        log.debug("Entry '" + path + "' size changed (" + size1 + " vs " + size2 + ").");
        return false;
    }

    // Check the CRC
    long crc1 = e1.getCrc();
    long crc2 = e2.getCrc();
    if (crc1 != -1 && crc2 != -1 && crc1 != crc2) {
        log.debug("Entry '" + path + "' CRC changed (" + crc1 + " vs " + crc2 + ").");
        return false;
    }

    // Check the time (ignored, logging only)
    if (log.isTraceEnabled()) {
        long time1 = e1.getTime();
        long time2 = e2.getTime();
        if (time1 != -1 && time2 != -1 && time1 != time2) {
            log.trace(
                    "Entry '" + path + "' time changed (" + new Date(time1) + " vs " + new Date(time2) + ").");
        }
    }

    return true;
}

From source file:com.httrack.android.HTTrackActivity.java

/**
 * Get the resource directory. Create it if necessary. Resources are created
 * in the dedicated cache, so that the files can be uninstalled upon
 * application removal./*ww  w  .j a v a  2 s . c  o m*/
 **/
private File buildResourceFile() {
    final File cache = android.os.Build.VERSION.SDK_INT >= VERSION_CODES.FROYO ? getExternalCacheDir()
            : getCacheDir();
    final File rscPath = new File(cache, "resources");
    final File stampFile = new File(rscPath, "resources.stamp");
    final long stamp = installOrUpdateTime();

    // Check timestamp of resources. If the applicate has been updated,
    // recreated cached resources.
    if (rscPath.exists()) {
        long diskStamp = 0;
        try {
            if (stampFile.exists()) {
                final FileReader reader = new FileReader(stampFile);
                final BufferedReader lreader = new BufferedReader(reader);
                try {
                    diskStamp = Long.parseLong(lreader.readLine());
                } catch (final NumberFormatException nfe) {
                    diskStamp = 0;
                }
                lreader.close();
                reader.close();
            }
        } catch (final IOException io) {
            diskStamp = 0;
        }
        // Different one: wipe and recreate
        if (stamp != diskStamp) {
            Log.i(getClass().getSimpleName(), "deleting old resources " + rscPath.getAbsolutePath()
                    + " (app_stamp=" + stamp + " != disk_stamp=" + diskStamp + ")");
            CleanupActivity.deleteRecursively(rscPath);
        } else {
            Log.i(getClass().getSimpleName(),
                    "keeping resources " + rscPath.getAbsolutePath() + " (app_stamp=disk_stamp=" + stamp + ")");
        }
    }

    // Recreate resources ?
    if (!rscPath.exists()) {
        Log.i(getClass().getSimpleName(),
                "creating resources " + rscPath.getAbsolutePath() + " with stamp " + stamp);
        if (HTTrackActivity.mkdirs(rscPath)) {
            long totalSize = 0;
            int totalFiles = 0;
            try {
                final InputStream zipStream = getResources().openRawResource(R.raw.resources);
                final ZipInputStream file = new ZipInputStream(zipStream);
                ZipEntry entry;
                while ((entry = file.getNextEntry()) != null) {
                    final File dest = new File(rscPath.getAbsoluteFile() + "/" + entry.getName());
                    if (entry.getName().endsWith("/")) {
                        dest.mkdirs();
                    } else {
                        final FileOutputStream writer = new FileOutputStream(dest);
                        final byte[] bytes = new byte[1024];
                        int length;
                        while ((length = file.read(bytes)) >= 0) {
                            writer.write(bytes, 0, length);
                            totalSize += length;
                        }
                        writer.close();
                        totalFiles++;
                        dest.setLastModified(entry.getTime());
                    }
                }
                file.close();
                zipStream.close();
                Log.i(getClass().getSimpleName(), "created resources " + rscPath.getAbsolutePath() + " ("
                        + totalFiles + " files, " + totalSize + " bytes)");

                // Write stamp
                final FileWriter writer = new FileWriter(stampFile);
                final BufferedWriter lwriter = new BufferedWriter(writer);
                lwriter.write(Long.toString(stamp));
                lwriter.close();
                writer.close();

                // Little info
                showNotification(getString(R.string.info_recreated_resources));
            } catch (final IOException io) {
                Log.w(getClass().getSimpleName(), "could not create resources", io);
                CleanupActivity.deleteRecursively(rscPath);
                showNotification(getString(R.string.info_could_not_create_resources), true);
            }
        }
    }

    // Return resources path
    return rscPath;
}