Example usage for org.apache.commons.compress.archivers ArchiveStreamFactory ArchiveStreamFactory

List of usage examples for org.apache.commons.compress.archivers ArchiveStreamFactory ArchiveStreamFactory

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers ArchiveStreamFactory ArchiveStreamFactory.

Prototype

ArchiveStreamFactory

Source Link

Usage

From source file:org.apache.tomcat.maven.plugin.tomcat8.run.AbstractStandaloneWarMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (!"war".equals(project.getPackaging())) {
        throw new MojoFailureException("Pacakaging must be of type war for standalone-war goal.");
    }/*from ww  w  .j a v a 2  s .c o  m*/

    File warExecFile = new File(buildDirectory, finalName);
    if (warExecFile.exists()) {
        warExecFile.delete();
    }

    File execWarJar = new File(buildDirectory, finalName);

    FileOutputStream execWarJarOutputStream = null;
    ArchiveOutputStream os = null;
    File tmpPropertiesFile = null;
    File tmpManifestFile = null;
    FileOutputStream tmpPropertiesFileOutputStream = null;
    PrintWriter tmpManifestWriter = null;

    try {
        tmpPropertiesFile = new File(buildDirectory, "war-exec.properties");
        if (tmpPropertiesFile.exists()) {
            tmpPropertiesFile.delete();
        }
        tmpPropertiesFile.getParentFile().mkdirs();

        tmpManifestFile = new File(buildDirectory, "war-exec.manifest");
        if (tmpManifestFile.exists()) {
            tmpManifestFile.delete();
        }
        tmpPropertiesFileOutputStream = new FileOutputStream(tmpPropertiesFile);
        execWarJar.getParentFile().mkdirs();
        execWarJar.createNewFile();
        execWarJarOutputStream = new FileOutputStream(execWarJar);

        tmpManifestWriter = new PrintWriter(tmpManifestFile);

        // store :
        //* wars in the root: foo.war
        //* tomcat jars
        //* file tomcat.standalone.properties with possible values :
        //   * useServerXml=true/false to use directly the one provided
        //   * enableNaming=true/false
        //   * wars=foo.war|contextpath;bar.war  ( |contextpath is optionnal if empty use the war name )
        //   * accessLogValveFormat=
        //   * connectorhttpProtocol: HTTP/1.1 or org.apache.coyote.http11.Http11NioProtocol
        //   * codeSourceContextPath=path parameter, default is project.artifactId
        //* optionnal: conf/ with usual tomcat configuration files
        //* MANIFEST with Main-Class

        Properties properties = new Properties();

        properties.put(Tomcat8Runner.ARCHIVE_GENERATION_TIMESTAMP_KEY,
                Long.toString(System.currentTimeMillis()));
        properties.put(Tomcat8Runner.ENABLE_NAMING_KEY, Boolean.toString(enableNaming));
        properties.put(Tomcat8Runner.ACCESS_LOG_VALVE_FORMAT_KEY, accessLogValveFormat);
        properties.put(Tomcat8Runner.HTTP_PROTOCOL_KEY, connectorHttpProtocol);
        properties.put(Tomcat8Runner.CODE_SOURCE_CONTEXT_PATH, path);

        os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR,
                execWarJarOutputStream);

        extractJarToArchive(new JarFile(projectArtifact.getFile()), os, null);

        if (serverXml != null && serverXml.exists()) {
            os.putArchiveEntry(new JarArchiveEntry("conf/server.xml"));
            IOUtils.copy(new FileInputStream(serverXml), os);
            os.closeArchiveEntry();
            properties.put(Tomcat8Runner.USE_SERVER_XML_KEY, Boolean.TRUE.toString());
        } else {
            properties.put(Tomcat8Runner.USE_SERVER_XML_KEY, Boolean.FALSE.toString());
        }

        os.putArchiveEntry(new JarArchiveEntry("conf/web.xml"));
        IOUtils.copy(getClass().getResourceAsStream("/conf/web.xml"), os);
        os.closeArchiveEntry();

        properties.store(tmpPropertiesFileOutputStream, "created by Apache Tomcat Maven plugin");

        tmpPropertiesFileOutputStream.flush();
        tmpPropertiesFileOutputStream.close();

        os.putArchiveEntry(new JarArchiveEntry(Tomcat8RunnerCli.STAND_ALONE_PROPERTIES_FILENAME));
        IOUtils.copy(new FileInputStream(tmpPropertiesFile), os);
        os.closeArchiveEntry();

        // add tomcat classes
        for (Artifact pluginArtifact : pluginArtifacts) {
            if (StringUtils.equals("org.apache.tomcat", pluginArtifact.getGroupId()) //
                    || StringUtils.equals("org.apache.tomcat.embed", pluginArtifact.getGroupId()) //
                    || StringUtils.equals("org.eclipse.jdt.core.compiler", pluginArtifact.getGroupId()) //
                    || StringUtils.equals("commons-cli", pluginArtifact.getArtifactId()) //
                    || StringUtils.equals("tomcat8-war-runner", pluginArtifact.getArtifactId())) {
                JarFile jarFile = new JarFile(pluginArtifact.getFile());
                extractJarToArchive(jarFile, os, null);
            }
        }

        // add extra dependencies
        if (extraDependencies != null && !extraDependencies.isEmpty()) {
            for (Dependency dependency : extraDependencies) {
                String version = dependency.getVersion();
                if (StringUtils.isEmpty(version)) {
                    version = findArtifactVersion(dependency);
                }

                if (StringUtils.isEmpty(version)) {
                    throw new MojoExecutionException("Dependency '" + dependency.getGroupId() + "':'"
                            + dependency.getArtifactId() + "' does not have version specified");
                }
                // String groupId, String artifactId, String version, String scope, String type
                Artifact artifact = artifactFactory.createArtifact(dependency.getGroupId(), //
                        dependency.getArtifactId(), //
                        version, //
                        dependency.getScope(), //
                        dependency.getType());

                artifactResolver.resolve(artifact, this.remoteRepos, this.local);
                JarFile jarFile = new JarFile(artifact.getFile());
                extractJarToArchive(jarFile, os, excludes);
            }
        }

        Manifest manifest = new Manifest();

        Manifest.Attribute mainClassAtt = new Manifest.Attribute();
        mainClassAtt.setName("Main-Class");
        mainClassAtt.setValue(mainClass);
        manifest.addConfiguredAttribute(mainClassAtt);

        manifest.write(tmpManifestWriter);
        tmpManifestWriter.flush();
        tmpManifestWriter.close();

        os.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
        IOUtils.copy(new FileInputStream(tmpManifestFile), os);
        os.closeArchiveEntry();

        if (attachArtifact) {
            //MavenProject project, String artifactType, String artifactClassifier, File artifactFile
            projectHelper.attachArtifact(project, attachArtifactClassifierType, attachArtifactClassifier,
                    execWarJar);
        }

        if (extraResources != null) {
            for (ExtraResource extraResource : extraResources) {

                DirectoryScanner directoryScanner = new DirectoryScanner();
                directoryScanner.setBasedir(extraResource.getDirectory());
                directoryScanner.addDefaultExcludes();
                directoryScanner.setExcludes(toStringArray(extraResource.getExcludes()));
                directoryScanner.setIncludes(toStringArray(extraResource.getIncludes()));
                directoryScanner.scan();
                for (String includeFile : directoryScanner.getIncludedFiles()) {
                    getLog().debug("include file:" + includeFile);
                    os.putArchiveEntry(new JarArchiveEntry(includeFile));
                    IOUtils.copy(new FileInputStream(new File(extraResource.getDirectory(), includeFile)), os);
                    os.closeArchiveEntry();
                }
            }
        }

        if (tomcatConfigurationFilesDirectory != null && tomcatConfigurationFilesDirectory.exists()) {
            // Because its the tomcat default dir for configs
            String aConfigOutputDir = "conf/";
            copyDirectoryContentIntoArchive(tomcatConfigurationFilesDirectory, aConfigOutputDir, os);
        }
    } catch (ManifestException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArchiveException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(tmpManifestWriter);
        IOUtils.closeQuietly(execWarJarOutputStream);
        IOUtils.closeQuietly(tmpPropertiesFileOutputStream);
    }

}

