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 void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:org.apache.hadoop.hbase.TestClassFinder.java

/**
 * Makes a jar out of some class files. Unfortunately it's very tedious.
 * @param filesInJar Files created via compileTestClass.
 * @return path to the resulting jar file.
 */// w ww .  j  a  va 2 s . c  om
private static String packageAndLoadJar(FileAndPath... filesInJar) throws Exception {
    // First, write the bogus jar file.
    String path = basePath + "jar" + jarCounter.incrementAndGet() + ".jar";
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    FileOutputStream fos = new FileOutputStream(path);
    JarOutputStream jarOutputStream = new JarOutputStream(fos, manifest);
    // Directory entries for all packages have to be added explicitly for
    // resources to be findable via ClassLoader. Directory entries must end
    // with "/"; the initial one is expected to, also.
    Set<String> pathsInJar = new HashSet<String>();
    for (FileAndPath fileAndPath : filesInJar) {
        String pathToAdd = fileAndPath.path;
        while (pathsInJar.add(pathToAdd)) {
            int ix = pathToAdd.lastIndexOf('/', pathToAdd.length() - 2);
            if (ix < 0) {
                break;
            }
            pathToAdd = pathToAdd.substring(0, ix);
        }
    }
    for (String pathInJar : pathsInJar) {
        jarOutputStream.putNextEntry(new JarEntry(pathInJar));
        jarOutputStream.closeEntry();
    }
    for (FileAndPath fileAndPath : filesInJar) {
        File file = fileAndPath.file;
        jarOutputStream.putNextEntry(new JarEntry(fileAndPath.path + file.getName()));
        byte[] allBytes = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(allBytes);
        fis.close();
        jarOutputStream.write(allBytes);
        jarOutputStream.closeEntry();
    }
    jarOutputStream.close();
    fos.close();

    // Add the file to classpath.
    File jarFile = new File(path);
    assertTrue(jarFile.exists());
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
    method.setAccessible(true);
    method.invoke(urlClassLoader, new Object[] { jarFile.toURI().toURL() });
    return jarFile.getAbsolutePath();
}

From source file:com.wolvereness.overmapped.OverMapped.java

private void writeToFile(final MultiProcessor executor, final Map<String, ByteClass> byteClasses,
        final List<Pair<ZipEntry, byte[]>> fileEntries, final BiMap<String, String> nameMaps,
        final BiMap<Signature, Signature> signatureMaps, final Map<Signature, Integer> flags)
        throws IOException, FileNotFoundException, InterruptedException, ExecutionException {
    final Collection<Future<Pair<ZipEntry, byte[]>>> classWrites = newArrayList();
    for (final ByteClass clazz : byteClasses.values()) {
        classWrites.add(//  w w  w . ja v  a2s .c o  m
                executor.submit(clazz.callable(signatureMaps, nameMaps, byteClasses, flags, correctEnums)));
    }

    FileOutputStream fileOut = null;
    JarOutputStream jar = null;
    try {
        jar = new JarOutputStream(fileOut = new FileOutputStream(output));
        for (final Pair<ZipEntry, byte[]> fileEntry : fileEntries) {
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight());
        }
        for (final Future<Pair<ZipEntry, byte[]>> fileEntryFuture : classWrites) {
            final Pair<ZipEntry, byte[]> fileEntry = fileEntryFuture.get();
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight());
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (final IOException ex) {
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (final IOException ex) {
            }
        }
    }
}

From source file:com.android.builder.testing.MockableJarGenerator.java

/**
 * Writes a modified *.class file to the output JAR file.
 *//* w  ww .  j  a v a 2  s  .c o  m*/
private void rewriteClass(JarEntry entry, InputStream inputStream, JarOutputStream outputStream)
        throws IOException {
    ClassReader classReader = new ClassReader(inputStream);
    ClassNode classNode = new ClassNode(Opcodes.ASM5);

    classReader.accept(classNode, EMPTY_FLAGS);

    modifyClass(classNode);

    ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
    classNode.accept(classWriter);

    outputStream.putNextEntry(new ZipEntry(entry.getName()));
    outputStream.write(classWriter.toByteArray());
}

From source file:com.aliyun.odps.mapred.BridgeJobRunner.java

/**
 * Create jar with jobconf.//from   w  w w . java  2 s  .  c o m
 *
 * @return
 * @throws OdpsException
 */
