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:ca.weblite.jdeploy.JDeploy.java

private String[] findClassPath(File jarFile) throws IOException {
    Manifest m = new JarFile(jarFile).getManifest();
    //System.out.println(m.getEntries());
    String cp = m.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
    //System.out.println("Class path is "+cp);
    if (cp != null) {
        return cp.split(" ");
    } else {/*w ww .  j a va  2 s . co  m*/
        return new String[0];
    }
}

From source file:org.jvnet.hudson.test.HudsonTestCase.java

/**
 * If this test harness is launched for a Hudson plugin, locate the <tt>target/test-classes/the.hpl</tt>
 * and add a recipe to install that to the new Hudson.
 *
 * <p>/*from w  w w  . ja v a  2s  .  c o m*/
 * This file is created by <tt>maven-hpi-plugin</tt> at the testCompile phase when the current
 * packaging is <tt>hpi</tt>.
 */
protected void recipeLoadCurrentPlugin() throws Exception {
    Enumeration<URL> e = getClass().getClassLoader().getResources("the.hpl");
    if (!e.hasMoreElements())
        return; // nope

    final URL hpl = e.nextElement();

    if (e.hasMoreElements()) {
        // this happens if one plugin produces a test jar and another plugin depends on it.
        // I can't think of a good way to make this work, so for now, just detect that and report an error.
        URL hpl2 = e.nextElement();
        throw new Error("We have both " + hpl + " and " + hpl2);
    }

    recipes.add(new Runner() {
        @Override
        public void decorateHome(HudsonTestCase testCase, File home) throws Exception {
            // make the plugin itself available
            Manifest m = new Manifest(hpl.openStream());
            String shortName = m.getMainAttributes().getValue("Short-Name");
            if (shortName == null)
                throw new Error(hpl + " doesn't have the Short-Name attribute");
            FileUtils.copyURLToFile(hpl, new File(home, "plugins/" + shortName + ".hpl"));

            // make dependency plugins available
            // TODO: probably better to read POM, but where to read from?
            // TODO: this doesn't handle transitive dependencies

            // Tom: plugins are now searched on the classpath first. They should be available on
            // the compile or test classpath. As a backup, we do a best-effort lookup in the Maven repository
            // For transitive dependencies, we could evaluate Plugin-Dependencies transitively. 

            String dependencies = m.getMainAttributes().getValue("Plugin-Dependencies");
            if (dependencies != null) {
                MavenEmbedder embedder = new MavenEmbedder(null);
                embedder.setClassLoader(getClass().getClassLoader());
                embedder.start();
                for (String dep : dependencies.split(",")) {
                    String[] tokens = dep.split(":");
                    String artifactId = tokens[0];
                    String version = tokens[1];
                    File dependencyJar = null;
                    // need to search multiple group IDs
                    // TODO: extend manifest to include groupID:artifactID:version
                    Exception resolutionError = null;
                    for (String groupId : new String[] { "org.jvnet.hudson.plugins",
                            "org.jvnet.hudson.main" }) {

                        // first try to find it on the classpath.
                        // this takes advantage of Maven POM located in POM
                        URL dependencyPomResource = getClass()
                                .getResource("/META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml");
                        if (dependencyPomResource != null) {
                            // found it
                            dependencyJar = Which.jarFile(dependencyPomResource);
                            break;
                        } else {
                            Artifact a;
                            a = embedder.createArtifact(groupId, artifactId, version,
                                    "compile"/*doesn't matter*/, "hpi");
                            try {
                                embedder.resolve(a,
                                        Arrays.asList(embedder.createRepository(
                                                "http://maven.glassfish.org/content/groups/public/", "repo")),
                                        embedder.getLocalRepository());
                                dependencyJar = a.getFile();
                            } catch (AbstractArtifactResolutionException x) {
                                // could be a wrong groupId
                                resolutionError = x;
                            }
                        }
                    }
                    if (dependencyJar == null)
                        throw new Exception("Failed to resolve plugin: " + dep, resolutionError);

                    File dst = new File(home, "plugins/" + artifactId + ".hpi");
                    if (!dst.exists() || dst.lastModified() != dependencyJar.lastModified()) {
                        FileUtils.copyFile(dependencyJar, dst);
                    }
                }
                embedder.stop();
            }
        }
    });
}

