List of usage examples for java.util.jar JarFile getManifest
public Manifest getManifest() throws IOException
From source file:org.pepstock.jem.node.NodeInfoUtility.java
/** * Extracts from manifest file the attribute passed by argument * @param what name of attribute to get/*from w ww . j a v a 2 s . c om*/ * @return attribute value or null, if doesn't exist */ public static String getManifestAttribute(String what) { JarFile jarFile = null; try { // gets JAR file jarFile = new JarFile(new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI())); // gets attributes Attributes at = (Attributes) jarFile.getManifest().getAttributes(ConfigKeys.JEM_MANIFEST_SECTION); // gets version return at.getValue(ConfigKeys.JEM_MANIFEST_VERSION); } catch (IOException e) { // ignore the stack trace LogAppl.getInstance().ignore(e.getMessage(), e); LogAppl.getInstance().emit(NodeMessage.JEMC184W); } catch (URISyntaxException e) { // ignore the stack trace LogAppl.getInstance().ignore(e.getMessage(), e); LogAppl.getInstance().emit(NodeMessage.JEMC184W); } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { // debug LogAppl.getInstance().debug(e.getMessage(), e); } } } return null; }
From source file:ml.shifu.shifu.util.ShifuCLI.java
/** * print version info for shifu/*w ww .j av a2s. 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:com.qmetry.qaf.automation.core.ConfigurationManager.java
private static Map<String, String> getBuildInfo() { Manifest manifest = null;//from w w w . jav a 2 s.co m Map<String, String> buildInfo = new HashMap<String, String>(); JarFile jar = null; try { URL url = ConfigurationManager.class.getProtectionDomain().getCodeSource().getLocation(); File file = new File(url.toURI()); jar = new JarFile(file); manifest = jar.getManifest(); } catch (NullPointerException ignored) { } catch (URISyntaxException ignored) { } catch (IOException ignored) { } catch (IllegalArgumentException ignored) { } finally { if (null != jar) try { jar.close(); } catch (IOException e) { log.warn(e.getMessage()); } } if (manifest == null) { return buildInfo; } try { Attributes attributes = manifest.getAttributes("Build-Info"); Set<Entry<Object, Object>> entries = attributes.entrySet(); for (Entry<Object, Object> e : entries) { buildInfo.put(String.valueOf(e.getKey()), String.valueOf(e.getValue())); } } catch (NullPointerException e) { // Fall through } return buildInfo; }
From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java
private static Pair<Artifact, byte[]> extractPacked(JarFile jar, ModList modlist, File... modDirs) throws IOException { Attributes attrs;//ww w . ja va 2s . com if (jar.getManifest() == null) return null; JarEntry manifest_entry = jar.getJarEntry(JarFile.MANIFEST_NAME); if (manifest_entry == null) manifest_entry = jar.stream() .filter(e -> JarFile.MANIFEST_NAME.equals(e.getName().toUpperCase(Locale.ENGLISH))).findFirst() .get(); //We know that getManifest returned non-null so we know there is *some* entry that matches the manifest file. So we dont need to empty check. attrs = jar.getManifest().getMainAttributes(); String modSide = attrs.getValue(LibraryManager.MODSIDE); if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide)) return null; if (attrs.containsKey(MODCONTAINSDEPS)) { for (String dep : attrs.getValue(MODCONTAINSDEPS).split(" ")) { if (!dep.endsWith(".jar")) { FMLLog.log.error("Contained Dep is not a jar file: {}", dep); throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep); } if (jar.getJarEntry(dep) == null && jar.getJarEntry("META-INF/libraries/" + dep) != null) dep = "META-INF/libraries/" + dep; JarEntry depEntry = jar.getJarEntry(dep); if (depEntry == null) { FMLLog.log.error("Contained Dep is not in the jar: {}", dep); throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep); } String depEndName = new File(dep).getName(); // extract last part of name if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) { FMLLog.log.error("Skipping dep at request: {}", dep); continue; } Attributes meta = null; byte[] data = null; byte[] manifest_data = null; JarEntry metaEntry = jar.getJarEntry(dep + ".meta"); if (metaEntry != null) { manifest_data = readAll(jar.getInputStream(metaEntry)); meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes(); } else { data = readAll(jar.getInputStream(depEntry)); try (ZipInputStream zi = new ZipInputStream(new ByteArrayInputStream(data))) //We use zip input stream directly, as the current Oracle implementation of JarInputStream only works when the manifest is the First/Second entry in the jar... { ZipEntry ze = null; while ((ze = zi.getNextEntry()) != null) { if (ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) { manifest_data = readAll(zi); meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes(); break; } } } } if (meta == null || !meta.containsKey(MAVEN_ARTIFACT)) //Ugh I really don't want to do backwards compatibility here, I want to force modders to provide information... TODO: Remove in 1.13? { boolean found = false; for (File dir : modDirs) { File target = new File(dir, depEndName); if (target.exists()) { FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction", target.getCanonicalPath()); found = true; } } if (!found) { File target = new File(modDirs[0], depEndName); FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath()); try { Files.createParentDirs(target); try (FileOutputStream out = new FileOutputStream(target); InputStream in = data == null ? jar.getInputStream(depEntry) : new ByteArrayInputStream(data)) { ByteStreams.copy(in, out); } FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(), target.getCanonicalPath()); extractPacked(target, modlist, modDirs); } catch (IOException e) { FMLLog.log.error("An error occurred extracting dependency", e); } } } else { try { Artifact artifact = readArtifact(modlist.getRepository(), meta); File target = artifact.getFile(); if (target.exists()) { FMLLog.log.debug( "Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction", dep, artifact.toString(), target.getCanonicalPath(), jar.getName()); if (!ENABLE_AUTO_MOD_MOVEMENT) { Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down. if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one. { modlist.add(artifact); } } } else { FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath()); Files.createParentDirs(target); try (FileOutputStream out = new FileOutputStream(target); InputStream in = data == null ? jar.getInputStream(depEntry) : new ByteArrayInputStream(data)) { ByteStreams.copy(in, out); } FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep, artifact.toString(), jar.getName(), target.getCanonicalPath()); if (artifact.isSnapshot()) { SnapshotJson json = SnapshotJson.create(artifact.getSnapshotMeta()); json.add(new SnapshotJson.Entry(artifact.getTimestamp(), meta.getValue(MD5))); json.write(artifact.getSnapshotMeta()); } if (!DISABLE_EXTERNAL_MANIFEST) { File meta_target = new File(target.getAbsolutePath() + ".meta"); Files.write(manifest_data, meta_target); } Pair<?, ?> child = extractPacked(target, modlist, modDirs); if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one. { modlist.add(artifact); } } } catch (NumberFormatException nfe) { FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage( "An error occurred extracting dependency. Invalid Timestamp: {}", meta.getValue(TIMESTAMP)), nfe); } catch (IOException e) { FMLLog.log.error("An error occurred extracting dependency", e); } } } } if (attrs.containsKey(MAVEN_ARTIFACT)) { Artifact artifact = readArtifact(modlist.getRepository(), attrs); modlist.add(artifact); return Pair.of(artifact, readAll(jar.getInputStream(manifest_entry))); } return null; }
From source file:com.dtolabs.rundeck.ExpandRunServer.java
/** * Load the manifest main attributes from the enclosing jar * * @return/*from ww w.j ava 2 s . c om*/ */ private static Attributes getJarMainAttributes() { Attributes mainAttributes = null; try { final File file = thisJarFile(); final JarFile jarFile = new JarFile(file); mainAttributes = jarFile.getManifest().getMainAttributes(); } catch (IOException e) { e.printStackTrace(); } return mainAttributes; }
From source file:org.apache.axis2.jaxws.description.builder.JAXWSRIWSDLGenerator.java
/** * Walk the classloader hierarchy and add to the classpath * * @param cl/*from w ww . ja va 2s .co m*/ * @param classpath */ private static void fillClassPath(ClassLoader cl, HashSet classpath) { while (cl != null) { if (cl instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) cl).getURLs(); for (int i = 0; (urls != null) && i < urls.length; i++) { String path = urls[i].getPath(); //If it is a drive letter, adjust accordingly. if (path.length() >= 3 && path.charAt(0) == '/' && path.charAt(2) == ':') path = path.substring(1); addPath(classpath, URLDecoder.decode(path)); // if its a jar extract Class-Path entries from manifest File file = new File(urls[i].getFile()); if (file.isFile()) { FileInputStream fis = null; try { fis = new FileInputStream(file); if (isJar(fis)) { JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attributes = manifest.getMainAttributes(); if (attributes != null) { String s = attributes.getValue(Attributes.Name.CLASS_PATH); String base = file.getParent(); if (s != null) { StringTokenizer st = new StringTokenizer(s, " "); while (st.hasMoreTokens()) { String t = st.nextToken(); addPath(classpath, base + File.separatorChar + t); } } } } } } catch (IOException ioe) { } finally { if (fis != null) { try { fis.close(); } catch (IOException ioe2) { } } } } } } cl = cl.getParent(); } }
From source file:umbrella.Umbrella.java
/** * Builds an analyzer instance based on a jar file. * @param file The jar file.// w ww . ja v a2 s. co m * @param relativePath A relative path which is prepended to all elements. * @return The analyzer. * @throws IOException Occurs if reading any class path element is not possible. */ public static Analyzer getAnalyzer(@NonNull JarFile file, @NonNull String relativePath) throws IOException { // fix relative path if (relativePath == null) relativePath = ""; // grab manifest Manifest manifest = file.getManifest(); // log getLogger().debug("Searching for class-path information within the jar ..."); // get class path String classPath = manifest.getMainAttributes().getValue("Class-Path"); // search Class-Path attribute if (classPath == null) return null; // create basic analyzer Analyzer analyzer = new Analyzer(); // reset analyzer analyzer.reset(); // append all elements for (String element : Splitter.on(' ').omitEmptyStrings().splitToList(classPath)) { // create file File elementFile = new File(relativePath + element); // log getLogger().debug("Adding \"" + element + "\" to the analyzer class path."); // add adapter analyzer.addAdapter((elementFile.isDirectory() ? new ExplodedAnalyzerAdapter(elementFile) : new JarAnalyzerAdapter(new JarFile(elementFile)))); } // return finished analyzer instance return analyzer; }
From source file:ar.edu.taco.TacoMain.java
/** * // w w w .java 2s. c o m */ private static String getManifestAttribute(Name name) { String manifestAttributeValue = "Undefined"; try { String jarFileName = System.getProperty("java.class.path") .split(System.getProperty("path.separator"))[0]; JarFile jar = new JarFile(jarFileName); Manifest manifest = jar.getManifest(); Attributes mainAttributes = manifest.getMainAttributes(); manifestAttributeValue = mainAttributes.getValue(name); jar.close(); } catch (IOException e) { } return manifestAttributeValue; }
From source file:org.hyperic.hq.plugin.jboss.JBossDetector.java
public static String getVersion(File installPath, String jar) { File file = new File(installPath, "lib" + File.separator + jar); if (!file.exists()) { log.debug("[getVersion] file '" + file + "' not found"); return null; }//from ww w .jav a 2 s . c o m Attributes attributes; try { JarFile jarFile = new JarFile(file); log.debug("[getVersion] jarFile='" + jarFile.getName() + "'"); attributes = jarFile.getManifest().getMainAttributes(); jarFile.close(); } catch (IOException e) { log.debug(e, e); return null; } //e.g. Implementation-Version: //3.0.6 Date:200301260037 //3.2.1 (build: CVSTag=JBoss_3_2_1 date=200306201521) //3.2.2 (build: CVSTag=JBoss_3_2_2 date=200310182216) //3.2.3 (build: CVSTag=JBoss_3_2_3 date=200311301445) //4.0.0DR2 (build: CVSTag=JBoss_4_0_0_DR2 date=200307030107) //5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221) String version = attributes.getValue("Implementation-Version"); log.debug("[getVersion] version='" + version + "'"); if (version == null) { return null; } if (version.length() < 3) { return null; } if (!(Character.isDigit(version.charAt(0)) && (version.charAt(1) == '.') && Character.isDigit(version.charAt(2)))) { return null; } return version; }
From source file:net.minecraftforge.fml.relauncher.CoreModManager.java
private static Map<String, File> extractContainedDepJars(JarFile jar, File baseModsDir, File versionedModsDir) throws IOException { Map<String, File> result = Maps.newHashMap(); if (!jar.getManifest().getMainAttributes().containsKey(MODCONTAINSDEPS)) return result; String deps = jar.getManifest().getMainAttributes().getValue(MODCONTAINSDEPS); String[] depList = deps.split(" "); for (String dep : depList) { String depEndName = new File(dep).getName(); // extract last part of name if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) { FMLRelaunchLog.log(Level.ERROR, "Skipping dep at request: %s", dep); continue; }/*from w w w . j a v a2 s .c o m*/ final JarEntry jarEntry = jar.getJarEntry(dep); if (jarEntry == null) { FMLRelaunchLog.log(Level.ERROR, "Found invalid ContainsDeps declaration %s in %s", dep, jar.getName()); continue; } File target = new File(versionedModsDir, depEndName); File modTarget = new File(baseModsDir, depEndName); if (target.exists()) { FMLRelaunchLog.log(Level.DEBUG, "Found existing ContainsDep extracted to %s, skipping extraction", target.getCanonicalPath()); result.put(dep, target); continue; } else if (modTarget.exists()) { FMLRelaunchLog.log(Level.DEBUG, "Found ContainsDep in main mods directory at %s, skipping extraction", modTarget.getCanonicalPath()); result.put(dep, modTarget); continue; } FMLRelaunchLog.log(Level.DEBUG, "Extracting ContainedDep %s from %s to %s", dep, jar.getName(), target.getCanonicalPath()); try { Files.createParentDirs(target); FileOutputStream targetOutputStream = null; InputStream jarInputStream = null; try { targetOutputStream = new FileOutputStream(target); jarInputStream = jar.getInputStream(jarEntry); ByteStreams.copy(jarInputStream, targetOutputStream); } finally { IOUtils.closeQuietly(targetOutputStream); IOUtils.closeQuietly(jarInputStream); } FMLRelaunchLog.log(Level.DEBUG, "Extracted ContainedDep %s from %s to %s", dep, jar.getName(), target.getCanonicalPath()); result.put(dep, target); } catch (IOException e) { FMLRelaunchLog.log(Level.ERROR, e, "An error occurred extracting dependency"); } } return result; }