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:org.eclipse.emf.mwe.utils.StandaloneSetup.java

protected String getBundleNameFromManifest(JarFile jarFile) throws IOException {
    Manifest manifest = jarFile.getManifest();
    if (manifest != null) {
        return manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    }//  ww w. j  a v  a  2  s  . com
    return null;
}

From source file:com.datatorrent.stram.client.AppPackage.java

/**
 * Creates an App Package object./*from w w w.  j  a  v a2 s .  c  o m*/
 *
 * If app directory is to be processed, there may be resource leak in the class loader. Only pass true for short-lived
 * applications
 *
 * If contentFolder is not null, it will try to create the contentFolder, file will be retained on disk after App Package is closed
 * If contentFolder is null, temp folder will be created and will be cleaned on close()
 *
 * @param file
 * @param contentFolder  the folder that the app package will be extracted to
 * @param processAppDirectory
 * @throws java.io.IOException
 * @throws net.lingala.zip4j.exception.ZipException
 */
public AppPackage(File file, File contentFolder, boolean processAppDirectory) throws IOException, ZipException {
    super(file);

    if (contentFolder != null) {
        FileUtils.forceMkdir(contentFolder);
        cleanOnClose = false;
    } else {
        cleanOnClose = true;
        contentFolder = Files.createTempDirectory("dt-appPackage-").toFile();
    }
    directory = contentFolder;

    Manifest manifest = getManifest();
    if (manifest == null) {
        throw new IOException("Not a valid app package. MANIFEST.MF is not present.");
    }
    Attributes attr = manifest.getMainAttributes();
    appPackageName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_NAME);
    appPackageVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_VERSION);
    appPackageGroupId = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_GROUP_ID);
    dtEngineVersion = attr.getValue(ATTRIBUTE_DT_ENGINE_VERSION);
    appPackageDisplayName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_DISPLAY_NAME);
    appPackageDescription = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_DESCRIPTION);
    String classPathString = attr.getValue(ATTRIBUTE_CLASS_PATH);
    if (appPackageName == null || appPackageVersion == null || classPathString == null) {
        throw new IOException(
                "Not a valid app package.  App Package Name or Version or Class-Path is missing from MANIFEST.MF");
    }
    classPath.addAll(Arrays.asList(StringUtils.split(classPathString, " ")));
    extractToDirectory(directory, file);
    if (processAppDirectory) {
        processAppDirectory(new File(directory, "app"));
    }
    File confDirectory = new File(directory, "conf");
    if (confDirectory.exists()) {
        processConfDirectory(confDirectory);
    }
    resourcesDirectory = new File(directory, "resources");

    File propertiesXml = new File(directory, "META-INF/properties.xml");
    if (propertiesXml.exists()) {
        processPropertiesXml(propertiesXml, null);
    }

    if (processAppDirectory) {
        for (AppInfo app : applications) {
            app.requiredProperties.addAll(requiredProperties);
            app.defaultProperties.putAll(defaultProperties);
            File appPropertiesXml = new File(directory, "META-INF/properties-" + app.name + ".xml");
            if (appPropertiesXml.exists()) {
                processPropertiesXml(appPropertiesXml, app);
            }
        }
    }
}

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

/**
 * @param scanJarsAtDir//from  w ww.j a  va2  s  .co m
 * @return A Map(featureId -> featureVersion)
 */
public Map<String, String> scanFeatureVersionsAtDir(final String scanJarsAtDir) {
    final Map<String, String> featureVersions = new LinkedHashMap<String, String>();

    final File file = new File(scanJarsAtDir);
    if (!file.exists() || !file.isDirectory()) {
        log.error("Directory '" + file.getAbsolutePath() + "' does not exists.");
        return featureVersions;
    }

    for (final File jar : file.listFiles()) {
        if (jar.isFile() && jar.getName().toLowerCase().endsWith(".jar")) {
            try {
                final JarInputStream jarStream = new JarInputStream(
                        new BufferedInputStream(new FileInputStream(jar)));
                final Manifest manifest = jarStream.getManifest();
                final String featureId = manifest.getMainAttributes().getValue("FeatureBuilder-FeatureId");
                final String featureVersion = manifest.getMainAttributes()
                        .getValue("FeatureBuilder-FeatureVersion");

                if (featureId != null && featureVersion != null) {
                    featureVersions.put(featureId, featureVersion);
                }

            } catch (final FileNotFoundException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            } catch (final IOException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            }
        }
    }
    return featureVersions;
}

