Example usage for java.util.jar JarInputStream JarInputStream

List of usage examples for java.util.jar JarInputStream JarInputStream

Introduction

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

Prototype

public JarInputStream(InputStream in) throws IOException 

Source Link

Document

Creates a new JarInputStream and reads the optional manifest.

Usage

From source file:brooklyn.management.osgi.OsgiStandaloneTest.java

@Test
public void testReadKnownManifest() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    InputStream in = this.getClass().getResourceAsStream(BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    JarInputStream jarIn = new JarInputStream(in);
    ManifestHelper helper = Osgis.ManifestHelper.forManifest(jarIn.getManifest());
    jarIn.close();/*from  w ww  .j ava  2s  . c  om*/
    Assert.assertEquals(helper.getVersion().toString(), "0.1.0");
    Assert.assertTrue(helper.getExportedPackages().contains("brooklyn.osgi.tests"));
}

From source file:org.apache.brooklyn.core.mgmt.osgi.OsgiStandaloneTest.java

@Test
public void testReadKnownManifest() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    InputStream in = this.getClass().getResourceAsStream(BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    JarInputStream jarIn = new JarInputStream(in);
    ManifestHelper helper = Osgis.ManifestHelper.forManifest(jarIn.getManifest());
    jarIn.close();//w ww.j av a 2 s.  c  o m
    Assert.assertEquals(helper.getVersion().toString(), "0.1.0");
    Assert.assertTrue(helper.getExportedPackages().contains("org.apache.brooklyn.test.osgi.entities"));
}

From source file:org.rhq.enterprise.server.xmlschema.ServerPluginDescriptorUtil.java

/**
 * Loads a plugin descriptor from the given plugin jar and returns it. If the given jar does not
 * have a server plugin descriptor, <code>null</code> will be returned, meaning this is not
 * a server plugin jar./*from w  ww .  ja  va 2s  .co m*/
 *  
 * @param pluginJarFileUrl URL to a plugin jar file
 * @return the plugin descriptor found in the given plugin jar file, or <code>null</code> if there
 *         is no plugin descriptor in the jar file
 * @throws Exception if failed to parse the descriptor file found in the plugin jar
 */
public static ServerPluginDescriptorType loadPluginDescriptorFromUrl(URL pluginJarFileUrl) throws Exception {

    final Log logger = LogFactory.getLog(ServerPluginDescriptorUtil.class);

    if (pluginJarFileUrl == null) {
        throw new Exception("A valid plugin JAR URL must be supplied.");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Loading plugin descriptor from plugin jar at [" + pluginJarFileUrl + "]...");
    }

    testPluginJarIsReadable(pluginJarFileUrl);

    JarInputStream jis = null;
    JarEntry descriptorEntry = null;

    try {
        jis = new JarInputStream(pluginJarFileUrl.openStream());
        JarEntry nextEntry = jis.getNextJarEntry();
        while (nextEntry != null && descriptorEntry == null) {
            if (PLUGIN_DESCRIPTOR_PATH.equals(nextEntry.getName())) {
                descriptorEntry = nextEntry;
            } else {
                jis.closeEntry();
                nextEntry = jis.getNextJarEntry();
            }
        }

        ServerPluginDescriptorType pluginDescriptor = null;

        if (descriptorEntry != null) {
            Unmarshaller unmarshaller = null;
            try {
                unmarshaller = getServerPluginDescriptorUnmarshaller();
                Object jaxbElement = unmarshaller.unmarshal(jis);
                pluginDescriptor = ((JAXBElement<? extends ServerPluginDescriptorType>) jaxbElement).getValue();
            } finally {
                if (unmarshaller != null) {
                    ValidationEventCollector validationEventCollector = (ValidationEventCollector) unmarshaller
                            .getEventHandler();
                    logValidationEvents(pluginJarFileUrl, validationEventCollector);
                }
            }
        }

        return pluginDescriptor;

    } catch (Exception e) {
        throw new Exception("Could not successfully parse the plugin descriptor [" + PLUGIN_DESCRIPTOR_PATH
                + "] found in plugin jar at [" + pluginJarFileUrl + "]", e);
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (Exception e) {
                logger.warn("Cannot close jar stream [" + pluginJarFileUrl + "]. Cause: " + e);
            }
        }
    }
}

From source file:com.github.sampov2.OneJarMojo.java

