Example usage for java.util.zip ZipOutputStream ZipOutputStream

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

Introduction

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

Prototype

public ZipOutputStream(OutputStream out) 

Source Link

Document

Creates a new ZIP output stream.

Usage

From source file:com.compomics.pladipus.core.control.util.ZipUtils.java

/**
 * Zips a single file to the specified folder
 *
 * @param input the original folder//from w  ww  .  j  av  a2s  .c o m
 * @param output the destination zip file
 */
public static void zipFile(File inputFile, File zipFile) {

    try (FileInputStream fileInputStream = new FileInputStream(inputFile);
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
        ZipEntry zipEntry = new ZipEntry(inputFile.getName());
        zipOutputStream.putNextEntry(zipEntry);
        byte[] buf = new byte[1024];
        int bytesRead;

        // Read the input file by chucks of 1024 bytes
        // and write the read bytes to the zip stream
        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            zipOutputStream.write(buf, 0, bytesRead);
        }

        // close ZipEntry to store the stream to the file
        zipOutputStream.closeEntry();
        LOGGER.debug("Regular file :" + inputFile.getCanonicalPath() + " is zipped to archive :"
                + zipFile.getAbsolutePath());
    } catch (IOException e) {
        LOGGER.error(e);
    }

}

From source file:io.lightlink.excel.StreamingExcelTransformer.java

public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException {
    try {/*www.  j  a v a2s. c  om*/
        ZipInputStream zipIn = new ZipInputStream(template);
        ZipOutputStream zipOut = new ZipOutputStream(out);

        ZipEntry entry;

        Map<String, byte[]> sheets = new HashMap<String, byte[]>();

        while ((entry = zipIn.getNextEntry()) != null) {

            String name = entry.getName();

            if (name.startsWith("xl/sharedStrings.xml")) {

                byte[] bytes = IOUtils.toByteArray(zipIn);
                zipOut.putNextEntry(new ZipEntry(name));
                zipOut.write(bytes);

                sharedStrings = processSharedStrings(bytes);

            } else if (name.startsWith("xl/worksheets/sheet")) {
                byte[] bytes = IOUtils.toByteArray(zipIn);
                sheets.put(name, bytes);
            } else if (name.equals("xl/calcChain.xml")) {
                // skip this file, let excel recreate it
            } else if (name.equals("xl/workbook.xml")) {
                zipOut.putNextEntry(new ZipEntry(name));

                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();
                Writer writer = new OutputStreamWriter(zipOut, "UTF-8");

                byte[] bytes = IOUtils.toByteArray(zipIn);
                saxParser.parse(new ByteArrayInputStream(bytes), new WorkbookTemplateHandler(writer));

                writer.flush();
            } else {
                zipOut.putNextEntry(new ZipEntry(name));
                IOUtils.copy(zipIn, zipOut);
            }

        }

        for (Map.Entry<String, byte[]> sheetEntry : sheets.entrySet()) {
            String name = sheetEntry.getKey();

            byte[] bytes = sheetEntry.getValue();
            zipOut.putNextEntry(new ZipEntry(name));
            processSheet(bytes, zipOut, visitor);
        }

        zipIn.close();
        template.close();

        zipOut.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.toString(), e);
    }
}

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 {//www  . ja  v a 2  s  .co m
        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:com.mobicage.rogerthat.mfr.dal.Streamable.java

public String toBase64() {
    try {//  w  ww  .j a v  a 2  s. co m
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ZipOutputStream zip = new ZipOutputStream(bos);
            try {
                zip.setLevel(9);
                zip.putNextEntry(new ZipEntry("entry"));
                try {
                    ObjectOutput out = new ObjectOutputStream(zip);
                    try {
                        out.writeObject(this);
                    } finally {
                        out.flush();
                    }
                } finally {
                    zip.closeEntry();
                }
                zip.flush();
                return Base64.encodeBase64URLSafeString(bos.toByteArray());
            } finally {
                zip.close();
            }
        } finally {
            bos.close();
        }
    } catch (IOException e) {
        log.log((Level.SEVERE), "IO Error while serializing member", e);
        return null;
    }
}

