List of usage examples for java.util.jar Manifest getMainAttributes
public Attributes getMainAttributes()
From source file:org.pentaho.reporting.libraries.base.versioning.VersionHelper.java
/** * Looks up the attributes for the given module specified by <code>name</code> in the given Manifest. * * @param props the manifest where to search for the attributes. * @param name the name of the module./*from w w w . j a va2 s . c o m*/ * @return the attributes for the module or the main attributes if the jar contains no such module. */ private Attributes getAttributes(final Manifest props, final String name) { final Attributes attributes = props.getAttributes(name); if (attributes == null) { return props.getMainAttributes(); } return attributes; }
From source file:com.orange.mmp.module.osgi.MMPOSGiContainer.java
/** * Deploy a module bundle on MMP server//from w w w. j a v a 2 s. co m * @param moduleFile The module file (JAR file) */ @SuppressWarnings("unchecked") public Module deployModule(File moduleFile) throws MMPException { try { JarFile jarFile = new JarFile(new File(moduleFile.toURI())); Manifest manifest = jarFile.getManifest(); if (manifest == null) { throw new MMPException("invalid module archive, MANIFEST file not found"); } // Get Bundle category Attributes attributes = manifest.getMainAttributes(); String category = attributes.getValue(BUNDLE_CATEGORY_HEADER); // Test if the module is a widget if (category != null && category.equals(com.orange.mmp.core.Constants.MODULE_CATEGORY_WIDGET)) { Widget widget = new Widget(); String symbName = attributes.getValue(BUNDLE_SYMBOLICNAME_HEADER); String branch = symbName.split(com.orange.mmp.widget.Constants.BRANCH_SUFFIX_PATTERN)[1]; widget.setLocation(moduleFile.toURI()); widget.setBranchId(branch); DaoManagerFactory.getInstance().getDaoManager().getDao("module").createOrUdpdate(widget); this.lastUpdate = 0; this.refresh(); return widget; } else { Module module = new Module(); module.setLocation(moduleFile.toURI()); DaoManagerFactory.getInstance().getDaoManager().getDao("module").createOrUdpdate(module); this.lastUpdate = 0; this.refresh(); return module; } } catch (IOException ioe) { throw new MMPException("Failed to deploy module", ioe); } }
From source file:org.xwiki.extension.repository.internal.core.DefaultCoreExtensionScanner.java
@Override public DefaultCoreExtension loadEnvironmentExtension(DefaultCoreExtensionRepository repository) { InputStream is = this.environment.getResourceAsStream("/META-INF/MANIFEST.MF"); if (is != null) { // Probably running in an application server try {//from w w w.j a va 2 s .c o m Manifest manifest = new Manifest(is); Attributes manifestAttributes = manifest.getMainAttributes(); String extensionId = manifestAttributes.getValue(MavenUtils.MF_EXTENSION_ID); if (extensionId != null) { String[] mavenId = StringUtils.split(extensionId, ':'); String descriptorPath = String.format("/META-INF/maven/%s/%s/pom.xml", mavenId[0], mavenId[1]); URL descriptorURL = this.environment.getResource(descriptorPath); if (descriptorURL != null) { try { DefaultCoreExtension coreExtension = parseMavenPom(descriptorURL, repository); return coreExtension; } catch (Exception e) { this.logger.warn("Failed to parse extension descriptor [{}]", descriptorURL, e); } } else { this.logger.warn("Can't find resource file [{}] which contains distribution informations.", descriptorPath); } } } catch (IOException e) { this.logger.error("Failed to parse environment META-INF/MANIFEST.MF file", e); } finally { IOUtils.closeQuietly(is); } } this.logger.debug("No declared environmennt extension"); return null; }
From source file:com.github.lindenb.jvarkit.util.command.CommandFactory.java
private void loadManifest() { try {// ww w. ja va2s .co m Enumeration<URL> resources = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");//not '/META-INF' while (resources.hasMoreElements()) { URL url = resources.nextElement(); InputStream in = url.openStream(); if (in == null) { continue; } Manifest m = new Manifest(in); in.close(); in = null; java.util.jar.Attributes attrs = m.getMainAttributes(); if (attrs == null) { continue; } String s = attrs.getValue("Git-Hash"); if (s != null && !s.isEmpty() && !s.contains("$")) //ant failed { this.version = s; } s = attrs.getValue("Compile-Date"); if (s != null && !s.isEmpty()) //ant failed { this.compileDate = s; } } } catch (Exception err) { } }
From source file:net.cliseau.composer.javacor.MissingToolException.java
/** * Create a JAR file for startup of the unit. * * The created JAR file contains all the specified archive files and contains a * manifest which in particular determines the class path for the JAR file. * All files in startupArchiveFileNames are deleted during the execution of * this method.// ww w . ja va 2 s .co m * * @param fileName Name of the file to write the result to. * @param startupArchiveFileNames Names of files to include in the JAR file. * @param startupDependencies Names of classpath entries to include in the JAR file classpath. * @exception IOException Thrown if file operations fail, such as creating the JAR file or reading from the input file(s). */ private void createJAR(final String fileName, final Collection<String> startupArchiveFileNames, final Collection<String> startupDependencies) throws IOException, InvalidConfigurationException { // Code inspired by: // http://www.java2s.com/Code/Java/File-Input-Output/CreateJarfile.htm // http://www.massapi.com/class/java/util/jar/Manifest.java.html // construct manifest with appropriate "Class-path" property Manifest starterManifest = new Manifest(); Attributes starterAttributes = starterManifest.getMainAttributes(); // Remark for those who read this code to learn something: // If one forgets to set the MANIFEST_VERSION attribute, then // silently *nothing* (except for a line break) will be written // to the JAR file manifest! starterAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0"); starterAttributes.put(Attributes.Name.MAIN_CLASS, getStartupName()); starterAttributes.put(Attributes.Name.CLASS_PATH, StringUtils.join(startupDependencies, manifestClassPathSeparator)); // create output JAR file FileOutputStream fos = new FileOutputStream(fileName); JarOutputStream jos = new JarOutputStream(fos, starterManifest); // add the entries for the starter archive's files for (String archFileName : startupArchiveFileNames) { File startupArchiveFile = new File(archFileName); JarEntry startupEntry = new JarEntry(startupArchiveFile.getName()); startupEntry.setTime(startupArchiveFile.lastModified()); jos.putNextEntry(startupEntry); // copy the content of the starter archive's file // TODO: if we used Apache Commons IO 2.1, then the following // code block could be simplified as: // FileUtils.copyFile(startupArchiveFile, jos); FileInputStream fis = new FileInputStream(startupArchiveFile); byte buffer[] = new byte[1024 /*bytes*/]; while (true) { int nRead = fis.read(buffer, 0, buffer.length); if (nRead <= 0) break; jos.write(buffer, 0, nRead); } fis.close(); // end of FileUtils.copyFile() substitution code jos.closeEntry(); startupArchiveFile.delete(); // cleanup the disk a bit } jos.close(); fos.close(); }
From source file:org.krakenapps.main.Kraken.java
private void setBanner() throws IOException { try {/*from w ww . ja v a 2 s. c o m*/ String jarFileName = System.getProperty("java.class.path") .split(System.getProperty("path.separator"))[0]; JarFile jar = new JarFile(jarFileName); Manifest mf = jar.getManifest(); Attributes attrs = mf.getMainAttributes(); BANNER = "Kraken (version " + attrs.getValue("Kraken-Version") + ")"; } catch (FileNotFoundException e) { BANNER = "Kraken (Debug mode)"; } }
From source file:org.kepler.kar.karxml.KarXmlGenerator.java
/** * Read in the main attributes of the KAR and append them to the xml. * /* ww w . j a va 2 s .c om*/ * @throws IOException */ private void appendXmlForMainAttributes() throws IOException { karxml.append(tab + "<mainAttributes>" + nl); // gets the manifest Manifest mf = _karFile.getManifest(); // gets the main attributes in the manifest Attributes atts = mf.getMainAttributes(); if (atts != null) { String lsid = atts.getValue(KARFile.LSID); if (lsid != null) { karxml.append(tab + tab + "<" + KARFile.LSID + ">" + nl); karxml.append(tab + tab + tab + lsid + nl); karxml.append(tab + tab + "</" + KARFile.LSID + ">" + nl); } String moduleDependencies = atts.getValue(KARFile.MOD_DEPEND); if (moduleDependencies != null) { karxml.append(tab + tab + "<" + KARFile.MOD_DEPEND + ">" + nl); karxml.append(tab + tab + tab + moduleDependencies + nl); karxml.append(tab + tab + "</" + KARFile.MOD_DEPEND + ">" + nl); } String karVersion = atts.getValue(KARFile.KAR_VERSION); if (karVersion != null) { karxml.append(tab + tab + "<" + KARFile.KAR_VERSION + ">" + nl); karxml.append(tab + tab + tab + karVersion + nl); karxml.append(tab + tab + "</" + KARFile.KAR_VERSION + ">" + nl); } String manifestVersion = atts.getValue(_manifestVersion); if (manifestVersion != null) { karxml.append(tab + tab + "<" + _manifestVersion + ">" + nl); karxml.append(tab + tab + tab + manifestVersion + nl); karxml.append(tab + tab + "</" + _manifestVersion + ">" + nl); } } // Loop through the attributes /*for (Object att : atts.keySet()) { if (att instanceof Name) { Name attrName = (Name) att; String attrValue = atts.getValue(attrName); karxml.append(tab + tab + "<" + attrName + ">" + nl); karxml.append(tab + tab + tab + attrValue + nl); karxml.append(tab + tab + "</" + attrName + ">" + nl); } else { throw new IOException("Unrecognized Main Attribute"); } }*/ karxml.append(tab + "</mainAttributes>" + nl); //System.out.println("karxml is ==========\n "+karxml.toString()); }
From source file:org.tobarsegais.webapp.ServletContextListenerImpl.java
public void contextInitialized(ServletContextEvent sce) { ServletContext application = sce.getServletContext(); Map<String, String> bundles = new HashMap<String, String>(); Map<String, Toc> contents = new LinkedHashMap<String, Toc>(); List<IndexEntry> keywords = new ArrayList<IndexEntry>(); Directory index = new RAMDirectory(); Analyzer analyzer = new StandardAnalyzer(LUCENE_VERSON); IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_VERSON, analyzer); IndexWriter indexWriter;/*from w ww. j a v a 2 s. c o m*/ try { indexWriter = new IndexWriter(index, indexWriterConfig); } catch (IOException e) { application.log("Cannot create search index. Search will be unavailable.", e); indexWriter = null; } for (String path : (Set<String>) application.getResourcePaths(BUNDLE_PATH)) { if (path.endsWith(".jar")) { String key = path.substring("/WEB-INF/bundles/".length(), path.lastIndexOf(".jar")); application.log("Parsing " + path); URLConnection connection = null; try { URL url = new URL("jar:" + application.getResource(path) + "!/"); connection = url.openConnection(); if (!(connection instanceof JarURLConnection)) { application.log(path + " is not a jar file, ignoring"); continue; } JarURLConnection jarConnection = (JarURLConnection) connection; JarFile jarFile = jarConnection.getJarFile(); Manifest manifest = jarFile.getManifest(); if (manifest != null) { String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName"); if (symbolicName != null) { int i = symbolicName.indexOf(';'); if (i != -1) { symbolicName = symbolicName.substring(0, i); } bundles.put(symbolicName, key); key = symbolicName; } } JarEntry pluginEntry = jarFile.getJarEntry("plugin.xml"); if (pluginEntry == null) { application.log(path + " does not contain a plugin.xml file, ignoring"); continue; } Plugin plugin = Plugin.read(jarFile.getInputStream(pluginEntry)); Extension tocExtension = plugin.getExtension("org.eclipse.help.toc"); if (tocExtension == null || tocExtension.getFile("toc") == null) { application.log(path + " does not contain a 'org.eclipse.help.toc' extension, ignoring"); continue; } JarEntry tocEntry = jarFile.getJarEntry(tocExtension.getFile("toc")); if (tocEntry == null) { application.log(path + " is missing the referenced toc: " + tocExtension.getFile("toc") + ", ignoring"); continue; } Toc toc; try { toc = Toc.read(jarFile.getInputStream(tocEntry)); } catch (IllegalStateException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); continue; } contents.put(key, toc); Extension indexExtension = plugin.getExtension("org.eclipse.help.index"); if (indexExtension != null && indexExtension.getFile("index") != null) { JarEntry indexEntry = jarFile.getJarEntry(indexExtension.getFile("index")); if (indexEntry != null) { try { keywords.addAll(Index.read(key, jarFile.getInputStream(indexEntry)).getChildren()); } catch (IllegalStateException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } } else { application.log( path + " is missing the referenced index: " + indexExtension.getFile("index")); } } application.log(path + " successfully parsed and added as " + key); if (indexWriter != null) { application.log("Indexing content of " + path); Set<String> files = new HashSet<String>(); Stack<Iterator<? extends TocEntry>> stack = new Stack<Iterator<? extends TocEntry>>(); stack.push(Collections.singleton(toc).iterator()); while (!stack.empty()) { Iterator<? extends TocEntry> cur = stack.pop(); if (cur.hasNext()) { TocEntry entry = cur.next(); stack.push(cur); if (!entry.getChildren().isEmpty()) { stack.push(entry.getChildren().iterator()); } String file = entry.getHref(); if (file == null) { continue; } int hashIndex = file.indexOf('#'); if (hashIndex != -1) { file = file.substring(0, hashIndex); } if (files.contains(file)) { // already indexed // todo work out whether to just pull the section continue; } Document document = new Document(); document.add(new Field("title", entry.getLabel(), Field.Store.YES, Field.Index.ANALYZED)); document.add(new Field("href", key + "/" + entry.getHref(), Field.Store.YES, Field.Index.NO)); JarEntry docEntry = jarFile.getJarEntry(file); if (docEntry == null) { // ignore missing file continue; } InputStream inputStream = null; try { inputStream = jarFile.getInputStream(docEntry); org.jsoup.nodes.Document docDoc = Jsoup.parse(IOUtils.toString(inputStream)); document.add(new Field("contents", docDoc.body().text(), Field.Store.NO, Field.Index.ANALYZED)); indexWriter.addDocument(document); } finally { IOUtils.closeQuietly(inputStream); } } } } } catch (XMLStreamException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } catch (MalformedURLException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } catch (IOException e) { application.log("Could not parse " + path + " due to " + e.getMessage(), e); } finally { if (connection instanceof HttpURLConnection) { // should never be the case, but we should try to be sure ((HttpURLConnection) connection).disconnect(); } } } } if (indexWriter != null) { try { indexWriter.close(); } catch (IOException e) { application.log("Cannot create search index. Search will be unavailable.", e); } application.setAttribute("index", index); } application.setAttribute("toc", Collections.unmodifiableMap(contents)); application.setAttribute("keywords", new Index(keywords)); application.setAttribute("bundles", Collections.unmodifiableMap(bundles)); application.setAttribute("analyzer", analyzer); application.setAttribute("contentsQueryParser", new QueryParser(LUCENE_VERSON, "contents", analyzer)); }
From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java
@Test public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException { String expected = "1.4"; // Write the manifest, setting the implementation version Path tmp = folder.newFolder(); Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0"); manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected); Path manifestFile = tmp.resolve("manifest"); try (OutputStream fos = Files.newOutputStream(manifestFile)) { manifest.write(fos);/*from w w w .ja v a 2 s .co m*/ } // Write another manifest, setting the implementation version to something else manifest = new Manifest(); manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0"); manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0"); Path input = tmp.resolve("input.jar"); try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) { ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF"); out.putNextEntry(entry); manifest.write(out); } Path output = tmp.resolve("output.jar"); JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output, ImmutableSortedSet.of(Paths.get("input.jar")), /* main class */ null, tmp.resolve("manifest"), /* merge manifest */ true, /* blacklist */ ImmutableSet.of()); ExecutionContext context = TestExecutionContext.newInstance(); assertEquals(0, step.execute(context).getExitCode()); try (Zip zip = new Zip(output, false)) { byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF"); manifest = new Manifest(new ByteArrayInputStream(rawManifest)); String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION); assertEquals(expected, version); } }
From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarCreator.java
/** * Actual jar creation.//from w w w .j a v a 2s. c o m * * @param manifest to use * @param entries array of resource to include in the jar * @return the number of bytes written to the underlying stream. * * @throws IOException */ protected int addJarContent(Manifest manifest, Map entries) throws IOException { // load manifest // add it to the jar if (log.isTraceEnabled()) { if (manifest != null) log.trace("Adding MANIFEST.MF [" + manifest.getMainAttributes().entrySet() + "]"); log.trace("Adding entries:"); Set key = entries.keySet(); for (Iterator iter = key.iterator(); iter.hasNext();) { log.trace(iter.next()); } } return JarUtils.createJar(manifest, entries, storage.getOutputStream()); }