Example usage for java.util.zip ZipOutputStream putNextEntry

List of usage examples for java.util.zip ZipOutputStream putNextEntry

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

From source file:it.greenvulcano.util.zip.ZipHelper.java

private void internalZipFile(File srcFile, ZipOutputStream zos, URI base) throws IOException {
    String zipEntryName = base.relativize(srcFile.toURI()).getPath();
    if (srcFile.isDirectory()) {
        zipEntryName = zipEntryName.endsWith("/") ? zipEntryName : zipEntryName + "/";
        ZipEntry anEntry = new ZipEntry(zipEntryName);
        anEntry.setTime(srcFile.lastModified());
        zos.putNextEntry(anEntry);

        File[] dirList = srcFile.listFiles();
        for (File file : dirList) {
            internalZipFile(file, zos, base);
        }//  ww w  .ja  va 2  s .c  om
    } else {
        ZipEntry anEntry = new ZipEntry(zipEntryName);
        anEntry.setTime(srcFile.lastModified());
        zos.putNextEntry(anEntry);

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(srcFile);
            IOUtils.copy(fis, zos);
            zos.closeEntry();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException exc) {
                // Do nothing
            }
        }
    }
}

From source file:com.baasbox.db.async.ExportJob.java

@Override
public void run() {
    FileOutputStream dest = null;
    ZipOutputStream zip = null;
    FileOutputStream tempJsonOS = null;
    FileInputStream in = null;//from w w w.  j  av a 2 s  .  co  m
    try {
        //File f = new File(this.fileName);
        File f = File.createTempFile("export", ".temp");

        dest = new FileOutputStream(f);
        zip = new ZipOutputStream(dest);

        File tmpJson = File.createTempFile("export", ".json");
        tempJsonOS = new FileOutputStream(tmpJson);
        DbHelper.exportData(this.appcode, tempJsonOS);
        BaasBoxLogger.info(String.format("Writing %d bytes ", tmpJson.length()));
        tempJsonOS.close();

        ZipEntry entry = new ZipEntry("export.json");
        zip.putNextEntry(entry);
        in = new FileInputStream(tmpJson);
        final int BUFFER = BBConfiguration.getImportExportBufferSize();
        byte buffer[] = new byte[BUFFER];

        int length;
        while ((length = in.read(buffer)) > 0) {
            zip.write(buffer, 0, length);
        }
        zip.closeEntry();
        in.close();

        File manifest = File.createTempFile("manifest", ".txt");
        FileUtils.writeStringToFile(manifest,
                BBInternalConstants.IMPORT_MANIFEST_VERSION_PREFIX + BBConfiguration.getApiVersion());

        ZipEntry entryManifest = new ZipEntry("manifest.txt");
        zip.putNextEntry(entryManifest);
        zip.write(FileUtils.readFileToByteArray(manifest));
        zip.closeEntry();

        tmpJson.delete();
        manifest.delete();

        File finaldestination = new File(this.fileName);
        FileUtils.moveFile(f, finaldestination);

    } catch (Exception e) {
        BaasBoxLogger.error(ExceptionUtils.getMessage(e));
    } finally {
        try {
            if (zip != null)
                zip.close();
            if (dest != null)
                dest.close();
            if (tempJsonOS != null)
                tempJsonOS.close();
            if (in != null)
                in.close();

        } catch (Exception ioe) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(ioe));
        }
    }
}

From source file:de.bps.course.nodes.ChecklistCourseNode.java

@Override
public boolean archiveNodeData(Locale locale, ICourse course, ArchiveOptions options,
        ZipOutputStream exportStream, String charset) {
    String filename = "checklist_" + StringHelper.transformDisplayNameToFileSystemName(getShortName()) + "_"
            + Formatter.formatDatetimeFilesystemSave(new Date(System.currentTimeMillis()));

    Checklist checklist = loadOrCreateChecklist(course.getCourseEnvironment().getCoursePropertyManager());
    String exportContent = XStreamHelper.createXStreamInstance().toXML(checklist);
    try {//from w ww .j av  a 2  s  . c  o  m
        exportStream.putNextEntry(new ZipEntry(filename));
        IOUtils.write(exportContent, exportStream);
        exportStream.closeEntry();
    } catch (IOException e) {
        log.error("", e);
    }
    return true;
}

From source file:edu.stanford.epad.epadws.handlers.dicom.DownloadUtil.java

