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:Main.java

public static void main(String[] argv) throws Exception {
    JarFile jarfile = new JarFile("filename.jar");

    Manifest manifest = jarfile.getManifest();

    Attributes attrs = (Attributes) manifest.getMainAttributes();

    for (Iterator it = attrs.keySet().iterator(); it.hasNext();) {
        Attributes.Name attrName = (Attributes.Name) it.next();

        String attrValue = attrs.getValue(attrName);
    }//from www.  j ava 2s  .c  o m
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JarFile jarfile = new JarFile("filename.jar", true);

    Manifest manifest = jarfile.getManifest();

    Attributes attrs = (Attributes) manifest.getMainAttributes();

    for (Iterator it = attrs.keySet().iterator(); it.hasNext();) {
        Attributes.Name attrName = (Attributes.Name) it.next();

        String attrValue = attrs.getValue(attrName);
    }//  w ww.ja v  a2  s .c  o  m
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JarFile jarfile = new JarFile(new File("filename.jar"), true);

    Manifest manifest = jarfile.getManifest();

    Attributes attrs = (Attributes) manifest.getMainAttributes();

    for (Iterator it = attrs.keySet().iterator(); it.hasNext();) {
        Attributes.Name attrName = (Attributes.Name) it.next();

        String attrValue = attrs.getValue(attrName);
    }/*from   ww  w.java  2 s. co m*/
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    JarFile jarfile = new JarFile(new File("filename.jar"), true, JarFile.OPEN_READ);

    Manifest manifest = jarfile.getManifest();

    Attributes attrs = (Attributes) manifest.getMainAttributes();

    for (Iterator it = attrs.keySet().iterator(); it.hasNext();) {
        Attributes.Name attrName = (Attributes.Name) it.next();

        String attrValue = attrs.getValue(attrName);
    }//from  w  w  w  . ja  v a 2 s.co  m
}

From source file:com.textocat.textokit.morph.opencorpora.resource.XmlDictionaryPSP.java

public static void main(String[] args) throws Exception {
    XmlDictionaryPSP cfg = new XmlDictionaryPSP();
    new JCommander(cfg, args);

    MorphDictionaryImpl dict = new MorphDictionaryImpl();
    DictionaryExtension ext = cfg.dictExtensionClass.newInstance();
    FileInputStream fis = FileUtils.openInputStream(cfg.dictXmlFile);
    try {/*from   www .j  a  v  a 2 s.  co  m*/
        new XmlDictionaryParser(dict, ext, fis).run();
    } finally {
        IOUtils.closeQuietly(fis);
    }

    System.out.println("Preparing to serialization...");
    long timeBefore = currentTimeMillis();
    OutputStream fout = new BufferedOutputStream(FileUtils.openOutputStream(cfg.outputJarFile), 8192 * 8);
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(OpencorporaMorphDictionaryAPI.ME_OPENCORPORA_DICTIONARY_VERSION,
            dict.getVersion());
    manifest.getMainAttributes().putValue(OpencorporaMorphDictionaryAPI.ME_OPENCORPORA_DICTIONARY_REVISION,
            dict.getRevision());
    manifest.getMainAttributes().putValue(OpencorporaMorphDictionaryAPI.ME_OPENCORPORA_DICTIONARY_VARIANT,
            cfg.variant);
    String dictEntryName = String.format(
            OpencorporaMorphDictionaryAPI.FILENAME_PATTERN_OPENCORPORA_SERIALIZED_DICT, dict.getVersion(),
            dict.getRevision(), cfg.variant);
    JarOutputStream jarOut = new JarOutputStream(fout, manifest);
    jarOut.putNextEntry(new ZipEntry(dictEntryName));
    ObjectOutputStream serOut = new ObjectOutputStream(jarOut);
    try {
        serOut.writeObject(dict.getGramModel());
        serOut.writeObject(dict);
    } finally {
        serOut.flush();
        jarOut.closeEntry();
        serOut.close();
    }
    System.out.println(String.format("Serialization finished in %s ms.\nOutput size: %s bytes",
            currentTimeMillis() - timeBefore, cfg.outputJarFile.length()));
}

From source file:org.northrop.leanne.publisher.Main.java

