List of usage examples for java.util.jar Manifest getMainAttributes
public Attributes getMainAttributes()
From source file:edu.cmu.tetrad.cli.util.Args.java
public static void showHelp(String algorithmName, Options options) { StringBuilder sb = new StringBuilder("java -jar"); try {/* w w w. j av a 2s . c o m*/ JarFile jarFile = new JarFile(Args.class.getProtectionDomain().getCodeSource().getLocation().getPath(), true); Manifest manifest = jarFile.getManifest(); Attributes attributes = manifest.getMainAttributes(); String artifactId = attributes.getValue("Implementation-Title"); String version = attributes.getValue("Implementation-Version"); sb.append(String.format(" %s-%s.jar", artifactId, version)); } catch (IOException exception) { sb.append(" causal-cmd.jar"); } sb.append(" --algorithm "); sb.append(algorithmName); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(-1); formatter.printHelp(sb.toString(), options, true); }
From source file:org.broadleafcommerce.common.extensibility.InstrumentationRuntimeFactory.java
private static boolean validateAgentJarManifest(File agentJarFile, String agentClassName) { try {/* w ww. j av a2 s . c o m*/ JarFile jar = new JarFile(agentJarFile); Manifest manifest = jar.getManifest(); if (manifest == null) { return false; } Attributes attributes = manifest.getMainAttributes(); String ac = attributes.getValue("Agent-Class"); if (ac != null && ac.equals(agentClassName)) { return true; } } catch (Exception e) { if (LOG.isTraceEnabled()) { LOG.trace("Unexpected exception occured.", e); } } return false; }
From source file:org.ebayopensource.turmeric.tools.codegen.util.ClassPathUtil.java
private static List<File> getJarClassPathRefs(File file) { List<File> refs = new ArrayList<File>(); JarFile jar = null;/*from w ww .j a v a2s .c o m*/ try { jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest == null) { // No manifest, no classpath. return refs; } Attributes attrs = manifest.getMainAttributes(); if (attrs == null) { /* * No main attributes. (not sure how that's possible, but we can skip this jar) */ return refs; } String classPath = attrs.getValue(Attributes.Name.CLASS_PATH); if (CodeGenUtil.isEmptyString(classPath)) { return refs; } String parentDir = FilenameUtils.getFullPath(file.getAbsolutePath()); File possible; for (String path : StringUtils.splitStr(classPath, ' ')) { possible = new File(path); if (!possible.isAbsolute()) { // relative path? possible = new File(FilenameUtils.normalize(parentDir + path)); } if (!refs.contains(possible)) { refs.add(possible); } } } catch (IOException e) { LOG.log(Level.WARNING, "Unable to load/read/parse Jar File: " + file.getAbsolutePath(), e); } finally { CodeGenUtil.closeQuietly(jar); } return refs; }
From source file:org.apache.hadoop.hbase.TestClassFinder.java
/** * Makes a jar out of some class files. Unfortunately it's very tedious. * @param filesInJar Files created via compileTestClass. * @return path to the resulting jar file. *//* w w w . ja v a2 s.c om*/ private static String packageAndLoadJar(FileAndPath... filesInJar) throws Exception { // First, write the bogus jar file. String path = basePath + "jar" + jarCounter.incrementAndGet() + ".jar"; Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); FileOutputStream fos = new FileOutputStream(path); JarOutputStream jarOutputStream = new JarOutputStream(fos, manifest); // Directory entries for all packages have to be added explicitly for // resources to be findable via ClassLoader. Directory entries must end // with "/"; the initial one is expected to, also. Set<String> pathsInJar = new HashSet<String>(); for (FileAndPath fileAndPath : filesInJar) { String pathToAdd = fileAndPath.path; while (pathsInJar.add(pathToAdd)) { int ix = pathToAdd.lastIndexOf('/', pathToAdd.length() - 2); if (ix < 0) { break; } pathToAdd = pathToAdd.substring(0, ix); } } for (String pathInJar : pathsInJar) { jarOutputStream.putNextEntry(new JarEntry(pathInJar)); jarOutputStream.closeEntry(); } for (FileAndPath fileAndPath : filesInJar) { File file = fileAndPath.file; jarOutputStream.putNextEntry(new JarEntry(fileAndPath.path + file.getName())); byte[] allBytes = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); fis.read(allBytes); fis.close(); jarOutputStream.write(allBytes); jarOutputStream.closeEntry(); } jarOutputStream.close(); fos.close(); // Add the file to classpath. File jarFile = new File(path); assertTrue(jarFile.exists()); URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class }); method.setAccessible(true); method.invoke(urlClassLoader, new Object[] { jarFile.toURI().toURL() }); return jarFile.getAbsolutePath(); }
From source file:org.asoem.greyfish.cli.GreyfishCLIApplication.java
private static Optional<String> getCommitHash(final Class<?> clazz) { try {//from www.j a v a 2 s. c om final JarFile jarFile = Resources.getJarFile(clazz); final Manifest manifest = jarFile.getManifest(); final Attributes attr = manifest.getMainAttributes(); return Optional.of(attr.getValue("Git-Commit-Hash")); } catch (IOException e) { throw new IOError(e); } catch (UnsupportedOperationException e) { return Optional.absent(); } }
From source file:com.hurence.logisland.plugin.PluginManager.java
private static void installPlugin(String artifact, String logislandHome) { Optional<ModuleInfo> moduleInfo = findPluginMeta().entrySet().stream() .filter(e -> artifact.equals(e.getKey().getArtifact())).map(Map.Entry::getKey).findFirst(); if (moduleInfo.isPresent()) { System.err// w ww.j a v a2 s . co m .println("A component already matches the artifact " + artifact + ". Please remove it first."); System.exit(-1); } try { IvySettings settings = new IvySettings(); settings.load(new File(logislandHome, "conf/ivy.xml")); Ivy ivy = Ivy.newInstance(settings); ivy.bind(); System.out.println("\nDownloading dependencies. Please hold on...\n"); String parts[] = Arrays.stream(artifact.split(":")).map(String::trim).toArray(a -> new String[a]); if (parts.length != 3) { throw new IllegalArgumentException( "Unrecognized artifact format. It should be groupId:artifactId:version"); } ModuleRevisionId revisionId = new ModuleRevisionId(new ModuleId(parts[0], parts[1]), parts[2]); Set<ArtifactDownloadReport> toBePackaged = downloadArtifacts(ivy, revisionId, new String[] { "default", "compile", "runtime" }); ArtifactDownloadReport artifactJar = toBePackaged.stream() .filter(a -> a.getArtifact().getModuleRevisionId().equals(revisionId)).findFirst() .orElseThrow(() -> new IllegalStateException("Unable to find artifact " + artifact + ". Please check the name is correct and the repositories on ivy.xml are correctly configured")); Manifest manifest = new JarFile(artifactJar.getLocalFile()).getManifest(); File libDir = new File(logislandHome, "lib"); if (manifest.getMainAttributes().containsKey(ManifestAttributes.MODULE_ARTIFACT)) { org.apache.commons.io.FileUtils.copyFileToDirectory(artifactJar.getLocalFile(), libDir); //we have a logisland plugin. Just copy it System.out.println(String.format("Found logisland plugin %s version %s\n" + "It will provide:", manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_NAME), manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_VERSION))); Arrays.stream(manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_EXPORTS).split(",")) .map(String::trim).forEach(s -> System.out.println("\t" + s)); } else { System.out.println("Repackaging artifact and its dependencies"); Set<ArtifactDownloadReport> environment = downloadArtifacts(ivy, revisionId, new String[] { "provided" }); Set<ArtifactDownloadReport> excluded = toBePackaged.stream() .filter(adr -> excludeGroupIds.stream() .anyMatch(s -> s.matches(adr.getArtifact().getModuleRevisionId().getOrganisation())) || excludedArtifactsId.stream().anyMatch( s -> s.matches(adr.getArtifact().getModuleRevisionId().getName()))) .collect(Collectors.toSet()); toBePackaged.removeAll(excluded); environment.addAll(excluded); Repackager rep = new Repackager(artifactJar.getLocalFile(), new LogislandPluginLayoutFactory()); rep.setMainClass(""); File destFile = new File(libDir, "logisland-component-" + artifactJar.getLocalFile().getName()); rep.repackage(destFile, callback -> toBePackaged.stream().filter(adr -> adr.getLocalFile() != null) .filter(adr -> !adr.getArtifact().getModuleRevisionId().equals(revisionId)) .map(adr -> new Library(adr.getLocalFile(), LibraryScope.COMPILE)).forEach(library -> { try { callback.library(library); } catch (IOException e) { throw new UncheckedIOException(e); } })); Thread.currentThread().setContextClassLoader(new URLClassLoader( environment.stream().filter(adr -> adr.getLocalFile() != null).map(adr -> { try { return adr.getLocalFile().toURI().toURL(); } catch (Exception e) { throw new RuntimeException(e); } }).toArray(a -> new URL[a]), Thread.currentThread().getContextClassLoader())); //now clean up package and write the manifest String newArtifact = "com.hurence.logisland.repackaged:" + parts[1] + ":" + parts[2]; LogislandRepackager.execute(destFile.getAbsolutePath(), "BOOT-INF/lib-provided", parts[2], newArtifact, "Logisland Component for " + artifact, "Logisland Component for " + artifact, new String[] { "org.apache.kafka.*" }, new String[0], "org.apache.kafka.connect.connector.Connector"); } System.out.println("Install done!"); } catch (Exception e) { System.err.println("Unable to install artifact " + artifact); e.printStackTrace(); System.exit(-1); } }
From source file:com.arcusys.liferay.vaadinplugin.util.WidgetsetUtil.java
private static void includeVaadinAddonJar(File file, List<VaadinAddonInfo> addons) { try {/* ww w. ja v a2 s . c om*/ URL url = new URL("file:" + file.getCanonicalPath()); url = new URL("jar:" + url.toExternalForm() + "!/"); JarURLConnection conn = (JarURLConnection) url.openConnection(); JarFile jarFile = conn.getJarFile(); if (jarFile != null) { Manifest manifest = jarFile.getManifest(); if (manifest == null) { // No manifest so this is not a Vaadin Add-on return; } Attributes attrs = manifest.getMainAttributes(); String value = attrs.getValue("Vaadin-Widgetsets"); if (value != null) { String name = attrs.getValue("Implementation-Title"); String version = attrs.getValue("Implementation-Version"); if (name == null || version == null) { // A jar file with Vaadin-Widgetsets but name or version // missing. Most probably vaadin.jar itself, skipping it // here return; } List<String> widgetsets = new ArrayList<String>(); String[] widgetsetNames = value.split(","); for (String wName : widgetsetNames) { String widgetsetname = wName.trim().intern(); if (!widgetsetname.equals("")) { widgetsets.add(widgetsetname); } } if (!widgetsets.isEmpty()) { addons.add(new VaadinAddonInfo(name, version, file, widgetsets)); } } } } catch (Exception e) { log.warn("Exception trying to include Vaadin Add-ons.", e); } }
From source file:org.commonjava.maven.ext.manip.io.PomIO.java
/** * Retrieves the SHA this was built with. * * @return the GIT sha of this codebase. * @throws ManipulationException if an error occurs. *///from w ww . j a v a 2 s .c o m public static String getManifestInformation() throws ManipulationException { String result = ""; try { final Enumeration<URL> resources = PomIO.class.getClassLoader().getResources("META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { final URL jarUrl = resources.nextElement(); if (jarUrl.getFile().contains("pom-manipulation-")) { final Manifest manifest = new Manifest(jarUrl.openStream()); result = manifest.getMainAttributes().getValue("Implementation-Version"); result += " ( SHA: " + manifest.getMainAttributes().getValue("Scm-Revision") + " ) "; break; } } } catch (final IOException e) { throw new ManipulationException("Error retrieving information from manifest", e); } return result; }
From source file:org.fusesource.meshkeeper.classloader.basic.BasicClassLoaderServer.java
private static void addExportedFile(ArrayList<ExportedFile> elements, File file) throws IOException { ExportedFile exportedFile = new ExportedFile(); exportedFile.file = file;//from ww w.j a v a2s.c om // No need to add if it does not exist. if (!file.exists()) { return; } // No need to add if it's in the list allready.. for (ExportedFile element : elements) { if (file.equals(element.file)) { if (LOG.isDebugEnabled()) LOG.debug("duplicate file :" + file + " on classpath"); return; } } ArrayList<URL> manifestClasspath = null; // if it's a directory, then jar it up.. if (file.isDirectory()) { if (file.list().length <= 0) { return; } if (LOG.isDebugEnabled()) LOG.debug("Jaring: " + file); File jar = exportedFile.jared = jar(file); if (LOG.isDebugEnabled()) LOG.debug("Jared: " + file + " as: " + jar); file = jar; } else { // if it's a file then it needs to be eaither a zip or jar file. String name = file.getName(); if (!(name.endsWith(".jar") || name.endsWith(".zip"))) { if (LOG.isDebugEnabled()) LOG.debug("Not a jar.. ommititng from the classpath: " + file); return; } //Parse the manifest, and include entries in the exported //classpath: try { JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { String classpath = (String) manifest.getMainAttributes() .get(java.util.jar.Attributes.Name.CLASS_PATH); if (classpath != null) { String[] entries = classpath.split(" "); manifestClasspath = new ArrayList<URL>(entries.length); for (String entry : classpath.split(" ")) { manifestClasspath.add(new URL(file.getParentFile().toURI().toURL(), entry)); } } } } catch (Exception e) { LOG.warn("Error reading jar manifest for: " + file); } } exportedFile.element.id = ids.incrementAndGet(); exportedFile.element.length = file.length(); exportedFile.element.fingerprint = BasicClassLoaderFactory.fingerprint(new FileInputStream(file)); elements.add(exportedFile); //Add in any manifest entries: if (manifestClasspath != null) { addExportedURLs(manifestClasspath.toArray(new URL[] {}), elements); } }
From source file:org.jahia.services.templates.JahiaTemplatesPackageHandler.java
/** * Extract data from the MANIFEST.MF file and builds the * JahiaTemplatesPackage object//from ww w . j a v a 2s . c o m * * @param file the package file to read */ private static JahiaTemplatesPackage read(File file) { JahiaTemplatesPackage templatePackage = new JahiaTemplatesPackage(); // extract data from the META-INF/MANIFEST.MF file try { File manifestFile = new File(file, "META-INF/MANIFEST.MF"); if (manifestFile.exists()) { InputStream manifestStream = new BufferedInputStream(new FileInputStream(manifestFile), 1024); Manifest manifest = new Manifest(manifestStream); IOUtils.closeQuietly(manifestStream); String packageName = (String) manifest.getMainAttributes().get(new Attributes.Name("package-name")); String rootFolder = (String) manifest.getMainAttributes().get(new Attributes.Name("root-folder")); String moduleType = (String) manifest.getMainAttributes().get(new Attributes.Name("module-type")); String implementationVersionStr = (String) manifest.getMainAttributes() .get(new Attributes.Name("Implementation-Version")); if (packageName == null) { packageName = file.getName(); } if (rootFolder == null) { rootFolder = file.getName(); } String depends = (String) manifest.getMainAttributes().get(new Attributes.Name("depends")); if (depends != null) { String[] dependencies = depends.split(","); for (String dependency : dependencies) { templatePackage.setDepends(dependency.trim()); } } String definitions = (String) manifest.getMainAttributes().get(new Attributes.Name("definitions")); if (definitions != null) { String[] defs = definitions.split(","); for (String defFile : defs) { templatePackage.getDefinitionsFiles().add(defFile.trim()); } } String imports = (String) manifest.getMainAttributes().get(new Attributes.Name("initial-imports")); if (imports != null) { String[] importFiles = imports.split(","); for (String imp : importFiles) { templatePackage.addInitialImport(imp.trim()); } } String resourceBundle = (String) manifest.getMainAttributes() .get(new Attributes.Name("resource-bundle")); if (StringUtils.isNotBlank(resourceBundle)) { templatePackage.setResourceBundleName(resourceBundle.trim()); } templatePackage.setName(packageName); templatePackage.setRootFolder(rootFolder); templatePackage.setModuleType(moduleType); if (implementationVersionStr != null) { templatePackage.setVersion(new Version(implementationVersionStr)); } } } catch (IOException ioe) { logger.warn("Failed extracting module package data from META-INF/MANIFEST.MF file for package " + file, ioe); } return templatePackage; }