Example usage for java.util.zip ZipOutputStream write

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

Introduction

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

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:fll.web.GatherBugReport.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    ZipOutputStream zipOut = null;
    final StringBuilder message = new StringBuilder();
    try {/*  w  ww . j av  a  2s  . c om*/
        if (null != SessionAttributes.getMessage(session)) {
            message.append(SessionAttributes.getMessage(session));
        }

        connection = datasource.getConnection();
        final Document challengeDocument = ApplicationAttributes.getChallengeDocument(application);

        final File fllWebInfDir = new File(application.getRealPath("/WEB-INF"));
        final String nowStr = new SimpleDateFormat("yyyy-MM-dd_HH-mm").format(new Date());
        final File bugReportFile = File.createTempFile(nowStr, ".zip", fllWebInfDir);

        zipOut = new ZipOutputStream(new FileOutputStream(bugReportFile));

        final String description = request.getParameter("bug_description");
        if (null != description) {
            zipOut.putNextEntry(new ZipEntry("bug_description.txt"));
            zipOut.write(description.getBytes(Utilities.DEFAULT_CHARSET));
        }

        zipOut.putNextEntry(new ZipEntry("server_info.txt"));
        zipOut.write(String.format(
                "Java version: %s%nJava vendor: %s%nOS Name: %s%nOS Arch: %s%nOS Version: %s%nServlet API: %d.%d%nServlet container: %s%n",
                System.getProperty("java.vendor"), //
                System.getProperty("java.version"), //
                System.getProperty("os.name"), //
                System.getProperty("os.arch"), //
                System.getProperty("os.version"), //
                application.getMajorVersion(), application.getMinorVersion(), //
                application.getServerInfo()).getBytes(Utilities.DEFAULT_CHARSET));

        addDatabase(zipOut, connection, challengeDocument);
        addLogFiles(zipOut, application);

        message.append(String.format(
                "<i>Bug report saved to '%s', please notify the computer person in charge to look for bug report files.</i>",
                bugReportFile.getAbsolutePath()));
        session.setAttribute(SessionAttributes.MESSAGE, message);

        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/"));

    } catch (final SQLException sqle) {
        throw new RuntimeException(sqle);
    } finally {
        SQLFunctions.close(connection);
        IOUtils.closeQuietly(zipOut);
    }

}

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

protected void writeSkinZipEntries(String prefix, File dir, ZipOutputStream out) throws IOException {
    if (dir.isDirectory()) {
        if (prefix.length() > 0) {
            prefix = prefix + "/";
        }/*from   w w  w .  j a  v a2s .  co  m*/
        File[] myChildren = dir.listFiles();
        for (File myFile : myChildren) {
            if (myFile.isFile()) {
                writeZipEntry(prefix, out, myFile);
            } else {
                ZipEntry mySkinFile = new ZipEntry(prefix + myFile.getName() + "/");
                mySkinFile.setTime(myFile.lastModified());
                out.putNextEntry(mySkinFile);
                out.write(new byte[0]);
                out.closeEntry();
                writeSkinZipEntries(prefix + myFile.getName(), myFile, out);
            }
        }
    }
}

From source file:com.cordys.coe.ac.emailio.archive.FileArchiver.java

/**
 * This method starts the actual archiving of the passed on context containers.
 *
 * @param   lccContainers  The containers to archive.
 * @param   spqmManager    The QueryManager to use.
 *
 * @throws  ArchiverException  In case of any exceptions.
 *
 * @see     com.cordys.coe.ac.emailio.archive.IArchiver#doArchive(java.util.List, com.cordys.coe.ac.emailio.objects.IStorageProviderQueryManager)
 */// w  w  w . j av a2 s  .  c om