public static boolean ZipAndStreamFiles(OutputStream out, List<String> fileNames, String dirPath) {

    File dir_file = new File(dirPath);
    int dir_l = dir_file.getAbsolutePath().length();
    ZipOutputStream zipout = new ZipOutputStream(out);
    zipout.setLevel(1);//from  ww  w.j a va  2s . c om
    for (int i = 0; i < fileNames.size(); i++) {
        File f = (File) new File(dirPath + fileNames.get(i));
        if (f.canRead()) {
            log.debug("Adding file: " + f.getAbsolutePath());
            try {
                zipout.putNextEntry(new ZipEntry(f.getAbsolutePath().substring(dir_l + 1)));
            } catch (Exception e) {
                log.warning("Error adding to zip file", e);
                return false;
            }
            BufferedInputStream fr;
            try {
                fr = new BufferedInputStream(new FileInputStream(f));

                byte buffer[] = new byte[0xffff];
                int b;
                while ((b = fr.read(buffer)) != -1)
                    zipout.write(buffer, 0, b);

                fr.close();
                zipout.closeEntry();

            } catch (Exception e) {
                log.warning("Error closing zip file", e);
                return false;
            }
        }
    }

    try {
        zipout.finish();
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    return true;

}

From source file:com.samczsun.helios.tasks.DecompileAndSaveTask.java

@Override
public void run() {
    File file = FileChooserUtil.chooseSaveLocation(Settings.LAST_DIRECTORY.get().asString(),
            Arrays.asList("zip"));
    if (file == null)
        return;// www.  j  a  v a 2 s .  c  o  m
    if (file.exists()) {
        boolean delete = SWTUtil.promptForYesNo(Constants.REPO_NAME + " - Overwrite existing file",
                "The selected file already exists. Overwrite?");
        if (!delete) {
            return;
        }
    }

    AtomicReference<Transformer> transformer = new AtomicReference<>();

    Display display = Display.getDefault();
    display.syncExec(() -> {
        Shell shell = new Shell(Display.getDefault());
        Combo combo = new Combo(shell, SWT.DROP_DOWN | SWT.BORDER);
        List<Transformer> transformers = new ArrayList<>();
        transformers.addAll(Decompiler.getAllDecompilers());
        transformers.addAll(Disassembler.getAllDisassemblers());
        for (Transformer t : transformers) {
            combo.add(t.getName());
        }
        shell.pack();
        shell.open();
        System.out.println(Arrays.toString(combo.getItems()));
    });

    // TODO: Ask for list of decompilers

    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        fileOutputStream = new FileOutputStream(file);
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        for (Pair<String, String> pair : data) {
            StringBuilder buffer = new StringBuilder();
            LoadedFile loadedFile = Helios.getLoadedFile(pair.getValue0());
            if (loadedFile != null) {
                String innerName = pair.getValue1();
                byte[] bytes = loadedFile.getData().get(innerName);
                if (bytes != null) {
                    Decompiler.getById("cfr-decompiler").decompile(null, bytes, buffer);
                    zipOutputStream.putNextEntry(
                            new ZipEntry(innerName.substring(0, innerName.length() - 6) + ".java"));
                    zipOutputStream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
                    zipOutputStream.closeEntry();
                }
            }
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * This method zips the contents of Directory specified into a zip file whose name is provided.
 * //www  .ja  va  2  s.  com
 * @param dir {@link String}
 * @param zipfile {@link String}
 * @param excludeBatchXml boolean
 * @throws IOException 
 * @throws IllegalArgumentException in case of error
 */
public static void zipDirectory(final String dir, final String zipfile, final boolean excludeBatchXml)
        throws IOException, IllegalArgumentException {
    // Check that the directory is a directory, and get its contents
    File directory = new File(dir);
    if (!directory.isDirectory()) {
        throw new IllegalArgumentException("Not a directory:  " + dir);
    }
    String[] entries = directory.list();
    byte[] buffer = new byte[UtilConstants.BUFFER_CONST]; // Create a buffer for copying
    int bytesRead;

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

    for (int index = 0; index < entries.length; index++) {
        if (excludeBatchXml && entries[index].contains(IUtilCommonConstants.BATCH_XML)) {
            continue;
        }
        File file = new File(directory, entries[index]);
        if (file.isDirectory()) {
            continue;// Ignore directory
        }
        FileInputStream input = new FileInputStream(file); // Stream to read file
        ZipEntry entry = new ZipEntry(file.getName()); // Make a ZipEntry
        out.putNextEntry(entry); // Store entry
        bytesRead = input.read(buffer);
        while (bytesRead != -1) {
            out.write(buffer, 0, bytesRead);
            bytesRead = input.read(buffer);
        }
        if (input != null) {
            input.close();
        }
    }
    if (out != null) {
        out.close();
    }
}

From source file:org.syncope.core.scheduling.ReportJob.java

@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {

    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }/* w  ww  .ja  v a2  s. c o  m*/

    // 1. create execution
    ReportExec execution = new ReportExec();
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStartDate(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    // 2. define a SAX handler for generating result as XML
    TransformerHandler handler;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    try {
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        handler = transformerFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        // a single ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(report.getName()));

        // streaming SAX handler in a compressed byte array stream
        handler.setResult(new StreamResult(zos));
    } catch (Exception e) {
        throw new JobExecutionException("While configuring for SAX generation", e, true);
    }

    execution.setStatus(ReportExecStatus.RUNNING);
    execution = reportExecDAO.save(execution);

    ConfigurableListableBeanFactory beanFactory = ApplicationContextManager.getApplicationContext()
            .getBeanFactory();

    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    StringWriter exceptionWriter = new StringWriter();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ATTR_NAME, XSD_STRING, report.getName());
        handler.startElement("", "", ELEMENT_REPORT, atts);

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class reportletClass = null;
            try {
                reportletClass = Class.forName(reportletConf.getReportletClassName());
            } catch (ClassNotFoundException e) {
                LOG.error("Reportlet class not found: {}", reportletConf.getReportletClassName(), e);

            }

            if (reportletClass != null) {
                Reportlet autowired = (Reportlet) beanFactory.createBean(reportletClass,
                        AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                autowired.setConf(reportletConf);

                // invoke reportlet
                try {
                    autowired.extract(handler);
                } catch (Exception e) {
                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable t = e instanceof ReportException ? e.getCause() : e;
                    exceptionWriter.write(t.getMessage() + "\n\n");
                    t.printStackTrace(new PrintWriter(exceptionWriter));
                    reportExecutionMessage.append(exceptionWriter.toString()).append("\n==================\n");
                }
            }
        }

        // report footer
        handler.endElement("", "", ELEMENT_REPORT);
        handler.endDocument();

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {

            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);

        exceptionWriter.write(e.getMessage() + "\n\n");
        e.printStackTrace(new PrintWriter(exceptionWriter));
        reportExecutionMessage.append(exceptionWriter.toString());

        throw new JobExecutionException(e, true);
    } finally {
        try {
            zos.closeEntry();
            zos.close();
            baos.close();
        } catch (IOException e) {
            LOG.error("While closing StreamResult's backend", e);
        }

        execution.setExecResult(baos.toByteArray());
        execution.setMessage(reportExecutionMessage.toString());
        execution.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java

/**
 * Given a DITA map bounded object set, zips it up into a DXP Zip package.
 * @param mapBos/*from ww  w .  j a va  2s .  c  o  m*/
 * @param outputZipFile
 * @throws Exception 
 */
public static void zipMapBos(DitaBoundedObjectSet mapBos, File outputZipFile, MapBosProcessorOptions options)
        throws Exception {
    /*
     *  Some potential complexities:
     *  
     *  - DXP package spec requires either a map manifest or that 
     *  there be exactly one map at the root of the zip package. This 
     *  means that the file structure of the BOS needs to be checked to
     *  see if the files already conform to this structure and, if not,
     *  they need to be reorganized and have pointers rewritten if a 
     *  map manifest has not been requested.
     *  
     *  - If the file structure of the original data includes files not
     *  below the root map, the file organization must be reworked whether
     *  or not a map manifest has been requested.
     *  
     *  - Need to generate DXP map manifest if a manifest is requested.
     *  
     *  - If user has requested that the original file structure be 
     *  remembered, a manifest must be generated.
     */

    log.debug("Determining zip file organization...");

    BosVisitor visitor = new DxpFileOrganizingBosVisitor();
    visitor.visit(mapBos);

    if (!options.isQuiet())
        log.info("Creating DXP package \"" + outputZipFile.getAbsolutePath() + "\"...");
    OutputStream outStream = new FileOutputStream(outputZipFile);
    ZipOutputStream zipOutStream = new ZipOutputStream(outStream);

    ZipEntry entry = null;

    // At this point, URIs of all members should reflect their
    // storage location within the resulting DXP package. There
    // must also be a root map, either the original map
    // we started with or a DXP manifest map.

    URI rootMapUri = mapBos.getRoot().getEffectiveUri();
    URI baseUri = null;
    try {
        baseUri = AddressingUtil.getParent(rootMapUri);
    } catch (URISyntaxException e) {
        throw new BosException("URI syntax exception getting parent URI: " + e.getMessage());
    }

    Set<String> dirs = new HashSet<String>();

    if (!options.isQuiet())
        log.info("Constructing DXP package...");
    for (BosMember member : mapBos.getMembers()) {
        if (!options.isQuiet())
            log.info("Adding member " + member + " to zip...");
        URI relativeUri = baseUri.relativize(member.getEffectiveUri());
        File temp = new File(relativeUri.getPath());
        String parentPath = temp.getParent();
        if (parentPath != null && !"".equals(parentPath) && !parentPath.endsWith("/")) {
            parentPath += "/";
        }
        log.debug("parentPath=\"" + parentPath + "\"");
        if (!"".equals(parentPath) && parentPath != null && !dirs.contains(parentPath)) {
            entry = new ZipEntry(parentPath);
            zipOutStream.putNextEntry(entry);
            zipOutStream.closeEntry();
            dirs.add(parentPath);
        }
        entry = new ZipEntry(relativeUri.getPath());
        zipOutStream.putNextEntry(entry);
        IOUtils.copy(member.getInputStream(), zipOutStream);
        zipOutStream.closeEntry();
    }

    zipOutStream.close();
    if (!options.isQuiet())
        log.info("DXP package \"" + outputZipFile.getAbsolutePath() + "\" created.");
}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

private void writeZipEntry(String prefix, ZipOutputStream out, File file)
        throws IOException, FileNotFoundException {
    ZipEntry mySkinFile = new ZipEntry(prefix + file.getName());
    mySkinFile.setSize(file.length());/*from   w w w . j a  v a2 s  .co  m*/
    mySkinFile.setTime(file.lastModified());
    out.putNextEntry(mySkinFile);

    byte[] buf = new byte[1024];
    InputStream in = new FileInputStream(file);
    try {
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    } finally {
        in.close();
    }
    // Complete the entry
    out.closeEntry();
}

From source file:edu.ku.brc.specify.rstools.GoogleEarthExporter.java

/**
 * @param outputFile//from w  ww  . ja v  a2  s  . c  o  m
 * @param defaultIconFile
 */
protected void createKMZ(final File outputFile, final File defaultIconFile) throws IOException {
    // now we have the KML in outputFile
    // we need to create a KMZ (zip file containing doc.kml and other files)

    // create a buffer for reading the files
    byte[] buf = new byte[1024];
    int len;

    // create the KMZ file
    File outputKMZ = File.createTempFile("sp6-export-", ".kmz");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputKMZ));

    // add the doc.kml file to the ZIP
    FileInputStream in = new FileInputStream(outputFile);
    // add ZIP entry to output stream
    out.putNextEntry(new ZipEntry("doc.kml"));
    // copy the bytes
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    // complete the entry
    out.closeEntry();
    in.close();

    // add a "files" directory to the KMZ file
    ZipEntry filesDir = new ZipEntry("files/");
    out.putNextEntry(filesDir);
    out.closeEntry();

    if (defaultIconFile != null) {
        File iconTmpFile = defaultIconFile;
        if (false) {
            // Shrink File
            ImageIcon icon = new ImageIcon(defaultIconFile.getAbsolutePath());
            BufferedImage bimage = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                    BufferedImage.TYPE_INT_ARGB);
            Graphics g = bimage.createGraphics();
            g.drawImage(icon.getImage(), 0, 0, null);
            g.dispose();
            BufferedImage scaledBI = GraphicsUtils.getScaledInstance(bimage, 16, 16, true);
            iconTmpFile = File.createTempFile("sp6-export-icon-scaled", ".png");
            ImageIO.write(scaledBI, "PNG", iconTmpFile);
        }

        // add the specify32.png file (default icon file) to the ZIP (in the "files" directory)
        in = new FileInputStream(iconTmpFile);
        // add ZIP entry to output stream
        out.putNextEntry(new ZipEntry("files/specify32.png"));
        // copy the bytes
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // complete the entry
        out.closeEntry();
        in.close();
    }

    // complete the ZIP file
    out.close();

    // now put the KMZ file where the KML output was
    FileUtils.copyFile(outputKMZ, outputFile);

    outputKMZ.delete();
}