Example usage for java.util.jar JarOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

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

@Test
public void testWarUploadFullMvnPath() throws Exception {
    String warPath = "org.acme/acme-ui/1.0/acme-ui-1.0.war";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream jas = new JarOutputStream(baos);
    addEntry(jas, "WEB-INF/web.xml", "<web/>".getBytes());
    jas.close();

    byte[] contents = baos.toByteArray();

    testUpload(warPath, contents, false);
}

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

@Test
public void testWarUploadNoMvnPath() throws Exception {
    String warPath = "acme-ui-1.0.war";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream jas = new JarOutputStream(baos);
    addEntry(jas, "WEB-INF/web.xml", "<web/>".getBytes());
    jas.close();

    byte[] contents = baos.toByteArray();

    testUpload(warPath, contents, true);
}

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 {//ww w . j av  a  2  s.co  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: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();

    byte[] contents = baos.toByteArray();

    testUpload(jarPath, contents, false);
}

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

@Test
public void testWarUploadWithMvnPom() throws Exception {
    String warPath = "org.acme/acme-ui/1.0/acme-ui-1.0.war";

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream jas = new JarOutputStream(baos);
    addEntry(jas, "WEB-INF/web.xml", "<web/>".getBytes());
    addPom(jas, "org.acme", "acme-ui", "1.0");
    jas.close();

    byte[] contents = baos.toByteArray();

    testUpload(warPath, contents, false);
}

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

/** Compiles a scala class
 * @param script// ww  w  . j a  v a  2 s.com
 * @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.pig.impl.util.JarManager.java

private static void createPigScriptUDFJar(OutputStream os, PigContext pigContext,
        HashMap<String, String> contents) throws IOException {
    JarOutputStream jarOutputStream = new JarOutputStream(os);
    for (String path : pigContext.scriptFiles) {
        log.debug("Adding entry " + path + " to job jar");
        InputStream stream = null;
        File inputFile = new File(path);
        if (inputFile.exists()) {
            stream = new FileInputStream(inputFile);
        } else {/*from w  w w  .j a va2  s.  co  m*/
            stream = PigContext.getClassLoader().getResourceAsStream(path);
        }
        if (stream == null) {
            throw new IOException("Cannot find " + path);
        }
        try {
            addStream(jarOutputStream, path, stream, contents, inputFile.lastModified());
        } finally {
            stream.close();
        }
    }
    for (Map.Entry<String, File> entry : pigContext.getScriptFiles().entrySet()) {
        log.debug("Adding entry " + entry.getKey() + " to job jar");
        InputStream stream = null;
        if (entry.getValue().exists()) {
            stream = new FileInputStream(entry.getValue());
        } else {
            stream = PigContext.getClassLoader().getResourceAsStream(entry.getValue().getPath());
        }
        if (stream == null) {
            throw new IOException("Cannot find " + entry.getValue().getPath());
        }
        try {
            addStream(jarOutputStream, entry.getKey(), stream, contents, entry.getValue().lastModified());
        } finally {
            stream.close();
        }
    }
    if (!contents.isEmpty()) {
        jarOutputStream.close();
    } else {
        os.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  ww  .  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:org.jahia.modules.serversettings.portlets.BasePortletHelper.java

/**
 * Returns a file descriptor for the modified (prepared) portlet WAR file.
 * // w w  w .j a va2  s .c o m
 * @param sourcePortletWar
 *            the source portlet WAR file
 * @return a file descriptor for the modified (prepared) portlet WAR file
 * @throws IOException
 *             in case of processing error
 */
public File process(File sourcePortletWar) throws IOException {
    JarFile jar = new JarFile(sourcePortletWar);
    File dest = new File(FilenameUtils.getFullPathNoEndSeparator(sourcePortletWar.getPath()),
            FilenameUtils.getBaseName(sourcePortletWar.getName()) + ".war");
    try {
        boolean needsServerSpecificProcessing = needsProcessing(jar);
        if (portletTldsPresent(jar) && !needsServerSpecificProcessing) {
            return sourcePortletWar;
        }
        jar.close();
        final JarInputStream jarIn = new JarInputStream(new FileInputStream(sourcePortletWar));
        final Manifest manifest = jarIn.getManifest();
        final JarOutputStream jarOut;
        if (manifest != null) {
            jarOut = new JarOutputStream(new FileOutputStream(dest), manifest);
        } else {
            jarOut = new JarOutputStream(new FileOutputStream(dest));
        }

        try {
            copyEntries(jarIn, jarOut);

            process(jarIn, jarOut);

            if (!hasPortletTld) {
                addToJar("META-INF/portlet-resources/portlet.tld", "WEB-INF/portlet.tld", jarOut);
            }
            if (!hasPortlet2Tld) {
                addToJar("META-INF/portlet-resources/portlet_2_0.tld", "WEB-INF/portlet_2_0.tld", jarOut);
            }
        } finally {
            jarIn.close();
            jarOut.close();
            FileUtils.deleteQuietly(sourcePortletWar);
        }
        return dest;
    } finally {
        jar.close();
    }
}

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

private boolean createFeatureJar(final String featureId, final String featureVersion, final String featureXml,
        final String jarDir) {

    final File file = new File(jarDir, featureId + "_" + featureVersion + ".jar");
    file.getParentFile().mkdirs();/*from  www .jav  a  2  s . c om*/

    try {
        final JarOutputStream jarOutputStream = new JarOutputStream(
                new BufferedOutputStream(new FileOutputStream(file)));

        final JarEntry entry = new JarEntry("feature.xml");
        jarOutputStream.putNextEntry(entry);

        final BufferedInputStream featureXmlStream = new BufferedInputStream(new FileInputStream(featureXml));
        copy(featureXmlStream, jarOutputStream);

        jarOutputStream.close();

    } catch (final FileNotFoundException e) {
        throw new RuntimeException("Could not create Feature Jar: " + file.getAbsolutePath(), e);
    } catch (final IOException e) {
        throw new RuntimeException("Could not create Feature Jar: " + file.getAbsolutePath(), e);
    }

    return true;
}