Example usage for java.util.jar Manifest getMainAttributes

List of usage examples for java.util.jar Manifest getMainAttributes

Introduction

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

Prototype

public Attributes getMainAttributes() 

Source Link

Document

Returns the main Attributes for the Manifest.

Usage

From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginOSGiManifestTest.java

private String valueFor(final String prefix) throws IOException {
    if (!manifestFile.exists()) {
        return null;
    }/*ww w .  j  av a  2  s . co  m*/

    FileInputStream manifestInputStream = new FileInputStream(manifestFile);
    Manifest manifest = new Manifest(manifestInputStream);
    Attributes entries = manifest.getMainAttributes();

    return entries.getValue(prefix);
}

From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginOSGiManifestTest.java

private void addHeaderToManifest(String header, String value) throws IOException {
    FileInputStream manifestInputStream = new FileInputStream(manifestFile);
    Manifest manifest = new Manifest(manifestInputStream);
    Attributes entries = manifest.getMainAttributes();
    entries.put(new Attributes.Name(header), value);

    FileOutputStream manifestOutputStream = new FileOutputStream(manifestFile, false);
    manifest.write(manifestOutputStream);
    manifestOutputStream.close();//from  w w w  .ja  va2s  .  c om
    manifestInputStream.close();
}

From source file:com.twosigma.beakerx.autocomplete.ClasspathScanner.java