From source file:org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor.java

protected void processManifest(FragmentDescriptor fd, String fileName, Manifest mf) {
    Attributes attrs = mf.getMainAttributes();
    String id = attrs.getValue("Bundle-SymbolicName");
    if (id != null) {
        int p = id.indexOf(';');
        if (p > -1) { // remove properties part if any
            id = id.substring(0, p);/*from w  w  w  .j  a  v  a2s . c  o m*/
        }
        jar2Id.put(fileName, id);
        fd.name = id;
        if (fd.requires != null && !fd.requires.isEmpty()) {
            throw new RuntimeException(
                    "In compatibility mode you must not use <require> tags for OSGi bundles - use Require-Bundle manifest header instead. Bundle: "
                            + fileName);
        }
        // needed to control start-up order (which differs from
        // Require-Bundle)
        String requires = attrs.getValue("Nuxeo-Require");
        if (requires == null) { // if not specific requirement is met use
                                // Require-Bundle
            requires = attrs.getValue("Require-Bundle");
        }
        if (requires != null) {
            String[] ids = StringUtils.split(requires, ',', true);
            fd.requires = new ArrayList<String>(ids.length);
            for (int i = 0; i < ids.length; i++) {
                String rid = ids[i];
                p = rid.indexOf(';');
                if (p > -1) { // remove properties part if any
                    ids[i] = rid.substring(0, p);
                }
                fd.requires.add(ids[i]);
            }
        }

        String requiredBy = attrs.getValue("Nuxeo-RequiredBy");
        if (requiredBy != null) {
            String[] ids = StringUtils.split(requiredBy, ',', true);
            for (int i = 0; i < ids.length; i++) {
                String rid = ids[i];
                p = rid.indexOf(';');
                if (p > -1) { // remove properties part if any
                    ids[i] = rid.substring(0, p);
                }
            }
            fd.requiredBy = ids;
        }

    } else {
        jar2Id.put(fileName, fd.name);
    }
}

From source file:com.github.lindenb.jvarkit.util.command.Command.java

private void loadManifest() {
    try {/*from   w  w w  . java2  s .  c om*/
        Enumeration<URL> resources = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");//not '/META-INF'
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            InputStream in = url.openStream();
            if (in == null) {
                continue;
            }

            Manifest m = new Manifest(in);
            in.close();
            in = null;
            java.util.jar.Attributes attrs = m.getMainAttributes();
            if (attrs == null) {
                continue;
            }
            String s = attrs.getValue("Git-Hash");
            if (s != null && !s.isEmpty() && !s.contains("$")) //ant failed
            {
                this.gitHash = s;
            }

            s = attrs.getValue("Compile-Date");
            if (s != null && !s.isEmpty()) //ant failed
            {
                this.compileDate = s;
            }
        }
    } catch (Exception err) {

    }

}

From source file:de.tobiasroeser.maven.featurebuilder.FeatureBuilder.java

public List<Bundle> scanBundlesAtDir(final String scanJarsAtDir) {
    final File file = new File(scanJarsAtDir);

    final LinkedList<Bundle> bundles = new LinkedList<Bundle>();

    if (!file.exists() || !file.isDirectory()) {
        log.error("Directory '" + file.getAbsolutePath() + "' does not exists.");
        return bundles;
    }/*from   w ww .  java2 s .  c om*/

    for (final File jar : file.listFiles()) {
        if (jar.isFile() && jar.getName().toLowerCase().endsWith(".jar")) {
            try {
                final JarInputStream jarStream = new JarInputStream(
                        new BufferedInputStream(new FileInputStream(jar)));
                final Manifest manifest = jarStream.getManifest();
                String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
                final String version = manifest.getMainAttributes().getValue("Bundle-Version");
                if (symbolicName != null && version != null) {
                    symbolicName = symbolicName.split(";")[0].trim();
                    final Bundle bundle = new Bundle(symbolicName, version, jar.length(), jar);
                    bundles.add(bundle);
                } else {
                    log.warn("jar '" + jar.getAbsolutePath() + "' is not an OSGi bundle.");
                }

            } catch (final FileNotFoundException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            } catch (final IOException e) {
                log.error("Errors while reading the Mainfest of: " + jar, e);
            }

        }
    }
    log.info("Found " + bundles.size() + " bundles in scanned directory: " + file.getAbsolutePath());

    Collections.sort(bundles);
    return bundles;
}

