Example usage for org.apache.commons.compress.archivers.jar JarArchiveEntry JarArchiveEntry

List of usage examples for org.apache.commons.compress.archivers.jar JarArchiveEntry JarArchiveEntry

Introduction

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

Prototype

public JarArchiveEntry(JarEntry entry) throws ZipException 

Source Link

Usage

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/** Copy all the files in a manifest from input to output. */
private static void copyFiles(Manifest manifest, JarFile in, JarArchiveOutputStream out, long timestamp)
        throws IOException {
    final byte[] buffer = new byte[4096];
    int num;// ww  w .java 2 s  . c om

    final Map<String, Attributes> entries = manifest.getEntries();
    final List<String> names = new ArrayList<>(entries.keySet());
    Collections.sort(names);
    for (final String name : names) {
        final JarEntry inEntry = in.getJarEntry(name);
        if (inEntry.getMethod() == JarArchiveEntry.STORED) {
            // Preserve the STORED method of the input entry.
            out.putArchiveEntry(new JarArchiveEntry(inEntry));
        } else {
            // Create a new entry so that the compressed len is recomputed.
            final JarArchiveEntry je = new JarArchiveEntry(name);
            je.setTime(timestamp);
            out.putArchiveEntry(je);
        }

        final InputStream data = in.getInputStream(inEntry);
        while ((num = data.read(buffer)) > 0) {
            out.write(buffer, 0, num);
        }
        out.flush();
        out.closeArchiveEntry();
    }
}

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

private static void extractJarToArchive(JarFile file, ArchiveOutputStream aos) throws IOException {
    Enumeration<? extends JarEntry> entries = file.entries();
    while (entries.hasMoreElements()) {
        JarEntry j = entries.nextElement();
        if (!"META-INF/MANIFEST.MF".equals(j.getName())) {
            aos.putArchiveEntry(new JarArchiveEntry(j.getName()));
            IOUtils.copy(file.getInputStream(j), aos);
            aos.closeArchiveEntry();/*from  ww  w .jav a2 s.c o  m*/
        }
    }
}

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

private void addFile(ArchiveOutputStream aos, String from, String to) throws IOException {
    aos.putArchiveEntry(new JarArchiveEntry(to));
    IOUtils.copy(getClass().getResourceAsStream(from), aos);
    aos.closeArchiveEntry();//  w  w  w  .j a  v  a2 s.c om
}

From source file:org.apache.hadoop.hive.ql.processors.CompileProcessor.java

@VisibleForTesting
/**/*from  ww  w.j  a v a2s  . co m*/
 * Method converts statement into a file, compiles the file and then packages the file.
 * @param ss
 * @return Response code of 0 for success 1 for failure
 * @throws CompileProcessorException
 */
CommandProcessorResponse compile(SessionState ss) throws CompileProcessorException {
    Project proj = new Project();
    String ioTempDir = System.getProperty(IO_TMP_DIR);
    File ioTempFile = new File(ioTempDir);
    if (!ioTempFile.exists()) {
        throw new CompileProcessorException(ioTempDir + " does not exists");
    }
    if (!ioTempFile.isDirectory() || !ioTempFile.canWrite()) {
        throw new CompileProcessorException(ioTempDir + " is not a writable directory");
    }
    Groovyc g = new Groovyc();
    long runStamp = System.currentTimeMillis();
    String jarId = myId + "_" + runStamp;
    g.setProject(proj);
    Path sourcePath = new Path(proj);
    File destination = new File(ioTempFile, jarId + "out");
    g.setDestdir(destination);
    File input = new File(ioTempFile, jarId + "in");
    sourcePath.setLocation(input);
    g.setSrcdir(sourcePath);
    input.mkdir();

    File fileToWrite = new File(input, this.named);
    try {
        Files.write(this.code, fileToWrite, Charset.forName("UTF-8"));
    } catch (IOException e1) {
        throw new CompileProcessorException("writing file", e1);
    }
    destination.mkdir();
    try {
        g.execute();
    } catch (BuildException ex) {
        throw new CompileProcessorException("Problem compiling", ex);
    }
    File testArchive = new File(ioTempFile, jarId + ".jar");
    JarArchiveOutputStream out = null;
    try {
        out = new JarArchiveOutputStream(new FileOutputStream(testArchive));
        for (File f : destination.listFiles()) {
            JarArchiveEntry jentry = new JarArchiveEntry(f.getName());
            FileInputStream fis = new FileInputStream(f);
            out.putArchiveEntry(jentry);
            IOUtils.copy(fis, out);
            fis.close();
            out.closeArchiveEntry();
        }
        out.finish();
    } catch (IOException e) {
        throw new CompileProcessorException("Exception while writing jar", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException WhatCanYouDo) {
            }
        }
    }

    if (ss != null) {
        ss.add_resource(ResourceType.JAR, testArchive.getAbsolutePath());
    }
    CommandProcessorResponse good = new CommandProcessorResponse(0, testArchive.getAbsolutePath(), null);
    return good;
}