private JarInputStream openOnejarTemplateArchive() throws IOException {
    if (localOneJarTemplate != null) {
        return new JarInputStream(new FileInputStream(new File(project.getBasedir(), localOneJarTemplate)));
    } else {//from  www  . ja  va  2 s  .co  m
        return new JarInputStream(getClass().getClassLoader().getResourceAsStream(getOnejarArchiveName()));
    }
}

From source file:com.ottogroup.bi.asap.repository.ComponentClassloader.java

/**
 * Initializes the class loader by pointing it to folder holding managed JAR files
 * @param componentFolder//from  w ww.  j  ava2 s  . c  o m
 * @param componentJarIdentifier file to search for in component JAR which identifies it as component JAR 
 * @throws IOException
 * @throws RequiredInputMissingException
 */
public void initialize(final String componentFolder, final String componentJarIdentifier)
        throws IOException, RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(componentFolder))
        throw new RequiredInputMissingException("Missing required value for parameter 'componentFolder'");

    File folder = new File(componentFolder);
    if (!folder.isDirectory())
        throw new IOException("Provided input '" + componentFolder + "' does not reference a valid folder");

    File[] jarFiles = folder.listFiles();
    if (jarFiles == null || jarFiles.length < 1)
        throw new RequiredInputMissingException("No JAR files found in folder '" + componentFolder + "'");
    //
    ///////////////////////////////////////////////////////////////////

    logger.info("Initializing component classloader [componentJarIdentifier=" + componentJarIdentifier
            + ", folder=" + componentFolder + "]");

    // step through jar files, ensure it is a file and iterate through its contents
    for (File jarFile : jarFiles) {
        if (jarFile.isFile()) {

            JarInputStream jarInputStream = null;
            try {
                jarInputStream = new JarInputStream(new FileInputStream(jarFile));
                JarEntry jarEntry = null;
                while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
                    String jarEntryName = jarEntry.getName();
                    // if the current file references a class implementation, replace slashes by dots, strip 
                    // away the class suffix and add a reference to the classes-2-jar mapping 
                    if (StringUtils.endsWith(jarEntryName, ".class")) {
                        jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                        this.classesJarMapping.put(jarEntryName, jarFile.getAbsolutePath());
                    } else {
                        // if the current file references a resource, check if it is the identifier file which
                        // marks this jar to contain component implementation                     
                        if (StringUtils.equalsIgnoreCase(jarEntryName, componentJarIdentifier))
                            this.componentJarFiles.add(jarFile.getAbsolutePath());
                        // ...and add a mapping for resource to jar file as well                     
                        this.resourcesJarMapping.put(jarEntryName, jarFile.getAbsolutePath());
                    }
                }
            } catch (Exception e) {
                logger.error("Failed to read from JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                        + e.getMessage());
            } finally {
                try {
                    jarInputStream.close();
                } catch (Exception e) {
                    logger.error("Failed to close open JAR file '" + jarFile.getAbsolutePath() + "'. Error: "
                            + e.getMessage());
                }
            }
        }
    }

    // load classes from jars marked component files and extract the deployment descriptors
    for (String cjf : this.componentJarFiles) {
        logger.info("Attempting to load pipeline components located in '" + cjf + "'");

        // open JAR file and iterate through it's contents
        JarInputStream jarInputStream = null;
        try {
            jarInputStream = new JarInputStream(new FileInputStream(cjf));
            JarEntry jarEntry = null;
            while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {

                // fetch name of current entry and ensure it is a class file
                String jarEntryName = jarEntry.getName();
                if (jarEntryName.endsWith(".class")) {
                    // replace slashes by dots and strip away '.class' suffix
                    jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 6).replace('/', '.');
                    Class<?> c = loadClass(jarEntryName);
                    AsapComponent pc = c.getAnnotation(AsapComponent.class);
                    if (pc != null) {
                        this.managedComponents.put(getManagedComponentKey(pc.name(), pc.version()),
                                new ComponentDescriptor(c.getName(), pc.type(), pc.name(), pc.version(),
                                        pc.description()));
                        logger.info("pipeline component found [type=" + pc.type() + ", name=" + pc.name()
                                + ", version=" + pc.version() + "]");
                        ;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Failed to read from JAR file '" + cjf + "'. Error: " + e.getMessage());
        } finally {
            try {
                jarInputStream.close();
            } catch (Exception e) {
                logger.error("Failed to close open JAR file '" + cjf + "'. Error: " + e.getMessage());
            }
        }
    }
}

From source file:org.bluedolmen.alfresco.marketplace.utils.ModuleManager.java

public JarInputStream getModuleInputStream(final NodeRef moduleNode) throws IOException {

    if (null == moduleNode) {
        throw new NullPointerException("The provided nodeRef is null");
    }/* w  ww.jav a  2 s  .  c  o m*/

    final ContentReader contentReader = contentService.getReader(moduleNode, ContentModel.PROP_CONTENT);
    if (!contentReader.exists())
        return null;

    final InputStream inputStream = contentReader.getContentInputStream();
    return new JarInputStream(inputStream);

}

From source file:org.webical.plugin.classloading.PluginClassLoader.java

/**
 * Reads in all classes in a jar file for later reference
 * @param name the full name and path of the jar file
 * @throws PluginException //  w w w.  j ava 2 s.c om
 */
public void readJarFile(File jarFile) throws PluginException {
    //Firstly check input
    if (jarFile == null) {
        log.error("Cannot load jar without a reference...");
        throw new PluginException("Cannot load jar without a reference...");
    }

    JarInputStream jis;
    JarEntry je;

    if (!jarFile.exists()) {
        log.error("Jar does not exist: " + jarFile.getAbsolutePath());
        throw new PluginException("Jar does not exist: " + jarFile.getAbsolutePath());
    }
    if (!jarFile.canRead()) {
        log.error("Jar is not readable: " + jarFile.getAbsolutePath());
        throw new PluginException("Jar is not readable: " + jarFile.getAbsolutePath());
    }
    if (log.isDebugEnabled())
        log.debug("Loading jar file " + jarFile);

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(jarFile);
        jis = new JarInputStream(fis);
    } catch (IOException ioe) {
        log.error("Can't open jar file " + jarFile, ioe);
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.error("Could not close filehandle to: " + jarFile.getAbsolutePath(), e);
                throw new PluginException("Could not close filehandle to: " + jarFile.getAbsolutePath(), e);
            }
        }
        throw new PluginException("Can't open jar file " + jarFile, ioe);
    }

    //Loop over the jarfile entries
    try {
        while ((je = jis.getNextJarEntry()) != null) {
            String jarEntryName = je.getName();
            //Skip the META-INF dir
            if (jarEntryName.startsWith(META_INF)) {
                continue;
            }

            if (jarEntryName.endsWith(FileUtils.CLASS_FILE_EXTENSION)) {
                //Extract java class
                loadClassBytes(jis, ClassUtils.fileToFullClassName(jarEntryName));
            } else if (je.isDirectory()) {
                //Extract directory
                unpackDirectory(jarEntryName, jarFile);
            } else {
                //it could be an image or audio file so let's extract it and store it somewhere for later reference
                try {
                    extractJarResource(jis, jarEntryName, jarFile);
                } catch (Exception e) {
                    log.error("Cannot cache jar resource: " + jarEntryName + " from jar file: "
                            + jarFile.getAbsolutePath(), e);
                    throw new PluginException("Cannot cache jar resource: " + jarEntryName + " from jar file: "
                            + jarFile.getAbsolutePath(), e);
                }
            }
            jis.closeEntry();
        }
    } catch (IOException ioe) {
        log.error("Badly formatted jar file: " + jarFile.getAbsolutePath(), ioe);
        throw new PluginException("Badly formatted jar file: " + jarFile.getAbsolutePath(), ioe);
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (IOException e) {
                log.error("Could not close connection to jar: " + jarFile.getAbsolutePath(), e);
                throw new PluginException("Could not close connection to jar: " + jarFile.getAbsolutePath(), e);
            }
        }
    }
}

