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.intuit.tank.service.impl.v1.agent.AgentServiceV1.java

@Override
@Nonnull/* ww w . ja  v  a2  s  .  c  om*/
public Response getSupportFiles() {
    ResponseBuilder responseBuilder = Response.ok();
    // AuthUtil.checkLoggedIn(servletContext);
    final FileStorage fileStorage = FileStorageFactory.getFileStorage(new TankConfig().getJarDir(), false);

    final File harnessJar = new File(servletContext.getRealPath("/tools/" + HARNESS_JAR));
    LOG.info("harnessJar = " + harnessJar.getAbsolutePath());
    final List<FileData> files = fileStorage.listFileData("");

    StreamingOutput streamingOutput = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            ZipOutputStream zip = new ZipOutputStream(output);
            try {
                boolean harnessJarExists = harnessJar.exists();
                if (harnessJarExists) {
                    addFileToZip(HARNESS_JAR, new FileInputStream(harnessJar), zip);
                    zip.flush();
                }
                for (FileData fileData : files) {
                    if (harnessJarExists && fileData.getFileName().equals(HARNESS_JAR)) {
                        LOG.info("Not adding harness because we found it in the war.");
                    } else {
                        addFileToZip(fileData.getFileName(), fileStorage.readFileData(fileData), zip);
                        zip.flush();
                    }
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(zip);
            }
        }
    };
    String filename = "agent-support-files.zip";
    responseBuilder.header("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    responseBuilder.entity(streamingOutput);
    return responseBuilder.build();
}

From source file:mediathek.controller.IoXmlSchreiben.java

private void xmlSchreibenStart() throws IOException, XMLStreamException {
    Log.systemMeldung("Start Schreiben nach: " + xmlFilePath.toAbsolutePath());
    final OutputStream outputStream = Files.newOutputStream(xmlFilePath);
    if (xmlFilePath.endsWith(GuiKonstanten.FORMAT_BZ2)) {
        bZip2CompressorOutputStream = new BZip2CompressorOutputStream(outputStream, 2);
        out = new OutputStreamWriter(bZip2CompressorOutputStream, Konstanten.KODIERUNG_UTF);
    } else if (xmlFilePath.endsWith(GuiKonstanten.FORMAT_ZIP)) {
        zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry entry = new ZipEntry(Konstanten.PROGRAMMNAME);
        zipOutputStream.putNextEntry(entry);
        out = new OutputStreamWriter(zipOutputStream, Konstanten.KODIERUNG_UTF);
    } else {//from  w  ww .j  a  v  a 2 s  .com
        out = new OutputStreamWriter(outputStream, Konstanten.KODIERUNG_UTF);
    }

    XMLOutputFactory outFactory = XMLOutputFactory.newInstance();
    writer = outFactory.createXMLStreamWriter(out);
    writer.writeStartDocument(Konstanten.KODIERUNG_UTF, "1.0");
    writer.writeCharacters("\n");//neue Zeile
    writer.writeStartElement(Konstanten.XML_START);
    writer.writeCharacters("\n");//neue Zeile
}

From source file:com.bstek.dorado.web.resolver.AbstractWebFileResolver.java

protected OutputStream getOutputStream(HttpServletRequest request, HttpServletResponse response,
        ResourcesWrapper resourcesWrapper) throws IOException {
    int encodingType = 0;
    String encoding = request.getHeader(HttpConstants.ACCEPT_ENCODING);
    if (encoding != null) {
        encodingType = (encoding.indexOf(HttpConstants.GZIP) >= 0) ? 1
                : (encoding.indexOf(HttpConstants.COMPRESS) >= 0 ? 2 : 0);
    }// w w  w  .j  a  v  a2  s. c om

    OutputStream out = response.getOutputStream();
    if (encodingType > 0 && shouldCompress(resourcesWrapper)) {
        try {
            if (encodingType == 1) {
                response.setHeader(HttpConstants.CONTENT_ENCODING, HttpConstants.GZIP);
                out = new GZIPOutputStream(out);
            } else if (encodingType == 2) {
                response.setHeader(HttpConstants.CONTENT_ENCODING, HttpConstants.COMPRESS);
                out = new ZipOutputStream(out);
            }
        } catch (IOException e) {
            // do nothing
        }
    }
    return out;
}

