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.equinox.servletbridge.FrameworkLauncher.java

/**
 * deployExtensionBundle will generate the Servletbridge extensionbundle if it is not already present in the platform's
 * plugin directory. By default it exports "org.eclipse.equinox.servletbridge" and a versioned export of the Servlet API.
 * Additional exports can be added by using the "extendedFrameworkExports" initial-param in the ServletConfig
 *///from  w ww. j  a v a2 s.  c o m
private void deployExtensionBundle(File plugins) {
    File extensionBundle = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0.jar"); //$NON-NLS-1$
    File extensionBundleDir = new File(plugins, "org.eclipse.equinox.servletbridge.extensionbundle_1.0.0"); //$NON-NLS-1$
    if (Boolean.valueOf(config.getInitParameter(CONFIG_OVERRIDE_AND_REPLACE_EXTENSION_BUNDLE)).booleanValue()) {
        extensionBundle.delete();
        deleteDirectory(extensionBundleDir);
    } else if (extensionBundle.exists() || extensionBundleDir.isDirectory())
        return;

    Manifest mf = new Manifest();
    Attributes attribs = mf.getMainAttributes();
    attribs.putValue(MANIFEST_VERSION, "1.0"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_MANIFEST_VERSION, "2"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_NAME, "Servletbridge Extension Bundle"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_SYMBOLIC_NAME, "org.eclipse.equinox.servletbridge.extensionbundle"); //$NON-NLS-1$
    attribs.putValue(BUNDLE_VERSION, "1.0.0"); //$NON-NLS-1$
    attribs.putValue(FRAGMENT_HOST, "system.bundle; extension:=framework"); //$NON-NLS-1$

    String servletVersion = context.getMajorVersion() + "." + context.getMinorVersion(); //$NON-NLS-1$
    String packageExports = "org.eclipse.equinox.servletbridge; version=1.0" + //$NON-NLS-1$
            ", javax.servlet; version=" + servletVersion + //$NON-NLS-1$
            ", javax.servlet.http; version=" + servletVersion + //$NON-NLS-1$
            ", javax.servlet.resources; version=" + servletVersion; //$NON-NLS-1$

    String extendedExports = config.getInitParameter(CONFIG_EXTENDED_FRAMEWORK_EXPORTS);
    if (extendedExports != null && extendedExports.trim().length() != 0)
        packageExports += ", " + extendedExports; //$NON-NLS-1$

    attribs.putValue(EXPORT_PACKAGE, packageExports);

    try {
        JarOutputStream jos = null;
        try {
            jos = new JarOutputStream(new FileOutputStream(extensionBundle), mf);
            jos.finish();
        } finally {
            if (jos != null)
                jos.close();
        }
    } catch (IOException e) {
        context.log("Error generating extension bundle", e); //$NON-NLS-1$
    }
}

From source file:org.eclipse.ebr.maven.BundleMojo.java

private String getL10nResolvedValue(final Manifest manifest, final String manifestHeaderKey,
        final Properties l10nProps) {
    final String value = manifest.getMainAttributes().getValue(manifestHeaderKey);
    if ((value == null) || !value.startsWith(I18N_KEY_PREFIX))
        return value;
    if (l10nProps == null)
        return null;
    final String key = value.substring(1).trim();
    return l10nProps.getProperty(key);
}

From source file:org.syncany.operations.plugin.PluginOperation.java

private PluginInfo readPluginInfoFromJar(File pluginJarFile) throws Exception {
    try (JarInputStream jarStream = new JarInputStream(new FileInputStream(pluginJarFile))) {
        Manifest jarManifest = jarStream.getManifest();

        if (jarManifest == null) {
            throw new Exception(
                    "Given file is not a valid Syncany plugin file (not a JAR file, or no manifest).");
        }/*from w w w . j  a  v  a  2 s  .c o m*/

        String pluginId = jarManifest.getMainAttributes().getValue("Plugin-Id");

        if (pluginId == null) {
            throw new Exception("Given file is not a valid Syncany plugin file (no plugin ID in manifest).");
        }

        PluginInfo pluginInfo = new PluginInfo();

        pluginInfo.setPluginId(pluginId);
        pluginInfo.setPluginName(jarManifest.getMainAttributes().getValue("Plugin-Name"));
        pluginInfo.setPluginVersion(jarManifest.getMainAttributes().getValue("Plugin-Version"));
        pluginInfo.setPluginDate(jarManifest.getMainAttributes().getValue("Plugin-Date"));
        pluginInfo.setPluginAppMinVersion(jarManifest.getMainAttributes().getValue("Plugin-App-Min-Version"));
        pluginInfo.setPluginRelease(
                Boolean.parseBoolean(jarManifest.getMainAttributes().getValue("Plugin-Release")));

        if (jarManifest.getMainAttributes().getValue("Plugin-Conflicts-With") != null) {
            pluginInfo.setConflictingPluginIds(
                    Arrays.asList(jarManifest.getMainAttributes().getValue("Plugin-Conflicts-With")));
        }

        return pluginInfo;
    }
}

