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.aimfire.main.MainActivity.java

private void displayVersion() {
    try {//from   w w  w.  j av a2  s . c o  m
        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();

        if (BuildConfig.DEBUG)
            printDebugMsg("App creation time: " + s + "\n");

    } catch (Exception e) {
    }
}

From source file:slash.navigation.download.actions.Extractor.java

private void doExtract(File tempFile, File destination, boolean flatten) throws IOException {
    try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(tempFile))) {
        ZipEntry entry = zipInputStream.getNextEntry();
        while (entry != null) {
            if (entry.isDirectory()) {
                if (!flatten) {
                    File directory = new File(destination, entry.getName());
                    handleDirectory(directory, entry);
                }//  w  ww . j a v  a  2s.  c  o  m

            } else {
                File extracted;
                if (flatten)
                    extracted = new File(destination, lastPathFragment(entry.getName(), MAX_VALUE));
                else {
                    extracted = new File(destination, entry.getName());
                }
                File directory = extracted.getParentFile();
                handleDirectory(directory, entry);

                log.info(format("Extracting from %s to %s", tempFile, extracted));
                FileOutputStream output = new FileOutputStream(extracted);
                new Copier(listener).copy(zipInputStream, output, 0, entry.getSize());
                // do not close zip input stream
                closeQuietly(output);
                setLastModified(extracted, fromMillis(entry.getTime()));

                zipInputStream.closeEntry();
            }

            entry = zipInputStream.getNextEntry();
        }
    }
}

From source file:com.facebook.buck.zip.ZipScrubberStepIntegrationTest.java

@Test
public void modificationTimes() throws Exception {

    // Create a dummy ZIP file.
    Path zip = tmp.newFile("output.zip");
    try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(zip))) {
        ZipEntry entry = new ZipEntry("file1");
        byte[] data = "data1".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);// w w  w  .j ava 2  s .  c om
        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();
    }

    // Execute the zip scrubber step.
    ExecutionContext executionContext = TestExecutionContext.newInstance();
    ZipScrubberStep step = new ZipScrubberStep(new ProjectFilesystem(tmp.getRoot()), Paths.get("output.zip"));
    assertEquals(0, step.execute(executionContext).getExitCode());

    // 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 FileInputStream(zip.toFile()))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

From source file:VASSAL.tools.io.ZipArchive.java

private void writeToDisk() throws IOException {
    // write all files to a temporary zip archive
    final File tmpFile = File.createTempFile("tmp", ".zip", archiveFile.getParentFile());

    ZipOutputStream out = null;/*from ww  w. ja  va2s .  c  o m*/
    try {
        out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile)));
        out.setLevel(9);

        final byte[] buf = new byte[8192];

        if (zipFile != null) {
            zipFile.close();
            zipFile = null;

            // copy unmodified file into the temp archive
            ZipInputStream in = null;
            try {
                in = new ZipInputStream(new BufferedInputStream(new FileInputStream(archiveFile)));

                ZipEntry ze = null;
                while ((ze = in.getNextEntry()) != null) {
                    // skip modified or removed entries
                    final Entry e = entries.get(ze.getName());
                    if (e == null || e.file != null)
                        continue;

                    // We can't reuse entries for compressed files because there's
                    // no way to reset all fields to acceptable values.
                    if (ze.getMethod() == ZipEntry.DEFLATED) {
                        ze = new ZipEntry(ze.getName());
                        ze.setTime(ze.getTime());
                    }

                    out.putNextEntry(ze);
                    IOUtils.copy(in, out, buf);

                    entries.remove(ze.getName());
                }

                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }

        for (String name : entries.keySet()) {
            final Entry e = entries.get(name);

            // write new or modified file into the temp archive
            FileInputStream in = null;
            try {
                in = new FileInputStream(e.file);
                out.putNextEntry(e.ze);
                IOUtils.copy(in, out, buf);
                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }

        out.close();
    } finally {
        IOUtils.closeQuietly(out);
    }

    // Replace old archive with temp archive.
    if (!tmpFile.renameTo(archiveFile)) {
        try {
            FileUtils.forceDelete(archiveFile);
            FileUtils.moveFile(tmpFile, archiveFile);
        } catch (IOException e) {
            String err = "Unable to overwrite " + archiveFile.getAbsolutePath() + ": ";

            if (!archiveFile.exists()) {
                err += " file does not exist.";
            } else if (!archiveFile.canWrite()) {
                err += " file is not writable.";
            } else if (!archiveFile.isFile()) {
                err += " not a normal file.";
            }

            err += " Data written to " + tmpFile.getAbsolutePath() + " instead.";
            throw (IOException) new IOException(err).initCause(e);
        }
    }

    closed = true;
    modified = false;
    entries.clear();
}

