下面列出了java.util.jar.JarFile#getManifest ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
public List<File> getJarClassPath(File file) throws IOException {
String parent = file.getParent();
JarFile jarFile = new JarFile(file);
try {
Manifest man = jarFile.getManifest();
if (man == null)
return Collections.emptyList();
Attributes attr = man.getMainAttributes();
if (attr == null)
return Collections.emptyList();
String path = attr.getValue(Attributes.Name.CLASS_PATH);
if (path == null)
return Collections.emptyList();
List<File> list = new ArrayList<File>();
for (StringTokenizer st = new StringTokenizer(path); st.hasMoreTokens(); ) {
String elt = st.nextToken();
File f = (parent == null ? new File(elt) : new File(parent, elt));
list.add(f);
}
return list;
} finally {
jarFile.close();
}
}
private void addJarClassPath(String jarFileName, boolean warn) {
try {
String jarParent = new File(jarFileName).getParent();
JarFile jar = new JarFile(jarFileName);
try {
Manifest man = jar.getManifest();
if (man == null) return;
Attributes attr = man.getMainAttributes();
if (attr == null) return;
String path = attr.getValue(Attributes.Name.CLASS_PATH);
if (path == null) return;
for (StringTokenizer st = new StringTokenizer(path);
st.hasMoreTokens();) {
String elt = st.nextToken();
if (jarParent != null)
elt = new File(jarParent, elt).getCanonicalPath();
addFile(elt, warn);
}
} finally {
jar.close();
}
} catch (IOException e) {
// log.error(Position.NOPOS,
// "error.reading.file", jarFileName,
// e.getLocalizedMessage());
}
}
private static Manifest getManifest(File jar) throws IOException {
JarFile jf = new JarFile(jar);
try {
return jf.getManifest();
} finally {
jf.close();
}
}
public Manifest getManifest() {
assertIsFile();
try {
JarFile jarFile = new JarFile(this);
try {
return jarFile.getManifest();
} finally {
jarFile.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static boolean isOSGiBundle(File jarFile) {
try {
JarFile jar = new JarFile(jarFile);
Manifest mf = jar.getManifest();
return mf != null && mf.getMainAttributes().getValue("Bundle-SymbolicName") != null; // NOI18N
} catch (IOException ioe) {
ERR.log(Level.INFO, ioe.getLocalizedMessage(), ioe);
}
return false;
}
public void testPackageDependencyMayfail() throws Exception {
//see #63904:
MockModuleInstaller installer = new MockModuleInstaller();
MockEvents ev = new MockEvents();
ModuleManager mgr = new ModuleManager(installer, ev);
mgr.mutexPrivileged().enterWriteAccess();
try {
Manifest mani;
JarFile jf = new JarFile(new File(jars, "simple-module.jar"));
try {
mani = jf.getManifest();
} finally {
jf.close();
}
Module toFail = mgr.create(new File(jars, "fails-on-non-existing-package.jar"), null, false, false, false);
Module fixed = mgr.createFixed(mani, null, this.getClass().getClassLoader());
try {
mgr.enable(new HashSet<Module>(Arrays.asList(toFail, fixed)));
fail("Was able to turn on fails-on-non-existing-package.jar without complaint");
} catch (InvalidException e) {
assertTrue("fails-on-non-existing-package.jar was not enabled", e.getModule() == toFail);
}
assertTrue("simple-module.jar was enabled", fixed.isEnabled());
} finally {
mgr.mutexPrivileged().exitWriteAccess();
}
}
private void addJarClassPath(String jarFileName, boolean warn) {
try {
String jarParent = new File(jarFileName).getParent();
JarFile jar = new JarFile(jarFileName);
try {
Manifest man = jar.getManifest();
if (man == null) return;
Attributes attr = man.getMainAttributes();
if (attr == null) return;
String path = attr.getValue(Attributes.Name.CLASS_PATH);
if (path == null) return;
for (StringTokenizer st = new StringTokenizer(path);
st.hasMoreTokens();) {
String elt = st.nextToken();
if (jarParent != null)
elt = new File(jarParent, elt).getCanonicalPath();
addFile(elt, warn);
}
} finally {
jar.close();
}
} catch (IOException e) {
// log.error(Position.NOPOS,
// "error.reading.file", jarFileName,
// e.getLocalizedMessage());
}
}
private static void extendLibrariesManifests(
final Project prj,
final File mainJar,
final List<? extends File> libraries) throws IOException {
String codebase = null;
String permissions = null;
String appName = null;
final JarFile jf = new JarFile(mainJar);
try {
final java.util.jar.Manifest mf = jf.getManifest();
if (mf != null) {
final Attributes attrs = mf.getMainAttributes();
codebase = attrs.getValue(ATTR_CODEBASE);
permissions = attrs.getValue(ATTR_PERMISSIONS);
appName = attrs.getValue(ATTR_APPLICATION_NAME);
}
} finally {
jf.close();
}
prj.log(
String.format(
"Application: %s manifest: Codebase: %s, Permissions: %s, Application-Name: %s", //NOI18N
safeRelativePath(prj.getBaseDir(), mainJar),
codebase,
permissions,
appName),
Project.MSG_VERBOSE);
if (codebase != null || permissions != null || appName != null) {
for (File library : libraries) {
try {
extendLibraryManifest(prj, library, codebase, permissions, appName);
} catch (ManifestException mex) {
throw new IOException(mex);
}
}
}
}
public List<File> getJarClassPath(File file) throws IOException {
String parent = file.getParent();
JarFile jarFile = new JarFile(file);
try {
Manifest man = jarFile.getManifest();
if (man == null)
return Collections.emptyList();
Attributes attr = man.getMainAttributes();
if (attr == null)
return Collections.emptyList();
String path = attr.getValue(Attributes.Name.CLASS_PATH);
if (path == null)
return Collections.emptyList();
List<File> list = new ArrayList<File>();
for (StringTokenizer st = new StringTokenizer(path); st.hasMoreTokens(); ) {
String elt = st.nextToken();
File f = (parent == null ? new File(elt) : new File(parent, elt));
list.add(f);
}
return list;
} finally {
jarFile.close();
}
}
/**
* Recursively verify that a jar file, and any urls mentioned
* in its class path, do not conflict with the target jar file.
*
* @param indent is the current nesting level
* @param url is the path to the jar file being checked.
* @return true if there is no newer URL, otherwise false
*/
private boolean checkURLRecursively(int indent, URL url)
throws IOException
{
verboseMessage("Comparing with " + url);
JarLoader jarloader = new JarLoader(url);
JarFile j = jarloader.getJarFile();
Manifest man = j.getManifest();
if (man != null) {
Attributes attr = man.getMainAttributes();
if (attr != null){
String title = attr.getValue(Name.SPECIFICATION_TITLE);
String version = attr.getValue(Name.SPECIFICATION_VERSION);
String vendor = attr.getValue(Name.SPECIFICATION_VENDOR);
String implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
String implVersion
= attr.getValue(Name.IMPLEMENTATION_VERSION);
String implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
String sealed = attr.getValue(Name.SEALED);
if (title != null){
if (title.equals(targetSpecTitle)){
if (version != null){
if (version.equals(targetSpecVersion) ||
isNotOlderThan(version,targetSpecVersion)){
verboseMessage("");
verboseMessage("CONFLICT DETECTED ");
verboseMessage("Conflicting file:"+ url);
verboseMessage("Installed Version:" +
version);
if (implTitle != null)
verboseMessage("Implementation Title:"+
implTitle);
if (implVersion != null)
verboseMessage("Implementation Version:"+
implVersion);
if (implVendor != null)
verboseMessage("Implementation Vendor:"+
implVendor);
return false;
}
}
}
}
}
}
boolean result = true;
URL[] loaderList = jarloader.getClassPath();
if (loaderList != null) {
for(int i=0; i < loaderList.length; i++){
if (url != null){
boolean res = checkURLRecursively(indent+1,loaderList[i]);
result = res && result;
}
}
}
return result;
}
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;
}
private void assertJarFileManifestClassPath(final File dependenciesJar, final Collection<String> expectedJarDependencies)
throws IOException
{
JarFile dependenciesJarFile = new JarFile(dependenciesJar);
Manifest manifest = dependenciesJarFile.getManifest();
assertNotNull(manifest);
Attributes attributes = manifest.getMainAttributes();
assertNotNull(attributes);
assertTrue(attributes.containsKey(Name.CLASS_PATH));
String[] actualJarDependencies = attributes.getValue(Name.CLASS_PATH).split(" ");
assertNotNull(actualJarDependencies);
assertTrue(String.format("Expected the actual number of JAR dependencies to be (%1$d); but was (%2$d)!",
expectedJarDependencies.size(), actualJarDependencies.length),
actualJarDependencies.length >= expectedJarDependencies.size());
//assertTrue(Arrays.asList(actualJarDependencies).containsAll(expectedJarDependencies));
List<String> actualJarDependenciesList = new ArrayList<String>(Arrays.asList(actualJarDependencies));
List<String> missingExpectedJarDependenciesList = new ArrayList<String>(expectedJarDependencies.size());
for (String expectedJarDependency : expectedJarDependencies) {
boolean containsExpectedJar = false;
for (int index = 0, size = actualJarDependenciesList.size(); index < size; index++) {
if (actualJarDependenciesList.get(index).toLowerCase().contains(expectedJarDependency.toLowerCase())) {
actualJarDependenciesList.remove(index);
containsExpectedJar = true;
break;
}
}
if (!containsExpectedJar) {
missingExpectedJarDependenciesList.add(expectedJarDependency);
}
}
assertTrue(String.format("GemFire dependencies JAR file (%1$s) does not contain the expected dependencies (%2$s) in the Manifest Class-Path attribute (%3$s)!",
dependenciesJar, missingExpectedJarDependenciesList, attributes.getValue(Name.CLASS_PATH)),
missingExpectedJarDependenciesList.isEmpty());
}
private static TomcatVersion getTomcatVersionFallback(File catalinaHome) throws IllegalStateException {
File lib = new File(catalinaHome, "common" + File.separator + "lib"); // NOI18N
if (lib.isDirectory()) {
// 5 or 5.5
File tasks = new File(catalinaHome, "bin" + File.separator + "catalina-tasks.xml"); // NOI18N
if (tasks.isFile()) {
// 5.5
return TomcatVersion.TOMCAT_55;
}
return TomcatVersion.TOMCAT_50;
} else {
// 6 or 7 or 8
File bootstrapJar = new File(catalinaHome, "bin" + File.separator + "bootstrap.jar"); // NOI18N
if (!bootstrapJar.exists()) {
return null;
}
try {
JarFile jar = new JarFile(bootstrapJar);
try {
Manifest manifest = jar.getManifest();
String specificationVersion = null;
if (manifest != null) {
specificationVersion = manifest.getMainAttributes()
.getValue("Specification-Version"); // NOI18N
}
if (specificationVersion != null) { // NOI18N
specificationVersion = specificationVersion.trim();
return getTomcatVersion(specificationVersion, TomcatVersion.TOMCAT_55);
}
} finally {
try {
jar.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex);
}
}
} catch (IOException e) {
LOGGER.log(Level.FINE, null, e);
}
}
return TomcatVersion.TOMCAT_50;
}
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;
}
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;
}
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;
}
/**
* This method publish all the layer into the plugin jar.
* @param jarBuffer Plugin jar.
* @return Plugin instance.
*/
public static synchronized Plugin publishPlugin(ByteBuffer jarBuffer) {
String pluginGroupName = Strings.EMPTY_STRING;
String pluginName = Strings.EMPTY_STRING;
Version pluginVersion = null;
Plugin result = null;
try {
File tempFile = File.createTempFile("."+UUID.randomUUID().toString(), "tmp");
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(jarBuffer.array());
fos.flush();
fos.close();
JarFile jarFile = new JarFile(tempFile);
Manifest manifest = jarFile.getManifest();
Attributes pluginAttributes = manifest.getMainAttributes();
pluginGroupName = pluginAttributes.getValue(PLUGIN_GROUP_NAME);
if(pluginGroupName == null) {
throw new HCJFRuntimeException("Plugin group name is not specified into the manifest file (Plugin-Group-Name)");
}
pluginName = pluginAttributes.getValue(PLUGIN_NAME);
if(pluginName == null) {
throw new HCJFRuntimeException("Plugin name is not specified into the manifest file (Plugin-Name)");
}
pluginVersion = Version.build(pluginAttributes.getValue(PLUGIN_VERSION));
result = new Plugin(pluginGroupName, pluginName, pluginVersion);
boolean deployPlugin = false;
if(instance.plugins.contains(result)) {
int currentIndex = instance.plugins.indexOf(result);
if(!instance.plugins.get(currentIndex).getVersion().equals(result.getVersion())) {
Plugin currentPlugin = instance.plugins.remove(currentIndex);
if(currentPlugin.getVersion().compareTo(result.getVersion()) > 0) {
Log.d(SystemProperties.get(SystemProperties.Layer.LOG_TAG), "Downgrade plugin version %s.%s:%s -> %s",
pluginGroupName, pluginName, currentPlugin.getVersion().toString(), pluginVersion.toString());
} else {
Log.d(SystemProperties.get(SystemProperties.Layer.LOG_TAG), "Upgrade plugin version %s.%s:%s -> %s",
pluginGroupName, pluginName, currentPlugin.getVersion().toString(), pluginVersion.toString());
}
deployPlugin = true;
}
} else {
deployPlugin = true;
}
if(deployPlugin) {
instance.plugins.add(result);
String[] layers = pluginAttributes.getValue(LAYERS).split(CLASS_SEPARATOR);
Log.d(SystemProperties.get(SystemProperties.Layer.LOG_TAG), "Deploying plugin %s.%s:%s", pluginGroupName, pluginName, pluginVersion.toString());
URLClassLoader pluginClassLoader = new PluginClassLoader(result, new URL[]{tempFile.toURI().toURL()},
instance.getClass().getClassLoader());
Class<? extends Layer> layerClass;
List<Layer> toDeployLayers = new ArrayList<>();
Layer layer;
for (String layerClassName : layers) {
Log.d(SystemProperties.get(SystemProperties.Layer.LOG_TAG), "Loading layer %s", layerClassName);
layerClass = (Class<? extends Layer>) Class.forName(layerClassName, true, pluginClassLoader);
result.addLayer(layerClass);
layer = layerClass.getConstructor().newInstance();
toDeployLayers.add(layer);
Log.d(SystemProperties.get(SystemProperties.Layer.LOG_TAG), "Layer %s loaded", layer.getImplName());
}
for (Layer layerInstance : toDeployLayers) {
instance.pluginCache.remove(layerInstance.getClass().getName());
instance.pluginCache.put(layerInstance.getClass().getName(), layerInstance);
for (Class<? extends LayerInterface> layerInterfaceClass : getLayerInterfaceClass(layerInstance.getClass())) {
if (!instance.pluginLayerImplementations.containsKey(layerInterfaceClass)) {
instance.pluginLayerImplementations.put(layerInterfaceClass, new HashMap<>());
}
if (!instance.pluginLayerImplementations.get(layerInterfaceClass).containsKey(layerInstance.getImplName())) {
instance.pluginLayerImplementations.get(layerInterfaceClass).put(layerInstance.getImplName(), layerInstance.getClass().getName());
}
}
}
} else {
Log.d(SystemProperties.get(SystemProperties.Layer.LOG_TAG), "Exists a plugin deployment in the same group with the same name and version: %s.%s:%s", pluginGroupName, pluginName, pluginVersion.toString());
}
} catch (Exception ex) {
Log.d(SystemProperties.get(SystemProperties.Layer.LOG_TAG), "Plugin deployment fail %s.%s", ex, pluginGroupName, pluginName);
}
return result;
}
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;
}
/** Scan a disabled module JAR file for its manifest contents.
* Subclasses may implement this efficiently, e.g. to use a special cache.
* <p>The default implementation simply opens the JAR and gets its manifest
* using the standard JRE calls.
* <p>Never called for reloadable JARs.
* @param jar a module JAR to open
* @return its manifest
* @throws IOException if the JAR cannot be opened or does not have a manifest at all
* @since org.netbeans.core/1 1.5
* @see "#26786"
*/
public Manifest loadManifest(File jar) throws IOException {
JarFile jarFile = new JarFile(jar, false);
try {
Manifest m = jarFile.getManifest();
if (m == null) throw new IOException("No manifest found in " + jar); // NOI18N
return m;
} finally {
jarFile.close();
}
}