Java Code Examples for java.util.jar.Manifest#getMainAttributes()

The following examples show how to use java.util.jar.Manifest#getMainAttributes() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JarManifestParser.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private static Optional<String> findFirstManifestAttribute(JarFile jarFile, String... attributes) throws IOException {
	Manifest manifest = jarFile.getManifest();
	if (manifest == null) {
		return Optional.empty();
	}

	Attributes mainAttributes = manifest.getMainAttributes();
	for (String attribute : attributes) {
		String value = mainAttributes.getValue(attribute);
		if (value != null) {
			return Optional.of(value);
		}
	}

	return Optional.empty();
}
 
Example 2
Source File: MavenSourceBundleVirtualizer.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private void fillManifest ( final Manifest mf, final BundleInformation bi )
{
    final Attributes attr = mf.getMainAttributes ();

    attr.put ( Attributes.Name.MANIFEST_VERSION, "1.0" );

    attr.putValue ( Constants.BUNDLE_SYMBOLICNAME, bi.getId () + ".source" );
    attr.putValue ( Constants.BUNDLE_VERSION, "" + bi.getVersion () );
    attr.putValue ( Constants.BUNDLE_MANIFESTVERSION, "2" );
    attr.putValue ( Constants.BUNDLE_VENDOR, bi.getVendor () );
    attr.putValue ( Constants.BUNDLE_NAME, String.format ( "Source bundle for '%s'", bi.getId () ) );

    attr.putValue ( "Created-By", VersionInformation.VERSIONED_PRODUCT );

    attr.putValue ( "Eclipse-SourceBundle", makeSourceString ( bi ) );

    if ( bi.getBundleLocalization () != null )
    {
        attr.putValue ( Constants.BUNDLE_LOCALIZATION, bi.getBundleLocalization () );
    }
}
 
Example 3
Source File: Metadata.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
/**
    * Public main method, used solely for allowing customers to
    * print version and other metadata information from the enclosing
    * JAR file's manifest. This information is printed to stdout;
    * errors are printed to stderr.
    * 
    * @since 2011.1
    * @param args not used.
    */
public static void main(String[] args) {
	try {
		Manifest manifest = getManifest();
		Attributes attr = manifest.getMainAttributes();
		System.out.println(attr.getValue(Name.IMPLEMENTATION_TITLE));
		StringBuilder version = new StringBuilder(
				attr.getValue(Name.IMPLEMENTATION_VERSION));
		String changelist = attr.getValue("Build-Changelist");
		if (changelist != null) {
			version.append('/').append(changelist);
		}
		String type = attr.getValue("Build-Type");
		if (type != null) {
			version.append('/').append(type);
		}
		System.out.println(version);
	} catch (Exception exception) {
		System.err.println(exception.getLocalizedMessage());
	}
}
 
Example 4
Source File: Utils.java    From Scripts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves BAR's implementation date
 *
 * @return the implementation date or an empty strong if date could not be
 *         retrieved.
 */
private static String buildDate() {
	// http://stackoverflow.com/questions/1272648/
	if (BUILD_DATE == null) {
		final Class<Utils> clazz = Utils.class;
		final String className = clazz.getSimpleName() + ".class";
		final String classPath = clazz.getResource(className).toString();
		final String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1)
				+ "/META-INF/MANIFEST.MF";
		try {
			final Manifest manifest = new Manifest(new URL(manifestPath).openStream());
			final Attributes attr = manifest.getMainAttributes();
			BUILD_DATE = attr.getValue("Implementation-Date");
			BUILD_DATE = BUILD_DATE.substring(0, BUILD_DATE.lastIndexOf("T"));
		} catch (final Exception ignored) {
			BUILD_DATE = "";
		}
	}
	return BUILD_DATE;
}
 
Example 5
Source File: ApkPatch.java    From atlas with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
protected Manifest getMeta() {
    Manifest manifest = new Manifest();
    Attributes main = manifest.getMainAttributes();
    main.putValue("Manifest-Version", "1.0");
    main.putValue("Created-By", "1.0 (ApkPatch)");
    main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString());
    main.putValue("From-File", baseFiles.get(0).getName());
    main.putValue("To-File", newFiles.get(0).getName());
    main.putValue("Patch-Name", name);
    main.putValue(name + "-Patch-Classes", Formater.dotStringList(classes));
    main.putValue(name + "-Prepare-Classes", Formater.dotStringList(prepareClasses));
    main.putValue(name + "-Used-Methods", Formater.dotStringList(usedMethods));
    main.putValue(name + "-Modified-Classes", Formater.dotStringList(modifiedClasses));
    main.putValue(name + "-Used-Classes", Formater.dotStringList(usedClasses));
    main.putValue(name + "-add-classes", Formater.dotStringList(addClasses));

    return manifest;
}
 
