Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Creates a zip archive of the currently serialized files in
 * getCurrentDirectory(), placing the archive in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()/*w ww  . j  ava 2  s  .c om*/
 * @see #getArchiveDirectory()
 */
public void archiveCurrentDirectory() throws RuntimeException {
    System.out.println("Making zip archive of files in " + getCurrentDirectory() + ", putting it in "
            + getArchiveDirectory() + ".");

    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalArgumentException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    File archive = new File(getArchiveDirectory());
    if (archive.exists() && !archive.isDirectory()) {
        throw new IllegalArgumentException(
                "Output directory " + archive.getAbsolutePath() + " is not a directory.");
    }

    if (!archive.exists()) {
        archive.mkdirs();
    }

    String[] filenames = current.list();

    // Create a buffer for reading the files
    byte[] buf = new byte[1024];

    try {
        String version = Version.currentRepositoryVersion().toString();

        // Create the ZIP file
        String outFilename = "serializedclasses-" + version + ".zip";
        File _file = new File(getArchiveDirectory(), outFilename);
        FileOutputStream fileOut = new FileOutputStream(_file);
        ZipOutputStream out = new ZipOutputStream(fileOut);

        // Compress the files
        for (String filename : filenames) {
            File file = new File(current, filename);

            FileInputStream in = new FileInputStream(file);

            // Add ZIP entry to output stream.
            ZipEntry entry = new ZipEntry(filename);
            entry.setSize(file.length());
            entry.setTime(file.lastModified());

            out.putNextEntry(entry);

            // Transfer bytes from the file to the ZIP file
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            // Complete the entry
            out.closeEntry();
            in.close();
        }

        // Complete the ZIP file
        out.close();

        System.out.println("Finished writing zip file " + outFilename + ".");
    } catch (IOException e) {
        throw new RuntimeException("There was an I/O error associated with "
                + "the process of zipping up files in " + getCurrentDirectory() + ".", e);
    }
}

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

protected void assembleEar(Map<String, Object> properties, com.wavemaker.tools.io.File warFile) {
    ZipOutputStream out;
    InputStream is;/*  w ww. j a  v  a  2s  .c o m*/
    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: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.");
    }/*w w w. j  a  va 2  s . co 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:de.decidr.model.workflowmodel.deployment.PackageBuilder.java

/**
 * @param workFlowId/*from  w w w . j  av  a 2  s  .c o m*/
 * @param bpel
 * @param wsdl
 * @param dd
 *            depoyment descriptor
 * @param serverLocation
 *            location for service endpoints
 * @return the zip'ed package as byte array
 * @throws JAXBException
 * @throws IOException
 */
public static byte[] getPackage(long workFlowId, TProcess bpel, TDefinitions wsdl, TDeployment dd,
        HashMap<String, List<ServerLoadView>> serverMap) throws JAXBException, IOException {

    ByteArrayOutputStream zipOut = new ByteArrayOutputStream();

    TransformationHelper th = new TransformationHelper();

    de.decidr.model.schema.bpel.executable.ObjectFactory of = new de.decidr.model.schema.bpel.executable.ObjectFactory();
    de.decidr.model.schema.wsdl.ObjectFactory ofwasl = new de.decidr.model.schema.wsdl.ObjectFactory();
    de.decidr.model.schema.bpel.dd.ObjectFactory ofdd = new de.decidr.model.schema.bpel.dd.ObjectFactory();

    JAXBElement<TDefinitions> def = ofwasl.createDefinitions(wsdl);
    JAXBElement<TDeployment> d = ofdd.createDeploy(dd);

    String bpelFilename = "BPELPROCESS_" + workFlowId + ".bpel";
    String wsdlFilename = TransformConstants.FILENAME_WSDL_PROCESS_NAME_TEMPLATE.replace("?", workFlowId + "");
    String ddFilename = "deploy.xml";

    ZipOutputStream zip_out_stream = new ZipOutputStream(zipOut);

    // Add BPEL to zip
    zip_out_stream.putNextEntry(new ZipEntry(bpelFilename));
    String fileBPEL = th.jaxbObjectToStringWithWorkflowNamespace(of.createProcess(bpel),
            bpel.getTargetNamespace(), TransformationHelper.BPEL_CLASSES);
    zip_out_stream.write(fileBPEL.getBytes());
    zip_out_stream.closeEntry();

    // Add WSDL to zip
    zip_out_stream.putNextEntry(new ZipEntry(wsdlFilename));
    String fileWSDL = th.jaxbObjectToStringWithWorkflowNamespace(def, bpel.getTargetNamespace(),
            TransformationHelper.WSDL_CLASSES);
    zip_out_stream.write(fileWSDL.getBytes());
    zip_out_stream.closeEntry();

    // Add Deployment Descriptor to zip
    zip_out_stream.putNextEntry(new ZipEntry(ddFilename));
    String fileDD = th.jaxbObjectToStringWithWorkflowNamespace(d, bpel.getTargetNamespace(),
            TransformationHelper.DD_CLASSES);
    zip_out_stream.write(fileDD.getBytes());
    zip_out_stream.closeEntry();

    // Add the EMail WSDL to package and modify the service endpoint
    zip_out_stream.putNextEntry(new ZipEntry(TransformConstants.FILENAME_WSDL_EMAIL));
    zip_out_stream.write(getEmailWsdl(
            URLGenerator.getEmailWSUrl(serverMap.get(ServerTypeEnum.Ode.toString()).get(0).getLocation())));
    zip_out_stream.closeEntry();

    // Add the HT WSDL to package and modify the service endpoint
    zip_out_stream.putNextEntry(new ZipEntry(TransformConstants.FILENAME_WSDL_HUMANTASK));
    zip_out_stream.write(getHTWsdl(
            URLGenerator.getHumanTaskWSUrl(serverMap.get(ServerTypeEnum.Ode.toString()).get(0).getLocation())));
    zip_out_stream.closeEntry();

    // Add the PS WSDL to package and modify the service endpoint
    zip_out_stream.putNextEntry(new ZipEntry(TransformConstants.FILENAME_WSDL_PROXY));
    zip_out_stream.write(getPSWsdl(URLGenerator
            .getProxyServiceWSUrl(serverMap.get(ServerTypeEnum.Ode.toString()).get(0).getLocation())));
    zip_out_stream.closeEntry();

    // Add DecidrTypes schema to package
    zip_out_stream.putNextEntry(new ZipEntry(TransformConstants.FILENAME_XSD_DECIDR_TYPES));
    zip_out_stream.write(loadSchema(TransformConstants.FILENAME_XSD_DECIDR_TYPES));
    zip_out_stream.closeEntry();

    zip_out_stream.close();
    return zipOut.toByteArray();

}