private ByteArrayOutputStream createJarArchive() throws OdpsException {
    try {
        ByteArrayOutputStream archiveOut = new ByteArrayOutputStream();
        // Open archive file
        JarOutputStream out = new JarOutputStream(archiveOut, new Manifest());

        ByteArrayOutputStream jobOut = new ByteArrayOutputStream();
        job.writeXml(jobOut);
        // Add jobconf entry
        JarEntry jobconfEntry = new JarEntry("jobconf.xml");
        out.putNextEntry(jobconfEntry);
        out.write(jobOut.toByteArray());

        out.close();
        return archiveOut;
    } catch (IOException ex) {
        throw new OdpsException(ErrorCode.UNEXPECTED.toString(), ex);
    }
}

From source file:com.wolvereness.renumerated.Renumerated.java

private void process() throws Throwable {
    validateInput();//from  w  w w.  j av a 2s . c  o m

    final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1,
            new ThreadFactoryBuilder().setDaemon(true)
                    .setNameFormat(Renumerated.class.getName() + "-processor-%d")
                    .setUncaughtExceptionHandler(this).build());
    final Future<?> fileCopy = executor.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            if (original != null) {
                if (original.exists()) {
                    original.delete();
                }
                Files.copy(input, original);
            }
            return null;
        }
    });

    final List<Pair<ZipEntry, Future<byte[]>>> fileEntries = newArrayList();
    final List<Pair<MutableObject<ZipEntry>, Future<byte[]>>> classEntries = newArrayList();
    {
        final ZipFile input = new ZipFile(this.input);
        final Enumeration<? extends ZipEntry> inputEntries = input.entries();
        while (inputEntries.hasMoreElements()) {
            final ZipEntry entry = inputEntries.nextElement();
            final Future<byte[]> future = executor.submit(new Callable<byte[]>() {
                @Override
                public byte[] call() throws Exception {
                    return ByteStreams.toByteArray(input.getInputStream(entry));
                }
            });
            if (entry.getName().endsWith(".class")) {
                classEntries.add(new MutablePair<MutableObject<ZipEntry>, Future<byte[]>>(
                        new MutableObject<ZipEntry>(entry), future));
            } else {
                fileEntries.add(new ImmutablePair<ZipEntry, Future<byte[]>>(entry, future));
            }
        }

        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> pair : classEntries) {
            final byte[] data = pair.getRight().get();
            pair.setValue(executor.submit(new Callable<byte[]>() {
                String className;
                List<String> fields;

                @Override
                public byte[] call() throws Exception {
                    try {
                        return method();
                    } catch (final Exception ex) {
                        throw new Exception(pair.getLeft().getValue().getName(), ex);
                    }
                }

                private byte[] method() throws Exception {
                    final ClassReader clazz = new ClassReader(data);
                    clazz.accept(new ClassVisitor(ASM4) {
                        @Override
                        public void visit(final int version, final int access, final String name,
                                final String signature, final String superName, final String[] interfaces) {
                            if (superName.equals("java/lang/Enum")) {
                                className = name;
                            }
                        }

                        @Override
                        public FieldVisitor visitField(final int access, final String name, final String desc,
                                final String signature, final Object value) {
                            if (className != null && (access & 0x4000) != 0) {
                                List<String> fieldNames = fields;
                                if (fieldNames == null) {
                                    fieldNames = fields = newArrayList();
                                }
                                fieldNames.add(name);
                            }
                            return null;
                        }
                    }, ClassReader.SKIP_CODE);

                    if (className == null)
                        return data;

                    final String classDescriptor = Type.getObjectType(className).getDescriptor();

                    final ClassWriter writer = new ClassWriter(0);
                    clazz.accept(new ClassVisitor(ASM4, writer) {
                        @Override
                        public MethodVisitor visitMethod(final int access, final String name, final String desc,
                                final String signature, final String[] exceptions) {
                            final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature,
                                    exceptions);
                            if (!name.equals("<clinit>")) {
                                return methodVisitor;
                            }
                            return new MethodVisitor(ASM4, methodVisitor) {
                                final Iterator<String> it = fields.iterator();
                                boolean active;
                                String lastName;

                                @Override
                                public void visitTypeInsn(final int opcode, final String type) {
                                    if (!active && it.hasNext()) {
                                        // Initiate state machine
                                        if (opcode != NEW)
                                            throw new AssertionError("Unprepared for " + opcode + " on " + type
                                                    + " in " + className);
                                        active = true;
                                    }
                                    super.visitTypeInsn(opcode, type);
                                }

                                @Override
                                public void visitLdcInsn(final Object cst) {
                                    if (active && lastName == null) {
                                        if (!(cst instanceof String))
                                            throw new AssertionError(
                                                    "Unprepared for " + cst + " in " + className);
                                        // Switch the first constant in the Enum constructor
                                        super.visitLdcInsn(lastName = it.next());
                                    } else {
                                        super.visitLdcInsn(cst);
                                    }
                                }

                                @Override
                                public void visitFieldInsn(final int opcode, final String owner,
                                        final String name, final String desc) {
                                    if (opcode == PUTSTATIC && active && lastName != null
                                            && owner.equals(className) && desc.equals(classDescriptor)
                                            && name.equals(lastName)) {
                                        // Finish the current state machine
                                        active = false;
                                        lastName = null;
                                    }
                                    super.visitFieldInsn(opcode, owner, name, desc);
                                }
                            };
                        }
                    }, ClassReader.EXPAND_FRAMES);

                    final MutableObject<ZipEntry> key = pair.getLeft();
                    key.setValue(new ZipEntry(key.getValue().getName()));
                    return writer.toByteArray();
                }
            }));
        }

        for (final Pair<ZipEntry, Future<byte[]>> pair : fileEntries) {
            pair.getRight().get();
        }

        input.close();
    }

    fileCopy.get();

    FileOutputStream fileOut = null;
    JarOutputStream jar = null;
    try {
        jar = new JarOutputStream(fileOut = new FileOutputStream(output));
        for (final Pair<ZipEntry, Future<byte[]>> fileEntry : fileEntries) {
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight().get());
        }
        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> classEntry : classEntries) {
            final byte[] data = classEntry.getRight().get();
            final ZipEntry entry = classEntry.getLeft().getValue();
            entry.setSize(data.length);
            jar.putNextEntry(entry);
            jar.write(data);
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (final IOException ex) {
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (final IOException ex) {
            }
        }
    }

    final Pair<Thread, Throwable> uncaught = this.uncaught;
    if (uncaught != null)
        throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()),
                uncaught.getRight());
}