From source file:net.sourceforge.jweb.maven.mojo.PropertiesOverideMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled) {
        this.getLog().info("plugin was disabled");
        return;//  w ww .j  a v  a2 s . c  o m
    }
    processConfiguration();
    if (replacements.isEmpty()) {
        this.getLog().info("Nothing to replace with");
        return;
    }

    String name = this.builddir.getAbsolutePath() + File.separator + this.finalName + "." + this.packing;//the final package
    this.getLog().debug("final artifact: " + name);// the final package

    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
            return;
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (acceptMime(entry)) {
                getLog().info("applying replacements for " + entry.getName());
                InputStream inputStream = zipFile.getInputStream(entry);
                String src = IOUtils.toString(inputStream, encoding);
                //do replacement
                for (Entry<String, String> e : replacements.entrySet()) {
                    src = src.replaceAll("#\\{" + e.getKey() + "}", e.getValue());
                }
                out.putNextEntry(new ZipEntry(entry.getName()));
                IOUtils.write(src, out, encoding);
                inputStream.close();
            } else {
                //not repalce, just put entry back to out zip
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }
        }
        zipFile.close();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.ephesoft.gxt.batchinstance.server.LogFileDownloadServlet.java

@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    LOGGER.info("Downloading the log files.");
    final String batchInstanceIdentifier = request.getParameter(BatchInfoConstants.BATCH_INSTANCE_IDENTIFIER);
    final String batchInstanceLogFilePath = request.getParameter(BatchInfoConstants.BI_LOG_FILE_PATH);
    LOGGER.debug("Batch Instance Identifier is : ", batchInstanceIdentifier);
    LOGGER.debug("Batch Instance log file path is : ", batchInstanceLogFilePath);

    if (EphesoftStringUtil.isNullOrEmpty(batchInstanceIdentifier)
            || EphesoftStringUtil.isNullOrEmpty(batchInstanceLogFilePath)) {
        LOGGER.error("Either the batch instance identifier or batch instance log file path is null.");
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error occured in downloading.");
    } else {/*  ww  w  . j  av a 2  s . c o  m*/
        final String zipFileName = EphesoftStringUtil.concatenate(batchInstanceIdentifier,
                BatchInfoConstants.UNDER_SCORE, BatchInfoConstants.LOG_FOLDER);
        LOGGER.debug("Zip File Name is ", zipFileName);
        response.setContentType(BatchInfoConstants.APPLICATION_ZIP);
        final String downloadedFile = EphesoftStringUtil.concatenate(zipFileName, BatchInfoConstants.ZIP_EXT,
                "\"\r\n");
        response.setHeader(BatchInfoConstants.CONTENT_DISPOSITION, "attachment; filename=\"" + downloadedFile);
        LOGGER.debug("File path is ", batchInstanceLogFilePath);
        File file = new File(batchInstanceLogFilePath);
        if (file.exists()) {
            ServletOutputStream out = null;
            ZipOutputStream zout = null;
            try {
                out = response.getOutputStream();
                zout = new ZipOutputStream(out);
                FileUtils.zipMultipleFiles(batchInstanceLogFilePath, zout, downloadedFile);
                response.setStatus(HttpServletResponse.SC_OK);
            } catch (IOException ioException) {
                LOGGER.error(ioException, "Unable to download the files.");
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Error occured in downloading.");
            } finally {
                IOUtils.closeQuietly(zout);
                IOUtils.closeQuietly(out);
            }
        } else {
            throw new IOException("Error Occurred in download log file because no log file exists.");
        }
    }
}

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.
 * /*from   ww w .  j  av a2  s . co  m*/
 * @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:com.castlemock.web.basis.web.mvc.controller.project.ProjectsOverviewController.java

/**
 * The method provides the functionality to update, delete and export projects. It bases the requested functionality based
 * on the provided action./*from w w  w .  j  av  a 2  s .  co  m*/
 * @param action The action is used to determined which action/functionality the perform.
 * @param projectModifierCommand The project overview command contains which ids going to be updated, deleted or exported.
 * @param response The HTTP servlet response
 * @return The model depending in which action was requested.
 */