From source file:org.beangle.commons.archiver.ZipUtils.java

public static File zip(List<String> fileNames, String zipPath, String encoding) {
    try {//from   w  ww .  j  a  v  a2  s.  c  om
        FileOutputStream f = new FileOutputStream(zipPath);
        ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, f);
        if (null != encoding) {
            zos.setEncoding(encoding);
        }
        for (int i = 0; i < fileNames.size(); i++) {
            String fileName = fileNames.get(i);
            String entryName = StringUtils.substringAfterLast(fileName, File.separator);
            ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
            zos.putArchiveEntry(entry);
            FileInputStream fis = new FileInputStream(fileName);
            IOUtils.copy(fis, zos);
            fis.close();
            zos.closeArchiveEntry();
        }
        zos.close();
        return new File(zipPath);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.beangle.ems.util.ZipUtils.java

/**
 * <p>//  w w w .ja v a 2  s . c  om
 * zip.
 * </p>
 * 
 * @param fileNames a {@link java.util.List} object.
 * @param zipPath a {@link java.lang.String} object.
 * @param encoding a {@link java.lang.String} object.
 * @return a {@link java.io.File} object.
 */
public static File zip(List<String> fileNames, String zipPath, String encoding) {
    try {
        FileOutputStream f = new FileOutputStream(zipPath);
        ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, f);
        if (null != encoding) {
            zos.setEncoding(encoding);
        }
        for (int i = 0; i < fileNames.size(); i++) {
            String fileName = fileNames.get(i);
            String entryName = Strings.substringAfterLast(fileName, File.separator);
            ZipArchiveEntry entry = new ZipArchiveEntry(entryName);
            zos.putArchiveEntry(entry);
            FileInputStream fis = new FileInputStream(fileName);
            IOs.copy(fis, zos);
            fis.close();
            zos.closeArchiveEntry();
        }
        zos.close();
        return new File(zipPath);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.betaconceptframework.astroboa.engine.jcr.io.SerializationBean.java

private void serializeContentToZip(SerializationReport serializationReport, Session session,
        SerializationConfiguration serializationConfiguration, String filePath, String filename,
        ContentObjectCriteria contentObjectCriteria) throws Exception {

    File zipFile = createSerializationFile(filePath, filename);

    OutputStream out = null;//from w  w w.  j av  a2s .co m
    ZipArchiveOutputStream os = null;

    try {
        out = new FileOutputStream(zipFile);
        os = (ZipArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

        os.setFallbackToUTF8(true);

        addContentToZip(os, serializationReport, session, serializationConfiguration, filename,
                contentObjectCriteria);

        os.finish();
        os.close();
    } catch (Exception e) {
        serializationReport.getErrors().add(e.getMessage());

        throw e;
    } finally {

        if (out != null) {
            org.apache.commons.io.IOUtils.closeQuietly(out);

            out = null;
        }

        if (os != null) {
            org.apache.commons.io.IOUtils.closeQuietly(os);

            os = null;
        }

        if (CollectionUtils.isNotEmpty(serializationReport.getErrors())) {
            //Delete zipfile
            if (zipFile != null && zipFile.exists()) {
                zipFile.delete();
            }
        }

        zipFile = null;

    }

}

From source file:org.betaconceptframework.astroboa.test.engine.AbstractRepositoryTest.java

protected void serializeUsingJCR(CmsEntityType cmsEntity) {

     long start = System.currentTimeMillis();

     String repositoryHomeDir = AstroboaClientContextHolder.getActiveClientContext().getRepositoryContext()
             .getCmsRepository().getRepositoryHomeDirectory();

     File serializationHomeDir = new File(
             repositoryHomeDir + File.separator + CmsConstants.SERIALIZATION_DIR_NAME);

     File zipFile = new File(serializationHomeDir,
             "document" + DateUtils.format(Calendar.getInstance(), "ddMMyyyyHHmmss.sss") + ".zip");

     OutputStream out = null;//from w w w .  j  ava 2  s . c o  m
     ZipArchiveOutputStream os = null;

     try {

         if (!zipFile.exists()) {
             FileUtils.touch(zipFile);
         }

         out = new FileOutputStream(zipFile);
         os = (ZipArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

         os.setFallbackToUTF8(true);

         //Serialize all repository using JCR
         os.putArchiveEntry(new ZipArchiveEntry("document-view.xml"));

         final Session session = getSession();

         switch (cmsEntity) {
         case OBJECT:
             session.exportDocumentView(JcrNodeUtils.getContentObjectRootNode(session).getPath(), os, false,
                     false);
             break;
         case REPOSITORY_USER:
             session.exportDocumentView(JcrNodeUtils.getRepositoryUserRootNode(session).getPath(), os, false,
                     false);
             break;
         case TAXONOMY:
             session.exportDocumentView(JcrNodeUtils.getTaxonomyRootNode(session).getPath(), os, false, false);
             break;
         case ORGANIZATION_SPACE:
             session.exportDocumentView(JcrNodeUtils.getOrganizationSpaceNode(session).getPath(), os, false,
                     false);
             break;
         case REPOSITORY:
             session.exportDocumentView(JcrNodeUtils.getCMSSystemNode(session).getPath(), os, false, false);
             break;

         default:
             break;
         }

         os.closeArchiveEntry();

         os.finish();
         os.close();

     } catch (Exception e) {
         throw new CmsException(e);
     } finally {
         if (out != null) {
             IOUtils.closeQuietly(out);
         }

         if (os != null) {
             IOUtils.closeQuietly(os);
         }
         long serialzationDuration = System.currentTimeMillis() - start;

         logger.debug("Export entities using JCR finished in {} ",
                 DurationFormatUtils.formatDurationHMS(serialzationDuration));
     }
 }

From source file:org.dataconservancy.packaging.impl.OpenPackageService.java

/**
 * Extract contents of an archive.//from w w  w.  j  a  va  2 s  .  c om
 *
 * @param dest_dir Destination to write archive content.
 * @param is Archive file.
 * @return Name of package base directory in dest_dir
 * @throws ArchiveException if there is an error creating the ArchiveInputStream
 * @throws IOException if there is more than one package root
 */
private String extract(final File dest_dir, final InputStream i) throws ArchiveException, IOException {
    // Apache commons compress requires buffered input streams

    InputStream is;

    try {
        is = new CompressorStreamFactory().createCompressorInputStream(new BufferedInputStream(i));
    } catch (final CompressorException e) {
        throw new IOException("Could not create compressed input stream", e);
    }

    // Extract entries from archive

    if (!is.markSupported()) {
        is = new BufferedInputStream(is);
    }

    String archive_base = null;

    final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(is);
    ArchiveEntry entry;

    while ((entry = ais.getNextEntry()) != null) {

        final File file = extract(dest_dir, entry, ais);

        final String root = get_root_file_name(file);

        if (archive_base == null) {
            archive_base = root;
        } else if (!archive_base.equals(root)) {
            throw new IOException("Package has more than one base directory.");
        }
    }

    return archive_base;
}

From source file:org.dataconservancy.packaging.tool.impl.BOREMPackageGeneratorTest.java

/**
 * Tests generating a well formed package, with all required parameters and the following options:
 * <ul>/*w  w w  . j av  a 2s  .  c om*/
 *     <li>checksum alg: md5</li>
 *     <li>compression-format: gz</li>
 *     <li>archiving-format: not specified</li>
 * </ul>
 *
 * <p/>
 *
 * Expects the de-compressed, deserialized package to contain:
 * <ul>
 *     <li>bag-info.txt file: Besides the input parameters, bag-info.txt file is expected to contain reference
 *     to the ReM of the whole package, expressed in PKG-ORE-REM parameter</li>
 *     <li>bagit.txt file</li>
 *     <li>manifest-<checksumalg>.txt files</checksumalg></li>
 *     <li>tagmanifest-<checksumalg>.txt files</checksumalg></li>
 *     <li>data/ folder</li>
 *     <li>payload files in data/ folder</li>
 *     <li>ORE-REM folder</li>
 *     <li>description files in ORE-REM/folder</li>
 * </ul>
 *
 *
 * @throws CompressorException
 * @throws ArchiveException
 * @throws IOException
 */
@Test
public void testGeneratingAGoodPackage() throws CompressorException, ArchiveException, IOException {
    params.addParam(GeneralParameterNames.PACKAGE_FORMAT_ID, PackagingFormat.BOREM.toString());
    params.addParam(GeneralParameterNames.PACKAGE_NAME, packageName);
    params.addParam(GeneralParameterNames.PACKAGE_LOCATION, packageLocationName);
    params.addParam(GeneralParameterNames.PACKAGE_STAGING_LOCATION, packageStagingLocationName);
    params.addParam(BagItParameterNames.BAGIT_PROFILE_ID, bagItProfileId);
    params.addParam(BagItParameterNames.CONTACT_NAME, contactName);
    params.addParam(BagItParameterNames.CONTACT_EMAIL, contactEmail);
    params.addParam(BagItParameterNames.CONTACT_PHONE, contactPhone);
    params.addParam(GeneralParameterNames.CHECKSUM_ALGORITHMS, checksumAlg);
    params.addParam(BagItParameterNames.COMPRESSION_FORMAT, compressionFormat);
    params.addParam(BagItParameterNames.PKG_BAG_DIR, packageName);
    // params.addParam(GeneralParameterNames.CONTENT_ROOT_LOCATION, pkgBagDir);
    params.addParam(GeneralParameterNames.CONTENT_ROOT_LOCATION, contentRootLocation);
    Package resultedPackage = underTest.generatePackage(desc, params);

    //Decompress and de archive files
    CompressorInputStream cis = new CompressorStreamFactory()
            .createCompressorInputStream(CompressorStreamFactory.GZIP, resultedPackage.serialize());
    TarArchiveInputStream ais = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream(ArchiveStreamFactory.TAR, cis);

    //get files from archive
    Set<String> files = new HashSet<String>();
    ArchiveEntry entry = ais.getNextEntry();
    while (entry != null) {
        files.add(entry.getName().replace("\\", "/"));
        if (entry.getName().equals(packageName + "/bag-info.txt") && ais.canReadEntryData(entry)) {
            verifyBagInfoContent(ais);
        }
        if (entry.getName()
                .equals(packageName + "/data/ProjectOne/Collection One/DataItem One/" + dataFileOneName)) {
            compareDataFile(ais, pathToFileOne);
        }
        if (entry.getName()
                .equals(packageName + "/data/ProjectOne/Collection One/DataItem One/" + dataFileTwoName)) {
            compareDataFile(ais, pathToFileTwo);
        }
        entry = ais.getNextEntry();
    }
    assertTrue(files.contains(packageName + "/bag-info.txt"));
    assertTrue(files.contains(packageName + "/bagit.txt"));
    assertTrue(files.contains(packageName + "/tagmanifest-md5.txt"));
    assertTrue(files.contains(packageName + "/manifest-md5.txt"));
    assertTrue(files.contains(packageName + "/data/"));
    assertTrue(files.contains(packageName + "/data/ProjectOne/Collection One/DataItem One/" + dataFileOneName));
    assertTrue(files.contains(packageName + "/data/ProjectOne/Collection One/DataItem One/" + dataFileTwoName));
    assertTrue(files.contains(packageName + "/ORE-REM/"));

    assertTrue(SupportedMimeTypes.getMimeType(compressionFormat).contains(resultedPackage.getContentType()));

}

From source file:org.dataconservancy.packaging.tool.impl.generator.BagItPackageAssembler.java

private File archiveBag() throws PackageToolException {
    File archivedFile = new File(packageLocationDir, bagBaseDir.getName() + "." + archivingFormat);
    try {/*from   ww  w.j  a v  a 2  s  .c  o m*/
        FileOutputStream fos = new FileOutputStream(archivedFile);
        ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream(archivingFormat,
                new BufferedOutputStream(fos));
        if (aos instanceof TarArchiveOutputStream) {
            ((TarArchiveOutputStream) aos).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        }
        // Get to putting all the files in the compressed output file
        for (File f : bagBaseDir.listFiles()) {
            //To support the cancelling of package creation we check here to see if the thread has been interrupted.
            if (Thread.currentThread().isInterrupted()) {
                break;
            }
            addFilesToArchive(aos, f);
        }
        aos.close();
        fos.close();
    } catch (FileNotFoundException e) {
        throw new PackageToolException(PackagingToolReturnInfo.PKG_FILE_NOT_FOUND_EXCEPTION, e,
                "Exception occurred when serializing the bag.");
    } catch (IOException e) {
        throw new PackageToolException(PackagingToolReturnInfo.PKG_IO_EXCEPTION, e,
                "Exception occurred when serializing the bag.");
    } catch (ArchiveException e) {
        throw new PackageToolException(PackagingToolReturnInfo.PKG_ASSEMBLER_ARCHIVE_EXP, e,
                "Archiving format \"" + archivingFormat + "\" is not supported.");
    }

    return archivedFile;
}

From source file:org.dataconservancy.packaging.tool.impl.generator.BagItPackageAssemblerTest.java

/**
 * Test assembling a bag which contain a data file and a metadata file.
 * @throws IOException/* w  w w  .j a  v  a2  s.  co  m*/
 */
private void testAssembleBag_TAR_GZIP(String dataFileName)
        throws IOException, CompressorException, ArchiveException {
    PackageGenerationParameters params = new PackageGenerationParameters();
    setupCommonPackageParams(params);
    params.addParam(GeneralParameterNames.ARCHIVING_FORMAT, ArchiveStreamFactory.TAR);
    params.addParam(GeneralParameterNames.COMPRESSION_FORMAT, CompressorStreamFactory.GZIP);
    params.addParam(GeneralParameterNames.CHECKSUM_ALGORITHMS, checksumAlg);
    params.addParam(GeneralParameterNames.CHECKSUM_ALGORITHMS, "sha1");

    underTest = new BagItPackageAssembler();
    underTest.init(params);

    //Reserve a URI for data file
    String filePath = "myProject/" + dataFileName;
    URI result = underTest.reserveResource(filePath, PackageResourceType.DATA);
    String expectedURI = "file:///" + packageName + "/" + "data" + "/" + filePath;
    log.debug("URI expected: " + expectedURI);
    log.debug("URI result: " + result.toString());
    assertTrue(expectedURI.equals(result.toString()));

    //Put content into the space specified by the URI
    String fileContent = "This is the data file. data data data data data data data data data data data data.";
    underTest.putResource(result, new ByteArrayInputStream(fileContent.getBytes()));

    //Reserve a URI for metadata file
    filePath = "metadataFile.txt";
    result = underTest.reserveResource(filePath, PackageResourceType.METADATA);
    expectedURI = "file:///" + packageName + "/" + filePath;
    assertTrue(expectedURI.equals(result.toString()));

    //Put content into the space specified by the URI
    fileContent = "This is the metadata file. metadata metadata metadata metadata metadata metadata metadata .";
    underTest.putResource(result, new ByteArrayInputStream(fileContent.getBytes()));

    Package pkg = underTest.assemblePackage();

    CompressorInputStream cis = new CompressorStreamFactory()
            .createCompressorInputStream(CompressorStreamFactory.GZIP, pkg.serialize());
    ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.TAR, cis);

    Set<String> files = new HashSet<String>();
    ArchiveEntry entry = ais.getNextEntry();
    while (entry != null) {
        files.add(entry.getName().replace("\\", "/"));
        entry = ais.getNextEntry();
    }

    //Make sure that the packageName is set properly (packageName + contentype extension)
    String expectedPackageName = packageName.concat(".tar").concat(".gz");
    Assert.assertEquals(expectedPackageName, pkg.getPackageName());

    // There should be 10 files: the 2 files above, bagit.txt, bag-info.txt
    // directories data and data/myProject, 2 manifest files and 2 tag-manifest files
    assertEquals(10, files.size());

    // make sure that expected files are in there
    String pathSep = "/";
    String bagFilePath = packageName + pathSep;
    assertTrue(files.contains(bagFilePath + "bagit.txt"));
    assertTrue(files.contains(bagFilePath + "bag-info.txt"));
    assertTrue(files.contains(bagFilePath + "metadataFile.txt"));
    assertTrue(files.contains(bagFilePath + "data" + pathSep));
    assertTrue(files.contains(bagFilePath + "data" + pathSep + "myProject" + pathSep));
    assertTrue(files.contains(bagFilePath + "data" + pathSep + "myProject" + pathSep + dataFileName));
}

From source file:org.dataconservancy.packaging.tool.impl.generator.BagItPackageAssemblerTest.java

/**
 * Test assembling a bag which contain a data file and a metadata file with ZIP format
 * @throws IOException/*  w ww  .  j a  va2  s  .  c  om*/
 */
@Test
public void testAssembleZipBag() throws IOException, CompressorException, ArchiveException {
    PackageGenerationParameters params = new PackageGenerationParameters();
    setupCommonPackageParams(params);
    params.addParam(GeneralParameterNames.ARCHIVING_FORMAT, ArchiveStreamFactory.ZIP);
    params.addParam(GeneralParameterNames.CHECKSUM_ALGORITHMS, checksumAlg);
    params.addParam(GeneralParameterNames.CHECKSUM_ALGORITHMS, "sha1");

    underTest = new BagItPackageAssembler();
    underTest.init(params);

    //Reserve a URI for data file
    String filePath = "myProject/dataFile.txt";
    URI result = underTest.reserveResource(filePath, PackageResourceType.DATA);
    String expectedURI = "file:///" + packageName + "/" + "data" + "/" + filePath;
    log.debug("URI expected: " + expectedURI);
    log.debug("URI result: " + result.toString());
    assertTrue(expectedURI.equals(result.toString()));

    //Put content into the space specified by the URI
    String fileContent = "This is the data file. data data data data data data data data data data data data.";
    underTest.putResource(result, new ByteArrayInputStream(fileContent.getBytes()));

    //Reserve a URI for metadata file
    filePath = "metadataFile.txt";
    result = underTest.reserveResource(filePath, PackageResourceType.METADATA);
    expectedURI = "file:///" + packageName + "/" + filePath;
    assertTrue(expectedURI.equals(result.toString()));

    //Put content into the space specified by the URI
    fileContent = "This is the metadata file. metadata metadata metadata metadata metadata metadata metadata .";
    underTest.putResource(result, new ByteArrayInputStream(fileContent.getBytes()));

    Package pkg = underTest.assemblePackage();

    ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP,
            pkg.serialize());

    Set<String> files = new HashSet<String>();
    ArchiveEntry entry = ais.getNextEntry();
    while (entry != null) {
        files.add(entry.getName().replace("\\", "/"));
        entry = ais.getNextEntry();
    }

    //Make sure that the packageName is set properly (packageName + contentype extension)
    String expectedPackageName = packageName.concat(".zip");
    Assert.assertEquals(expectedPackageName, pkg.getPackageName());

    // There should be 10 files: the 2 files above, bagit.txt, bag-info.txt
    // directories data and data/myProject, 2 manifest files and 2 tag-manifest files
    assertEquals(10, files.size());

    // make sure that expected files are in there
    String pathSep = "/";
    String bagFilePath = packageName + pathSep;
    assertTrue(files.contains(bagFilePath + "bagit.txt"));
    assertTrue(files.contains(bagFilePath + "bag-info.txt"));
    assertTrue(files.contains(bagFilePath + "metadataFile.txt"));
    assertTrue(files.contains(bagFilePath + "data" + pathSep));
    assertTrue(files.contains(bagFilePath + "data" + pathSep + "myProject" + pathSep));
    assertTrue(files.contains(bagFilePath + "data" + pathSep + "myProject" + pathSep + "dataFile.txt"));
}