Example 6
Source File: Main.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private boolean isAmbiguousMainClass(Manifest m) {
    if (ename != null) {
        Attributes global = m.getMainAttributes();
        if ((global.get(Attributes.Name.MAIN_CLASS) != null)) {
            error(getMsg("error.bad.eflag"));
            usageError();
            return true;
        }
    }
    return false;
}
 
Example 7
Source File: Main.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generates the transitive closure of the Class-Path attribute for
 * the specified jar file.
 */
List<String> getJarPath(String jar) throws IOException {
    List<String> files = new ArrayList<String>();
    files.add(jar);
    jarPaths.add(jar);

    // take out the current path
    String path = jar.substring(0, Math.max(0, jar.lastIndexOf('/') + 1));

    // class path attribute will give us jar file name with
    // '/' as separators, so we need to change them to the
    // appropriate one before we open the jar file.
    JarFile rf = new JarFile(jar.replace('/', File.separatorChar));

    if (rf != null) {
        Manifest man = rf.getManifest();
        if (man != null) {
            Attributes attr = man.getMainAttributes();
            if (attr != null) {
                String value = attr.getValue(Attributes.Name.CLASS_PATH);
                if (value != null) {
                    StringTokenizer st = new StringTokenizer(value);
                    while (st.hasMoreTokens()) {
                        String ajar = st.nextToken();
                        if (!ajar.endsWith("/")) {  // it is a jar file
                            ajar = path.concat(ajar);
                            /* check on cyclic dependency */
                            if (! jarPaths.contains(ajar)) {
                                files.addAll(getJarPath(ajar));
                            }
                        }
                    }
                }
            }
        }
    }
    rf.close();
    return files;
}
 
Example 8
Source File: Release.java    From juddi with Apache License 2.0 5 votes vote down vote up
public static String getVersionFromManifest(String jarName) {
	Enumeration<URL> resEnum;
       try {
           resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
           while (resEnum.hasMoreElements()) {
               try {
                   URL url = (URL) resEnum.nextElement();
                   if (url.toString().toLowerCase().contains(jarName)) {
                       InputStream is = url.openStream();
                       if (is != null) {
                           Manifest manifest = new Manifest(is);
                           Attributes mainAttribs = manifest.getMainAttributes();
                           String version = mainAttribs.getValue("Bundle-Version");
                           if (version != null) {
                               return (version);
                           }
                       }
                   }
               } catch (Exception e) {
                   // Silently ignore wrong manifests on classpath?
               }
           }
        } catch (IOException e1) {
           // Silently ignore wrong manifests on classpath?
        }
        return UNKNOWN;
}
 
Example 9
Source File: ProfileSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private Union2<Profile,String> findProfileInManifest(@NonNull URL root) {
    final ArchiveCache ac = context.getArchiveCache();
    Union2<Profile,String> res;
    final ArchiveCache.Key key = ac.createKey(root);
    if (key != null) {
        res = ac.getProfile(key);
        if (res != null) {
            return res;
        }
    }
    String profileName = null;
    final FileObject rootFo = URLMapper.findFileObject(root);
    if (rootFo != null) {
        final FileObject manifestFile = rootFo.getFileObject(RES_MANIFEST);
        if (manifestFile != null) {
            try {
                try (InputStream in = manifestFile.getInputStream()) {
                    final Manifest manifest = new Manifest(in);
                    final Attributes attrs = manifest.getMainAttributes();
                    profileName = attrs.getValue(ATTR_PROFILE);
                }
            } catch (IOException ioe) {
                LOG.log(
                    Level.INFO,
                    "Cannot read Profile attribute from: {0}", //NOI18N
                    FileUtil.getFileDisplayName(manifestFile));
            }
        }
    }
    final Profile profile = Profile.forName(profileName);
    res = profile != null ?
            Union2.<Profile,String>createFirst(profile) :
            Union2.<Profile,String>createSecond(profileName);
    if (key != null) {
        ac.putProfile(key, res);
    }
    return res;
}
 
Example 10
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private boolean isAmbiguousMainClass(Manifest m) {
    if (ename != null) {
        Attributes global = m.getMainAttributes();
        if ((global.get(Attributes.Name.MAIN_CLASS) != null)) {
            usageError(getMsg("error.bad.eflag"));
            return true;
        }
    }
    return false;
}
 
