Example usage for org.apache.commons.compress.archivers ArchiveOutputStream closeArchiveEntry

List of usage examples for org.apache.commons.compress.archivers ArchiveOutputStream closeArchiveEntry

Introduction

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

Prototype

public abstract void closeArchiveEntry() throws IOException;

Source Link

Document

Closes the archive entry, writing any trailer information that may be required.

Usage

From source file:big.BigZip.java

/**
 * Requires an InputStream, it will calculate the SHA1 checksum at the same
 * time that it writes data onto the big file. The input stream is expected
 * to be closed outside of this method./*from w  ww  . j a v  a 2 s.c om*/
 * @param stream
 * @param filePathToWriteInTextLine
 * @throws java.io.IOException 
 */
public void quickWriteStreamStandalone(final InputStream stream, final String filePathToWriteInTextLine)
        throws Exception {
    // declare
    ByteArrayOutputStream outputZipStream = new ByteArrayOutputStream();
    ByteArrayInputStream byteInput = null;
    // Create Archive Output Stream that attaches File Output Stream / and specifies type of compression
    ArchiveOutputStream logical_zip = new ArchiveStreamFactory()
            .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputZipStream);
    // Create Archive entry - write header information
    ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(filePathToWriteInTextLine);
    logical_zip.putArchiveEntry(zipArchiveEntry);
    // prepare the SHA1 signature generation
    final MessageDigest hash = MessageDigest.getInstance("SHA1");

    // Copy input file
    byte[] buffer = new byte[16384];
    int length;

    // decompress from the original zip file, compress to our zip format
    // calculate the SHA1 signature on the same loop to save resource
    while ((length = stream.read(buffer)) > 0) {
        logical_zip.write(buffer, 0, length);
        hash.update(buffer, 0, length);
    }

    // compute the file signature
    byte[] digest = hash.digest();
    final String SHA1 = utils.hashing.checksum.convertHash(digest);

    // close the zip related objects
    logical_zip.closeArchiveEntry();
    logical_zip.finish();
    logical_zip.flush();
    logical_zip.close();
    logical_zip = null;

    // define the line that will be written on the index file
    final String line = "\n".concat(utils.files.getPrettyFileSize(currentPosition)).concat(" ").concat(SHA1)
            .concat(" ").concat(filePathToWriteInTextLine);

    // get the bytes
    byteInput = new ByteArrayInputStream(outputZipStream.toByteArray());
    int counter = 0;

    // add the magic number to this file block
    outputStream.write(magicSignature.getBytes());
    // now copy the whole file into the BIG archive
    while ((length = byteInput.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
        counter += length;
    }
    // write a new line in our index file
    writerFileIndex.write(line);
    // increase the position counter
    currentPosition += counter + magicSignature.length();
    // close the streams that were created
    byteInput.close();
    outputZipStream.close();
}

From source file:fr.ortolang.diffusion.api.content.ContentResource.java