From source file:org.jahia.utils.zip.JahiaArchiveFileHandler.java

public Map<String, String> unzip(String path, boolean overwrite, PathFilter pathFilter, String pathPrefix)
        throws JahiaException {

    Map<String, String> unzippedFiles = new TreeMap<String, String>();
    Map<File, Long> timestamps = new HashMap<File, Long>();

    pathFilter = pathFilter != null ? pathFilter : PathFilter.ALL;

    try {/* w ww.j a  v a2 s. com*/

        String destPath = null;

        FileInputStream fis = new FileInputStream(m_FilePath);
        BufferedInputStream bis = new BufferedInputStream(fis);
        ZipInputStream zis = new ZipInputStream(bis);
        ZipFile zf = new ZipFile(m_FilePath);
        ZipEntry ze = null;
        String zeName = null;

        try {

            while ((ze = zis.getNextEntry()) != null) {

                zeName = ze.getName();

                String filePath = genPathFile(zeName);

                destPath = path + File.separator + filePath;

                File fo = new File(destPath);

                if (pathFilter.accept(pathPrefix != null ? pathPrefix + "/" + zeName : zeName)) {
                    String loggedPath = fo.getAbsolutePath();
                    if (basePath != null) {
                        loggedPath = StringUtils.substringAfter(loggedPath, basePath);
                    }
                    unzippedFiles.put(filePath, loggedPath);
                    long lastModified = ze.getTime();
                    if (lastModified > 0) {
                        timestamps.put(fo, lastModified);
                    }
                    if (ze.isDirectory()) {
                        fo.mkdirs();
                    } else if (overwrite || !fo.exists()) {
                        File parent = new File(fo.getParent());
                        parent.mkdirs();
                        FileOutputStream fos = new FileOutputStream(fo);
                        copyStream(zis, fos);
                    }
                }
                zis.closeEntry();
            }
        } finally {

            // Important !!!
            zf.close();
            fis.close();
            zis.close();
            bis.close();
        }

    } catch (IOException ioe) {

        logger.error(" fail unzipping " + ioe.getMessage(), ioe);

        throw new JahiaException(CLASS_NAME, "faile processing unzip", JahiaException.SERVICE_ERROR,
                JahiaException.ERROR_SEVERITY, ioe);

    }

    // preserve last modified time stamps
    for (Map.Entry<File, Long> tst : timestamps.entrySet()) {
        try {
            tst.getKey().setLastModified(tst.getValue());
        } catch (Exception e) {
            logger.warn("Unable to set last mofified date for file {}. Cause: {}", tst.getKey(),
                    e.getMessage());
        }
    }

    return unzippedFiles;

}

From source file:org.broad.igv.feature.genome.GenomeManager.java

/**
 * Rewrite the {@link Globals#GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY} property to equal
 * the specified {@code newSequencePath}. Works by creating a temp file and renaming
 *
 * @param targetFile      A .genome file, in zip format
 * @param newSequencePath//from w  w  w .  jav a  2  s .co  m
 * @return boolean indicating success or failure.
 * @throws IOException
 */
