List of usage examples for java.util.jar Manifest Manifest
public Manifest(Manifest man)
From source file:com.zimbra.cs.zimlet.ZimletUtil.java
public static void createZip(String dirName, String descFile) throws IOException { File dir = new File(dirName); if (!dir.exists() || !dir.isDirectory()) { throw new IOException("directory does not exist: " + dirName); }// w w w. java 2s . c o m String target = descFile; boolean found = false; for (String f : dir.list()) { if (target != null) { if (target.compareTo(f) == 0) { found = true; break; } } else if (f.endsWith(".xml") && f.substring(0, f.length() - 4).compareTo(dir.getName()) == 0) { target = f; found = true; break; } } if (!found) { throw new IOException("Zimlet description not found, or not named correctly."); } String manifest = "Manifest-Version: 1.0\nZimlet-Description-File: " + target + "\n"; JarOutputStream out = new JarOutputStream( new FileOutputStream(target.substring(0, target.length() - 4) + ".zip"), new Manifest(new ByteArrayInputStream(manifest.getBytes("UTF-8")))); for (File f : dir.listFiles()) { addZipEntry(out, f, null); } out.close(); }
From source file:org.teragrid.portal.filebrowser.applet.ConfigOperation.java
private void readVersionInformation() { InputStream stream = null;//from w w w. jav a 2 s .c o m try { JarFile tgfmJar = null; URL jarname = Class.forName("org.teragrid.portal.filebrowser.applet.ConfigOperation") .getResource("ConfigOperation.class"); JarURLConnection c = (JarURLConnection) jarname.openConnection(); tgfmJar = c.getJarFile(); stream = tgfmJar.getInputStream(tgfmJar.getEntry("META-INF/MANIFEST.MF")); Manifest manifest = new Manifest(stream); Attributes attributes = manifest.getMainAttributes(); for (Object attributeName : attributes.keySet()) { if (((Attributes.Name) attributeName).toString().equals(("Implementation-Version"))) { ConfigSettings.SOFTWARE_VERSION = attributes.getValue("Implementation-Version"); } else if (((Attributes.Name) attributeName).toString().equals(("Built-Date"))) { ConfigSettings.SOFTWARE_BUILD_DATE = attributes.getValue("Built-Date"); } LogManager .debug(attributeName + ": " + attributes.getValue((Attributes.Name) attributeName) + "\n"); } stream.close(); } catch (Exception e) { LogManager.error("Failed to retreive version information.", e); } finally { try { stream.close(); } catch (Exception e) { } } }
From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java
@Test public void testMdlDefaultHasNoOsgiManifest() throws IOException { compile("modules/def/CeylonClass.ceylon"); File carFile = getModuleArchive("default", null); assertTrue(carFile.exists());//from ww w. j ava 2s . com try (JarFile car = new JarFile(carFile)) { ZipEntry manifest = car.getEntry(OsgiUtil.OsgiManifest.MANIFEST_FILE_NAME); try (InputStream input = car.getInputStream(manifest)) { Manifest m = new Manifest(input); Assert.assertTrue(OsgiUtil.DefaultModuleManifest.isDefaultModule(m)); } } }
From source file:org.jvnet.hudson.test.JenkinsRule.java
/** * If this test harness is launched for a Jenkins plugin, locate the <tt>target/test-classes/the.jpl</tt> * and add a recipe to install that to the new Jenkins. * * <p>/* w w w. j ava 2 s .c o m*/ * This file is created by <tt>maven-hpi-plugin</tt> at the testCompile phase when the current * packaging is <tt>jpi</tt>. */ public void recipeLoadCurrentPlugin() throws Exception { final Enumeration<URL> jpls = getClass().getClassLoader().getResources("the.jpl"); final Enumeration<URL> hpls = getClass().getClassLoader().getResources("the.hpl"); final List<URL> all = Collections.list(jpls); all.addAll(Collections.list(hpls)); if (all.isEmpty()) return; // nope recipes.add(new JenkinsRecipe.Runner() { private File home; private final List<Jpl> jpls = new ArrayList<Jpl>(); @Override public void decorateHome(JenkinsRule testCase, File home) throws Exception { this.home = home; this.jpls.clear(); for (URL hpl : all) { Jpl jpl = new Jpl(hpl); jpl.loadManifest(); jpls.add(jpl); } for (Jpl jpl : jpls) { jpl.resolveDependencies(); } } class Jpl { final URL jpl; Manifest m; private String shortName; Jpl(URL jpl) { this.jpl = jpl; } void loadManifest() throws IOException { m = new Manifest(jpl.openStream()); shortName = m.getMainAttributes().getValue("Short-Name"); if (shortName == null) throw new Error(jpl + " doesn't have the Short-Name attribute"); FileUtils.copyURLToFile(jpl, new File(home, "plugins/" + shortName + ".jpl")); } void resolveDependencies() throws Exception { // make dependency plugins available // TODO: probably better to read POM, but where to read from? // TODO: this doesn't handle transitive dependencies // Tom: plugins are now searched on the classpath first. They should be available on // the compile or test classpath. As a backup, we do a best-effort lookup in the Maven repository // For transitive dependencies, we could evaluate Plugin-Dependencies transitively. String dependencies = m.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencies != null) { DEPENDENCY: for (String dep : dependencies.split(",")) { String suffix = ";resolution:=optional"; boolean optional = dep.endsWith(suffix); if (optional) { dep = dep.substring(0, dep.length() - suffix.length()); } String[] tokens = dep.split(":"); String artifactId = tokens[0]; String version = tokens[1]; for (Jpl other : jpls) { if (other.shortName.equals(artifactId)) continue DEPENDENCY; // resolved from another JPL file } File dependencyJar = resolveDependencyJar(artifactId, version); if (dependencyJar == null) { if (optional) { System.err.println("cannot resolve optional dependency " + dep + " of " + shortName + "; skipping"); continue; } throw new IOException("Could not resolve " + dep + " in " + System.getProperty("java.class.path")); } File dst = new File(home, "plugins/" + artifactId + ".jpi"); if (!dst.exists() || dst.lastModified() != dependencyJar.lastModified()) { try { FileUtils.copyFile(dependencyJar, dst); } catch (ClosedByInterruptException x) { throw new AssumptionViolatedException("copying dependencies was interrupted", x); } } } } } } /** * Lazily created embedder. */ private MavenEmbedder embedder; private MavenEmbedder getMavenEmbedder() throws MavenEmbedderException, IOException { if (embedder == null) embedder = MavenUtil.createEmbedder( new StreamTaskListener(System.out, Charset.defaultCharset()), (File) null, null); return embedder; } private @CheckForNull File resolveDependencyJar(String artifactId, String version) throws Exception { // try to locate it from manifest Enumeration<URL> manifests = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { URL manifest = manifests.nextElement(); InputStream is = manifest.openStream(); Manifest m = new Manifest(is); is.close(); if (artifactId.equals(m.getMainAttributes().getValue("Short-Name"))) return Which.jarFile(manifest); } // For snapshot plugin dependencies, an IDE may have replaced ~/.m2/repository//${artifactId}.hpi with /${artifactId}-plugin/target/classes/ // which unfortunately lacks META-INF/MANIFEST.MF so try to find index.jelly (which every plugin should include) and thus the ${artifactId}.hpi: Enumeration<URL> jellies = getClass().getClassLoader().getResources("index.jelly"); while (jellies.hasMoreElements()) { URL jellyU = jellies.nextElement(); if (jellyU.getProtocol().equals("file")) { File jellyF = new File(jellyU.toURI()); File classes = jellyF.getParentFile(); if (classes.getName().equals("classes")) { File target = classes.getParentFile(); if (target.getName().equals("target")) { File hpi = new File(target, artifactId + ".hpi"); if (hpi.isFile()) { return hpi; } } } } } // need to search multiple group IDs // TODO: extend manifest to include groupID:artifactID:version Exception resolutionError = null; for (String groupId : PLUGIN_GROUPIDS) { // first try to find it on the classpath. // this takes advantage of Maven POM located in POM URL dependencyPomResource = getClass() .getResource("/META-INF/maven/" + groupId + "/" + artifactId + "/pom.xml"); if (dependencyPomResource != null) { // found it return Which.jarFile(dependencyPomResource); } else { try { // currently the most of the plugins are still hpi return resolvePluginFile(artifactId, version, groupId, "hpi"); } catch (AbstractArtifactResolutionException x) { try { // but also try with the new jpi return resolvePluginFile(artifactId, version, groupId, "jpi"); } catch (AbstractArtifactResolutionException x2) { // could be a wrong groupId resolutionError = x; } } } } throw new Exception("Failed to resolve plugin: " + artifactId + " version " + version, resolutionError); } private @CheckForNull File resolvePluginFile(String artifactId, String version, String groupId, String type) throws Exception { final Artifact jpi = getMavenEmbedder().createArtifact(groupId, artifactId, version, "compile"/*doesn't matter*/, type); getMavenEmbedder().resolve(jpi, Arrays.asList(getMavenEmbedder() .createRepository("http://maven.glassfish.org/content/groups/public/", "repo")), embedder.getLocalRepository()); return jpi.getFile(); } }); }
From source file:org.marketcetera.strategy.StrategyTestBase.java
/** * Constructs a classpath to use for Java compilation. * // w ww . j a v a2 s. c o m * <p>This method will make a best-effort to create the classpath, * ignoring errors that occur during the collection. This method * is not expected to throw exceptions, muddling on instead. * * @return a <code>Set<String></code> value */ private Set<String> getClassPath() { // get the classloader that was used to load this class ClassLoader classLoader = getClass().getClassLoader(); // this collection will hold all the paths we find, duplicates discarded, in the order they appear Set<String> paths = new LinkedHashSet<String>(); // //Collect all URLs from the URL Class Loaders. // do { // if(classLoader instanceof URLClassLoader) { // URLClassLoader urlClassLoader = (URLClassLoader)classLoader; // for(URL url : urlClassLoader.getURLs()) { // try { // paths.add(url.toURI().getPath()); // } catch (URISyntaxException ignore) { // } // } // } // // traverse the classloader tree upwards until no more remain // } while((classLoader = classLoader.getParent()) != null); // // reset the classloader to the current // classLoader = getClass().getClassLoader(); //iterate through the manifests of all the jars to find the // values of their Class-Path attribute value and add them to the // set. try { Enumeration<URL> resourceEnumeration = classLoader.getResources("META-INF/MANIFEST.MF"); while (resourceEnumeration.hasMoreElements()) { URL resourceURL = resourceEnumeration.nextElement(); InputStream is = null; try { // open the resource is = resourceURL.openStream(); Manifest manifest = new Manifest(is); String theClasspath = manifest.getMainAttributes().getValue("Class-Path"); if (theClasspath != null && !theClasspath.trim().isEmpty()) { //manifest classpath is space separated URLs for (String path : theClasspath.split(" ")) { try { URL pathURL = new URL(path); paths.add(pathURL.toURI().getPath()); } catch (MalformedURLException ignore) { } catch (URISyntaxException ignore) { } } } } catch (IOException ignore) { } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } } } } catch (IOException ignore) { } return paths; }
From source file:org.apache.openejb.config.DeploymentLoader.java
@SuppressWarnings("unchecked") public Class<? extends DeploymentModule> discoverModuleType(final URL baseUrl, final ClassLoader classLoader, final Set<RequireDescriptors> requireDescriptor) throws IOException, UnknownModuleTypeException { final boolean scanPotentialEjbModules = !requireDescriptor.contains(RequireDescriptors.EJB); final boolean scanPotentialClientModules = !requireDescriptor.contains(RequireDescriptors.CLIENT); URL pathToScanDescriptors = baseUrl; String path;//from w w w. j a va 2s . c o m if (baseUrl != null) { path = URLs.toFile(baseUrl).getAbsolutePath(); if (baseUrl.getProtocol().equals("file") && path.endsWith("WEB-INF/classes/")) { //EJB found in WAR/WEB-INF/classes, scan WAR for ejb-jar.xml pathToScanDescriptors = new URL(path.substring(0, path.lastIndexOf("WEB-INF/classes/"))); } } else { path = ""; } final Map<String, URL> descriptors = getDescriptors(classLoader, pathToScanDescriptors); if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } if (path.endsWith(".xml") || path.endsWith(".json")) { // let say it is a resource module return ResourcesModule.class; } if (descriptors.containsKey("application.xml") || path.endsWith(".ear")) { return AppModule.class; } if (descriptors.containsKey("ra.xml") || path.endsWith(".rar")) { return ConnectorModule.class; } if (baseUrl != null) { final Map<String, URL> webDescriptors = getWebDescriptors(getFile(baseUrl)); if (webDescriptors.containsKey("web.xml") || webDescriptors.containsKey(WEB_FRAGMENT_XML) // descriptor || path.endsWith(".war") || new File(path, "WEB-INF").exists()) { // webapp specific files return WebModule.class; } } if (descriptors.containsKey("ejb-jar.xml") || descriptors.containsKey("beans.xml")) { return EjbModule.class; } if (descriptors.containsKey("application-client.xml")) { return ClientModule.class; } final URL manifestUrl = descriptors.get("MANIFEST.MF"); if (scanPotentialClientModules && manifestUrl != null) { // In this case scanPotentialClientModules really means "require application-client.xml" final InputStream is = new BufferedInputStream(manifestUrl.openStream()); final Manifest manifest = new Manifest(is); final String mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS); if (mainClass != null) { return ClientModule.class; } } final Class<? extends DeploymentModule> cls = checkAnnotations(baseUrl, classLoader, scanPotentialEjbModules, scanPotentialClientModules); if (cls != null) { return cls; } if (descriptors.containsKey("persistence.xml") || descriptors.containsKey("persistence-fragment.xml")) { return PersistenceModule.class; } //#TOMEE-613 final File file = URLs.toFile(baseUrl); if (DeploymentsResolver.isValidDirectory(file)) { final File[] files = file.listFiles(); if (containsEarAssets(files)) { return AppModule.class; } if (containsWebAssets(files)) { return WebModule.class; } } final Class<? extends DeploymentModule> defaultType = (Class<? extends DeploymentModule>) SystemInstance .get().getOptions().get("openejb.default.deployment-module", (Class<?>) null); if (defaultType != null) { // should we do a better filtering? it seems enough for common cases. if (WebModule.class.equals(defaultType) && (path.endsWith(".jar!") || path.endsWith(".jar"))) { throw new UnknownModuleTypeException("Unknown module type: url=" + path + " which can't be a war."); } logger.debug("type for '" + path + "' was not found, defaulting to " + defaultType.getSimpleName()); return defaultType; } throw new UnknownModuleTypeException("Unknown module type: url=" + path); // baseUrl can be null }