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:com.facebook.buck.util.zip.ZipScrubberTest.java

@Test
public void modificationZip64Times() throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] data = "data1".getBytes(Charsets.UTF_8);
    try (ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream)) {
        for (long i = 0; i < 2 * Short.MAX_VALUE + 1; i++) {
            ZipEntry entry = new ZipEntry("file" + i);
            entry.setSize(data.length);//from ww w . j av  a  2 s.  c om
            out.putNextEntry(entry);
            out.write(data);
            out.closeEntry();
        }
    }

    byte[] bytes = byteArrayOutputStream.toByteArray();
    ZipScrubber.scrubZipBuffer(bytes.length, ByteBuffer.wrap(bytes));

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(bytes))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

From source file:org.ngrinder.common.util.CompressionUtil.java

/**
 * Unpack the given jar file./*from   ww w  .  j  a  v  a 2  s  .c  o  m*/
 * 
 * @param jarFile
 *            file to be uncompressed
 * @param destDir
 *            destination directory
 * @throws IOException
 *             occurs when IO has a problem.
 */
public static void unjar(File jarFile, String destDir) throws IOException {
    File dest = new File(destDir);
    if (!dest.exists()) {
        dest.mkdirs();
    }
    if (!dest.isDirectory()) {
        LOGGER.error("Destination must be a directory.");
        throw new IOException("Destination must be a directory.");
    }
    JarInputStream jin = new JarInputStream(new FileInputStream(jarFile));
    byte[] buffer = new byte[1024];

    ZipEntry entry = jin.getNextEntry();
    while (entry != null) {
        String fileName = entry.getName();
        if (fileName.charAt(fileName.length() - 1) == '/') {
            fileName = fileName.substring(0, fileName.length() - 1);
        }
        if (fileName.charAt(0) == '/') {
            fileName = fileName.substring(1);
        }
        if (File.separatorChar != '/') {
            fileName = fileName.replace('/', File.separatorChar);
        }
        File file = new File(dest, fileName);
        if (entry.isDirectory()) {
            // make sure the directory exists
            file.mkdirs();
            jin.closeEntry();
        } else {
            // make sure the directory exists
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            // dump the file
            OutputStream out = new FileOutputStream(file);
            int len = 0;
            while ((len = jin.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            IOUtils.closeQuietly(out);
            jin.closeEntry();
            file.setLastModified(entry.getTime());
        }
        entry = jin.getNextEntry();
    }
    Manifest mf = jin.getManifest();
    if (mf != null) {
        File file = new File(dest, "META-INF/MANIFEST.MF");
        File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(file);
        mf.write(out);
        out.flush();
        IOUtils.closeQuietly(out);
    }
    IOUtils.closeQuietly(jin);
}

From source file:org.java.plugin.standard.ShadingPathResolver.java

static void unpack(final InputStream strm, final File destFolder) throws IOException {
    ZipInputStream zipStrm = new ZipInputStream(strm);
    ZipEntry entry = zipStrm.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        File entryFile = new File(destFolder.getCanonicalPath() + "/" + name); //$NON-NLS-1$
        if (name.endsWith("/")) { //$NON-NLS-1$
            if (!entryFile.exists() && !entryFile.mkdirs()) {
                throw new IOException("can't create folder " + entryFile); //$NON-NLS-1$
            }/* w ww. j av a2 s. c  o m*/
        } else {
            File folder = entryFile.getParentFile();
            if (!folder.exists() && !folder.mkdirs()) {
                throw new IOException("can't create folder " + folder); //$NON-NLS-1$
            }
            OutputStream out = new BufferedOutputStream(new FileOutputStream(entryFile, false));
            try {
                IoUtil.copyStream(zipStrm, out, 1024);
            } finally {
                out.close();
            }
        }
        entryFile.setLastModified(entry.getTime());
        entry = zipStrm.getNextEntry();
    }
}

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

public void testOverwritingTimestamps() throws IOException {
    File src = new File(MainExamplesTest.DEMO_ZIP);

    File dest = File.createTempFile("temp", ".zip");
    final ZipFile zf = new ZipFile(src);
    try {/*from   w  ww. j  a  v a  2 s  .c o m*/
        Zips.get(src).addEntries(new ZipEntrySource[0]).destination(dest).process();
        Zips.get(dest).iterate(new ZipEntryCallback() {
            public void process(InputStream in, ZipEntry zipEntry) throws IOException {
                String name = zipEntry.getName();
                // original timestamp is believed to be earlier than test execution time.
                assertTrue("Timestapms were carried over for entry " + name,
                        zf.getEntry(name).getTime() < zipEntry.getTime());
            }
        });
    } finally {
        ZipUtil.closeQuietly(zf);
        FileUtils.deleteQuietly(dest);
    }
}

From source file:org.jahia.utils.maven.plugin.DeployMojo.java

private void hotSwap(File deployedJar) {
    int colonIndex = address.indexOf(':');
    String connectorName = address.substring(0, colonIndex);
    if (connectorName.equals("socket"))
        connectorName = "com.sun.jdi.SocketAttach";
    else if (connectorName.equals("shmem"))
        connectorName = "com.sun.jdi.SharedMemoryAttach";
    String argumentsString = address.substring(colonIndex + 1);

    AttachingConnector connector = (AttachingConnector) findConnector(connectorName);
    Map<String, Argument> arguments = connector.defaultArguments();

    StringTokenizer st = new StringTokenizer(argumentsString, ",");
    while (st.hasMoreTokens()) {
        String pair = st.nextToken();
        int index = pair.indexOf('=');
        String name = pair.substring(0, index);
        String value = pair.substring(index + 1);
        Connector.Argument argument = (Connector.Argument) arguments.get(name);
        if (argument != null) {
            argument.setValue(value);//  ww w  . jav  a  2  s  .  co  m
        }
    }

    Map<String, Long> dates = new HashMap<String, Long>();
    try {
        ZipInputStream z = new ZipInputStream(new FileInputStream(deployedJar));
        ZipEntry entry;
        while ((entry = z.getNextEntry()) != null) {
            dates.put(entry.getName(), entry.getTime());
        }
        z.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    VirtualMachine vm = null;
    try {
        vm = connector.attach(arguments);
        getLog().info("Connected to " + vm.name() + " " + vm.version());

        Map<String, File> files = new HashMap<String, File>();

        parse(new File(output, "classes"), dates, "", files);
        getLog().debug("Classes : " + files.keySet());
        if (!files.isEmpty()) {
            reload(vm, files);
        }
    } catch (ConnectException e) {
        getLog().warn("Cannot hotswap classes : " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalConnectorArgumentsException e) {
        e.printStackTrace();
    } finally {
        if (vm != null) {
            vm.dispose();
        }
    }
}

From source file:org.eclipse.smila.connectivity.framework.compound.zip.ZipCompoundCrawler.java

/**
 * Read attribute value.//from   w ww .  j a v  a2 s  . com
 * 
 * @param zipEntry
 *          the ZipEntry
 * @param attribute
 *          the attribute
 * @param forceByteToString
 *          the force byte to string
 * 
 * @return the object
 * 
 * @throws CrawlerException
 *           the crawler exception
 */
private Serializable readAttribute(final ZipEntry zipEntry, final CompoundHandling.CompoundAttribute attribute,
        final boolean forceByteToString) throws CrawlerException {
    switch (attribute.getElementAttribute()) {
    case NAME:
        return FilenameUtils.getName(zipEntry.getName());
    case FILE_EXTENSION:
        return FilenameUtils.getExtension(zipEntry.getName());
    case PATH:
        return zipEntry.getName();
    case LAST_MODIFIED_DATE:
        return new Date(zipEntry.getTime());
    case SIZE:
        return new Long(zipEntry.getSize());
    case CONTENT:
        try {
            final byte[] bytes = readZipEntryContent(zipEntry);
            if (forceByteToString) {
                final String encoding = EncodingHelper.getEncoding(bytes);
                if (encoding != null) {
                    return IOUtils.toString(new ByteArrayInputStream(bytes), encoding);
                } else {
                    return IOUtils.toString(new ByteArrayInputStream(bytes));
                }
            } else {
                return bytes;
            }
        } catch (final IOException e) {
            throw new CrawlerException(e);
        }
    default:
        throw new RuntimeException(
                "Unknown compound element attributes type " + attribute.getElementAttribute());
    }
}

From source file:org.java.plugin.standard.ShadingPathResolver.java

static void unpack(final ZipFile zipFile, final File destFolder) throws IOException {
    for (Enumeration en = zipFile.entries(); en.hasMoreElements();) {
        ZipEntry entry = (ZipEntry) en.nextElement();
        String name = entry.getName();
        File entryFile = new File(destFolder.getCanonicalPath() + "/" + name); //$NON-NLS-1$
        if (name.endsWith("/")) { //$NON-NLS-1$
            if (!entryFile.exists() && !entryFile.mkdirs()) {
                throw new IOException("can't create folder " + entryFile); //$NON-NLS-1$
            }/*from  w  w w  . java2s .  co  m*/
        } else {
            File folder = entryFile.getParentFile();
            if (!folder.exists() && !folder.mkdirs()) {
                throw new IOException("can't create folder " + folder); //$NON-NLS-1$
            }
            OutputStream out = new BufferedOutputStream(new FileOutputStream(entryFile, false));
            try {
                InputStream in = zipFile.getInputStream(entry);
                try {
                    IoUtil.copyStream(in, out, 1024);
                } finally {
                    in.close();
                }
            } finally {
                out.close();
            }
        }
        entryFile.setLastModified(entry.getTime());
    }
}

From source file:com.gelakinetic.selfr.CameraActivity.java

/**
 * Helper function to return the build date of this APK
 *
 * @return A build date for this APK, or null if it could not be determined
 *///from   w  w w. j a v  a  2  s .c  o  m
private String getBuildDate() {
    try {
        ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0);
        ZipFile zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        String s = SimpleDateFormat.getInstance().format(new java.util.Date(time));
        zf.close();
        return s;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.facebook.buck.util.zip.ZipScrubberTest.java

@Test
public void modificationTimes() throws Exception {

    // Create a dummy ZIP file.
    ByteArrayOutputStream bytesOutputStream = new ByteArrayOutputStream();
    try (ZipOutputStream out = new ZipOutputStream(bytesOutputStream)) {
        ZipEntry entry = new ZipEntry("file1");
        byte[] data = "data1".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);//from   w  w w .j av a 2  s .  c  o m
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();

        entry = new ZipEntry("file2");
        data = "data2".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();
    }

    byte[] bytes = bytesOutputStream.toByteArray();
    // Execute the zip scrubber step.
    ZipScrubber.scrubZipBuffer(bytes.length, ByteBuffer.wrap(bytes));

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(bytes))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

From source file:com.twinsoft.convertigo.engine.util.ZipUtils.java

public static void expandZip(String zipFileName, String rootDir, String prefixDir)
        throws FileNotFoundException, IOException {
    Engine.logEngine.debug("Expanding the zip file " + zipFileName);

    // Creating the root directory
    File ftmp = new File(rootDir);
    if (!ftmp.exists()) {
        ftmp.mkdirs();/*from   w  w  w .jav  a 2  s. c o m*/
        Engine.logEngine.debug("Root directory created");
    }

    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFileName)));

    try {
        ZipEntry entry;
        int prefixSize = prefixDir != null ? prefixDir.length() : 0;

        while ((entry = zis.getNextEntry()) != null) {
            // Ignoring directories
            if (entry.isDirectory()) {

            } else {

                String entryName = entry.getName();
                Engine.logEngine.debug("+ Analyzing the entry: " + entryName);

                try {
                    // Ignore entry if does not belong to the project directory
                    if ((prefixDir == null) || entryName.startsWith(prefixDir)) {

                        // Ignore entry from _data or _private directory
                        if ((entryName.indexOf("/_data/") != prefixSize)
                                && (entryName.indexOf("/_private/") != prefixSize)) {
                            Engine.logEngine.debug("  The entry is accepted");
                            String s1 = rootDir + "/" + entryName;
                            String dir = s1.substring(0, s1.lastIndexOf('/'));

                            // Creating the directory if needed
                            ftmp = new File(dir);
                            if (!ftmp.exists()) {
                                ftmp.mkdirs();
                                Engine.logEngine.debug("  Directory created");
                            }

                            // Writing the files to the disk
                            File file = new File(rootDir + "/" + entryName);
                            FileOutputStream fos = new FileOutputStream(file);
                            try {
                                IOUtils.copy(zis, fos);
                            } finally {
                                fos.close();
                            }
                            file.setLastModified(entry.getTime());
                            Engine.logEngine.debug("  File written to: " + rootDir + "/" + entryName);
                        }
                    }
                } catch (IOException e) {
                    Engine.logEngine.error(
                            "Unable to expand the ZIP entry \"" + entryName + "\": " + e.getMessage(), e);
                }
            }
        }
    } finally {
        zis.close();
    }
}