From source file:au.com.permeance.liferay.util.zip.ZipWriter.java

public ZipWriter(File file) throws IOException {
    this.zipFile = file;
    this.zos = new ZipOutputStream(new FileOutputStream(this.zipFile));
}

From source file:de.knowwe.revisions.manager.action.DownloadRevisionZip.java

@Override
public void execute(UserActionContext context) throws IOException {
    if (context.getParameters().containsKey("date")) {
        String dateParam = context.getParameter("date");
        Date date;/*from  w  w w  .j  a  v  a2  s.c o  m*/
        try {
            date = new Date(Long.parseLong(dateParam));

            String filename = "revision-" + DATE_FORMAT.format(date) + ".zip";
            context.setContentType("application/force-download");
            context.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
            OutputStream outs = context.getOutputStream();
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(outs));
            zipRev(date, zos, context);
            outs.flush();
            outs.close();
        } catch (Exception e) {
            context.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.valueOf(e));
            e.printStackTrace();
        }

    }
}

From source file:de.decidr.model.workflowmodel.deployment.PackageBuilder.java

/**
 * @param workFlowId//from   w  ww.  j  a  va  2  s  . c  o m
 * @param bpel
 * @param wsdl
 * @param dd
 *            depoyment descriptor
 * @param serverLocation
 *            location for service endpoints
 * @return the zip'ed package as byte array
 * @throws JAXBException
 * @throws IOException
 */
public static byte[] getPackage(long workFlowId, TProcess bpel, TDefinitions wsdl, TDeployment dd,
        HashMap<String, List<ServerLoadView>> serverMap) throws JAXBException, IOException {

    ByteArrayOutputStream zipOut = new ByteArrayOutputStream();

    TransformationHelper th = new TransformationHelper();

    de.decidr.model.schema.bpel.executable.ObjectFactory of = new de.decidr.model.schema.bpel.executable.ObjectFactory();
    de.decidr.model.schema.wsdl.ObjectFactory ofwasl = new de.decidr.model.schema.wsdl.ObjectFactory();
    de.decidr.model.schema.bpel.dd.ObjectFactory ofdd = new de.decidr.model.schema.bpel.dd.ObjectFactory();

    JAXBElement<TDefinitions> def = ofwasl.createDefinitions(wsdl);
    JAXBElement<TDeployment> d = ofdd.createDeploy(dd);

    String bpelFilename = "BPELPROCESS_" + workFlowId + ".bpel";
    String wsdlFilename = TransformConstants.FILENAME_WSDL_PROCESS_NAME_TEMPLATE.replace("?", workFlowId + "");
    String ddFilename = "deploy.xml";

    ZipOutputStream zip_out_stream = new ZipOutputStream(zipOut);

    // Add BPEL to zip
    zip_out_stream.putNextEntry(new ZipEntry(bpelFilename));
    String fileBPEL = th.jaxbObjectToStringWithWorkflowNamespace(of.createProcess(bpel),
            bpel.getTargetNamespace(), TransformationHelper.BPEL_CLASSES);
    zip_out_stream.write(fileBPEL.getBytes());
    zip_out_stream.closeEntry();

    // Add WSDL to zip
    zip_out_stream.putNextEntry(new ZipEntry(wsdlFilename));
    String fileWSDL = th.jaxbObjectToStringWithWorkflowNamespace(def, bpel.getTargetNamespace(),
            TransformationHelper.WSDL_CLASSES);
    zip_out_stream.write(fileWSDL.getBytes());
    zip_out_stream.closeEntry();

    // Add Deployment Descriptor to zip
    zip_out_stream.putNextEntry(new ZipEntry(ddFilename));
    String fileDD = th.jaxbObjectToStringWithWorkflowNamespace(d, bpel.getTargetNamespace(),
            TransformationHelper.DD_CLASSES);
    zip_out_stream.write(fileDD.getBytes());
    zip_out_stream.closeEntry();

    // Add the EMail WSDL to package and modify the service endpoint
    zip_out_stream.putNextEntry(new ZipEntry(TransformConstants.FILENAME_WSDL_EMAIL));
    zip_out_stream.write(getEmailWsdl(
            URLGenerator.getEmailWSUrl(serverMap.get(ServerTypeEnum.Ode.toString()).get(0).getLocation())));
    zip_out_stream.closeEntry();

    // Add the HT WSDL to package and modify the service endpoint
    zip_out_stream.putNextEntry(new ZipEntry(TransformConstants.FILENAME_WSDL_HUMANTASK));
    zip_out_stream.write(getHTWsdl(
            URLGenerator.getHumanTaskWSUrl(serverMap.get(ServerTypeEnum.Ode.toString()).get(0).getLocation())));
    zip_out_stream.closeEntry();

    // Add the PS WSDL to package and modify the service endpoint
    zip_out_stream.putNextEntry(new ZipEntry(TransformConstants.FILENAME_WSDL_PROXY));
    zip_out_stream.write(getPSWsdl(URLGenerator
            .getProxyServiceWSUrl(serverMap.get(ServerTypeEnum.Ode.toString()).get(0).getLocation())));
    zip_out_stream.closeEntry();

    // Add DecidrTypes schema to package
    zip_out_stream.putNextEntry(new ZipEntry(TransformConstants.FILENAME_XSD_DECIDR_TYPES));
    zip_out_stream.write(loadSchema(TransformConstants.FILENAME_XSD_DECIDR_TYPES));
    zip_out_stream.closeEntry();

    zip_out_stream.close();
    return zipOut.toByteArray();

}