From source file:org.rhq.plugins.jbossas5.deploy.ManagedComponentDeployer.java

public void deploy(CreateResourceReport createResourceReport, ResourceType resourceType) {
    createResourceReport.setStatus(null);
    File archiveFile = null;//from   w ww.j av  a2s.  co  m

    try {
        ResourcePackageDetails details = createResourceReport.getPackageDetails();
        PackageDetailsKey key = details.getKey();

        archiveFile = downloader.prepareArchive(key, resourceType);

        String archiveName = key.getName();

        if (!DeploymentUtils.hasCorrectExtension(archiveName, resourceType)) {
            createResourceReport.setStatus(CreateResourceStatus.FAILURE);
            createResourceReport
                    .setErrorMessage("Incorrect extension specified on filename [" + archiveName + "]");
            return;
        }

        abortIfApplicationAlreadyDeployed(resourceType, archiveFile);

        Configuration deployTimeConfig = details.getDeploymentTimeConfiguration();
        @SuppressWarnings({ "ConstantConditions" })
        boolean deployExploded = deployTimeConfig.getSimple("deployExploded").getBooleanValue();

        DeploymentManager deploymentManager = this.profileServiceConnection.getDeploymentManager();
        boolean deployFarmed = deployTimeConfig.getSimple("deployFarmed").getBooleanValue();
        if (deployFarmed) {
            Collection<ProfileKey> profileKeys = deploymentManager.getProfiles();
            boolean farmSupported = false;
            for (ProfileKey profileKey : profileKeys) {
                if (profileKey.getName().equals(FARM_PROFILE_KEY.getName())) {
                    farmSupported = true;
                    break;
                }
            }
            if (!farmSupported) {
                throw new IllegalStateException("This application server instance is not a node in a cluster, "
                        + "so it does not support farmed deployments. Supported deployment profiles are "
                        + profileKeys + ".");
            }
            if (deployExploded) {
                throw new IllegalArgumentException(
                        "Deploying farmed applications in exploded form is not supported by the Profile Service.");
            }
            deploymentManager.loadProfile(FARM_PROFILE_KEY);
        }

        String[] deploymentNames;
        try {
            deploymentNames = DeploymentUtils.deployArchive(deploymentManager, archiveFile, deployExploded);
        } finally {
            // Make sure to switch back to the 'applications' profile if we switched to the 'farm' profile above.
            if (deployFarmed) {
                deploymentManager.loadProfile(APPLICATIONS_PROFILE_KEY);
            }
        }

        if (deploymentNames == null || deploymentNames.length != 1) {
            throw new RuntimeException("deploy operation returned invalid result: " + deploymentNames);
        }

        // e.g.: vfszip:/C:/opt/jboss-6.0.0.Final/server/default/deploy/foo.war
        String deploymentName = deploymentNames[0];

        // If deployed exploded, we need to store the SHA of source package in META-INF/MANIFEST.MF for correct
        // versioning.
        if (deployExploded) {
            MessageDigestGenerator sha256Generator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
            String shaString = sha256Generator.calcDigestString(archiveFile);
            URI deploymentURI = URI.create(deploymentName);
            // e.g.: /C:/opt/jboss-6.0.0.Final/server/default/deploy/foo.war
            String deploymentPath = deploymentURI.getPath();
            File deploymentFile = new File(deploymentPath);
            if (deploymentFile.isDirectory()) {
                File manifestFile = new File(deploymentFile, "META-INF/MANIFEST.MF");
                Manifest manifest;
                if (manifestFile.exists()) {
                    FileInputStream inputStream = new FileInputStream(manifestFile);
                    try {
                        manifest = new Manifest(inputStream);
                    } finally {
                        inputStream.close();
                    }
                } else {
                    File metaInf = new File(deploymentFile, "META-INF");
                    if (!metaInf.exists())
                        if (!metaInf.mkdir())
                            throw new Exception("Could not create directory " + deploymentFile + "META-INF.");

                    manifestFile = new File(metaInf, "MANIFEST.MF");
                    manifest = new Manifest();
                }
                Attributes attribs = manifest.getMainAttributes();
                attribs.putValue("RHQ-Sha256", shaString);
                FileOutputStream outputStream = new FileOutputStream(manifestFile);
                try {
                    manifest.write(outputStream);
                } finally {
                    outputStream.close();
                }
            } else {
                LOG.error("Exploded deployment '" + deploymentFile
                        + "' does not exist or is not a directory - unable to add RHQ versioning metadata to META-INF/MANIFEST.MF.");
            }
        }

        // Reload the management view to pickup the ManagedDeployment for the app we just deployed.
        ManagementView managementView = this.profileServiceConnection.getManagementView();
        managementView.load();

        ManagedDeployment managedDeployment = null;
        try {
            managedDeployment = managementView.getDeployment(deploymentName);
        } catch (NoSuchDeploymentException e) {
            LOG.error("Failed to find managed deployment '" + deploymentName + "' after deploying '"
                    + archiveName + "', so cannot start the application.");
            createResourceReport.setStatus(CreateResourceStatus.INVALID_ARTIFACT);
            createResourceReport.setErrorMessage("Unable to start application '" + deploymentName
                    + "' after deploying it, since lookup of the associated ManagedDeployment failed.");
        }
        if (managedDeployment != null) {
            DeploymentState state = managedDeployment.getDeploymentState();
            if (state != DeploymentState.STARTED) {
                // The app failed to start - do not consider this a FAILURE, since it was at least deployed
                // successfully. However, set the status to INVALID_ARTIFACT and set an error message, so
                // the user is informed of the condition.
                createResourceReport.setStatus(CreateResourceStatus.INVALID_ARTIFACT);
                createResourceReport.setErrorMessage(
                        "Failed to start application '" + deploymentName + "' after deploying it.");
            }
        }

        createResourceReport.setResourceName(archiveName);
        createResourceReport.setResourceKey(archiveName);
        if (createResourceReport.getStatus() == null) {
            // Deployment was 100% successful, including starting the app.
            createResourceReport.setStatus(CreateResourceStatus.SUCCESS);
        }
    } catch (Throwable t) {
        LOG.error("Error deploying application for request [" + createResourceReport + "].", t);
        createResourceReport.setStatus(CreateResourceStatus.FAILURE);
        createResourceReport.setException(t);
    } finally {
        if (archiveFile != null) {
            downloader.destroyArchive(archiveFile);
        }
    }
}

