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.hyperic.hq.product.ClientPluginDeployer.java

public boolean upToDate(ZipEntry source, File target) {
    boolean upToDate = upToDate(source.getTime(), target.lastModified());

    if (upToDate) {
        log.debug("Unchanged file: " + target);
    }/* w w w. j av a2s.  com*/

    return upToDate;
}

From source file:com.denizensoft.appcompatlib.AppActivity.java

@Override
public Date packageBuildTimestamp() {
    try {/*  ww  w  . j  av  a2s . co m*/
        ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0);

        ZipFile zf = new ZipFile(ai.sourceDir);

        ZipEntry ze = zf.getEntry("classes.dex");

        return new Date(ze.getTime());
    } catch (PackageManager.NameNotFoundException e) {
        appFatalErrorHook("App", e.getMessage());
    } catch (IOException e) {
        appFatalErrorHook("App", e.getMessage());
    }
    return null;
}

From source file:org.pentaho.reporting.libraries.repository.zip.ZipContentLocation.java

private void updateMetaData(final ZipEntry zipEntry) {
    this.comment = zipEntry.getComment();
    this.size = zipEntry.getSize();
    this.time = zipEntry.getTime();
}

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

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException, MojoFailureException {
    for (Artifact dependencyFile : (Iterable<Artifact>) project.getDependencyArtifacts()) {
        if ("org.jahia.server".equals(dependencyFile.getGroupId())
                && "jahia-war".equals(dependencyFile.getArtifactId())) {
            try {
                File webappDir = new File(output, "config/WEB-INF/jahia");
                ZipInputStream z = new ZipInputStream(new FileInputStream(dependencyFile.getFile()));
                ZipEntry entry;
                int cnt = 0;
                while ((entry = z.getNextEntry()) != null) {
                    if (!entry.isDirectory()) {
                        File target = new File(webappDir, entry.getName());

                        if (entry.getTime() > target.lastModified()) {

                            target.getParentFile().mkdirs();
                            FileOutputStream fileOutputStream = new FileOutputStream(target);
                            IOUtils.copy(z, fileOutputStream);
                            fileOutputStream.close();
                            cnt++;//ww  w  . ja v  a2  s  . c  om
                        }
                    }
                }
                z.close();
                getLog().info("Copied " + cnt + " files.");
            } catch (IOException e) {
                getLog().error("Error when copying file");
            }
        }
    }
}

From source file:org.orbeon.oxf.processor.zip.UnzipProcessor.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(UnzipProcessor.this, name) {

        public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) {
            try {
                // Read input in a temporary file
                final File temporaryZipFile;
                {//  w  w w .  jav  a  2 s .  co m
                    final FileItem fileItem = NetUtils.prepareFileItem(NetUtils.REQUEST_SCOPE, logger);
                    final OutputStream fileOutputStream = fileItem.getOutputStream();
                    readInputAsSAX(context, getInputByName(INPUT_DATA),
                            new BinaryTextXMLReceiver(fileOutputStream));
                    temporaryZipFile = ((DiskFileItem) fileItem).getStoreLocation();
                }

                xmlReceiver.startDocument();
                // <files>
                xmlReceiver.startElement("", "files", "files", SAXUtils.EMPTY_ATTRIBUTES);
                ZipFile zipFile = new ZipFile(temporaryZipFile);
                for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
                    // Go through each entry in the zip file
                    ZipEntry zipEntry = (ZipEntry) entries.nextElement();
                    // Get file name
                    String fileName = zipEntry.getName();
                    long fileSize = zipEntry.getSize();
                    String fileTime = DateUtils.DateTime().print(zipEntry.getTime());

                    InputStream entryInputStream = zipFile.getInputStream(zipEntry);
                    String uri = NetUtils.inputStreamToAnyURI(entryInputStream, NetUtils.REQUEST_SCOPE, logger);
                    // <file name="filename.ext">uri</file>
                    AttributesImpl fileAttributes = new AttributesImpl();
                    fileAttributes.addAttribute("", "name", "name", "CDATA", fileName);
                    fileAttributes.addAttribute("", "size", "size", "CDATA", Long.toString(fileSize));
                    fileAttributes.addAttribute("", "dateTime", "dateTime", "CDATA", fileTime);
                    xmlReceiver.startElement("", "file", "file", fileAttributes);
                    xmlReceiver.characters(uri.toCharArray(), 0, uri.length());
                    // </file>
                    xmlReceiver.endElement("", "file", "file");
                }
                // </files>
                xmlReceiver.endElement("", "files", "files");
                xmlReceiver.endDocument();

            } catch (IOException e) {
                throw new OXFException(e);
            } catch (SAXException e) {
                throw new OXFException(e);
            }
        }

        // We don't do any caching here since the file we produce are temporary. So we don't want a processor
        // downstream to keep a reference to a document that contains temporary URI that have since been deleted.

    };
    addOutput(name, output);
    return output;
}