@PreAuthorize("hasAuthority('READER') or hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView projectFunctionality(@RequestParam String action,
        @ModelAttribute ProjectModifierCommand projectModifierCommand, HttpServletResponse response) {
    LOGGER.debug("Project action requested: " + action);
    if (EXPORT_PROJECTS.equalsIgnoreCase(action)) {
        if (projectModifierCommand.getProjects().length == 0) {
            return redirect();
        }

        ZipOutputStream zipOutputStream = null;
        InputStream inputStream = null;
        final String outputFilename = tempFilesFolder + SLASH + "exported-projects-" + new Date().getTime()
                + ".zip";
        try {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(outputFilename));
            for (String project : projectModifierCommand.getProjects()) {
                final String[] projectData = project.split(SLASH);
                if (projectData.length != 2) {
                    continue;
                }

                final String projectTypeUrl = projectData[0];
                final String projectId = projectData[1];
                final String exportedProject = projectServiceFacade.exportProject(projectTypeUrl, projectId);
                final byte[] data = exportedProject.getBytes();
                final String filename = "exported-project-" + projectTypeUrl + "-" + projectId + ".xml";
                zipOutputStream.putNextEntry(new ZipEntry(filename));
                zipOutputStream.write(data, 0, data.length);
                zipOutputStream.closeEntry();
            }
            zipOutputStream.close();

            inputStream = new FileInputStream(outputFilename);
            IOUtils.copy(inputStream, response.getOutputStream());

            response.setContentType("application/zip");
            response.flushBuffer();
            return null;
        } catch (IOException exception) {
            LOGGER.error("Unable to export multiple projects and zip them", exception);
        } finally {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the zip output stream", exception);
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the input stream", exception);
                }
            }
            fileManager.deleteUploadedFile(outputFilename);
        }
    } else if (DELETE_PROJECTS.equalsIgnoreCase(action)) {
        List<ProjectDto> projects = new LinkedList<ProjectDto>();
        for (String project : projectModifierCommand.getProjects()) {
            final String[] projectData = project.split(SLASH);

            if (projectData.length != 2) {
                continue;
            }

            final String projectTypeUrl = projectData[0];
            final String projectId = projectData[1];
            final ProjectDto projectDto = projectServiceFacade.findOne(projectTypeUrl, projectId);
            projects.add(projectDto);
        }
        ModelAndView model = createPartialModelAndView(DELETE_PROJECTS_PAGE);
        model.addObject(PROJECTS, projects);
        model.addObject(DELETE_PROJECTS_COMMAND, new DeleteProjectsCommand());
        return model;
    }

    return redirect();
}

From source file:org.openmrs.module.omodexport.util.OmodExportUtil.java

/**
 * Utility method for exporting a set of selected modules. The select modules will be exported
 * in zip file called "modules.zip"/*from   w  ww .  ja va  2  s. c  o  m*/
 * 
 * @param moduleId -Dash-separated list of the module Ids
 * @param response
 * @throws IOException
 */
public static void exportSelectedModules(String moduleId, HttpServletResponse response) throws IOException {
    // Split the id string into an array of id's
    String[] moduleIds = moduleId.split("-");
    List<File> files = new ArrayList<File>();
    for (String mId : moduleIds) {
        Module m = ModuleFactory.getModuleById(mId);
        files.add(m.getFile());
    }
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=\"modules.ZIP\"");

    ZipOutputStream out = new ZipOutputStream(response.getOutputStream());

    zipFiles(files, out);
}

From source file:com.boundlessgeo.geoserver.bundle.BundleExporter.java

/**
 * Packages up the export as a zip file.
 *
 * @return The path pointing to the zip file.
 *///from   www .ja  v  a2  s.co m
public Path zip() throws IOException {
    Path zip = temp.resolve(options.name() + ".zip");
    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(zip.toFile()));) {
        ZipOutputStream zout = new ZipOutputStream(out);
        try {
            IOUtils.zipDirectory(root().toFile(), zout, null);
        } finally {
            zout.flush();
            zout.close();
            out.flush();
        }
    }
    return zip;
}

From source file:csns.web.controller.DownloadController.java

@RequestMapping(value = "/download", params = "submissionId")
public String downloadSubmissionFiles(@RequestParam Long submissionId, HttpServletResponse response,
        ModelMap models) throws IOException {
    Submission submission = submissionDao.getSubmission(submissionId);
    String name = submission.getAssignment().getAlias().replace(replaceRegex, "_");

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

    ZipOutputStream zip = new ZipOutputStream(response.getOutputStream());
    addToZip(zip, name, submission.getFiles());
    zip.close();//from w w  w  .j a  v a  2s.  c  om
    return null;
}