From source file:nl.coinsweb.sdk.FileManager.java

/**
 * Zips all the content of the [TEMP_ZIP_PATH] / [internalRef] to the specified target .ccr-file.
 *
 * @param target  the .ccr-file containing all the content from this container
 *///w  ww .  j  av  a2 s .c om
public static void zip(String internalRef, File target) {

    try {

        final Path homePath = getTempZipPath().resolve(internalRef);

        FileOutputStream fos = new FileOutputStream(target);
        final ZipOutputStream zos = new ZipOutputStream(fos);

        ZipEntry ze;
        File[] files;

        // Add bim
        ze = new ZipEntry(RDF_PATH + "/");
        zos.putNextEntry(ze);
        zos.closeEntry();
        files = homePath.resolve(RDF_PATH).toFile().listFiles();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isDirectory()) {
                addFileToZip(files[i].toString(), Paths.get(RDF_PATH).resolve(files[i].getName()), zos);
            }
        }

        // Add bim/repository
        ze = new ZipEntry(ONTOLOGIES_PATH + "/");
        zos.putNextEntry(ze);
        zos.closeEntry();
        files = homePath.resolve(ONTOLOGIES_PATH).toFile().listFiles();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isDirectory()) {
                addFileToZip(files[i].toString(), Paths.get(ONTOLOGIES_PATH).resolve(files[i].getName()), zos);
            }
        }

        // Add doc
        ze = new ZipEntry(ATTACHMENT_PATH + "/");
        zos.putNextEntry(ze);
        zos.closeEntry();
        files = homePath.resolve(ATTACHMENT_PATH).toFile().listFiles();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isDirectory()) {
                addFileToZip(files[i].toString(), Paths.get(ATTACHMENT_PATH).resolve(files[i].getName()), zos);
            }
        }

        // Add woa
        ze = new ZipEntry(WOA_PATH + "/");
        zos.putNextEntry(ze);
        zos.closeEntry();
        files = homePath.resolve(WOA_PATH).toFile().listFiles();
        for (int i = 0; i < files.length; i++) {
            if (!files[i].isDirectory()) {
                addFileToZip(files[i].toString(), Paths.get(WOA_PATH).resolve(files[i].getName()), zos);
            }
        }

        zos.close();

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

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnRGraphServiceImpl.java

/** *************************************************************
 * Export a saved RData file as a GraphML file, using the existing
 * open connection// w w  w  .  j  ava2 s.  c  o m
 *
 * @param savedRDatafile;
 * @return    a Map that contains various information about the results
 */

