Example usage for java.util.zip ZipOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry e) throws IOException 

Source Link

Document

Begins writing a new ZIP file entry and positions the stream to the start of the entry data.

Usage

From source file:fr.ippon.wip.config.ZipConfiguration.java

/**
 * Create a zip archive from a configuration.
 * //from  www  .  j  a v  a  2 s  . c o  m
 * @param configuration
 *            the configuration to zip
 * @param out
 *            the stream to be used
 */
public void zip(WIPConfiguration configuration, ZipOutputStream out) {
    XMLConfigurationDAO xmlConfigurationDAO = new XMLConfigurationDAO(FileUtils.getTempDirectoryPath());

    /*
     * a configuration with the same name may already has been unzipped in
     * the temp directory, so we try to delete it for avoiding name
     * modification (see ConfigurationDAO.correctConfigurationName).
     */
    xmlConfigurationDAO.delete(configuration);
    xmlConfigurationDAO.create(configuration);

    String configName = configuration.getName();

    try {
        int[] types = new int[] { XMLConfigurationDAO.FILE_NAME_CLIPPING,
                XMLConfigurationDAO.FILE_NAME_TRANSFORM, XMLConfigurationDAO.FILE_NAME_CONFIG };
        for (int type : types) {
            File file = xmlConfigurationDAO.getConfigurationFile(configName, type);
            ZipEntry entry = new ZipEntry(file.getName());
            out.putNextEntry(entry);
            copy(FileUtils.openInputStream(file), out);
            out.closeEntry();
        }

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

From source file:it.cnr.icar.eric.server.query.CompressContentQueryFilterPlugin.java

private void internalAddRepositoryItemToZipFile(RepositoryItem ri, ZipOutputStream zos, String zipEntryValue)
        throws IOException {
    if (ri != null) {
        int BUFFER = 2048;
        byte data[] = new byte[BUFFER];
        BufferedInputStream origin = null;
        try {//from  w  w w  .j  a  v  a  2s. c  o  m
            InputStream is = ri.getDataHandler().getInputStream();
            origin = new BufferedInputStream(is, BUFFER);
            ZipEntry entry = new ZipEntry(zipEntryValue);
            zos.putNextEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                zos.write(data, 0, count);
            }
        } finally {
            if (origin != null) {
                try {
                    origin.close();
                } catch (Throwable t) {
                    origin = null;
                }
            }
        }
    }
}

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

@Transactional
public void getSongsZip(User user, List<Long> desiredSongs, OutputStream os) throws IOException {
    ZipOutputStream zos = new ZipOutputStream(os);
    // level - the compression level (0-9)
    zos.setLevel(9);//  ww w. ja  v a  2  s.co  m

    HashMap<String, String> songs = new HashMap<String, String>();
    for (Long songSid : desiredSongs) {
        MDOSong song = daoSong.get(user.getLogin(), songSid);
        if (song != null) {
            // add file
            // extract the relative name for entry purpose
            String entryName = song.getLocation();
            if (songs.get(entryName) == null) {
                // not repeated
                songs.put(entryName, "ok");
                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();
            }
        }
    }

    zos.close();
}

From source file:fi.mikuz.boarder.util.FileProcessor.java

void zipAddDir(File dirObj, ZipOutputStream out) throws IOException {
    File[] files = dirObj.listFiles();
    byte[] tmpBuf = new byte[1024];

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            zipAddDir(files[i], out);/*from  w ww .j a va  2  s. co  m*/
            continue;
        }
        FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
        System.out.println(" Adding: " + files[i].getAbsolutePath().substring(mBoardDirLength));
        out.putNextEntry(new ZipEntry(files[i].getAbsolutePath().substring(mBoardDirLength)));
        int len;
        while ((len = in.read(tmpBuf)) > 0) {
            out.write(tmpBuf, 0, len);
        }
        out.closeEntry();
        in.close();
    }
}

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 {//from  w ww.  ja  v a2  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:org.kuali.coeus.s2sgen.impl.print.FormPrintServiceImpl.java

protected void addFileToZip(String path, String sourceFile, ZipOutputStream zipOutputStream) throws Exception {
    File attachmentFile = new File(sourceFile);
    if (attachmentFile.isDirectory()) {
        addFolderToZip(path, sourceFile, zipOutputStream);
    } else {/*w w w . j  a v  a  2  s .  co  m*/
        byte[] buffer = new byte[1024];
        int length;
        try (FileInputStream fileInputStream = new FileInputStream(attachmentFile)) {
            zipOutputStream.putNextEntry(new ZipEntry(path + "/" + attachmentFile.getName()));
            while ((length = fileInputStream.read(buffer)) > 0) {
                zipOutputStream.write(buffer, 0, length);
            }
        }
    }
}

From source file:com.cordys.coe.ac.emailio.archive.FileArchiver.java

/**
 * This method starts the actual archiving of the passed on context containers.
 *
 * @param   lccContainers  The containers to archive.
 * @param   spqmManager    The QueryManager to use.
 *
 * @throws  ArchiverException  In case of any exceptions.
 *
 * @see     com.cordys.coe.ac.emailio.archive.IArchiver#doArchive(java.util.List, com.cordys.coe.ac.emailio.objects.IStorageProviderQueryManager)
 *///from  w  ww.  ja  va 2s .  c om
@Override
public void doArchive(List<ContextContainer> lccContainers, IStorageProviderQueryManager spqmManager)
        throws ArchiverException {
    File fArchive = getArchiveFolder();

    for (ContextContainer ccContainer : lccContainers) {
        int iWrapperXML = 0;
        ZipOutputStream zosZip = null;
        File fZipFile = null;
        List<EmailMessage> lEmails = null;

        try {
            lEmails = spqmManager.getEmailMessagesByContextID(ccContainer.getID());

            // Create the ZipFile
            fZipFile = new File(fArchive, ccContainer.getID().replaceAll("[^a-zA-Z0-9]", "") + ".zip");
            zosZip = new ZipOutputStream(new FileOutputStream(fZipFile, false));
            zosZip.setLevel(m_iZipLevel);

            // Now we have both the container and the emails. We will create an XML
            // to hold all data.
            int iObjectData = ccContainer._getObjectData();

            // Create the zip entry for it.
            ZipEntry zeContainer = new ZipEntry("container.xml");
            zosZip.putNextEntry(zeContainer);

            String sXML = Node.writeToString(iObjectData, true);
            zosZip.write(sXML.getBytes());
            zosZip.closeEntry();

            // Add the email messages to the zip file.
            int iCount = 0;

            for (EmailMessage emMessage : lEmails) {
                iObjectData = emMessage._getObjectData();

                ZipEntry zeEmail = new ZipEntry("email_" + iCount++ + ".xml");
                zosZip.putNextEntry(zeEmail);

                sXML = Node.writeToString(iObjectData, true);
                zosZip.write(sXML.getBytes());
                zosZip.closeEntry();
            }

            // Now all files are written into a single Zip file, so we can close it.
        } catch (Exception e) {
            throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ARCHIVING_CONTAINER_0,
                    ccContainer.getID());
        } finally {
            if (iWrapperXML != 0) {
                Node.delete(iWrapperXML);
            }

            if (zosZip != null) {
                try {
                    zosZip.close();
                } catch (IOException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Error closing zip file " + fZipFile.getAbsolutePath(), e);
                    }
                }
            }
        }

        // If we get here the zipfile was successfully created. So now we need to remove the
        // mails and the container from the current storage provider.
        try {
            spqmManager.removeContextContainer(ccContainer);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Archived the container with id " + ccContainer.getID());
            }
        } catch (StorageProviderException e) {
            throw new ArchiverException(e,
                    ArchiverExceptionMessages.ARE_ERROR_REMOVING_CONTEXT_CONTAINER_0_FROM_THE_STORAGE,
                    ccContainer.getID());
        }
    }

    // Now all containers have been archived, we will create a single zip file.
    try {
        File fFinalArchive = new File(fArchive.getParentFile(), fArchive.getName() + ".zip");

        if (LOG.isDebugEnabled()) {
            LOG.debug("Archiving folder " + fArchive.getCanonicalPath() + " into file "
                    + fFinalArchive.getCanonicalPath());
        }

        new ZipUtil().compress(fArchive, fFinalArchive.getAbsolutePath());
    } catch (Exception e) {
        throw new ArchiverException(e, ArchiverExceptionMessages.ARE_ERROR_ZIPPING_ALL_ARCHIVE_FILES);
    }
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

