Example usage for java.util.jar JarOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry ze) throws IOException 

Source Link

Document

Begins writing a new JAR file entry and positions the stream to the start of the entry data.

Usage

From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java

/** Compiles a scala class
 * @param script//ww w. j  a  v a2s  . co m
 * @param clazz_name
 * @return
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 */
public Tuple2<ClassLoader, Object> buildClass(final String script, final String clazz_name,
        final Optional<IBucketLogger> logger)
        throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    final String relative_dir = "./script_classpath/";
    new File(relative_dir).mkdirs();

    final File source_file = new File(relative_dir + clazz_name + ".scala");
    FileUtils.writeStringToFile(source_file, script);

    final String this_path = LiveInjector.findPathJar(this.getClass(), "./dummy.jar");
    final File f = new File(this_path);
    final File fp = new File(f.getParent());
    final String classpath = Arrays.stream(fp.listFiles()).map(ff -> ff.toString())
            .filter(ff -> ff.endsWith(".jar")).collect(Collectors.joining(":"));

    // Need this to make the URL classloader be used, not the system classloader (which doesn't know about Aleph2..)

    final Settings s = new Settings();
    s.classpath().value_$eq(System.getProperty("java.class.path") + classpath);
    s.usejavacp().scala$tools$nsc$settings$AbsSettings$AbsSetting$$internalSetting_$eq(true);
    final StoreReporter reporter = new StoreReporter();
    final Global g = new Global(s, reporter);
    final Run r = g.new Run();
    r.compile(JavaConverters.asScalaBufferConverter(Arrays.<String>asList(source_file.toString())).asScala()
            .toList());

    if (reporter.hasErrors() || reporter.hasWarnings()) {
        final String errors = "Compiler: Errors/warnings (**to get to user script line substract 22**): "
                + JavaConverters.asJavaSetConverter(reporter.infos()).asJava().stream()
                        .map(info -> info.toString()).collect(Collectors.joining(" ;; "));
        logger.ifPresent(l -> l.log(reporter.hasErrors() ? Level.ERROR : Level.DEBUG, false, () -> errors,
                () -> "SparkScalaInterpreterTopology", () -> "compile"));

        //ERROR:
        if (reporter.hasErrors()) {
            System.err.println(errors);
        }
    }
    // Move any class files (eg including sub-classes)
    Arrays.stream(fp.listFiles()).filter(ff -> ff.toString().endsWith(".class"))
            .forEach(Lambdas.wrap_consumer_u(ff -> {
                FileUtils.moveFile(ff, new File(relative_dir + ff.getName()));
            }));

    // Create a JAR file...

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    final JarOutputStream target = new JarOutputStream(new FileOutputStream("./script_classpath.jar"),
            manifest);
    Arrays.stream(new File(relative_dir).listFiles()).forEach(Lambdas.wrap_consumer_i(ff -> {
        JarEntry entry = new JarEntry(ff.getName());
        target.putNextEntry(entry);
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(ff))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }));
    target.close();

    final String created = "Created = " + new File("./script_classpath.jar").toURI().toURL() + " ... "
            + Arrays.stream(new File(relative_dir).listFiles()).map(ff -> ff.toString())
                    .collect(Collectors.joining(";"));
    logger.ifPresent(l -> l.log(Level.DEBUG, true, () -> created, () -> "SparkScalaInterpreterTopology",
            () -> "compile"));

    final Tuple2<ClassLoader, Object> o = Lambdas.get(Lambdas.wrap_u(() -> {
        _cl.set(new java.net.URLClassLoader(
                Arrays.asList(new File("./script_classpath.jar").toURI().toURL()).toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader()));
        Object o_ = _cl.get().loadClass("ScriptRunner").newInstance();
        return Tuples._2T(_cl.get(), o_);
    }));
    return o;
}

From source file:org.apache.sqoop.integration.connectorloading.ClasspathTest.java

