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.reficio.p2.FeatureBuilder.java

private void addToJar(JarOutputStream jar, File content) throws IOException {
    for (File f : FileUtils.listFiles(content, null, true)) {
        String fname = f.getPath().replace("\\", "/");
        if (f.isDirectory()) {
            if (!fname.endsWith("/")) {
                fname = fname + "/";
            }//from   ww  w.j  a v  a2s . com
            JarEntry entry = new JarEntry(fname);
            entry.setTime(f.lastModified());
            jar.putNextEntry(entry);
            jar.closeEntry();
        } else {
            //must be a file
            JarEntry entry = new JarEntry(fname);
            entry.setTime(f.lastModified());
            jar.putNextEntry(entry);
            jar.write(IOUtils.toByteArray(new FileInputStream(f)));
            jar.closeEntry();
        }

    }
}

From source file:org.atricore.josso.tooling.wrapper.InstallCommand.java

private void createJar(File outFile, String resource) throws Exception {
    if (!outFile.exists()) {
        System.out.println(Ansi.ansi().a("Creating file: ").a(Ansi.Attribute.INTENSITY_BOLD)
                .a(outFile.getPath()).a(Ansi.Attribute.RESET).toString());
        InputStream is = getClass().getClassLoader().getResourceAsStream(resource);
        if (is == null) {
            throw new IllegalStateException("Resource " + resource + " not found!");
        }//from w ww.ja  v  a  2 s  . co  m
        try {
            JarOutputStream jar = new JarOutputStream(new FileOutputStream(outFile));
            int idx = resource.indexOf('/');
            while (idx > 0) {
                jar.putNextEntry(new ZipEntry(resource.substring(0, idx)));
                jar.closeEntry();
                idx = resource.indexOf('/', idx + 1);
            }
            jar.putNextEntry(new ZipEntry(resource));
            int c;
            while ((c = is.read()) >= 0) {
                jar.write(c);
            }
            jar.closeEntry();
            jar.close();
        } finally {
            safeClose(is);
        }
    }
}

From source file:org.apache.hadoop.mapreduce.v2.TestMRJobs.java

private Path makeJar(Path p, int index) throws FileNotFoundException, IOException {
    FileOutputStream fos = new FileOutputStream(new File(p.toUri().getPath()));
    JarOutputStream jos = new JarOutputStream(fos);
    ZipEntry ze = new ZipEntry("distributed.jar.inside" + index);
    jos.putNextEntry(ze);/*from  w ww .  ja va2  s  .co  m*/
    jos.write(("inside the jar!" + index).getBytes());
    jos.closeEntry();
    jos.close();
    localFs.setPermission(p, new FsPermission("700"));
    return p;
}

From source file:org.apache.phoenix.end2end.UserDefinedFunctionsIT.java

/**
 * Compiles the test class with bogus code into a .class file.
 * Upon finish, the bogus jar will be left at dynamic.jar.dir location
 *///  w ww .j a  v  a 2  s. c  o m
private static void compileTestClass(String className, String program, int counter) throws Exception {
    String javaFileName = className + ".java";
    File javaFile = new File(javaFileName);
    String classFileName = className + ".class";
    File classFile = new File(classFileName);
    String jarName = "myjar" + counter + ".jar";
    String jarPath = "." + File.separator + jarName;
    File jarFile = new File(jarPath);
    try {
        String packageName = "org.apache.phoenix.end2end";
        FileOutputStream fos = new FileOutputStream(javaFileName);
        fos.write(program.getBytes());
        fos.close();

        JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
        int result = jc.run(null, null, null, javaFileName);
        assertEquals(0, result);

        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        FileOutputStream jarFos = new FileOutputStream(jarPath);
        JarOutputStream jarOutputStream = new JarOutputStream(jarFos, manifest);
        String pathToAdd = packageName.replace('.', '/') + '/';
        String jarPathStr = new String(pathToAdd);
        Set<String> pathsInJar = new HashSet<String>();

        while (pathsInJar.add(jarPathStr)) {
            int ix = jarPathStr.lastIndexOf('/', jarPathStr.length() - 2);
            if (ix < 0) {
                break;
            }
            jarPathStr = jarPathStr.substring(0, ix);
        }
        for (String pathInJar : pathsInJar) {
            jarOutputStream.putNextEntry(new JarEntry(pathInJar));
            jarOutputStream.closeEntry();
        }

        jarOutputStream.putNextEntry(new JarEntry(pathToAdd + classFile.getName()));
        byte[] allBytes = new byte[(int) classFile.length()];
        FileInputStream fis = new FileInputStream(classFile);
        fis.read(allBytes);
        fis.close();
        jarOutputStream.write(allBytes);
        jarOutputStream.closeEntry();
        jarOutputStream.close();
        jarFos.close();

        assertTrue(jarFile.exists());
        Connection conn = driver.connect(url, EMPTY_PROPS);
        Statement stmt = conn.createStatement();
        stmt.execute("add jars '" + jarFile.getAbsolutePath() + "'");
    } finally {
        if (javaFile != null)
            javaFile.delete();
        if (classFile != null)
            classFile.delete();
        if (jarFile != null)
            jarFile.delete();
    }
}