From source file:org.apache.openejb.maven.plugin.customizer.monkey.jar.JarPatcher.java

private void jar(final int method, final JarArchiveOutputStream jar, final File f, final String prefix)
        throws IOException {
    final String path = f.getPath().replace(prefix, "").replace(File.separator, "/");
    final ZipArchiveEntry zip = new ZipArchiveEntry(f, path);
    zip.setMethod(method);//from w w  w .  ja va  2  s.c o  m
    final JarArchiveEntry archiveEntry = new JarArchiveEntry(zip);
    jar.putArchiveEntry(archiveEntry);
    if (f.isDirectory()) {
        jar.closeArchiveEntry();
        final File[] files = f.listFiles();
        if (files != null) {
            for (final File child : files) {
                jar(method, jar, child.getCanonicalFile(), prefix);
            }
        }
    } else {
        final InputStream is = new FileInputStream(f);
        IOUtils.copy(is, jar);
        is.close();
        jar.closeArchiveEntry();
    }
}

From source file:org.apache.openejb.maven.plugin.customizer.monkey.MonkeyTest.java

private File prepareProject() throws IOException {
    final File target = new File("target/MonkeyTest_run" + System.currentTimeMillis() + "/mvn/target");
    target.mkdirs();//ww  w. j  av a 2s.co  m

    final File classes = new File(target, "classes");
    classes.mkdirs();

    writeBinary(classes, "target/test-classes/test/patch/MyMain.class", "test/patch/MyMain.class");
    writeBinary(classes, "target/test-classes/test/patch/foo/Another.class", "test/patch/foo/Another.class");

    final File tomee = new File(target, "tomee");
    final File lib = new File(tomee, "lib");
    lib.mkdirs();

    // create the jar to patch, it is invalid but when patched it should work
    JarArchiveOutputStream stream = null;
    try {
        stream = new JarArchiveOutputStream(new FileOutputStream(new File(lib, "t.jar")));
        stream.putArchiveEntry(new JarArchiveEntry("test/patch/MyMain.class"));
        stream.write("invalid".getBytes());
        stream.closeArchiveEntry();
        stream.putArchiveEntry(new JarArchiveEntry("test/patch/foo/Another.class"));
        stream.write("invalid-too".getBytes());
        stream.closeArchiveEntry();
    } catch (final IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        IO.close(stream);
    }

    return tomee;
}

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

private void createExecutableJar() throws Exception {
    mkdirs(execFile.getParentFile());/* w  w  w.ja v  a 2 s.c om*/

    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  .  jav a  2 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

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();//from www  .  j a v a  2 s .  c  om

    // 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);
        }
    }

}

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

/**
 * return file can be deleted//from ww w .ja  v  a2 s  .  co 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;
}