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:info.evanchik.eclipse.karaf.core.KarafCorePluginUtils.java

/**
 * Reads a specified MANIFEST.MF entry from the JAR
 *
 * @param src//from ww w .ja  va2 s .  co m
 *            the JAR file
 * @param manifestHeader
 *            the name of the header to read
 * @return the header as read from the MANIFEST.MF or null if it does not
 *         exist or there was a problem reading the JAR
 * @throws IOException
 *             if there is a problem reading the JAR
 */
public static String getJarManifestHeader(final File src, final String manifestHeader) throws IOException {
    final JarFile jar = new JarFile(src);
    final Manifest mf = jar.getManifest();

    return (String) mf.getMainAttributes().get(manifestHeader);
}

From source file:org.springframework.data.hadoop.mapreduce.ExecutionUtils.java

static String mainClass(Resource jar) throws IOException {
    JarInputStream jis = new JarInputStream(jar.getInputStream());
    try {/*  w w  w.j  a  v a2 s .co m*/
        Manifest mf = jis.getManifest();
        if (mf != null) {
            String main = mf.getMainAttributes().getValue("Main-Class");
            if (StringUtils.hasText(main)) {
                return main.replace("/", ".");
            }
        }
        return null;
    } finally {
        IOUtils.closeStream(jis);
    }
}

From source file:io.selendroid.builder.SelendroidServerBuilder.java

public static String getJarVersionNumber() {
    Class clazz = SelendroidStandaloneDriver.class;
    String className = clazz.getSimpleName() + ".class";
    String classPath = clazz.getResource(className).toString();
    if (!classPath.startsWith("jar")) {
        // Class not from JAR
        return "dev";
    }//from w w w.  j a  v a 2 s.c  o m
    String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
    Manifest manifest = null;
    try {
        manifest = new Manifest(new URL(manifestPath).openStream());
    } catch (Exception e) {
        return "";
    }
    Attributes attr = manifest.getMainAttributes();
    String value = attr.getValue("version");
    return value;
}

From source file:com.heliosdecompiler.bootstrapper.Bootstrapper.java

private static HeliosData loadHelios() throws IOException {
    System.out.println("Finding Helios implementation");

    HeliosData data = new HeliosData();

    boolean needsToDownload = !IMPL_FILE.exists();
    if (!needsToDownload) {
        try (JarFile jarFile = new JarFile(IMPL_FILE)) {
            ZipEntry entry = jarFile.getEntry("META-INF/MANIFEST.MF");
            if (entry == null) {
                needsToDownload = true;// w  w  w. j a  v  a2 s.co  m
            } else {
                Manifest manifest = new Manifest(jarFile.getInputStream(entry));
                String ver = manifest.getMainAttributes().getValue("Implementation-Version");
                try {
                    data.buildNumber = Integer.parseInt(ver);
                    data.version = manifest.getMainAttributes().getValue("Version");
                    data.mainClass = manifest.getMainAttributes().getValue("Main-Class");
                } catch (NumberFormatException e) {
                    needsToDownload = true;
                }
            }
        } catch (IOException e) {
            needsToDownload = true;
        }
    }
    if (needsToDownload) {
        URL latestJar = new URL(LATEST_JAR);
        System.out.println("Downloading latest Helios implementation");

        FileOutputStream out = new FileOutputStream(IMPL_FILE);
        HttpURLConnection connection = (HttpURLConnection) latestJar.openConnection();
        if (connection.getResponseCode() == 200) {
            int contentLength = connection.getContentLength();
            if (contentLength > 0) {
                InputStream stream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int amnt;
                AtomicInteger total = new AtomicInteger();
                AtomicBoolean stop = new AtomicBoolean(false);

                Thread progressBar = new Thread() {
                    public void run() {
                        JPanel panel = new JPanel();
                        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

                        JLabel label = new JLabel();
                        label.setText("Downloading latest Helios build");
                        panel.add(label);

                        GridLayout layout = new GridLayout();
                        layout.setColumns(1);
                        layout.setRows(3);
                        panel.setLayout(layout);
                        JProgressBar pbar = new JProgressBar();
                        pbar.setMinimum(0);
                        pbar.setMaximum(100);
                        panel.add(pbar);

                        JTextArea textArea = new JTextArea(1, 3);
                        textArea.setOpaque(false);
                        textArea.setEditable(false);
                        textArea.setText("Downloaded 00.00MB/00.00MB");
                        panel.add(textArea);

                        JFrame frame = new JFrame();
                        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                        frame.setContentPane(panel);
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);

                        while (!stop.get()) {
                            SwingUtilities.invokeLater(
                                    () -> pbar.setValue((int) (100.0 * total.get() / contentLength)));

                            textArea.setText("Downloaded " + bytesToMeg(total.get()) + "MB/"
                                    + bytesToMeg(contentLength) + "MB");
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException ignored) {
                            }
                        }
                        frame.dispose();
                    }
                };
                progressBar.start();

                while ((amnt = stream.read(buffer)) != -1) {
                    out.write(buffer, 0, amnt);
                    total.addAndGet(amnt);
                }
                stop.set(true);
                return loadHelios();
            } else {
                throw new IOException("Content-Length set to " + connection.getContentLength());
            }
        } else if (connection.getResponseCode() == 404) { // Most likely bootstrapper is out of date
            throw new RuntimeException("Bootstrapper out of date!");
        } else {
            throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
        }
    }

    return data;
}