private void exportToArchive(String key, ArchiveOutputStream aos, ArchiveEntryFactory factory, PathBuilder path,
        boolean followsymlink, Pattern pattern)
        throws OrtolangException, KeyNotFoundException, BrowserServiceException, ExportToArchiveIOException {
    OrtolangObject object;//www .ja v a2 s  . c o  m
    try {
        object = browser.findObject(key);
    } catch (BrowserServiceException e) {
        return;
    }
    OrtolangObjectInfos infos = browser.getInfos(key);
    String type = object.getObjectIdentifier().getType();

    switch (type) {
    case Collection.OBJECT_TYPE:
        try {
            Set<CollectionElement> elements = ((Collection) object).getElements();
            ArchiveEntry centry = factory.createArchiveEntry(path.build() + "/",
                    infos.getLastModificationDate(), 0L);
            try {
                aos.putArchiveEntry(centry);
                for (CollectionElement element : elements) {
                    try {
                        PathBuilder pelement = path.clone().path(element.getName());
                        exportToArchive(element.getKey(), aos, factory, pelement, followsymlink, pattern);
                    } catch (InvalidPathException e) {
                        LOGGER.log(Level.SEVERE, "unexpected error during export to zip !!", e);
                    }
                }
            } catch (IOException e) {
                throw new ExportToArchiveIOException(
                        "unable to put archive entry for collection at path: " + path.build(), e);
            }
        } finally {
            try {
                aos.closeArchiveEntry();
            } catch (IOException e) {
                LOGGER.log(Level.FINEST, "unable to close archive entry for collection at path [" + path.build()
                        + "]: " + e.getMessage());
            }
        }
        break;
    case DataObject.OBJECT_TYPE:
        if (pattern != null && !pattern.matcher(object.getObjectName()).matches()) {
            return;
        }
        try (InputStream input = core.download(object.getObjectKey())) {
            DataObject dataObject = (DataObject) object;
            ArchiveEntry oentry = factory.createArchiveEntry(path.build(), infos.getLastModificationDate(),
                    dataObject.getSize());
            try {
                aos.putArchiveEntry(oentry);
                IOUtils.copy(input, aos);
            } catch (IOException e) {
                throw new ExportToArchiveIOException("unable to export dataobject at path: " + path.build(), e);
            } finally {
                try {
                    aos.closeArchiveEntry();
                } catch (IOException e) {
                    throw new ExportToArchiveIOException(
                            "unable to close archive entry for collection at path: " + path.build(), e);
                }
            }
        } catch (IOException e) {
            throw new ExportToArchiveIOException(
                    "unable to get input stream for dataobject at path: " + path.build(), e);
        } catch (AccessDeniedException e) {
            return;
        } catch (CoreServiceException | DataNotFoundException e) {
            LOGGER.log(Level.SEVERE, "unexpected error during export to zip", e);
        }
        break;
    case Link.OBJECT_TYPE:
        if (followsymlink) {
            LOGGER.log(Level.SEVERE, "link export is not managed yet");
            // TODO in case of following symlink, add cyclic detection
        }
        break;
    }
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writeOpf(String tname, List<String> allPages, ArchiveOutputStream out) {
    String pofTemplate = getTemplate(epubPath + AONE_OPF);
    StringBuilder sbItems = new StringBuilder();
    StringBuilder sbItemrefs = new StringBuilder();
    sbItems.append("<item id=\"css\" href=\"aone.css\" media-type=\"text/css\" />\n");
    sbItems.append("<item id=\"cover\" href=\"cover.jpg\" media-type=\"image/jpeg\" />\n");
    if (null != tname) {
        sbItems.append("<item id=\"index\" href=\"overview.html\" media-type=\"application/xhtml+xml\" />\n");
        sbItemrefs.append("<itemref idref=\"index\" />\n");
    }//from   ww w .  j av  a  2s .c om
    Iterator<String> it = allPages.iterator();
    while (it.hasNext()) {
        String str = it.next();
        if (str.contains("/index.html")) {
            String tagname = getIDFromResPath(str);
            String path = str.substring(str.indexOf("/") + 1, str.length());
            sbItems.append("<item id=\"" + tagname + "\" href=\"" + path
                    + "\" media-type=\"application/xhtml+xml\" />\n");
            sbItemrefs.append("<itemref idref=\"" + tagname + "\" />\n");
        } else {
            String pid = getIDFromResPath(str);
            sbItems.append(
                    "<item id=\"" + pid + "\" href=\"" + str + "\" media-type=\"application/xhtml+xml\" />\n");
            sbItemrefs.append("<itemref idref=\"" + pid + "\" />\n");
        }
    }
    sbItems.append("<item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\" />");
    pofTemplate = pofTemplate.replace("ITEMS", sbItems.toString());
    pofTemplate = pofTemplate.replace("ITEMREFS", sbItemrefs.toString());
    InputStream in = new ByteArrayInputStream(pofTemplate.getBytes());
    try {
        String entry = null != tname ? tname + "/aone.opf" : "aone.opf";
        out.putArchiveEntry(new ZipArchiveEntry(entry));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:net.duckling.ddl.service.export.impl.ExportServiceImpl.java

private void writeNcx(String tname, List<String> allPages, Map<String, String> id2Title,
        ArchiveOutputStream out) {
    String ncxTemplate = getTemplate(epubPath + TOC_NCX);
    if (null != tname) {
        ncxTemplate = ncxTemplate.replace("DOCTITLE", "" + tname);
        ncxTemplate = ncxTemplate.replace("DOCAUTHOR", "" + tname);
    }/*from w  w w.  ja  va2s . c o m*/
    StringBuilder sb = new StringBuilder();
    int playOrder = 0;
    if (null != tname) {
        sb.append("<navPoint id=\"nv-catalog\" playOrder=\"" + (++playOrder) + "\">\n"
                + "<navLabel><text></text></navLabel>\n<content src=\"overview.html\"/>\n</navPoint>\n");
    }
    int len = allPages.size();
    for (int par = 0; par < len; par++) {
        String str = allPages.get(par);
        if (str.contains("/index.html")) {
            String tagName = getTagNameFromResPath(str);
            String path = str.substring(str.indexOf("/") + 1, str.length());
            playOrder++;
            sb.append("<navPoint id=\"nv-" + playOrder + "\" playOrder=\"" + playOrder + "\">\n<navLabel><text>"
                    + tagName + "</text></navLabel>\n<content src=\"" + path + "\"/>\n");
            for (int child = par + 1; child < len; child++) {
                String item = allPages.get(child);
                if (item.contains("index")) {
                    break;
                }
                String pageTitle = id2Title.get(item);
                playOrder++;
                sb.append("<navPoint id=\"nv-" + playOrder + "\" playOrder=\"" + playOrder
                        + "\">\n<navLabel><text>" + pageTitle + "</text></navLabel>\n<content src=\"" + item
                        + "\"/>\n</navPoint>\n");
            }
            sb.append("</navPoint>\n");
        }
    }
    ncxTemplate = ncxTemplate.replace("NAV_POINTS", sb.toString());
    InputStream in = new ByteArrayInputStream(ncxTemplate.getBytes());
    try {
        String entry = null != tname ? tname + "/toc.ncx" : "toc.ncx";
        out.putArchiveEntry(new ZipArchiveEntry(entry));
        IOUtils.copy(in, out);
        in.close();
        out.closeArchiveEntry();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

From source file:org.apache.ant.compress.taskdefs.ArchiveBase.java

/**
 * Creates the archive archiving the given resources.
 *//*from  w  w w .  j a  v  a2s.  c om*/
protected void writeArchive(Collection/*<ResourceWithFlags>*/ src) throws IOException {
    ArchiveOutputStream out = null;
    Set addedDirectories = new HashSet();
    try {
        String enc = Expand.NATIVE_ENCODING.equals(getEncoding()) ? null : getEncoding();
        out = StreamHelper.getOutputStream(factory, getDest(), enc);
        if (out == null) {
            out = factory.getArchiveStream(new BufferedOutputStream(getDest().getOutputStream()), enc);
        }
        for (Iterator i = src.iterator(); i.hasNext();) {
            ResourceWithFlags r = (ResourceWithFlags) i.next();

            if (!isFilesOnly()) {
                ensureParentDirs(out, r, addedDirectories);
            }

            ArchiveEntry ent = entryBuilder.buildEntry(r);
            out.putArchiveEntry(ent);
            if (!r.getResource().isDirectory()) {
                InputStream in = null;
                try {
                    in = r.getResource().getInputStream();
                    IOUtils.copy(in, out);
                } finally {
                    FILE_UTILS.close(in);
                }
            } else {
                addedDirectories.add(r.getName());
            }
            out.closeArchiveEntry();

        }
    } finally {
        FILE_UTILS.close(out);
    }
}

From source file:org.apache.ant.compress.taskdefs.ArchiveBase.java

/**
 * Adds records for all parent directories of the given resource
 * that haven't already been added./*from   w  ww . j  a v  a  2 s . c o m*/
 *
 * <p>Flags for the "missing" directories will be taken from the
 * ResourceCollection that contains the resource to be added.</p>
 */
protected void ensureParentDirs(ArchiveOutputStream out, ResourceWithFlags r, Set directoriesAdded)
        throws IOException {

    String[] parentStack = FileUtils.getPathStack(r.getName());
    String currentParent = "";
    int skip = r.getName().endsWith("/") ? 2 : 1;
    for (int i = 0; i < parentStack.length - skip; i++) {
        if ("".equals(parentStack[i]))
            continue;
        currentParent += parentStack[i] + "/";
        if (directoriesAdded.add(currentParent)) {
            Resource dir = new Resource(currentParent, true, System.currentTimeMillis(), true);
            ResourceWithFlags artifical = new ResourceWithFlags(currentParent, dir, r.getCollectionFlags(),
                    new ResourceFlags());
            ArchiveEntry ent = entryBuilder.buildEntry(artifical);
            out.putArchiveEntry(ent);
            out.closeArchiveEntry();
        }
    }
}

From source file:org.apache.gobblin.service.modules.orchestration.AzkabanJobHelper.java

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "OBL_UNSATISFIED_OBLIGATION", justification = "Lombok construct of @Cleanup is handing this, but not detected by FindBugs")
private static void addFilesToZip(File zipFile, List<File> filesToAdd) throws IOException {
    try {// w ww  .ja  va2  s .c  o m
        @Cleanup
        OutputStream archiveStream = new FileOutputStream(zipFile);
        @Cleanup
        ArchiveOutputStream archive = new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, archiveStream);

        for (File fileToAdd : filesToAdd) {
            ZipArchiveEntry entry = new ZipArchiveEntry(fileToAdd.getName());
            archive.putArchiveEntry(entry);

            @Cleanup
            BufferedInputStream input = new BufferedInputStream(new FileInputStream(fileToAdd));
            IOUtils.copy(input, archive);
            archive.closeArchiveEntry();
        }

        archive.finish();
    } catch (ArchiveException e) {
        throw new IOException("Issue with creating archive", e);
    }
}

From source file:org.apache.openejb.maven.plugin.ExecMojo.java

private void createExecutableJar() throws Exception {
    mkdirs(execFile.getParentFile());/*from   w ww .  ja v  a 2s  .co  m*/

    final Properties config = new Properties();
    config.put("distribution", distributionName);
    config.put("workingDir", runtimeWorkingDir);
    config.put("command", script);
    final List<String> jvmArgs = generateJVMArgs();

    final String catalinaOpts = toString(jvmArgs);
    config.put("catalinaOpts", catalinaOpts);
    config.put("timestamp", Long.toString(System.currentTimeMillis()));
    // java only
    final String cp = getAdditionalClasspath();
    if (cp != null) {
        config.put("additionalClasspath", cp);
    }
    config.put("shutdownCommand", tomeeShutdownCommand);
    int i = 0;
    boolean encodingSet = catalinaOpts.contains("-Dfile.encoding");
    for (final String jvmArg : jvmArgs) {
        config.put("jvmArg." + i++, jvmArg);
        encodingSet = encodingSet || jvmArg.contains("-Dfile.encoding");
    }
    if (!encodingSet) { // forcing encoding for launched process to be able to read conf files
        config.put("jvmArg." + i, "-Dfile.encoding=UTF-8");
    }

    // create an executable jar with main runner and zipFile
    final FileOutputStream fileOutputStream = new FileOutputStream(execFile);
    final ArchiveOutputStream os = new ArchiveStreamFactory()
            .createArchiveOutputStream(ArchiveStreamFactory.JAR, fileOutputStream);

    { // distrib
        os.putArchiveEntry(new JarArchiveEntry(distributionName));
        final FileInputStream in = new FileInputStream(zipFile);
        try {
            IOUtils.copy(in, os);
            os.closeArchiveEntry();
        } finally {
            IOUtil.close(in);
        }
    }

    { // config
        os.putArchiveEntry(new JarArchiveEntry("configuration.properties"));
        final StringWriter writer = new StringWriter();
        config.store(writer, "");
        IOUtils.copy(new ByteArrayInputStream(writer.toString().getBytes("UTF-8")), os);
        os.closeArchiveEntry();
    }

    { // Manifest
        final Manifest manifest = new Manifest();

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

        final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
        manifest.write(baos);

        os.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
        IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), os);
        os.closeArchiveEntry();
    }

    { // Main + utility
        for (final Class<?> clazz : asList(ExecRunner.class, Files.class, Files.PatternFileFilter.class,
                Files.DeleteThread.class, Files.FileRuntimeException.class,
                Files.FileDoesNotExistException.class, Files.NoopOutputStream.class,
                LoaderRuntimeException.class, Pipe.class, IO.class, Zips.class, JarLocation.class,
                RemoteServer.class, RemoteServer.CleanUpThread.class, OpenEJBRuntimeException.class, Join.class,
                QuickServerXmlParser.class, Options.class, Options.NullLog.class,
                Options.TomEEPropertyAdapter.class, Options.NullOptions.class, Options.Log.class)) {
            final String name = clazz.getName().replace('.', '/') + ".class";
            os.putArchiveEntry(new JarArchiveEntry(name));
            IOUtils.copy(getClass().getResourceAsStream('/' + name), os);
            os.closeArchiveEntry();
        }
    }

    IOUtil.close(os);
    IOUtil.close(fileOutputStream);
}

From source file:org.apache.tomcat.maven.plugin.tomcat7.run.AbstractExecWarMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
        getLog().info("skip execution");
        return;/* w  w w.j ava  2  s  .  co  m*/
    }
    //project.addAttachedArtifact(  );
    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
        //* optionnal: conf/ with usual tomcat configuration files
        //* MANIFEST with Main-Class

        Properties properties = new Properties();

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

        if (httpPort != null) {
            properties.put(Tomcat7Runner.HTTP_PORT_KEY, httpPort);
        }

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

        if ("war".equals(project.getPackaging())) {

            os.putArchiveEntry(new JarArchiveEntry(StringUtils.removeStart(path, "/") + ".war"));
            IOUtils.copy(new FileInputStream(projectArtifact.getFile()), os);
            os.closeArchiveEntry();

            properties.put(Tomcat7Runner.WARS_KEY, StringUtils.removeStart(path, "/") + ".war|" + path);
        } else if (warRunDependencies != null && !warRunDependencies.isEmpty()) {
            for (WarRunDependency warRunDependency : warRunDependencies) {
                if (warRunDependency.dependency != null) {
                    Dependency dependency = warRunDependency.dependency;
                    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");
                    }
                    Artifact artifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(),
                            dependency.getArtifactId(), version, dependency.getType(),
                            dependency.getClassifier());

                    artifactResolver.resolve(artifact, this.remoteRepos, this.local);

                    File warFileToBundle = new File(resolvePluginWorkDir(), artifact.getFile().getName());
                    FileUtils.copyFile(artifact.getFile(), warFileToBundle);

                    if (warRunDependency.contextXml != null) {
                        warFileToBundle = addContextXmlToWar(warRunDependency.contextXml, warFileToBundle);
                    }
                    final String warFileName = artifact.getFile().getName();
                    os.putArchiveEntry(new JarArchiveEntry(warFileName));
                    IOUtils.copy(new FileInputStream(warFileToBundle), os);
                    os.closeArchiveEntry();
                    String propertyWarValue = properties.getProperty(Tomcat7Runner.WARS_KEY);
                    String contextPath = StringUtils.isEmpty(warRunDependency.contextPath) ? "/"
                            : warRunDependency.contextPath;
                    if (propertyWarValue != null) {
                        properties.put(Tomcat7Runner.WARS_KEY,
                                propertyWarValue + ";" + warFileName + "|" + contextPath);
                    } else {
                        properties.put(Tomcat7Runner.WARS_KEY, warFileName + "|" + contextPath);
                    }
                }
            }
        }

        if (serverXml != null && serverXml.exists()) {
            os.putArchiveEntry(new JarArchiveEntry("conf/server.xml"));
            IOUtils.copy(new FileInputStream(serverXml), os);
            os.closeArchiveEntry();
            properties.put(Tomcat7Runner.USE_SERVER_XML_KEY, Boolean.TRUE.toString());
        } else {
            properties.put(Tomcat7Runner.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(Tomcat7RunnerCli.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("tomcat7-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, this.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.apache.tomcat.maven.plugin.tomcat7.run.AbstractExecWarMojo.java

protected void copyDirectoryContentIntoArchive(File sourceFolder, String destinationPath,
        ArchiveOutputStream archiveOutputStream) throws IOException {

    // Scan the directory
    DirectoryScanner directoryScanner = new DirectoryScanner();
    directoryScanner.setBasedir(sourceFolder);
    directoryScanner.addDefaultExcludes();
    directoryScanner.scan();//w  w  w  .  ja  v  a 2 s.  co m

    // Each File
    for (String includeFileName : directoryScanner.getIncludedFiles()) {
        getLog().debug("include configuration file : " + destinationPath + includeFileName);
        File inputFile = new File(sourceFolder, includeFileName);

        FileInputStream sourceFileInputStream = null;
        try {
            sourceFileInputStream = new FileInputStream(inputFile);

            archiveOutputStream.putArchiveEntry(new JarArchiveEntry(destinationPath + includeFileName));
            IOUtils.copy(sourceFileInputStream, archiveOutputStream);
            archiveOutputStream.closeArchiveEntry();
        } finally {
            IOUtils.closeQuietly(sourceFileInputStream);
        }
    }

}