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:net.hillsdon.reviki.wiki.plugin.PluginClassLoader.java

public PluginClassLoader(final URL jarUrl, final ClassLoader parent) throws InvalidPluginException {
    super(new URL[] { jarUrl }, parent);
    InputStream manifestInputStream = null;
    try {// w w w.  java2s  .  com
        final URL manifestUrl = getManifestURL(jarUrl);
        try {
            manifestInputStream = manifestUrl.openStream();
        } catch (IOException ex) {
            throw new InvalidPluginException("Could not open META-INF/MANIFEST.MF in plugin jar.");
        }
        final Manifest manifest = new Manifest(manifestInputStream);

        final Attributes attrs = manifest.getMainAttributes();
        String classPath = attrs.getValue("Class-Path");
        if (classPath != null && classPath.length() > 0) {
            cacheClassPathEntries(jarUrl, classPath);
        }
        String pluginContributions = attrs.getValue("Plugin-Contributions");
        if (pluginContributions != null && pluginContributions.length() > 0) {
            _contributedClasses = unmodifiableList(loadPluginContributionClasses(pluginContributions));
        } else {
            _contributedClasses = Collections.emptyList();
        }
    } catch (URISyntaxException ex) {
        throw new InvalidPluginException(ex);
    } catch (IOException ex) {
        throw new InvalidPluginException(ex);
    } catch (ClassNotFoundException ex) {
        throw new InvalidPluginException(ex);
    } finally {
        IOUtils.closeQuietly(manifestInputStream);
    }
}

From source file:de.metanome.backend.algorithm_loading.AlgorithmFinder.java

/**
 * Finds out which subclass of Algorithm is implemented by the source code in the
 * algorithmJarFile./*from  www. ja v  a 2s.  co m*/
 *
 * @param algorithmJarFile the algorithm's jar file
 * @return the interfaces of the algorithm implementation in algorithmJarFile
 * @throws java.io.IOException if the algorithm jar file could not be opened
 * @throws java.lang.ClassNotFoundException if the algorithm contains a not supported interface
 */
public Set<Class<?>> getAlgorithmInterfaces(File algorithmJarFile) throws IOException, ClassNotFoundException {
    JarFile jar = new JarFile(algorithmJarFile);

    Manifest man = jar.getManifest();
    Attributes attr = man.getMainAttributes();
    String className = attr.getValue(bootstrapClassTagName);

    URL[] url = { algorithmJarFile.toURI().toURL() };
    ClassLoader loader = new URLClassLoader(url, Algorithm.class.getClassLoader());

    Class<?> algorithmClass;
    try {
        algorithmClass = Class.forName(className, false, loader);
    } catch (ClassNotFoundException e) {
        System.out.println("Could not find class " + className);
        return new HashSet<>();
    } finally {
        jar.close();
    }

    return new HashSet<>(ClassUtils.getAllInterfaces(algorithmClass));
}

From source file:org.cleverbus.core.common.version.impl.ManifestVersionInfoSource.java

private String getVendorId(Attributes attrs) {
    String vendorId = attrs.getValue(ATTR_VENDOR_ID);
    if (vendorId == null) {
        vendorId = attrs.getValue(ATTR_BUNDLE_SYMBOLIC_NAME);
    }//from  ww w.  j a v  a  2  s  . c  om
    return vendorId;
}

From source file:org.rhq.core.clientapi.descriptor.PluginTransformer.java

private String getVersionFromPluginJarManifest(URL pluginJarUrl) throws IOException {
    JarInputStream jarInputStream = new JarInputStream(pluginJarUrl.openStream());
    Manifest manifest = jarInputStream.getManifest();
    if (manifest == null) {
        // BZ 682116 (ips, 03/25/11): The manifest file is not in the standard place as the 2nd entry of the JAR,
        // but we want to be flexible and support JARs that have a manifest file somewhere else, so scan the entire
        // JAR for one.
        JarEntry jarEntry;// w  w w .  j  a v  a 2s .  c  om
        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
            if (JarFile.MANIFEST_NAME.equalsIgnoreCase(jarEntry.getName())) {
                manifest = new Manifest(jarInputStream);
                break;
            }
        }
    }
    try {
        jarInputStream.close();
    } catch (IOException e) {
        LOG.error("Failed to close plugin jar input stream for plugin jar [" + pluginJarUrl + "].", e);
    }
    if (manifest != null) {
        Attributes attributes = manifest.getMainAttributes();
        return attributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
    } else {
        return null;
    }
}

From source file:org.sonar.batch.internal.PluginsManager.java

