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

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

Introduction

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

Prototype

String JAR

To view the source code for org.apache.commons.compress.archivers ArchiveStreamFactory JAR.

Click Source Link

Document

Constant used to identify the JAR archive format.

Usage

From source file:com.geewhiz.pacify.model.PArchiveBase.java

public String getType() {
    String type = getInternalType();

    if ("jar".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.JAR;
    }//from  w  w w .j a v  a 2  s.  c o  m
    if ("war".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.JAR;
    }
    if ("ear".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.JAR;
    }
    if ("zip".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.ZIP;
    }
    if ("tar".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.TAR;
    }
    return type;
}

From source file:com.geewhiz.pacify.utils.ArchiveUtils.java

public static String getArchiveType(String archiveName) {
    int idx = archiveName.lastIndexOf(".");
    String type = archiveName.substring(idx + 1);

    if ("jar".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.JAR;
    }/*from ww  w  . j  av  a 2  s.  c om*/
    if ("war".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.JAR;
    }
    if ("ear".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.JAR;
    }
    if ("zip".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.ZIP;
    }
    if ("tar".equalsIgnoreCase(type)) {
        return ArchiveStreamFactory.TAR;
    }

    return type;
}

From source file:net.sf.util.zip.FileNameUtil.java

/**
 *
 * @param fileName the file name/*  www .  java 2  s. c o  m*/
 * @return  Archive file type, as defined in ArchiveStreamFactory
 */
public static String getArchieveFileType(String fileName) {
    String s = fileName.toLowerCase();
    if (s.endsWith(".jar") || s.endsWith(".war") || s.endsWith(".ear"))
        return ArchiveStreamFactory.JAR;
    else if (s.endsWith(".tar"))
        return ArchiveStreamFactory.TAR;
    else if (s.endsWith(".zip"))
        return ArchiveStreamFactory.ZIP;

    return null;
}

From source file:ch.rasc.embeddedtc.plugin.PackageTcWarMojo.java