From source file:org.universAAL.itests.IntegrationTest.java

/**
 * This method copies contents of target/classes to target/test-classes.
 * Thanks to that regular classes of given bundle can be used for testing
 * without a need to load the bundle from maven repository. It is very
 * important because in the maven build cycle "test" precedes "install". If
 * this method will not be invoked, when bundle does not exist in the maven
 * repository there is a deadlock - bundle cannot be tested because it is
 * not in the repo and bundle cannot be installed in the repo because tests
 * fail./* w w w  .ja  v a 2s . c o  m*/
 *
 * Additionally method rewrites bundle manifest for purpose of adding
 * imports to packages related to itests bundle.
 *
 * @throws IOException
 *
 */
private void prepareClassesToTests() throws Exception {
    FileUtils.copyDirectory(new File("./target/classes"), new File("./target/test-classes"));
    File separatedArtifactDepsFile = new File(IntegrationTestConsts.SEPARATED_ARTIFACT_DEPS);
    if (separatedArtifactDepsFile.exists()) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(separatedArtifactDepsFile)));
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (!line.isEmpty()) {
                unzipInpuStream(new URL(line).openStream(), "target/test-classes");
            }
        }
    }

    Manifest bundleMf = new Manifest(new FileInputStream("./target/classes/META-INF/MANIFEST.MF"));
    Attributes mainAttribs = bundleMf.getMainAttributes();

    bundleSymbolicName = mainAttribs.getValue("Bundle-SymbolicName");
    bundleVersion = mainAttribs.getValue("Bundle-Version");
    bundleVersion = bundleVersion.replaceFirst("\\.SNAPSHOT", "-SNAPSHOT");

    mainAttribs.put(new Attributes.Name("Import-Package"),
            mainAttribs.getValue("Import-Package") + ",org.universAAL.itests,org.springframework.util");
    String dynamicImports = mainAttribs.getValue("DynamicImport-Package");
    if (dynamicImports == null) {
        dynamicImports = "*";
        mainAttribs.put(new Attributes.Name("DynamicImport-Package"), dynamicImports);
    }

    bundleMf.write(new FileOutputStream("./target/test-classes/META-INF/MANIFEST.MF"));
}

From source file:org.ops4j.pax.runner.platform.internal.PlatformImpl.java

/**
 * Validate that the file is an valid bundle.
 * A valid bundle will be a loadable jar file that has manifest and the manifest contains at least an entry for
 * Bundle-SymboliName or Bundle-Name (R3).
 *
 * @param url  original url from where the bundle was created.
 * @param file file to be validated/*from  w ww  .  jav  a 2  s .co m*/
 *
 * @throws PlatformException if the jar is not a valid bundle
 */
void validateBundle(final URL url, final File file) throws PlatformException {
    String bundleSymbolicName = null;
    String bundleName = null;
    JarFile jar = null;
    try {
        // verify that is a valid jar. Do not verify that is signed (the false param).
        jar = new JarFile(file, false);
        final Manifest manifest = jar.getManifest();
        if (manifest == null) {
            throw new PlatformException("[" + url + "] is not a valid bundle");
        }
        bundleSymbolicName = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
        bundleName = manifest.getMainAttributes().getValue(Constants.BUNDLE_NAME);
    } catch (IOException e) {
        throw new PlatformException("[" + url + "] is not a valid bundle", e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException ignore) {
                // just ignore as this is less probably to happen.
            }
        }
    }
    if (bundleSymbolicName == null && bundleName == null) {
        throw new PlatformException("[" + url + "] is not a valid bundle");
    }
}

From source file:massbank.admin.VersionManager.java

