Example usage for java.util.jar JarFile getManifest

List of usage examples for java.util.jar JarFile getManifest

Introduction

In this page you can find the example usage for java.util.jar JarFile getManifest.

Prototype

public Manifest getManifest() throws IOException 

Source Link

Document

Returns the jar file manifest, or null if none.

Usage

From source file:org.hyperic.hq.agent.server.AgentDaemon.java

private void loadAgentServerHandlerJars(File[] libJars) throws AgentConfigException {
    AgentServerHandler loadedHandler;//from   w ww  . j a v  a2s . co m

    // Save the current context loader, and reset after we load plugin jars
    ClassLoader currentContext = Thread.currentThread().getContextClassLoader();

    for (File libJar : libJars) {
        try {
            JarFile jarFile = new JarFile(libJar);
            Manifest manifest = jarFile.getManifest();
            String mainClass = manifest.getMainAttributes().getValue("Main-Class");
            if (mainClass != null) {
                String jarPath = libJar.getAbsolutePath();
                loadedHandler = this.handlerLoader.loadServerHandler(jarPath);
                this.serverHandlers.add(loadedHandler);
                this.dispatcher.addServerHandler(loadedHandler);
            }
            jarFile.close();
        } catch (Exception e) {
            throw new AgentConfigException("Failed to load " + "'" + libJar + "': " + e.getMessage());
        }
    }

    // Restore the class loader
    Thread.currentThread().setContextClassLoader(currentContext);
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File hudsonTemplateWar = new File(warTemplateFile);

    if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) {
        String message = "The given Hudson template WAR [" + hudsonTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);/*from w ww .ja va2s  .c o m*/
        throw new IllegalStateException(message);
    }

    String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration);

    File hudsonDeployFile = new File(deployLocation);

    if (hudsonDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct HUDSON_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar),
                hudsonTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat.
        FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:org.cytoscape.app.internal.manager.AppManager.java

private boolean checkIfCytoscapeApp(File file) {
    JarFile jarFile = null;

    try {/*w  w w.java 2s  . co  m*/
        jarFile = new JarFile(file);

        Manifest manifest = jarFile.getManifest();

        // Check the manifest file 
        if (manifest != null) {
            if (manifest.getMainAttributes().getValue("Cytoscape-App-Name") != null) {

                jarFile.close();
                return true;
            }
        }

        jarFile.close();
    } catch (ZipException e) {
        // Do nothing; skip file
        // e.printStackTrace();
    } catch (IOException e) {
        // Do nothing; skip file
        // e.printStackTrace();
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
            }
        }
    }

    return false;
}

From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java

private void installBundles(File file, MessageContext context, String originalFilename, boolean forceUpdate,
        boolean autoStart) throws IOException, BundleException {

    JarFile jarFile = new JarFile(file);
    try {//from  w w  w . j  a v  a2s . c  om

        Attributes manifestAttributes = jarFile.getManifest().getMainAttributes();
        String jahiaRequiredVersion = manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_REQUIRED_VERSION);
        if (StringUtils.isEmpty(jahiaRequiredVersion)) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.install.required.version.missing.error").error()
                    .build());
            return;
        }
        if (new Version(jahiaRequiredVersion).compareTo(new Version(Jahia.VERSION)) > 0) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.install.required.version.error")
                    .args(jahiaRequiredVersion, Jahia.VERSION).error().build());
            return;
        }

        if (manifestAttributes.getValue(Constants.ATTR_NAME_JAHIA_PACKAGE_NAME) != null) {
            handlePackage(jarFile, manifestAttributes, originalFilename, forceUpdate, autoStart, context);
        } else {
            ModuleInstallationResult installationResult = installModule(file, context, null, null, forceUpdate,
                    autoStart);
            if (installationResult != null) {
                addModuleInstallationMessage(installationResult, context);
            }
        }
    } finally {
        jarFile.close();
    }
}

From source file:org.netbeans.nbbuild.MakeJnlp2.java

/**
 * returns version of jar file depending on manifest.mf or explicitly specified
 * @param jar/* w  w w .  j a  va  2 s  .  co  m*/
 * @return
 * @throws IOException
 */
