Example usage for java.util.zip ZipEntry ZipEntry

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

Introduction

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

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:com.jaspersoft.jasperserver.export.io.ZipOutput.java

public void mkdir(String path) throws IOException {
    if (directories.add(path)) {
        String zipPath = getZipPath(path);
        ZipEntry dirEntry = new ZipEntry(zipPath + ZIP_ENTRY_DIR_SUFFIX);
        zipOut.putNextEntry(dirEntry);/* w w w.  ja va2  s .  com*/
        zipOut.closeEntry();
    }
}

From source file:it.geosolutions.tools.compress.file.Compressor.java

public static File deflate(final File outputDir, final File zipFile, final File[] files, boolean overwrite) {

    if (zipFile.exists() && overwrite) {
        if (LOGGER.isInfoEnabled())
            LOGGER.info("The output file already exists: " + zipFile + " overvriting");
        return zipFile;
    }// w ww  . j  a  v a  2s . c om

    // Create a buffer for reading the files
    byte[] buf = new byte[Conf.getBufferSize()];

    ZipOutputStream out = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(zipFile);
        bos = new BufferedOutputStream(fos);
        out = new ZipOutputStream(bos);

        // Compress the files
        for (File file : files) {
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                if (file.isDirectory()) {
                    continue;
                } else {
                    // Add ZIP entry to output stream.
                    out.putNextEntry(new ZipEntry(file.getName()));
                    // Transfer bytes from the file to the ZIP file
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.flush();
                }

            } finally {
                try {
                    // Complete the entry
                    out.closeEntry();
                } catch (Exception e) {
                }
                IOUtils.closeQuietly(in);
            }

        }

    } catch (IOException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
        return null;
    } finally {

        // Complete the ZIP file
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(bos);
        IOUtils.closeQuietly(fos);
    }

    return zipFile;
}

From source file:org.messic.server.api.APIPlayLists.java

@Transactional
public void getPlaylistZip(User user, Long playlistSid, OutputStream os)
        throws IOException, SidNotFoundMessicException {
    MDOPlaylist mdoplaylist = daoPlaylist.get(user.getLogin(), playlistSid);
    if (mdoplaylist == null) {
        throw new SidNotFoundMessicException();
    }//from  w w w. j  av  a2s .  co m
    List<MDOSong> desiredSongs = mdoplaylist.getSongs();

    ZipOutputStream zos = new ZipOutputStream(os);
    // level - the compression level (0-9)
    zos.setLevel(9);

    HashMap<String, String> songs = new HashMap<String, String>();

    M3U m3u = new M3U();
    m3u.setExtensionM3U(true);
    List<Resource> resources = m3u.getResources();

    for (MDOSong song : desiredSongs) {
        if (song != null) {

            // add file
            // extract the relative name for entry purpose
            String entryName = song.getLocation();
            if (songs.get(entryName) == null) {
                Resource r = new Resource();
                r.setLocation(song.getLocation());
                r.setName(song.getName());
                resources.add(r);

                songs.put(entryName, "ok");
                // song not repeated
                ZipEntry ze = new ZipEntry(entryName);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(song.calculateAbsolutePath(daoSettings.getSettings()));
                int len;
                byte buffer[] = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
            }
        }
    }

    // the last is the playlist m3u
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        m3u.writeTo(baos, "UTF8");
        // song not repeated
        ZipEntry ze = new ZipEntry(mdoplaylist.getName() + ".m3u");
        zos.putNextEntry(ze);
        byte[] bytes = baos.toByteArray();
        zos.write(bytes, 0, bytes.length);
        zos.closeEntry();
    } catch (Exception e) {
        e.printStackTrace();
    }

    zos.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;/*from  www.  ja 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:eionet.gdem.utils.ZipUtil.java

/**
 *
 * @param f/*from  w ww . j av a  2 s  . c om*/
 *            - File that will be zipped
 * @param outZip
 *            - ZipOutputStream represents the zip file, where the files will be placed
 * @param sourceDir
 *            - root directory, where the zipping started
 * @param doCompress
 *            - don't comress the file, if doCompress=true
 * @throws IOException If an error occurs.
 */