From source file:org.eclipse.gemini.blueprint.util.DebugUtils.java

private static URL checkBundleJarsForClass(Bundle bundle, String name) {
    String cname = name.replace('.', '/') + ".class";
    for (Enumeration e = bundle.findEntries("/", "*.jar", true); e != null && e.hasMoreElements();) {
        URL url = (URL) e.nextElement();
        JarInputStream jin = null;
        try {//from ww w . ja  va 2  s  .c  om
            jin = new JarInputStream(url.openStream());
            // Copy entries from the real jar to our virtual jar
            for (JarEntry ze = jin.getNextJarEntry(); ze != null; ze = jin.getNextJarEntry()) {
                if (ze.getName().equals(cname)) {
                    jin.close();
                    return url;
                }
            }
        } catch (IOException e1) {
            log.trace("Skipped " + url.toString() + ": " + e1.getMessage());
        }

        finally {
            if (jin != null) {
                try {
                    jin.close();
                } catch (Exception ex) {
                    // ignore it
                }
            }
        }

    }
    return null;
}

From source file:org.apache.sling.osgi.obr.Repository.java

File spoolModified(InputStream ins) throws IOException {
    JarInputStream jis = new JarInputStream(ins);

    // immediately handle the manifest
    JarOutputStream jos;//ww  w.ja  va 2s.  c o  m
    Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Missing Manifest !");
    }

    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    if (symbolicName == null || symbolicName.length() == 0) {
        throw new IOException("Missing Symbolic Name in Manifest !");
    }

    String version = manifest.getMainAttributes().getValue("Bundle-Version");
    Version v = Version.parseVersion(version);
    if (v.getQualifier().indexOf("SNAPSHOT") >= 0) {
        String tStamp;
        synchronized (DATE_FORMAT) {
            tStamp = DATE_FORMAT.format(new Date());
        }
        version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "."
                + v.getQualifier().replaceAll("SNAPSHOT", tStamp);
        manifest.getMainAttributes().putValue("Bundle-Version", version);
    }

    File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar");
    OutputStream out = null;
    try {
        out = new FileOutputStream(bundle);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                spool(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();

    } finally {
        IOUtils.closeQuietly(out);
    }

    return bundle;
}