private String getJarVersion(JarFile jar) throws IOException {
    String version = jar.getManifest().getMainAttributes().getValue("OpenIDE-Module-Specification-Version");
    if (version == null) {
        version = jar.getManifest().getMainAttributes().getValue("Specification-Version");
    }
    if (version == null && jarVersions != null) {
        version = jarVersions.get(jar.getName());
    }
    return version;
}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File jenkinsTemplateWar = new File(warTemplateFile);

    if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) {
        String message = "The given Jenkins template WAR [" + jenkinsTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);/*from  w  w w . ja va  2  s.  c o  m*/
        throw new IllegalStateException(message);
    }

    String pathProperty = perOrg ? configuration.getOrganizationIdentifier()
            : configuration.getProjectIdentifier();

    String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL)
            + jenkinsPath + pathProperty + "/jenkins/";
    deployedUrl.replace("//", "/");
    URL deployedJenkinsUrl;
    try {
        deployedJenkinsUrl = new URL(deployedUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    String webappName = deployedJenkinsUrl.getPath();
    if (webappName.startsWith("/")) {
        webappName = webappName.substring(1);
    }
    if (webappName.endsWith("/")) {
        webappName = webappName.substring(0, webappName.length() - 1);
    }
    webappName = webappName.replace("/", "#");
    webappName = webappName + ".war";

    // Calculate our final filename.

    String deployLocation = targetWebappsDir + webappName;

    File jenkinsDeployFile = new File(deployLocation);

    if (jenkinsDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct JENKINS_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar),
                jenkinsTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into its deployment location so that it can be picked up and deployed by the app server.
        FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:dalma.container.ClassLoaderImpl.java

/**
 * Get the manifest from the given jar, if it is indeed a jar and it has a
 * manifest/* w  w w  . j a va  2  s  .  c o  m*/
 *
 * @param container the File from which a manifest is required.
 *
 * @return the jar's manifest or null is the container is not a jar or it
 *         has no manifest.
 *
 * @exception IOException if the manifest cannot be read.
 */
private Manifest getJarManifest(File container) throws IOException {
    if (container.isDirectory()) {
        return null;
    }
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(container);
        return jarFile.getManifest();
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java

private ModuleInstallationResult installModule(File file, MessageContext context, List<String> providedBundles,
        Map<Bundle, MessageResolver> collectedResolutionErrors, boolean forceUpdate, boolean autoStart)
        throws IOException, BundleException {

    JarFile jarFile = new JarFile(file);
    try {/*from w  w w.  j av a  2s  .c o m*/

        Manifest manifest = jarFile.getManifest();
        String symbolicName = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_BUNDLE_SYMBOLIC_NAME);
        if (symbolicName == null) {
            symbolicName = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_ROOT_FOLDER);
        }
        String version = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_IMPL_VERSION);
        String groupId = manifest.getMainAttributes().getValue(Constants.ATTR_NAME_GROUP_ID);
        if (templateManagerService.differentModuleWithSameIdExists(symbolicName, groupId)) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.install.moduleWithSameIdExists").arg(symbolicName)
                    .error().build());
            return null;
        }
        ModuleVersion moduleVersion = new ModuleVersion(version);
        Set<ModuleVersion> allVersions = templatePackageRegistry.getAvailableVersionsForModule(symbolicName);
        if (!forceUpdate) {
            if (!moduleVersion.isSnapshot()) {
                if (allVersions.contains(moduleVersion)) {
                    context.addMessage(new MessageBuilder().source("moduleExists")
                            .code("serverSettings.manageModules.install.moduleExists")
                            .args(symbolicName, version).build());
                    return null;
                }
            }
        }

        String successMessage = (autoStart ? "serverSettings.manageModules.install.uploadedAndStarted"
                : "serverSettings.manageModules.install.uploaded");
        String resolutionError = null;

        boolean shouldAutoStart = autoStart;
        if (autoStart && !Boolean.valueOf(SettingsBean.getInstance().getPropertiesFile()
                .getProperty("org.jahia.modules.autoStartOlderVersions"))) {
            // verify that a newer version is not active already
            JahiaTemplatesPackage currentActivePackage = templateManagerService.getTemplatePackageRegistry()
                    .lookupById(symbolicName);
            ModuleVersion currentVersion = currentActivePackage != null ? currentActivePackage.getVersion()
                    : null;
            if (currentActivePackage != null && moduleVersion.compareTo(currentVersion) < 0) {
                // we do not start the uploaded older version automatically
                shouldAutoStart = false;
                successMessage = "serverSettings.manageModules.install.uploadedNotStartedDueToNewerVersionActive";
            }
        }

        try {
            moduleManager.install(new FileSystemResource(file), null, shouldAutoStart);
        } catch (ModuleManagementException e) {
            Throwable cause = e.getCause();
            if (cause != null && cause instanceof BundleException
                    && ((BundleException) cause).getType() == BundleException.RESOLVE_ERROR) {
                // we are dealing with unresolved dependencies here
                resolutionError = cause.getMessage();
            } else {
                // re-throw the exception
                throw e;
            }
        }

        Bundle bundle = BundleUtils.getBundle(symbolicName, version);

        JahiaTemplatesPackage module = BundleUtils.getModule(bundle);

        if (module.getState().getState() == ModuleState.State.WAITING_TO_BE_IMPORTED) {
            // This only can happen in a cluster.
            successMessage = "serverSettings.manageModules.install.waitingToBeImported";
        }

        if (resolutionError != null) {
            List<String> missingDeps = getMissingDependenciesFrom(module.getDepends(), providedBundles);
            if (!missingDeps.isEmpty()) {
                createMessageForMissingDependencies(context, missingDeps);
            } else {
                MessageResolver errorMessage = new MessageBuilder().source("moduleFile")
                        .code("serverSettings.manageModules.resolutionError").arg(resolutionError).error()
                        .build();
                if (collectedResolutionErrors != null) {
                    // we just collect the resolution errors for multiple module to double-check them after all modules are installed
                    collectedResolutionErrors.put(bundle, errorMessage);
                    return new ModuleInstallationResult(bundle, successMessage);
                } else {
                    // we directly add error message
                    context.addMessage(errorMessage);
                }
            }
        } else if (module.getState().getState() == ModuleState.State.ERROR_WITH_DEFINITIONS) {
            context.addMessage(new MessageBuilder().source("moduleFile")
                    .code("serverSettings.manageModules.errorWithDefinitions")
                    .arg(((Exception) module.getState().getDetails()).getCause().getMessage()).error().build());
        } else {
            return new ModuleInstallationResult(bundle, successMessage);
        }
    } finally {
        IOUtils.closeQuietly(jarFile);
    }

    return null;
}

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

