Example usage for java.util.jar Attributes getValue

List of usage examples for java.util.jar Attributes getValue

Introduction

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

Prototype

public String getValue(Name name) 

Source Link

Document

Returns the value of the specified Attributes.Name, or null if the attribute was not found.

Usage

From source file:com.orange.mmp.module.osgi.MMPOSGiContainer.java

/**
 * Deploy a module bundle on MMP server//from ww w . ja  v a2  s .co  m
 * @param moduleFile The module file (JAR file)
 */
@SuppressWarnings("unchecked")
public Module deployModule(File moduleFile) throws MMPException {
    try {
        JarFile jarFile = new JarFile(new File(moduleFile.toURI()));
        Manifest manifest = jarFile.getManifest();
        if (manifest == null) {
            throw new MMPException("invalid module archive, MANIFEST file not found");
        }
        // Get Bundle category
        Attributes attributes = manifest.getMainAttributes();
        String category = attributes.getValue(BUNDLE_CATEGORY_HEADER);
        // Test if the module is a widget
        if (category != null && category.equals(com.orange.mmp.core.Constants.MODULE_CATEGORY_WIDGET)) {
            Widget widget = new Widget();
            String symbName = attributes.getValue(BUNDLE_SYMBOLICNAME_HEADER);
            String branch = symbName.split(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN)[1];
            widget.setLocation(moduleFile.toURI());
            widget.setBranchId(branch);
            DaoManagerFactory.getInstance().getDaoManager().getDao("module").createOrUdpdate(widget);
            this.lastUpdate = 0;
            this.refresh();
            return widget;
        } else {
            Module module = new Module();
            module.setLocation(moduleFile.toURI());
            DaoManagerFactory.getInstance().getDaoManager().getDao("module").createOrUdpdate(module);
            this.lastUpdate = 0;
            this.refresh();
            return module;
        }

    } catch (IOException ioe) {
        throw new MMPException("Failed to deploy module", ioe);
    }
}

From source file:org.jahia.data.templates.ModulesPackage.java

private ModulesPackage(JarFile jarFile) throws IOException {
    modules = new LinkedHashMap<String, PackagedModule>();
    Attributes manifestAttributes = jarFile.getManifest().getMainAttributes();
    version = new Version(manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_VERSION));
    name = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_NAME);
    description = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_DESCRIPTION);
    // read jars//from   w ww.  j  av  a  2s.  c om
    Enumeration<JarEntry> jars = jarFile.entries();

    while (jars.hasMoreElements()) {
        JarEntry jar = jars.nextElement();
        JarFile moduleJarFile = null;
        OutputStream output = null;
        if (StringUtils.endsWith(jar.getName(), ".jar")) {
            try {
                InputStream input = jarFile.getInputStream(jar);
                File moduleFile = File.createTempFile(jar.getName(), "");
                output = new FileOutputStream(moduleFile);
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = input.read(bytes)) != -1) {
                    output.write(bytes, 0, read);
                }
                moduleJarFile = new JarFile(moduleFile);
                Attributes moduleManifestAttributes = moduleJarFile.getManifest().getMainAttributes();
                String bundleName = moduleManifestAttributes.getValue(Constants.ATTR_NAME_BUNDLE_SYMBOLIC_NAME);
                String jahiaGroupId = moduleManifestAttributes.getValue(Constants.ATTR_NAME_GROUP_ID);
                if (bundleName == null || jahiaGroupId == null) {
                    throw new IOException(
                            "Jar file " + jar.getName() + " in package does not seems to be a DX bundle.");
                }
                modules.put(bundleName, new PackagedModule(bundleName, moduleManifestAttributes, moduleFile));
            } finally {
                IOUtils.closeQuietly(output);
                if (moduleJarFile != null) {
                    moduleJarFile.close();
                }
            }
        }
    }

    // we finally sort modules based on dependencies
    try {
        sortByDependencies(modules);
    } catch (CycleDetectedException e) {
        throw new JahiaRuntimeException("A cyclic dependency detected in the modules of the supplied package",
                e);
    }
}

From source file:org.apache.xmlgraphics.util.ClasspathResource.java