From source file:org.dita.dost.util.DitaUtil.java

public static ILaunch publish(IFile ditaMapFile, String antTargets, String ditavalFileName)
        throws IOException, CoreException, URISyntaxException {

    IProject ditaProject = ditaMapFile.getProject();

    IFolder ditaFolder = ditaProject.getFolder(new Path("dita"));

    IFile ditaValFile = ditaFolder.getFile(ditavalFileName);

    StringBuffer jvmArguments = new StringBuffer();
    for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
        if (arg.startsWith("-X")) {
            jvmArguments.append(arg);/*from   w ww . jav  a  2 s . c o  m*/
            jvmArguments.append(" ");
        }
    }

    jvmArguments.append("-Dfile.encoding=UTF-8 ");

    String[] segments = ditaMapFile.getName().split("\\.");

    String ditaMapFileRoot = segments[0];

    Bundle bundle = Platform.getBundle("org.dita.dost");

    Path path = new Path("META-INF/MANIFEST.MF");

    URL fileURL = FileLocator.find(bundle, path, null);

    Path ditadirPath = new Path("DITA-OT");

    URL ditadirURL = FileLocator.find(bundle, ditadirPath, null);

    ditadirURL = FileLocator.toFileURL(ditadirURL);

    InputStream in = fileURL.openStream();

    Manifest ditaPluginManifest = new Manifest(in);

    Attributes attributes = ditaPluginManifest.getMainAttributes();

    String ditaClassPath = attributes.getValue("Bundle-ClassPath");

    List<String> classpath = new ArrayList<String>();

    String ditaRequiredBundles = attributes.getValue("Require-Bundle");

    for (String requiredBundleSymbolicName : ditaRequiredBundles.split(",")) {

        // get before ;
        Bundle requiredBundle = Platform.getBundle(requiredBundleSymbolicName.split(";")[0]);

        // Assume the bundle is optional if null
        if (requiredBundle != null) {
            File file = FileLocator.getBundleFile(requiredBundle);

            IRuntimeClasspathEntry requiredBundleEntry = JavaRuntime
                    .newArchiveRuntimeClasspathEntry(new Path(file.getPath()));
            requiredBundleEntry.setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
            classpath.add(requiredBundleEntry.getMemento());
        }
    }

    for (String classPath : ditaClassPath.split(",")) {
        if (".".equals(classPath)) {
            URL url = FileLocator.find(bundle, new Path(""), null);
            url = FileLocator.toFileURL(url);
            IRuntimeClasspathEntry pluginEntry = JavaRuntime.newRuntimeContainerClasspathEntry(
                    new Path(url.getPath()), IRuntimeClasspathEntry.USER_CLASSES);
            classpath.add(pluginEntry.getMemento());
        } else {
            URL url = FileLocator.find(bundle, new Path(classPath), null);
            url = FileLocator.toFileURL(url);
            IRuntimeClasspathEntry toolsEntry = JavaRuntime
                    .newArchiveRuntimeClasspathEntry(new Path(url.getPath()));
            toolsEntry.setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
            classpath.add(toolsEntry.getMemento());
        }
    }

    ContributedClasspathEntriesEntry ccee = new ContributedClasspathEntriesEntry();

    AntHomeClasspathEntry ace = new AntHomeClasspathEntry();

    classpath.add(ace.getMemento());

    classpath.add(ccee.getMemento());

    ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();

    ILaunchConfigurationType type = launchManager
            .getLaunchConfigurationType(IAntLaunchConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);

    URL ditaPublishBuildFileURL = fileURL = FileLocator.find(bundle, new Path("dita-publish.xml"), null);

    ditaPublishBuildFileURL = FileLocator.toFileURL(ditaPublishBuildFileURL);

    String name = launchManager.generateLaunchConfigurationName("Publish DITA");

    ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, name);

    workingCopy.setAttribute("org.eclipse.ui.externaltools.ATTR_LOCATION", ditaPublishBuildFileURL.getPath());

    IVMInstall jre = JavaRuntime.getDefaultVMInstall();

    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, jre.getName());

    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
            "-Djavax.xml.transform.TransformerFactory=net.sf.saxon.TransformerFactoryImpl");

    Map<String, String> antProperties = new HashMap<String, String>();

    antProperties.put("dita.dir", ditadirURL.getPath());
    antProperties.put("ditaMapFile", ditaMapFile.getLocation().toOSString());

    if (ditaValFile != null) {
        antProperties.put("args.filter", ditaValFile.getLocation().toOSString());

    }

    antProperties.put("ditaMapFileName", ditaMapFile.getName().substring(0,
            ditaMapFile.getName().length() - ditaMapFile.getFileExtension().length()));

    // antProperties.put("outputLocation", ditaProject.getLocation().toOSString());
    antProperties.put("dita.output", ditaProject.getLocation().append(antTargets).toOSString());
    antProperties.put("ditaMapFileRoot", ditaMapFileRoot);

    String fileName = getFileNameFromMap(ditaMapFile.getLocation().toOSString());
    if (StringUtils.isEmpty(fileName)) {
        fileName = ditaMapFile.getName().replace("." + ditaMapFile.getFileExtension(), "");
    }

    antProperties.put("fileName", fileName);
    antProperties.put("args.debug", "no");
    antProperties.put("ditaFilePath", ditaFolder.getLocation().toOSString());
    antProperties.put("tempFilePath",
            org.dita.dost.internal.Activator.getDefault().getStateLocation().append("temp").toOSString());
    antProperties.put("docProject", ditaProject.getLocation().toOSString());

    String pdfFileLocation = ditaMapFile.getName();
    pdfFileLocation = pdfFileLocation.replaceFirst(".ditamap", ".pdf");
    antProperties.put("pdflocation", pdfFileLocation);

    workingCopy.setAttribute("process_factory_id", "org.eclipse.ant.ui.remoteAntProcessFactory");
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
            "org.eclipse.ant.internal.ui.antsupport.InternalAntRunner");

    workingCopy.setAttribute(
            org.eclipse.core.externaltools.internal.IExternalToolConstants.ATTR_WORKING_DIRECTORY,
            ditaProject.getLocation().toOSString());
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, jvmArguments.toString());
    workingCopy.setAttribute(org.eclipse.ant.launching.IAntLaunchConstants.ATTR_ANT_TARGETS, antTargets);
    workingCopy.setAttribute(IAntLaunchConstants.ATTR_ANT_PROPERTIES, antProperties);
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpath);
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false);
    workingCopy.setAttribute(IDebugUIConstants.ATTR_CONSOLE_PROCESS, false);
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER,
            "org.eclipse.ant.ui.AntClasspathProvider");
    workingCopy.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, true);

    workingCopy.setAttribute(DebugPlugin.ATTR_CONSOLE_ENCODING, "UTF-8");

    workingCopy.migrate();

    return workingCopy.launch(ILaunchManager.RUN_MODE, null, false, true);
}