public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    try {// www.  ja va  2s .com
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (args.length == 0 || line.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("pub", options);
        } else if (line.hasOption("version")) {
            URLClassLoader cl = (URLClassLoader) Main.class.getClassLoader();
            String title = "";
            String version = "";
            String date = "";
            try {
                URL url = cl.findResource("META-INF/MANIFEST.MF");
                Manifest manifest = new Manifest(url.openStream());
                Attributes attr = manifest.getMainAttributes();
                title = attr.getValue("Implementation-Title");
                version = attr.getValue("Implementation-Version");
                date = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM)
                        .format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(attr.getValue("Built-Date")));
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println("------------------------------------------------------------");
            System.out.println("Publisher Pipeline " + version);
            System.out.println("------------------------------------------------------------");
            System.out.println("");
            System.out.println(title + " build time " + date);
            System.out.println("Java: " + System.getProperty("java.version"));
            System.out.println("JVM:  " + System.getProperty("java.vendor"));
            System.out.println("OS:   " + System.getProperty("os.name") + " " + System.getProperty("os.version")
                    + " " + System.getProperty("os.arch"));
        } else {
            Option[] options = line.getOptions();
            Binding binding = new Binding();
            binding.setVariable("home", System.getProperty("pub.home"));
            binding.setVariable("inputDir", System.getProperty("pub.home") + "/input");
            binding.setVariable("outputDir", System.getProperty("pub.home") + "/output");
            binding.setVariable("appName", System.getProperty("program.name"));
            binding.setVariable("isdebug", false);

            for (int i = 0; i < options.length; i++) {
                Option opt = options[i];
                binding.setVariable("is" + opt.getOpt(), true);
            }

            String[] roots = new String[] { System.getProperty("pub.home") + "/resources/scripts",
                    System.getProperty("pub.home") + "/resources/scripts/formats" };
            ClassLoader parent = Main.class.getClassLoader();
            GroovyScriptEngine gse = new GroovyScriptEngine(roots, parent);

            if (!line.hasOption("rerun")) {
                gse.run("prep.groovy", binding);
            }

            for (String name : getFormats()) {
                if (line.hasOption(name.toLowerCase())) {
                    String file = ("" + name.charAt(0)).toLowerCase() + name.substring(1) + ".groovy";
                    gse.run(file, binding);
                }
            }
        }
    } catch (ParseException exp) {
        System.err.println("Command line parsing failed.  Reason: " + exp.getMessage());
    } catch (ResourceException resourceError) {
        System.err.println("Groovy script failed.  Reason: " + resourceError.getMessage());
    } catch (IOException ioError) {
        System.err.println("Groovy script failed.  Reason: " + ioError.getMessage());
    } catch (ScriptException error) {
        System.err.println("Groovy script failed.  Reason: " + error.getMessage());
        error.printStackTrace();
    }
}

From source file:org.apache.hadoop.hbase.util.RunTrigger.java

/**
 * @param args// w w w  .j  a  v a 2s.  c  om
 * @throws Throwable 
 */
public static void main(String[] args) throws Throwable {
    String usage = "RunTrigger jarFile [mainClass] args...";

    if (args.length < 1) {
        System.err.println(usage);
        System.exit(-1);
    }
    int firstArg = 0;
    String fileName = args[firstArg++];
    File file = new File(fileName);
    File tmpJarFile = new File("/tmp/hbase/triggerJar/trigger.jar");
    if (tmpJarFile.exists()) {
        tmpJarFile.delete();
    }
    FileUtils.copyFile(file, tmpJarFile);

    String mainClassName = null;
    JarFile jarFile;
    try {
        jarFile = new JarFile(fileName);
    } catch (IOException e) {
        throw new IOException("Error opening trigger jar: " + fileName).initCause(e);
    }

    Manifest manifest = jarFile.getManifest();
    if (manifest != null) {
        mainClassName = manifest.getMainAttributes().getValue("Main-Class");
    }
    jarFile.close();
    System.out.println("Manifest From Jar: " + mainClassName);

    if (mainClassName == null) {
        if (args.length < 2) {
            System.err.println(usage);
            System.exit(-1);
        }
        mainClassName = args[firstArg++];
    }
    System.out.println("Manifest class from argument: " + mainClassName);

    mainClassName = mainClassName.replace("/", ".");

    //'hbase.tmp.dir'
    File tmpDir = new File("/tmp/hbase/trigger/");

    tmpDir.mkdirs();
    if (!tmpDir.isDirectory()) {
        System.err.println("Mkdirs failed to create " + tmpDir);
        System.exit(-1);
    }
    final File workDir = File.createTempFile("trigger-unjar", "", tmpDir);
    workDir.delete();
    workDir.mkdirs();
    if (!workDir.isDirectory()) {
        System.err.println("Mkdirs failed to create " + workDir);
        System.exit(-1);
    }

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                FileUtil.fullyDelete(workDir);
            } catch (IOException e) {
            }
        }
    });

    unJar(file, workDir);

    ArrayList<URL> classPath = new ArrayList<URL>();
    classPath.add(new File(workDir + "/").toURL());
    classPath.add(file.toURL());
    classPath.add(new File(workDir, "classes/").toURL());
    File[] libs = new File(workDir, "lib").listFiles();
    if (libs != null) {
        for (int i = 0; i < libs.length; i++) {
            classPath.add(libs[i].toURL());
        }
    }

    ClassLoader loader = new URLClassLoader(classPath.toArray(new URL[0]));
    Thread.currentThread().setContextClassLoader(loader);
    Class<?> mainClass = Class.forName(mainClassName, true, loader);
    Method main = mainClass.getMethod("main", new Class[] { Array.newInstance(String.class, 0).getClass() });
    String[] newArgs = Arrays.asList(args).subList(firstArg, args.length).toArray(new String[0]);
    try {
        main.invoke(null, new Object[] { newArgs });
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}