Example 11
Source File: ExtCheck.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
URL[] getClassPath() throws IOException {
    Manifest man = jar.getManifest();
    if (man != null) {
        Attributes attr = man.getMainAttributes();
        if (attr != null) {
            String value = attr.getValue(Name.CLASS_PATH);
            if (value != null) {
                return parseClassPath(csu, value);
            }
        }
    }
    return null;
}
 
Example 12
Source File: Main.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void addCreatedBy(Manifest m) {
    Attributes global = m.getMainAttributes();
    if (global.getValue(new Attributes.Name("Created-By")) == null) {
        String javaVendor = System.getProperty("java.vendor");
        String jdkVersion = System.getProperty("java.version");
        global.put(new Attributes.Name("Created-By"), jdkVersion + " (" +
                    javaVendor + ")");
    }
}
 
Example 13
Source File: JavacTurbineTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testManifestEntries() throws Exception {
  optionsBuilder.setTargetLabel("//foo:foo");
  optionsBuilder.setInjectingRuleKind("foo_library");
  compile();
  try (JarFile jarFile = new JarFile(output.toFile())) {
    Manifest manifest = jarFile.getManifest();
    Attributes attributes = manifest.getMainAttributes();
    assertThat(attributes.getValue("Target-Label")).isEqualTo("//foo:foo");
    assertThat(attributes.getValue("Injecting-Rule-Kind")).isEqualTo("foo_library");
    assertThat(jarFile.getEntry(JarFile.MANIFEST_NAME).getLastModifiedTime().toInstant())
        .isEqualTo(
            LocalDateTime.of(2010, 1, 1, 0, 0, 0).atZone(ZoneId.systemDefault()).toInstant());
  }
}
 
Example 14
Source File: ManifestInfo.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Instantiates a new manifest info.
 *
 * @param mf the mf
 */
public ManifestInfo(Manifest mf) {
    this.mf = mf;
    if (mf != null) {
        attr = mf.getAttributes("");
        main = mf.getMainAttributes();
        entries = mf.getEntries();
    } else {
        attr = null;
        main = null;
        entries = null;
    }
}
 
Example 15
Source File: Main.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private void addCreatedBy(Manifest m) {
    Attributes global = m.getMainAttributes();
    if (global.getValue(new Attributes.Name("Created-By")) == null) {
        String javaVendor = System.getProperty("java.vendor");
        String jdkVersion = System.getProperty("java.version");
        global.put(new Attributes.Name("Created-By"), jdkVersion + " (" +
                    javaVendor + ")");
    }
}
 
Example 16
Source File: PackageAttrsCache.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String[] extractFromManifest(Manifest man, String path) {
    Attributes spec = man.getAttributes(path);
    Attributes main = man.getMainAttributes();
    String[] arr = new String[7];
    arr[0] = getAttr(spec, main, Attributes.Name.SPECIFICATION_TITLE);
    arr[1] = getAttr(spec, main, Attributes.Name.SPECIFICATION_VERSION);
    arr[2] = getAttr(spec, main, Attributes.Name.SPECIFICATION_VENDOR);
    arr[3] = getAttr(spec, main, Attributes.Name.IMPLEMENTATION_TITLE);
    arr[4] = getAttr(spec, main, Attributes.Name.IMPLEMENTATION_VERSION);
    arr[5] = getAttr(spec, main, Attributes.Name.IMPLEMENTATION_VENDOR);
    arr[6] = getAttr(spec, main, Attributes.Name.SEALED);
    return arr;
}
 
Example 17
Source File: ExtensionDependency.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
protected boolean checkExtensionAgainst(String extensionName,
                                        Attributes attr,
                                        final File file)
    throws IOException,
           FileNotFoundException,
           ExtensionInstallationException
{

    debug("Checking extension " + extensionName +
          " against " + file.getName());

    // Load the jar file ...
    Manifest man;
    try {
        man = AccessController.doPrivileged(
            new PrivilegedExceptionAction<Manifest>() {
                public Manifest run()
                        throws IOException, FileNotFoundException {
                     if (!file.exists())
                         throw new FileNotFoundException(file.getName());
                     JarFile jarFile =  new JarFile(file);
                     return jarFile.getManifest();
                 }
             });
    } catch(PrivilegedActionException e) {
        if (e.getException() instanceof FileNotFoundException)
            throw (FileNotFoundException) e.getException();
        throw (IOException) e.getException();
    }

    // Construct the extension information object
    ExtensionInfo reqInfo = new ExtensionInfo(extensionName, attr);
    debug("Requested Extension : " + reqInfo);

    int isCompatible = ExtensionInfo.INCOMPATIBLE;
    ExtensionInfo instInfo = null;

    if (man != null) {
        Attributes instAttr = man.getMainAttributes();
        if (instAttr != null) {
            instInfo = new ExtensionInfo(null, instAttr);
            debug("Extension Installed " + instInfo);
            isCompatible = instInfo.isCompatibleWith(reqInfo);
            switch(isCompatible) {
            case ExtensionInfo.COMPATIBLE:
                debug("Extensions are compatible");
                return true;

            case ExtensionInfo.INCOMPATIBLE:
                debug("Extensions are incompatible");
                return false;

            default:
                // everything else
                debug("Extensions require an upgrade or vendor switch");
                return installExtension(reqInfo, instInfo);

            }
        }
    }
    return false;
}
 
