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:ZipTransformTest.java

public void testByteArrayTransformerInStream() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file1 = File.createTempFile("temp", null);
    File file2 = File.createTempFile("temp", null);
    try {// w  ww .j  ava 2 s.  c  o m
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(file1);
            out = new FileOutputStream(file2);

            ZipUtil.transformEntry(in, name, new ByteArrayZipEntryTransformer() {
                protected byte[] transform(ZipEntry zipEntry, byte[] input) throws IOException {
                    String s = new String(input);
                    assertEquals(new String(contents), s);
                    return s.toUpperCase().getBytes();
                }
            }, out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file2, name);
        assertNotNull(actual);
        assertEquals(new String(contents).toUpperCase(), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
        FileUtils.deleteQuietly(file2);
    }
}

From source file:ZipTransformTest.java

public void testFileZipEntryTransformerInStream() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file1 = File.createTempFile("temp", null);
    File file2 = File.createTempFile("temp", null);
    try {/* w w w  .jav a  2  s .c o m*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file1));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Transform the ZIP file
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(file1);
            out = new FileOutputStream(file2);

            ZipUtil.transformEntry(in, name, new FileZipEntryTransformer() {
                protected void transform(ZipEntry zipEntry, File in, File out) throws IOException {
                    FileWriter fw = new FileWriter(out);
                    fw.write("CAFEBABE");
                    fw.close();
                }
            }, out);
        } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(out);
        }

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file2, name);
        assertNotNull(actual);
        assertEquals("CAFEBABE", new String(actual));
    } finally {
        FileUtils.deleteQuietly(file1);
        FileUtils.deleteQuietly(file2);
    }
}

From source file:nl.mpi.tg.eg.frinex.rest.CsvController.java

private void addToZipArchive(final ZipOutputStream zipStream, String fileName, byte[] content)
        throws IOException {
    ZipEntry zipEntry = new ZipEntry(fileName);
    zipStream.putNextEntry(zipEntry);//from   w ww.ja v a 2s. c o m
    zipStream.write(content);
    zipStream.closeEntry();
}

From source file:org.dicen.recolnat.services.core.data.SetResource.java

/**
 * Creates a zip file in the Colaboratory's downloads directory containing the
 * images of a Set.// w  w  w.java2s.  com
 *
 * @param setId UID of the Set to export/download.
 * @param user Login of the user
 * @throws AccessForbiddenException
 */
public static void prepareDownload(String setId, String user) throws AccessForbiddenException {
    // Get set data, download images
    boolean retry = true;
    List<File> images = new LinkedList<>();
    String setName = "";
    String uuid = UUID.randomUUID().toString();
    String tempDirPath = Configuration.Exports.DIRECTORY + "/" + uuid + "/";
    File temporaryDirectory = new File(tempDirPath);
    temporaryDirectory.mkdir();

    while (retry) {
        retry = false;
        OrientBaseGraph g = DatabaseAccess.getReadOnlyGraph();
        try {
            OrientVertex vUser = AccessUtils.getUserByLogin(user, g);
            OrientVertex vSet = AccessUtils.getSet(setId, g);
            if (!AccessRights.canRead(vUser, vSet, g, DatabaseAccess.rightsDb)) {
                throw new AccessForbiddenException(user, setId);
            }
            Iterator<Vertex> itItems = vSet.getVertices(Direction.OUT, DataModel.Links.containsItem).iterator();
            while (itItems.hasNext()) {
                SetResource.getImagesOfItem((OrientVertex) itItems.next(), images, tempDirPath, vUser, g);
            }
            setName = vSet.getProperty(DataModel.Properties.name);
        } catch (OConcurrentModificationException e) {
            log.warn("Database busy, retrying operation");
            retry = true;
        } finally {
            g.rollback();
            g.shutdown();
        }
    }

    if (!images.isEmpty()) {
        String zipFileName = Configuration.Exports.DIRECTORY + "/" + user + "-" + setName + "-"
                + DateFormatUtils.export.format(new Date()) + ".zip";
        File zipFile = new File(zipFileName);

        try {
            zipFile.createNewFile();
            ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));

            final int BUFFER = 2048;
            byte data[] = new byte[BUFFER];

            for (File f : images) {
                log.info("Compressing " + f.getName());
                FileInputStream fis = new FileInputStream(f);
                ZipEntry entry = new ZipEntry(f.getName());
                zos.putNextEntry(entry);
                int count = 0;
                while ((count = fis.read(data)) != -1) {
                    //            log.info("Compressed " + count);
                    zos.write(data);
                }
                zos.closeEntry();
                fis.close();
                f.delete();
            }
            zos.close();
        } catch (ZipException ex) {
            log.error("Error creating zip file " + zipFileName, ex);
            return;
        } catch (FileNotFoundException ex) {
            log.error("Destination zip file not created " + zipFileName, ex);
            return;
        } catch (IOException ex) {
            log.error("Error with file " + zipFileName, ex);
            return;
        }

        temporaryDirectory.delete();

        // Add file to list of stuff ready to export
        DatabaseAccess.exportsDb.addUserExport(user, zipFile.getName(), zipFile.getName());
        if (log.isDebugEnabled()) {
            log.debug("Preparation finished");
        }
    }
}

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

