List of usage examples for java.util.jar Manifest getMainAttributes
public Attributes getMainAttributes()
From source file:org.s4i.feature.FeatureMojo.java
private IFeaturePlugin createFeaturePlugin(IFeatureModel model, DependencyNode node) throws CoreException, MojoExecutionException { FeaturePlugin featurePlugin = new FeaturePlugin(); featurePlugin.setModel(model);//from w ww.ja v a 2 s . co m File file = node.getArtifact().getFile(); if (file == null) { /* the file was already resolved, it's just that is not available in the dependency node */ file = new File(this.localRepository.getBasedir(), this.localRepository.pathOf(node.getArtifact())); } String type = node.getArtifact().getType(); if (!"jar".equals(type)) { getLog().error("Unsupported type \"" + type + "\" for artifact: " + node.getArtifact().getId()); return null; } try { JarFile jarFile = new JarFile(file); Manifest manifest = jarFile.getManifest(); if (manifest == null) { getLog().warn("Artifact is not an OSGi bundle and will be ignored (no manifest): " + node.getArtifact().getId()); return null; } Attributes attrs = manifest.getMainAttributes(); String bsn = getBundleSymbolicName(attrs); String ver = getBundleVersion(attrs); if (bsn == null || ver == null) { getLog().warn("Artifact is not an OSGi bundle and will be ignored (no BSN/version): " + node.getArtifact().getId()); return null; } featurePlugin.setId(bsn); featurePlugin.setVersion(ver); featurePlugin.setFragment(isFragment(attrs)); getLog().info("Adding OSGi bundle to feature: " + node.getArtifact().getId()); } catch (Exception e) { getLog().error("Artifact is not an OSGi bundle and will be ignored: " + node.getArtifact().getId(), e); return null; } long size = file.length() / 1024; featurePlugin.setInstallSize(size); featurePlugin.setDownloadSize(size); featurePlugin.setUnpack(false); return featurePlugin; }
From source file:com.basistech.bbhmp.RosapiBundleCollectorMojo.java
private boolean isJarFragment(File outputFile) throws MojoExecutionException, MojoFailureException { JarFile jar;//from w w w. j a v a2 s . c o m try { jar = new JarFile(outputFile); } catch (IOException e) { throw new MojoExecutionException( "Failed to open dependency we just copied " + outputFile.getAbsolutePath(), e); } final Manifest manifest; try { manifest = jar.getManifest(); } catch (IOException e) { throw new MojoFailureException( "Failed to read manifest from dependency we just copied " + outputFile.getAbsolutePath(), e); } final Attributes mattr = manifest.getMainAttributes(); // getValue is case-insensitive. String mfVersion = mattr.getValue("Bundle-ManifestVersion"); /* * '2' is the only legitimate bundle manifest version. Version 1 is long obsolete, and not supported * in current containers. There's no plan on the horizon for a version 3. No version at all indicates * that the jar file is not an OSGi bundle at all. */ if (!"2".equals(mfVersion)) { throw new MojoFailureException("Bundle-ManifestVersion is not '2' from dependency we just copied " + outputFile.getAbsolutePath()); } String host = mattr.getValue("Fragment-Host"); return host != null; }
From source file:interactivespaces.launcher.bootstrap.InteractiveSpacesFrameworkBootstrap.java
/** * Get the Interactive Spaces version from the JAR manifest. * * @return The interactive spaces version *//*from w ww. j av a 2 s.c om*/ private String getInteractiveSpacesVersion() { String classContainer = getClass().getProtectionDomain().getCodeSource().getLocation().toString(); InputStream in = null; try { URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF"); in = manifestUrl.openStream(); Manifest manifest = new Manifest(in); Attributes attributes = manifest.getMainAttributes(); return attributes.getValue(MANIFEST_PROPERTY_INTERACTIVESPACES_VERSION); } catch (IOException ex) { return null; } finally { if (in != null) { try { in.close(); } catch (IOException e) { // Don't care } } } }
From source file:org.apache.sling.maven.slingstart.PreparePackageMojo.java
private Manifest getRunModesManifest(Feature feature) throws MojoExecutionException { Map<String, StringBuilder> runModes = new HashMap<>(); for (RunMode rm : feature.getRunModes()) { for (ArtifactGroup ag : rm.getArtifactGroups()) { int startOrder = ag.getStartLevel(); // For subsystems the start level on the artifact group is used as start order. for (org.apache.sling.provisioning.model.Artifact a : ag) { Artifact artifact = ModelUtils.getArtifact(this.project, this.mavenSession, this.artifactHandlerManager, this.resolver, a.getGroupId(), a.getArtifactId(), a.getVersion(), a.getType(), a.getClassifier()); File artifactFile = artifact.getFile(); String entryName = getEntryName(artifactFile, startOrder); String[] runModeNames = rm.getNames(); if (runModeNames == null) runModeNames = new String[] { ALL_RUNMODES_KEY }; for (String runModeName : runModeNames) { StringBuilder sb = runModes.get(runModeName); if (sb == null) { sb = new StringBuilder(); runModes.put(runModeName, sb); } else { sb.append('|'); }//from www. java2s. co m sb.append(entryName); } } } } Manifest mf = new Manifest(); Attributes attrs = mf.getMainAttributes(); attrs.putValue("Manifest-Version", "1.0"); // Manifest does not work without this value attrs.putValue("About-This-Manifest", "This is not a real manifest, it is used as information when this archive is transformed into a real subsystem .esa file"); for (Map.Entry<String, StringBuilder> entry : runModes.entrySet()) { attrs.putValue(entry.getKey().replace(':', '_'), entry.getValue().toString()); } return mf; }
From source file:org.apache.sling.maven.slingstart.PreparePackageMojo.java
private int createSubsystemManifest(Feature feature, Map<String, Integer> startOrderMap, ZipOutputStream os) throws IOException { int subsystemStartLevel = -1; ZipEntry ze = new ZipEntry("SUBSYSTEM-MANIFEST-BASE.MF"); try {/*from w ww . j av a 2 s. c o m*/ os.putNextEntry(ze); Manifest mf = new Manifest(); Attributes attributes = mf.getMainAttributes(); attributes.putValue("Manifest-Version", "1.0"); // Manifest does not work without this value attributes.putValue("Subsystem-SymbolicName", feature.getName()); attributes.putValue("Subsystem-Version", "1"); // Version must be an integer (cannot be a long), TODO better idea? attributes.putValue("Subsystem-Type", feature.getType()); for (Section section : feature.getAdditionalSections("subsystem-manifest")) { String sl = section.getAttributes().get("startLevel"); try { subsystemStartLevel = Integer.parseInt(sl); } catch (NumberFormatException nfe) { // Not a valid start level } BufferedReader br = new BufferedReader(new StringReader(section.getContents())); String line = null; while ((line = br.readLine()) != null) { int idx = line.indexOf(':'); if (idx > 0) { String key = line.substring(0, idx); String value; idx++; if (line.length() > idx) value = line.substring(idx); else value = ""; attributes.putValue(key.trim(), value.trim()); } } } mf.write(os); } finally { os.closeEntry(); } return subsystemStartLevel; }
From source file:org.orbisgis.framework.BundleTools.java
/** * Register in the host bundle the provided list of bundle reference * @param hostBundle Host BundleContext//w w w .jav a 2s .co m * @param nonDefaultBundleDeploying Bundle Reference array to deploy bundles in a non default way (install&start) */ public void installBundles(BundleContext hostBundle, BundleReference[] nonDefaultBundleDeploying) { //Create a Map of nonDefaultBundleDeploying by their artifactId Map<String, BundleReference> customDeployBundles = new HashMap<String, BundleReference>( nonDefaultBundleDeploying.length); for (BundleReference ref : nonDefaultBundleDeploying) { customDeployBundles.put(ref.getArtifactId(), ref); } // List bundles in the /bundle subdirectory File bundleFolder = new File(BUNDLE_DIRECTORY); if (!bundleFolder.exists()) { return; } File[] files = bundleFolder.listFiles(); List<File> jarList = new ArrayList<File>(); if (files != null) { for (File file : files) { if (FilenameUtils.isExtension(file.getName(), "jar")) { jarList.add(file); } } } if (!jarList.isEmpty()) { Map<String, Bundle> installedBundleMap = new HashMap<String, Bundle>(); Set<String> fragmentHosts = new HashSet<>(); // Keep a reference to bundles in the framework cache for (Bundle bundle : hostBundle.getBundles()) { String key = bundle.getSymbolicName(); installedBundleMap.put(key, bundle); String fragmentHost = getFragmentHost(bundle); if (fragmentHost != null) { fragmentHosts.add(fragmentHost); } } // final List<Bundle> installedBundleList = new LinkedList<Bundle>(); for (File jarFile : jarList) { // Extract version and symbolic name of the bundle String key = ""; BundleReference jarRef; try { List<PackageDeclaration> packageDeclarations = new ArrayList<PackageDeclaration>(); jarRef = parseJarManifest(jarFile, packageDeclarations); key = jarRef.getArtifactId(); } catch (IOException ex) { LOGGER.log(Logger.LOG_ERROR, ex.getLocalizedMessage(), ex); // Do not install this jar continue; } // Retrieve from the framework cache the bundle at this location Bundle installedBundle = installedBundleMap.remove(key); // Read Jar manifest without installing it BundleReference reference = new BundleReference(""); // Default deploy try (JarFile jar = new JarFile(jarFile)) { Manifest manifest = jar.getManifest(); if (manifest != null && manifest.getMainAttributes() != null) { String artifact = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); BundleReference customRef = customDeployBundles.get(artifact); if (customRef != null) { reference = customRef; } } } catch (Exception ex) { LOGGER.log(Logger.LOG_ERROR, I18N.tr("Could not read bundle manifest"), ex); } try { if (installedBundle != null) { if (getFragmentHost(installedBundle) != null) { // Fragment cannot be reinstalled continue; } else { String installedBundleLocation = installedBundle.getLocation(); int verDiff = -1; if (installedBundle.getVersion() != null && jarRef.getVersion() != null) { verDiff = installedBundle.getVersion().compareTo(jarRef.getVersion()); } if (verDiff == 0) { // If the same version or SNAPSHOT that is not used by fragments if (!fragmentHosts.contains(installedBundle.getSymbolicName()) && (!installedBundleLocation.equals(jarFile.toURI().toString()) || (installedBundle.getVersion() != null && "SNAPSHOT" .equals(installedBundle.getVersion().getQualifier())))) { //if the location is not the same reinstall it LOGGER.log(Logger.LOG_INFO, "Uninstall bundle " + installedBundle.getSymbolicName()); installedBundle.uninstall(); installedBundle = null; } } else if (verDiff < 0) { // Installed version is older than the bundle version LOGGER.log(Logger.LOG_INFO, "Uninstall bundle " + installedBundle.getLocation()); installedBundle.uninstall(); installedBundle = null; } else { // Installed version is more recent than the bundle version // Do not install this jar continue; } } } // If the bundle is not in the framework cache install it if ((installedBundle == null) && reference.isAutoInstall()) { installedBundle = hostBundle.installBundle(jarFile.toURI().toString()); LOGGER.log(Logger.LOG_INFO, "Install bundle " + installedBundle.getSymbolicName()); if (!isFragment(installedBundle) && reference.isAutoStart()) { installedBundleList.add(installedBundle); } } } catch (BundleException ex) { LOGGER.log(Logger.LOG_ERROR, "Error while installing bundle in bundle directory", ex); } } // Start new bundles for (Bundle bundle : installedBundleList) { try { bundle.start(); } catch (BundleException ex) { LOGGER.log(Logger.LOG_ERROR, "Error while starting bundle in bundle directory", ex); } } } }
From source file:com.taobao.android.apatch.MergePatch.java
private void fillManifest(Attributes main) throws IOException { JarFile jarFile;/* w w w. j a v a2 s . c o m*/ Manifest manifest; StringBuffer fromBuffer = new StringBuffer(); StringBuffer toBuffer = new StringBuffer(); String from; String to; String name; // String classes; for (File file : patchs) { jarFile = new JarFile(file); JarEntry dexEntry = jarFile.getJarEntry("META-INF/PATCH.MF"); manifest = new Manifest(jarFile.getInputStream(dexEntry)); Attributes attributes = manifest.getMainAttributes(); from = attributes.getValue("From-File"); if (fromBuffer.length() > 0) { fromBuffer.append(','); } fromBuffer.append(from); to = attributes.getValue("To-File"); if (toBuffer.length() > 0) { toBuffer.append(','); } toBuffer.append(to); name = attributes.getValue("Patch-Name"); // classes = attributes.getValue(name + "-Patch-Classes"); main.putValue(name + "-Patch-Classes", attributes.getValue(name + "-Patch-Classes")); main.putValue(name + "-Prepare-Classes", attributes.getValue(name + "-Prepare-Classes")); main.putValue(name + "-Used-Methods", attributes.getValue(name + "-Used-Methods")); main.putValue(name + "-Modified-Classes", attributes.getValue(name + "-Modified-Classes")); main.putValue(name + "-Used-Classes", attributes.getValue(name + "-Used-Classes")); main.putValue(name + "-add-classes", attributes.getValue(name + "-add-classes")); } main.putValue("From-File", fromBuffer.toString()); main.putValue("To-File", toBuffer.toString()); }
From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java
/** * Copies the content of a Jar/Zip archive into the receiver archive. * <p/>An optional {@link IZipEntryFilter} allows to selectively choose which files * to copy over./*from w ww. ja va 2 s.com*/ * * @param input the {@link InputStream} for the Jar/Zip to copy. * @param filter the filter or <code>null</code> * @throws IOException * @throws SignedJarBuilder.IZipEntryFilter.ZipAbortException if the {@link IZipEntryFilter} filter indicated that the write * must be aborted. */ public void writeZip(InputStream input, IZipEntryFilter filter) throws IOException, IZipEntryFilter.ZipAbortException { ZipInputStream zis = new ZipInputStream(input); try { // loop on the entries of the intermediary package and put them in the final package. ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String name = entry.getName(); // do not take directories or anything inside a potential META-INF folder. if (entry.isDirectory()) { continue; } // ignore some of the content in META-INF/ but not all if (name.startsWith("META-INF/")) { // ignore the manifest file. String subName = name.substring(9); if ("MANIFEST.MF".equals(subName)) { int count; ByteArrayOutputStream out = new ByteArrayOutputStream(); while ((count = zis.read(buffer)) != -1) { out.write(buffer, 0, count); } ByteArrayInputStream swapStream = new ByteArrayInputStream(out.toByteArray()); Manifest manifest = new Manifest(swapStream); mManifest.getMainAttributes().putAll(manifest.getMainAttributes()); continue; } // special case for Maven meta-data because we really don't care about them in apks. if (name.startsWith("META-INF/maven/")) { continue; } // check for subfolder int index = subName.indexOf('/'); if (index == -1) { // no sub folder, ignores signature files. if (subName.endsWith(".SF") || name.endsWith(".RSA") || name.endsWith(".DSA")) { continue; } } } // if we have a filter, we check the entry against it if (filter != null && !filter.checkEntry(name)) { continue; } JarEntry newEntry; // Preserve the STORED method of the input entry. if (entry.getMethod() == JarEntry.STORED) { newEntry = new JarEntry(entry); } else { // Create a new entry so that the compressed len is recomputed. newEntry = new JarEntry(name); } writeEntry(zis, newEntry); zis.closeEntry(); } } finally { zis.close(); } }
From source file:org.rhq.plugins.jbossas.util.FileContentDelegate.java
/** * Write the SHA256 to the manifest using the RHQ-Sha256 attribute tag. * * @param deploymentFolder app deployment folder * @param sha SHA256//from ww w. j a va 2 s . c om * @throws IOException */ private void writeSHAToManifest(File deploymentFolder, String sha) throws IOException { File manifestFile = new File(deploymentFolder, MANIFEST_RELATIVE_PATH); Manifest manifest; if (manifestFile.exists()) { FileInputStream inputStream = new FileInputStream(manifestFile); try { manifest = new Manifest(inputStream); } finally { inputStream.close(); } } else { manifest = new Manifest(); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); } Attributes attribs = manifest.getMainAttributes(); //The main section of the manifest file does not get saved if both of //these two attributes are missing. Please see Attributes implementation. if (!attribs.containsKey(Attributes.Name.MANIFEST_VERSION.toString()) && !attribs.containsKey(Attributes.Name.SIGNATURE_VERSION.toString())) { attribs.putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); } attribs.putValue(RHQ_SHA_256, sha); FileOutputStream outputStream = new FileOutputStream(manifestFile); try { manifest.write(outputStream); } finally { outputStream.close(); } }
From source file:org.jenkins.tools.test.PluginCompatTester.java
/** * Scans through a WAR file, accumulating plugin information * @param war WAR to scan/*from w w w.j a va 2 s.c o m*/ * @param pluginGroupIds Map pluginName to groupId if set in the manifest, MUTATED IN THE EXECUTION * @return Update center data * @throws IOException */ private UpdateSite.Data scanWAR(File war, Map<String, String> pluginGroupIds) throws IOException { JSONObject top = new JSONObject(); top.put("id", DEFAULT_SOURCE_ID); JSONObject plugins = new JSONObject(); JarFile jf = new JarFile(war); if (pluginGroupIds == null) { pluginGroupIds = new HashMap<String, String>(); } try { Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); Matcher m = Pattern.compile("WEB-INF/lib/jenkins-core-([0-9.]+(?:-[0-9.]+)?(?:-SNAPSHOT)?)[.]jar") .matcher(name); if (m.matches()) { if (top.has("core")) { throw new IOException(">1 jenkins-core.jar in " + war); } top.put("core", new JSONObject().accumulate("name", "core").accumulate("version", m.group(1)) .accumulate("url", "")); } m = Pattern.compile("WEB-INF/(?:optional-)?plugins/([^/.]+)[.][hj]pi").matcher(name); if (m.matches()) { JSONObject plugin = new JSONObject().accumulate("url", ""); InputStream is = jf.getInputStream(entry); try { JarInputStream jis = new JarInputStream(is); try { Manifest manifest = jis.getManifest(); String shortName = manifest.getMainAttributes().getValue("Short-Name"); if (shortName == null) { shortName = manifest.getMainAttributes().getValue("Extension-Name"); if (shortName == null) { shortName = m.group(1); } } plugin.put("name", shortName); pluginGroupIds.put(shortName, manifest.getMainAttributes().getValue("Group-Id")); plugin.put("version", manifest.getMainAttributes().getValue("Plugin-Version")); plugin.put("url", "jar:" + war.toURI() + "!/" + name); JSONArray dependenciesA = new JSONArray(); String dependencies = manifest.getMainAttributes().getValue("Plugin-Dependencies"); if (dependencies != null) { // e.g. matrix-auth:1.0.2;resolution:=optional,credentials:1.8.3;resolution:=optional for (String pair : dependencies.replace(";resolution:=optional", "").split(",")) { String[] nameVer = pair.split(":"); assert nameVer.length == 2; dependenciesA.add(new JSONObject().accumulate("name", nameVer[0]) .accumulate("version", nameVer[1]) ./* we do care about even optional deps here */accumulate("optional", "false")); } } plugin.accumulate("dependencies", dependenciesA); plugins.put(shortName, plugin); } finally { jis.close(); } } finally { is.close(); } } } } finally { jf.close(); } top.put("plugins", plugins); if (!top.has("core")) { throw new IOException("no jenkins-core.jar in " + war); } System.out.println("Scanned contents of " + war + ": " + top); return newUpdateSiteData(new UpdateSite(DEFAULT_SOURCE_ID, null), top); }