private void loadManifests() {
        Enumeration e;//from w w w. j  av  a  2 s  . com
        try {

            Iterator it = getClassLoadersForResources().iterator();
            while (it.hasNext()) {
                ClassLoader classLoader = (ClassLoader) it.next();

                e = classLoader.getResources(MANIFEST_PATH);

                while (e.hasMoreElements()) {
                    final URL u = (URL) e.nextElement();
                    try {
                        final Manifest manifest = new Manifest(u.openStream());
                        final Map entries = manifest.getEntries();
                        final Iterator entrysetiterator = entries.entrySet().iterator();
                        while (entrysetiterator.hasNext()) {
                            final Map.Entry entry = (Map.Entry) entrysetiterator.next();
                            final String name = (String) entry.getKey();
                            final Attributes attributes = (Attributes) entry.getValue();
                            final String contentType = attributes.getValue(CONTENT_TYPE_KEY);
                            if (contentType != null) {
                                addToMapping(contentType, name, classLoader);
                            }
                        }
                    } catch (IOException io) {
                        // TODO: Log.
                    }
                }
            }

        } catch (IOException io) {
            // TODO: Log.
        }
    }

From source file:hudson.plugins.simpleupdatesite.HPI.java

private void init(Attributes attributes, long timestamp) throws IOException {
    this.timestamp = timestamp;
    this.name = attributes.getValue("Implementation-Title");
    this.version = attributes.getValue("Implementation-Version");
    this.pluginVersion = attributes.getValue("Plugin-Version");
    this.wiki = attributes.getValue("Url");
    this.shortName = attributes.getValue("Short-Name");
    this.title = attributes.getValue("Long-Name");
    this.compatibleSinceVersion = attributes.getValue("Compatible-Since-Version");
    this.requiredCore = attributes.getValue("Hudson-Version");
    this.setDevelopers(getDevelopers(attributes));
    this.setDependencies(getDependencies(attributes));
    this.builtBy = getBuiltBy(attributes);
}

From source file:de.micromata.genome.jpa.impl.JpaWithExtLibrariesScanner.java

/**
 * A jar may have also declared more deps in manifest (like surefire).
 * /* ww w .  j  a v a  2s .com*/
 * @param url the url
 * @param collector the collector to use
 */
@SuppressWarnings("deprecation")
private void handleClassManifestClassPath(URL url, ScanResultCollector collector, Matcher<String> urlMatcher) {
    String urls = url.toString();
    URL urltoopen = fixUrlToOpen(url);
    urls = urltoopen.toString();
    if (urls.endsWith(".jar") == false) {
        return;
    }

    try (InputStream is = urltoopen.openStream()) {
        try (JarInputStream jarStream = new JarInputStream(is)) {
            Manifest manifest = jarStream.getManifest();
            if (manifest == null) {
                return;
            }
            Attributes attr = manifest.getMainAttributes();
            String val = attr.getValue("Class-Path");
            if (StringUtils.isBlank(val) == true) {
                return;
            }
            String[] entries = StringUtils.split(val, " \t\n");
            for (String entry : entries) {
                URL surl = new URL(entry);
                visitUrl(surl, collector, urlMatcher);
            }

        }

    } catch (IOException ex) {
        log.warn("JpaScan; Cannot open jar: " + url + ": " + ex.getMessage());
    }

}

From source file:org.nuxeo.osgi.JarBundleFile.java

@Override
public Collection<BundleFile> getNestedBundles(File tmpDir) throws IOException {
    Attributes attrs = jarFile.getManifest().getMainAttributes();
    String cp = attrs.getValue(Constants.BUNDLE_CLASSPATH);
    if (cp == null) {
        cp = attrs.getValue("Class-Path");
    }// w  w w . j  av  a2  s . co m
    if (cp == null) {
        return null;
    }
    String[] paths = StringUtils.split(cp, ',', true);
    URL base = new URL("jar:" + new File(jarFile.getName()).toURI().toURL().toExternalForm() + "!/");
    String fileName = getFileName();
    List<BundleFile> nested = new ArrayList<BundleFile>();
    for (String path : paths) {
        if (path.equals(".")) {
            continue; // TODO
        }
        String location = base + path;
        String name = path.replace('/', '_');
        File dest = new File(tmpDir, fileName + '-' + name);
        try {
            extractNestedJar(jarFile, path, dest);
            nested.add(new NestedJarBundleFile(location, dest));
        } catch (FileNotFoundException e) {
            log.error("A nested jar is referenced in manifest but not found: " + location);
        } catch (IOException e) {
            log.error(e);
        }
    }
    return nested;
}