From source file:JarEntryOutputStream.java

/**
 * Writes the entry to a the jar file.  This is done by creating a
 * temporary jar file, copying the contents of the existing jar to the
 * temp jar, skipping the entry named by this.jarEntryName if it exists.
 * Then, if the stream was written to, then contents are written as a
 * new entry.  Last, a callback is made to the EnhancedJarFile to
 * swap the temp jar in for the old jar.
 *//*ww w  .ja va  2  s .c o  m*/
private void writeToJar() throws IOException {

    File jarDir = new File(this.jar.getName()).getParentFile();
    // create new jar
    File newJarFile = File.createTempFile("config", ".jar", jarDir);
    newJarFile.deleteOnExit();
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        Enumeration entries = this.jar.entries();

        // copy all current entries into the new jar
        while (entries.hasMoreElements()) {
            JarEntry nextEntry = (JarEntry) entries.nextElement();
            // skip the entry named jarEntryName
            if (!this.jarEntryName.equals(nextEntry.getName())) {
                // the next 3 lines of code are a work around for
                // bug 4682202 in the java.sun.com bug parade, see:
                // http://developer.java.sun.com/developer/bugParade/bugs/4682202.html
                JarEntry entryCopy = new JarEntry(nextEntry);
                entryCopy.setCompressedSize(-1);
                jarOutputStream.putNextEntry(entryCopy);

                InputStream intputStream = this.jar.getInputStream(nextEntry);
                // write the data
                for (int data = intputStream.read(); data != -1; data = intputStream.read()) {

                    jarOutputStream.write(data);
                }
            }
        }

        // write the new or modified entry to the jar
        if (size() > 0) {
            jarOutputStream.putNextEntry(new JarEntry(this.jarEntryName));
            jarOutputStream.write(super.buf, 0, size());
            jarOutputStream.closeEntry();
        }
    } finally {
        // close close everything up
        try {
            if (jarOutputStream != null) {
                jarOutputStream.close();
            }
        } catch (IOException ioe) {
            // eat it, just wanted to close stream
        }
    }

    // swap the jar
    this.jar.swapJars(newJarFile);
}

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

/**
 * Aadimos el contenido del documento jdom como archivo web.xml al flujo de escritura del war
 *
 * @param jarOutputStream flujo de escritura del war
 * @throws TransformerException/*ww  w .j  a v  a  2s. c  om*/
 * @throws IOException
 */
private void addNewWebXml(JarOutputStream jarOutputStream) throws TransformerException, IOException {
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    DocumentType docType = eDMExportDocument.getDoctype();
    if (docType != null) {
        if (docType.getPublicId() != null)
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
    }
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(eDMExportDocument);
    transformer.transform(source, result);
    String xmlString = sw.toString();
    jarOutputStream.putNextEntry(new JarEntry("WEB-INF/web.xml"));
    jarOutputStream.write(xmlString.getBytes());
    jarOutputStream.closeEntry();
}

From source file:org.gradle.jvm.tasks.api.ApiJar.java