static boolean rewriteSequenceLocation(File targetFile, String newSequencePath) throws IOException {

    ZipFile targetZipFile = new ZipFile(targetFile);
    boolean success = false;

    File tmpZipFile = File.createTempFile("tmpGenome", ".zip");
    ZipEntry propEntry = targetZipFile.getEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);

    InputStream propertyInputStream = null;
    ZipOutputStream zipOutputStream = null;
    Properties inputProperties = new Properties();

    try {
        propertyInputStream = targetZipFile.getInputStream(propEntry);
        BufferedReader reader = new BufferedReader(new InputStreamReader(propertyInputStream));

        //Copy over property.txt, only replacing a few properties
        inputProperties.load(reader);
        inputProperties.put(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY, newSequencePath);
        inputProperties.put(Globals.GENOME_ARCHIVE_CUSTOM_SEQUENCE_LOCATION_KEY, Boolean.TRUE.toString());

        ByteArrayOutputStream propertyBytes = new ByteArrayOutputStream();
        PrintWriter propertyFileWriter = new PrintWriter(new OutputStreamWriter(propertyBytes));

        inputProperties.store(propertyFileWriter, null);

        propertyFileWriter.flush();
        byte[] newPropertyBytes = propertyBytes.toByteArray();

        Enumeration<? extends ZipEntry> entries = targetZipFile.entries();
        zipOutputStream = new ZipOutputStream(new FileOutputStream(tmpZipFile));
        while (entries.hasMoreElements()) {
            ZipEntry curEntry = entries.nextElement();
            ZipEntry writeEntry = null;

            if (curEntry.getName().equals(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME)) {
                writeEntry = new ZipEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);
                writeEntry.setSize(newPropertyBytes.length);
                zipOutputStream.putNextEntry(writeEntry);
                zipOutputStream.write(newPropertyBytes);
                continue;
            } else {
                //Because the compressed size can vary,
                //we generate a new ZipEntry and copy some attributes
                writeEntry = new ZipEntry(curEntry.getName());
                writeEntry.setSize(curEntry.getSize());
                writeEntry.setComment(curEntry.getComment());
                writeEntry.setTime(curEntry.getTime());
            }

            zipOutputStream.putNextEntry(writeEntry);
            InputStream tmpIS = null;
            try {
                tmpIS = targetZipFile.getInputStream(writeEntry);
                int bytes = IOUtils.copy(tmpIS, zipOutputStream);
                log.debug(bytes + " bytes written to " + targetFile);
            } finally {
                if (tmpIS != null)
                    tmpIS.close();
            }

        }
    } catch (Exception e) {
        tmpZipFile.delete();
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (propertyInputStream != null)
            propertyInputStream.close();
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.finish();
            zipOutputStream.close();
        }
        zipOutputStream = null;
        System.gc();
        success = true;
    }

    //This is a hack. I don't know why it's necessary,
    //but for some reason the output zip file seems to be corrupt
    //at least when called from GenomeManager.refreshArchive
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        //
    }

    //Rename tmp file
    if (success) {
        targetFile.delete();
        FileUtils.copyFile(tmpZipFile, targetFile);
        success = targetFile.exists();
        tmpZipFile.delete();
    }
    return success;
}

From source file:org.wso2.carbon.greg.soap.viewer.WSDLVisualizer.java

/**
 * Get the temp location of output directory where wsdl files is saved with its dependencies
 *
 * @param path Registry path the the WSDL file
 * @return Output directory path/*from w ww  .j  ava2s.  c  o m*/
 */
private String writeResourceToFile(String path) {
    String outDir = null;
    try {
        Registry registry = ServiceHolder.getRegistryService().getSystemRegistry();
        ContentDownloadBean zipContentBean = ContentUtil.getContentWithDependencies(path,
                (UserRegistry) registry);
        InputStream zipContentStream = zipContentBean.getContent().getInputStream();
        ZipInputStream stream = new ZipInputStream(zipContentStream);
        byte[] buffer = new byte[2048];
        String uniqueID = UUID.randomUUID().toString();
        outDir = CarbonUtils.getCarbonHome() + File.separator + "tmp" + File.separator + uniqueID;
        (new File(outDir)).mkdir();
        ZipEntry entry;
        while ((entry = stream.getNextEntry()) != null) {
            String s = String.format("Entry: %s len %d added %TD", outDir + File.separator + entry.getName(),
                    entry.getSize(), new Date(entry.getTime()));

            String outPath = outDir + File.separator + entry.getName();
            (new File(outPath)).getParentFile().mkdirs();
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(outPath);
                int len = 0;
                while ((len = stream.read(buffer)) > 0) {
                    output.write(buffer, 0, len);
                }
            } finally {
                // Close the output file
                if (output != null) {
                    output.close();
                }
            }
        }

    } catch (FileNotFoundException e) {
        logger.error("temporary output directory cannot be found ", e);
    } catch (IOException e) {
        logger.error("Error occurred while writing the WSDL content to the temporary file", e);
    } catch (RegistryException e) {
        logger.error("Error occurred while getting registry from service holder", e);
    } catch (Exception e) {
        logger.error("Error occurred while getting registry from service holder", e);
    }
    return outDir;
}

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

/**
 * Deploy WAR artifact to application server
 * @param dependencyNode// w  w w.  ja  v a 2s. com
 */