From source file:com.orange.mmp.midlet.MidletManager.java

/**
 * Get Midlet for download.//  w w w. j a v a  2 s .  co  m
 * @param appId            The midlet main application ID
 * @param mobile          The mobile to use
 * @param isMidletSigned   Boolean indicating if the midlet is signed (true), unsigned (false), to sign (null)
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ByteArrayOutputStream getJar(String appId, Mobile mobile, Boolean isMidletSigned) throws MMPException {
    if (appId == null)
        appId = ServiceManager.getInstance().getDefaultService().getId();

    //Search in Cache first
    String jarKey = appId + isMidletSigned + mobile.getKey();

    if (this.midletCache.isKeyInCache(jarKey)) {
        return (ByteArrayOutputStream) this.midletCache.get(jarKey).getValue();
    }

    Object extraCSSJadAttr = null;

    //Not found, build the JAR
    ByteArrayOutputStream output = null;
    ZipOutputStream zipOut = null;
    ZipInputStream zipIn = null;
    InputStream resourceStream = null;
    try {
        Midlet midlet = new Midlet();
        midlet.setType(mobile.getMidletType());
        Midlet[] midlets = (Midlet[]) DaoManagerFactory.getInstance().getDaoManager().getDao("midlet")
                .find(midlet);
        if (midlets.length == 0)
            throw new MMPException("Midlet type not found : " + mobile.getMidletType());
        else
            midlet = midlets[0];

        //Get navigation widget
        Widget appWidget = WidgetManager.getInstance().getWidget(appId, mobile.getBranchId());
        if (appWidget == null) {
            // Use Default if not found
            appWidget = WidgetManager.getInstance().getWidget(appId);
        }
        List<URL> embeddedResources = WidgetManager.getInstance().findWidgetResources("/m4m/", "*", appId,
                mobile.getBranchId(), false);
        output = new ByteArrayOutputStream();
        zipOut = new ZipOutputStream(output);
        zipIn = new ZipInputStream(new FileInputStream(new File(new URI(midlet.getJarLocation()))));

        ZipEntry entry;
        while ((entry = zipIn.getNextEntry()) != null) {
            zipOut.putNextEntry(entry);

            // Manifest found, modify it before delivery
            if (entry.getName().equals(Constants.JAR_MANIFEST_ENTRY) && appWidget != null) {
                Manifest midletManifest = new Manifest(zipIn);

                // TODO ? Remove optional permissions if midlet is not signed
                if (isMidletSigned != null && !isMidletSigned)
                    midletManifest.getMainAttributes().remove(Constants.JAD_PARAMETER_OPT_PERMISSIONS);

                midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_APPNAME,
                        appWidget.getName());
                String launcherLine = midletManifest.getMainAttributes()
                        .getValue(Constants.JAD_PARAMETER_LAUNCHER);
                Matcher launcherLineMatcher = launcherPattern.matcher(launcherLine);
                if (launcherLineMatcher.matches()) {
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName().concat(", ").concat(launcherLineMatcher.group(2)).concat(", ")
                                    .concat(launcherLineMatcher.group(3)));
                } else
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName());

                // Add/Modify/Delete MANIFEST parameters according to mobile rules
                JadAttributeAction[] jadActions = mobile.getJadAttributeActions();
                for (JadAttributeAction jadAction : jadActions) {
                    if (jadAction.getInManifest().equals(ApplyCase.ALWAYS)
                            || (isMidletSigned != null && isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.SIGNED))
                            || (isMidletSigned != null && !isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.UNSIGNED))) {
                        Attributes.Name attrName = new Attributes.Name(jadAction.getAttribute());
                        boolean exists = midletManifest.getMainAttributes().get(attrName) != null;
                        if (jadAction.isAddAction() || jadAction.isModifyAction()) {
                            if (exists || !jadAction.isStrict())
                                midletManifest.getMainAttributes().putValue(jadAction.getAttribute(),
                                        jadAction.getValue());
                        } else if (jadAction.isDeleteAction() && exists)
                            midletManifest.getMainAttributes().remove(attrName);
                    }
                }

                //Retrieve MeMo CSS extra attribute
                extraCSSJadAttr = midletManifest.getMainAttributes()
                        .get(new Attributes.Name(Constants.JAD_PARAMETER_MEMO_EXTRA_CSS));

                midletManifest.write(zipOut);
            }
            //Other files of Midlet
            else {
                IOUtils.copy(zipIn, zipOut);
            }
            zipIn.closeEntry();
            zipOut.closeEntry();
        }

        if (embeddedResources != null) {
            for (URL resourceUrl : embeddedResources) {
                resourceStream = resourceUrl.openConnection().getInputStream();
                String resourcePath = resourceUrl.getPath();
                entry = new ZipEntry(resourcePath.substring(resourcePath.lastIndexOf("/") + 1));
                entry.setTime(MIDLET_LAST_MODIFICATION_DATE);
                zipOut.putNextEntry(entry);
                IOUtils.copy(resourceStream, zipOut);
                zipOut.closeEntry();
                resourceStream.close();
            }
        }

        //Put JAR in cache for next uses
        this.midletCache.set(new Element(jarKey, output));

        //If necessary, add special CSS file if specified in JAD attributes
        if (extraCSSJadAttr != null) {
            String extraCSSSheetName = (String) extraCSSJadAttr;
            //Get resource stream
            resourceStream = WidgetManager.getInstance().getWidgetResource(
                    extraCSSSheetName + "/" + this.cssSheetsBundleName, mobile.getBranchId());

            if (resourceStream == null)
                throw new DataAccessResourceFailureException("no CSS sheet named " + extraCSSSheetName + " in "
                        + this.cssSheetsBundleName + " special bundle");

            //Append CSS sheet file into JAR
            entry = new ZipEntry(new File(extraCSSSheetName).getName());
            entry.setTime(MidletManager.MIDLET_LAST_MODIFICATION_DATE);
            zipOut.putNextEntry(entry);
            IOUtils.copy(resourceStream, zipOut);
            zipOut.closeEntry();
            resourceStream.close();
        }

        return output;

    } catch (IOException ioe) {
        throw new MMPException(ioe);
    } catch (URISyntaxException use) {
        throw new MMPException(use);
    } catch (DataAccessException dae) {
        throw new MMPException(dae);
    } finally {
        try {
            if (output != null)
                output.close();
            if (zipIn != null)
                zipIn.close();
            if (zipOut != null)
                zipOut.close();
            if (resourceStream != null)
                resourceStream.close();
        } catch (IOException ioe) {
            //NOP
        }
    }
}

From source file:ca.weblite.jdeploy.JDeploy.java

private File[] findJarCandidates() throws IOException {
    File[] jars = findCandidates(directory.toPath().getFileSystem().getPathMatcher("glob:**/*.jar"));
    List<File> out = new ArrayList<File>();
    // We only want executable jars
    for (File f : jars) {
        Manifest m = new JarFile(f).getManifest();
        //System.out.println(m.getEntries());
        if (m != null) {
            Attributes atts = m.getMainAttributes();
            if (atts.containsKey(Attributes.Name.MAIN_CLASS)) {
                //executable jar
                out.add(f);// w  w w .ja  v a2s  .c  o  m
            }
        }
    }
    return out.toArray(new File[out.size()]);
}