private void addFileToJar(File source, JarOutputStream target) throws Exception {
    JarEntry entry = new JarEntry(source.getName());
    entry.setTime(source.lastModified());
    target.putNextEntry(entry);
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));

    long bufferSize = source.length();
    if (bufferSize < Integer.MIN_VALUE || bufferSize > Integer.MAX_VALUE) {
        throw new RuntimeException("file to large to be added to jar");
    }/*from   w ww .  j a  v  a2s .  c o m*/

    byte[] buffer = new byte[(int) bufferSize];
    while (true) {
        int count = in.read(buffer);
        if (count == -1)
            break;
        target.write(buffer, 0, count);
    }
    target.closeEntry();
    if (in != null)
        in.close();
}

From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java

private void addToJar(JarOutputStream jarOS, VirtualFile file) throws IOException {
    JarEntry entry = new JarEntry(file.getCanonicalPath());
    entry.setTime(file.getTimeStamp());/*  w w  w  .j  av a  2s. c  om*/
    jarOS.putNextEntry(entry);
    Reader reader = wrapWithReplacements(file.getInputStream(), file.getCharset());
    Writer writer = new OutputStreamWriter(jarOS);
    try {
        CharStreams.copy(reader, writer);
    } finally {
        Closeables.close(reader, true);
        Closeables.close(writer, true);
    }
}

From source file:org.codehaus.mojo.minijar.resource.LicenseHandler.java

public void onStopProcessing(JarOutputStream pOutput) throws IOException {
    if (licensesOutputStream == null) {
        // no license information aggregated
        return;/*from   w  w  w.  jav  a2 s  .  co  m*/
    }

    IOUtils.closeQuietly(licensesOutputStream);

    // insert aggregated license information into new jar

    final FileInputStream licensesInputStream = new FileInputStream(licensesFile);

    pOutput.putNextEntry(new JarEntry("LICENSE.txt"));

    IOUtils.copy(licensesInputStream, pOutput);

    IOUtils.closeQuietly(licensesInputStream);

}

From source file:org.stem.ExternalNode.java

private void createNodeJar(File jarFile, String mainClass, File nodeDir) throws IOException {
    File conf = new File(nodeDir, "conf");

    FileOutputStream fos = null;/*from  www.ja va2  s.co m*/
    JarOutputStream jos = null;

    try {
        fos = new FileOutputStream(jarFile);
        jos = new JarOutputStream(fos);
        jos.setLevel(JarOutputStream.STORED);
        jos.putNextEntry(new JarEntry("META-INF/MANIFEST.MF"));

        Manifest man = new Manifest();

        StringBuilder cp = new StringBuilder();
        cp.append(new URL(conf.toURI().toASCIIString()).toExternalForm());
        cp.append(' ');

        log.debug("Adding plugin artifact: " + ArtifactUtils.versionlessKey(mvnContext.pluginArtifact)
                + " to the classpath");
        cp.append(new URL(mvnContext.pluginArtifact.getFile().toURI().toASCIIString()).toExternalForm());
        cp.append(' ');

        log.debug("Adding: " + mvnContext.classesDir + " to the classpath");
        cp.append(new URL(mvnContext.classesDir.toURI().toASCIIString()).toExternalForm());
        cp.append(' ');

        for (Artifact artifact : mvnContext.pluginDependencies) {
            log.info("Adding plugin dependency artifact: " + ArtifactUtils.versionlessKey(artifact)
                    + " to the classpath");
            // NOTE: if File points to a directory, this entry MUST end in '/'.
            cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm());
            cp.append(' ');
        }

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

        man.write(jos);

    } finally {
        IOUtil.close(jos);
        IOUtil.close(fos);
    }
}

From source file:org.apache.openjpa.eclipse.PluginLibrary.java