From source file:org.rapidcontext.core.storage.ZipStorage.java

/**
 * Searches for an object at the specified location and returns
 * metadata about the object if found. The path may locate either
 * an index or a specific object.//from   w  w w.j  av  a  2 s .c  o m
 *
 * @param path           the storage location
 *
 * @return the metadata for the object, or
 *         null if not found
 */
public Metadata lookup(Path path) {
    if (PATH_STORAGEINFO.equals(path)) {
        return new Metadata(Dict.class, path, path(), mountTime());
    }
    Object obj = entries.get(path);
    if (obj instanceof Index) {
        Index idx = (Index) obj;
        return new Metadata(Index.class, path, path(), idx.lastModified());
    } else if (obj instanceof ZipEntry) {
        ZipEntry entry = (ZipEntry) obj;
        if (entry.getName().endsWith(DirStorage.SUFFIX_PROPS)) {
            return new Metadata(Dict.class, path, path(), entry.getTime());
        } else {
            return new Metadata(Binary.class, path, path(), entry.getTime());
        }
    } else {
        return null;
    }
}

From source file:org.springframework.integration.zip.transformer.UnZipTransformer.java

@Override
protected Object doZipTransform(final Message<?> message) throws Exception {

    try {/*ww w . j  a  v a 2s. c  o  m*/
        final Object payload = message.getPayload();
        final Object unzippedData;

        InputStream inputStream = null;

        try {
            if (payload instanceof File) {
                final File filePayload = (File) payload;

                if (filePayload.isDirectory()) {
                    throw new UnsupportedOperationException(
                            String.format("Cannot unzip a directory: '%s'", filePayload.getAbsolutePath()));
                }

                if (!SpringZipUtils.isValid(filePayload)) {
                    throw new IllegalStateException(
                            String.format("Not a zip file: '%s'.", filePayload.getAbsolutePath()));
                }

                inputStream = new FileInputStream(filePayload);
            } else if (payload instanceof InputStream) {
                inputStream = (InputStream) payload;
            } else if (payload instanceof byte[]) {
                inputStream = new ByteArrayInputStream((byte[]) payload);
            } else {
                throw new IllegalArgumentException(String.format("Unsupported payload type '%s'. "
                        + "The only supported payload types are java.io.File, byte[] and java.io.InputStream",
                        payload.getClass().getSimpleName()));
            }

            final SortedMap<String, Object> uncompressedData = new TreeMap<String, Object>();

            ZipUtil.iterate(inputStream, new ZipEntryCallback() {

                @Override
                public void process(InputStream zipEntryInputStream, ZipEntry zipEntry) throws IOException {

                    final String zipEntryName = zipEntry.getName();
                    final long zipEntryTime = zipEntry.getTime();
                    final long zipEntryCompressedSize = zipEntry.getCompressedSize();
                    final String type = zipEntry.isDirectory() ? "directory" : "file";

                    if (logger.isInfoEnabled()) {
                        logger.info(String.format(
                                "Unpacking Zip Entry - Name: '%s',Time: '%s', "
                                        + "Compressed Size: '%s', Type: '%s'",
                                zipEntryName, zipEntryTime, zipEntryCompressedSize, type));
                    }

                    if (ZipResultType.FILE.equals(zipResultType)) {
                        final File destinationFile = checkPath(message, zipEntryName);

                        if (zipEntry.isDirectory()) {
                            destinationFile.mkdirs(); //NOSONAR false positive
                        } else {
                            SpringZipUtils.copy(zipEntryInputStream, destinationFile);
                            uncompressedData.put(zipEntryName, destinationFile);
                        }
                    } else if (ZipResultType.BYTE_ARRAY.equals(zipResultType)) {
                        if (!zipEntry.isDirectory()) {
                            checkPath(message, zipEntryName);
                            byte[] data = IOUtils.toByteArray(zipEntryInputStream);
                            uncompressedData.put(zipEntryName, data);
                        }
                    } else {
                        throw new IllegalStateException("Unsupported zipResultType " + zipResultType);
                    }
                }

                public File checkPath(final Message<?> message, final String zipEntryName) throws IOException {
                    final File tempDir = new File(workDirectory, message.getHeaders().getId().toString());
                    tempDir.mkdirs(); //NOSONAR false positive
                    final File destinationFile = new File(tempDir, zipEntryName);

                    /* If we see the relative traversal string of ".." we need to make sure
                     * that the outputdir + name doesn't leave the outputdir.
                     */
                    if (!destinationFile.getCanonicalPath().startsWith(workDirectory.getCanonicalPath())) {
                        throw new ZipException("The file " + zipEntryName
                                + " is trying to leave the target output directory of " + workDirectory);
                    }
                    return destinationFile;
                }
            });

            if (uncompressedData.isEmpty()) {
                if (logger.isWarnEnabled()) {
                    logger.warn(
                            "No data unzipped from payload with message Id " + message.getHeaders().getId());
                }
                unzippedData = null;
            } else {

                if (this.expectSingleResult) {
                    if (uncompressedData.size() == 1) {
                        unzippedData = uncompressedData.values().iterator().next();
                    } else {
                        throw new MessagingException(message,
                                String.format(
                                        "The UnZip operation extracted %s "
                                                + "result objects but expectSingleResult was 'true'.",
                                        uncompressedData.size()));
                    }
                } else {
                    unzippedData = uncompressedData;
                }

            }
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (payload instanceof File && this.deleteFiles) {
                final File filePayload = (File) payload;
                if (!filePayload.delete() && logger.isWarnEnabled()) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("failed to delete File '" + filePayload + "'");
                    }
                }
            }
        }
        return unzippedData;
    } catch (Exception e) {
        throw new MessageHandlingException(message, "Failed to apply Zip transformation.", e);
    }
}

