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:at.gv.egovernment.moa.id.configuration.config.ConfigurationProvider.java

private String parseVersionFromManifest() {

    try {// w  w w  . j a  va  2  s  . c  o m
        Class clazz = ConfigurationProvider.class;
        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();

        if (classPath.startsWith("jar")) {
            log.info("MOA-ID-Configuration Version can NOT parsed from Manifest. Set blank Version");
            return Constants.DEFAULT_VERSION;

        }

        String manifestPath = classPath.substring(0,
                classPath.lastIndexOf("WEB-INF/classes/") + "WEB-INF/classes/".length())
                + "../../META-INF/MANIFEST.MF";

        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
        ;

        Attributes attributes = manifest.getMainAttributes();
        String version = attributes.getValue("version");

        if (MiscUtil.isNotEmpty(version))
            return version;

        else {
            log.info("MOA-ID-Configuration Version not found in Manifest. Set blank Version");
            return Constants.DEFAULT_VERSION;

        }

    } catch (Throwable e) {
        log.info("MOA-ID Version can NOT parsed from Manifest. Set blank Version");

        return Constants.DEFAULT_VERSION;
    }

}

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  w ww.  ja  va 2  s.com
    });

    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.hl7.fhir.instance.conf.ServerConformanceProvider.java

private String getBuildDateFromManifest() {
    if (myRestfulServer != null && myRestfulServer.getServletContext() != null) {
        InputStream inputStream = myRestfulServer.getServletContext()
                .getResourceAsStream("/META-INF/MANIFEST.MF");
        if (inputStream != null) {
            try {
                Manifest manifest = new Manifest(inputStream);
                return manifest.getMainAttributes().getValue("Build-Time");
            } catch (IOException e) {
                // fall through
            }//from w ww.j av a  2 s .  c  o  m
        }
    }
    return null;
}

From source file:org.orbisgis.framework.BundleTools.java

private List<String> getClassPath() {
    List<String> classPath = new LinkedList<String>();
    // Read declared class in the manifest
    try {// w  ww  . ja v a 2s  .  c o  m
        Enumeration<URL> resources = BundleTools.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            try {
                Manifest manifest = new Manifest(url.openStream());
                String value = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
                if (value != null) {
                    String[] pathElements = value.split(" ");
                    if (pathElements == null) {
                        pathElements = new String[] { value };
                    }
                    classPath.addAll(Arrays.asList(pathElements));
                }
            } catch (IOException ex) {
                LOGGER.log(Logger.LOG_WARNING, "Unable to retrieve Jar MANIFEST " + url, ex);
            }
        }
    } catch (IOException ex) {
        LOGGER.log(Logger.LOG_WARNING, "Unable to retrieve Jar MANIFEST", ex);
    }
    // Read packages in the class path
    String javaClasspath = System.getProperty("java.class.path");
    String[] pathElements = javaClasspath.split(":");
    if (pathElements == null) {
        pathElements = new String[] { javaClasspath };
    }
    classPath.addAll(Arrays.asList(pathElements));
    return classPath;
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void mainClassFromManifest() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithoutMainMethod.class);
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue("Manifest-Version", "1.0");
    manifest.getMainAttributes().putValue("Main-Class", "a.b.C");
    this.testJarFile.addManifest(manifest);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.repackage(NO_LIBRARIES);// www .  java 2  s . c  o m
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes().getValue("Main-Class"))
            .isEqualTo("org.springframework.boot.loader.JarLauncher");
    assertThat(actualManifest.getMainAttributes().getValue("Start-Class")).isEqualTo("a.b.C");
    assertThat(hasLauncherClasses(file)).isTrue();
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Writes a .SF file with a digest to the manifest.
 *//*from   ww  w.  j a  va  2s.  c o m*/
private void writeSignatureFile(OutputStream out) throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (Android)");

    MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true,
            SdkConstants.UTF_8);

    // Digest of the entire manifest
    mManifest.write(print);
    print.flush();
    main.putValue(DIGEST_MANIFEST_ATTR, new String(Base64.encode(md.digest()), "ASCII"));

    Map<String, Attributes> entries = mManifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        Attributes sfAttr = new Attributes();
        sfAttr.putValue(DIGEST_ATTR, new String(Base64.encode(md.digest()), "ASCII"));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }
    CountOutputStream cout = new CountOutputStream(out);
    sf.write(cout);

    // A bug in the java.util.jar implementation of Android platforms
    // up to version 1.6 will cause a spurious IOException to be thrown
    // if the length of the signature file is a multiple of 1024 bytes.
    // As a workaround, add an extra CRLF in this case.
    if ((cout.size() % 1024) == 0) {
        cout.write('\r');
        cout.write('\n');
    }
}

From source file:org.eclipse.ecr.testlib.NXRuntimeTestCase.java

protected String readSymbolicName(BundleFile bf) {
    Manifest manifest = bf.getManifest();
    if (manifest == null) {
        return null;
    }/*from  ww  w  .  jav a  2  s .  com*/
    Attributes attrs = manifest.getMainAttributes();
    String name = attrs.getValue("Bundle-SymbolicName");
    if (name == null) {
        return null;
    }
    String[] sp = name.split(";", 2);
    return sp[0];
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void springBootVersion() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.repackage(NO_LIBRARIES);// w  w w.  j  a v  a 2  s  . c o  m
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes()).containsKey(new Attributes.Name("Spring-Boot-Version"));
}

From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java

private void checkJarArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix)
        throws IOException {

    JarFile jarFile = null;/*ww w. j ava 2  s.c  o m*/
    try {
        jarFile = new JarFile(archiveFile);

        final Manifest manifest = jarFile.getManifest();
        assertNotNull("Manifest should be present", manifest);
        assertEquals("Manifest version should be 1.0", "1.0",
                manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION));

        final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix);

        final Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            final JarEntry jarEntry = entries.nextElement();
            if (MANIFEST_FILE_ENTRY_NAME.equalsIgnoreCase(jarEntry.getName())) {
                // It is the manifest file, not added by use
                continue;
            }
            if (jarEntry.isDirectory()) {
                assertTrue("Directory in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.dirs.contains(jarEntry.getName()));
                archiveEntries.dirs.remove(jarEntry.getName());
            } else {
                assertTrue("File in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.files.containsKey(jarEntry.getName()));
                final byte[] inflatedMd5 = getMd5Digest(jarFile.getInputStream(jarEntry), false);
                assertArrayEquals("MD5 hash of files should equal [" + jarEntry.getName() + "]",
                        archiveEntries.files.get(jarEntry.getName()), inflatedMd5);
                archiveEntries.files.remove(jarEntry.getName());
            }
        }

        // Check that all files and directories have been accounted for
        assertTrue("All directories should be in the jar", archiveEntries.dirs.isEmpty());
        assertTrue("All files should be in the jar", archiveEntries.files.isEmpty());
    } finally {
        if (null != jarFile) {
            jarFile.close();
        }
    }
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void noMainClassAndLayoutIsNone() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File file = this.testJarFile.getFile();
    Repackager repackager = new Repackager(file);
    repackager.setLayout(new Layouts.None());
    repackager.repackage(file, NO_LIBRARIES);
    Manifest actualManifest = getManifest(file);
    assertThat(actualManifest.getMainAttributes().getValue("Main-Class")).isEqualTo("a.b.C");
    assertThat(hasLauncherClasses(file)).isFalse();
}