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.rzo.yajsw.app.WrapperManagerImpl.java

/**
 * Load jar.//from w w w  . ja v a 2  s. co m
 * 
 * @param jarName
 *            the jar name
 * 
 * @return the method
 */
private Method loadJar(String jarName) {
    URL url = null;
    try {
        url = new File(jarName).toURI().toURL();
    } catch (MalformedURLException e2) {
        e2.printStackTrace();
        return null;
    }
    Manifest manifest;
    try {
        manifest = new JarFile(new File(jarName)).getManifest();
    } catch (IOException e1) {
        e1.printStackTrace();
        return null;
    }
    Attributes attr = manifest.getMainAttributes();

    String cl = attr.getValue("Class-Path");
    ClassLoader loader = null;
    if (cl != null) {
        ArrayList classpath = new ArrayList();
        String[] clArr = cl.split(" ");
        for (int i = 0; i < clArr.length; i++) {
            String file = clArr[i];
            File myFile;
            try {
                myFile = new File(file);
                classpath.add(myFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        URL[] urlsArr = new URL[classpath.size()];
        int i = 0;
        for (Iterator it = classpath.iterator(); it.hasNext(); i++)
            try {
                urlsArr[i] = ((File) it.next()).toURI().toURL();
            } catch (Exception e) {
                e.printStackTrace();
            }

        loader = new URLClassLoader(urlsArr, ClassLoader.getSystemClassLoader());
    }
    if (loader == null)
        loader = ClassLoader.getSystemClassLoader();

    String mainClassName = attr.getValue("Main-Class");
    if (mainClassName == null)
        return null;
    Method mainMethod = null;
    try {
        Class cls = loader.loadClass(mainClassName);// cl.loadClass(mainClassName);
        mainMethod = cls.getDeclaredMethod("main", new Class[] { String[].class });
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return mainMethod;
}

From source file:dalma.container.ClassLoaderImpl.java

/**
 * Locates the Main class through {@code META-INF/MANIFEST.MF} and
 * returns it.//from   w ww . j ava 2  s .co  m
 *
 * @return
 *      always non-null.
 */
public Class loadMainClass() throws IOException, ClassNotFoundException {
    // determine the Main class name
    Enumeration<URL> res = getResources("META-INF/MANIFEST.MF");
    while (res.hasMoreElements()) {
        URL url = res.nextElement();
        InputStream is = new BufferedInputStream(url.openStream());
        try {
            Manifest mf = new Manifest(is);
            String value = mf.getMainAttributes().getValue("Dalma-Main-Class");
            if (value != null) {
                logger.info("Found Dalma-Main-Class=" + value + " in " + url);
                return loadClass(value);
            }
        } finally {
            is.close();
        }
    }

    // default location
    return loadClass("Main");
}

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

private boolean checkIfCytoscapeApp(File file) {
    JarFile jarFile = null;//w  ww  .j  a v  a  2  s.  c  o  m

    try {
        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:io.smartspaces.launcher.bootstrap.SmartSpacesFrameworkBootstrap.java

/**
 * Get the Smart Spaces version from the JAR manifest.
 *
 * @return The smart spaces version// w  ww .ja v  a2s.  c  om
 */
private String getSmartSpacesVersion() {
    // This little lovely line gives us the name of the jar that gave the
    // class
    // we are looking at.
    String classContainer = getClass().getProtectionDomain().getCodeSource().getLocation().toString();

    InputStream in = null;
    try {
        URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF");
        in = manifestUrl.openStream();
        Manifest manifest = new Manifest(in);
        Attributes attributes = manifest.getMainAttributes();

        return attributes.getValue(MANIFEST_PROPERTY_SMARTSPACES_VERSION);
    } catch (IOException ex) {
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // Don't care
            }
        }
    }
}

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;//w  ww.  ja  va2 s .com
    }
    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:com.github.wolf480pl.mias4j.util.AbstractTransformingClassLoader.java

protected Package definePackage(String name, Manifest man, URL codeSourceURL) {
    String path = toInternalName(name) + "/";
    Attributes attr = man.getAttributes(path);
    String specTitle = null;// ww w. j a va 2 s  . c  om
    String specVersion = null;
    String specVendor = null;
    String implTitle = null;
    String implVersion = null;
    String implVendor = null;
    String sealed = null;

    if (attr != null) {
        specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
        specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
        specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
        implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
        implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
        implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
        sealed = attr.getValue(Name.SEALED);
    }

    attr = man.getMainAttributes();
    if (attr != null) {
        if (specTitle != null) {
            specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
        }
        if (specVersion != null) {
            specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
        }
        if (specVendor != null) {
            specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
        }
        if (implTitle != null) {
            implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
        }
        if (implVersion != null) {
            implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
        }
        if (implVendor != null) {
            implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
        }
        if (sealed != null) {
            sealed = attr.getValue(Name.SEALED);
        }
    }

    return definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor,
            sealed.equalsIgnoreCase("true") ? codeSourceURL : null);

}

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  ww  w . j a va2s  . com*/

        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:dalma.container.ClassLoaderImpl.java

/**
 * Add a file to the path. This classloader reads the manifest, if
 * available, and adds any additional class path jars specified in the
 * manifest.//from   ww w . j a  va2  s. c om
 *
 * @param pathComponent the file which is to be added to the path for
 *                      this class loader
 *
 * @throws IOException if data needed from the file cannot be read.
 */
public void addPathFile(File pathComponent) throws IOException {
    pathComponents.addElement(pathComponent);

    if (pathComponent.isDirectory()) {
        return;
    }

    String absPathPlusTimeAndLength = pathComponent.getAbsolutePath() + pathComponent.lastModified() + "-"
            + pathComponent.length();
    String classpath = pathMap.get(absPathPlusTimeAndLength);
    if (classpath == null) {
        ZipFile jarFile = null;
        InputStream manifestStream = null;
        try {
            jarFile = new ZipFile(pathComponent);
            manifestStream = jarFile.getInputStream(new ZipEntry("META-INF/MANIFEST.MF"));

            if (manifestStream == null) {
                return;
            }
            Manifest manifest = new Manifest(manifestStream);
            classpath = manifest.getMainAttributes().getValue("Class-Path");

        } finally {
            if (manifestStream != null) {
                manifestStream.close();
            }
            if (jarFile != null) {
                jarFile.close();
            }
        }
        if (classpath == null) {
            classpath = "";
        }
        pathMap.put(absPathPlusTimeAndLength, classpath);
    }

    if (!"".equals(classpath)) {
        URL baseURL = pathComponent.toURL();
        StringTokenizer st = new StringTokenizer(classpath);
        while (st.hasMoreTokens()) {
            String classpathElement = st.nextToken();
            URL libraryURL = new URL(baseURL, classpathElement);
            if (!libraryURL.getProtocol().equals("file")) {
                logger.fine("Skipping jar library " + classpathElement
                        + " since only relative URLs are supported by this" + " loader");
                continue;
            }
            File libraryFile = new File(libraryURL.getFile());
            if (libraryFile.exists() && !isInPath(libraryFile)) {
                addPathFile(libraryFile);
            }
        }
    }
}

From source file:net.hasor.maven.ExecMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for all
 * classpath elements. Copied from surefire (ForkConfiguration#createJar())
 *
 * @param classPath List&lt;String> of all classpath elements.
 * @return/*from   w w w  .  ja v a2 s .co m*/
 * @throws IOException
 */
private File createJar(List<String> classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);
    Manifest man = new Manifest();
    // we can't use StringUtils.join here since we need to add a '/' to
    // the end of directory entries - otherwise the jvm will ignore them.
    StringBuilder cp = new StringBuilder();
    for (String el : classPath) {
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " ");
    }
    man.getMainAttributes().putValue("Manifest-Version", "1.0");
    man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
    man.getMainAttributes().putValue("Main-Class", mainClass);
    man.write(jos);
    jos.close();
    return file;
}

From source file:com.taobao.android.tools.TPatchTool.java

/**
 * create manifest for patch file//from  w w  w  . java 2 s.c o  m
 *
 * @return
 */
private Manifest createManifest() {
    Manifest manifest = new Manifest();
    Attributes main = manifest.getMainAttributes();
    main.putValue("Manifest-Version", "1.0");
    main.putValue("Created-By", "1.0 (DexPatch)");
    main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString());
    return manifest;
}