Example usage for java.util.zip ZipEntry ZipEntry

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

Introduction

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

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:info.servertools.core.util.FileUtils.java

public static void zipDirectory(File directory, File zipfile, @Nullable Collection<String> fileBlacklist,
        @Nullable Collection<String> folderBlacklist) throws IOException {
    URI baseDir = directory.toURI();
    Deque<File> queue = new LinkedList<>();
    queue.push(directory);//from   ww w.  ja  v  a2  s .  c o  m
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = out;
    try {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty()) {
            directory = queue.removeFirst();
            File[] dirFiles = directory.listFiles();
            if (dirFiles != null && dirFiles.length != 0) {
                for (File child : dirFiles) {
                    if (child != null) {
                        String name = baseDir.relativize(child.toURI()).getPath();
                        if (child.isDirectory()
                                && (folderBlacklist == null || !folderBlacklist.contains(child.getName()))) {
                            queue.push(child);
                            name = name.endsWith("/") ? name : name + "/";
                            zout.putNextEntry(new ZipEntry(name));
                        } else {
                            if (fileBlacklist != null && !fileBlacklist.contains(child.getName())) {
                                zout.putNextEntry(new ZipEntry(name));
                                copy(child, zout);
                                zout.closeEntry();
                            }
                        }
                    }
                }
            }
        }
    } finally {
        res.close();
    }
}

From source file:ch.admin.suis.msghandler.util.ZipUtils.java

/**
 * Creates a new unique ZIP file in the destination directory and adds to it
 * the provided collection of files./*from   www  .  ja  va  2s  .com*/
 *
 * @param toDir The name of the file created
 * @param files The files to compress
 * @return A Zipped File
 * @throws IOException if the file cannot be created because of a IO error
 */
public static File compress(File toDir, Collection<File> files) throws IOException {
    final File zipFile = File.createTempFile("data", ".zip", toDir);

    // was there an exception?
    boolean exceptionThrown = false;

    try (ZipOutputStream zout = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(zipFile), BUFFER_SIZE))) {

        byte[] data = new byte[BUFFER_SIZE];

        for (File file : files) {
            // create the entry
            zout.putNextEntry(new ZipEntry(file.getName()));

            FileInputStream in = new FileInputStream(file);

            try (FileLock lock = in.getChannel().tryLock(0, Long.MAX_VALUE, true)) {
                isInValid(lock, in);
                int len;

                // write the file to the entry
                while ((len = in.read(data)) > 0) {
                    zout.write(data, 0, len);
                }
                lock.release();
            } finally {
                try {
                    in.close();
                } catch (IOException e) {
                    LOG.error("cannot properly close the opened file " + file.getAbsolutePath(), e);
                }
            }

        }
    } catch (IOException e) {
        LOG.error("error while creating the ZIP file " + zipFile.getAbsolutePath(), e);
        // mark for the finally block
        exceptionThrown = true;
        // rethrow - the finally block is only for the first exception
        throw e;
    } finally {
        // remove the file in case of an exception
        if (exceptionThrown && !zipFile.delete()) {
            LOG.error("cannot delete the file " + zipFile.getAbsolutePath());
        }
    }

    return zipFile;
}

From source file:com.joliciel.talismane.machineLearning.linearsvm.LinearSVMOneVsRestModel.java