@TaskAction
public void createApiJar() throws IOException {
    // Make sure all entries are always written in the same order
    final File[] sourceFiles = sortedSourceFiles();
    final ApiClassExtractor apiClassExtractor = new ApiClassExtractor(getExportedPackages());
    withResource(new JarOutputStream(new BufferedOutputStream(new FileOutputStream(getOutputFile()), 65536)),
            new ErroringAction<JarOutputStream>() {
                @Override//from  ww  w . j  av a2s . com
                protected void doExecute(final JarOutputStream jos) throws Exception {
                    writeManifest(jos);
                    writeClasses(jos);
                }

                private void writeManifest(JarOutputStream jos) throws IOException {
                    writeEntry(jos, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes());
                }

                private void writeClasses(JarOutputStream jos) throws Exception {
                    for (File sourceFile : sourceFiles) {
                        if (!isClassFile(sourceFile)) {
                            continue;
                        }
                        ClassReader classReader = new ClassReader(readFileToByteArray(sourceFile));
                        if (!apiClassExtractor.shouldExtractApiClassFrom(classReader)) {
                            continue;
                        }

                        byte[] apiClassBytes = apiClassExtractor.extractApiClassFrom(classReader);
                        String internalClassName = classReader.getClassName();
                        String entryPath = internalClassName + ".class";
                        writeEntry(jos, entryPath, apiClassBytes);
                    }
                }

                private void writeEntry(JarOutputStream jos, String name, byte[] bytes) throws IOException {
                    JarEntry je = new JarEntry(name);
                    // Setting time to 0 because we need API jars to be identical independently of
                    // the timestamps of class files
                    je.setTime(0);
                    je.setSize(bytes.length);
                    jos.putNextEntry(je);
                    jos.write(bytes);
                    jos.closeEntry();
                }
            });
}

From source file:org.nuclos.server.customcode.codegenerator.NuclosJavaCompilerComponent.java

private synchronized void jar(Map<String, byte[]> javacresult, List<CodeGenerator> generators) {
    try {/*from w w w .  ja  va2 s . co  m*/
        final boolean oldExists = moveJarToOld();
        if (javacresult.size() > 0) {
            final Set<String> entries = new HashSet<String>();
            final JarOutputStream jos = new JarOutputStream(
                    new BufferedOutputStream(new FileOutputStream(JARFILE)), getManifest());

            try {
                for (final String key : javacresult.keySet()) {
                    entries.add(key);
                    byte[] bytecode = javacresult.get(key);

                    // create entry for directory (required for classpath scanning)
                    if (key.contains("/")) {
                        String dir = key.substring(0, key.lastIndexOf('/') + 1);
                        if (!entries.contains(dir)) {
                            entries.add(dir);
                            jos.putNextEntry(new JarEntry(dir));
                            jos.closeEntry();
                        }
                    }

                    // call postCompile() (weaving) on compiled sources
                    for (CodeGenerator generator : generators) {
                        if (!oldExists || generator.isRecompileNecessary()) {
                            for (JavaSourceAsString src : generator.getSourceFiles()) {
                                final String name = src.getFQName();
                                if (key.startsWith(name.replaceAll("\\.", "/"))) {
                                    LOG.debug("postCompile (weaving) " + key);
                                    bytecode = generator.postCompile(key, bytecode);
                                    // Can we break here???
                                    // break outer;
                                }
                            }
                        }
                    }
                    jos.putNextEntry(new ZipEntry(key));
                    LOG.debug("writing to " + key + " to jar " + JARFILE);
                    jos.write(bytecode);
                    jos.closeEntry();
                }

                if (oldExists) {
                    final JarInputStream in = new JarInputStream(
                            new BufferedInputStream(new FileInputStream(JARFILE_OLD)));
                    final byte[] buffer = new byte[2048];
                    try {
                        int size;
                        JarEntry entry;
                        while ((entry = in.getNextJarEntry()) != null) {
                            if (!entries.contains(entry.getName())) {
                                jos.putNextEntry(entry);
                                LOG.debug("copying " + entry.getName() + " from old jar " + JARFILE_OLD);
                                while ((size = in.read(buffer, 0, buffer.length)) != -1) {
                                    jos.write(buffer, 0, size);
                                }
                                jos.closeEntry();
                            }
                            in.closeEntry();
                        }
                    } finally {
                        in.close();
                    }
                }
            } finally {
                jos.close();
            }
        }
    } catch (IOException ex) {
        throw new NuclosFatalException(ex);
    }
}