public Map<String, String> liveConnectionExport(String savedRDataFile) throws DvnRGraphException {

    Map<String, String> result = new HashMap<String, String>();

    DvnRConnection drc = null;

    try {

        // let's see if we have a connection that we can use: 

        if (myConnection == 0) {
            throw new DvnRGraphException("execute method called without creating a connection first");
        }

        myConnection = RConnectionPool.securePooledConnection(savedRDataFile, null, true, myConnection);
        dbgLog.info("Export: obtained connection " + myConnection);

        drc = RConnectionPool.getConnection(myConnection);

        String exportCommand = "dump_graphml(g, '" + GraphMLfileNameRemote + "')";
        dbgLog.fine(exportCommand);
        historyEntry.add(exportCommand);
        String cmdResponse = safeEval(drc.Rcon, exportCommand).asString();

        exportCommand = "dump_tab(g, '" + DSB_TMP_DIR + "/temp_" + IdSuffix + ".tab')";
        dbgLog.fine(exportCommand);
        historyEntry.add(exportCommand);
        cmdResponse = safeEval(drc.Rcon, exportCommand).asString();

        File zipFile = new File(TEMP_DIR, "subset_" + IdSuffix + ".zip");
        FileOutputStream zipFileStream = new FileOutputStream(zipFile);
        ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile));

        addZipEntry(drc.Rcon, zout, GraphMLfileNameRemote, "data/subset.xml");
        addZipEntry(drc.Rcon, zout, DSB_TMP_DIR + "/temp_" + IdSuffix + "_verts.tab", "data/vertices.tab");
        addZipEntry(drc.Rcon, zout, DSB_TMP_DIR + "/temp_" + IdSuffix + "_edges.tab", "data/edges.tab");

        zout.close();
        zipFileStream.close();

        result.put(GRAPHML_FILE_EXPORTED, zipFile.getAbsolutePath());

        String RexecDate = drc.Rcon.eval("as.character(as.POSIXct(Sys.time()))").asString();
        String RversionLine = "R.Version()$version.string";
        String Rversion = drc.Rcon.eval(RversionLine).asString();

        result.put("dsbHost", RSERVE_HOST);
        result.put("dsbPort", DSB_HOST_PORT);
        result.put("IdSuffix", IdSuffix);

        result.put("Rversion", Rversion);
        result.put("RexecDate", RexecDate);
        result.put("RCommandHistory", StringUtils.join(historyEntry, "\n"));

        dbgLog.fine("result object (before closing the Rserve):\n" + result);

    } catch (DvnRGraphException dre) {
        throw dre;
    } catch (RException re) {
        throw new DvnRGraphException("R run-time error: " + re.getMessage());
    } catch (RserveException rse) {
        dbgLog.info("LCE: rserve exception message: " + rse.getMessage());
        dbgLog.info("LCE: rserve exception description: " + rse.getRequestErrorDescription());
        throw new DvnRGraphException("RServe failure: " + rse.getMessage());

    } catch (REXPMismatchException mme) {
        throw new DvnRGraphException("REXPmismatchException occured");

    } catch (Exception ex) {
        throw new DvnRGraphException("Unknown exception occured: " + ex.getMessage());
    } finally {
        if (drc != null) {
            // set the connection time stamp: 
            Date now = new Date();
            drc.setLastQueryTime(now.getTime());

            drc.unlockConnection();
        }
    }
    return result;

}

From source file:net.sourceforge.jweb.maven.mojo.PropertiesOverideMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled) {
        this.getLog().info("plugin was disabled");
        return;//from w  w w .  ja v  a2  s.  c  om
    }
    processConfiguration();
    if (replacements.isEmpty()) {
        this.getLog().info("Nothing to replace with");
        return;
    }

    String name = this.builddir.getAbsolutePath() + File.separator + this.finalName + "." + this.packing;//the final package
    this.getLog().debug("final artifact: " + name);// the final package

    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
            return;
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (acceptMime(entry)) {
                getLog().info("applying replacements for " + entry.getName());
                InputStream inputStream = zipFile.getInputStream(entry);
                String src = IOUtils.toString(inputStream, encoding);
                //do replacement
                for (Entry<String, String> e : replacements.entrySet()) {
                    src = src.replaceAll("#\\{" + e.getKey() + "}", e.getValue());
                }
                out.putNextEntry(new ZipEntry(entry.getName()));
                IOUtils.write(src, out, encoding);
                inputStream.close();
            } else {
                //not repalce, just put entry back to out zip
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }
        }
        zipFile.close();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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/*from  ww  w.j a  va2  s . co m*/
        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:com.aurel.track.exchange.track.exporter.TrackExportBL.java

public static ZipOutputStream exportWorkItemsWithAttachments(List<ReportBean> reportBeanList, Integer personID,
        OutputStream outputStream) {

    ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

    Document document = exportWorkItems(reportBeanList, personID);
    ZipEntry dataEntry = new ZipEntry(ExchangeFieldNames.EXCHANGE_ZIP_ENTRY);
    try {//from w  ww . j  a va2s.  c  om
        zipOutputStream.putNextEntry(dataEntry);
    } catch (IOException e) {
        LOGGER.error("Adding the XML data to the zip failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    ReportBeansToXML.convertToXml(zipOutputStream, document);
    //zipOutputStream.closeEntry();
    //get the attachments for each workItem (if exist)
    if (reportBeanList != null) {
        for (ReportBean reportBean : reportBeanList) {
            TWorkItemBean workItemBean = reportBean.getWorkItemBean();
            Integer workItemID = workItemBean.getObjectID();
            String workItemAttachmentsDirectory = AttachBL.getFullDirName(null, workItemID);
            File file = new File(workItemAttachmentsDirectory);
            if (file.exists() && file.isDirectory()) {
                ReportBL.zipFiles(file, zipOutputStream, file.getAbsolutePath());
            }
        }
    }
    try {
        zipOutputStream.close();
    } catch (IOException e) {
        LOGGER.warn("Closing the zip failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return zipOutputStream;
}