public void start() throws Exception {
    LOG.info("Starting Sonar Plugins Manager (workDir: {})", workDir);

    collection = new ClassLoadersCollection(parentClassLoader);

    for (Map.Entry<File, Manifest> entry : manifests.entrySet()) {
        File file = entry.getKey();
        Manifest manifest = entry.getValue();

        Attributes attributes = manifest.getMainAttributes();
        String childFirst = attributes.getValue("Plugin-ChildFirstClassLoader");
        String pluginKey = attributes.getValue("Plugin-Key");
        String pluginClass = attributes.getValue("Plugin-Class");
        String pluginDependencies = StringUtils.defaultString(attributes.getValue("Plugin-Dependencies"));

        File pluginDir = file.getParentFile().getParentFile();

        Collection<URL> urls = new ArrayList<URL>();
        urls.add(pluginDir.toURL());//ww w. j a va2s .c o  m
        String[] deps = StringUtils.split(pluginDependencies);
        for (String dep : deps) {
            File depFile = new File(pluginDir, dep);
            urls.add(depFile.toURL());
        }
        LOG.debug("ClassPath for plugin {} : {}", pluginKey, urls);

        collection.createClassLoader(pluginKey, urls, "true".equals(childFirst));

        plugins.put(pluginKey, pluginClass);
    }

    collection.done();
}

From source file:de.romankreisel.faktotum.FaktotumContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    try (InputStream is = sce.getServletContext()
            .getResourceAsStream(FaktotumContextListener.RELATIVE_MANIFEST_PATH)) {
        Manifest manifest = new Manifest(is);
        Attributes attributes = manifest.getMainAttributes();
        String buildTimeString = attributes.getValue("Build-Time");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotBlank(buildTimeString)) {
            FaktotumContextListener.buildTime = simpleDateFormat.parse(buildTimeString);
        }//from w  w w .  j a  v a 2s.  c o m
        FaktotumContextListener.version = attributes.getValue("Implementation-Version");
        this.getLogger().info("Faktotum initialized");
        this.getLogger().info("Version: " + FaktotumContextListener.getVersion());
        this.getLogger().info("Build-Time: " + simpleDateFormat.format(FaktotumContextListener.getBuildTime()));

        this.getLogger().fine("Removing old sessions...");
        this.authenticationBean.removeOldSessions();
    } catch (IOException e) {
        this.getLogger().log(Level.WARNING, "Error reading build time from manifest", e);
    } catch (ParseException e) {
        this.getLogger().log(Level.WARNING, "Error parsing build time from manifest", e);
    } catch (Exception e) {
        this.getLogger().log(Level.SEVERE, "Error reading build time", e);
        throw e;
    }
}

From source file:org.openhab.tools.analysis.checkstyle.RequireBundleCheck.java

@Override
protected void processFiltered(File file, FileText fileText) {
    try {//from w  w  w .  j a v  a  2  s.  c  om
        // We use Manifest class here instead of ManifestParser,
        // because it is easier to get the content of the headers
        // in the MANIFEST.MF
        Manifest manifest = new Manifest(new FileInputStream(file));
        Attributes attributes = manifest.getMainAttributes();

        String fragmentHost = attributes.getValue(FRAGMENT_HOST_HEADER_NAME);
        String bundleSymbolicName = attributes.getValue(BUNDLE_SYMBOLIC_NAME_HEADER_NAME);

        boolean testBundle = false;
        if (StringUtils.isNotBlank(fragmentHost) && StringUtils.isNotBlank(bundleSymbolicName)) {
            testBundle = bundleSymbolicName.startsWith(fragmentHost)
                    && bundleSymbolicName.substring(fragmentHost.length()).startsWith(".test");
        }

        String requireBundleHeaderValue = attributes.getValue(REQUIRE_BUNDLE_HEADER_NAME);
        if (requireBundleHeaderValue != null && !testBundle) {

            int lineNumber = findLineNumberSafe(fileText, requireBundleHeaderValue, 0,
                    REQUIRE_BUNDLE_HEADER_NAME + " header line number not found.");
            log(lineNumber, "The MANIFEST.MF file must not contain any Require-Bundle entries. "
                    + "Instead, Import-Package must be used.");
        } else if (requireBundleHeaderValue != null && testBundle) {
            String[] bundleNames = requireBundleHeaderValue.split(",");
            for (String bundleName : bundleNames) {
                if (!allowedRequireBundles.contains(bundleName)) {
                    int lineNumber = findLineNumberSafe(fileText, requireBundleHeaderValue, 0,
                            "Header value not found.");
                    log(lineNumber,
                            "The MANIFEST.MF file of a test fragment must not contain Require-Bundle entries other than "
                                    + getAllowedBundlesString() + ".");
                    break;
                }
            }
        }
    } catch (

    FileNotFoundException e) {
        logger.error("An exception was thrown while trying to open the file " + file.getPath(), e);
    } catch (IOException e) {
        logger.error("An exception was thrown while trying to read the file " + file.getPath(), e);
    }
}

