Example usage for java.util.jar JarFile getManifest

List of usage examples for java.util.jar JarFile getManifest

Introduction

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

Prototype

public Manifest getManifest() throws IOException 

Source Link

Document

Returns the jar file manifest, or null if none.

Usage

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

@Override
public NamedVersionedResourceCollection<NamedVersionedResourceWithData<String>> getResourceCollection(
        File baseDir) {/*  ww w . j a va 2 s.  com*/
    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:org.eclipse.virgo.kernel.artifact.bundle.BundleBridgeTests.java

@Test
public void testBuildDictionary() throws ArtifactGenerationException, IOException {
    File testFile = new File(System.getProperty("user.home")
            + "/virgo-build-cache/ivy-cache/repository/org.eclipse.virgo.mirrored/javax.servlet/3.0.0.v201112011016/javax.servlet-3.0.0.v201112011016.jar");

    ArtifactDescriptor inputArtefact = BUNDLE_BRIDGE.generateArtifactDescriptor(testFile);

    Dictionary<String, String> dictionary = BundleBridge.convertToDictionary(inputArtefact);

    JarFile testJar = new JarFile(testFile);
    Attributes attributes = testJar.getManifest().getMainAttributes();

    testJar.close();/*from  w w w.  jav  a  2 s.  com*/

    assertEquals("Failed to match regenerated " + Constants.BUNDLE_SYMBOLICNAME,
            dictionary.get(Constants.BUNDLE_SYMBOLICNAME), attributes.getValue(Constants.BUNDLE_SYMBOLICNAME));
    assertEquals("Failed to match regenerated " + Constants.BUNDLE_VERSION,
            dictionary.get(Constants.BUNDLE_VERSION), attributes.getValue(Constants.BUNDLE_VERSION));
    assertEquals("Failed to match regenerated " + BUNDLE_MANIFEST_VERSION_HEADER_NAME,
            dictionary.get(BUNDLE_MANIFEST_VERSION_HEADER_NAME),
            attributes.getValue(BUNDLE_MANIFEST_VERSION_HEADER_NAME));
    assertEquals("Failed to match regenerated " + BUNDLE_NAME_HEADER_NAME,
            dictionary.get(BUNDLE_NAME_HEADER_NAME), attributes.getValue(BUNDLE_NAME_HEADER_NAME));

}

From source file:net.dries007.coremod.Module.java

/**
 * This method gets all the dependencies, ASM classes and ATs from the files associated with this module.
 *///www .ja  va2s . c  om
public void parceJarFiles() {
    for (ModuleFile mFile : this.files) {
        try {
            JarFile jar = new JarFile(mFile.file);
            Manifest mf = jar.getManifest();
            if (mf != null) {
                for (Entry<Object, Object> attribute : mf.getMainAttributes().entrySet()) {
                    attributes.put(attribute.getKey().toString(), attribute.getValue().toString());
                }
                /**
                 * Reading NORMAL libs from the modules' manifest files.
                 * We want: Space sperated pairs of filename:sha1
                 */
                if (Data.hasKey(Data.LIBKEY_NORMAL, Data.LIBURL_NORMAL)) {
                    String libs = mf.getMainAttributes().getValue(Data.get(Data.LIBKEY_NORMAL));
                    if (libs != null)
                        for (String lib : libs.split(" ")) {
                            DefaultDependency dependency = new DefaultDependency(lib);
                            dependecies.add(dependency);
                        }
                }

                /**
                 * Reading MAVEN libs from the modules' manifest files.
                 * We want: the maven name
                 */
                if (Data.hasKey(Data.LIBKEY_MAVEN, Data.LIBURL_MAVEN)) {
                    String libs = mf.getMainAttributes().getValue(Data.get(Data.LIBKEY_MAVEN));
                    if (libs != null)
                        for (String lib : libs.split(" ")) {
                            MavenDependency dependency = new MavenDependency(this, lib);
                            dependecies.add(dependency);
                            dependecies.addAll(Coremod.getDependencies(dependency));
                        }
                }

                /*
                 * Reading ASM classes from the modules' manifest files
                 */
                if (Data.hasKey(Data.CLASSKEY_ASM)) {
                    String asmclasses = mf.getMainAttributes().getValue(Data.get(Data.CLASSKEY_ASM));
                    if (asmclasses != null)
                        for (String asmclass : asmclasses.split(" ")) {
                            this.ASMClasses.add(asmclass);
                            System.out.println("[" + Data.NAME + "] Added ASM class (" + asmclass
                                    + ") for module file " + jar.getName());
                        }
                }

                /*
                 * Reading AT Files from the modules' manifest files
                 */
                if (Data.hasKey(Data.FILEKEY_TA)) {
                    String ats = mf.getMainAttributes().getValue(Data.FILEKEY_TA);
                    if (ats != null)
                        for (String at : ats.split(" ")) {
                            this.ATFiles.add(at);
                            System.out.println("[" + Data.NAME + "] Added AccessTransformer (" + at
                                    + ") for module file " + jar.getName());
                        }
                }
            }
            jar.close();
        } catch (final MalformedURLException e) {
            e.printStackTrace();
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.amalto.core.jobox.watch.JoboxListener.java

public void contextChanged(String jobFile, String context) {
    File entity = new File(jobFile);
    String sourcePath = jobFile;//from  www .ja  va2  s  .c  o  m
    int dotMark = jobFile.lastIndexOf("."); //$NON-NLS-1$
    int separateMark = jobFile.lastIndexOf(File.separatorChar);
    if (dotMark != -1) {
        sourcePath = System.getProperty("java.io.tmpdir") + File.separatorChar //$NON-NLS-1$
                + jobFile.substring(separateMark, dotMark);
    }
    try {
        JoboxUtil.extract(jobFile, System.getProperty("java.io.tmpdir") + File.separatorChar); //$NON-NLS-1$
    } catch (Exception e1) {
        LOGGER.error("Extraction exception occurred.", e1);
        return;
    }
    List<File> resultList = new ArrayList<File>();
    JoboxUtil.findFirstFile(null, new File(sourcePath), "classpath.jar", resultList); //$NON-NLS-1$
    if (!resultList.isEmpty()) {
        JarInputStream jarIn = null;
        JarOutputStream jarOut = null;
        try {
            JarFile jarFile = new JarFile(resultList.get(0));
            Manifest mf = jarFile.getManifest();
            jarIn = new JarInputStream(new FileInputStream(resultList.get(0)));
            Manifest newManifest = jarIn.getManifest();
            if (newManifest == null) {
                newManifest = new Manifest();
            }
            newManifest.getMainAttributes().putAll(mf.getMainAttributes());
            newManifest.getMainAttributes().putValue("activeContext", context); //$NON-NLS-1$
            jarOut = new JarOutputStream(new FileOutputStream(resultList.get(0)), newManifest);
            byte[] buf = new byte[4096];
            JarEntry entry;
            while ((entry = jarIn.getNextJarEntry()) != null) {
                if ("META-INF/MANIFEST.MF".equals(entry.getName())) { //$NON-NLS-1$
                    continue;
                }
                jarOut.putNextEntry(entry);
                int read;
                while ((read = jarIn.read(buf)) != -1) {
                    jarOut.write(buf, 0, read);
                }
                jarOut.closeEntry();
            }
        } catch (Exception e) {
            LOGGER.error("Extraction exception occurred.", e);
        } finally {
            IOUtils.closeQuietly(jarIn);
            IOUtils.closeQuietly(jarOut);
        }
        // re-zip file
        if (entity.getName().endsWith(".zip")) { //$NON-NLS-1$
            File sourceFile = new File(sourcePath);
            try {
                JoboxUtil.zip(sourceFile, jobFile);
            } catch (Exception e) {
                LOGGER.error("Zip exception occurred.", e);
            }
        }
    }
}

From source file:org.jvnet.hudson.update_center.LocalDirectoryRepository.java

/**
 * Return all plugins contained in the directory.
 * /*from  w  w  w.j  a va  2 s  .c o m*/
 * @return a collection of histories of plugins contained in the directory.
 * @see org.jvnet.hudson.update_center.MavenRepository#listHudsonPlugins()
 */
@Override
public Collection<PluginHistory> listHudsonPlugins() throws PlexusContainerException, ComponentLookupException,
        IOException, UnsupportedExistingLuceneIndexException, AbstractArtifactResolutionException {
    // Search all plugins contained in the directory.
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(dir);
    ds.setIncludes(new String[] { "**/*.hpi", "**/*.jpi" });
    ds.scan();

    // build plugin history.
    Map<String, PluginHistory> plugins = new TreeMap<String, PluginHistory>(String.CASE_INSENSITIVE_ORDER);

    for (String filename : ds.getIncludedFiles()) {
        File hpiFile = new File(dir, filename);
        JarFile jar = new JarFile(hpiFile);
        Manifest manifest = jar.getManifest();
        long lastModified = jar.getEntry("META-INF/MANIFEST.MF").getTime();
        jar.close();

        String groupId = manifest.getMainAttributes().getValue("Group-Id");
        if (groupId == null) {
            // Old plugins inheriting from org.jvnet.hudson.plugins do not have
            // Group-Id field set in manifest. Absence of group id causes NPE in ArtifactInfo.
            groupId = "org.jvnet.hudson.plugins";
        }

        final String extension = FilenameUtils.getExtension(filename);

        // Extension-Name and Implementation-Title is not set for plugin using gradle (ex: ivy:1.26)
        // Short-Name seems always present and have the same value as the other two.
        String artifactId = manifest.getMainAttributes().getValue("Short-Name");
        ArtifactInfo a = new ArtifactInfo(null, // fname
                extension, groupId, artifactId, manifest.getMainAttributes().getValue("Plugin-Version"), // version
                // maybe Implementation-Version is more proper.
                null, // classifier
                "hpi", // packaging
                manifest.getMainAttributes().getValue("Long-Name"), // name
                manifest.getMainAttributes().getValue("Specification-Title"), // description
                lastModified, // lastModified
                hpiFile.length(), // size
                null, // md5
                null, // sha1
                ArtifactAvailablility.NOT_PRESENT, // sourcesExists
                ArtifactAvailablility.NOT_PRESENT, //javadocExists,
                ArtifactAvailablility.NOT_PRESENT, //signatureExists,
                null // repository
        );

        if (!includeSnapshots && a.version.contains("SNAPSHOT"))
            continue; // ignore snapshots
        PluginHistory p = plugins.get(a.artifactId);
        if (p == null)
            plugins.put(a.artifactId, p = new PluginHistory(a.artifactId));

        URL url;
        if (downloadDir == null) {
            // No downloadDir specified.
            // Just link to packages where they are located.
            String path = filename;
            if (File.separatorChar != '/') {
                // fix path separate character to /
                path = filename.replace(File.separatorChar, '/');
            }
            url = new URL(baseUrl, path);
        } else {
            // downloadDir is specified.
            // Packages are deployed into downloadDir, based on its plugin name and version.
            final String path = new LocalHPI(this, p, a, hpiFile, null).getRelativePath();
            url = new URL(new URL(baseUrl, "download/"), path);
        }
        p.addArtifact(new LocalHPI(this, p, a, hpiFile, url));
        p.groupId.add(a.groupId);
    }

    return plugins.values();
}

From source file:org.sonar.updatecenter.common.PluginManifest.java

/**
 * Load the manifest from a JAR file./*w w  w  . j av  a 2  s . c om*/
 */
public PluginManifest(File file) throws IOException {
    JarFile jar = new JarFile(file);
    try {
        if (jar.getManifest() != null) {
            loadManifest(jar.getManifest());
        }

    } finally {
        jar.close();
    }
}

From source file:org.springframework.cloud.function.deployer.ApplicationBootstrap.java

private URL[] extractClasspath(URL url) {
    // This works for a jar indirection like in surefire and IntelliJ
    if (url.toString().endsWith(".jar")) {
        JarFile jar;
        try {//from w w  w  .j av a 2  s.c  o  m
            jar = new JarFile(new File(url.toURI()));
            String path = jar.getManifest().getMainAttributes().getValue("Class-Path");
            if (path != null) {
                List<URL> result = new ArrayList<>();
                for (String element : path.split(" ")) {
                    result.add(new URL(element));
                }
                return result.toArray(new URL[0]);
            }
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:org.apache.apex.common.util.JarHelper.java

/**
 * Adds dependent jar-files from manifest to the target list of jar-files
 * @param jarFile Jar file/*  w w w . j  a  va 2s. co m*/
 * @param set Set of target jar-files
 * @throws IOException
 */
public void getDependentJarsFromManifest(JarFile jarFile, Set<String> set) throws IOException {
    String value = jarFile.getManifest().getMainAttributes().getValue(APEX_DEPENDENCIES);
    if (!StringUtils.isEmpty(value)) {
        Path folderPath = Paths.get(jarFile.getName()).getParent();
        for (String jar : value.split(",")) {
            File file = folderPath.resolve(jar).toFile();
            if (file.exists()) {
                set.add(file.getPath());
                logger.debug("The file {} was added as a dependent of the jar {}", file.getPath(),
                        jarFile.getName());
            } else {
                logger.warn("The dependent file {} of the jar {} does not exist", file.getPath(),
                        jarFile.getName());
            }
        }
    }
}

From source file:net.avalonrealms.plugins.core.Core.java

@Override
public void onEnable() {
    // Folders/*from   w  w w . ja  va  2 s. c  o  m*/
    downloadFolder = new File(getDataFolder(), "downloads");
    errorFolder = new File(getDataFolder(), "errors");
    addonFolder = new File(getDataFolder(), "addons");
    repoFolder = new File(getDataFolder(), "repo");

    // Make folders TODO check result
    downloadFolder.mkdirs();
    errorFolder.mkdirs();
    addonFolder.mkdirs();
    repoFolder.mkdirs();

    // Utils
    errorUtils = new ErrorUtils(this);
    hookUtils = new HookUtils(this);

    // Updater
    updater = new Updater(this);

    // CommandInfo map
    try {
        Class<?> craftServer = SVPTools.getCurrentCBClass("CraftServer");
        if (craftServer == null)
            throw new RuntimeException("Computer says no to getting the craft server");
        Field f = craftServer.getDeclaredField("commandMap");
        f.setAccessible(true);
        commandMap = (CommandMap) f.get(getServer());
    } catch (Exception e) {
        errorUtils.logError(e);
        getServer().getPluginManager().disablePlugin(this);
        return;
    }

    // Listeners
    PluginManager p = getServer().getPluginManager();

    if (getHookUtils().isHooked(HookUtils.Hook.WORLD_GUARD)) {
        p.registerEvents(new WGListener(this, (com.sk89q.worldguard.bukkit.WorldGuardPlugin) getHookUtils()
                .getHook(HookUtils.Hook.WORLD_GUARD)), this);
    } else {
        getLogger().warning("WorldGuard was not found. WorldGuard events will not run.");
    }

    // Addons
    File[] addons = getAddonFolder().listFiles();

    if (addons == null) {
        throw new RuntimeException("Unable to create addon directory");
    }

    for (File file : addons) {
        if (file.isDirectory() || !file.getName().endsWith(".jar")) {
            continue;
        }

        try {
            ClasspathTools.addFileToClasspath(getClassLoader(), file);

            JarFile jar = new JarFile(file);

            Class<?> main = Class.forName(jar.getManifest().getMainAttributes().getValue("Addon-Package"));
            CoreAddon addon = (CoreAddon) main.newInstance();
            addon.setManifestValues(jar.getManifest());
            coreAddons.put(addon.getName(), addon);

            jar.close();
        } catch (Exception e) {
            errorUtils.logError(e);
        }
    }

    for (CoreAddon addon : Maps.newHashMap(coreAddons).values()) {
        addon.initialise(this);
        addon.onEnable();
    }

    getLogger().info("Enabled " + coreAddons.size() + " addons.");
}

From source file:org.jenkins_ci.update_center.model.MavenArtifact.java

public Manifest getManifest() throws IOException {
    if (manifest == null) {
        try {//from  w ww .j a  v a 2  s .co m
            JarFile jar = new JarFile(file);
            ZipEntry e = jar.getEntry("META-INF/MANIFEST.MF");
            timestamp = e.getTime();
            manifest = jar.getManifest();
            jar.close();
        } catch (IOException x) {
            throw (IOException) new IOException("Failed to open " + file).initCause(x);
        }
    }
    return manifest;
}