From source file:com.izforge.izpack.installer.unpacker.UnpackerBase.java

private void logIntro() {
    final String startMessage = messages.get("installer.started");
    char[] chars = new char[startMessage.length()];
    Arrays.fill(chars, '=');
    logger.info(new String(chars));
    logger.info(startMessage);/* www.j  a v a  2 s .c  o m*/

    URLClassLoader cl = (URLClassLoader) getClass().getClassLoader();
    InputStream is = null;
    try {
        URL url = cl.findResource("META-INF/MANIFEST.MF");
        is = url.openStream();
        Manifest manifest = new Manifest(is);
        Attributes attr = manifest.getMainAttributes();
        logger.info(messages.get("installer.version", attr.getValue("Created-By")));
    } catch (IOException e) {
        logger.log(Level.WARNING, "IzPack version not found in manifest", e);
    } finally {
        IOUtils.closeQuietly(is);
    }

    logger.info(messages.get("installer.platform", matcher.getCurrentPlatform()));
}

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

private void scanJar(Map<String, Map<String, Map<String, VersionLocation>>> packageVersionCounts, File jarFile,
        String defaultVersion) throws IOException {
    JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile));
    Manifest jarManifest = jarInputStream.getManifest();
    // Map<String, String> manifestVersions = new HashMap<String,String>();
    String specificationVersion = null;
    if (jarManifest == null) {
        getLog().warn("No MANIFEST.MF file found for dependency " + jarFile);
    } else {/*w  ww  . ja  v  a  2s  .c om*/
        if (jarManifest.getMainAttributes() == null) {
            getLog().warn("No main attributes found in MANIFEST.MF file found for dependency " + jarFile);
        } else {
            specificationVersion = jarManifest.getMainAttributes().getValue("Specification-Version");
            if (defaultVersion == null) {
                if (jarManifest.getMainAttributes().getValue("Bundle-Version") != null) {
                } else if (specificationVersion != null) {
                    defaultVersion = specificationVersion;
                } else {
                    defaultVersion = jarManifest.getMainAttributes().getValue("Implementation-Version");
                }
            }
            String exportPackageHeaderValue = jarManifest.getMainAttributes().getValue("Export-Package");
            if (exportPackageHeaderValue != null) {
                ManifestElement[] manifestElements = new ManifestElement[0];
                try {
                    manifestElements = ManifestElement.parseHeader("Export-Package", exportPackageHeaderValue);
                } catch (BundleException e) {
                    getLog().warn("Error while parsing Export-Package header value for jar " + jarFile, e);
                }
                for (ManifestElement manifestElement : manifestElements) {
                    String[] packageNames = manifestElement.getValueComponents();
                    String version = manifestElement.getAttribute("version");
                    for (String packageName : packageNames) {
                        updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), version,
                                version, packageName);
                    }
                }
            }
            for (Map.Entry<String, Attributes> manifestEntries : jarManifest.getEntries().entrySet()) {
                String packageName = manifestEntries.getKey().replaceAll("/", ".");
                if (packageName.endsWith(".class")) {
                    continue;
                }
                if (packageName.endsWith(".")) {
                    packageName = packageName.substring(0, packageName.length() - 1);
                }
                if (packageName.endsWith(".*")) {
                    packageName = packageName.substring(0, packageName.length() - 1);
                }
                int lastDotPos = packageName.lastIndexOf(".");
                String lastPackage = packageName;
                if (lastDotPos > -1) {
                    lastPackage = packageName.substring(lastDotPos + 1);
                }
                if (lastPackage.length() > 0 && Character.isUpperCase(lastPackage.charAt(0))) {
                    // ignore non package version
                    continue;
                }
                if (StringUtils.isEmpty(packageName) || packageName.startsWith("META-INF")
                        || packageName.startsWith("OSGI-INF") || packageName.startsWith("OSGI-OPT")
                        || packageName.startsWith("WEB-INF") || packageName.startsWith("org.osgi")) {
                    // ignore private package names
                    continue;
                }
                String packageVersion = null;
                if (manifestEntries.getValue().getValue("Specification-Version") != null) {
                    packageVersion = manifestEntries.getValue().getValue("Specification-Version");
                } else {
                    packageVersion = manifestEntries.getValue().getValue("Implementation-Version");
                }
                if (packageVersion != null) {
                    getLog().info("Found package version in " + jarFile.getName() + " MANIFEST : " + packageName
                            + " v" + packageVersion);
                    updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(),
                            packageVersion, specificationVersion, packageName);
                    // manifestVersions.put(packageName, packageVersion);
                }
            }
        }
    }
    JarEntry jarEntry = null;
    // getLog().debug("Processing file " + artifact.getFile() + "...");
    while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
        if (!jarEntry.isDirectory()) {
            String entryName = jarEntry.getName();
            String entryPackage = "";
            int lastSlash = entryName.lastIndexOf("/");
            if (lastSlash > -1) {
                entryPackage = entryName.substring(0, lastSlash);
                entryPackage = entryPackage.replaceAll("/", ".");
                if (StringUtils.isNotEmpty(entryPackage) && !entryPackage.startsWith("META-INF")
                        && !entryPackage.startsWith("OSGI-INF") && !entryPackage.startsWith("OSGI-OPT")
                        && !entryPackage.startsWith("WEB-INF") && !entryPackage.startsWith("org.osgi")) {
                    updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(),
                            defaultVersion, specificationVersion, entryPackage);
                }
            }
        }
    }
    jarInputStream.close();
}

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

