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:com.asual.summer.core.util.ResourceUtils.java

public static String getManifestAttribute(String key) {
    try {/*from  www  .  j  a  v a2s .  co  m*/
        if (!attributes.containsKey(key)) {
            String path = "META-INF/MANIFEST.MF";
            Manifest mf = new Manifest();
            URL resource = RequestUtils.getServletContext().getResource("/" + path);
            if (resource == null) {
                resource = getClasspathResources(path, false).get(0);
            }
            mf.read(new FileInputStream(resource.getFile()));
            attributes.put(key, mf.getMainAttributes().getValue(key));
        }
        return attributes.get(key);
    } catch (Exception e) {
        return "";
    }
}

From source file:com.opengamma.web.WebAbout.java

private static Set<URL> forManifest(final URL url) {
    Set<URL> result = Sets.newLinkedHashSet();
    result.add(url);//from  w w w. j  a v a2  s  . com
    try {
        final String part = ClasspathHelper.cleanPath(url);
        File jarFile = new File(part);
        try (JarFile myJar = new JarFile(part)) {
            URL validUrl = tryToGetValidUrl(jarFile.getPath(), new File(part).getParent(), part);
            if (validUrl != null) {
                result.add(validUrl);
            }
            final Manifest manifest = myJar.getManifest();
            if (manifest != null) {
                final String classPath = manifest.getMainAttributes()
                        .getValue(new Attributes.Name("Class-Path"));
                if (classPath != null) {
                    for (String jar : classPath.split(" ")) {
                        validUrl = tryToGetValidUrl(jarFile.getPath(), new File(part).getParent(), jar);
                        if (validUrl != null) {
                            result.add(validUrl);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        // don't do anything, we're going on the assumption it is a jar, which could be wrong
    }
    return result;
}

From source file:org.orbisgis.core.plugin.BundleTools.java

/**
 * Register in the host bundle the provided list of bundle reference
 * @param hostBundle Host BundleContext/*from www. j  a va 2s .  c o  m*/
 * @param nonDefaultBundleDeploying Bundle Reference array to deploy bundles in a non default way (install&start)
 */
public static void installBundles(BundleContext hostBundle, BundleReference[] nonDefaultBundleDeploying) {
    //Create a Map of nonDefaultBundleDeploying by their artifactId
    Map<String, BundleReference> customDeployBundles = new HashMap<String, BundleReference>(
            nonDefaultBundleDeploying.length);
    for (BundleReference ref : nonDefaultBundleDeploying) {
        customDeployBundles.put(ref.getArtifactId(), ref);
    }

    // List bundles in the /bundle subdirectory
    File bundleFolder = new File(BUNDLE_DIRECTORY);
    if (!bundleFolder.exists()) {
        return;
    }
    File[] files = bundleFolder.listFiles();
    List<File> jarList = new ArrayList<File>();
    if (files != null) {
        for (File file : files) {
            if (FilenameUtils.isExtension(file.getName(), "jar")) {
                jarList.add(file);
            }
        }
    }
    if (!jarList.isEmpty()) {
        Map<String, Bundle> installedBundleMap = new HashMap<String, Bundle>();

        // Keep a reference to bundles in the framework cache
        for (Bundle bundle : hostBundle.getBundles()) {
            String key = bundle.getSymbolicName() + "_" + bundle.getVersion();
            installedBundleMap.put(key, bundle);
        }

        //
        final List<Bundle> installedBundleList = new LinkedList<Bundle>();
        for (File jarFile : jarList) {
            // Extract version and symbolic name of the bundle
            String key = "";
            try {
                List<PackageDeclaration> packageDeclarations = new ArrayList<PackageDeclaration>();
                BundleReference jarRef = parseJarManifest(jarFile, packageDeclarations);
                key = jarRef.getArtifactId() + "_" + jarRef.getVersion();
            } catch (IOException ex) {
                LOGGER.error(ex.getLocalizedMessage(), ex);
            }
            // Retrieve from the framework cache the bundle at this location
            Bundle b = installedBundleMap.remove(key);

            // Read Jar manifest without installing it
            BundleReference reference = new BundleReference(""); // Default deploy
            try {
                JarFile jar = new JarFile(jarFile);
                Manifest manifest = jar.getManifest();
                if (manifest != null && manifest.getMainAttributes() != null) {
                    String artifact = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
                    BundleReference customRef = customDeployBundles.get(artifact);
                    if (customRef != null) {
                        reference = customRef;
                    }
                }

            } catch (Exception ex) {
                LOGGER.error(I18N.tr("Could not read bundle manifest"), ex);
            }

            try {
                if (b != null) {
                    String installedBundleLocation = b.getLocation();
                    if (!installedBundleLocation.equals(jarFile.toURI().toString())) {
                        //if the location is not the same reinstall it
                        b.uninstall();
                        b = null;
                    }
                }
                // If the bundle is not in the framework cache install it
                if ((b == null) && reference.isAutoInstall()) {
                    b = hostBundle.installBundle(jarFile.toURI().toString());
                    if (!isFragment(b) && reference.isAutoStart()) {
                        installedBundleList.add(b);
                    }
                } else if ((b != null)) {
                    b.update();
                }
            } catch (BundleException ex) {
                LOGGER.error("Error while installing bundle in bundle directory", ex);
            }
        }
        // Start new bundles
        for (Bundle bundle : installedBundleList) {
            try {
                bundle.start();
            } catch (BundleException ex) {
                LOGGER.error("Error while starting bundle in bundle directory", ex);
            }
        }
    }
}

From source file:de.upb.wdqa.wdvd.FeatureExtractor.java

private static String getBuildTime() {
    String result = null;//w ww . j  a v a2  s. co m
    try {
        Enumeration<URL> resources;
        resources = FeatureExtractor.class.getClassLoader().getResources("META-INF/MANIFEST.MF");

        //      while (resources.hasMoreElements()) {
        Manifest manifest = new Manifest(resources.nextElement().openStream());
        // check that this is your manifest and do what you need or get the next one

        result = manifest.getMainAttributes().getValue("Build-Time");

    } catch (IOException e) {
    }

    return result;
}

From source file:sx.blah.discord.modules.ModuleLoader.java

/**
 * Loads a jar file and automatically adds any modules.
 * To avoid high overhead recursion, specify the attribute "Discord4J-ModuleClass" in your jar manifest.
 * Multiple classes should be separated by a semicolon ";".
 *
 * @param file The jar file to load.//ww  w.jav  a 2 s  .co  m
 */
public static synchronized void loadExternalModules(File file) { // A bit hacky, but oracle be dumb and encapsulates URLClassLoader#addUrl()
    if (file.isFile() && file.getName().endsWith(".jar")) { // Can't be a directory and must be a jar
        try (JarFile jar = new JarFile(file)) {
            Manifest man = jar.getManifest();
            String moduleAttrib = man == null ? null
                    : man.getMainAttributes().getValue("Discord4J-ModuleClass");
            String[] moduleClasses = new String[0];
            if (moduleAttrib != null) {
                moduleClasses = moduleAttrib.split(";");
            }
            // Executes would should be URLCLassLoader.addUrl(file.toURI().toURL());
            URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
            URL url = file.toURI().toURL();
            for (URL it : Arrays.asList(loader.getURLs())) { // Ensures duplicate libraries aren't loaded
                if (it.equals(url)) {
                    return;
                }
            }
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(loader, url);
            if (moduleClasses.length == 0) { // If the Module Developer has not specified the Implementing Class, revert to recursive search
                // Scans the jar file for classes which have IModule as a super class
                List<String> classes = new ArrayList<>();
                jar.stream()
                        .filter(jarEntry -> !jarEntry.isDirectory() && jarEntry.getName().endsWith(".class"))
                        .map(path -> path.getName().replace('/', '.').substring(0,
                                path.getName().length() - ".class".length()))
                        .forEach(classes::add);
                for (String clazz : classes) {
                    try {
                        Class classInstance = loadClass(clazz);
                        if (IModule.class.isAssignableFrom(classInstance)
                                && !classInstance.equals(IModule.class)) {
                            addModuleClass(classInstance);
                        }
                    } catch (NoClassDefFoundError ignored) {
                        /* This can happen. Looking recursively looking through the classpath is hackish... */ }
                }
            } else {
                for (String moduleClass : moduleClasses) {
                    Discord4J.LOGGER.info(LogMarkers.MODULES, "Loading Class from Manifest Attribute: {}",
                            moduleClass);
                    Class classInstance = loadClass(moduleClass);
                    if (IModule.class.isAssignableFrom(classInstance))
                        addModuleClass(classInstance);
                }
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException
                | ClassNotFoundException e) {
            Discord4J.LOGGER.error(LogMarkers.MODULES, "Unable to load module " + file.getName() + "!", e);
        }
    }
}

From source file:org.gradle.api.java.archives.internal.DefaultManifest.java

private static void addMainAttributesToJavaManifest(org.gradle.api.java.archives.Manifest gradleManifest,
        Manifest javaManifest) {
    for (Map.Entry<String, Object> entry : gradleManifest.getAttributes().entrySet()) {
        String mainAttributeName = entry.getKey();
        String mainAttributeValue = entry.getValue().toString();
        javaManifest.getMainAttributes().putValue(mainAttributeName, mainAttributeValue);
    }/*from  w  ww  . j  a v a2 s . c o  m*/
}

From source file:ml.shifu.shifu.util.ShifuCLI.java

/**
 * print version info for shifu/*from   w  ww. j av a  2  s . c om*/
 */
private static void printVersionString() {
    String findContainingJar = JarManager.findContainingJar(ShifuCLI.class);
    JarFile jar = null;
    try {
        jar = new JarFile(findContainingJar);
        final Manifest manifest = jar.getManifest();

        String vendor = manifest.getMainAttributes().getValue("vendor");
        String title = manifest.getMainAttributes().getValue("title");
        String version = manifest.getMainAttributes().getValue("version");
        String timestamp = manifest.getMainAttributes().getValue("timestamp");
        System.out.println(vendor + " " + title + " version " + version + " \ncompiled " + timestamp);
    } catch (Exception e) {
        throw new RuntimeException("unable to read pigs manifest file", e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                throw new RuntimeException("jar closed failed", e);
            }
        }
    }
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

public static ILaunch publish(IFile ditaMapFile, String antTargets, String ditavalFileName)
        throws IOException, CoreException, URISyntaxException {

    IProject ditaProject = ditaMapFile.getProject();

    IFolder ditaFolder = ditaProject.getFolder(new Path("dita"));

    IFile ditaValFile = ditaFolder.getFile(ditavalFileName);

    StringBuffer jvmArguments = new StringBuffer();
    for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
        if (arg.startsWith("-X")) {
            jvmArguments.append(arg);/*from  w w w.  j  a  va 2s.c o m*/
            jvmArguments.append(" ");
        }
    }

    jvmArguments.append("-Dfile.encoding=UTF-8 ");

    String[] segments = ditaMapFile.getName().split("\\.");

    String ditaMapFileRoot = segments[0];

    Bundle bundle = Platform.getBundle("org.eclipse.mdht.dita.ui");

    Path path = new Path("META-INF/MANIFEST.MF");

    URL fileURL = FileLocator.find(bundle, path, null);

    Path ditadirPath = new Path("DITA-OT");

    URL ditadirURL = FileLocator.find(bundle, ditadirPath, null);

    if (ditadirURL == null) {
        return null;
    }

    ditadirURL = FileLocator.toFileURL(ditadirURL);

    InputStream in = fileURL.openStream();

    Manifest ditaPluginManifest = new Manifest(in);

    Attributes attributes = ditaPluginManifest.getMainAttributes();

    String ditaClassPath = attributes.getValue("Bundle-ClassPath");

    List<String> classpath = new ArrayList<String>();

    String ditaRequiredBundles = attributes.getValue("Require-Bundle");

    for (String requiredBundleSymbolicName : ditaRequiredBundles.split(",")) {

        // get before ;
        Bundle requiredBundle = Platform.getBundle(requiredBundleSymbolicName.split(";")[0]);

        // Assume the bundle is optional if null
        if (requiredBundle != null) {
            File file = FileLocator.getBundleFile(requiredBundle);

            IRuntimeClasspathEntry requiredBundleEntry = JavaRuntime
                    .newArchiveRuntimeClasspathEntry(new Path(file.getPath()));
            requiredBundleEntry.setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
            classpath.add(requiredBundleEntry.getMemento());
        }
    }

    for (String classPath : ditaClassPath.split(",")) {
        if (".".equals(classPath)) {
            URL url = FileLocator.find(bundle, new Path(""), null);
            url = FileLocator.toFileURL(url);
            IRuntimeClasspathEntry pluginEntry = JavaRuntime.newRuntimeContainerClasspathEntry(
                    new Path(url.getPath()), IRuntimeClasspathEntry.USER_CLASSES);
            classpath.add(pluginEntry.getMemento());
        } else {
            URL url = FileLocator.find(bundle, new Path(classPath), null);
            url = FileLocator.toFileURL(url);
            IRuntimeClasspathEntry toolsEntry = JavaRuntime
                    .newArchiveRuntimeClasspathEntry(new Path(url.getPath()));
            toolsEntry.setClasspathProperty(IRuntimeClasspathEntry.USER_CLASSES);
            classpath.add(toolsEntry.getMemento());
        }
    }

    ContributedClasspathEntriesEntry ccee = new ContributedClasspathEntriesEntry();

    AntHomeClasspathEntry ace = new AntHomeClasspathEntry();

    classpath.add(ace.getMemento());

    classpath.add(ccee.getMemento());

    ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();

    ILaunchConfigurationType type = launchManager
            .getLaunchConfigurationType(IAntLaunchConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);

    URL ditaPublishBuildFileURL = fileURL = FileLocator.find(bundle, new Path("dita-publish.xml"), null);

    ditaPublishBuildFileURL = FileLocator.toFileURL(ditaPublishBuildFileURL);

    String name = launchManager.generateLaunchConfigurationName("Publish DITA");

    ILaunchConfigurationWorkingCopy workingCopy = type.newInstance(null, name);

    workingCopy.setAttribute("org.eclipse.ui.externaltools.ATTR_LOCATION", ditaPublishBuildFileURL.getPath());

    IVMInstall jre = JavaRuntime.getDefaultVMInstall();

    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH, jre.getName());

    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
            "-Djavax.xml.transform.TransformerFactory=net.sf.saxon.TransformerFactoryImpl");

    Map<String, String> antProperties = new HashMap<String, String>();

    antProperties.put("dita.dir", ditadirURL.getPath());
    antProperties.put("ditaMapFile", ditaMapFile.getLocation().toOSString());

    if (ditaValFile != null) {
        antProperties.put("args.filter", ditaValFile.getLocation().toOSString());

    }

    antProperties.put("ditaMapFileName", ditaMapFile.getName().substring(0,
            ditaMapFile.getName().length() - ditaMapFile.getFileExtension().length()));

    // antProperties.put("outputLocation", ditaProject.getLocation().toOSString());
    antProperties.put("dita.output", ditaProject.getLocation().append(antTargets).toOSString());
    antProperties.put("ditaMapFileRoot", ditaMapFileRoot);

    String fileName = getFileNameFromMap(ditaMapFile.getLocation().toOSString());
    if (StringUtils.isEmpty(fileName)) {
        fileName = ditaMapFile.getName().replace("." + ditaMapFile.getFileExtension(), "");
    }

    antProperties.put("fileName", fileName);
    antProperties.put("args.debug", "no");
    antProperties.put("ditaFilePath", ditaFolder.getLocation().toOSString());
    antProperties.put("tempFilePath", org.eclipse.mdht.dita.ui.internal.Activator.getDefault()
            .getStateLocation().append("temp").toOSString());
    antProperties.put("docProject", ditaProject.getLocation().toOSString());

    String pdfFileLocation = ditaMapFile.getName();
    pdfFileLocation = pdfFileLocation.replaceFirst(".ditamap", ".pdf");
    antProperties.put("pdflocation", pdfFileLocation);

    workingCopy.setAttribute("process_factory_id", "org.eclipse.ant.ui.remoteAntProcessFactory");
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
            "org.eclipse.ant.internal.ui.antsupport.InternalAntRunner");

    workingCopy.setAttribute(
            org.eclipse.core.externaltools.internal.IExternalToolConstants.ATTR_WORKING_DIRECTORY,
            ditaProject.getLocation().toOSString());
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, jvmArguments.toString());
    workingCopy.setAttribute(org.eclipse.ant.launching.IAntLaunchConstants.ATTR_ANT_TARGETS, antTargets);
    workingCopy.setAttribute(IAntLaunchConstants.ATTR_ANT_PROPERTIES, antProperties);
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH, classpath);
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_DEFAULT_CLASSPATH, false);
    workingCopy.setAttribute(IDebugUIConstants.ATTR_CONSOLE_PROCESS, false);
    workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER,
            "org.eclipse.ant.ui.AntClasspathProvider");
    workingCopy.setAttribute(IDebugUIConstants.ATTR_LAUNCH_IN_BACKGROUND, true);

    workingCopy.setAttribute(DebugPlugin.ATTR_CONSOLE_ENCODING, "UTF-8");

    workingCopy.migrate();

    return workingCopy.launch(ILaunchManager.RUN_MODE, null, false, true);
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static String getPropertyFromManifest(String manifestPath, String property) {
    try {//  www  .  j av  a  2 s . c om
        URLClassLoader cl = (URLClassLoader) FileUtil.class.getClassLoader();

        URL url = cl.findResource(manifestPath);
        Manifest manifest = new Manifest(url.openStream());
        Attributes attr = manifest.getMainAttributes();

        return attr.getValue(property);
    } catch (IOException ex) {
        logger.debug("Exception: ", ex);
        return null;
    }
}

From source file:org.cloudifysource.dsl.internal.packaging.Packager.java

private static void createManifestFile(final File destPuFolder) throws IOException {
    final File manifestFolder = new File(destPuFolder, "META-INF");
    final File manifestFile = new File(manifestFolder, "MANIFEST.MF");

    final Manifest manifest = new Manifest();

    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().putValue("Class-Path",
            "lib/platform/cloudify/dsl.jar lib/platform/usm/usm.jar "
                    // added support for @grab annotation in groovy file - requires ivy and groovy in same classloader
                    + "tools/groovy/embeddable/groovy-all-1.8.6.jar tools/groovy/lib/ivy-2.2.0.jar ");

    OutputStream out = null;/*ww  w  . ja v  a2s . c o  m*/

    try {
        out = new BufferedOutputStream(new FileOutputStream(manifestFile));
        manifest.write(out);

    } finally {
        if (out != null) {

            try {
                out.close();
            } catch (final IOException e) {
                logger.log(Level.SEVERE, "Failed to close file: " + manifestFile, e);
            }

        }
    }

}