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:org.zeroturnaround.zip.ZipUtil.java

/**
 * Compresses the given file into a ZIP file with single entry.
 *
 * @param file file to be compressed.//from   w w  w.  j  a v  a2 s.  co m
 * @return ZIP file created.
 */
public static byte[] packEntry(File file) {
    log.trace("Compressing '{}' into a ZIP file with single entry.", file);

    ByteArrayOutputStream result = new ByteArrayOutputStream();
    try {
        ZipOutputStream out = new ZipOutputStream(result);
        ZipEntry entry = new ZipEntry(file.getName());
        entry.setTime(file.lastModified());
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        try {
            ZipEntryUtil.addEntry(entry, in, out);
        } finally {
            IOUtils.closeQuietly(in);
        }
        out.close();
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    }
    return result.toByteArray();
}

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

/**
 * Compresses the given files into a ZIP file.
 * <p>/*w  w  w.  j a v a2s  . c o m*/
 * The ZIP file must not be a directory and its parent directory must exist.
 *
 * @param filesToPack
 *          files that needs to be zipped.
 * @param destZipFile
 *          ZIP file that will be created or overwritten.
 */
public static void packEntries(File[] filesToPack, File destZipFile) {
    log.debug("Compressing '{}' into '{}'.", filesToPack, destZipFile);

    ZipOutputStream out = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(destZipFile);
        out = new ZipOutputStream(new BufferedOutputStream(fos));

        for (int i = 0; i < filesToPack.length; i++) {
            File fileToPack = filesToPack[i];

            ZipEntry zipEntry = new ZipEntry(fileToPack.getName());
            zipEntry.setSize(fileToPack.length());
            zipEntry.setTime(fileToPack.lastModified());
            out.putNextEntry(zipEntry);
            FileUtil.copy(fileToPack, out);
            out.closeEntry();
        }
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(fos);
    }
}

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

/**
 * Compresses the given directory and all its sub-directories into a ZIP file.
 *
 * @param dir/*from w  w w . j a  v  a 2s . c  o m*/
 *          root directory.
 * @param out
 *          ZIP output stream.
 * @param mapper
 *          call-back for renaming the entries.
 * @param pathPrefix
 *          prefix to be used for the entries.
 * @param mustHaveChildren
 *          if true, but directory to pack doesn't have any files, throw an exception.
 */
private static void pack(File dir, ZipOutputStream out, NameMapper mapper, String pathPrefix,
        boolean mustHaveChildren) throws IOException {
    String[] filenames = dir.list();
    if (filenames == null) {
        if (!dir.exists()) {
            throw new ZipException("Given file '" + dir + "' doesn't exist!");
        }
        throw new IOException("Given file is not a directory '" + dir + "'");
    }

    if (mustHaveChildren && filenames.length == 0) {
        throw new ZipException("Given directory '" + dir + "' doesn't contain any files!");
    }

    for (int i = 0; i < filenames.length; i++) {
        String filename = filenames[i];
        File file = new File(dir, filename);
        boolean isDir = file.isDirectory();
        String path = pathPrefix + file.getName(); // NOSONAR
        if (isDir) {
            path += PATH_SEPARATOR; // NOSONAR
        }

        // Create a ZIP entry
        String name = mapper.map(path);
        if (name != null) {
            ZipEntry zipEntry = new ZipEntry(name);
            if (!isDir) {
                zipEntry.setSize(file.length());
                zipEntry.setTime(file.lastModified());
            }

            out.putNextEntry(zipEntry);

            // Copy the file content
            if (!isDir) {
                FileUtil.copy(file, out);
            }

            out.closeEntry();
        }

        // Traverse the directory
        if (isDir) {
            pack(file, out, mapper, path, false);
        }
    }
}

From source file:org.exoplatform.services.jcr.ext.artifact.ArtifactManagingServiceImpl.java

private void mapRepositoryToZipStream(Node parentNode, ZipOutputStream zout)
        throws RepositoryException, IOException {

    NodeIterator folderIterator = parentNode.getNodes();
    while (folderIterator.hasNext()) {
        Node folder = folderIterator.nextNode();
        if (folder.isNodeType("exo:artifact")) {
            String entryName = parentNode.getPath() + File.separator + folder.getName();
            ZipEntry entry = new ZipEntry(entryName + "/");

            zout.putNextEntry(entry);/*  ww  w  .j a v a2s. c om*/

            mapRepositoryToZipStream(folder, zout);

        } else if (folder.isNodeType("exo:file")) {

            String entryName = parentNode.getPath() + File.separator + folder.getName();
            ZipEntry entry = new ZipEntry(entryName);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Zipping " + entryName);
            }

            Node dataNode = folder.getNode("jcr:content");
            Property data = dataNode.getProperty("jcr:data");
            InputStream in = data.getStream();

            Property lastModified = dataNode.getProperty("jcr:lastModified");

            entry.setTime(lastModified.getLong());
            entry.setSize(in.available());
            zout.putNextEntry(entry);

            int count;
            byte[] buf = new byte[BUFFER];
            while ((count = in.read(buf, 0, BUFFER)) != -1) {
                zout.write(buf, 0, count);
            }
            zout.flush();
            in.close();
        }
    }
}