From source file:interactivespaces.resource.analysis.OsgiResourceAnalyzer.java

@Override
public NamedVersionedResourceCollection<NamedVersionedResourceWithData<String>> getResourceCollection(
        File baseDir) {/*  ww  w . ja v  a  2  s.  co  m*/
    NamedVersionedResourceCollection<NamedVersionedResourceWithData<String>> resources = NamedVersionedResourceCollection
            .newNamedVersionedResourceCollection();

    File[] files = baseDir.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.getName().endsWith(".jar");
        }
    });

    if (files != null) {
        for (File file : files) {
            JarFile jarFile = null;
            try {
                jarFile = new JarFile(file);
                Manifest manifest = jarFile.getManifest();
                Attributes attributes = manifest.getMainAttributes();
                String name = attributes.getValue(OSGI_HEADER_SYMBOLIC_NAME);
                String version = attributes.getValue(OSGI_HEADER_VERSION);
                if (name != null && version != null) {
                    NamedVersionedResourceWithData<String> resource = new NamedVersionedResourceWithData<String>(
                            name, Version.parseVersion(version), file.getAbsolutePath());

                    resources.addResource(resource.getName(), resource.getVersion(), resource);
                } else {
                    log.warn(String.format(
                            "Resource %s is not a proper OSGi bundle (missing symbolic name and/or version) and is being ignored.",
                            file.getAbsolutePath()));
                }
            } catch (IOException e) {
                log.error(String.format("Could not open resource file jar manifest for %s",
                        file.getAbsolutePath()), e);
            } finally {
                // For some reason Closeables does not work with JarFile despite it
                // claiming it is Closeable in the Javadoc.
                if (jarFile != null) {
                    try {
                        jarFile.close();
                    } catch (IOException e) {
                        // Don't care.
                    }
                }
            }
        }
    }

    return resources;
}

From source file:net.minecraftforge.fml.relauncher.CoreModManager.java