private void addFileToZip(final String basePath, final File file, final ZipOutputStream zipout)
        throws IOException {
    if (file == null || !file.exists()) {
        return;/*from ww w .ja  v a 2  s.c  om*/
    }

    final String filePath = file.getPath();
    if (file.isDirectory()) {
        if (!isExcluded(filePath, true, basePath)) {
            final File[] files = file.listFiles();
            for (final File f : files) {
                addFileToZip(basePath, f, zipout);
            }
        }
    } else {
        if (!isExcluded(filePath, false, basePath)) {
            final byte[] buf = new byte[65536];
            int len;
            FileInputStream in = null;
            try {
                in = new FileInputStream(file);
                zipout.putNextEntry(new ZipEntry(filePath.substring(basePath.length() + 1)));
                while ((len = in.read(buf)) > 0) {
                    zipout.write(buf, 0, len);
                }
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        }
    }
}

From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java

protected void exportSitePages(ZipOutputStream zos, String path) throws WPBIOException {
    try {// w  ww .ja  va2  s . c o  m
        List<WPBPage> pages = dataStorage.getAllRecords(WPBPage.class);
        for (WPBPage page : pages) {
            String pageXmlPath = path + page.getExternalKey() + "/" + "metadata.xml";
            Map<String, Object> map = new HashMap<String, Object>();
            exporter.export(page, map);
            ZipEntry metadataZe = new ZipEntry(pageXmlPath);
            zos.putNextEntry(metadataZe);
            exportToXMLFormat(map, zos);
            zos.closeEntry();
            String pageSourcePath = path + page.getExternalKey() + "/" + "pageSource.txt";
            String pageSource = page.getHtmlSource() != null ? page.getHtmlSource() : "";
            ZipEntry pageSourceZe = new ZipEntry(pageSourcePath);
            zos.putNextEntry(pageSourceZe);
            zos.write(pageSource.getBytes("UTF-8"));
            zos.closeEntry();

            String parametersPath = String.format(PATH_SITE_PAGES_PARAMETERS, page.getExternalKey());
            ZipEntry paramsZe = new ZipEntry(parametersPath);
            zos.putNextEntry(paramsZe);
            zos.closeEntry();

            exportParameters(page.getExternalKey(), zos, parametersPath);

        }
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("Cannot export site web pages to Zip", e);
    }
}