From source file:org.red5.server.plugin.PluginLauncher.java

public void afterPropertiesSet() throws Exception {

    ApplicationContext common = (ApplicationContext) applicationContext.getBean("red5.common");
    Server server = (Server) common.getBean("red5.server");

    //server should be up and running at this point so load any plug-ins now         

    //get the plugins dir
    File pluginsDir = new File(System.getProperty("red5.root"), "plugins");

    File[] plugins = pluginsDir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            //lower the case
            String tmp = name.toLowerCase();
            //accept jars and zips
            return tmp.endsWith(".jar") || tmp.endsWith(".zip");
        }//from www  . j  a va  2  s . c  o m
    });

    if (plugins != null) {

        IRed5Plugin red5Plugin = null;

        log.debug("{} plugins to launch", plugins.length);
        for (File plugin : plugins) {
            JarFile jar = null;
            Manifest manifest = null;
            try {
                jar = new JarFile(plugin, false);
                manifest = jar.getManifest();
            } catch (Exception e1) {
                log.warn("Error loading plugin manifest: {}", plugin);
            } finally {
                jar.close();
            }
            if (manifest == null) {
                continue;
            }
            Attributes attributes = manifest.getMainAttributes();
            if (attributes == null) {
                continue;
            }
            String pluginMainClass = attributes.getValue("Red5-Plugin-Main-Class");
            if (pluginMainClass == null || pluginMainClass.length() <= 0) {
                continue;
            }
            // attempt to load the class; since it's in the plugins directory this should work
            ClassLoader loader = common.getClassLoader();
            Class<?> pluginClass;
            String pluginMainMethod = null;
            try {
                pluginClass = Class.forName(pluginMainClass, true, loader);
            } catch (ClassNotFoundException e) {
                continue;
            }
            try {
                //handle plug-ins without "main" methods
                pluginMainMethod = attributes.getValue("Red5-Plugin-Main-Method");
                if (pluginMainMethod == null || pluginMainMethod.length() <= 0) {
                    //just get an instance of the class
                    red5Plugin = (IRed5Plugin) pluginClass.newInstance();
                } else {
                    Method method = pluginClass.getMethod(pluginMainMethod, (Class<?>[]) null);
                    Object o = method.invoke(null, (Object[]) null);
                    if (o != null && o instanceof IRed5Plugin) {
                        red5Plugin = (IRed5Plugin) o;
                    }
                }
                //register and start
                if (red5Plugin != null) {
                    //set top-level context
                    red5Plugin.setApplicationContext(applicationContext);
                    //set server reference
                    red5Plugin.setServer(server);
                    //register the plug-in to make it available for lookups
                    PluginRegistry.register(red5Plugin);
                    //start the plugin
                    red5Plugin.doStart();
                }
                log.info("Loaded plugin: {}", pluginMainClass);
            } catch (Throwable t) {
                log.warn("Error loading plugin: {}; Method: {}", pluginMainClass, pluginMainMethod);
                log.error("", t);
            }
        }
    } else {
        log.info("Plugins directory cannot be accessed or doesnt exist");
    }

}

From source file:org.jboss.windup.decorator.archive.ManifestVersionMapperDecorator.java

private boolean matchAttributes(Attributes attributes) {
    boolean matched = true;
    for (String key : attributeNameToRegex.keySet()) {

        // if it looks for the attribute in the attributes set
        // and it does not exist, return false.
        String attrVal = attributes.getValue(key);
        if (attrVal == null) {
            return false;
        } else {//  ww w. j  a v  a  2  s . co  m
            // else if it found the attribute, check if it matches a given regex pattern.
            matched = processPattern(attributeNameToRegex.get(key), attrVal);

            if (LOG.isTraceEnabled()) {
                LOG.trace("Key[" + key + "] Found: " + attrVal + " trying to match: "
                        + attributeNameToRegex.get(key) + " :: " + matched);
            }
        }

        // if they become false at any point, return false.
        if (!matched) {
            return false;
        }
    }
    return matched;
}

From source file:com.taobao.android.apatch.MergePatch.java