void copyJar(JarInputStream jar, JarOutputStream out) throws IOException {
    if (jar == null || out == null)
        return;/* w w w .  j  a v  a 2s.c om*/

    try {
        JarEntry entry = null;
        while ((entry = jar.getNextJarEntry()) != null) {
            out.putNextEntry(entry);
            int b = -1;
            while ((b = jar.read()) != -1) {
                out.write(b);
            }
        }
        out.closeEntry();
    } finally {
        out.finish();
        out.flush();
        out.close();
        jar.close();
    }
}

From source file:edu.stanford.muse.email.JarDocCache.java

/** returns a jar outputstream for the given filename.
 * copies over jar entries if the file was already existing.
 * unfortunately, we can't append to the end of a jar file easily.
 * see e.g.http://stackoverflow.com/questions/2223434/appending-files-to-a-zip-file-with-java
 * and http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4129445
 * may consider using truezip at some point, but the doc is dense.
 *///from w ww . j a  v a 2  s  .  c om
private static JarOutputStream appendOrCreateJar(String filename) throws IOException {
    JarOutputStream jos;
    File f = new File(filename);
    if (!f.exists())
        return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));

    // bak* is going to be all the previous file entries
    String bakFilename = filename + ".bak";
    File bakFile = new File(bakFilename);
    f.renameTo(new File(bakFilename));
    jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
    JarFile bakJF;
    try {
        bakJF = new JarFile(bakFilename);
    } catch (Exception e) {
        log.warn("Bad jar file! " + bakFilename + " size " + new File(filename).length() + " bytes");
        Util.print_exception(e, log);
        return new JarOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
    }

    // copy all entries from bakJF to jos
    Enumeration<JarEntry> bakEntries = bakJF.entries();
    while (bakEntries.hasMoreElements()) {
        JarEntry je = bakEntries.nextElement();
        jos.putNextEntry(je);
        InputStream is = bakJF.getInputStream(je);

        // copy over everything from is to jos
        byte buf[] = new byte[32 * 1024]; // randomly 32K
        int nBytes;
        while ((nBytes = is.read(buf)) != -1)
            jos.write(buf, 0, nBytes);

        jos.closeEntry();
    }
    bakFile.delete();

    return jos;
}

From source file:com.jasonstedman.maven.RequireConfigTransformer.java

public void modifyOutputStream(JarOutputStream jos) throws IOException {
    logger.info("Creating merged data-main script at war path : " + dataMainPath);
    logger.info("Merging require configs matching path pattern : " + configFilePattern);
    logger.info("Using initial define block from : " + initialDefinition);

    Map<String, Object> configBlock = mergeConfigBlocks();

    jos.putNextEntry(new JarEntry(dataMainPath));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(jos));
    writer.write("require.config(");
    writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(configBlock));
    writer.write(");");
    writer.newLine();/*from  w  ww .j  a v  a  2 s.c  om*/
    writer.write(initBlock);
    writer.flush();
}

From source file:com.streamsets.pipeline.maven.rbgen.RBGenMojo.java

private void addFile(String path, File file, JarOutputStream jar) throws IOException {
    try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
        JarEntry entry = new JarEntry(path);
        entry.setTime(file.lastModified());
        jar.putNextEntry(entry);
        IOUtils.copy(in, jar);//from   w w  w  . j a  va 2s .  c o  m
        jar.closeEntry();
    }
}

From source file:org.echocat.nodoodle.transport.HandlerPacker.java

protected void writeData(Handler<?> handler, JarOutputStream jar, String dataFileName) throws IOException {
    if (handler == null) {
        throw new NullPointerException();
    }/*from   ww w. j a va  2  s. c o m*/
    if (jar == null) {
        throw new NullPointerException();
    }
    final JarEntry entry = new JarEntry(dataFileName);
    jar.putNextEntry(entry);
    final ObjectOutputStream oos = new ObjectOutputStream(jar);
    oos.writeObject(handler);
    oos.flush();
    jar.closeEntry();
}