From source file:com.github.sampov2.OneJarMojo.java

private Manifest prepareManifest() throws IOException {
    // Copy the template's boot-manifest.mf file
    ZipInputStream zipIS = openOnejarTemplateArchive();
    Manifest manifest = new Manifest(getFileBytes(zipIS, "boot-manifest.mf"));
    IOUtils.closeQuietly(zipIS);/*from  w  ww .  j  a  v a2  s .c  o  m*/

    Attributes mainAttributes = manifest.getMainAttributes();
    // first add the custom specified entries
    addExplicitManifestEntries(mainAttributes);

    // If the client has specified an implementationVersion argument, add it also
    // (It's required and defaulted, so this always executes...)
    //
    // TODO: The format of this manifest entry is not "hard and fast".  Some specs call for "implementationVersion",
    // some for "implemenation-version", and others use various capitalizations of these two.  It's likely that a
    // better solution then this "brute-force" bit here is to allow clients to configure these entries from the
    // Maven POM.
    setRequired(mainAttributes, new AttributeEntry(MF_REQUIRED_IMPL_VERSION, implementationVersion),
            MF_REQUIRED_IMPL_VERSION);

    // If the client has specified a splashScreen argument, add the proper entry to the manifest
    setOptional(splashScreen, mainAttributes, new AttributeEntry(MF_OPTION_SPLASH_SCREEN_IMAGE, splashScreen),
            MF_OPTION_SPLASH_SCREEN_IMAGE);

    // If the client has specified a mainClass argument, add the proper entry to the manifest
    // to be backwards compatible, add mainclass as simple option when not already set in manifestEntries
    setOptional(mainClass, mainAttributes, new AttributeEntry(MF_OPTION_MAIN_CLASS, mainClass),
            MF_OPTION_MAIN_CLASS);

    return manifest;
}

From source file:org.eu.gasp.core.internal.DefaultPluginRegistry.java

private void registerPlugin(File file) throws Exception {
    if (isFileRegistered(file)) {
        return;/*from  ww  w .  j  a v  a  2  s . co  m*/
    }

    final JarFile jarFile = new JarFile(file);
    final Manifest manifest = jarFile.getManifest();

    String pluginId = null;
    String pluginClassName = null;
    Version version = null;
    final List<DefaultPluginDependency> pluginDependencies = new ArrayList<DefaultPluginDependency>();
    final List<String> services = new ArrayList<String>();

    final Attributes attrs = manifest.getMainAttributes();
    for (final Map.Entry entry : attrs.entrySet()) {
        final String key = entry.getKey().toString();
        final String value = StringUtils.trimToNull(entry.getValue().toString());

        if (value == null) {
            continue;
        }

        if (JAR_PLUGIN.equals(key)) {
            pluginId = value;
        } else if (JAR_PLUGIN_CLASS.equals(key)) {
            pluginClassName = value;
        } else if (JAR_PLUGIN_VERSION.equals(key)) {
            version = new Version(value);
        } else if (JAR_PLUGIN_PROVIDES.equals(key)) {
            for (final String service : value.split(",")) {
                services.add(service);
            }
        } else if (JAR_PLUGIN_REQUIRES.equals(key)) {
            for (final String versionnedRequiredPluginId : value.split(",")) {
                pluginDependencies.add(new DefaultPluginDependency(versionnedRequiredPluginId, null));
            }
        }
    }

    if (StringUtils.isBlank(pluginId)) {
        throw new IllegalStateException("Missing " + JAR_PLUGIN + " attribute in manifest");
    }
    if (version == null) {
        throw new IllegalStateException("Missing " + JAR_PLUGIN_VERSION + " attribute in manifest");
    }

    final PluginDescriptor pluginDescriptor = new DefaultPluginDescriptor(pluginId, version, pluginClassName,
            pluginDependencies, services);
    if (!plugins.containsKey(pluginDescriptor)) {
        log.info("Registering plugin: " + pluginDescriptor);
        plugins.put(pluginDescriptor, new PluginData(file));
    }
}