From source file:com.healthcit.analytics.servlet.DataExportServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String token = request.getParameter("token");
    TOKENS_MAP.put(token, DownloadStatus.STARTED);
    String keys = request.getParameter("keys");
    if (keys != null) {
        //JSONArray ownerIdsJSON = (JSONArray)JSONSerializer.toJSON(ownerIds ) ;
        String[] ownerIdsArray = StringUtils.split(keys, ",");

        response.setContentType(Constants.JSON_CONTENT_TYPE);
        response.addHeader(Constants.CONTENT_DISPOSITION, "attachment; filename=dataExport.zip");
        response.addHeader(Constants.PRAGMA_HEADER, Constants.NO_CACHE);

        response.setHeader(Constants.CACHE_CONTROL_HEADER, Constants.NO_CACHE);
        ServletOutputStream os = response.getOutputStream();
        ZipOutputStream zos = new ZipOutputStream(os);
        //         ZipEntry entry = new ZipEntry("dataExport."+OutputFormat.JSON.toString().toLowerCase());
        ZipEntry entry = new ZipEntry("dataExport." + OutputFormat.XML.toString().toLowerCase());
        zos.putNextEntry(entry);//from w  w w  .j  a  v a  2 s.  c o m
        //         OwnerDataManager ownerManager = new OwnerDataManager(OutputFormat.JSON);
        OwnerDataManager ownerManager = new OwnerDataManager(OutputFormat.XML);
        try {
            ownerManager.getEntitiesData(ownerIdsArray, zos);
            TOKENS_MAP.put(token, DownloadStatus.FINISHED);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            TOKENS_MAP.put(token, DownloadStatus.ERROR);
        } finally {
            zos.close();
            //            os.flush();

            //            os.close();
        }
    } else {
        TOKENS_MAP.put(token, DownloadStatus.ERROR);
    }
}

From source file:com.openkm.misc.ZipTest.java

public void testJava() throws IOException {
    log.debug("testJava()");
    File zip = File.createTempFile("java_", ".zip");

    // Create zip
    FileOutputStream fos = new FileOutputStream(zip);
    ZipOutputStream zos = new ZipOutputStream(fos);
    zos.putNextEntry(new ZipEntry("coeta"));
    zos.closeEntry();/*  ww  w  . j a v  a 2s  .c  o m*/
    zos.close();

    // Read zip
    FileInputStream fis = new FileInputStream(zip);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry ze = zis.getNextEntry();
    System.out.println(ze.getName());
    assertEquals(ze.getName(), "coeta");
    zis.close();
}