From source file:cn.com.ebmp.freesql.io.ResolverUtil.java

/**
 * Recursively list all resources under the given URL that appear to define
 * a Java class. Matching resources will have a name that ends in ".class"
 * and have a relative path such that each segment of the path is a valid
 * Java identifier. The resource paths returned will be relative to the URL
 * and begin with the specified path.// ww w  . j  ava 2s  .co m
 * 
 * @param url
 *            The URL of the parent resource to search.
 * @param path
 *            The path with which each matching resource path must begin,
 *            relative to the URL.
 * @return A list of matching resources. The list may be empty.
 * @throws IOException
 */
protected List<String> listClassResources(URL url, String path) throws IOException {
    log.debug("Listing classes in " + url);

    InputStream is = null;
    try {
        List<String> resources = new ArrayList<String>();

        // First, try to find the URL of a JAR file containing the requested
        // resource. If a JAR
        // file is found, then we'll list child resources by reading the
        // JAR.
        URL jarUrl = findJarForResource(url, path);
        if (jarUrl != null) {
            is = jarUrl.openStream();
            resources = listClassResources(new JarInputStream(is), path);
        } else {
            List<String> children = new ArrayList<String>();
            try {
                if (isJar(url)) {
                    // Some versions of JBoss VFS might give a JAR stream
                    // even if the resource
                    // referenced by the URL isn't actually a JAR
                    is = url.openStream();
                    JarInputStream jarInput = new JarInputStream(is);
                    for (JarEntry entry; (entry = jarInput.getNextJarEntry()) != null;) {
                        log.debug("Jar entry: " + entry.getName());
                        if (isRelevantResource(entry.getName())) {
                            children.add(entry.getName());
                        }
                    }
                } else {
                    // Some servlet containers allow reading from
                    // "directory" resources like a
                    // text file, listing the child resources one per line.
                    is = url.openStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    for (String line; (line = reader.readLine()) != null;) {
                        log.debug("Reader entry: " + line);
                        if (isRelevantResource(line)) {
                            children.add(line);
                        }
                    }
                }
            } catch (FileNotFoundException e) {
                /*
                 * For file URLs the openStream() call might fail, depending
                 * on the servlet container, because directories can't be
                 * opened for reading. If that happens, then list the
                 * directory directly instead.
                 */
                if ("file".equals(url.getProtocol())) {
                    File file = new File(url.getFile());
                    log.debug("Listing directory " + file.getAbsolutePath());
                    if (file.isDirectory()) {
                        children = Arrays.asList(file.list(new FilenameFilter() {
                            public boolean accept(File dir, String name) {
                                return isRelevantResource(name);
                            }
                        }));
                    }
                } else {
                    // No idea where the exception came from so rethrow it
                    throw e;
                }
            }

            // The URL prefix to use when recursively listing child
            // resources
            String prefix = url.toExternalForm();
            if (!prefix.endsWith("/"))
                prefix = prefix + "/";

            // Iterate over each immediate child, adding classes and
            // recursing into directories
            for (String child : children) {
                String resourcePath = path + "/" + child;
                if (child.endsWith(".class")) {
                    log.debug("Found class file: " + resourcePath);
                    resources.add(resourcePath);
                } else {
                    URL childUrl = new URL(prefix + child);
                    resources.addAll(listClassResources(childUrl, resourcePath));
                }
            }
        }

        return resources;
    } finally {
        try {
            is.close();
        } catch (Exception e) {
        }
    }
}