From source file:de.uzk.hki.da.utils.Utilities.java

public static String getBuildNumber() {
    String buildNumber = "fakeBuildNumber";
    try {//from  w  ww .j  a v  a 2s  . co  m
        JarFile file = null;
        Manifest mf = null;
        file = new JarFile(new File(
                Utilities.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()));
        mf = file.getManifest();
        Attributes attr = mf.getMainAttributes();
        buildNumber = attr.getValue("buildNumber");
    } catch (Exception e) {
        logger.debug("Can not extract the build number from ");
    }
    return buildNumber;
}

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

/**
 * Returns the version for the plugin represented by the given descriptor/file.
 * If the descriptor defines a version, that is considered the version of the plugin.
 * However, if the plugin descriptor does not define a version, the plugin jar's manifest
 * is searched for an implementation version string and if one is found that is the version
 * of the plugin. If the manifest entry is also not found, the plugin does not have a version
 * associated with it, which causes this method to throw an exception.
 *
 * @param pluginFile the plugin jar/*w  w  w .java  2  s  . c  om*/
 * @param descriptor the plugin descriptor as found in the plugin jar (if <code>null</code>,
 *                   the plugin file will be read and the descriptor parsed from it)
 * @return the version of the plugin
 * @throws Exception if the plugin is invalid, there is no version for the plugin or the version string is invalid
 */
public static ComparableVersion getPluginVersion(File pluginFile, PluginDescriptor descriptor)
        throws Exception {

    if (descriptor == null) {
        descriptor = loadPluginDescriptorFromUrl(pluginFile.toURI().toURL());
    }

    String version = descriptor.getVersion();
    if (version == null) {
        Manifest manifest = getManifest(pluginFile);
        if (manifest != null) {
            version = manifest.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
        }
    }

    if (version == null) {
        throw new Exception("No version is defined for plugin jar [" + pluginFile
                + "]. A version must be defined either via the MANIFEST.MF ["
                + Attributes.Name.IMPLEMENTATION_VERSION
                + "] attribute or via the plugin descriptor 'version' attribute.");
    }

    try {
        return new ComparableVersion(version);
    } catch (RuntimeException e) {
        throw new Exception("Version [" + version + "] for [" + pluginFile + "] did not parse", e);
    }
}