@Override
public void execute() throws MojoExecutionException {
    setBuildDirectory(projectBuildDirectory);
    setOutputDirectory(new File(projectOutputDirectory));

    if (!"jar".equals(project.getPackaging()) && !"bundle".equals(project.getPackaging())
            && !"war".equals(project.getPackaging())) {
        getLog().info("Not a JAR/WAR/Bundle project, will do nothing.");
        return;//from www. j  a  va  2 s  .  c  o m
    }
    loadSystemPackages();

    buildExclusionPatterns();

    Set<PackageInfo> explicitPackageImports = new TreeSet<PackageInfo>();

    final ParsingContext projectParsingContext = new ParsingContext(
            MavenAetherHelperUtils.getCoords(project.getArtifact()), 0, 0, project.getArtifactId(),
            project.getBasedir().getPath(), project.getVersion(), null);

    List<PackageInfo> bundlePluginExplicitPackages = new ArrayList<PackageInfo>();
    Map<String, String> originalInstructions = new LinkedHashMap<String, String>();
    try {
        Xpp3Dom felixBundlePluginConfiguration = (Xpp3Dom) project
                .getPlugin("org.apache.felix:maven-bundle-plugin").getConfiguration();
        if (felixBundlePluginConfiguration != null) {
            Xpp3Dom instructionsDom = felixBundlePluginConfiguration.getChild("instructions");
            for (Xpp3Dom instructionChild : instructionsDom.getChildren()) {
                originalInstructions.put(instructionChild.getName(), instructionChild.getValue());
            }
            if (felixBundlePluginConfiguration.getChild("excludeDependencies") != null) {
                excludeDependencies = felixBundlePluginConfiguration.getChild("excludeDependencies").getValue();
            }
            getBundlePluginExplicitPackageImports(projectParsingContext, bundlePluginExplicitPackages,
                    originalInstructions);
        }
    } catch (Exception e) {
        // no overrides
        getLog().info(
                "No maven-bundle-plugin found, will not use dependency exclude or deal with explicit Import-Package configurations. ("
                        + e.getMessage() + ")");
    }

    Properties properties = new Properties();
    try {
        Builder builder = getOSGiBuilder(project, originalInstructions, properties, getClasspath(project));
        resolveEmbeddedDependencies(project, builder);
    } catch (Exception e) {
        throw new MojoExecutionException("Error trying to process bundle plugin instructions", e);
    }

    List<PackageInfo> existingPackageImports = getExistingImportPackages(projectParsingContext);
    explicitPackageImports.addAll(existingPackageImports);

    parsingContextCache = new ParsingContextCache(new File(dependencyParsingCacheDirectory), null);

    long timer = System.currentTimeMillis();
    int scanned = 0;
    try {
        scanClassesBuildDirectory(projectParsingContext);

        getLog().info("Scanned classes directory in " + (System.currentTimeMillis() - timer) + " ms. Found "
                + projectParsingContext.getLocalPackages().size() + " project packages.");

        scanned = scanDependencies(projectParsingContext);
    } catch (IOException e) {
        throw new MojoExecutionException("Error while scanning dependencies", e);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error while scanning project packages", e);
    }

    getLog().info("Scanned " + scanned + " project dependencies in " + (System.currentTimeMillis() - timer)
            + " ms. Currently we have " + projectParsingContext.getLocalPackages().size()
            + " project packages.");

    projectParsingContext.postProcess();

    if (projectParsingContext.getSplitPackages().size() > 0) {
        if (failBuildOnSplitPackages) {
            StringBuilder splitPackageList = new StringBuilder();
            for (PackageInfo packageInfo : projectParsingContext.getSplitPackages()) {
                splitPackageList.append("  ");
                splitPackageList.append(packageInfo.toString());
                splitPackageList.append(" from locations:\n    ");
                splitPackageList.append(StringUtils.join(packageInfo.getSourceLocations(), "\n    "));
                splitPackageList.append("\n");
            }
            throw new MojoExecutionException("Detected split packages:\n" + splitPackageList.toString());
        }
    }

    String extension = project.getPackaging();
    if ("bundle".equals(extension)) {
        extension = "jar";
    }
    String artifactFilePath = project.getBuild().getDirectory() + "/" + project.getBuild().getFinalName() + "."
            + extension;

    File artifactFile = new File(artifactFilePath);
    if (artifactFile == null || !artifactFile.exists()) {
        throw new MojoExecutionException(
                "No artifact generated for project, was the goal called in the proper phase (should be verify) ?");
    }

    Set<FullyEqualPackageInfo> allPackageExports = collectAllDependenciesExports(projectParsingContext,
            new HashSet<String>());

    Set<PackageInfo> missingPackageExports = new TreeSet<PackageInfo>();
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(artifactFile);
        Manifest manifest = jarFile.getManifest();
        if (manifest.getMainAttributes() == null) {
            throw new MojoExecutionException(
                    "Error reading OSGi bundle manifest data from artifact " + artifactFile);
        }
        String importPackageHeaderValue = manifest.getMainAttributes().getValue("Import-Package");
        Set<String> visitedPackageImports = new TreeSet<String>();
        if (importPackageHeaderValue != null) {
            List<ManifestValueClause> importPackageClauses = BundleUtils.getHeaderClauses("Import-Package",
                    importPackageHeaderValue);
            List<ManifestValueClause> clausesToRemove = new ArrayList<ManifestValueClause>();
            boolean modifiedImportPackageClauses = false;
            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;
                    } else if ("mandatory".equals(clauseResolution)) {
                        // the resolution directive is explicitely specified as mandatory, we won't modify it
                        optionalClause = false;
                    } else {
                        if (containsPackage(existingPackageImports, importPackagePath)
                                || containsPackage(bundlePluginExplicitPackages, importPackagePath)) {
                            // the package was explicitely configured either through Maven properties or through
                            // explicit configuration in the bundle plugin, in this case we will not touch the
                            // package's resolution directive
                            getLog().info("Explicit package configuration found for " + importPackagePath
                                    + ", will not mark as optional.");
                        } else {
                            importPackageClause.getDirectives().put("resolution", "optional");
                            modifiedImportPackageClauses = true;
                        }
                    }
                    if (visitedPackageImports.contains(importPackagePath)) {
                        getLog().warn("Duplicate import detected on package " + importPackagePath
                                + ", will remove duplicate. To remove this warning remove the duplicate import (possibly coming from a explicit import in the maven-bundle-plugin instructions)");
                        clausesToRemove.add(importPackageClause);
                        modifiedImportPackageClauses = true;
                    }

                    //                        PackageInfo importPackageInfo = new PackageInfo(importPackagePath, clauseVersion, optionalClause, artifactFile.getPath(), projectParsingContext);
                    //                        if (!optionalClause) {
                    //                            if (PackageUtils.containsMatchingVersion(allPackageExports, importPackageInfo)
                    //                                    && !importPackageInfo.isOptional()) {
                    //                                // we must now check if the import is strict and if the available export is part of
                    //                                // an optional export, in which case we will have to change it to be optional
                    //                                for (PackageInfo packageExport : allPackageExports) {
                    //                                    if (packageExport.matches(importPackageInfo)) {
                    //                                        if (packageExport.getOrigin() != null) {
                    //                                            ParsingContext parsingContext = packageExport.getOrigin();
                    //                                            if (parsingContext.isOptional()) {
                    //                                                // JAR is optional, we should modify the import package clause to be optional too !
                    //                                                getLog().warn("Mandatory package import " + importPackageInfo + " provided by optional JAR " + getTrail(packageExport) + " will be forced as optional !");
                    //                                                importPackageClause.getDirectives().put("resolution", "optional");
                    //                                                modifiedImportPackageClauses = true;
                    //                                            }
                    //                                        }
                    //                                    }
                    //                                }
                    //                            }
                    //                            if (!PackageUtils.containsIgnoreVersion(allPackageExports, importPackageInfo) &&
                    //                                    !PackageUtils.containsIgnoreVersion(systemPackages, importPackageInfo) &&
                    //                                    !PackageUtils.containsIgnoreVersion(projectParsingContext.getLocalPackages(), importPackageInfo)) {
                    //                                missingPackageExports.add(importPackageInfo);
                    //                            }
                    //                        }
                    visitedPackageImports.add(importPackagePath);
                }
            }
            if (modifiedImportPackageClauses) {
                for (ManifestValueClause clauseToRemove : clausesToRemove) {
                    boolean removeSuccessful = importPackageClauses.remove(clauseToRemove);
                    if (!removeSuccessful) {
                        getLog().warn("Removal of clause " + clauseToRemove
                                + " was not successful, duplicates may still remain in Manifest !");
                    }
                }
                updateBundle(manifest, importPackageClauses, artifactFile, buildDirectory);
            }
        }
    } catch (IOException e) {
        throw new MojoExecutionException(
                "Error reading OSGi bundle manifest data from artifact " + artifactFile, e);
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                // do nothing if close fails
            }
        }
    }
    missingPackageExports.removeAll(explicitPackageImports);

    if (missingPackageExports.size() > 0) {

        List<String> missingPackageNames = new ArrayList<String>();
        for (PackageInfo missingPackageExport : missingPackageExports) {
            missingPackageNames.add(missingPackageExport.getName());
        }

        getLog().info("Search for code origin of " + missingPackageExports.size()
                + " missing package imports, please wait...");
        final Map<String, Map<String, Artifact>> packageResults = FindPackageUsesMojo.findPackageUses(
                missingPackageNames, project.getArtifacts(), project, outputDirectory, searchInDependencies,
                getLog());
        if (packageResults.size() == 0) {
            getLog().warn(
                    "No results found in project files, use the <searchInDependencies>true</searchInDependencies> parameter to make the plugin look in all the dependencies (which is MUCH slower !)");
        }

        StringBuilder optionaDirectivesBuilder = new StringBuilder();
        StringBuilder errorMessageBuilder = new StringBuilder();
        String separator = "";
        for (PackageInfo missingPackageExport : missingPackageExports) {
            optionaDirectivesBuilder.append(separator);
            errorMessageBuilder.append(missingPackageExport);
            List<String> artifactIDs = findPackageInMavenCentral(missingPackageExport.getName());
            if (artifactIDs.size() > 0) {
                String artifactList = StringUtils.join(artifactIDs, ", ");
                errorMessageBuilder.append(" (available from Maven Central artifacts ");
                errorMessageBuilder.append(artifactList);
                errorMessageBuilder.append(",... or more at ");
                errorMessageBuilder.append(PackageUtils.getPackageSearchUrl(missingPackageExport.getName()));
                errorMessageBuilder.append(" )");
            } else {
                errorMessageBuilder.append(" (not found at Maven Central, is it part of JDK ?)");
            }
            missingPackageExport.setOptional(true);
            missingPackageExport.setVersion(null);
            optionaDirectivesBuilder.append(missingPackageExport);
            if (packageResults.containsKey(missingPackageExport.getName())) {
                Map<String, Artifact> sourceLocations = packageResults.get(missingPackageExport.getName());
                for (Map.Entry<String, Artifact> foundClass : sourceLocations.entrySet()) {
                    if (!foundClass.getValue().toString().equals(project.getArtifact().toString())) {
                        errorMessageBuilder.append("\n     used in class " + foundClass.getKey() + " ("
                                + foundClass.getValue().getFile() + ")");
                    } else {
                        errorMessageBuilder.append("\n     used in class " + foundClass.getKey()
                                + " (in project or embedded dependencies)");
                    }
                }
            }
            errorMessageBuilder.append("\n\n");
            separator = ",\n";
        }
        getLog().warn(
                "Couldn't find any exported packages in Maven project dependencies for the following imported packages:\n"
                        + errorMessageBuilder.toString());
        getLog().warn(
                "Use the following lines in the <Import-Package> maven-bundle-plugin configuration to ignore these packages :\n"
                        + optionaDirectivesBuilder.toString());
        getLog().warn(
                " or add the missing dependencies to your Maven project by finding the related missing Maven dependency");
        getLog().warn("");
        getLog().warn(
                "Bundle may not deploy successfully unless the above dependencies are either deployed, added to Maven project or marked explicitely as optional (as in the above list)");
        getLog().warn(
                "If you prefer to keep this warning activated but not fail the build, simply add <failBuildOnMissingPackageExports>false</failBuildOnMissingPackageExports> to the check-dependencies goal of the jahia-maven-plugin");
        getLog().warn("");
        getLog().warn(
                "You could also use mvn jahia:find-package-uses -DpackageNames=COMMA_SEPARATED_PACKAGE_LIST to find where a specific package is used in the project");
        getLog().warn(
                "or mvn jahia:find-packages -DpackageNames=COMMA_SEPARATED_PACKAGE_LIST to find the packages inside the project");
        getLog().warn("");
        if (failBuildOnMissingPackageExports) {
            throw new MojoExecutionException(
                    "Missing package exports for imported packages (see build log for details)");
        }
    }
}