From source file:com.moss.nomad.core.packager.Packager.java

public void write(OutputStream o) throws Exception {

    JarOutputStream out = new JarOutputStream(o);

    {//  w ww .  j a v  a 2 s. co m
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(container, bao);

        byte[] containerIndex = bao.toByteArray();

        JarEntry entry = new JarEntry("META-INF/container.xml");
        out.putNextEntry(entry);
        out.write(containerIndex);
    }

    final byte[] buffer = new byte[1024 * 10]; //10k buffer

    for (String path : dependencies.keySet()) {
        ResolvedDependencyInfo info = dependencies.get(path);

        JarEntry entry = new JarEntry(path);
        out.putNextEntry(entry);

        InputStream in = new FileInputStream(info.file());
        for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
            out.write(buffer, 0, numRead);
        }
        in.close();
    }

    out.close();
}

From source file:com.speed.ob.api.ClassStore.java

public void dump(File in, File out, Config config) throws IOException {
    if (in.isDirectory()) {
        for (ClassNode node : nodes()) {
            String[] parts = node.name.split("\\.");
            String dirName = node.name.substring(0, node.name.lastIndexOf("."));
            dirName = dirName.replace(".", "/");
            File dir = new File(out, dirName);
            if (!dir.exists()) {
                if (!dir.mkdirs())
                    throw new IOException("Could not make output dir: " + dir.getAbsolutePath());
            }/*from ww w.  ja v  a  2 s  .com*/
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            FileOutputStream fOut = new FileOutputStream(
                    new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1)));
            fOut.write(data);
            fOut.flush();
            fOut.close();
        }
    } else if (in.getName().endsWith(".jar")) {
        File output = new File(out, in.getName());
        JarFile jf = new JarFile(in);
        HashMap<JarEntry, Object> existingData = new HashMap<>();
        if (output.exists()) {
            try {
                JarInputStream jarIn = new JarInputStream(new FileInputStream(output));
                JarEntry entry;
                while ((entry = jarIn.getNextJarEntry()) != null) {
                    if (!entry.isDirectory()) {
                        byte[] data = IOUtils.toByteArray(jarIn);
                        existingData.put(entry, data);
                        jarIn.closeEntry();
                    }
                }
                jarIn.close();
            } catch (IOException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                        "Could not read existing output file, overwriting", e);
            }
        }
        FileOutputStream fout = new FileOutputStream(output);
        Manifest manifest = null;
        if (jf.getManifest() != null) {
            manifest = jf.getManifest();
            if (!config.getBoolean("ClassNameTransform.keep_packages")
                    && config.getBoolean("ClassNameTransform.exclude_mains")) {
                manifest = new Manifest(manifest);
                if (manifest.getMainAttributes().getValue("Main-Class") != null) {
                    String manifestName = manifest.getMainAttributes().getValue("Main-Class");
                    if (manifestName.contains(".")) {
                        manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1);
                        manifest.getMainAttributes().putValue("Main-Class", manifestName);
                    }
                }
            }
        }
        jf.close();
        JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout)
                : new JarOutputStream(fout, manifest);
        Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files");
        if (!existingData.isEmpty()) {
            for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) {
                Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName());
                jarOut.putNextEntry(entry.getKey());
                jarOut.write((byte[]) entry.getValue());
                jarOut.closeEntry();
            }
        }
        for (ClassNode node : nodes()) {
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            int index = node.name.lastIndexOf("/");
            String fileName;
            if (index > 0) {
                fileName = node.name.substring(0, index + 1).replace(".", "/");
                fileName += node.name.substring(index + 1).concat(".class");
            } else {
                fileName = node.name.concat(".class");
            }
            JarEntry entry = new JarEntry(fileName);
            jarOut.putNextEntry(entry);
            jarOut.write(data);
            jarOut.closeEntry();
        }
        jarOut.close();
    } else {
        if (nodes().size() == 1) {
            File outputFile = new File(out, in.getName());
            ClassNode node = nodes().iterator().next();
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            byte[] data = writer.toByteArray();
            FileOutputStream stream = new FileOutputStream(outputFile);
            stream.write(data);
            stream.close();
        }
    }
}