private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader) {
    ModListHelper.parseModList(mcDir);/*from w w w . j  a  va2  s  .c  o m*/
    FMLRelaunchLog.fine("Discovering coremods");
    File coreMods = setupCoreModDir(mcDir);
    FilenameFilter ff = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }
    };
    FilenameFilter derpfilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar.zip");
        }
    };
    File[] derplist = coreMods.listFiles(derpfilter);
    if (derplist != null && derplist.length > 0) {
        FMLRelaunchLog.severe(
                "FML has detected several badly downloaded jar files,  which have been named as zip files. You probably need to download them again, or they may not work properly");
        for (File f : derplist) {
            FMLRelaunchLog.severe("Problem file : %s", f.getName());
        }
    }
    FileFilter derpdirfilter = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && new File(pathname, "META-INF").isDirectory();
        }

    };
    File[] derpdirlist = coreMods.listFiles(derpdirfilter);
    if (derpdirlist != null && derpdirlist.length > 0) {
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "There appear to be jars extracted into the mods directory. This is VERY BAD and will almost NEVER WORK WELL");
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "You should place original jars only in the mods directory. NEVER extract them to the mods directory.");
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "The directories below appear to be extracted jar files. Fix this before you continue.");

        for (File f : derpdirlist) {
            FMLRelaunchLog.log.getLogger().log(Level.FATAL, "Directory {} contains {}", f.getName(),
                    Arrays.asList(new File(f, "META-INF").list()));
        }

        RuntimeException re = new RuntimeException("Extracted mod jars found, loading will NOT continue");
        // We're generating a crash report for the launcher to show to the user here
        try {
            Class<?> crashreportclass = classLoader.loadClass("b");
            Object crashreport = crashreportclass.getMethod("a", Throwable.class, String.class).invoke(null, re,
                    "FML has discovered extracted jar files in the mods directory.\nThis breaks mod loading functionality completely.\nRemove the directories and replace with the jar files originally provided.");
            File crashreportfile = new File(new File(coreMods.getParentFile(), "crash-reports"),
                    String.format("fml-crash-%1$tY-%1$tm-%1$td_%1$tT.txt", Calendar.getInstance()));
            crashreportclass.getMethod("a", File.class).invoke(crashreport, crashreportfile);
            System.out.println("#@!@# FML has crashed the game deliberately. Crash report saved to: #@!@# "
                    + crashreportfile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            // NOOP - hopefully
        }
        throw re;
    }
    File[] coreModList = coreMods.listFiles(ff);
    File versionedModDir = new File(coreMods, FMLInjectionData.mccversion);
    if (versionedModDir.isDirectory()) {
        File[] versionedCoreMods = versionedModDir.listFiles(ff);
        coreModList = ObjectArrays.concat(coreModList, versionedCoreMods, File.class);
    }

    coreModList = ObjectArrays.concat(coreModList, ModListHelper.additionalMods.values().toArray(new File[0]),
            File.class);

    coreModList = FileListHelper.sortFileList(coreModList);

    for (File coreMod : coreModList) {
        FMLRelaunchLog.fine("Examining for coremod candidacy %s", coreMod.getName());
        JarFile jar = null;
        Attributes mfAttributes;
        String fmlCorePlugin;
        try {
            jar = new JarFile(coreMod);
            if (jar.getManifest() == null) {
                // Not a coremod and no access transformer list
                continue;
            }
            ModAccessTransformer.addJar(jar);
            mfAttributes = jar.getManifest().getMainAttributes();
            String cascadedTweaker = mfAttributes.getValue("TweakClass");
            if (cascadedTweaker != null) {
                FMLRelaunchLog.info("Loading tweaker %s from %s", cascadedTweaker, coreMod.getName());
                Integer sortOrder = Ints.tryParse(Strings.nullToEmpty(mfAttributes.getValue("TweakOrder")));
                sortOrder = (sortOrder == null ? Integer.valueOf(0) : sortOrder);
                handleCascadingTweak(coreMod, jar, cascadedTweaker, classLoader, sortOrder);
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            List<String> modTypes = mfAttributes.containsKey(MODTYPE)
                    ? Arrays.asList(mfAttributes.getValue(MODTYPE).split(","))
                    : ImmutableList.of("FML");

            if (!modTypes.contains("FML")) {
                FMLRelaunchLog.fine(
                        "Adding %s to the list of things to skip. It is not an FML mod,  it has types %s",
                        coreMod.getName(), modTypes);
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            String modSide = mfAttributes.containsKey(MODSIDE) ? mfAttributes.getValue(MODSIDE) : "BOTH";
            if (!("BOTH".equals(modSide) || FMLLaunchHandler.side.name().equals(modSide))) {
                FMLRelaunchLog.fine("Mod %s has ModSide meta-inf value %s, and we're %s. It will be ignored",
                        coreMod.getName(), modSide, FMLLaunchHandler.side.name());
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            ModListHelper.additionalMods.putAll(extractContainedDepJars(jar, coreMods, versionedModDir));
            fmlCorePlugin = mfAttributes.getValue("FMLCorePlugin");
            if (fmlCorePlugin == null) {
                // Not a coremod
                FMLRelaunchLog.fine("Not found coremod data in %s", coreMod.getName());
                continue;
            }
        } catch (IOException ioe) {
            FMLRelaunchLog.log(Level.ERROR, ioe, "Unable to read the jar file %s - ignoring",
                    coreMod.getName());
            continue;
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (IOException e) {
                    // Noise
                }
            }
        }
        // Support things that are mod jars, but not FML mod jars
        try {
            classLoader.addURL(coreMod.toURI().toURL());
            if (!mfAttributes.containsKey(COREMODCONTAINSFMLMOD)) {
                FMLRelaunchLog.finer("Adding %s to the list of known coremods, it will not be examined again",
                        coreMod.getName());
                ignoredModFiles.add(coreMod.getName());
            } else {
                FMLRelaunchLog.finer(
                        "Found FMLCorePluginContainsFMLMod marker in %s, it will be examined later for regular @Mod instances",
                        coreMod.getName());
                candidateModFiles.add(coreMod.getName());
            }
        } catch (MalformedURLException e) {
            FMLRelaunchLog.log(Level.ERROR, e, "Unable to convert file into a URL. weird");
            continue;
        }
        loadCoreMod(classLoader, fmlCorePlugin, coreMod);
    }
}

From source file:de.micromata.mgc.application.ManifestMgcApplicationInfo.java

public Manifest findManifest() {
    try {//from   w  w w. ja  v a  2s. co m
        Enumeration<URL> resources = application.getClass().getClassLoader()
                .getResources("META-INF/MANIFEST.MF");

        while (resources.hasMoreElements()) {
            try {
                URL url = resources.nextElement();
                Manifest manifest = new Manifest(url.openStream());
                // check that this is your manifest and do what you need or get the next one
                Attributes attrs = manifest.getMainAttributes();

                String val = attrs.getValue(MgcAppName);
                if (StringUtils.isNotBlank(val) == true) {
                    return manifest;
                }
            } catch (IOException E) {
                // handle
            }
        }
        return null;
    } catch (IOException ex) {
        return null;
    }
}