public static void zipFile(File f, ZipOutputStream outZip, String sourceDir, boolean doCompress)
        throws IOException {

    // Read the source file into byte array
    byte[] fileBytes = Utils.getBytesFromFile(f);

    // create a new zip entry
    String strAbsPath = f.getPath();
    String strZipEntryName = strAbsPath.substring(sourceDir.length() + 1, strAbsPath.length());
    strZipEntryName = Utils.Replace(strZipEntryName, File.separator, "/");
    ZipEntry anEntry = new ZipEntry(strZipEntryName);

    // Don't compress the file, if not needed
    if (!doCompress) {
        // ZipEntry can't calculate crc size automatically, if we use STORED method.
        anEntry.setMethod(ZipEntry.STORED);
        anEntry.setSize(fileBytes.length);
        CRC32 crc321 = new CRC32();
        crc321.update(fileBytes);
        anEntry.setCrc(crc321.getValue());
    }
    // place the zip entry in the ZipOutputStream object
    outZip.putNextEntry(anEntry);

    // now write the content of the file to the ZipOutputStream
    outZip.write(fileBytes);

    outZip.flush();
    // Close the current entry
    outZip.closeEntry();

}

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  w w  .j  av a 2  s.c o 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: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.ja  v  a  2  s  . c o m*/
 *
 * @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:com.controlj.green.modstat.work.ModstatWork.java

@Override
public void run() {
    final ZipOutputStream zout;
    ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
    zout = new ZipOutputStream(out);

    try {/*from w w w.ja  v a  2  s  . c o m*/

        connection.runReadAction(FieldAccessFactory.newFieldAccess(), new ReadAction() {

            public void execute(@NotNull SystemAccess access) throws Exception {
                Location root = access.getTree(SystemTree.Network).resolve(rootPath);

                Collection<ModuleStatus> aspects = root.find(ModuleStatus.class, Acceptors.acceptAll());

                synchronized (this) {
                    progressLimit = aspects.size();
                }

                for (ModuleStatus aspect : aspects) {
                    Location location = aspect.getLocation();
                    try {
                        if (!location.getAspect(Device.class).isOutOfService()) {
                            String path = getReferencePath(location);

                            //System.out.println("Gathering modstat from "+path);

                            ZipEntry entry = new ZipEntry(path + ".txt");
                            entry.setMethod(ZipEntry.DEFLATED);
                            zout.putNextEntry(entry);
                            IOUtils.copy(new StringReader(aspect.getReportText()), zout);
                            zout.closeEntry();

                            synchronized (this) {
                                progress++;
                                if (isInterrupted()) {
                                    error = new Exception("Gathering Modstats interrupted");
                                    return;
                                }
                            }
                        }
                    } catch (NoSuchAspectException e) { // skip and go to the next one
                    }
                }

            }
        });
    } catch (Exception e) {
        synchronized (this) {
            error = e;
        }
        return;
    } finally {
        try {
            zout.close();
        } catch (IOException e) {
        } // we tried our best
    }
    if (!hasError()) {
        cache = out.toByteArray();
    }
}

From source file:com.orange.ocara.model.export.docx.DocxWriter.java

/**
 * To zip a directory./*from w  w  w  .j  a  va 2 s  . c  om*/
 *
 * @param rootPath  root path
 * @param directory directory
 * @param zos       ZipOutputStream
 * @throws IOException
 */
private void zipDirectory(String rootPath, File directory, ZipOutputStream zos) throws IOException {
    //get a listing of the directory content
    File[] files = directory.listFiles();

    //loop through dirList, and zip the files
    for (File file : files) {
        if (file.isDirectory()) {
            zipDirectory(rootPath, file, zos);
            continue;
        }

        String filePath = FilenameUtils.normalize(file.getPath(), true);
        String fileName = StringUtils.difference(rootPath, filePath);

        fileName = fileName.replaceAll("\\[_\\]", "_").replaceAll("\\[.\\]", ".");

        //create a FileInputStream on top of file
        ZipEntry anEntry = new ZipEntry(fileName);
        zos.putNextEntry(anEntry);

        FileUtils.copyFile(file, zos);
    }
}