private boolean processJarManifest(File jarFile, ParsingContext parsingContext, JarInputStream jarInputStream)
        throws IOException {
    boolean processedBundleHeadersSuccessfully = false;
    Manifest jarManifest = jarInputStream.getManifest();
    if (jarManifest != null && jarManifest.getMainAttributes() != null) {
        Attributes mainAttributes = jarManifest.getMainAttributes();
        String bundleSymbolicName = mainAttributes.getValue("Bundle-SymbolicName");
        if (bundleSymbolicName != null) {
            String bundleVersion = mainAttributes.getValue("Bundle-Version");
            String bundleClassPath = mainAttributes.getValue("Bundle-ClassPath");
            if (bundleClassPath != null && !".".equals(bundleClassPath.trim())) {
                String[] bundleClassPathEntries = bundleClassPath.split(",");
                for (String bundleClassPathEntry : bundleClassPathEntries) {
                    parsingContext.getBundleClassPath().add(bundleClassPathEntry.trim());
                }//from   ww w . j  a va  2  s  .  co  m
            }
            getLog().debug("OSGi bundle detected with symbolic name=" + bundleSymbolicName + " version="
                    + bundleVersion);
            parsingContext.setOsgiBundle(true);
            parsingContext.setVersion(bundleVersion);
            String importPackageHeaderValue = mainAttributes.getValue("Import-Package");
            String exportPackageHeaderValue = mainAttributes.getValue("Export-Package");
            String ignorePackageHeaderValue = mainAttributes.getValue("Ignore-Package");
            if (importPackageHeaderValue != null) {
                List<ManifestValueClause> importPackageClauses = BundleUtils.getHeaderClauses("Import-Package",
                        importPackageHeaderValue);
                for (ManifestValueClause importPackageClause : importPackageClauses) {
                    for (String importPackagePath : importPackageClause.getPaths()) {
                        String clauseVersion = importPackageClause.getAttributes().get("version");
                        String clauseResolution = importPackageClause.getDirectives().get("resolution");
                        boolean optionalClause = false;
                        if ("optional".equals(clauseResolution)) {
                            optionalClause = true;
                        }
                        PackageInfo importPackageInfo = new PackageInfo(importPackagePath, clauseVersion,
                                optionalClause, jarFile.getPath(), parsingContext);
                        parsingContext.addPackageImport(importPackageInfo);
                    }
                }
            }
            if (exportPackageHeaderValue != null) {
                List<ManifestValueClause> exportPackageClauses = BundleUtils.getHeaderClauses("Export-Package",
                        exportPackageHeaderValue);
                for (ManifestValueClause exportPackageClause : exportPackageClauses) {
                    for (String importPackagePath : exportPackageClause.getPaths()) {
                        String clauseVersion = exportPackageClause.getAttributes().get("version");
                        PackageInfo exportPackageInfo = new PackageInfo(importPackagePath, clauseVersion, false,
                                jarFile.getPath(), parsingContext);
                        parsingContext.addPackageExport(exportPackageInfo);
                    }
                }
            }
            if (ignorePackageHeaderValue != null) {
                List<ManifestValueClause> ignorePackageClauses = BundleUtils.getHeaderClauses("Ignore-Package",
                        ignorePackageHeaderValue);
                for (ManifestValueClause ignorePackageClause : ignorePackageClauses) {
                    for (String importPackagePath : ignorePackageClause.getPaths()) {
                        String clauseVersion = ignorePackageClause.getAttributes().get("version");
                        boolean optionalClause = true;
                        PackageInfo ignorePackageInfo = new PackageInfo(importPackagePath, clauseVersion,
                                optionalClause, jarFile.getPath(), parsingContext);
                        parsingContext.addPackageImport(ignorePackageInfo);
                    }
                }
            }
            processedBundleHeadersSuccessfully = true;
        }
    }
    return processedBundleHeadersSuccessfully;
}

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