From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java

public static void main(String[] args) {
    // check &   validate cmdline options
    OptionGroup opt_g = getCMDLineOptionsGroups();
    Options opt = getCMDLineOptions();//  w w  w . j  a va  2s.  c  o  m
    opt.addOptionGroup(opt_g);

    CommandLineParser cli = new DefaultParser();
    try {
        CommandLine cl = cli.parse(opt, args);

        if (cl.hasOption("v")) {
            VerboseOutputFilter.SHOW_VERBOSE = true;
        }

        switch (opt_g.getSelected()) {
        case "V":
            try {
                URL jarUrl = Main.class.getProtectionDomain().getCodeSource().getLocation();
                String jarPath = URLDecoder.decode(jarUrl.getFile(), "UTF-8");
                JarFile jarFile = new JarFile(jarPath);
                Manifest m = jarFile.getManifest();
                StringBuilder versionInfo = new StringBuilder();
                for (Object key : m.getMainAttributes().keySet()) {
                    versionInfo.append(key).append(":").append(m.getMainAttributes().getValue(key.toString()))
                            .append("\n");
                }
                System.out.println(versionInfo.toString());
            } catch (Exception e) {
                log.error("Version info could not be read.");
            }
            break;
        case "h":
            HelpFormatter help = new HelpFormatter();
            String header = ""; //TODO: missing infotext 
            StringBuilder footer = new StringBuilder("Supported configuration properties :");
            help.printHelp("CodeGen -h | -V | -g  [...]", header, opt, footer.toString());
            break;
        case "g":
            // target dir
            if (cl.hasOption("t")) {
                File target = new File(cl.getOptionValue("t"));
                if (target.isDirectory() && target.canExecute() && target.canWrite()) {
                    config.setProperty("target.dir", cl.getOptionValue("t"));
                } else {
                    log.error("Target dir '{}' is inaccessible!", cl.getOptionValue("t"));
                    break;
                }
            } else {
                config.setProperty("target.dir", System.getProperty("java.io.tmpdir"));
            }

            // project dir
            if (cl.hasOption("p")) {
                File project = new File(cl.getOptionValue("p"));
                if (!project.exists()) {
                    if (!project.mkdirs()) {
                        log.error("Project dir '{}' can't be created!", cl.getOptionValue("p"));
                        break;
                    }
                }

                if (project.isDirectory() && project.canExecute() && project.canWrite()) {
                    config.setProperty("project.dir", cl.getOptionValue("p"));
                } else {
                    log.error("Project dir '{}' is inaccessible!", cl.getOptionValue("p"));
                    break;
                }
            }

            generateAppfromXML(cl.getOptionValue("g"));
            break;
        }
    } catch (ParseException e) {
        log.error("ParseException occurred while parsing cmdline arguments!\n{}", e.getLocalizedMessage());
    }

}

From source file:Main.java

private static Manifest getCompositeManifest(Map compositeManifest) {
    Manifest manifest = new Manifest();
    Attributes attributes = manifest.getMainAttributes();
    attributes.putValue("Manifest-Version", "1.0"); //$NON-NLS-1$//$NON-NLS-2$
    // get the common headers Bundle-ManifestVersion, Bundle-SymbolicName and Bundle-Version
    // get the manifest version from the map
    String manifestVersion = (String) compositeManifest.remove(Constants.BUNDLE_MANIFESTVERSION);
    // here we assume the validation got the correct version for us
    attributes.putValue(Constants.BUNDLE_MANIFESTVERSION, manifestVersion);
    // Ignore the Equinox composite bundle header
    compositeManifest.remove(BaseStorageHook.COMPOSITE_HEADER);
    attributes.putValue(BaseStorageHook.COMPOSITE_HEADER, BaseStorageHook.COMPOSITE_BUNDLE);
    for (Iterator entries = compositeManifest.entrySet().iterator(); entries.hasNext();) {
        Map.Entry entry = (Entry) entries.next();
        if (entry.getKey() instanceof String && entry.getValue() instanceof String)
            attributes.putValue((String) entry.getKey(), (String) entry.getValue());
    }//ww  w. j  av  a2  s  .c  om
    return manifest;
}

From source file:edu.cmu.tetrad.cli.TetradCliApp.java

private static void showVersion() {
    try {/*  ww w  . j  a  v  a  2s. c  om*/
        JarFile jarFile = new JarFile(
                TetradCliApp.class.getProtectionDomain().getCodeSource().getLocation().getPath(), true);
        Manifest manifest = jarFile.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        String artifactId = attributes.getValue("Implementation-Title");
        String version = attributes.getValue("Implementation-Version");
        System.out.printf("%s version: %s%n", artifactId, version);
    } catch (IOException exception) {
        String errMsg = "Unable to retrieve version number.";
        System.err.println(errMsg);
        LOGGER.error(errMsg, exception);
    }
}