protected void deployWarDependency(DependencyNode dependencyNode) throws Exception {
    Artifact artifact = dependencyNode.getArtifact();
    File webappDir = getWebappDeploymentDir();

    getLog().info("Deploying artifact " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
            + artifact.getVersion() + "(file: " + artifact.getFile() + ")");
    getLog().info("Updating " + artifact.getType() + " resources for " + getDeployer().getName()
            + " in directory " + webappDir);

    String[] excludes = getDeployer().getWarExcludes() != null
            ? StringUtils.split(getDeployer().getWarExcludes(), ",")
            : null;

    // if we are dealing with WAR overlay, we want to overwrite the target
    boolean overwrite = StringUtils.isNotEmpty(artifact.getClassifier());

    try {
        ZipInputStream z = new ZipInputStream(new FileInputStream(artifact.getFile()));
        ZipEntry entry;
        int cnt = 0;
        while ((entry = z.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                if (excludes != null) {
                    boolean doExclude = false;
                    for (String excludePattern : excludes) {
                        if (SelectorUtils.matchPath(excludePattern, entry.getName())) {
                            doExclude = true;
                            break;
                        }
                    }
                    if (doExclude) {
                        continue;
                    }
                }
                File target = new File(webappDir, entry.getName());
                if (overwrite || entry.getTime() > target.lastModified()) {

                    target.getParentFile().mkdirs();
                    FileOutputStream fileOutputStream = new FileOutputStream(target);
                    IOUtils.copy(z, fileOutputStream);
                    fileOutputStream.close();
                    cnt++;
                }
            } else {
                //in the case of empty folders create anyway
                (new File(webappDir, entry.getName())).mkdir();
            }
        }
        z.close();
        getLog().info("Copied " + cnt + " files.");
    } catch (IOException e) {
        getLog().error("Error while deploying dependency", e);
    }
}

From source file:dev.dworks.apps.anexplorer.provider.ExternalStorageProvider.java

private void includeZIPFile(MatrixCursor result, String docId, ZipEntry zipEntry) throws FileNotFoundException {

    int flags = 0;

    final String displayName = zipEntry.getName();
    final String mimeType = ""; //getTypeForFile(zipEntry);

    final RowBuilder row = result.newRow();
    row.add(Document.COLUMN_DOCUMENT_ID, docId);
    row.add(Document.COLUMN_DISPLAY_NAME, displayName);
    row.add(Document.COLUMN_SIZE, zipEntry.getSize());
    row.add(Document.COLUMN_MIME_TYPE, mimeType);
    row.add(Document.COLUMN_PATH, "");//zipEntry.getAbsolutePath());
    row.add(Document.COLUMN_FLAGS, flags);
    if (zipEntry.isDirectory()) {
        row.add(Document.COLUMN_SUMMARY, "? files");
    }/* w  ww  . jav  a  2  s .  com*/

    // Only publish dates reasonably after epoch
    long lastModified = zipEntry.getTime();
    if (lastModified > 31536000000L) {
        row.add(Document.COLUMN_LAST_MODIFIED, lastModified);
    }
}

From source file:org.wso2.carbon.governance.soap.viewer.WSDLVisualizer.java

/**
 * Get the temp location of output directory where wsdl files is saved with its dependencies
 *
 * @param path Registry path the the WSDL file
 * @return Output directory path//w w w  . jav a 2s  .co m
 */
private String writeResourceToFile(String path, int tenantId) {
    String outDir = null;
    try {
        UserRegistry registry = ServiceHolder.getRegistryService().getSystemRegistry(tenantId);
        ContentDownloadBean zipContentBean = ContentUtil.getContentWithDependencies(path, registry);
        InputStream zipContentStream = zipContentBean.getContent().getInputStream();
        ZipInputStream stream = new ZipInputStream(zipContentStream);
        byte[] buffer = new byte[2048];
        String uniqueID = UUID.randomUUID().toString();
        outDir = CarbonUtils.getCarbonHome() + File.separator + "tmp" + File.separator + uniqueID;
        (new File(outDir)).mkdir();
        ZipEntry entry;
        while ((entry = stream.getNextEntry()) != null) {
            String s = String.format("Entry: %s len %d added %TD", outDir + File.separator + entry.getName(),
                    entry.getSize(), new Date(entry.getTime()));

            String outPath = outDir + File.separator + entry.getName();
            (new File(outPath)).getParentFile().mkdirs();
            FileOutputStream output = null;
            try {
                output = new FileOutputStream(outPath);
                int len = 0;
                while ((len = stream.read(buffer)) > 0) {
                    output.write(buffer, 0, len);
                }
            } finally {
                // Close the output file
                if (output != null) {
                    output.close();
                }
            }
        }

    } catch (FileNotFoundException e) {
        logger.error("temporary output directory cannot be found ", e);
    } catch (IOException e) {
        logger.error("Error occurred while writing the WSDL content to the temporary file", e);
    } catch (RegistryException e) {
        logger.error("Error occurred while getting registry from service holder", e);
    } catch (Exception e) {
        logger.error("Error occurred while getting registry from service holder", e);
    }
    return outDir;
}