List of usage examples for java.util.jar Manifest getMainAttributes
public Attributes getMainAttributes()
From source file:org.apache.struts2.osgi.host.BaseOsgiHost.java
/** * Gets the version used to export the packages. it tries to get it from MANIFEST.MF, or the file name */// www.jav a 2 s . c o m protected String getVersion(URL url) { if ("jar".equals(url.getProtocol())) { try { FileManager fileManager = ServletActionContext.getContext().getInstance(FileManagerFactory.class) .getFileManager(); JarFile jarFile = new JarFile(new File(fileManager.normalizeToFileProtocol(url).toURI())); Manifest manifest = jarFile.getManifest(); if (manifest != null) { String version = manifest.getMainAttributes().getValue("Bundle-Version"); if (StringUtils.isNotBlank(version)) { return getVersionFromString(version); } } else { //try to get the version from the file name return getVersionFromString(jarFile.getName()); } } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Unable to extract version from [#0], defaulting to '1.0.0'", url.toExternalForm()); } } } return "1.0.0"; }
From source file:org.languagetool.JLanguageTool.java
/** * Returns the build date or {@code null} if not run from JAR. *///w ww .ja va2s .c o m @Nullable private static String getBuildDate() { try { URL res = JLanguageTool.class.getResource(JLanguageTool.class.getSimpleName() + ".class"); if (res == null) { // this will happen on Android, see http://stackoverflow.com/questions/15371274/ return null; } Object connObj = res.openConnection(); if (connObj instanceof JarURLConnection) { JarURLConnection conn = (JarURLConnection) connObj; Manifest manifest = conn.getManifest(); return manifest.getMainAttributes().getValue("Implementation-Date"); } else { return null; } } catch (IOException e) { throw new RuntimeException("Could not get build date from JAR", e); } }
From source file:io.stallion.plugins.PluginRegistry.java
private void doLoadJarPlugins(String targetPath) throws Exception { String jarFolderPath = targetPath + "/jars"; Log.fine("Loading jars at {0}", jarFolderPath); File jarFolder = new File(jarFolderPath); if (!jarFolder.exists() || !jarFolder.isDirectory()) { Log.fine("No jar folder exists at {0}. No jar plugins will be loaded.", jarFolderPath); return;//from ww w . ja v a 2s. c o m } File[] files = jarFolder.listFiles(); ArrayList<URL> urls = new ArrayList<URL>(); for (int i = 0; i < files.length; i++) { if (files[i].getName().endsWith(".jar")) { //urls.add(files[i].toURL()); Log.fine("Loading plugin jar {0}", files[i].toURI()); urls.add(files[i].toURI().toURL()); } } String pluginBooterClass = ""; for (URL jarUrl : urls) { // Add jars to the class loader getClassLoader().addURL(jarUrl); } for (URL jarUrl : urls) { // Load the booter class Manifest m = new JarFile(jarUrl.getFile()).getManifest(); Log.finer("Found manifest for jar {0}", jarUrl); if (!StringUtils.isEmpty(m.getMainAttributes().getValue("pluginBooterClass"))) { pluginBooterClass = m.getMainAttributes().getValue("pluginBooterClass"); } if (empty(pluginBooterClass)) { continue; } Log.fine("Load plugin class {0} from jar={1}", pluginBooterClass, jarUrl); Class booterClass = getClassLoader().loadClass(pluginBooterClass); Log.finer("Booter class was loaded from: {0} ", booterClass.getProtectionDomain().getCodeSource().getLocation()); StallionJavaPlugin booter = (StallionJavaPlugin) booterClass.newInstance(); loadPluginFromBooter(booter); DynamicSettings.instance().initGroup(booter.getPluginName()); } }
From source file:org.apache.sling.maven.slingstart.PreparePackageMojoTest.java
@Test public void testSubsystemBaseGeneration() throws Exception { // Provide the system with some artifacts that are known to be in the local .m2 repo // These are explicitly included in the test section of the pom.xml PreparePackageMojo ppm = getMojoUnderTest("org.apache.sling/org.apache.sling.commons.classloader/1.3.2", "org.apache.sling/org.apache.sling.commons.classloader/1.3.2/app", "org.apache.sling/org.apache.sling.commons.contentdetection/1.0.2", "org.apache.sling/org.apache.sling.commons.json/2.0.12", "org.apache.sling/org.apache.sling.commons.mime/2.1.8", "org.apache.sling/org.apache.sling.commons.osgi/2.3.0", "org.apache.sling/org.apache.sling.commons.threads/3.2.0"); try {/*from ww w .j a v a 2 s . c o m*/ // The launchpad feature is a prerequisite for the model String modelTxt = "[feature name=:launchpad]\n" + "[artifacts]\n" + " org.apache.sling/org.apache.sling.commons.classloader/1.3.2\n" + "" + "[feature name=test1 type=osgi.subsystem.composite]\n" + "" + "[:subsystem-manifest startLevel=123]\n" + " Subsystem-Description: Extra subsystem headers can go here including very long ones that would span multiple lines in a manifest\n" + " Subsystem-Copyright: (c) 2015 yeah!\n" + "" + "[artifacts]\n" + " org.apache.sling/org.apache.sling.commons.osgi/2.3.0\n" + "" + "[artifacts startLevel=10]\n" + " org.apache.sling/org.apache.sling.commons.json/2.0.12\n" + " org.apache.sling/org.apache.sling.commons.mime/2.1.8\n" + "" + "[artifacts startLevel=20 runModes=foo,bar,:blah]\n" + " org.apache.sling/org.apache.sling.commons.threads/3.2.0\n" + "" + "[artifacts startLevel=100 runModes=bar]\n" + " org.apache.sling/org.apache.sling.commons.contentdetection/1.0.2\n"; Model model = ModelReader.read(new StringReader(modelTxt), null); ppm.execute(model); File generatedFile = new File(ppm.getTmpDir() + "/test1.subsystem-base"); try (JarFile jf = new JarFile(generatedFile)) { // Test META-INF/MANIFEST.MF Manifest mf = jf.getManifest(); Attributes attrs = mf.getMainAttributes(); String expected = "Potential_Bundles/0/org.apache.sling.commons.osgi-2.3.0.jar|" + "Potential_Bundles/10/org.apache.sling.commons.json-2.0.12.jar|" + "Potential_Bundles/10/org.apache.sling.commons.mime-2.1.8.jar"; assertEquals(expected, attrs.getValue("_all_")); assertEquals("Potential_Bundles/20/org.apache.sling.commons.threads-3.2.0.jar", attrs.getValue("foo")); assertEquals( "Potential_Bundles/20/org.apache.sling.commons.threads-3.2.0.jar|" + "Potential_Bundles/100/org.apache.sling.commons.contentdetection-1.0.2.jar", attrs.getValue("bar")); // Test SUBSYSTEM-MANIFEST-BASE.MF ZipEntry smbZE = jf.getEntry("SUBSYSTEM-MANIFEST-BASE.MF"); try (InputStream smbIS = jf.getInputStream(smbZE)) { Manifest smbMF = new Manifest(smbIS); Attributes smbAttrs = smbMF.getMainAttributes(); assertEquals("test1", smbAttrs.getValue("Subsystem-SymbolicName")); assertEquals("osgi.subsystem.composite", smbAttrs.getValue("Subsystem-Type")); assertEquals("(c) 2015 yeah!", smbAttrs.getValue("Subsystem-Copyright")); assertEquals( "Extra subsystem headers can go here including very long ones " + "that would span multiple lines in a manifest", smbAttrs.getValue("Subsystem-Description")); } // Test embedded bundles File mrr = getMavenRepoRoot(); File soj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.osgi", "2.3.0"); ZipEntry sojZE = jf.getEntry("Potential_Bundles/0/org.apache.sling.commons.osgi-2.3.0.jar"); try (InputStream is = jf.getInputStream(sojZE)) { assertArtifactsEqual(soj, is); } File sjj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.json", "2.0.12"); ZipEntry sjZE = jf.getEntry("Potential_Bundles/10/org.apache.sling.commons.json-2.0.12.jar"); try (InputStream is = jf.getInputStream(sjZE)) { assertArtifactsEqual(sjj, is); } File smj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.mime", "2.1.8"); ZipEntry smjZE = jf.getEntry("Potential_Bundles/10/org.apache.sling.commons.mime-2.1.8.jar"); try (InputStream is = jf.getInputStream(smjZE)) { assertArtifactsEqual(smj, is); } File stj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.threads", "3.2.0"); ZipEntry stjZE = jf.getEntry("Potential_Bundles/20/org.apache.sling.commons.threads-3.2.0.jar"); try (InputStream is = jf.getInputStream(stjZE)) { assertArtifactsEqual(stj, is); } File ctj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.contentdetection", "1.0.2"); ZipEntry ctjZE = jf .getEntry("Potential_Bundles/100/org.apache.sling.commons.contentdetection-1.0.2.jar"); try (InputStream is = jf.getInputStream(ctjZE)) { assertArtifactsEqual(ctj, is); } } } finally { FileUtils.deleteDirectory(new File(ppm.project.getBuild().getDirectory())); } }
From source file:org.gradle.api.java.archives.internal.DefaultManifest.java
private void addJavaManifestToAttributes(Manifest javaManifest) { attributes.put("Manifest-Version", "1.0"); for (Object attributeKey : javaManifest.getMainAttributes().keySet()) { String attributeName = attributeKey.toString(); String attributeValue = javaManifest.getMainAttributes().getValue(attributeName); attributes.put(attributeName, attributeValue); }/* w ww . j ava 2 s. co m*/ }
From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java
@Test public void testUpdateZipfile() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {/* w w w . ja v a 2 s.c o m*/ JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#jenkins.war"; configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir); configurator.setTargetWebappsDir(webappsTarget); configurator.setJenkinsPath("/s/"); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java
@Test public void testUpdateZipfile() throws Exception { // First, set up our zipfile test. // Create a manifest with a random header so that we can ensure it's preserved by the configurator. Manifest mf = new Manifest(); Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR; String mfTestValue = "someCrazyValue"; mf.getMainAttributes().put(mfTestHeader, mfTestValue); // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you // don't add it, your manifest will be blank. mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader)); File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war"); configurator.setWarTemplateFile(testWar.getAbsolutePath()); try {//from ww w . ja va 2s . c o m JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf); String specialFileName = "foo/bar.xml"; String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file."; // Make our configurator replace this file within the JAR. configurator.setWebXmlFilename(specialFileName); // Create several random files in the zip. for (int i = 0; i < 10; i++) { JarEntry curEntry = new JarEntry("folder/file" + i); jarOutStream.putNextEntry(curEntry); IOUtils.write(fileContents, jarOutStream); } // Push in our special file now. JarEntry specialEntry = new JarEntry(specialFileName); jarOutStream.putNextEntry(specialEntry); IOUtils.write(fileContents, jarOutStream); // Close the output stream now, time to do the test. jarOutStream.close(); // Configure this configurator with appropriate folders for testing. String expectedHomeDir = "/some/silly/random/homeDir"; String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/"; File webappsTargetDir = new File(webappsTarget); if (webappsTargetDir.exists()) { FileUtils.deleteDirectory(webappsTargetDir); } String expectedDestFile = webappsTarget + "s#test#hudson.war"; HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy(); warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war"); configurator.setHudsonWarNamingStrategy(warNamingStrategy); configurator.setTargetHudsonHomeBaseDir(expectedHomeDir); ProjectServiceConfiguration config = new ProjectServiceConfiguration(); config.setProjectIdentifier("test123"); Map<String, String> m = new HashMap<String, String>(); m.put(ProjectServiceConfiguration.PROJECT_ID, "test"); m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com"); config.setProperties(m); config.setProjectIdentifier("test"); // Now, run it against our test setup configurator.configure(config); // Confirm that the zipfile was updates as expected. File configuredWar = new File(expectedDestFile); assertTrue(configuredWar.exists()); try { JarFile configuredWarJar = new JarFile(configuredWar); Manifest extractedMF = configuredWarJar.getManifest(); assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader)); // Make sure all of our entries are present, and contain the data we expected. JarEntry curEntry = null; Enumeration<JarEntry> entries = configuredWarJar.entries(); while (entries.hasMoreElements()) { curEntry = entries.nextElement(); // If this is the manifest, skip it. if (curEntry.getName().equals("META-INF/MANIFEST.MF")) { continue; } String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry)); if (curEntry.getName().equals(specialFileName)) { assertFalse(fileContents.equals(entryContents)); assertTrue(entryContents.contains(expectedHomeDir)); } else { // Make sure our content was unchanged. assertEquals(fileContents, entryContents); assertFalse(entryContents.contains(expectedHomeDir)); } } } finally { // Clean up our test file. configuredWar.delete(); } } finally { // Clean up our test file. testWar.delete(); } }
From source file:org.apache.sling.maven.slingstart.PreparePackageMojoTest.java
@Test public void testBSNRenaming() throws Exception { // Provide the system with some artifacts that are known to be in the local .m2 repo // These are explicitly included in the test section of the pom.xml PreparePackageMojo ppm = getMojoUnderTest("org.apache.sling/org.apache.sling.commons.classloader/1.3.2", "org.apache.sling/org.apache.sling.commons.classloader/1.3.2/app", "org.apache.sling/org.apache.sling.commons.json/2.0.12"); try {/*from w w w . ja v a2 s .c om*/ String modelTxt = "[feature name=:launchpad]\n" + "[artifacts]\n" + " org.apache.sling/org.apache.sling.commons.classloader/1.3.2\n" + "" + "[feature name=rename_test]\n" + " org.apache.sling/org.apache.sling.commons.json/2.0.12 [bundle:rename-bsn=r-foo.bar.renamed.sling.commons.json]\n"; Model model = ModelReader.read(new StringReader(modelTxt), null); ppm.execute(model); File orgJar = getMavenArtifactFile(getMavenRepoRoot(), "org.apache.sling", "org.apache.sling.commons.json", "2.0.12"); File generatedJar = new File(ppm.getTmpDir() + "/r-foo.bar.renamed.sling.commons.json-2.0.12.jar"); compareJarContents(orgJar, generatedJar); try (JarFile jfOrg = new JarFile(orgJar); JarFile jfNew = new JarFile(generatedJar)) { Manifest mfOrg = jfOrg.getManifest(); Manifest mfNew = jfNew.getManifest(); Attributes orgAttrs = mfOrg.getMainAttributes(); Attributes newAttrs = mfNew.getMainAttributes(); for (Object key : orgAttrs.keySet()) { String orgVal = orgAttrs.getValue(key.toString()); String newVal = newAttrs.getValue(key.toString()); if ("Bundle-SymbolicName".equals(key.toString())) { assertEquals("Should have recorded the original Bundle-SymbolicName", orgVal, newAttrs.getValue("X-Original-Bundle-SymbolicName")); assertEquals("r-foo.bar.renamed.sling.commons.json", newVal); } else { assertEquals("Different keys: " + key, orgVal, newVal); } } } } finally { FileUtils.deleteDirectory(new File(ppm.project.getBuild().getDirectory())); } }
From source file:nz.govt.natlib.ndha.manualdeposit.dialogs.About.java
@SuppressWarnings("unchecked") private void startup() { try {// ww w .j av a 2 s . c o m try { theFormControl = new FormControl(this, theSettingsPath); } catch (Exception ex) { LOG.error("Error loading form parameters", ex); } ClassLoader cLoader = Thread.currentThread().getContextClassLoader(); Toolkit kit = Toolkit.getDefaultToolkit(); Package p = this.getClass().getPackage(); lblVersion.setText(p.getImplementationVersion()); if (new File(theLogoFileName).exists()) { theLogo = kit.getImage(theLogoFileName); } else { java.net.URL imageURL = cLoader.getResource(theLogoFileName); if (imageURL != null) { theLogo = kit.getImage(imageURL); } } if (theLogo != null) { lblBuildNo.setForeground(Color.white); lblBuildNoLabel.setForeground(Color.white); //lblHeader.setForeground(Color.white); lblVersion.setForeground(Color.white); lblVersionLabel.setForeground(Color.white); paintImage(); } //String manifestFileName = "/META-INF/MANIFEST.MF"; Class cls = this.getClass(); String className = cls.getSimpleName(); String classFileName = className + ".class"; String pathToThisClass = cls.getResource(classFileName).toString(); int mark = pathToThisClass.indexOf("!"); String pathToManifest = pathToThisClass.substring(0, mark + 1); if (!pathToManifest.equals("")) { pathToManifest += "/META-INF/MANIFEST.MF"; LOG.debug("Path to manifest: " + pathToManifest); Manifest mf = new Manifest(new URL(pathToManifest).openStream()); if (mf != null) { Attributes attr = mf.getMainAttributes(); String attrVersion = "Implementation-Version"; String attrBuild = "Implementation-Build"; String version = attr.getValue(attrVersion); String build = attr.getValue(attrBuild); this.lblVersion.setText(version); this.lblBuildNo.setText(build); } } Runtime runtime = Runtime.getRuntime(); long maxMemory = runtime.maxMemory(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); LOG.debug("free memory: " + freeMemory / 1024); LOG.debug("allocated memory: " + allocatedMemory / 1024); LOG.debug("max memory: " + maxMemory / 1024); LOG.debug("total free memory: " + (freeMemory + (maxMemory - allocatedMemory)) / 1024); } catch (IOException ex) { ex.printStackTrace(); LOG.error(ex.getMessage(), ex); } }
From source file:org.apache.felix.deploymentadmin.itest.util.DPSigner.java
private byte[] getRawBytesMainAttributes(Manifest manifest) throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos)) { Attributes attrs = manifest.getMainAttributes(); Method m = Attributes.class.getDeclaredMethod("writeMain", DataOutputStream.class); m.setAccessible(true);//from w w w. ja v a 2 s . co m m.invoke(attrs, dos); return baos.toByteArray(); } catch (NoSuchMethodException | SecurityException | InvocationTargetException | IllegalAccessException e) { throw new RuntimeException("Failed to get raw bytes of main attributes!", e); } }