private void updateBundle(Manifest manifest, List<ManifestValueClause> importPackageClauses, File artifactFile,
        String buildDirectory) {/*from  w  ww . j  a  v a  2s  . com*/
    StringBuilder sb = new StringBuilder();
    String separator = "";
    for (ManifestValueClause importPackageClause : importPackageClauses) {
        sb.append(separator);
        sb.append(importPackageClause.toString());
        separator = ",";
    }
    manifest.getMainAttributes().putValue("Import-Package", sb.toString());
    File expandedJarDirectory = unpackBundle(artifactFile);
    getLog().info("Extract JAR " + artifactFile + " contents to directory " + expandedJarDirectory);
    if (expandedJarDirectory == null) {
        getLog().error("Error unpacking artifact " + artifactFile + " aborting bundle update");
        return;
    }
    File manifestFile = new File(expandedJarDirectory, "META-INF/MANIFEST.MF");
    if (manifestFile.exists()) {
        getLog().info("Overwriting existing META-INF/MANIFEST file");
    } else {
        getLog().warn("Missing META-INF/MANIFEST.MF file in bundle, how did that happen ?");
    }
    FileOutputStream manifestFileOutputStream = null;
    try {
        manifestFileOutputStream = new FileOutputStream(manifestFile);
        manifest.write(manifestFileOutputStream);
    } catch (FileNotFoundException e) {
        getLog().error("Error writing new META-INF/MANIFEST.MF file", e);
        return;
    } catch (IOException e) {
        getLog().error("Error writing new META-INF/MANIFEST.MF file", e);
        return;
    } finally {
        IOUtils.closeQuietly(manifestFileOutputStream);
    }
    packBundle(artifactFile, manifestFile, expandedJarDirectory);

    try {
        FileUtils.deleteDirectory(expandedJarDirectory);
        getLog().info("Deleted temporary JAR extraction directory " + expandedJarDirectory);
    } catch (IOException e) {
        getLog().error("Error purging temporary extracted JAR directory " + expandedJarDirectory, e);
    }

    Artifact mainArtifact = project.getArtifact();

    if ("bundle".equals(mainArtifact.getType())) {
        // workaround for MNG-1682: force maven to install artifact using the "jar" handler
        mainArtifact.setArtifactHandler(artifactHandlerManager.getArtifactHandler("jar"));
    }

    if (null == classifier || classifier.trim().length() == 0) {
        mainArtifact.setFile(artifactFile);
    } else {
        mavenProjectHelper.attachArtifact(project, artifactFile, classifier);
    }

}