From source file:com.alu.e3.prov.service.ApiJarBuilder.java

@Override
public byte[] build(Api api, ExchangeData exchange) {
    final Map<Object, Object> variablesMap = new HashMap<Object, Object>();
    variablesMap.put("exchange", exchange);

    byte[] jarBytes = null;
    ByteArrayOutputStream baos = null;
    JarOutputStream jos = null;
    try {//w w w .j av a 2 s  .c o m
        baos = new ByteArrayOutputStream();
        jos = new JarOutputStream(baos);

        List<JarEntryData> entries = new ArrayList<JarEntryData>();
        doGenXML(entries, api, variablesMap);
        doGenManifest(entries, api, variablesMap);
        doGenResources(entries, api, variablesMap);

        for (JarEntryData anEntry : entries) {
            jos.putNextEntry(anEntry.jarEntry);
            jos.write(anEntry.bytes);

        }
        // the close is necessary before getting bytes
        jos.close();
        jarBytes = baos.toByteArray();

        if (this.generateJarInFile) {
            // generate Jar in Disk for debug only
            doGenJar(jarBytes, api, variablesMap);
        }

    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Error building the jar for apiID:" + api.getId(), e);
        }
    } finally {
        if (jos != null)
            try {
                jos.close();
            } catch (IOException e) {
                LOG.error("Error closing stream", e);
            }

        if (baos != null)
            try {
                baos.close();
            } catch (IOException e) {
                LOG.error("Error closing stream", e);
            }
    }

    return jarBytes;
}

From source file:com.speed.ob.api.ClassStore.java

public void init(JarInputStream jarIn, File output, File in) throws IOException {
    ZipEntry entry;/*from  w w  w.ja  v  a2 s.  co m*/
    JarOutputStream out = new JarOutputStream(new FileOutputStream(new File(output, in.getName())));
    while ((entry = jarIn.getNextEntry()) != null) {
        byte[] data = IOUtils.toByteArray(jarIn);
        if (entry.getName().endsWith(".class")) {
            ClassReader reader = new ClassReader(data);
            ClassNode cn = new ClassNode();
            reader.accept(cn, ClassReader.EXPAND_FRAMES);
            store.put(cn.name, cn);
        } else if (!entry.isDirectory()) {
            Logger.getLogger(getClass().getName()).finer("Storing " + entry.getName() + " in output file");
            JarEntry je = new JarEntry(entry.getName());
            out.putNextEntry(je);
            out.write(data);
            out.closeEntry();
        }
    }
    out.close();
}

From source file:org.dspace.installer_edm.InstallerCrosswalk.java

/**
 * Aade contenido archivo class a nuevo archivo class en el jar
 *
 * @param jarOutputStream flujo de escritura para el jar
 * @throws IOException// w w w  .  j  a  v a  2s.c o  m
 */
protected void addClass2Jar(JarOutputStream jarOutputStream) throws IOException {
    File file = new File(myInstallerWorkDirPath + fileSeparator + edmCrossWalkClass);
    byte[] fileData = new byte[(int) file.length()];
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    dis.readFully(fileData);
    dis.close();
    jarOutputStream.putNextEntry(new JarEntry(edmCrossWalkClass));
    jarOutputStream.write(fileData);
    jarOutputStream.closeEntry();
}