From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java

/**
 * Generate a description for a single zip-entry.
 *
 * @param ze  the zip entry to describe.
 * @param buf the buffer to place the description into
 *///from  w ww.  ja  va  2s .  c  om
private static void entry2xml(ZipEntry ze, StringBuilder buf) {
    buf.append("<ZipEntry name=\"").append(attrEscape(ze.getName())).append("\"");

    if (ze.isDirectory())
        buf.append(" isDirectory=\"true\"");
    if (ze.getCrc() >= 0)
        buf.append(" crc=\"").append(ze.getCrc()).append("\"");
    if (ze.getSize() >= 0)
        buf.append(" size=\"").append(ze.getSize()).append("\"");
    if (ze.getCompressedSize() >= 0)
        buf.append(" compressedSize=\"").append(ze.getCompressedSize()).append("\"");
    if (ze.getTime() >= 0)
        buf.append(" time=\"").append(ze.getTime()).append("\"");

    if (ze.getComment() != null || ze.getExtra() != null) {
        buf.append(">\n");

        if (ze.getComment() != null)
            buf.append("<Comment>").append(xmlEscape(ze.getComment())).append("</Comment>\n");
        if (ze.getExtra() != null)
            buf.append("<Extra>").append(base64Encode(ze.getExtra())).append("</Extra>\n");

        buf.append("</ZipEntry>\n");
    } else {
        buf.append("/>\n");
    }
}

From source file:cpcc.vvrte.services.db.DownloadServiceTest.java