From source file:org.nuxeo.runtime.deployment.preprocessor.DeploymentPreprocessor.java

protected String getSymbolicName(File file) {
    Manifest mf = JarUtils.getManifest(file);
    if (mf != null) {
        Attributes attrs = mf.getMainAttributes();
        String id = attrs.getValue("Bundle-SymbolicName");
        if (id != null) {
            int p = id.indexOf(';');
            if (p > -1) { // remove properties part if any
                id = id.substring(0, p);
            }//  w ww .ja  va2 s  .c  o m
            return id;
        }
    }
    return null;
}

From source file:org.talend.core.ui.metadata.celleditor.ModuleListDialog.java

private void addListeners() {
    innerBtn.addSelectionListener(new SelectionAdapter() {

        @Override//from w w  w  .j a v a  2  s .c  o  m
        public void widgetSelected(SelectionEvent e) {
            checkField(true);
        }

    });
    extBtn.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            checkField(false);
        }

    });
    jarsViewer.addSelectionChangedListener(new ISelectionChangedListener() {

        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            if (jarsViewer.getList().getSelection().length <= 0) {
                getOKButton().setEnabled(false);
            } else {
                getOKButton().setEnabled(true);
            }
            selecteModuleArray = jarsViewer.getList().getSelection();
        }
    });
    selectField.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            if (selectField.getText().trim().length() <= 0) {
                getOKButton().setEnabled(false);
            } else {
                String version = "0.0.1-SNAPSHOT";

                try {

                    Manifest manifest = new JarFile(selectField.getText()).getManifest();
                    Attributes mainAttribs = manifest.getMainAttributes();

                    if (StringUtils.isNotBlank(mainAttribs.getValue("Bundle-Version"))) {
                        version = mainAttribs.getValue("Bundle-Version");
                    } else if (StringUtils.isNotBlank(mainAttribs.getValue("Implementation-Version"))) {
                        version = mainAttribs.getValue("Implementation-Version");
                    }
                } catch (Exception eee) {

                }

                if (versionLabel != null) {
                    versionLabel.setText(version);
                }

                getOKButton().setEnabled(true);
            }
        }
    });

    addBtn.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            FileDialog dialog = new FileDialog(getShell());
            dialog.setFilterExtensions(new String[] { "*.jar", "*.zip", "*.*", "*" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
            String userDir = System.getProperty("user.dir"); //$NON-NLS-1$
            String pathSeparator = System.getProperty("file.separator"); //$NON-NLS-1$
            dialog.setFilterPath(userDir + pathSeparator + "lib" + pathSeparator + "java"); //$NON-NLS-1$ //$NON-NLS-2$
            String path = dialog.open();
            if (path == null) {
                return;
            }
            if (!jarsList.contains(path)) {
                jarsList.add(path);
                jarsViewer.setInput(jarsList);
            } else {
                MessageDialog.openWarning(getShell(), Messages.getString("ModuleListCellEditor.warningTitle"), //$NON-NLS-1$
                        Messages.getString("ModuleListCellEditor.warningMessage")); //$NON-NLS-1$
            }
            if (jarsList.size() > 0) {
                getOKButton().setEnabled(true);
            } else {
                getOKButton().setEnabled(false);
            }
        }

    });

    delBtn.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            for (Object o : ((StructuredSelection) jarsViewer.getSelection()).toList()) {
                jarsList.remove(o);
            }
            jarsViewer.setInput(jarsList);

            if (jarsList.size() > 0) {
                getOKButton().setEnabled(true);
            } else {
                getOKButton().setEnabled(false);
            }
        }
    });
}