private boolean findClasses(File root, File file, boolean includeJars) {
    if (file != null && file.isDirectory()) {
        File[] lf = file.listFiles();
        if (lf != null)
            for (File child : lf) {
                if (!findClasses(root, child, includeJars)) {
                    return false;
                }//  w  w  w .  j  a v a  2  s .co m
            }
    } else {
        if (file.getName().toLowerCase().endsWith(".jar") && includeJars) {
            JarFile jar = null;
            try {
                jar = new JarFile(file);
            } catch (Exception ex) {
            }
            if (jar != null) {
                try {
                    Manifest mf = jar.getManifest();
                    if (mf != null) {
                        String cp = mf.getMainAttributes().getValue("Class-Path");
                        if (StringUtils.isNotEmpty(cp)) {
                            for (String fn : cp.split(" ")) {
                                if (!fn.equals(".")) {
                                    File child = new File(
                                            file.getParent() + System.getProperty("file.separator") + fn);
                                    if (child.getAbsolutePath().equals(jar.getName())) {
                                        continue; //skip bad jars, that contain references to themselves in MANIFEST.MF
                                    }
                                    if (child.exists()) {
                                        if (!findClasses(root, child, includeJars)) {
                                            return false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                }

                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    JarEntry entry = entries.nextElement();
                    String name = entry.getName();
                    int extIndex = name.lastIndexOf(".class");
                    if (extIndex > 0 && !name.contains("$")) {
                        String cname = name.substring(0, extIndex).replace("/", ".");
                        int pIndex = cname.lastIndexOf('.');
                        if (pIndex > 0) {
                            String pname = cname.substring(0, pIndex);
                            cname = cname.substring(pIndex + 1);
                            if (!packages.containsKey(pname))
                                packages.put(pname, new ArrayList<String>());
                            packages.get(pname).add(cname);
                        }
                    }
                }
            }
        } else if (file.getName().toLowerCase().endsWith(".class")) {
            String cname = createClassName(root, file);
            if (!cname.contains("$")) {
                int pIndex = cname.lastIndexOf('.');
                if (pIndex > 0) {
                    String pname = cname.substring(0, pIndex + 1);
                    cname = cname.substring(pIndex);
                    if (!packages.containsKey(pname))
                        packages.put(pname, new ArrayList<String>());
                    packages.get(pname).add(cname);
                }
            }
        } else {
            examineFile(root, file);
        }
    }

    return true;
}

From source file:com.wavemaker.tools.ant.NewCopyRuntimeJarsTask.java

protected List<String> getReferencedClassPathJars(File jarFile, boolean failOnError) {

    try {/* w w w.  j  ava  2  s  . c om*/
        JarFile runtimeJar = new JarFile(jarFile);
        Manifest manifest = runtimeJar.getManifest();
        String jarClassPath = manifest.getMainAttributes().getValue(CLASSPATH_ATTR_NAME);
        if (failOnError && jarClassPath == null) {
            throw new IllegalStateException(CLASSPATH_ATTR_NAME + " attribute is missing from " + jarFile);
        } else if (jarClassPath == null) {
            return new ArrayList<String>();
        }

        String[] tokens = jarClassPath.split("\\s");

        List<String> jarNames = new ArrayList<String>(tokens.length + 1);

        jarNames.add(jarFile.getName());
        for (String jarName : jarClassPath.split("\\s")) {
            jarNames.add(jarName);
        }
        return jarNames;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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.
 *//*  w ww . j  av a  2s. com*/
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:org.apache.felix.webconsole.internal.core.InstallAction.java

private String getSymbolicName(File bundleFile) {
    JarFile jar = null;/*from  ww w .  j  a  v  a 2  s. c om*/
    try {
        jar = new JarFile(bundleFile);
        Manifest m = jar.getManifest();
        if (m != null) {
            return m.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
        }
    } catch (IOException ioe) {
        getLog().log(LogService.LOG_WARNING, "Cannot extract symbolic name of bundle file " + bundleFile, ioe);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }

    // fall back to "not found"
    return null;
}

From source file:cn.homecredit.web.listener.MyOsgiHost.java

protected String getVersion(URL url) {
    if ("jar".equals(url.getProtocol())) {
        try {/*from   w w w .j  av  a 2 s .c  om*/
            JarFile jarFile = new JarFile(new File(URLUtil.normalizeToFileProtocol(url).toURI()));
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (StringUtils.isNotBlank(version)) {
                    return getVersionFromString(version);
                }
            } else {
                //try to get the version from the file name
                return getVersionFromString(jarFile.getName());
            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Unable to extract version from [#0], defaulting to '1.0.0'", url.toExternalForm());
            }
        }
    }
    return "1.0.0";
}

From source file:io.fabric8.vertx.maven.plugin.utils.PackageHelper.java

/**
 *
 *///from  w  w w . jav  a  2 s . c o m
protected void generateManifest() {
    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    attributes.put(Attributes.Name.MAIN_CLASS, mainClass);
    //This is a typical situation when application is launched with custom launcher
    if (mainVerticle != null) {
        attributes.put(MAIN_VERTICLE, mainVerticle);
    }

    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        manifest.write(bout);
        bout.close();
        byte[] bytes = bout.toByteArray();
        //TODO: merge existing manifest with current one
        this.archive.setManifest(new ByteArrayAsset(bytes));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.bndtools.rt.repository.server.RepositoryResourceComponent.java

@POST
@Path("bundles")
@Consumes({ MediaType.APPLICATION_OCTET_STREAM, ProvisioningService.MIME_BUNDLE })
public Response uploadBundle(@Context UriInfo uriInfo, InputStream stream) throws Exception {
    if (!repo.canWrite())
        return Response.status(Status.BAD_REQUEST).entity("Repository is not writeable").build();

    InputStream bufferedStream = stream.markSupported() ? stream : new BufferedInputStream(stream);
    Manifest manifest = readManifest(bufferedStream);

    Attributes mainAttribs = manifest.getMainAttributes();
    String bsn = mainAttribs.getValue(Constants.BUNDLE_SYMBOLICNAME);
    if (bsn == null)
        return Response.status(Status.BAD_REQUEST).entity("not a bundle").build();
    String versionStr = mainAttribs.getValue(Constants.BUNDLE_VERSION);
    Version version = versionStr != null ? new Version(versionStr) : Version.emptyVersion;

    URI bundleLocation = uriInfo.getAbsolutePathBuilder().path("{bsn}/{version}").build(bsn, version);

    repo.put(bufferedStream, RepositoryPlugin.DEFAULTOPTIONS);
    return Response.created(bundleLocation).build();
}

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

public Manifest findManifest() {
    try {/*  w ww  .  j av a  2s. c o  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;
    }
}