@Test
public void shouldGetAllVirtualVehicles() throws IOException {
    byte[] actual = sut.getAllVirtualVehicles();

    ByteArrayInputStream bis = new ByteArrayInputStream(actual);
    ZipInputStream zis = new ZipInputStream(bis, Charset.forName("UTF-8"));

    ZipEntry entry = zis.getNextEntry();
    assertThat(entry).isNotNull();//  w  w w.  jav a 2s . c o m
    assertThat(entry.getName()).isEqualTo(VV_ONE_UUID + "/");
    assertThat(entry.getTime()).isEqualTo(CURRENT_TIME);

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_ONE_UUID + "/vv.properties");
    assertThat(entry.getTime()).isEqualTo(CURRENT_TIME);
    Properties actualProps = new Properties();
    actualProps.load(zis);
    assertThat(actualProps.getProperty("api-version")).isEqualTo(Integer.toString(VV_ONE_API_VERSION));
    assertThat(actualProps.getProperty("end-time")).isEqualTo(sdf.format(VV_ONE_END_TIME));
    assertThat(actualProps.getProperty("name")).isEqualTo(VV_ONE_NAME);
    assertThat(actualProps.getProperty("start-time")).isEqualTo(VV_ONE_START_TIME);
    assertThat(actualProps.getProperty("state")).isEqualTo(VV_ONE_STATE.name());

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_ONE_UUID + "/code.js");
    assertThat(entry.getTime()).isEqualTo(CURRENT_TIME);
    assertThat(IOUtils.toString(zis)).isEqualTo(VV_ONE_CODE);

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_ONE_UUID + "/state-info.txt");
    assertThat(entry.getTime()).isEqualTo(CURRENT_TIME);
    assertThat(IOUtils.toString(zis)).isEqualTo(VV_ONE_STATE_INFO);

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_ONE_UUID + "/storage/");
    assertThat(entry.getTime()).isEqualTo(CURRENT_TIME);

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_TWO_UUID + "/");
    assertThat(entry.getTime()).isEqualTo(CURRENT_TIME);

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_TWO_UUID + "/vv.properties");
    actualProps = new Properties();
    actualProps.load(zis);
    assertThat(actualProps.getProperty("api-version")).isEqualTo(Integer.toString(VV_TWO_API_VERSION));
    assertThat(actualProps.getProperty("end-time")).isEqualTo(VV_TWO_END_TIME_STR);
    assertThat(actualProps.getProperty("name")).isEqualTo(VV_TWO_NAME);
    assertThat(actualProps.getProperty("start-time")).isEqualTo(sdf.format(VV_TWO_START_TIME));
    assertThat(actualProps.getProperty("state")).isEqualTo(VV_TWO_STATE.name());

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_TWO_UUID + "/code.js");
    assertThat(entry.getTime()).isEqualTo(CURRENT_TIME);
    assertThat(IOUtils.toString(zis)).isEqualTo(VV_TWO_CODE);

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_TWO_UUID + "/continuation.dat");
    assertThat(entry.getTime()).isEqualTo(CURRENT_TIME);
    assertThat(IOUtils.toByteArray(zis)).isEqualTo(VV_TWO_CONTINUATION);

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_TWO_UUID + "/storage/");
    assertThat(entry.getTime()).isEqualTo(CURRENT_TIME);

    entry = zis.getNextEntry();
    assertThat(entry).isNotNull();
    assertThat(entry.getName()).isEqualTo(VV_TWO_UUID + "/storage/itemOne1.json");
    assertThat(entry.getTime()).isEqualTo(ITEM_ONE_1_TIME.getTime());
    assertThat(IOUtils.toByteArray(zis)).isEqualTo(ITEM_ONE_1_CONTENT);
}

From source file:at.alladin.rmbt.android.about.RMBTAboutFragment.java

/**
 * /* ww w . j  a  v  a2s .  c om*/
 * @param context
 * @return
 */
private String getAppInfo(final Context context) {
    PackageInfo pInfo;
    try {

        String date = "";
        try {
            final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                    0);
            final ZipFile zf = new ZipFile(ai.sourceDir);
            final ZipEntry ze = zf.getEntry("classes.dex");
            zf.close();
            final long time = ze.getTime();
            date = DateFormat.getDateTimeInstance().format(new java.util.Date(time));

        } catch (final Exception e) {// not much we can do
        }

        pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        clientVersion = pInfo.versionName + " (" + pInfo.versionCode + ")\n("
                + RevisionHelper.getVerboseRevision() + ")\n(" + date + ")";
        clientName = context.getResources().getString(R.string.app_name);
    } catch (final Exception e) {
        // e1.printStackTrace();
        Log.e(DEBUG_TAG, "version of the application cannot be found", e);
    }

    return clientVersion;
}