Example usage for java.util.zip ZipOutputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

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

protected void exportSitePages(ZipOutputStream zos, String path) throws WPBIOException {
    try {//from w  w  w .j  av  a 2s .c om
        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);
    }
}

From source file:org.dataconservancy.ui.stripes.DepositActionBeanTest.java

/**
 * Deposit a ZIP file (which will create a DataItem (aka Data Set) for each file in the ZIP). We expect one Package
 * to be created for the ZIP file, which is represented by a single row in the PACKAGE_TABLE. Two rows should be
 * created in the PACKAGE_FILE_DATA, one row for each file in the ZIP.
 * <p/>// ww  w .  j ava  2 s  . c o  m
 * Then attempt to update one of the data items originally deposited in the ZIP. This should result in a second
 * Package being created, which is represented by another row in the PACKAGE_TABLE. An additional row should be
 * created in the PACKAGE_FILE_DATA which represents the updated file.
 * <p/>
 * <strong>N.B.</strong>: the original two rows in the PACKAGE_FILE_DATA still remain in the data base table after
 * the update, which may not be the proper behavior.
 * 
 * @throws Exception
 */
@Test
public void testDepositZipFileThenUpdateDataset() throws Exception {
    // No Packages should exist at this point
    assertEquals(0, packageDao.selectPackage().size());

    // Create a ZIP file to deposit, containing two text files.
    File zipFileToDeposit = File.createTempFile("DepositActionBeanTest-testDepositZipFileThenUpdateDataset-",
            ".zip");
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileToDeposit));

    // Create a ZipEntry for the first text file.
    final String zipFileName1 = "DepositActionBeanTest-testDepositZipFileThenUpdateDataset-01.txt";
    ZipEntry zipFile = new ZipEntry(zipFileName1);
    zipOut.putNextEntry(zipFile);
    final String zipFileContent1 = "Test File One";
    IOUtils.write(zipFileContent1, zipOut);
    zipOut.closeEntry();

    // Create a second ZipEntry for the second text file.
    final String zipFileName2 = "DepositActionBeanTest-testDepositZipFileThenUpdateDataset-02.txt";
    zipFile = new ZipEntry(zipFileName2);
    zipOut.putNextEntry(zipFile);
    final String zipFileContent2 = "Test File Two";
    IOUtils.write(zipFileContent2, zipOut);
    zipOut.closeEntry();
    zipOut.close();

    List<String> dataItemsDepositIds = archiveService.listDataSets(ArchiveDepositInfo.Status.DEPOSITED);
    int startingDataItemCount = dataItemsDepositIds.size();
    MockRoundtrip depositRoundTrip = new MockRoundtrip(servletCtx, DepositActionBean.class, adminSession);
    depositRoundTrip.setParameter("currentCollectionId", collectionOne.getId()); // The collectionWithData to
                                                                                 // deposit to
    depositRoundTrip.setParameter("isContainer", "true"); // The file being deposited is a container (it's a ZIP
                                                          // file)
    depositRoundTrip.setParameter("uploadedFile", zipFileToDeposit.getAbsolutePath());
    // Making sure the page is redirected properly after the deposit.
    depositRoundTrip.addParameter("redirectUrl", UserCollectionsActionBean.HOME_COLLECTIONS_PATH);

    // Execute the DepositActionBean. A Package should be created by the deposit, and the Package should contain
    // two files.

    depositRoundTrip.execute("deposit");
    assertEquals("Expected one Package to be created by this deposit!", 1, packageDao.selectPackage().size());
    assertEquals("Expected two files to be contained in this package!", 2,
            packageDao.selectPackage().iterator().next().getFileData().size());

    // Two Data Items should have been created in the Archive

    archiveService.pollArchive(); // Update the deposit status of any pending deposits
    dataItemsDepositIds = archiveService.listDataSets(ArchiveDepositInfo.Status.DEPOSITED);
    assertEquals(startingDataItemCount + 2, dataItemsDepositIds.size());

    // Retrieve one of the DataItems

    ArchiveSearchResult<DataItem> dataItems = archiveService.retrieveDataSet(dataItemsDepositIds.get(0));
    assertEquals(1, dataItems.getResultCount());
    DataItem dataItem = dataItems.getResults().iterator().next();
    assertNotNull(dataItem);

    // The Data Item should only have a single file, with a name equal to one of the two files we originally
    // deposited.

    assertEquals(1, dataItem.getFiles().size());
    DataFile f = dataItem.getFiles().get(0);
    assertTrue(f.getName().equals(zipFileName1) || f.getName().equals(zipFileName2));

    // Now, let's update the Data Item by replacing the file.
    File updateFile = File.createTempFile("DepositActionBeanTest-testDepositZipFileThenUpdateDataset-03",
            ".txt");
    IOUtils.write("Test Content Three", new FileOutputStream(updateFile));

    depositRoundTrip = new MockRoundtrip(servletCtx, DepositActionBean.class, adminSession);
    depositRoundTrip.setParameter("currentCollectionId", collectionOne.getId()); // The collectionWithData to
                                                                                 // deposit to
    depositRoundTrip.setParameter("isContainer", "false"); // The file being deposited is not a container
    depositRoundTrip.setParameter("uploadedFile", updateFile.getAbsolutePath()); // This is the file with the
                                                                                 // updated contents
    depositRoundTrip.setParameter("datasetToUpdateId", dataItem.getId()); // This is the data item we are updating
    // Making sure the page is redirected properly after the deposit.
    depositRoundTrip.addParameter("redirectUrl", UserCollectionsActionBean.HOME_COLLECTIONS_PATH);
    // Execute the DepositActionBean. A Package should be created by the deposit, and the Package should contain
    // a single file.

    depositRoundTrip.execute("update");
    assertEquals("Expected one Package to be created by this deposit!", 2, packageDao.selectPackage().size());
    assertEquals("Expected one file to be contained in this package!", 1,
            packageDao.selectPackage().get(1).getFileData().size());

}

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