@Override
public void doArchive(List<ContextContainer> lccContainers, IStorageProviderQueryManager spqmManager)
        throws ArchiverException {
    File fArchive = getArchiveFolder();

    for (ContextContainer ccContainer : lccContainers) {
        int iWrapperXML = 0;
        ZipOutputStream zosZip = null;
        File fZipFile = null;
        List<EmailMessage> lEmails = null;

        try {
            lEmails = spqmManager.getEmailMessagesByContextID(ccContainer.getID());

            // Create the ZipFile
            fZipFile = new File(fArchive, ccContainer.getID().replaceAll("[^a-zA-Z0-9]", "") + ".zip");
            zosZip = new ZipOutputStream(new FileOutputStream(fZipFile, false));
            zosZip.setLevel(m_iZipLevel);

            // Now we have both the container and the emails. We will create an XML
            // to hold all data.
            int iObjectData = ccContainer._getObjectData();

            // Create the zip entry for it.
            ZipEntry zeContainer = new ZipEntry("container.xml");
            zosZip.putNextEntry(zeContainer);

            String sXML = Node.writeToString(iObjectData, true);
            zosZip.write(sXML.getBytes());
            zosZip.closeEntry();

            // Add the email messages to the zip file.
            int iCount = 0;

            for (EmailMessage emMessage : lEmails) {
                iObjectData = emMessage._getObjectData();

                ZipEntry zeEmail = new ZipEntry("email_" + iCount++ + ".xml");
                zosZip.putNextEntry(zeEmail);

                sXML = Node.writeToString(iObjectData, true);
                zosZip.write(sXML.getBytes());
                zosZip.closeEntry();
            }

            // Now all files are written into a single Zip file, so we can close it.
        } catch (Exception e) {
            throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ARCHIVING_CONTAINER_0,
                    ccContainer.getID());
        } finally {
            if (iWrapperXML != 0) {
                Node.delete(iWrapperXML);
            }

            if (zosZip != null) {
                try {
                    zosZip.close();
                } catch (IOException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Error closing zip file " + fZipFile.getAbsolutePath(), e);
                    }
                }
            }
        }

        // If we get here the zipfile was successfully created. So now we need to remove the
        // mails and the container from the current storage provider.
        try {
            spqmManager.removeContextContainer(ccContainer);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Archived the container with id " + ccContainer.getID());
            }
        } catch (StorageProviderException e) {
            throw new ArchiverException(e,
                    ArchiverExceptionMessages.ARE_ERROR_REMOVING_CONTEXT_CONTAINER_0_FROM_THE_STORAGE,
                    ccContainer.getID());
        }
    }

    // Now all containers have been archived, we will create a single zip file.
    try {
        File fFinalArchive = new File(fArchive.getParentFile(), fArchive.getName() + ".zip");

        if (LOG.isDebugEnabled()) {
            LOG.debug("Archiving folder " + fArchive.getCanonicalPath() + " into file "
                    + fFinalArchive.getCanonicalPath());
        }

        new ZipUtil().compress(fArchive, fFinalArchive.getAbsolutePath());
    } catch (Exception e) {
        throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ZIPPING_ALL_ARCHIVE_FILES);
    }
}

From source file:com.comcast.video.dawg.show.video.VideoSnap.java

/**
 * Retrieve the images with input device ids from cache and stores it in zip
 * output stream.//from   www.  j  a  v a2 s.c om
 *
 * @param capturedImageIds
 *            Ids of captures images
 * @param deviceMacs
 *            Mac address of selected devices
 * @param response
 *            http servelet response
 * @param session
 *            http session.
 */