/**
 * jart@Co?[W?/*from  www. ja  v a 2  s  . c o  m*/
 * @param path t@CpX
 * @return o?[W?
 */
private VersionInfo getVerJarFile(String path) {
    VersionInfo verInfo = null;
    try {
        // }jtFXgo?[W?
        JarFile jar = new JarFile(new File(path));
        Manifest manifest = jar.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        String item1 = attributes.getValue("Implementation-Version");
        if (item1 == null) {
            item1 = "-";
        }
        // Xy?[X?o?[Wt?o
        String[] item2 = item1.trim().split(" ");
        String ver = item2[0];
        String date = "-";
        if (item2.length > 1) {
            date = item2[1];
        }
        verInfo = new VersionInfo(null, ver, date);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return verInfo;
}

From source file:uk.ac.ebi.embl.api.validation.EnaValidator.java

private String getImplementationVersion(Manifest manifest) {

    Attributes attributes = manifest.getMainAttributes();
    return attributes.getValue("Implementation-Version");
}

From source file:org.jahia.utils.maven.plugin.osgi.BuildFrameworkPackageListMojo.java

private void scanExistingManifest(Map<String, Map<String, Map<String, VersionLocation>>> packageVersionCounts)
        throws IOException, Exception {
    FileInputStream in = null;/*w w w .  java2 s  .co  m*/
    try {
        if (inputManifestFile.exists()) {
            in = new FileInputStream(inputManifestFile);
            Manifest mf = new Manifest(in);
            String exportPackageStr = mf.getMainAttributes().getValue("Export-Package");
            String bundleVersion = mf.getMainAttributes().getValue("Bundle-Version");
            ManifestElement[] manifestElements = ManifestElement.parseHeader("Export-Package",
                    exportPackageStr);
            if (manifestElements != null) {
                for (ManifestElement manifestElement : manifestElements) {
                    String[] packageNames = manifestElement.getValueComponents();
                    String version = manifestElement.getAttribute("version");
                    if (version != null) {
                        for (String packageName : packageNames) {
                            if (version.equals(bundleVersion)) {
                                if (packageName.startsWith("org.jahia")) {
                                    updateVersionLocationCounts(packageVersionCounts,
                                            inputManifestFile.toString(), version, bundleVersion, packageName);
                                } else {
                                    updateVersionLocationCounts(packageVersionCounts,
                                            inputManifestFile.toString(), null, bundleVersion, packageName);
                                }
                            } else {
                                updateVersionLocationCounts(packageVersionCounts, inputManifestFile.toString(),
                                        version, bundleVersion, packageName);
                            }
                        }
                    } else {
                        for (String packageName : packageNames) {
                            updateVersionLocationCounts(packageVersionCounts, inputManifestFile.toString(),
                                    null, bundleVersion, packageName);
                        }
                    }
                }
                getLog().info("Found " + manifestElements.length + " package exports.");
            }
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java

/**
 * Add configurations to a running OSGi instance for initial content.
 * @param targetURL The web console base url
 * @param file The artifact (bundle)/*w  w w  . ja  v a 2  s .  co m*/
 * @throws MojoExecutionException
 */
protected void configure(String targetURL, File file) throws MojoExecutionException {
    // first, let's get the manifest and see if initial content is configured
    ManifestHeader header = null;
    try {
        final Manifest mf = this.getManifest(file);
        final String value = mf.getMainAttributes().getValue(HEADER_INITIAL_CONTENT);
        if (value == null) {
            getLog().debug("Bundle has no initial content - no file system provider config created.");
            return;
        }
        header = ManifestHeader.parse(value);
        if (header == null || header.getEntries().length == 0) {
            getLog().warn("Unable to parse header or header is empty: " + value);
            return;
        }
    } catch (IOException ioe) {
        throw new MojoExecutionException("Unable to read manifest from file " + file, ioe);
    }
    // setup http client
    final HttpClient client = getHttpClient();

    getLog().info("Trying to configure file system provider...");
    // quick check if resources are configured
    final List resources = project.getResources();
    if (resources == null || resources.size() == 0) {
        throw new MojoExecutionException("No resources configured for this project.");
    }
    // now get current configurations
    final Map oldConfigs = this.getCurrentFileProviderConfigs(targetURL, client);

    final Entry[] entries = header.getEntries();
    for (final Entry entry : entries) {
        String path = entry.getValue();
        if (path != null && !path.endsWith("/")) {
            path += "/";
        }
        // check if we should ignore this
        final String ignoreValue = entry.getDirectiveValue("maven:mount");
        if (ignoreValue != null && ignoreValue.equalsIgnoreCase("false")) {
            getLog().debug("Ignoring " + path);
            continue;
        }
        String installPath = entry.getDirectiveValue("path");
        if (installPath == null) {
            installPath = "/";
        }
        // search the path in the resources (usually this should be the first resource
        // entry but this might be reconfigured
        File dir = null;
        final Iterator i = resources.iterator();
        while (dir == null && i.hasNext()) {
            final Resource rsrc = (Resource) i.next();
            String child = path;
            // if resource mapping defines a target path: remove target path from checked resource path
            String targetPath = rsrc.getTargetPath();
            if (targetPath != null && !targetPath.endsWith("/")) {
                targetPath = targetPath + "/";
            }
            if (targetPath != null && path.startsWith(targetPath)) {
                child = child.substring(targetPath.length());
            }
            dir = new File(rsrc.getDirectory(), child);
            if (!dir.exists()) {
                dir = null;
            }
        }
        if (dir == null) {
            throw new MojoExecutionException("No resource entry found containing " + path);
        }
        // check for root mapping - which we don't support atm
        if ("/".equals(installPath)) {
            throw new MojoExecutionException(
                    "Mapping to root path not supported by fs provider at the moment. Please adapt your initial content configuration.");
        }
        getLog().info("Mapping " + dir + " to " + installPath);

        // check if this is already configured
        boolean found = false;
        final Iterator entryIterator = oldConfigs.entrySet().iterator();
        while (!found && entryIterator.hasNext()) {
            final Map.Entry current = (Map.Entry) entryIterator.next();
            final String[] value = (String[]) current.getValue();
            getLog().debug("Comparing " + dir.getAbsolutePath() + " with " + value[0] + " (" + value[1] + ")");
            if (dir.getAbsolutePath().equals(value[0])) {
                if (installPath.equals(value[1])) {
                    getLog().debug("Using existing configuration for " + dir + " and " + installPath);
                    found = true;
                } else {
                    // remove old config
                    getLog().debug("Removing old configuration for " + value[0] + " and " + value[1]);
                    removeConfiguration(client, targetURL, current.getKey().toString());
                }
                entryIterator.remove();
            }
        }
        if (!found) {
            getLog().debug("Adding new configuration for " + dir + " and " + installPath);
            addConfiguration(client, targetURL, dir.getAbsolutePath(), installPath);
        }
    }
    // finally remove old configs
    final Iterator entryIterator = oldConfigs.entrySet().iterator();
    while (entryIterator.hasNext()) {
        final Map.Entry current = (Map.Entry) entryIterator.next();
        final String[] value = (String[]) current.getValue();
        getLog().debug("Removing old configuration for " + value[0] + " and " + value[1]);
        // remove old config
        removeConfiguration(client, targetURL, current.getKey().toString());
    }
}

From source file:org.eclipse.ebr.maven.BundleMojo.java

private File generateFinalBundleManifest() throws MojoExecutionException {
    try {/*  w ww .jav  a  2 s . c o  m*/
        File mfile = new File(outputDirectory, "META-INF/MANIFEST.MF");
        final InputStream is = new FileInputStream(mfile);
        Manifest mf;
        try {
            mf = new Manifest(is);
        } finally {
            is.close();
        }
        final Attributes attributes = mf.getMainAttributes();

        if (attributes.getValue(Name.MANIFEST_VERSION) == null) {
            attributes.put(Name.MANIFEST_VERSION, "1.0");
        }

        // shameless self-promotion
        attributes.putValue(CREATED_BY, "Eclipse Bundle Recipe Maven Plug-in");

        final String expandedVersion = getExpandedVersion();
        attributes.putValue(BUNDLE_VERSION, expandedVersion);

        mfile = getFinalBundleManifestFile();
        mfile.getParentFile().mkdirs();
        final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(mfile));
        try {
            mf.write(os);
        } finally {
            os.close();
        }

        return mfile;
    } catch (final Exception e) {
        throw new MojoExecutionException("Error generating bundle manifest: " + e.getMessage(), e);
    }
}