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.esofthead.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java

@Override
public InputStream getStream() {
    if (resources.size() == 1) {
        Resource res = resources.iterator().next();
        if (res.isExternalResource()) {
            ExternalResourceService service = ResourceUtils
                    .getExternalResourceService(ResourceUtils.getType(res));
            return service.download(ResourceUtils.getExternalDrive(res), res.getPath());
        } else {/*from ww w .j a v  a 2  s. co m*/
            return resourceService.getContentStream(res.getPath());
        }
    }

    final PipedInputStream inStream = new PipedInputStream();
    final PipedOutputStream outStream;

    try {
        outStream = new PipedOutputStream(inStream);
    } catch (IOException ex) {
        LOG.error("Can not create outstream file", ex);
        return null;
    }

    Thread threadExport = new MyCollabThread(new Runnable() {

        @Override
        public void run() {
            try {
                ZipOutputStream zipOutStream = new ZipOutputStream(outStream);
                zipResource(zipOutStream, resources);
                zipOutStream.close();
                outStream.close();
            } catch (Exception e) {
                LOG.error("Error while saving content stream", e);
            }
        }
    });

    threadExport.start();

    return inStream;
}

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;/*from www .j ava2  s . 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.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.solidmaps.webapp.service.ApostilamentosServiceImpl.java

private FileSystemResource generateZip(CompanyEntity companyEntity) {

    String fileName = FILE_PATH + "Apostilamento-" + companyEntity.getCnpj() + ".zip";
    FileOutputStream fos = null;//from  ww  w .  j  av a2s . com

    try {

        fos = new FileOutputStream(fileName);
        ZipOutputStream zos = new ZipOutputStream(fos);
        this.addToZip(zos, fileFederal);
        this.addToZip(zos, fileCivil);
        this.addToZip(zos, fileExercito);

        zos.closeEntry();
        zos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    FileSystemResource fileSystemResource = new FileSystemResource(fileName);

    return fileSystemResource;
}

From source file:fr.cirad.mgdb.exporting.markeroriented.BEDExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs,
        ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms,
        int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    ZipOutputStream zos = new ZipOutputStream(outputStream);

    if (readyToExportFiles != null)
        for (String readyToExportFile : readyToExportFiles.keySet()) {
            zos.putNextEntry(new ZipEntry(readyToExportFile));
            InputStream inputStream = readyToExportFiles.get(readyToExportFile);
            byte[] dataBlock = new byte[1024];
            int count = inputStream.read(dataBlock, 0, 1024);
            while (count != -1) {
                zos.write(dataBlock, 0, count);
                count = inputStream.read(dataBlock, 0, 1024);
            }/*w ww  . ja va 2s  .  co  m*/
        }

    int markerCount = markerCursor.count();

    List<String> selectedIndividualList = new ArrayList<String>();
    for (Individual ind : getIndividualsFromSamples(sModule, sampleIDs))
        selectedIndividualList.add(ind.getId());

    String exportName = sModule + "_" + markerCount + "variants_" + selectedIndividualList.size()
            + "individuals";
    zos.putNextEntry(new ZipEntry(exportName + ".bed"));

    short nProgress = 0, nPreviousProgress = 0;
    int nChunkSize = Math.min(2000, markerCount), nLoadedMarkerCount = 0;
    while (markerCursor.hasNext()) {
        int nLoadedMarkerCountInLoop = 0;
        Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>();
        boolean fStartingNewChunk = true;
        markerCursor.batchSize(nChunkSize);
        while (markerCursor.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) {
            DBObject exportVariant = markerCursor.next();
            DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
            markerChromosomalPositions.put((Comparable) exportVariant.get("_id"),
                    refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":"
                            + refPos.get(ReferencePosition.FIELDNAME_START_SITE));
            nLoadedMarkerCountInLoop++;
            fStartingNewChunk = false;
        }

        for (Comparable variantId : markerChromosomalPositions.keySet()) // read data and write results into temporary files (one per sample)
        {
            String[] chromAndPos = markerChromosomalPositions.get(variantId).split(":");
            zos.write((chromAndPos[0] + "\t" + (Long.parseLong(chromAndPos[1]) - 1) + "\t"
                    + (Long.parseLong(chromAndPos[1]) - 1) + "\t" + variantId + "\t" + "0" + "\t" + "+")
                            .getBytes());
            zos.write((LINE_SEPARATOR).getBytes());
        }

        if (progress.hasAborted())
            return;

        nLoadedMarkerCount += nLoadedMarkerCountInLoop;
        nProgress = (short) (nLoadedMarkerCount * 100 / markerCount);
        if (nProgress > nPreviousProgress) {
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }
    }

    zos.close();
    progress.setCurrentStepProgress((short) 100);
}

From source file:info.servertools.core.util.FileUtils.java