protected void exportFiles(ZipOutputStream zos, String path) throws WPBIOException {
    try {/*from ww  w  .j  a v  a  2  s  .  c  om*/
        List<WPBFile> files = dataStorage.getAllRecords(WPBFile.class);
        for (WPBFile file : files) {
            String fileXmlPath = path + file.getExternalKey() + "/" + "metadata.xml";
            Map<String, Object> map = new HashMap<String, Object>();
            exporter.export(file, map);
            ZipEntry metadataZe = new ZipEntry(fileXmlPath);
            zos.putNextEntry(metadataZe);
            exportToXMLFormat(map, zos);
            zos.closeEntry();
            String contentPath = String.format(PATH_FILE_CONTENT, file.getExternalKey());
            ZipEntry contentZe = new ZipEntry(contentPath);
            zos.putNextEntry(contentZe);
            zos.closeEntry();

            if (file.getDirectoryFlag() == null || file.getDirectoryFlag() != 1) {
                try {
                    String filePath = contentPath + file.getFileName();
                    WPBFilePath cloudFile = new WPBFilePath(PUBLIC_BUCKET, file.getBlobKey());
                    InputStream is = cloudFileStorage.getFileContent(cloudFile);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    IOUtils.copy(is, bos);
                    bos.flush();
                    byte[] content = bos.toByteArray();
                    ZipEntry fileZe = new ZipEntry(filePath);
                    zos.putNextEntry(fileZe);
                    zos.write(content);
                    zos.closeEntry();
                } catch (Exception e) {
                    log.log(Level.SEVERE, " Exporting file :" + file.getExternalKey(), e);
                    // do nothing, we do not abort the export because of a failure, but we need to log this as warning
                }
            }
        }
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
        throw new WPBIOException("Cannot export files to Zip", e);
    }
}

From source file:org.bdval.BDVModel.java

/**
 * Store the BDVModel training platform to the specified output stream.
 *
 * @param stream  The stream to store the properties to
 * @param options The options associated with this model
 * @throws IOException if there is a problem writing to the stream
 *//*from w  w  w.  j a v a 2s  .com*/
