Example usage for java.util.jar JarOutputStream JarOutputStream

List of usage examples for java.util.jar JarOutputStream JarOutputStream

Introduction

In this page you can find the example usage for java.util.jar JarOutputStream JarOutputStream.

Prototype

public JarOutputStream(OutputStream out) throws IOException 

Source Link

Document

Creates a new JarOutputStream with no manifest.

Usage

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

private static void replaceInJar(File sourceJar, String origFile, File replacementFile) throws IOException {
    String srcJarAbsPath = sourceJar.getAbsolutePath();
    String srcJarSuffix = srcJarAbsPath.substring(srcJarAbsPath.lastIndexOf(File.separator) + 1);
    String srcJarName = srcJarSuffix.split(".jar")[0];

    String destJarName = srcJarName + "-managix";
    String destJarSuffix = destJarName + ".jar";
    File destJar = new File(sourceJar.getParentFile().getAbsolutePath() + File.separator + destJarSuffix);
    //  File destJar = new File(sourceJar.getAbsolutePath() + ".modified");
    JarFile sourceJarFile = new JarFile(sourceJar);
    Enumeration<JarEntry> entries = sourceJarFile.entries();
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(destJar));
    byte[] buffer = new byte[2048];
    int read;//  ww w  .  j  a  v  a2 s. c o m
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String name = entry.getName();
        if (name.equals(origFile)) {
            continue;
        }
        InputStream jarIs = sourceJarFile.getInputStream(entry);
        jos.putNextEntry(entry);
        while ((read = jarIs.read(buffer)) != -1) {
            jos.write(buffer, 0, read);
        }
        jarIs.close();
    }
    sourceJarFile.close();
    JarEntry entry = new JarEntry(origFile);
    jos.putNextEntry(entry);
    FileInputStream fis = new FileInputStream(replacementFile);
    while ((read = fis.read(buffer)) != -1) {
        jos.write(buffer, 0, read);
    }
    fis.close();
    jos.close();
    sourceJar.delete();
    destJar.renameTo(sourceJar);
    destJar.setExecutable(true);
}

From source file:boa.compiler.BoaCompiler.java

private static void generateJar(final String jarName, final File dir, final List<File> libJars)
        throws IOException, FileNotFoundException {
    final JarOutputStream jar = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(new File(jarName))));

    try {/*from w  w  w  .  j  a v a  2 s.  c om*/
        final int offset = dir.toString().length() + 1;

        for (final File f : findFiles(dir, new ArrayList<File>()))
            putJarEntry(jar, f, f.getPath().substring(offset));

        for (final File f : libJars)
            putJarEntry(jar, f, "lib" + File.separatorChar + f.getName());
    } finally {
        jar.close();
    }
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

/**
 * @deprecated support for this is not going to stick around, seriously.
 *///from  w w w . j  a  v a  2s .  c  o  m
@Deprecated
public void testAlreadyInstalledNotIsolated() throws Exception {
    String pluginName = "fake-plugin";
    Path pluginDir = createTempDir().resolve(pluginName);
    Files.createDirectories(pluginDir);
    // create a jar file in the plugin
    Path pluginJar = pluginDir.resolve("fake-plugin.jar");
    try (ZipOutputStream out = new JarOutputStream(
            Files.newOutputStream(pluginJar, StandardOpenOption.CREATE))) {
        out.putNextEntry(new ZipEntry("foo.class"));
        out.closeEntry();
    }
    String pluginUrl = createPlugin(pluginDir, "description", "fake desc", "name", pluginName, "version", "1.0",
            "elasticsearch.version", Version.CURRENT.toString(), "java.version",
            System.getProperty("java.specification.version"), "isolated", "false", "jvm", "true", "classname",
            "FakePlugin");

    // install
    ExitStatus status = new PluginManagerCliParser(terminal).execute(args("install " + pluginUrl));
    assertEquals("unexpected exit status: output: " + terminal.getTerminalOutput(), ExitStatus.OK, status);

    // install again
    status = new PluginManagerCliParser(terminal).execute(args("install " + pluginUrl));
    List<String> output = terminal.getTerminalOutput();
    assertEquals("unexpected exit status: output: " + output, ExitStatus.IO_ERROR, status);
    boolean foundExpectedMessage = false;
    for (String line : output) {
        foundExpectedMessage |= line.contains("already exists");
    }
    assertTrue(foundExpectedMessage);
}