@Override
public void execute() throws MojoExecutionException {

    Path warExecFile = Paths.get(this.buildDirectory, this.finalName);
    try {//from   w w w .j av  a2s.c o  m
        Files.deleteIfExists(warExecFile);
        Files.createDirectories(warExecFile.getParent());

        try (OutputStream os = Files.newOutputStream(warExecFile);
                ArchiveOutputStream aos = new ArchiveStreamFactory()
                        .createArchiveOutputStream(ArchiveStreamFactory.JAR, os)) {

            // If project is a war project add the war to the project
            if ("war".equalsIgnoreCase(this.project.getPackaging())) {
                File projectArtifact = this.project.getArtifact().getFile();
                if (projectArtifact != null && Files.exists(projectArtifact.toPath())) {
                    aos.putArchiveEntry(new JarArchiveEntry(projectArtifact.getName()));
                    try (InputStream is = Files.newInputStream(projectArtifact.toPath())) {
                        IOUtils.copy(is, aos);
                    }
                    aos.closeArchiveEntry();
                }
            }

            // Add extraWars into the jar
            if (this.extraWars != null) {
                for (Dependency extraWarDependency : this.extraWars) {
                    ArtifactRequest request = new ArtifactRequest();
                    request.setArtifact(new DefaultArtifact(extraWarDependency.getGroupId(),
                            extraWarDependency.getArtifactId(), extraWarDependency.getType(),
                            extraWarDependency.getVersion()));
                    request.setRepositories(this.projectRepos);
                    ArtifactResult result;
                    try {
                        result = this.repoSystem.resolveArtifact(this.repoSession, request);
                    } catch (ArtifactResolutionException e) {
                        throw new MojoExecutionException(e.getMessage(), e);
                    }

                    File extraWarFile = result.getArtifact().getFile();
                    aos.putArchiveEntry(new JarArchiveEntry(extraWarFile.getName()));
                    try (InputStream is = Files.newInputStream(extraWarFile.toPath())) {
                        IOUtils.copy(is, aos);
                    }
                    aos.closeArchiveEntry();

                }
            }

            // Add extraResources into the jar. Folder /extra
            if (this.extraResources != null) {
                for (Resource extraResource : this.extraResources) {
                    DirectoryScanner directoryScanner = new DirectoryScanner();
                    directoryScanner.setBasedir(extraResource.getDirectory());

                    directoryScanner.setExcludes(extraResource.getExcludes()
                            .toArray(new String[extraResource.getExcludes().size()]));

                    if (!extraResource.getIncludes().isEmpty()) {
                        directoryScanner.setIncludes(extraResource.getIncludes()
                                .toArray(new String[extraResource.getIncludes().size()]));
                    } else {
                        // include everything by default
                        directoryScanner.setIncludes(new String[] { "**" });
                    }

                    directoryScanner.scan();
                    for (String includeFile : directoryScanner.getIncludedFiles()) {
                        aos.putArchiveEntry(
                                new JarArchiveEntry(Runner.EXTRA_RESOURCES_DIR + "/" + includeFile));

                        Path extraFile = Paths.get(extraResource.getDirectory(), includeFile);
                        try (InputStream is = Files.newInputStream(extraFile)) {
                            IOUtils.copy(is, aos);
                        }
                        aos.closeArchiveEntry();
                    }

                }
            }

            Set<String> includeArtifacts = new HashSet<>();
            includeArtifacts.add("org.apache.tomcat:tomcat-jdbc");
            includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-core");
            includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-websocket");
            includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-logging-juli");
            includeArtifacts.add("org.yaml:snakeyaml");
            includeArtifacts.add("com.beust:jcommander");

            if (this.includeJSPSupport) {
                includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-jasper");
                includeArtifacts.add("org.apache.tomcat.embed:tomcat-embed-el");
                includeArtifacts.add("org.eclipse.jdt.core.compiler:ecj");
            }

            for (Artifact pluginArtifact : this.pluginArtifacts) {
                String artifactName = pluginArtifact.getGroupId() + ":" + pluginArtifact.getArtifactId();
                if (includeArtifacts.contains(artifactName)) {
                    try (JarFile jarFile = new JarFile(pluginArtifact.getFile())) {
                        extractJarToArchive(jarFile, aos);
                    }
                }
            }

            if (this.extraDependencies != null) {
                for (Dependency dependency : this.extraDependencies) {

                    ArtifactRequest request = new ArtifactRequest();
                    request.setArtifact(new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(),
                            dependency.getType(), dependency.getVersion()));
                    request.setRepositories(this.projectRepos);
                    ArtifactResult result;
                    try {
                        result = this.repoSystem.resolveArtifact(this.repoSession, request);
                    } catch (ArtifactResolutionException e) {
                        throw new MojoExecutionException(e.getMessage(), e);
                    }

                    try (JarFile jarFile = new JarFile(result.getArtifact().getFile())) {
                        extractJarToArchive(jarFile, aos);
                    }
                }
            }

            if (this.includeJSPSupport) {
                addFile(aos, "/conf/web.xml", "conf/web.xml");
            } else {
                addFile(aos, "/conf/web_wo_jsp.xml", "conf/web.xml");
            }
            addFile(aos, "/conf/logging.properties", "conf/logging.properties");

            if (this.includeTcNativeWin32 != null) {
                aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.32"));
                Files.copy(Paths.get(this.includeTcNativeWin32), aos);
                aos.closeArchiveEntry();
            }

            if (this.includeTcNativeWin64 != null) {
                aos.putArchiveEntry(new JarArchiveEntry("tcnative-1.dll.64"));
                Files.copy(Paths.get(this.includeTcNativeWin64), aos);
                aos.closeArchiveEntry();
            }

            String[] runnerClasses = { "ch.rasc.embeddedtc.runner.CheckConfig$CheckConfigOptions",
                    "ch.rasc.embeddedtc.runner.CheckConfig", "ch.rasc.embeddedtc.runner.Config",
                    "ch.rasc.embeddedtc.runner.Shutdown", "ch.rasc.embeddedtc.runner.Context",
                    "ch.rasc.embeddedtc.runner.DeleteDirectory",
                    "ch.rasc.embeddedtc.runner.ObfuscateUtil$ObfuscateOptions",
                    "ch.rasc.embeddedtc.runner.ObfuscateUtil", "ch.rasc.embeddedtc.runner.Runner$1",
                    "ch.rasc.embeddedtc.runner.Runner$2", "ch.rasc.embeddedtc.runner.Runner$StartOptions",
                    "ch.rasc.embeddedtc.runner.Runner$StopOptions",
                    "ch.rasc.embeddedtc.runner.Runner$RunnerShutdownHook", "ch.rasc.embeddedtc.runner.Runner" };

            for (String rc : runnerClasses) {
                String classAsPath = rc.replace('.', '/') + ".class";

                try (InputStream is = getClass().getResourceAsStream("/" + classAsPath)) {
                    aos.putArchiveEntry(new JarArchiveEntry(classAsPath));
                    IOUtils.copy(is, aos);
                    aos.closeArchiveEntry();
                }
            }

            Manifest manifest = new Manifest();

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

            aos.putArchiveEntry(new JarArchiveEntry("META-INF/MANIFEST.MF"));
            manifest.write(aos);
            aos.closeArchiveEntry();

            aos.putArchiveEntry(new JarArchiveEntry(Runner.TIMESTAMP_FILENAME));
            aos.write(String.valueOf(System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8));
            aos.closeArchiveEntry();

        }
    } catch (IOException | ArchiveException | ManifestException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:com.geewhiz.pacify.utils.ArchiveUtils.java

public static void replaceFilesInArchive(File archive, String archiveType, Map<String, File> filesToReplace) {
    ArchiveStreamFactory factory = new ArchiveStreamFactory();

    File manifest = null;/*from   w  w w.  jav  a  2  s  . c o m*/
    InputStream archiveStream = null;
    ArchiveInputStream ais = null;
    ArchiveOutputStream aos = null;
    List<FileInputStream> streamsToClose = new ArrayList<FileInputStream>();

    File tmpArchive = FileUtils.createEmptyFileWithSamePermissions(archive);

    try {
        aos = factory.createArchiveOutputStream(archiveType, new FileOutputStream(tmpArchive));
        ChangeSet changes = new ChangeSet();

        if (ArchiveStreamFactory.JAR.equalsIgnoreCase(archiveType)) {
            manifest = manifestWorkaround(archive, archiveType, aos, changes, streamsToClose);
        }

        for (String filePath : filesToReplace.keySet()) {
            File replaceWithFile = filesToReplace.get(filePath);

            ArchiveEntry archiveEntry = aos.createArchiveEntry(replaceWithFile, filePath);
            FileInputStream fis = new FileInputStream(replaceWithFile);
            streamsToClose.add(fis);
            changes.add(archiveEntry, fis, true);
        }

        archiveStream = new FileInputStream(archive);
        ais = factory.createArchiveInputStream(archiveType, archiveStream);

        ChangeSetPerformer performer = new ChangeSetPerformer(changes);
        performer.perform(ais, aos);

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ArchiveException e) {
        throw new RuntimeException(e);
    } finally {
        for (FileInputStream fis : streamsToClose) {
            IOUtils.closeQuietly(fis);
        }
        IOUtils.closeQuietly(aos);
        IOUtils.closeQuietly(ais);
        IOUtils.closeQuietly(archiveStream);
    }

    if (manifest != null) {
        manifest.delete();
    }

    if (!archive.delete()) {
        throw new RuntimeException("Couldn't delete file [" + archive.getPath() + "]... Aborting!");
    }
    if (!tmpArchive.renameTo(archive)) {
        throw new RuntimeException("Couldn't rename filtered file from [" + tmpArchive.getPath() + "] to ["
                + archive.getPath() + "]... Aborting!");
    }
}

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

private void createExecutableJar() throws Exception {
    mkdirs(execFile.getParentFile());//from  w w w  .java  2 s . c  o  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 a v  a2  s  . c  o  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

/**
 * return file can be deleted/* w w  w.ja v  a2 s  .  c  o  m*/
 */
protected File addContextXmlToWar(File contextXmlFile, File warFile) throws IOException, ArchiveException {
    ArchiveOutputStream os = null;
    OutputStream warOutputStream = null;
    File tmpWar = File.createTempFile("tomcat", "war-exec");
    tmpWar.deleteOnExit();

    try {
        warOutputStream = new FileOutputStream(tmpWar);
        os = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR, warOutputStream);
        os.putArchiveEntry(new JarArchiveEntry("META-INF/context.xml"));
        IOUtils.copy(new FileInputStream(contextXmlFile), os);
        os.closeArchiveEntry();

        JarFile jarFile = new JarFile(warFile);
        extractJarToArchive(jarFile, os, null);
        os.flush();
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(warOutputStream);
    }
    return tmpWar;
}

From source file:org.apache.tomcat.maven.plugin.tomcat7.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.");
    }//  w  w w  .j ava2 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(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);
        properties.put(Tomcat7Runner.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(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, 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.tomcat8.run.AbstractExecWarMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
        getLog().info("skip execution");
        return;/*from w  w w .  ja v  a2  s  . c om*/
    }
    //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(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);

        if (httpPort != null) {
            properties.put(Tomcat8Runner.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(Tomcat8Runner.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(Tomcat8Runner.WARS_KEY);
                    String contextPath = StringUtils.isEmpty(warRunDependency.contextPath) ? "/"
                            : warRunDependency.contextPath;
                    if (propertyWarValue != null) {
                        properties.put(Tomcat8Runner.WARS_KEY,
                                propertyWarValue + ";" + warFileName + "|" + contextPath);
                    } else {
                        properties.put(Tomcat8Runner.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(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, 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);
    }
}