From source file:org.eclipse.che.vfs.impl.fs.FSMountPoint.java

ContentStream zip(VirtualFileImpl virtualFile, VirtualFileFilter filter)
        throws ForbiddenException, ServerException {
    if (!virtualFile.isFolder()) {
        throw new ForbiddenException(
                String.format("Unable export to zip. Item '%s' is not a folder. ", virtualFile.getPath()));
    }//from  w  ww.j  av  a2s .c  o  m
    java.io.File zipFile = null;
    FileOutputStream out = null;
    try {
        zipFile = java.io.File.createTempFile("export", ".zip");
        out = new FileOutputStream(zipFile);
        final ZipOutputStream zipOut = new ZipOutputStream(out);
        final LinkedList<VirtualFile> q = new LinkedList<>();
        q.add(virtualFile);
        final int zipEntryNameTrim = virtualFile.getVirtualFilePath().length();
        final byte[] buff = new byte[COPY_BUFFER_SIZE];
        while (!q.isEmpty()) {
            for (VirtualFile current : doGetChildren((VirtualFileImpl) q.pop(), SERVICE_GIT_DIR_FILTER)) {
                // (1) Check filter.
                // (2) Check permission directly for current file only.
                // We already know parent accessible for current user otherwise we should not be here.
                // Ignore item if don't have permission to read it.
                if (filter.accept(current)
                        && hasPermission((VirtualFileImpl) current, BasicPermissions.READ.value(), false)) {
                    final String zipEntryName = current.getVirtualFilePath().subPath(zipEntryNameTrim)
                            .toString().substring(1);
                    if (current.isFile()) {
                        final ZipEntry zipEntry = new ZipEntry(zipEntryName);
                        zipOut.putNextEntry(zipEntry);
                        InputStream in = null;
                        final PathLockFactory.PathLock lock = pathLockFactory
                                .getLock(current.getVirtualFilePath(), false).acquire(LOCK_FILE_TIMEOUT);
                        try {
                            zipEntry.setTime(virtualFile.getLastModificationDate());
                            in = new FileInputStream(((VirtualFileImpl) current).getIoFile());
                            int r;
                            while ((r = in.read(buff)) != -1) {
                                zipOut.write(buff, 0, r);
                            }
                        } finally {
                            closeQuietly(in);
                            lock.release();
                        }
                        zipOut.closeEntry();
                    } else if (current.isFolder()) {
                        final ZipEntry zipEntry = new ZipEntry(zipEntryName + '/');
                        zipEntry.setTime(0);
                        zipOut.putNextEntry(zipEntry);
                        q.add(current);
                        zipOut.closeEntry();
                    }
                }
            }
        }
        closeQuietly(zipOut);
        final String name = virtualFile.getName() + ".zip";
        return new ContentStream(name, new DeleteOnCloseFileInputStream(zipFile), ExtMediaType.APPLICATION_ZIP,
                zipFile.length(), new Date());
    } catch (IOException | RuntimeException ioe) {
        if (zipFile != null) {
            zipFile.delete();
        }
        throw new ServerException(ioe.getMessage(), ioe);
    } finally {
        closeQuietly(out);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeJsonPrefCity() {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    int cnt = 0;//from  ww  w. j  a  va 2 s  . c  o m

    try {

        ParentChild data = getParentChildDao().get("prefs");
        String json = toJsonPrefs(data);
        ZipEntry entry = new ZipEntry("prefs.json");
        entry.setTime(timestamp);
        zos.putNextEntry(entry);
        zos.write(json.getBytes("UTF-8"));
        zos.closeEntry();
        ++cnt;

        for (Pref pref : getPrefs()) {

            data = getParentChildDao().get(pref.getCode());

            if (data == null) {
                continue;
            }

            json = toJsonCities(data);
            entry = new ZipEntry(pref.getCode() + ".json");
            entry.setTime(timestamp);
            zos.putNextEntry(entry);
            zos.write(json.getBytes("UTF-8"));
            zos.closeEntry();
            ++cnt;
        }

        zos.finish();
        getRawDao().store(baos.toByteArray(), "json_prefcity.zip");
        log.info("count:" + cnt);

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeJsonCorp() {

    LinkedList<City> cities = getCities();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    int cnt = 0;//from w  w w .  j a  va 2  s  . c o m

    try {

        for (City city : cities) {

            String key = city.getCode() + "c";
            ParentChild data = getParentChildDao().get(key);

            if (data == null) {
                continue;
            }

            String json = toJsonCorps(data);
            ZipEntry entry = new ZipEntry(key + ".json");
            entry.setTime(timestamp);
            zos.putNextEntry(entry);
            zos.write(json.getBytes("UTF-8"));
            zos.closeEntry();
            ++cnt;
        }

        zos.finish();
        getRawDao().store(baos.toByteArray(), "json_corp.zip");
        log.info("count:" + cnt);

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }

    return;
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public void storeJsonArea() {

    LinkedList<City> cities = getCities();
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    int cnt = 0;//from w w w.  j  a  va2  s .  c om

    try {

        for (City city : cities) {

            ParentChild data = getParentChildDao().get(city.getCode());

            if (data == null) {
                continue;
            }

            SortedSet<String> children = new TreeSet<String>();
            String json = toJsonAdd1s(data, children);
            ZipEntry entry = new ZipEntry(city.getCode() + ".json");
            entry.setTime(timestamp);
            zos.putNextEntry(entry);
            zos.write(json.getBytes("UTF-8"));
            zos.closeEntry();
            ++cnt;

            for (String add1 : children) {

                json = toJsonAdd2s(data, add1);
                entry = new ZipEntry(city.getCode() + "-" + toHex(add1) + ".json");
                entry.setTime(timestamp);
                zos.putNextEntry(entry);
                zos.write(json.getBytes("UTF-8"));
                zos.closeEntry();
                ++cnt;
            }
        }

        zos.finish();
        getRawDao().store(baos.toByteArray(), "json_area.zip");
        log.info("count:" + cnt);

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }

    return;
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

public String storeJsonZips(String digits) {

    if ((digits == null) || (digits.length() == 0)) {
        digits = "0";
    }/*from  ww w  .  j  av  a  2s  . com*/
    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    int cnt = 0;

    try {

        for (int i = 0; i < 100; ++i) {

            String zip1 = digits + String.format("%02d", i);
            ParentChild data = getParentChildDao().get(zip1);

            if (data == null) {
                continue;
            }

            Map<String, ParentChild> pcs = new HashMap<String, ParentChild>();
            SortedSet<String> zip2s = new TreeSet<String>();

            for (String json : data.getChildren()) {

                JSONObject jo = new JSONObject(json);
                String key = jo.optString("key", "");
                String zip2 = jo.optString("zip2", "");

                if (key.length() == 0) {
                    continue;
                }
                if (zip2.length() == 0) {
                    continue;
                }

                if (!pcs.containsKey(jo.optString("key", ""))) {
                    pcs.put(key, getParentChildDao().get(key));
                }

                zip2s.add(zip2);
            }

            for (String zip2 : zip2s) {

                String zip = zip1 + zip2;
                String json = toJsonZips(data, zip, pcs);
                ZipEntry entry = new ZipEntry(zip + ".json");
                entry.setTime(timestamp);
                zos.putNextEntry(entry);
                zos.write(json.getBytes("UTF-8"));
                zos.closeEntry();
                ++cnt;
            }
        }

        if (cnt == 0) {

            ZipEntry entry = new ZipEntry("empty.txt");
            entry.setTime(timestamp);
            zos.putNextEntry(entry);
            zos.write("empty".getBytes("UTF-8"));
            zos.closeEntry();
        }

        zos.finish();
        getRawDao().store(baos.toByteArray(), "json_zip" + digits + ".zip");
        log.info(digits + ":" + cnt);

    } catch (JSONException e) {
        log.log(Level.WARNING, "", e);
    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }

    return digits.equals("9") ? null : "" + (Integer.parseInt(digits) + 1);
}

From source file:jp.zippyzip.impl.GeneratorServiceImpl.java

/**
 * JSON ??/*from  w  w  w . ja v a 2s .c  om*/
 * 
 * @param name "area" / "corp"
 * @param suffix "" / "c"
 */
void storeJson(String name, String suffix) {

    long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime();
    Collection<City> cities = getCities();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_utf8.json");
    entry.setTime(timestamp);
    int cnt = 0;

    try {

        zos.putNextEntry(entry);
        zos.write("[".getBytes("UTF-8"));

        for (City city : cities) {

            ParentChild pc = getParentChildDao().get(city.getCode() + suffix);

            if (pc == null) {
                continue;
            }

            for (String json : pc.getChildren()) {

                if (0 < cnt) {
                    zos.write(",".getBytes("UTF-8"));
                }
                zos.write(json.getBytes("UTF-8"));
                ++cnt;
            }
        }

        zos.write("]".getBytes("UTF-8"));
        zos.closeEntry();
        zos.finish();
        getRawDao().store(baos.toByteArray(), name + "_utf8_json.zip");
        log.info("count: " + cnt);

    } catch (IOException e) {
        log.log(Level.WARNING, "", e);
    }
}