From source file:org.argouml.moduleloader.ModuleLoader2.java

/**
 * Check a jar file for an ArgoUML extension/module.
 * <p>/*w ww.  j a v  a 2s.  co m*/
 *
 * If there isn't a manifest or it isn't readable, we fall back to using the
 * raw JAR entries.
 *
 * @param classloader
 *            The classloader to use.
 * @param file
 *            The file to process.
 * @throws ClassNotFoundException
 *             if the manifest file contains a class that doesn't exist.
 */
private void processJarFile(ClassLoader classloader, File file) throws ClassNotFoundException {

    LOG.log(Level.INFO, "Opening jar file {0}", file);
    JarFile jarfile = null;
    try {
        jarfile = new JarFile(file);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to open " + file, e);
        return;
    } finally {
        IOUtils.closeQuietly(jarfile);
    }

    Manifest manifest;
    try {
        manifest = jarfile.getManifest();
        if (manifest == null) {
            // We expect all extensions to have a manifest even though we
            // can operate without one if necessary.
            LOG.log(Level.WARNING, file + " does not have a manifest");
        }
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to read manifest of " + file, e);
        return;
    }

    // TODO: It is a performance drain to load all classes at startup time.
    // They should be lazy loaded when needed. Instead of scanning all
    // classes for ones which implement our loadable module interface, we
    // should use a manifest entry or a special name/name pattern that we
    // look for to find the single main module class to load here. - tfm

    boolean loadedClass = false;
    if (manifest == null) {
        Enumeration<JarEntry> jarEntries = jarfile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = jarEntries.nextElement();
            loadedClass = loadedClass | processEntry(classloader, entry.getName());
        }
    } else {
        Map<String, Attributes> entries = manifest.getEntries();
        for (String key : entries.keySet()) {
            // Look for our specification
            loadedClass = loadedClass | processEntry(classloader, key);
        }
    }

    // Add this to search list for I18N properties
    // (Done for both modules & localized property file sets)
    Translator.addClassLoader(classloader);

    // If it didn't have a loadable module class and it doesn't look like
    // a localized property set, warn the user that something funny is in
    // their extension directory
    if (!loadedClass && !file.getName().contains("argouml-i18n-")) {
        LOG.log(Level.SEVERE, "Failed to find any loadable ArgoUML modules in jar " + file);
    }
}