Example usage for java.util.jar JarOutputStream write

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

Introduction

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

Prototype

public synchronized void write(byte[] b, int off, int len) throws IOException 

Source Link

Document

Writes an array of bytes to the current ZIP entry data.

Usage

From source file:oz.hadoop.yarn.api.utils.JarUtils.java

/**
 *
 * @param source/*from   ww w.ja  v a 2 s  .com*/
 * @param lengthOfOriginalPath
 * @param target
 * @throws IOException
 */
private static void add(File source, int lengthOfOriginalPath, JarOutputStream target) throws IOException {
    BufferedInputStream in = null;
    try {
        String path = source.getAbsolutePath();
        path = path.substring(lengthOfOriginalPath);

        if (source.isDirectory()) {
            String name = path.replace("\\", "/");
            if (!name.isEmpty()) {
                if (!name.endsWith("/")) {
                    name += "/";
                }
                JarEntry entry = new JarEntry(name.substring(1)); // avoiding absolute path warning
                target.putNextEntry(entry);
                target.closeEntry();
            }

            for (File nestedFile : source.listFiles()) {
                add(nestedFile, lengthOfOriginalPath, target);
            }

            return;
        }

        JarEntry entry = new JarEntry(path.replace("\\", "/").substring(1)); // avoiding absolute path warning
        entry.setTime(source.lastModified());
        try {
            target.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1) {
                    break;
                }
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        } catch (Exception e) {
            String message = e.getMessage();
            if (StringUtils.hasText(message)) {
                if (!message.toLowerCase().contains("duplicate")) {
                    throw new IllegalStateException(e);
                }
                logger.warn(message);
            } else {
                throw new IllegalStateException(e);
            }
        }
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:de.fhg.igd.mapviewer.server.file.FileTiler.java

/**
 * Creates a Jar archive that includes the given list of files
 * //ww  w .  j  a v a2  s  . c  om
 * @param archiveFile the name of the jar archive file
 * @param tobeJared the files to be included in the jar file
 * 
 * @return if the operation was successful
 */
public static boolean createJarArchive(File archiveFile, List<File> tobeJared) {
    try {
        byte buffer[] = new byte[BUFFER_SIZE];
        // Open archive file
        FileOutputStream stream = new FileOutputStream(archiveFile);
        JarOutputStream out = new JarOutputStream(stream, new Manifest());

        for (int i = 0; i < tobeJared.size(); i++) {
            if (tobeJared.get(i) == null || !tobeJared.get(i).exists() || tobeJared.get(i).isDirectory())
                continue; // Just in case...
            log.debug("Adding " + tobeJared.get(i).getName());

            // Add archive entry
            JarEntry jarAdd = new JarEntry(tobeJared.get(i).getName());
            jarAdd.setTime(tobeJared.get(i).lastModified());
            out.putNextEntry(jarAdd);

            // Write file to archive
            FileInputStream in = new FileInputStream(tobeJared.get(i));
            while (true) {
                int nRead = in.read(buffer, 0, buffer.length);
                if (nRead <= 0)
                    break;
                out.write(buffer, 0, nRead);
            }
            in.close();
        }

        out.close();
        stream.close();
        log.info("Adding completed OK");
        return true;
    } catch (Exception e) {
        log.error("Creating jar file failed", e);
        return false;
    }
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static void writeSignatureBlock(byte[] sigBlock, SignatureType signatureType, String signatureName,
        JarOutputStream jos) throws IOException {

    // Block's extension depends on signature type
    String extension = null;/*from  w w w .  j ava2 s.  c  om*/

    if (signatureType == SHA1_DSA) {
        extension = DSA_SIG_BLOCK_EXT;
    } else {
        extension = RSA_SIG_BLOCK_EXT;
    }

    // Signature block entry
    JarEntry bkJarEntry = new JarEntry(
            MessageFormat.format(METAINF_FILE_LOCATION, signatureName, extension).toUpperCase());
    jos.putNextEntry(bkJarEntry);

    // Write content
    ByteArrayInputStream bais = new ByteArrayInputStream(sigBlock);

    byte[] buffer = new byte[2048];
    int read = -1;

    while ((read = bais.read(buffer)) != -1) {
        jos.write(buffer, 0, read);
    }

    jos.closeEntry();
}

From source file:io.dstream.tez.utils.ClassPathUtils.java

/**
 *
 * @param source//from   w ww . j ava2  s  . c  o m
 * @param lengthOfOriginalPath
 * @param target
 * @throws IOException
 */
private static void add(File source, int lengthOfOriginalPath, JarOutputStream target) throws IOException {
    BufferedInputStream in = null;
    try {
        String path = source.getAbsolutePath();
        path = path.substring(lengthOfOriginalPath);

        if (source.isDirectory()) {
            String name = path.replace("\\", "/");
            if (!name.isEmpty()) {
                if (!name.endsWith("/")) {
                    name += "/";
                }
                JarEntry entry = new JarEntry(name.substring(1)); // avoiding absolute path warning
                target.putNextEntry(entry);
                target.closeEntry();
            }

            for (File nestedFile : source.listFiles()) {
                add(nestedFile, lengthOfOriginalPath, target);
            }

            return;
        }

        JarEntry entry = new JarEntry(path.replace("\\", "/").substring(1)); // avoiding absolute path warning
        entry.setTime(source.lastModified());
        try {
            target.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1) {
                    break;
                }
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        } catch (Exception e) {
            String message = e.getMessage();
            if (message != null) {
                if (!message.toLowerCase().contains("duplicate")) {
                    throw new IllegalStateException(e);
                }
                logger.warn(message);
            } else {
                throw new IllegalStateException(e);
            }
        }
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:com.hellblazer.process.JavaProcessTest.java

protected void copyTestJarFile() throws Exception {
    String classFileName = HelloWorld.class.getCanonicalName().replace('.', '/') + ".class";
    URL classFile = getClass().getResource("/" + classFileName);
    assertNotNull(classFile);//  w w  w .j a v  a 2 s  .com

    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.putValue("Manifest-Version", "1.0");
    attributes.putValue("Main-Class", HelloWorld.class.getCanonicalName());

    FileOutputStream fos = new FileOutputStream(new File(testDir, TEST_JAR));
    JarOutputStream jar = new JarOutputStream(fos, manifest);
    JarEntry entry = new JarEntry(classFileName);
    jar.putNextEntry(entry);
    InputStream in = classFile.openStream();
    byte[] buffer = new byte[1024];
    for (int read = in.read(buffer); read != -1; read = in.read(buffer)) {
        jar.write(buffer, 0, read);
    }
    in.close();
    jar.closeEntry();
    jar.close();
}

From source file:Main.java

void createJarArchive(File archiveFile, File[] tobeJared) throws Exception {
    byte buffer[] = new byte[BUFFER_SIZE];
    FileOutputStream stream = new FileOutputStream(archiveFile);
    JarOutputStream out = new JarOutputStream(stream, new Manifest());
    for (int i = 0; i < tobeJared.length; i++) {
        if (tobeJared[i] == null || !tobeJared[i].exists() || tobeJared[i].isDirectory())
            continue; // Just in case...
        JarEntry jarAdd = new JarEntry(tobeJared[i].getName());
        jarAdd.setTime(tobeJared[i].lastModified());
        out.putNextEntry(jarAdd);/*w  w w .  j a v a2 s  .c  o m*/
        FileInputStream in = new FileInputStream(tobeJared[i]);
        while (true) {
            int nRead = in.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            out.write(buffer, 0, nRead);
        }
        in.close();
    }
    out.close();
    stream.close();
}

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

@Override
public synchronized void saveContents(String contents, String prefix, int msgNum)
        throws IOException, GeneralSecurityException {
    JarOutputStream jos = getContentsJarOS(prefix);

    // create the bytes
    ZipEntry ze = new ZipEntry(msgNum + ".content");
    ze.setMethod(ZipEntry.DEFLATED);
    //      byte[] buf = CryptoUtils.getEncryptedBytes(contents.getBytes("UTF-8"));
    byte[] buf = contents.getBytes("UTF-8");
    jos.putNextEntry(ze);/*www.j  ava2 s .  c  om*/
    jos.write(buf, 0, buf.length);
    jos.closeEntry();
    jos.flush();
}

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  ww  w. j  av a2s.  c o m*/
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:org.colombbus.tangara.FileUtils.java

public static void makeJar(File directory, File jar, String mainClass, PropertyChangeListener listener,
        Hashtable<String, String> manifestAttributes) {
    JarOutputStream jarOutput = null;
    try {//w w  w . j av  a  2  s .  c  o m
        jarOutput = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)));
        addDirectoryToJar(directory, jarOutput, null, listener);
        StringBuffer sbuf = new StringBuffer();
        sbuf.append("Manifest-Version: 1.0\n");
        sbuf.append("Built-By: Colombbus\n");
        if (mainClass != null)
            sbuf.append("Main-Class: " + mainClass + "\n");
        if (manifestAttributes != null) {
            for (Enumeration<String> keys = manifestAttributes.keys(); keys.hasMoreElements();) {
                String name = keys.nextElement();
                sbuf.append(name + ": " + manifestAttributes.get(name) + "\n");
            }
        }
        InputStream is = new ByteArrayInputStream(sbuf.toString().getBytes("UTF-8"));

        JarEntry manifestEntry = new JarEntry("META-INF/MANIFEST.MF");
        jarOutput.putNextEntry(manifestEntry);

        byte buffer[] = new byte[2048];
        while (true) {
            int n = is.read(buffer);
            if (n <= 0)
                break;
            jarOutput.write(buffer, 0, n);
        }
        is.close();
        jarOutput.close();
    } catch (Exception e) {
        LOG.error("Error while creating JAR file '" + jar.getAbsolutePath() + "'", e);
    } finally {
        try {
            if (jarOutput != null)
                jarOutput.close();
        } catch (IOException e) {
        }
    }
}

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

/** Compiles a scala class
 * @param script/*w w w  .  jav a 2  s .  c o  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;
}