private void fillManifest(Attributes main) throws IOException {
    JarFile jarFile;//from   w  w w .  j  a  v  a  2s  .c  o m
    Manifest manifest;
    StringBuffer fromBuffer = new StringBuffer();
    StringBuffer toBuffer = new StringBuffer();
    String from;
    String to;
    String name;
    // String classes;
    for (File file : patchs) {
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("META-INF/PATCH.MF");
        manifest = new Manifest(jarFile.getInputStream(dexEntry));
        Attributes attributes = manifest.getMainAttributes();

        from = attributes.getValue("From-File");
        if (fromBuffer.length() > 0) {
            fromBuffer.append(',');
        }
        fromBuffer.append(from);
        to = attributes.getValue("To-File");
        if (toBuffer.length() > 0) {
            toBuffer.append(',');
        }
        toBuffer.append(to);

        name = attributes.getValue("Patch-Name");
        // classes = attributes.getValue(name + "-Patch-Classes");
        main.putValue(name + "-Patch-Classes", attributes.getValue(name + "-Patch-Classes"));
        main.putValue(name + "-Prepare-Classes", attributes.getValue(name + "-Prepare-Classes"));
        main.putValue(name + "-Used-Methods", attributes.getValue(name + "-Used-Methods"));
        main.putValue(name + "-Modified-Classes", attributes.getValue(name + "-Modified-Classes"));
        main.putValue(name + "-Used-Classes", attributes.getValue(name + "-Used-Classes"));
        main.putValue(name + "-add-classes", attributes.getValue(name + "-add-classes"));

    }
    main.putValue("From-File", fromBuffer.toString());
    main.putValue("To-File", toBuffer.toString());
}

From source file:org.lnicholls.galleon.app.AppDescriptor.java

public AppDescriptor(File jar) throws IOException, AppException {
    mJar = jar;/*w w w.j  a va  2 s  .co  m*/

    JarFile zipFile = new JarFile(jar);
    Enumeration entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        String name = entry.getName();
        if (name.toUpperCase().equals(JarFile.MANIFEST_NAME)) {
            InputStream in = null;
            try {
                in = zipFile.getInputStream(entry);
                Manifest manifest = new Manifest(in);
                Attributes attributes = manifest.getMainAttributes();
                if (attributes.getValue("Main-Class") != null) {
                    mClassName = (String) attributes.getValue("Main-Class");
                    if (attributes.getValue("HME-Arguments") != null)
                        mArguments = (String) attributes.getValue("HME-Arguments");
                    if (attributes.getValue(TITLE) != null)
                        mTitle = (String) attributes.getValue(TITLE);
                    if (attributes.getValue(RELEASE_DATE) != null)
                        mReleaseDate = (String) attributes.getValue(RELEASE_DATE);
                    if (attributes.getValue(DESCRIPTION) != null)
                        mDescription = (String) attributes.getValue(DESCRIPTION);
                    if (attributes.getValue(DOCUMENTATION) != null)
                        mDocumentation = (String) attributes.getValue(DOCUMENTATION);
                    if (attributes.getValue(AUTHOR_NAME) != null)
                        mAuthorName = (String) attributes.getValue(AUTHOR_NAME);
                    if (attributes.getValue(AUTHOR_EMAIL) != null)
                        mAuthorEmail = (String) attributes.getValue(AUTHOR_EMAIL);
                    if (attributes.getValue(AUTHOR_HOMEPAGE) != null)
                        mAuthorHomepage = (String) attributes.getValue(AUTHOR_HOMEPAGE);
                    if (attributes.getValue(VERSION) != null)
                        mVersion = (String) attributes.getValue(VERSION);
                    if (attributes.getValue(CONFIGURATION) != null)
                        mConfiguration = (String) attributes.getValue(CONFIGURATION);
                    if (attributes.getValue(CONFIGURATION_PANEL) != null)
                        mConfigurationPanel = (String) attributes.getValue(CONFIGURATION_PANEL);
                    if (attributes.getValue(TAGS) != null)
                        mTags = (String) attributes.getValue(TAGS);
                }

                if (mTitle == null) {
                    mTitle = jar.getName().substring(0, jar.getName().indexOf('.'));
                }
            } catch (Exception ex) {
                Tools.logException(AppDescriptor.class, ex, "Cannot get descriptor: " + jar.getAbsolutePath());
            } finally {
                if (in != null) {
                    try {
                        in.close();
                        in = null;
                    } catch (Exception ex) {
                    }
                }
            }
            break;
        }
    }
    zipFile.close();
}