@Override
public void writeModelToStream(OutputStream outputStream) {
    try {/*  www.ja va2s . co  m*/
        ZipOutputStream zos = new ZipOutputStream(outputStream);
        zos.setLevel(ZipOutputStream.STORED);
        int i = 0;
        for (Model model : models) {
            LOG.debug("Writing model " + i + " for outcome " + outcomes.get(i));
            ZipEntry zipEntry = new ZipEntry("model" + i);
            i++;
            zos.putNextEntry(zipEntry);
            Writer writer = new OutputStreamWriter(zos, "UTF-8");
            Writer unclosableWriter = new UnclosableWriter(writer);
            model.save(unclosableWriter);
            zos.closeEntry();
            zos.flush();
        }
    } catch (UnsupportedEncodingException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:ee.ria.xroad.common.messagelog.archive.LogArchiveCache.java

private void addAsicContainersToArchive(ZipOutputStream zipOut) throws IOException {
    for (String eachName : archiveFileNames) {
        ZipEntry entry = new ZipEntry(eachName);

        zipOut.putNextEntry(entry);//from  w  ww  .  j  a v a 2s  .  c o  m

        try (InputStream archiveInput = Files.newInputStream(createTempAsicPath(eachName))) {
            IOUtils.copy(archiveInput, zipOut);
        }

        zipOut.closeEntry();
    }
}

From source file:com.marklogic.contentpump.OutputArchive.java

public void write(String uri, InputStream is, long size) throws IOException {
    ZipEntry entry = new ZipEntry(uri);
    if (outputStream == null || (currentFileBytes + size > Integer.MAX_VALUE) && currentFileBytes > 0) {
        newOutputStream();// w w  w  . j  a  va 2s.c o m
    }
    try {
        outputStream.putNextEntry(entry);
        long bufSize = Math.min(size, 512 << 10);
        byte[] buf = new byte[(int) bufSize];
        for (long toRead = size, read = 0; toRead > 0; toRead -= read) {
            read = is.read(buf, 0, (int) bufSize);
            if (read > 0) {
                outputStream.write(buf, 0, (int) read);
            } else {
                LOG.warn("Premature EOF: uri=" + uri + ",toRead=" + toRead);
                break;
            }
        }
        outputStream.closeEntry();
    } catch (ZipException e) {
        LOG.warn("Exception caught: " + e.getMessage() + entry.getName());
    }
    currentFileBytes += size;
    currentEntries++;
}

From source file:com.stehno.oxy.ZipBuilder.java

/**
 * Used to add an entry with the given parameters.
 *
 * @param name the entry name// w  w  w .ja  v a 2  s .  c o  m
 * @param comment the entry comment
 * @param bytes the entry data
 * @return a reference to the builder
 * @throws IOException if there is a problem writing the entry data
 */
public ZipBuilder addEntry(final String name, final String comment, final byte[] bytes) throws IOException {
    final ZipEntry entry = new ZipEntry(name);
    if (isNotBlank(comment)) {
        entry.setComment(comment);
    }
    return (addEntry(entry, bytes));
}

From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java

/**
 * Exports all projects into separate xml files and adds them to a zip archive.  
 * @return null Always returns null, so user stays on same screen after action performed
 *//*from   www .ja v a  2 s  . c  o  m*/
public String exportAllProjectsToZip() {
    List<PlanProperties> ppList = em.createQuery("select p from PlanProperties p").getResultList();

    if (!ppList.isEmpty()) {
        log.debug("number of plans to export: " + ppList.size());
        String filename = "allprojects.zip";

        String exportPath = OS.getTmpPath() + "export" + System.currentTimeMillis() + "/";
        new File(exportPath).mkdirs();

        String binarydataTempPath = exportPath + "binarydata/";
        File binarydataTempDir = new File(binarydataTempPath);
        binarydataTempDir.mkdirs();

        try {
            OutputStream out = new BufferedOutputStream(new FileOutputStream(exportPath + filename));
            ZipOutputStream zipOut = new ZipOutputStream(out);

            for (PlanProperties pp : ppList) {
                log.debug("EXPORTING: " + pp.getName());
                ZipEntry zipAdd = new ZipEntry(String.format("%1$03d", pp.getId()) + "-"
                        + FileUtils.makeFilename(pp.getName()) + ".xml");
                zipOut.putNextEntry(zipAdd);
                // export the complete project, including binary data
                exportComplete(pp.getId(), zipOut, binarydataTempPath);
                zipOut.closeEntry();
            }
            zipOut.close();
            out.close();
            new File(exportPath + "finished.info").createNewFile();

            FacesMessages.instance().add(FacesMessage.SEVERITY_INFO, "Export was written to: " + exportPath);
            log.info("Export was written to: " + exportPath);
        } catch (IOException e) {
            FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR,
                    "An error occured while generating the export file.");
            log.error("An error occured while generating the export file.", e);
            File errorInfo = new File(exportPath + "error.info");
            try {
                Writer w = new FileWriter(errorInfo);
                w.write("An error occured while generating the export file:");
                w.write(e.getMessage());
                w.close();
            } catch (IOException e1) {
                log.error("Could not write error file.");
            }

        } finally {
            // remove all binary temp files
            OS.deleteDirectory(binarydataTempDir);
        }

    } else {
        FacesMessages.instance().add("No Projects found!");
    }
    return null;
}

From source file:com.googlecode.dex2jar.v3.DexExceptionHandlerImpl.java

public void dumpException(DexFileReader reader, File errorFile) throws IOException {
    for (Map.Entry<Method, Exception> e : exceptions.entrySet()) {
        System.err.println("Error:" + e.getKey().toString() + "->" + e.getValue().getMessage());
    }/*from   www .j  av  a 2 s.  co  m*/

    final ZipOutputStream errorZipOutputStream = new ZipOutputStream(FileUtils.openOutputStream(errorFile));
    errorZipOutputStream.putNextEntry(new ZipEntry("summary.txt"));
    final PrintWriter fw = new PrintWriter(new OutputStreamWriter(errorZipOutputStream, "UTF-8"));
    fw.println(getVersionString());
    fw.println("there are " + exceptions.size() + " error methods");
    fw.print("options: ");
    if ((readerConfig & DexFileReader.SKIP_DEBUG) == 0) {
        fw.print(" -d");
    }
    fw.println();
    fw.flush();
    errorZipOutputStream.closeEntry();
    final Out out = new Out() {

        @Override
        public void pop() {

        }

        @Override
        public void push() {

        }

        @Override
        public void s(String s) {
            fw.println(s);
        }

        @Override
        public void s(String format, Object... arg) {
            fw.println(String.format(format, arg));
        }
    };
    final int[] count = new int[] { 0 };
    reader.accept(new EmptyVisitor() {

        @Override
        public DexClassVisitor visit(int accessFlags, String className, String superClass,
                String[] interfaceNames) {
            return new EmptyVisitor() {

                @Override
                public DexMethodVisitor visitMethod(final int accessFlags, final Method method) {
                    if (exceptions.containsKey(method)) {
                        return new EmptyVisitor() {

                            @Override
                            public DexCodeVisitor visitCode() {
                                try {
                                    errorZipOutputStream.putNextEntry(new ZipEntry("t" + count[0]++ + ".txt"));
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                                Exception exception = exceptions.get(method);
                                exception.printStackTrace(fw);
                                out.s("");
                                out.s("DexMethodVisitor mv=cv.visitMethod(%s, %s);",
                                        Escape.methodAcc(accessFlags), Escape.v(method));
                                out.s("DexCodeVisitor code = mv.visitCode();");
                                return new ASMifierCodeV(out);
                            }

                            @Override
                            public void visitEnd() {
                                out.s("mv.visitEnd();");
                                fw.flush();
                                try {
                                    errorZipOutputStream.closeEntry();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        };
                    }
                    return null;
                }

            };
        }

    }, readerConfig);
    errorZipOutputStream.close();

}

From source file:com.l2jserver.service.core.logging.TruncateToZipFileAppender.java

/**
 * This method creates archive with file instead of deleting it.
 * /*from  w  w  w  . j  a  va  2  s.co m*/
 * @param file
 *            file to truncate
 */
protected void truncate(File file) {
    LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started.");

    // Linux systems doesn't provide file creation time, so we have to hope
    // that log files
    // were not modified manually after server starup
    // We can use here Windowns-only solution but that suck :(
    if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) {
        File backupRoot = new File(getBackupDir());
        if (!backupRoot.exists() && !backupRoot.mkdirs()) {
            throw new Error("Can't create backup dir for backup storage");
        }

        SimpleDateFormat df;
        try {
            df = new SimpleDateFormat(getBackupDateFormat());
        } catch (Exception e) {
            throw new Error("Invalid date formate for backup files: " + getBackupDateFormat(), e);
        }
        String date = df.format(new Date(file.lastModified()));

        File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip");

        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            zos = new ZipOutputStream(new FileOutputStream(zipFile));
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setMethod(ZipEntry.DEFLATED);
            entry.setCrc(FileUtils.checksumCRC32(file));
            zos.putNextEntry(entry);
            fis = FileUtils.openInputStream(file);

            byte[] buffer = new byte[1024];
            int readed;
            while ((readed = fis.read(buffer)) != -1) {
                zos.write(buffer, 0, readed);
            }

        } catch (Exception e) {
            throw new Error("Can't create zip file", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    // not critical error
                    LogLog.warn("Can't close zip file", e);
                }
            }

            if (fis != null) {
                try {
                    // not critical error
                    fis.close();
                } catch (IOException e) {
                    LogLog.warn("Can't close zipped file", e);
                }
            }
        }

        if (!file.delete()) {
            throw new Error("Can't delete old log file " + file.getAbsolutePath());
        }
    }
}

From source file:cross.io.misc.WorkflowZipper.java

private void addRelativeZipEntry(final int bufsize, final ZipOutputStream zos, final byte[] input_buffer,
        final String relativePath, final File file, final HashSet<String> zipEntries) throws IOException {
    log.debug("Adding zip entry for file {}", file);
    if (file.exists() && file.isFile()) {
        // Use the file name for the ZipEntry name.
        final ZipEntry zip_entry = new ZipEntry(relativePath);
        if (zipEntries.contains(relativePath)) {
            log.info("Skipping duplicate zip entry {}", relativePath + "/" + file.getName());
            return;
        } else {//w w w . j  ava  2s .c  o m
            zipEntries.add(relativePath);
        }
        zos.putNextEntry(zip_entry);

        // Create a buffered input stream from the file stream.
        final FileInputStream in = new FileInputStream(file);
        // Read from source into buffer and write, thereby compressing
        // on the fly
        try (BufferedInputStream source = new BufferedInputStream(in, bufsize)) {
            // Read from source into buffer and write, thereby compressing
            // on the fly
            int len = 0;
            while ((len = source.read(input_buffer, 0, bufsize)) != -1) {
                zos.write(input_buffer, 0, len);
            }
            zos.flush();
        }
        zos.closeEntry();
    } else {
        log.warn("Skipping nonexistant file or directory {}", file);
    }
}