public void addImagesToZipFile(String[] capturedImageIds, String[] deviceMacs, HttpServletResponse response,
        HttpSession session) {

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + "Images_" + getCurrentDateAndTime() + ".zip\"");
    response.setContentType("application/zip");

    ServletOutputStream serveletOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        serveletOutputStream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        BufferedImage image;
        ZipEntry zipEntry;
        ByteArrayOutputStream imgByteArrayOutputStream = null;

        for (int i = 0; i < deviceMacs.length; i++) {
            // Check whether id of captured image is null or not
            if (!StringUtils.isEmpty(capturedImageIds[i])) {
                image = imgCache.getItem(capturedImageIds[i]);
                zipEntry = new ZipEntry(deviceMacs[i].toUpperCase() + "." + IMG_FORMAT);
                zipOutputStream.putNextEntry(zipEntry);
                imgByteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_FORMAT, imgByteArrayOutputStream);
                imgByteArrayOutputStream.flush();
                zipOutputStream.write(imgByteArrayOutputStream.toByteArray());
                zipOutputStream.closeEntry();
            }
        }

        zipOutputStream.flush();
        zipOutputStream.close();
        serveletOutputStream.write(byteArrayOutputStream.toByteArray());
    } catch (IOException ioe) {
        LOGGER.error("Image zipping failed !!!", ioe);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
}

From source file:net.minecraftforge.fml.common.asm.transformers.AccessTransformer.java