From source file:com.googlecode.mycontainer.maven.plugin.ExecMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for
 * SurefireBooter and a Class-Path entry for all classpath elements. Copied
 * from surefire (ForkConfiguration#createJar())
 * /*from w ww  . j  a  va2s. co  m*/
 * @param classPath
 *            List&lt;String> of all classpath elements.
 * @return
 * @throws IOException
 */
private File createJar(List classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);

    Manifest man = new Manifest();

    // we can't use StringUtils.join here since we need to add a '/' to
    // the end of directory entries - otherwise the jvm will ignore them.
    String cp = "";
    for (Iterator it = classPath.iterator(); it.hasNext();) {
        String el = (String) it.next();
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp += UrlUtils.getURL(new File(el)).toExternalForm() + " ";
    }

    man.getMainAttributes().putValue("Manifest-Version", "1.0");
    man.getMainAttributes().putValue("Class-Path", cp.trim());
    man.getMainAttributes().putValue("Main-Class", mainClass);

    man.write(jos);
    jos.close();

    return file;
}

From source file:com.simpligility.maven.plugins.android.phase09package.ApkMojo.java

private void extractDuplicateFiles(List<File> jarFiles, Collection<File> sourceFolders) throws IOException {
    getLog().debug("Extracting duplicates");
    List<String> duplicates = new ArrayList<String>();
    List<File> jarToModify = new ArrayList<File>();
    for (String s : jars.keySet()) {
        List<File> l = jars.get(s);
        if (l.size() > 1) {
            getLog().warn("Duplicate file " + s + " : " + l);
            duplicates.add(s);// w  ww.j  av  a 2  s. c  o m
            for (int i = 0; i < l.size(); i++) {
                if (!jarToModify.contains(l.get(i))) {
                    jarToModify.add(l.get(i));
                }
            }
        }
    }

    // Rebuild jars.  Remove duplicates from ALL jars, then add them back into a duplicate-resources.jar
    File tmp = new File(targetDirectory.getAbsolutePath(), "unpacked-embedded-jars");
    tmp.mkdirs();
    File duplicatesJar = new File(tmp, "duplicate-resources.jar");
    Set<String> duplicatesAdded = new HashSet<String>();

    duplicatesJar.createNewFile();
    final FileOutputStream fos = new FileOutputStream(duplicatesJar);
    final JarOutputStream zos = new JarOutputStream(fos);

    for (File file : jarToModify) {
        final int index = jarFiles.indexOf(file);
        if (index != -1) {
            final File newJar = removeDuplicatesFromJar(file, duplicates, duplicatesAdded, zos, index);
            getLog().debug("Removed duplicates from " + newJar);
            if (newJar != null) {
                jarFiles.set(index, newJar);
            }
        } else {
            removeDuplicatesFromFolder(file, file, duplicates, duplicatesAdded, zos);
            getLog().debug("Removed duplicates from " + file);
        }
    }
    //add transformed resources to duplicate-resources.jar
    if (transformers != null) {
        for (ResourceTransformer transformer : transformers) {
            if (transformer.hasTransformedResource()) {
                transformer.modifyOutputStream(zos);
            }
        }
    }
    zos.close();
    fos.close();

    if (!jarToModify.isEmpty() && duplicatesJar.length() > 0) {
        jarFiles.add(duplicatesJar);
    }
}

From source file:net.hasor.maven.ExecMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for all
 * classpath elements. Copied from surefire (ForkConfiguration#createJar())
 *
 * @param classPath List&lt;String> of all classpath elements.
 * @return//from  w w w  . j a  v a2s.c  o m
 * @throws IOException
 */
private File createJar(List<String> classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);
    Manifest man = new Manifest();
    // we can't use StringUtils.join here since we need to add a '/' to
    // the end of directory entries - otherwise the jvm will ignore them.
    StringBuilder cp = new StringBuilder();
    for (String el : classPath) {
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " ");
    }
    man.getMainAttributes().putValue("Manifest-Version", "1.0");
    man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
    man.getMainAttributes().putValue("Main-Class", mainClass);
    man.write(jos);
    jos.close();
    return file;
}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