Example 18
Source File: ExtensionDependency.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
protected boolean checkExtensions(JarFile jar)
    throws ExtensionInstallationException
{
    Manifest man;
    try {
        man = jar.getManifest();
    } catch (IOException e) {
        return false;
    }

    if (man == null) {
        // The applet does not define a manifest file, so
        // we just assume all dependencies are satisfied.
        return true;
    }

    boolean result = true;
    Attributes attr = man.getMainAttributes();
    if (attr != null) {
        // Let's get the list of declared dependencies
        String value = attr.getValue(Name.EXTENSION_LIST);
        if (value != null) {
            StringTokenizer st = new StringTokenizer(value);
            // Iterate over all declared dependencies
            while (st.hasMoreTokens()) {
                String extensionName = st.nextToken();
                debug("The file " + jar.getName() +
                      " appears to depend on " + extensionName);
                // Sanity Check
                String extName = extensionName + "-" +
                    Name.EXTENSION_NAME.toString();
                if (attr.getValue(extName) == null) {
                    debug("The jar file " + jar.getName() +
                          " appers to depend on "
                          + extensionName + " but does not define the " +
                          extName + " attribute in its manifest ");

                } else {
                    if (!checkExtension(extensionName, attr)) {
                        debug("Failed installing " + extensionName);
                        result = false;
                    }
                }
            }
        } else {
            debug("No dependencies for " + jar.getName());
        }
    }
    return result;
}
 
Example 19
Source File: BundleEntry.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
public BundleEntry(JarEntry entry, InputStream is, BundleContext bundleContext) throws IOException {
    super(entry, is);
    String[] segments = entry.getName().split("\\/");
    String startStr = segments[2];
    if (segments[1].contains(".")) {
        runmode = StringUtils.substringAfter(segments[1], ".");
    } else {
        runmode = null;
    }
    start = Integer.parseInt(startStr, 10);
    log.debug("Loaded start level {}", start);
    try (JarInputStream bundleIs = new JarInputStream(new ByteArrayInputStream(this.getContents()))) {

        Manifest manifest = bundleIs.getManifest();
        Attributes attributes = manifest.getMainAttributes();

        if (attributes.getValue(BUNDLE_SYMBOLIC_NAME).contains(";")) {
            symbolicName = StringUtils.substringBefore(attributes.getValue(BUNDLE_SYMBOLIC_NAME), ";");
        } else {
            symbolicName = attributes.getValue(BUNDLE_SYMBOLIC_NAME);
        }
        log.debug("Loaded symbolic name: {}", symbolicName);

        version = new Version(attributes.getValue("Bundle-Version"));
        log.debug("Loaded version: {}", version);
    }

    Bundle currentBundle = null;
    for (Bundle b : bundleContext.getBundles()) {
        if (b.getSymbolicName().equals(this.symbolicName)) {
            currentBundle = b;
        }
    }
    if (currentBundle != null) {
        installed = true;
        if (currentBundle.getVersion().compareTo(version) < 0) {
            updated = true;
        } else {
            updated = false;
        }
    } else {
        installed = false;
        updated = true;
    }
}
 
Example 20
Source File: EclipseProperties.java    From google-cloud-eclipse with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the host bundle name defined in the manifest of the test fragment bundle.
 * <p>
 * The working directory is assumed to be the root of the fragment bundle (i.e.
 * <code>META-INF/MANIFEST.MF</code> is a valid path to the manifest file of the fragment.
 *
 * @return the value of <code>Fragment-Host</code> attribute or <code>null</code> if the attribute
 *         is not present
 * @throws IOException if the manifest file is not found or an error occurs while reading it
 */
static String getHostBundleName() throws IOException {
  String manifestPath = "META-INF/MANIFEST.MF";
  try (InputStream in = Files.newInputStream(Paths.get(manifestPath))) {
    Manifest manifest = new Manifest(in);
    Attributes attributes = manifest.getMainAttributes();
    return attributes.getValue("Fragment-Host");
  }
}