private static void processJar(File inFile, File outFile, AccessTransformer[] transformers) throws IOException {
    ZipInputStream inJar = null;//from  www. j a v a2s  . com
    ZipOutputStream outJar = null;

    try {
        try {
            inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(inFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open input file: " + e.getMessage());
        }

        try {
            outJar = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("Could not open output file: " + e.getMessage());
        }

        ZipEntry entry;
        while ((entry = inJar.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                outJar.putNextEntry(entry);
                continue;
            }

            byte[] data = new byte[4096];
            ByteArrayOutputStream entryBuffer = new ByteArrayOutputStream();

            int len;
            do {
                len = inJar.read(data);
                if (len > 0) {
                    entryBuffer.write(data, 0, len);
                }
            } while (len != -1);

            byte[] entryData = entryBuffer.toByteArray();

            String entryName = entry.getName();

            if (entryName.endsWith(".class") && !entryName.startsWith(".")) {
                ClassNode cls = new ClassNode();
                ClassReader rdr = new ClassReader(entryData);
                rdr.accept(cls, 0);
                String name = cls.name.replace('/', '.').replace('\\', '.');

                for (AccessTransformer trans : transformers) {
                    entryData = trans.transform(name, name, entryData);
                }
            }

            ZipEntry newEntry = new ZipEntry(entryName);
            outJar.putNextEntry(newEntry);
            outJar.write(entryData);
        }
    } finally {
        IOUtils.closeQuietly(outJar);
        IOUtils.closeQuietly(inJar);
    }
}

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

@Override
public void run() {
    File file = FileChooserUtil.chooseSaveLocation(Settings.LAST_DIRECTORY.get().asString(),
            Collections.singletonList("zip"));
    if (file == null)
        return;//from   w  w  w  .j  a  v a2s  .c om
    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.asyncExec(() -> {
        Shell shell = new Shell(Display.getDefault());
        FillLayout layout = new FillLayout();
        layout.type = SWT.VERTICAL;
        shell.setLayout(layout);
        Transformer.getAllTransformers(t -> {
            return t instanceof Decompiler || t instanceof Disassembler;
        }).forEach(t -> {
            Button button = new Button(shell, SWT.RADIO);
            button.setText(t.getName());
            button.addSelectionListener(new SelectionAdapter() {
                @Override
                public void widgetSelected(SelectionEvent e) {
                    transformer.set(t);
                }
            });
        });
        Button ok = new Button(shell, SWT.NONE);
        ok.setText("OK");
        ok.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.close();
                shell.dispose();
                synchronized (transformer) {
                    transformer.notify();
                }
            }
        });
        shell.pack();
        SWTUtil.center(shell);
        shell.open();
    });

    synchronized (transformer) {
        try {
            transformer.wait();
        } catch (InterruptedException e) {
            ExceptionHandler.handle(e);
        }
    }

    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        file.createNewFile();
        fileOutputStream = new FileOutputStream(file);
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        Set<String> written = new HashSet<>();
        for (Pair<String, String> pair : data) {
            LoadedFile loadedFile = Helios.getLoadedFile(pair.getValue0());
            if (loadedFile != null) {
                String innerName = pair.getValue1();
                byte[] bytes = loadedFile.getAllData().get(innerName);
                if (bytes != null) {
                    if (loadedFile.getClassNode(pair.getValue1()) != null) {
                        StringBuilder buffer = new StringBuilder();
                        transformer.get().transform(loadedFile.getClassNode(pair.getValue1()), bytes, buffer);
                        String name = innerName.substring(0, innerName.length() - 6) + ".java";
                        if (written.add(name)) {
                            zipOutputStream.putNextEntry(new ZipEntry(name));
                            zipOutputStream.write(buffer.toString().getBytes(StandardCharsets.UTF_8));
                            zipOutputStream.closeEntry();
                        } else {
                            SWTUtil.showMessage("Duplicate entry occured: " + name);
                        }
                    } else {
                        if (written.add(pair.getValue1())) {
                            zipOutputStream.putNextEntry(new ZipEntry(pair.getValue1()));
                            zipOutputStream.write(loadedFile.getAllData().get(pair.getValue1()));
                            zipOutputStream.closeEntry();
                        } else {
                            SWTUtil.showMessage("Duplicate entry occured: " + pair.getValue1());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        ExceptionHandler.handle(e);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:eionet.meta.exports.ods.Ods.java

/**
 * Zips file.//from  w  w  w  .  j  a va2s  .  c om
 *
 * @param fileToZip
 *            file to zip (full path)
 * @param fileName
 *            file name
 * @throws java.lang.Exception
 *             if operation fails.
 */
private void zip(String fileToZip, String fileName) throws Exception {
    // get source file
    File src = new File(workingFolderPath + ODS_FILE_NAME);
    ZipFile zipFile = new ZipFile(src);
    // create temp file for output
    File tempDst = new File(workingFolderPath + ODS_FILE_NAME + ".zip");
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(tempDst));
    // iterate on each entry in zip file
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        BufferedInputStream bis;
        if (StringUtils.equals(fileName, zipEntry.getName())) {
            bis = new BufferedInputStream(new FileInputStream(new File(fileToZip)));
        } else {
            bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
        }
        ZipEntry ze = new ZipEntry(zipEntry.getName());
        zos.putNextEntry(ze);

        while (bis.available() > 0) {
            zos.write(bis.read());
        }
        zos.closeEntry();
        bis.close();
    }
    zos.finish();
    zos.close();
    zipFile.close();
    // rename file
    src.delete();
    tempDst.renameTo(src);
}

From source file:au.org.ala.biocache.service.DownloadService.java

/**
 * Writes the supplied download to the supplied output stream. It will include all the appropriate citations etc.
 * /*  w  ww  .  j  a v a 2 s  . c o m*/
 * @param dd
 * @param requestParams
 * @param ip
 * @param out
 * @param includeSensitive
 * @param fromIndex
 * @throws Exception
 */
private void writeQueryToStream(DownloadDetailsDTO dd, DownloadRequestParams requestParams, String ip,
        OutputStream out, boolean includeSensitive, boolean fromIndex, boolean limit) throws Exception {

    String filename = requestParams.getFile();
    String originalParams = requestParams.toString();
    //Use a zip output stream to include the data and citation together in the download
    ZipOutputStream zop = new ZipOutputStream(out);
    String suffix = requestParams.getFileType().equals("shp") ? "zip" : requestParams.getFileType();
    zop.putNextEntry(new java.util.zip.ZipEntry(filename + "." + suffix));
    //put the facets
    if ("all".equals(requestParams.getQa())) {
        requestParams.setFacets(new String[] { "assertions", "data_resource_uid" });
    } else {
        requestParams.setFacets(new String[] { "data_resource_uid" });
    }
    Map<String, Integer> uidStats = null;
    try {
        if (fromIndex)
            uidStats = searchDAO.writeResultsFromIndexToStream(requestParams, zop, includeSensitive, dd, limit);
        else
            uidStats = searchDAO.writeResultsToStream(requestParams, zop, 100, includeSensitive, dd);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        unregisterDownload(dd);
    }
    zop.closeEntry();

    //add the Readme for the data field descriptions
    zop.putNextEntry(new java.util.zip.ZipEntry("README.html"));
    zop.write(("For more information about the fields that are being downloaded please consult <a href='"
            + dataFieldDescriptionURL + "'>Download Fields</a>.").getBytes());

    //add the readme for the Shape file header mappings if necessary
    if (dd.getHeaderMap() != null) {
        zop.putNextEntry(new java.util.zip.ZipEntry("Shape-README.html"));
        zop.write(
                ("The name of features is limited to 10 characters. Listed below are the mappings of feature name to download field:")
                        .getBytes());
        zop.write(("<table><td><b>Feature</b></td><td><b>Download Field<b></td>").getBytes());
        for (String key : dd.getHeaderMap().keySet()) {
            zop.write(("<tr><td>" + key + "</td><td>" + dd.getHeaderMap().get(key) + "</td></tr>").getBytes());
        }
        zop.write(("</table>").getBytes());
        //logger.debug("JSON::: " + objectMapper.writeValueAsString(dd));
    }

    //Add the data citation to the download
    if (uidStats != null && !uidStats.isEmpty() && citationsEnabled) {
        //add the citations for the supplied uids
        zop.putNextEntry(new java.util.zip.ZipEntry("citation.csv"));
        try {
            getCitations(uidStats, zop, requestParams.getSep(), requestParams.getEsc());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        zop.closeEntry();
    } else {
        logger.debug("Not adding citation. Enabled: " + citationsEnabled + " uids: " + uidStats);
    }
    zop.flush();
    zop.close();

    //now construct the sourceUrl for the log event
    String sourceUrl = originalParams.contains("qid:") ? webservicesRoot + "?" + requestParams.toString()
            : webservicesRoot + "?" + originalParams;

    //logger.debug("UID stats : " + uidStats);
    //log the stats to ala logger        
    LogEventVO vo = new LogEventVO(1002, requestParams.getReasonTypeId(), requestParams.getSourceTypeId(),
            requestParams.getEmail(), requestParams.getReason(), ip, null, uidStats, sourceUrl);
    logger.log(RestLevel.REMOTE, vo);
}

From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
    ZipOutputStream zout = null;
    OutputStream out = null;//  w ww  .j a va2  s . c  o m
    try {
        sCheckPermissions(resourceRequest);
        _log.info("Export All As Zip");

        Map<String, String> savedscripts = new TreeMap<String, String>();
        PortletPreferences prefs = resourceRequest.getPreferences();
        for (String prefName : prefs.getMap().keySet()) {
            if (prefName != null && prefName.startsWith("savedscript.")) {
                String scriptName = prefName.substring("savedscript.".length());
                String script = prefs.getValue(prefName, "");
                String lang = prefs.getValue("lang." + scriptName, getDefaultLanguage());
                savedscripts.put(scriptName + "." + lang, script);
            }
        }

        String filename = "liferay-scripts.zip";

        out = resourceResponse.getPortletOutputStream();
        zout = new ZipOutputStream(out);
        for (String key : savedscripts.keySet()) {
            String value = savedscripts.get(key);
            zout.putNextEntry(new ZipEntry(key));
            zout.write(value.getBytes("utf-8"));
        }
        resourceResponse.setContentType("application/zip");
        resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate");
        resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, "filename=" + filename);

    } catch (Exception e) {
        _log.error(e);
    } finally {
        try {
            if (zout != null) {
                zout.close();
            }
        } catch (Exception e) {
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
        }
    }
}