@Test
public void testJarUploadFullMvnPath() throws Exception {
    String jarPath = "org.acme/acme-core/1.0/acme-core-1.0.jar";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream jas = new JarOutputStream(baos);
    addEntry(jas, "hello.txt", "Hello!".getBytes());
    jas.close();/*w ww . j a  v  a  2  s .c om*/

    byte[] contents = baos.toByteArray();

    testUpload(jarPath, contents, false);
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

private void compileJavaModule(File jarOutputFolder, File classesOutputFolder, String moduleName,
        String moduleVersion, File sourceFolder, File[] extraClassPath, String... sourceFileNames)
        throws IOException {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    assertNotNull("Missing Java compiler, this test is probably being run with a JRE instead of a JDK!",
            javaCompiler);/*from  w  w w . jav  a 2s .  c o  m*/
    StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
    Set<String> sourceDirectories = new HashSet<String>();
    File[] javaSourceFiles = new File[sourceFileNames.length];
    for (int i = 0; i < javaSourceFiles.length; i++) {
        javaSourceFiles[i] = new File(sourceFolder, sourceFileNames[i]);
        String sfn = sourceFileNames[i].replace(File.separatorChar, '/');
        int p = sfn.lastIndexOf('/');
        String sourceDir = sfn.substring(0, p);
        sourceDirectories.add(sourceDir);
    }
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaSourceFiles);
    StringBuilder cp = new StringBuilder();
    for (int i = 0; i < extraClassPath.length; i++) {
        if (i > 0)
            cp.append(File.pathSeparator);
        cp.append(extraClassPath[i]);
    }
    CompilationTask task = javaCompiler.getTask(null, null, null, Arrays.asList("-d",
            classesOutputFolder.getPath(), "-cp", cp.toString(), "-sourcepath", sourceFolder.getPath()), null,
            compilationUnits);
    assertEquals(Boolean.TRUE, task.call());

    File jarFolder = new File(jarOutputFolder,
            moduleName.replace('.', File.separatorChar) + File.separatorChar + moduleVersion);
    jarFolder.mkdirs();
    File jarFile = new File(jarFolder, moduleName + "-" + moduleVersion + ".jar");
    // now jar it up
    JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(jarFile));
    for (String sourceFileName : sourceFileNames) {
        String classFileName = sourceFileName.substring(0, sourceFileName.length() - 5) + ".class";
        ZipEntry entry = new ZipEntry(classFileName);
        outputStream.putNextEntry(entry);

        File classFile = new File(classesOutputFolder, classFileName);
        FileInputStream inputStream = new FileInputStream(classFile);
        Util.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.flush();
    }
    outputStream.close();
    for (String sourceDir : sourceDirectories) {
        File module = null;
        String sourceName = "module.properties";
        File properties = new File(sourceFolder, sourceDir + File.separator + sourceName);
        if (properties.exists()) {
            module = properties;
        } else {
            sourceName = "module.xml";
            properties = new File(sourceFolder, sourceDir + File.separator + sourceName);
            if (properties.exists()) {
                module = properties;
            }
        }
        if (module != null) {
            File moduleFile = new File(sourceFolder, sourceDir + File.separator + sourceName);
            FileInputStream inputStream = new FileInputStream(moduleFile);
            FileOutputStream moduleOutputStream = new FileOutputStream(new File(jarFolder, sourceName));
            Util.copy(inputStream, moduleOutputStream);
            inputStream.close();
            moduleOutputStream.flush();
            moduleOutputStream.close();
        }
    }
}

From source file:kr.motd.maven.exec.ExecMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for all
 * classpath elements. Copied from surefire (ForkConfiguration#createJar())
 *
 * @param classPath List&lt;String> of all classpath elements.
 * @return/*  www .  j  av  a  2 s.  c  o m*/
 * @throws IOException
 */
private File createJar(List<String> classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);

    Manifest man = new Manifest();

    // we can't use StringUtils.join here since we need to add a '/' to
    // the end of directory entries - otherwise the jvm will ignore them.
    StringBuilder cp = new StringBuilder();
    for (String el : classPath) {
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " ");
    }

    man.getMainAttributes().putValue("Manifest-Version", "1.0");
    man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
    man.getMainAttributes().putValue("Main-Class", mainClass);

    man.write(jos);
    jos.close();

    return file;
}

From source file:io.fabric8.maven.proxy.impl.MavenProxyServletSupportTest.java

@Test
public void testJarUploadWithMvnPom() throws Exception {
    String jarPath = "org.acme/acme-core/1.0/acme-core-1.0.jar";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream jas = new JarOutputStream(baos);
    addEntry(jas, "hello.txt", "Hello!".getBytes());
    addPom(jas, "org.acme", "acme-core", "1.0");
    jas.close();/* ww w. j  av  a  2 s.  c  om*/

    byte[] contents = baos.toByteArray();

    testUpload(jarPath, contents, false);
}