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.l2jfree.sql.L2DataSource.java

protected static final boolean writeBackup(String databaseName, InputStream in) throws IOException {
    FileUtils.forceMkdir(new File("backup/database"));

    final Date time = new Date();

    final L2TextBuilder tb = new L2TextBuilder();
    tb.append("backup/database/DatabaseBackup_");
    tb.append(new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(new Date()));
    tb.append("_uptime-").append(L2Config.getShortUptime());
    tb.append(".zip");

    final File backupFile = new File(tb.moveToString());

    int written = 0;
    ZipOutputStream out = null;// w w  w  .j  ava  2 s  . co m
    try {
        out = new ZipOutputStream(new FileOutputStream(backupFile));
        out.setMethod(ZipOutputStream.DEFLATED);
        out.setLevel(Deflater.BEST_COMPRESSION);
        out.setComment("L2jFree Schema Backup Utility\r\n\r\nBackup date: "
                + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS z").format(new Date()));
        out.putNextEntry(new ZipEntry(databaseName + ".sql"));

        byte[] buf = new byte[4096];
        for (int read; (read = in.read(buf)) != -1;) {
            out.write(buf, 0, read);

            written += read;
        }
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }

    if (written == 0) {
        backupFile.delete();
        return false;
    }

    _log.info("DatabaseBackupManager: Database `" + databaseName + "` backed up successfully in "
            + (System.currentTimeMillis() - time.getTime()) / 1000 + " s.");
    return true;
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

/** creates a plugin .zip and bad checksum file and returns the url for testing */
private String createPluginWithBadChecksum(final Path structure, String... properties) throws IOException {
    writeProperties(structure, properties);
    Path zip = createTempDir().resolve(structure.getFileName() + ".zip");
    try (ZipOutputStream stream = new ZipOutputStream(Files.newOutputStream(zip))) {
        Files.walkFileTree(structure, new SimpleFileVisitor<Path>() {
            @Override/*from w ww . j a v  a 2s  . com*/
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                stream.putNextEntry(new ZipEntry(structure.relativize(file).toString()));
                Files.copy(file, stream);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    if (randomBoolean()) {
        writeSha1(zip, true);
    } else {
        writeMd5(zip, true);
    }
    return zip.toUri().toURL().toString();
}

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

/**
 * Copy zip file and remove ignored files
 *
 * @param srcFile//from  w  ww . java2 s.c o m
 * @param destFile
 * @throws IOException
 */
public void copyZip(final String srcFile, final String destFile) throws Exception {
    loadDefaultExcludePattern(getRootFolderInZip(srcFile));

    final ZipFile zipSrc = new ZipFile(srcFile);
    final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile));

    try {
        final Enumeration<? extends ZipEntry> entries = zipSrc.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            if (!isExcluded(LocalPath.combine(srcFile, entry.getName()), false, srcFile)) {
                final ZipEntry newEntry = new ZipEntry(entry.getName());
                out.putNextEntry(newEntry);

                final BufferedInputStream in = new BufferedInputStream(zipSrc.getInputStream(entry));
                int len;
                final byte[] buf = new byte[65536];
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
        }
        out.finish();
    } catch (final IOException e) {
        errorMsg = Messages.getString("CreateUploadZipCommand.CopyArchiveErrorMessageFormat"); //$NON-NLS-1$
        log.error("Exceptions when copying exising archive ", e); //$NON-NLS-1$
        throw e;
    } finally {
        out.close();
        zipSrc.close();
    }
}

From source file:org.tonguetied.datatransfer.DataServiceImpl.java

public void createArchive(File directory) throws ExportException, IllegalArgumentException {
    if (!directory.isDirectory())
        throw new IllegalArgumentException("expecting a directory");

    ZipOutputStream zos = null;//from   w ww. jav a2 s .  co  m
    try {
        File[] files = directory.listFiles();
        if (files.length > 0) {
            final File archive = new File(directory, directory.getName() + ".zip");
            zos = new ZipOutputStream(new FileOutputStream(archive));
            for (File file : files) {
                zos.putNextEntry(new ZipEntry(file.getName()));
                IOUtils.write(FileUtils.readFileToByteArray(file), zos);
                zos.closeEntry();
            }

            if (logger.isDebugEnabled())
                logger.debug("archived " + files.length + " files to " + archive.getPath());
        }
    } catch (IOException ioe) {
        throw new ExportException(ioe);
    } finally {
        IOUtils.closeQuietly(zos);
    }
}

From source file:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Generates a zip file.//  w w w  .j  a  v  a 2s . c  o m
 *
 * @param source      source file or directory to compress.
 * @param destination destination of zipped file.
 * @return the zipped file.
 */
private void generateZip(File source, File destination) throws IOException {
    if (source == null || !source.exists()) {
        throw new IllegalArgumentException("source file should exist");
    }
    if (destination == null) {
        throw new IllegalArgumentException("destination file should be not null");
    }

    FileOutputStream output = new FileOutputStream(destination);
    ZipOutputStream zip_out = new ZipOutputStream(output);
    zip_out.setLevel(cfgManager.getDownloadConfiguration().getCompressionLevel());

    List<QualifiedFile> file_list = getFileList(source);
    byte[] buffer = new byte[BUFFER_SIZE];
    for (QualifiedFile qualified_file : file_list) {
        ZipEntry entry = new ZipEntry(qualified_file.getQualifier());
        InputStream input = new FileInputStream(qualified_file.getFile());

        int read;
        zip_out.putNextEntry(entry);
        while ((read = input.read(buffer)) != -1) {
            zip_out.write(buffer, 0, read);
        }
        input.close();
        zip_out.closeEntry();
    }
    zip_out.close();
    output.close();
}

From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java

public void export(Set<String> fields, MaalrQuery query, File dest) throws IOException, InvalidQueryException,
        NoIndexAvailableException, BrokenIndexException, InvalidTokenOffsetsException {
    query.setPageNr(0);/*  w w  w .ja  va2  s.co  m*/
    query.setPageSize(50);
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest));
    zout.putNextEntry(new ZipEntry("exported.tsv"));
    OutputStream out = new BufferedOutputStream(zout);
    OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
    for (String field : fields) {
        writer.write(field);
        writer.write("\t");
    }
    writer.write("\n");
    while (true) {
        QueryResult result = index.query(query, false);
        if (result == null || result.getEntries() == null || result.getEntries().size() == 0)
            break;
        List<LemmaVersion> entries = result.getEntries();
        for (LemmaVersion version : entries) {
            write(writer, version, fields);
            writer.write("\n");
        }
        query.setPageNr(query.getPageNr() + 1);
    }
    writer.flush();
    zout.closeEntry();
    writer.close();

}

From source file:com.wavemaker.tools.project.StageDeploymentManager.java

protected void assembleEar(Map<String, Object> properties, com.wavemaker.tools.io.File warFile) {
    ZipOutputStream out;/*from ww  w.j ava2  s  .c o  m*/
    InputStream is;
    try {
        com.wavemaker.tools.io.File earFile = (com.wavemaker.tools.io.File) properties
                .get(EAR_FILE_NAME_PROPERTY);
        out = new ZipOutputStream(earFile.getContent().asOutputStream());
        out.putNextEntry(new ZipEntry(warFile.getName()));
        is = warFile.getContent().asInputStream();
        org.apache.commons.io.IOUtils.copy(is, out);
        out.closeEntry();
        is.close();

        Folder webInf = ((Folder) properties.get(BUILD_WEBAPPROOT_PROPERTY)).getFolder("WEB-INF");
        com.wavemaker.tools.io.File appXml = webInf.getFile("application.xml");
        out.putNextEntry(new ZipEntry("META-INF/" + appXml.getName()));
        is = appXml.getContent().asInputStream();
        org.apache.commons.io.IOUtils.copy(is, out);
        out.closeEntry();
        is.close();

        String maniFest = "Manifest-Version: 1.0\n" + "Created-By: WaveMaker Studio (CloudJee Inc.)";
        out.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
        org.apache.commons.io.IOUtils.write(maniFest, out);
        out.closeEntry();
        is.close();
        out.close();
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:it.unimi.di.big.mg4j.document.SimpleCompressedDocumentCollectionBuilder.java

public void open(final CharSequence suffix) throws IOException {
    basenameSuffix = basename + suffix;/*  w w w . j a  va  2s  .co m*/
    documentsOutputBitStream = new OutputBitStream(
            ioFactory.getOutputStream(basenameSuffix + SimpleCompressedDocumentCollection.DOCUMENTS_EXTENSION),
            false);
    termsOutputStream = new CountingOutputStream(new FastBufferedOutputStream(
            ioFactory.getOutputStream(basenameSuffix + SimpleCompressedDocumentCollection.TERMS_EXTENSION)));
    nonTermsOutputStream = exact
            ? new CountingOutputStream(new FastBufferedOutputStream(ioFactory
                    .getOutputStream(basenameSuffix + SimpleCompressedDocumentCollection.NONTERMS_EXTENSION)))
            : null;
    documentOffsetsObs = new OutputBitStream(ioFactory.getOutputStream(
            basenameSuffix + SimpleCompressedDocumentCollection.DOCUMENT_OFFSETS_EXTENSION), false);
    termOffsetsObs = new OutputBitStream(ioFactory.getOutputStream(
            basenameSuffix + SimpleCompressedDocumentCollection.TERM_OFFSETS_EXTENSION), false);
    nonTermOffsetsObs = exact
            ? new OutputBitStream(
                    ioFactory.getOutputStream(
                            basenameSuffix + SimpleCompressedDocumentCollection.NONTERM_OFFSETS_EXTENSION),
                    false)
            : null;
    fieldContent = new IntArrayList();

    if (hasNonText)
        nonTextZipDataOutputStream = new DataOutputStream(
                nonTextZipOutputStream = new ZipOutputStream(new FastBufferedOutputStream(
                        ioFactory.getOutputStream(basenameSuffix + ZipDocumentCollection.ZIP_EXTENSION))));

    terms.clear();
    terms.trim(INITIAL_TERM_MAP_SIZE);
    if (exact) {
        nonTerms.clear();
        nonTerms.trim(INITIAL_TERM_MAP_SIZE);
    }
    words = fields = bitsForWords = bitsForNonWords = bitsForFieldLengths = bitsForUris = bitsForTitles = documents = 0;

    // First offset
    documentOffsetsObs.writeDelta(0);
    termOffsetsObs.writeDelta(0);
    if (exact)
        nonTermOffsetsObs.writeDelta(0);

}

From source file:edu.harvard.iq.dvn.core.analysis.NetworkDataServiceBean.java

public File getSubsetExport(boolean getGraphML, boolean getTabular) {

    if (!getGraphML && !getTabular) {
        throw new IllegalArgumentException("At least one download type must be set to true.");
    }/*from   w  w w  . ja  va 2 s .  c  o  m*/

    //  Map<String, String> resultInfo = dgs.liveConnectionExport(rWorkspace);
    //return new File( resultInfo.get(DvnRGraphServiceImpl.GRAPHML_FILE_EXPORTED) );
    File xmlFile;
    File vertsFile;
    File edgesFile;
    File zipOutputFile;
    ZipOutputStream zout;
    try {

        xmlFile = File.createTempFile("graphml", "xml");
        vertsFile = File.createTempFile("vertices", "tab");
        edgesFile = File.createTempFile("edges", "tab");

        String delimiter = "\t";
        if (getGraphML) {
            dvnGraph.dumpGraphML(xmlFile.getAbsolutePath());
        }
        if (getTabular) {
            dvnGraph.dumpTables(vertsFile.getAbsolutePath(), edgesFile.getAbsolutePath(), delimiter);
        }

        // Create zip file
        String exportTimestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss").format(new Date());
        zipOutputFile = File.createTempFile("subset_" + exportTimestamp, "zip");
        zout = new ZipOutputStream((OutputStream) new FileOutputStream(zipOutputFile));

        if (getGraphML) {
            addZipEntry(zout, xmlFile.getAbsolutePath(), "graphml_" + exportTimestamp + ".xml");
        }
        if (getTabular) {
            addZipEntry(zout, vertsFile.getAbsolutePath(), "vertices_" + exportTimestamp + ".tab");
            addZipEntry(zout, edgesFile.getAbsolutePath(), "edges_" + exportTimestamp + ".tab");
        }

        zout.close();

    } catch (IOException e) {
        throw new EJBException(e);
    }

    return zipOutputFile;
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.ExportBatchClassDownloadServlet.java

/**
 * Overriden doGet method.//from   w  w  w .j a  va  2 s.  c o  m
 * 
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @throws IOException
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    BatchClassService batchClassService = this.getSingleBeanOfType(BatchClassService.class);
    BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
    BatchClass batchClass = batchClassService.getLoadedBatchClassByIdentifier(req.getParameter("identifier"));
    if (batchClass == null) {
        LOG.error("Incorrect batch class identifier specified.");
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Incorrect batch class identifier specified.");
    } else {
        Calendar cal = Calendar.getInstance();
        String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation();

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyy", Locale.getDefault());
        String formattedDate = formatter.format(new Date());
        String zipFileName = batchClass.getIdentifier() + BatchClassManagementConstants.UNDERSCORE
                + formattedDate + BatchClassManagementConstants.UNDERSCORE + cal.get(Calendar.HOUR_OF_DAY)
                + cal.get(Calendar.SECOND);

        String tempFolderLocation = exportSerailizationFolderPath + File.separator + zipFileName;
        File copiedFolder = new File(tempFolderLocation);

        if (copiedFolder.exists()) {
            copiedFolder.delete();
        }

        copiedFolder.mkdirs();

        BatchClassUtil.copyModules(batchClass);
        BatchClassUtil.copyDocumentTypes(batchClass);
        BatchClassUtil.copyScannerConfig(batchClass);
        BatchClassUtil.exportEmailConfiguration(batchClass);
        BatchClassUtil.exportUserGroups(batchClass);
        BatchClassUtil.exportBatchClassField(batchClass);

        File serializedExportFile = new File(
                tempFolderLocation + File.separator + batchClass.getIdentifier() + SERIALIZATION_EXT);

        try {
            SerializationUtils.serialize(batchClass, new FileOutputStream(serializedExportFile));
            boolean isImagemagickBaseFolder = false;
            String imageMagickBaseFolderParam = req
                    .getParameter(batchSchemaService.getImagemagickBaseFolderName());
            if (imageMagickBaseFolderParam != null && (imageMagickBaseFolderParam
                    .equalsIgnoreCase(batchSchemaService.getImagemagickBaseFolderName())
                    || Boolean.parseBoolean(imageMagickBaseFolderParam))) {
                isImagemagickBaseFolder = true;
            }

            boolean isSearchSampleName = false;
            String isSearchSampleNameParam = req.getParameter(batchSchemaService.getSearchSampleName());
            if (isSearchSampleNameParam != null
                    && (isSearchSampleNameParam.equalsIgnoreCase(batchSchemaService.getSearchSampleName())
                            || Boolean.parseBoolean(isSearchSampleNameParam))) {
                isSearchSampleName = true;
            }

            File originalFolder = new File(
                    batchSchemaService.getBaseSampleFDLock() + File.separator + batchClass.getIdentifier());

            if (originalFolder.isDirectory()) {

                validateFolderAndFile(batchSchemaService, copiedFolder, isImagemagickBaseFolder,
                        isSearchSampleName, originalFolder);
            }

        } catch (FileNotFoundException e) {
            // Unable to read serializable file
            LOG.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.");

        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            LOG.error("Error occurred while creating the serializable file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Error occurred while creating the serializable file.Please try again");
        }
        resp.setContentType("application/x-zip\r\n");
        resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName + ZIP_EXT + "\"\r\n");
        ServletOutputStream out = null;
        ZipOutputStream zout = null;
        try {
            out = resp.getOutputStream();
            zout = new ZipOutputStream(out);
            FileUtils.zipDirectory(tempFolderLocation, zout, zipFileName);
            resp.setStatus(HttpServletResponse.SC_OK);
        } catch (IOException e) {
            // Unable to create the temporary export file(s)/folder(s)
            LOG.error("Error occurred while creating the zip file." + e, e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to export.Please try again.");
        } finally {
            // clean up code
            if (zout != null) {
                zout.close();
            }
            if (out != null) {
                out.flush();
            }
            FileUtils.deleteDirectoryAndContentsRecursive(copiedFolder);
        }
    }
}