private void savePlatform(final OutputStream stream, final DAVOptions options) throws IOException {
    switch (format) {
    case BINARY:
        BinIO.storeObject(options.trainingPlatform, stream);
        break;
    case PROPERTIES:
        final Map<String, java.util.Properties> propertyMap = options.trainingPlatform.toPropertyMap();
        for (final Map.Entry<String, java.util.Properties> entry : propertyMap.entrySet()) {
            final String entryName = platformFilename + "." + entry.getKey() + "."
                    + ModelFileExtension.properties.toString();
            if (zipModel) {
                final ZipOutputStream zipStream = (ZipOutputStream) stream;
                zipStream.putNextEntry(new ZipEntry(FilenameUtils.getName(entryName)));
                entry.getValue().store(zipStream, null);
                zipStream.closeEntry();
            } else {
                // this is really deprecated anyway, but in case we need to bring it back
                // TODO - need to store a bunch of files here if we want to store not in zip
                entry.getValue().store(stream, null);
            }
        }
        break;
    }
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

/**
 * 2jar?,??jar/*from w  w  w . j  a  v  a  2  s . co m*/
 * @param baseJar
 * @param diffJar
 * @param outJar
 */
public static void unionJar(File baseJar, File diffJar, File outJar) throws IOException {
    File outParentFolder = outJar.getParentFile();
    if (!outParentFolder.exists()) {
        outParentFolder.mkdirs();
    }
    List<String> diffEntries = getZipEntries(diffJar);
    FileOutputStream fos = new FileOutputStream(outJar);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(baseJar);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (diffEntries.contains(name)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();

}

From source file:org.bdval.BDVModel.java

/**
 * Store the BDVModel scale mean to the specified output stream.
 *
 * @param stream  The stream to store the properties to
 * @param options The options associated with this model
 * @throws IOException if there is a problem writing to the stream
 */// w  w  w .  j  a v  a2s  .  co  m
private void saveMeansMap(final OutputStream stream, final DAVOptions options) throws IOException {
    probesetScaleMeanMap = options.probesetScaleMeanMap;
    switch (format) {
    case BINARY:
        BinIO.storeObject(probesetScaleMeanMap, stream);
        break;
    case PROPERTIES:
        if (zipModel) {
            final ZipOutputStream zipStream = (ZipOutputStream) stream;
            zipStream.putNextEntry(new ZipEntry(FilenameUtils.getName(meansMapFilename)));
            saveMapAsProperties(probesetScaleMeanMap, zipStream);
            zipStream.closeEntry();
        } else {
            saveMapAsProperties(probesetScaleMeanMap, stream);
        }
        break;
    }
}

From source file:org.bdval.BDVModel.java

/**
 * Store the BDVModel scale range to the specified output stream.
 *
 * @param stream  The stream to store the properties to
 * @param options The options associated with this model
 * @throws IOException if there is a problem writing to the stream
 *///  w w  w  . ja  va  2 s  . c o  m
private void saveRangeMap(final OutputStream stream, final DAVOptions options) throws IOException {
    probesetScaleRangeMap = options.probesetScaleRangeMap;
    switch (format) {
    case BINARY:
        BinIO.storeObject(probesetScaleRangeMap, stream);
        break;
    case PROPERTIES:
        if (zipModel) {
            final ZipOutputStream zipStream = (ZipOutputStream) stream;
            zipStream.putNextEntry(new ZipEntry(FilenameUtils.getName(rangeMapFilename)));
            saveMapAsProperties(probesetScaleRangeMap, zipStream);
            zipStream.closeEntry();
        } else {
            saveMapAsProperties(probesetScaleRangeMap, stream);
        }
        break;
    }
}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

protected void writeSkinZipEntries(String prefix, File dir, ZipOutputStream out) throws IOException {
    if (dir.isDirectory()) {
        if (prefix.length() > 0) {
            prefix = prefix + "/";
        }//from  www .j  a v  a  2 s .  c o  m
        File[] myChildren = dir.listFiles();
        for (File myFile : myChildren) {
            if (myFile.isFile()) {
                writeZipEntry(prefix, out, myFile);
            } else {
                ZipEntry mySkinFile = new ZipEntry(prefix + myFile.getName() + "/");
                mySkinFile.setTime(myFile.lastModified());
                out.putNextEntry(mySkinFile);
                out.write(new byte[0]);
                out.closeEntry();
                writeSkinZipEntries(prefix + myFile.getName(), myFile, out);
            }
        }
    }
}

From source file:com.taobao.android.tpatch.utils.JarSplitUtils.java

public static void splitZip(File inputFile, File outputFile, Set<String> includeEnties) throws IOException {
    if (outputFile.exists()) {
        FileUtils.deleteQuietly(outputFile);
    }/*from w w  w.j a  v a2  s  .  co m*/
    if (null == includeEnties || includeEnties.size() < 1) {
        return;
    }
    FileOutputStream fos = new FileOutputStream(outputFile);
    ZipOutputStream jos = new ZipOutputStream(fos);
    final byte[] buffer = new byte[8192];
    FileInputStream fis = new FileInputStream(inputFile);
    ZipInputStream zis = new ZipInputStream(fis);

    try {
        // loop on the entries of the jar file package and put them in the final jar
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (!includeEnties.contains(name)) {
                continue;
            }
            JarEntry newEntry;
            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }
            // add the entry to the jar archive
            jos.putNextEntry(newEntry);

            // read the content of the entry from the input stream, and write it into the archive.
            int count;
            while ((count = zis.read(buffer)) != -1) {
                jos.write(buffer, 0, count);
            }
            // close the entries for this file
            jos.closeEntry();
            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
    fis.close();
    jos.close();
}

From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java

private void removeFileInZipContaining(List<String> contentFilter, File zipFile)
        throws ZipException, IOException {
    ZipScanner zs = new ZipScanner();
    zs.setSrc(zipFile);/*  w w  w  .  ja  v  a 2s.  c  o  m*/
    String[] includes = { "**/*.process" };
    zs.setIncludes(includes);
    //zs.setCaseSensitive(true);
    zs.init();
    zs.scan();

    File originalProjlib = zipFile; // to be overwritten
    File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read
    FileUtils.copyFile(originalProjlib, tmpProjlib);

    ZipFile listZipFile = new ZipFile(tmpProjlib);
    ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib));
    ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib));

    ZipEntry zipEntry;
    boolean keep;
    while ((zipEntry = readZipFile.getNextEntry()) != null) {
        keep = true;
        for (String filter : contentFilter) {
            keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry));
        }
        //         if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry))
        //          && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) {
        if (keep) {
            writeZipFile.putNextEntry(zipEntry);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = readZipFile.read(buf)) >= 0) {
                writeZipFile.write(buf, 0, len);
            }
            writeZipFile.closeEntry();
            //getLog().info("written");
        } else {
            getLog().info("removed " + zipEntry.getName());
        }

    }

    writeZipFile.close();
    readZipFile.close();
    listZipFile.close();

    originalProjlib.setLastModified(originalProjlib.lastModified() - 100000);
}