From source file:org.orbisgis.core.plugin.BundleTools.java

/**
 * Parse a Manifest in order to extract Exported Package
 * @param manifest/*from ww w  .j  av a  2  s. c om*/
 * @param packages
 * @throws IOException
 */
public static BundleReference parseManifest(Manifest manifest, List<PackageDeclaration> packages)
        throws IOException {
    Attributes attributes = manifest.getMainAttributes();
    String exports = attributes.getValue(Constants.EXPORT_PACKAGE);
    String versionProperty = attributes.getValue(Constants.BUNDLE_VERSION_ATTRIBUTE);
    Version version = null;
    if (versionProperty != null) {
        version = new Version(versionProperty);
    }
    String symbolicName = attributes.getValue(Constants.BUNDLE_SYMBOLICNAME);
    org.apache.felix.framework.Logger logger = new org.apache.felix.framework.Logger();
    // Use Apache Felix to parse the Manifest Export header
    List<BundleCapability> exportsCapability = ManifestParser.parseExportHeader(logger, null, exports, "0",
            new Version(0, 0, 0));
    for (BundleCapability bc : exportsCapability) {
        Map<String, Object> attr = bc.getAttributes();
        // If the package contain a package name and a package version
        if (attr.containsKey(PACKAGE_NAMESPACE)) {
            Version packageVersion = new Version(0, 0, 0);
            if (attr.containsKey(Constants.VERSION_ATTRIBUTE)) {
                packageVersion = (Version) attr.get(Constants.VERSION_ATTRIBUTE);
            }
            if (packageVersion.getMajor() != 0 || packageVersion.getMinor() != 0
                    || packageVersion.getMicro() != 0) {
                packages.add(new PackageDeclaration((String) attr.get(PACKAGE_NAMESPACE), packageVersion));
            } else {
                // No version, take the bundle version
                packages.add(new PackageDeclaration((String) attr.get(PACKAGE_NAMESPACE), version));
            }
        }
    }
    return new BundleReference(symbolicName, version);
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/**
 * Write a .SF file with a digest the specified manifest.
 *///from   www . j av  a2s. c o m
private static byte[] writeSignatureFile(Manifest manifest, OutputStream out)
        throws IOException, GeneralSecurityException {
    final Manifest sf = new Manifest();
    final Attributes main = sf.getMainAttributes();
    main.putValue("Manifest-Version", MANIFEST_VERSION);
    main.putValue("Created-By", CREATED_BY);

    final MessageDigest md = MessageDigest.getInstance("SHA1");
    final PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true,
            "UTF-8");

    // Digest of the entire manifest
    manifest.write(print);
    print.flush();
    main.putValue("SHA1-Digest-Manifest", base64encode(md.digest()));

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

        final Attributes sfAttr = new Attributes();
        sfAttr.putValue("SHA1-Digest", base64encode(md.digest()));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }

    final ByteArrayOutputStream sos = new ByteArrayOutputStream();
    sf.write(sos);

    String value = sos.toString();
    String done = value.replace("Manifest-Version", "Signature-Version");

    out.write(done.getBytes());

    print.close();
    sos.close();

    return done.getBytes();
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/** Add the SHA1 of every file to the manifest, creating it if necessary. */
private static Manifest addDigestsToManifest(final JarFile jar) throws IOException, GeneralSecurityException {
    final Manifest input = jar.getManifest();
    final Manifest output = new Manifest();

    final Attributes main = output.getMainAttributes();
    main.putValue("Manifest-Version", MANIFEST_VERSION);
    main.putValue("Created-By", CREATED_BY);

    // We sort the input entries by name, and add them to the output manifest in sorted order.
    // We expect that the output map will be deterministic.
    final TreeMap<String, JarEntry> byName = new TreeMap<>();
    for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
        JarEntry entry = e.nextElement();
        byName.put(entry.getName(), entry);
    }/*from   w  w  w. j a  v a 2s  .  com*/

    final MessageDigest md = MessageDigest.getInstance("SHA1");
    final byte[] buffer = new byte[4096];
    int num;

    for (JarEntry entry : byName.values()) {
        final String name = entry.getName();
        if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME)
                && !name.equals(CERT_RSA_NAME)) {
            InputStream data = jar.getInputStream(entry);
            while ((num = data.read(buffer)) > 0) {
                md.update(buffer, 0, num);
            }

            Attributes attr = null;
            if (input != null) {
                attr = input.getAttributes(name);
            }
            attr = attr != null ? new Attributes(attr) : new Attributes();
            attr.putValue("SHA1-Digest", base64encode(md.digest()));
            output.getEntries().put(name, attr);
        }
    }

    return output;
}