public static void zipDirectory(File directory, File zipfile, @Nullable Collection<String> fileBlacklist,
        @Nullable Collection<String> folderBlacklist) throws IOException {
    URI baseDir = directory.toURI();
    Deque<File> queue = new LinkedList<>();
    queue.push(directory);//w w  w. j  a v  a 2 s. c  o  m
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = out;
    try {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty()) {
            directory = queue.removeFirst();
            File[] dirFiles = directory.listFiles();
            if (dirFiles != null && dirFiles.length != 0) {
                for (File child : dirFiles) {
                    if (child != null) {
                        String name = baseDir.relativize(child.toURI()).getPath();
                        if (child.isDirectory()
                                && (folderBlacklist == null || !folderBlacklist.contains(child.getName()))) {
                            queue.push(child);
                            name = name.endsWith("/") ? name : name + "/";
                            zout.putNextEntry(new ZipEntry(name));
                        } else {
                            if (fileBlacklist != null && !fileBlacklist.contains(child.getName())) {
                                zout.putNextEntry(new ZipEntry(name));
                                copy(child, zout);
                                zout.closeEntry();
                            }
                        }
                    }
                }
            }
        }
    } finally {
        res.close();
    }
}

From source file:be.fedict.eid.dss.sp.servlet.UploadServlet.java

@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOG.debug("doPost");

    String fileName = null;//  w w w .  j a v a 2 s  .  c  o  m
    String contentType;
    byte[] document = null;

    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        if (!items.isEmpty()) {
            fileName = items.get(0).getName();
            // contentType = items.get(0).getContentType();
            document = items.get(0).get();
        }
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    String extension = FilenameUtils.getExtension(fileName).toLowerCase();
    contentType = supportedFileExtensions.get(extension);
    if (null == contentType) {
        /*
         * Unsupported content-type is converted to a ZIP container.
         */
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(zipEntry);
        IOUtils.write(document, zipOutputStream);
        zipOutputStream.close();
        fileName = FilenameUtils.getBaseName(fileName) + ".zip";
        document = outputStream.toByteArray();
        contentType = "application/zip";
    }

    LOG.debug("File name: " + fileName);
    LOG.debug("Content Type: " + contentType);

    String signatureRequest = new String(Base64.encode(document));

    request.getSession().setAttribute(DOCUMENT_SESSION_ATTRIBUTE, document);
    request.getSession().setAttribute("SignatureRequest", signatureRequest);
    request.getSession().setAttribute("ContentType", contentType);

    response.sendRedirect(request.getContextPath() + this.postPage);
}

From source file:azkaban.utils.Utils.java

public static void zipFolderContent(File folder, File output) throws IOException {
    FileOutputStream out = new FileOutputStream(output);
    ZipOutputStream zOut = new ZipOutputStream(out);
    try {//from  w  ww. j a v  a2 s . com
        File[] files = folder.listFiles();
        if (files != null) {
            for (File f : files) {
                zipFile("", f, zOut);
            }
        }
    } finally {
        zOut.close();
    }
}

From source file:de.mpg.imeji.logic.export.format.ZIPExport.java

/**
 * This method exports all images of the current browse page as a zip file
 * /*from  w ww . j  a  v  a 2s  .  c o  m*/
 * @throws Exception
 * @throws URISyntaxException
 */
public void exportAllImages(SearchResult sr, OutputStream out) throws URISyntaxException, Exception {
    List<String> source = sr.getResults();
    ZipOutputStream zip = new ZipOutputStream(out);
    try {
        // Create the ZIP file
        for (int i = 0; i < source.size(); i++) {
            SessionBean session = (SessionBean) BeanHelper.getSessionBean(SessionBean.class);
            ItemController ic = new ItemController(session.getUser());
            Item item = ic.retrieve(new URI(source.get(i)));
            StorageController sc = new StorageController();
            try {
                zip.putNextEntry(new ZipEntry(item.getFilename()));
                sc.read(item.getFullImageUrl().toString(), zip, false);
                // Complete the entry
                zip.closeEntry();
            } catch (ZipException ze) {
                if (ze.getMessage().contains("duplicate entry")) {
                    String name = i + "_" + item.getFilename();
                    zip.putNextEntry(new ZipEntry(name));
                    sc.read(item.getFullImageUrl().toString(), zip, false);
                    // Complete the entry
                    zip.closeEntry();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // Complete the ZIP file
        zip.close();
    }
}

From source file:io.lavagna.service.LavagnaExporter.java

public void exportData(OutputStream os) throws IOException {
    try (ZipOutputStream zf = new ZipOutputStream(os);
            OutputStreamWriter osw = new OutputStreamWriter(zf, StandardCharsets.UTF_8)) {
        writeEntry("config.json", configurationRepository.findAll(), zf, osw);
        writeEntry("users.json", userRepository.findAll(), zf, osw);
        writeEntry("permissions.json", permissionService.findAllRolesAndRelatedPermissionWithUsers(), zf, osw);

        exportFiles(zf, osw);/*from   ww w.  ja  v a  2  s  .c  om*/

        for (Project p : projectService.findAll()) {
            exportProject(zf, osw, p);
        }

        //
        final int amountPerPage = 100;
        int pages = (eventRepository.count() + amountPerPage - 1) / amountPerPage;

        writeEntry("events-page-count.json", pages, zf, osw);
        for (int i = 0; i < pages; i++) {
            writeEntry("events-" + i + ".json", toEventFull(eventRepository.find(i * 100, 100)), zf, osw);
        }
        //
        writeEntry("card-data-types-order.json",
                cardDataRepository.findAllByTypes(
                        EnumSet.of(CardType.ACTION_LIST, CardType.ACTION_CHECKED, CardType.ACTION_UNCHECKED)),
                zf, osw);
    }
}