/**
 * Zips the article contents from specified date and writes the resulting
 * zip-File to the ZipOutputStream./*from w  w w. j a  va  2 s . co  m*/
 * 
 * @created 22.04.2013
 * @param date
 * @param zos
 * @throws IOException
 */
private void zipRev(Date date, ZipOutputStream zos, UserActionContext context) throws IOException {
    RevisionManager revm = RevisionManager.getRM(context);
    ArticleManager am = revm.getArticleManager(date);
    Collection<Article> articles = am.getArticles();
    for (Article article : articles) {
        zos.putNextEntry(new ZipEntry(URLEncoder.encode(article.getTitle() + ".txt", "UTF-8")));
        zos.write(article.getRootSection().getText().getBytes("UTF-8"));
        zos.closeEntry();

        // Attachments
        Collection<WikiAttachment> atts = Environment.getInstance().getWikiConnector()
                .getAttachments(article.getTitle());
        for (WikiAttachment att : atts) {
            zos.putNextEntry(new ZipEntry(URLEncoder.encode(att.getParentName(), "UTF-8") + "-att/"
                    + URLEncoder.encode(att.getFileName(), "UTF-8")));
            IOUtils.copy(att.getInputStream(), zos);
            zos.closeEntry();
        }
    }
    zos.close();
}

From source file:com.jd.survey.web.reports.ReportController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "spss", produces = "text/html")
public void surveySPSSExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {//from   w ww . j a v  a 2s . com
        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../accessDenied");
            //throw new AccessDeniedException("Unauthorized access attempt");
        }

        String metadataFileName = "survey" + surveyDefinitionId + ".sps";
        String dataFileName = "survey" + surveyDefinitionId + ".dat";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipfile = new ZipOutputStream(baos);

        //metadata    
        zipfile.putNextEntry(new ZipEntry(metadataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSMetadata(surveyDefinitionId, dataFileName));
        //data
        zipfile.putNextEntry(new ZipEntry(dataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSData(surveyDefinitionId));
        zipfile.close();

        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinitionId + "_spss.zip");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.write(baos.toByteArray());
        servletOutputStream.flush();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:de.unisaarland.swan.export.ExportUtil.java

private void createZipEntry(File file, ZipOutputStream zos) throws IOException {
    zos.putNextEntry(new ZipEntry(file.getName()));
    zos.write(FileUtils.readFileToByteArray(file));
    zos.closeEntry();/*w  w  w . j a va2s .c  o  m*/
}

From source file:gov.nasa.ensemble.resources.ResourceUtil.java

public static void zipContainer(final IContainer container, final OutputStream os,
        final IProgressMonitor monitor) throws CoreException {
    final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(os));
    container.refreshLocal(IResource.DEPTH_INFINITE, monitor);
    // monitor.beginTask("Zipping " + container.getName(), container.get);
    container.accept(new IResourceVisitor() {
        @Override//  w w w. j a  va 2  s.  com
        public boolean visit(IResource resource) throws CoreException {
            // MSLICE-1258
            for (IProjectPublishFilter filter : publishFilters)
                if (!filter.shouldInclude(resource))
                    return true;

            if (resource instanceof IFile) {
                final IFile file = (IFile) resource;
                final IPath relativePath = ResourceUtil.getRelativePath(container, file).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString());
                try {
                    out.putNextEntry(entry);
                    out.write(ResourceUtil.getContents(file));
                    out.closeEntry();
                } catch (IOException e) {
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to write contents of " + file.getName(), e));
                }
            } else if (resource instanceof IFolder) {
                final IFolder folder = (IFolder) resource;
                if (folder.members().length > 0)
                    return true;
                final IPath relativePath = ResourceUtil.getRelativePath(container, folder).some();
                final ZipEntry entry = new ZipEntry(relativePath.toString() + "/");
                try {
                    out.putNextEntry(entry);
                    out.closeEntry();
                } catch (IOException e) {
                    LogUtil.error(e);
                    throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                            "Failed to compress directory " + folder.getName(), e));
                }
            }
            return true;
        }
    });
    try {
        out.close();
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, EnsembleResourcesPlugin.PLUGIN_ID,
                "Failed to close output stream", e));
    }
}

From source file:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java

@Test
public void shouldReloadIfChanged() throws Exception {
    File file = this.zip.getFile("a/b/c.txt");
    assertThat(file.getContent().asString(), is("c"));
    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(this.zipFile));
    try {//  ww w  . j av a 2  s. c  o m
        zipOutputStream.putNextEntry(new ZipEntry("/a/b/c.txt"));
        zipOutputStream.write("c2".getBytes());
    } finally {
        zipOutputStream.close();
    }
    assertThat(file.getContent().asString(), is("c2"));
}

From source file:se.crisp.codekvast.agent.daemon.worker.impl.ZipFileDataExporterImpl.java

private void doExportMetaInfo(ZipOutputStream zip, Charset charset, ExportFileMetaInfo metaInfo)
        throws IOException, IllegalAccessException {
    zip.putNextEntry(ExportFileEntry.META_INFO.toZipEntry());

    Set<String> lines = new TreeSet<>();
    FileUtils.extractFieldValuesFrom(metaInfo, lines);
    for (String line : lines) {
        zip.write(line.getBytes(charset));
        zip.write('\n');
    }//from  w w w  .j  a va2s  . com
    zip.closeEntry();
}