List of usage examples for java.util.jar JarInputStream JarInputStream
public JarInputStream(InputStream in) throws IOException
JarInputStream
and reads the optional manifest. From source file:org.jenkins.tools.test.PluginCompatTester.java
/** * Scans through a WAR file, accumulating plugin information * @param war WAR to scan/* ww w. ja v a 2 s. c om*/ * @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); }
From source file:org.jahia.utils.maven.plugin.osgi.BuildFrameworkPackageListMojo.java
private void scanJar(Map<String, Map<String, Map<String, VersionLocation>>> packageVersionCounts, File jarFile, String defaultVersion) throws IOException { JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile)); Manifest jarManifest = jarInputStream.getManifest(); // Map<String, String> manifestVersions = new HashMap<String,String>(); String specificationVersion = null; if (jarManifest == null) { getLog().warn("No MANIFEST.MF file found for dependency " + jarFile); } else {// www.j ava2 s. c om if (jarManifest.getMainAttributes() == null) { getLog().warn("No main attributes found in MANIFEST.MF file found for dependency " + jarFile); } else { specificationVersion = jarManifest.getMainAttributes().getValue("Specification-Version"); if (defaultVersion == null) { if (jarManifest.getMainAttributes().getValue("Bundle-Version") != null) { } else if (specificationVersion != null) { defaultVersion = specificationVersion; } else { defaultVersion = jarManifest.getMainAttributes().getValue("Implementation-Version"); } } String exportPackageHeaderValue = jarManifest.getMainAttributes().getValue("Export-Package"); if (exportPackageHeaderValue != null) { ManifestElement[] manifestElements = new ManifestElement[0]; try { manifestElements = ManifestElement.parseHeader("Export-Package", exportPackageHeaderValue); } catch (BundleException e) { getLog().warn("Error while parsing Export-Package header value for jar " + jarFile, e); } for (ManifestElement manifestElement : manifestElements) { String[] packageNames = manifestElement.getValueComponents(); String version = manifestElement.getAttribute("version"); for (String packageName : packageNames) { updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), version, version, packageName); } } } for (Map.Entry<String, Attributes> manifestEntries : jarManifest.getEntries().entrySet()) { String packageName = manifestEntries.getKey().replaceAll("/", "."); if (packageName.endsWith(".class")) { continue; } if (packageName.endsWith(".")) { packageName = packageName.substring(0, packageName.length() - 1); } if (packageName.endsWith(".*")) { packageName = packageName.substring(0, packageName.length() - 1); } int lastDotPos = packageName.lastIndexOf("."); String lastPackage = packageName; if (lastDotPos > -1) { lastPackage = packageName.substring(lastDotPos + 1); } if (lastPackage.length() > 0 && Character.isUpperCase(lastPackage.charAt(0))) { // ignore non package version continue; } if (StringUtils.isEmpty(packageName) || packageName.startsWith("META-INF") || packageName.startsWith("OSGI-INF") || packageName.startsWith("OSGI-OPT") || packageName.startsWith("WEB-INF") || packageName.startsWith("org.osgi")) { // ignore private package names continue; } String packageVersion = null; if (manifestEntries.getValue().getValue("Specification-Version") != null) { packageVersion = manifestEntries.getValue().getValue("Specification-Version"); } else { packageVersion = manifestEntries.getValue().getValue("Implementation-Version"); } if (packageVersion != null) { getLog().info("Found package version in " + jarFile.getName() + " MANIFEST : " + packageName + " v" + packageVersion); updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), packageVersion, specificationVersion, packageName); // manifestVersions.put(packageName, packageVersion); } } } } JarEntry jarEntry = null; // getLog().debug("Processing file " + artifact.getFile() + "..."); while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { if (!jarEntry.isDirectory()) { String entryName = jarEntry.getName(); String entryPackage = ""; int lastSlash = entryName.lastIndexOf("/"); if (lastSlash > -1) { entryPackage = entryName.substring(0, lastSlash); entryPackage = entryPackage.replaceAll("/", "."); if (StringUtils.isNotEmpty(entryPackage) && !entryPackage.startsWith("META-INF") && !entryPackage.startsWith("OSGI-INF") && !entryPackage.startsWith("OSGI-OPT") && !entryPackage.startsWith("WEB-INF") && !entryPackage.startsWith("org.osgi")) { updateVersionLocationCounts(packageVersionCounts, jarFile.getCanonicalPath(), defaultVersion, specificationVersion, entryPackage); } } } } jarInputStream.close(); }
From source file:streamflow.service.TopologyService.java
private void embedFrameworkResources(JarBuilder jarBuilder, byte[] frameworkJar) { JarEntry jarEntry;//from w ww.j a va 2 s.com JarInputStream jarInputStream; try { jarInputStream = new JarInputStream(new ByteArrayInputStream(frameworkJar)); while ((jarEntry = jarInputStream.getNextJarEntry()) != null) { // A resource file is defined as a non *.class file that is a real file if (!jarEntry.isDirectory() && !jarEntry.getName().endsWith(".class")) { // Ignore the resource files in the META-INF folder if (!jarEntry.getName().startsWith("META-INF") && !jarEntry.getName().startsWith("STREAMFLOW-INF")) { // Create the handle to the target resource file in the topology jar if (!jarBuilder.addFile(jarEntry.getName(), IOUtils.toByteArray(jarInputStream))) { LOG.error("Error occurred while writing a framework resource to the topology jar: " + jarEntry.getName()); } } } } } catch (IOException ex) { LOG.error("Exception while embedding framework resource: " + ex.getMessage()); } }
From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java
/** * Find all classes from a given jar file and add them to the provided * list./* w ww . j av a 2 s. c o m*/ * * @author paouelle * * @param classes the non-<code>null</code> collection of classes where to add new * found classes * @param url the non-<code>null</code> url for the jar where to find classes * @param resource the non-<code>null</code> resource being scanned that * corresponds to given package * @param cl the classloader to find the classes with */ private static void findClassesFromJar(Collection<Class<?>> classes, URL url, String resource, ClassLoader cl) { try { final JarURLConnection conn = (JarURLConnection) url.openConnection(); final URL jurl = conn.getJarFileURL(); try (final JarInputStream jar = new JarInputStream(jurl.openStream());) { while (true) { final JarEntry entry = jar.getNextJarEntry(); if (entry == null) { break; } final String name = entry.getName(); if (name.endsWith(".class") && name.startsWith(resource)) { final String cname = name.substring(0, name.length() - 6 // 6 for .class ).replace(File.separatorChar, '.'); try { classes.add(cl.loadClass(cname)); } catch (ClassNotFoundException e) { // ignore it } } } } } catch (IOException e) { throw new IllegalArgumentException("unable to find classes in package", e); } }
From source file:com.paniclauncher.workers.InstanceInstaller.java
public void deleteMetaInf() { File inputFile = getMinecraftJar(); File outputTmpFile = new File(App.settings.getTempDir(), pack.getSafeName() + "-minecraft.jar"); try {/* www . j av a2 s. co m*/ JarInputStream input = new JarInputStream(new FileInputStream(inputFile)); JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile)); JarEntry entry; while ((entry = input.getNextJarEntry()) != null) { if (entry.getName().contains("META-INF")) { continue; } output.putNextEntry(entry); byte buffer[] = new byte[1024]; int amo; while ((amo = input.read(buffer, 0, 1024)) != -1) { output.write(buffer, 0, amo); } output.closeEntry(); } input.close(); output.close(); inputFile.delete(); outputTmpFile.renameTo(inputFile); } catch (IOException e) { App.settings.getConsole().logStackTrace(e); } }
From source file:org.exist.repo.Deployment.java
public DocumentImpl getDescriptor(File jar) throws IOException, PackageException { final InputStream istream = new BufferedInputStream(new FileInputStream(jar)); final JarInputStream jis = new JarInputStream(istream); JarEntry entry;/*from ww w .j av a 2 s . com*/ DocumentImpl doc = null; while ((entry = jis.getNextJarEntry()) != null) { if (!entry.isDirectory() && "expath-pkg.xml".equals(entry.getName())) { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); int c; final byte[] b = new byte[4096]; while ((c = jis.read(b)) > 0) { bos.write(b, 0, c); } bos.close(); final byte[] data = bos.toByteArray(); final ByteArrayInputStream bis = new ByteArrayInputStream(data); try { doc = DocUtils.parse(broker.getBrokerPool(), null, bis); } catch (final XPathException e) { throw new PackageException("Error while parsing expath-pkg.xml: " + e.getMessage(), e); } break; } } jis.close(); return doc; }
From source file:com.github.helenusdriver.commons.lang3.reflect.ReflectionUtils.java
/** * Find all resources from a given jar file and add them to the provided * list.// ww w . j a va2 s . c om * * @author paouelle * * @param urls the non-<code>null</code> collection of resources where to add new * found resources * @param url the non-<code>null</code> url for the jar where to find resources * @param resource the non-<code>null</code> resource being scanned that * corresponds to given package * @param cl the classloader to find the resources with */ private static void findResourcesFromJar(Collection<URL> urls, URL url, String resource, ClassLoader cl) { try { final JarURLConnection conn = (JarURLConnection) url.openConnection(); final URL jurl = conn.getJarFileURL(); try (final JarInputStream jar = new JarInputStream(jurl.openStream());) { while (true) { final JarEntry entry = jar.getNextJarEntry(); if (entry == null) { break; } final String name = entry.getName(); if (name.startsWith(resource)) { final URL u = cl.getResource(name); if (u != null) { urls.add(u); } } } } } catch (IOException e) { throw new IllegalArgumentException("unable to find resources in package", e); } }
From source file:AndroidUninstallStock.java
public static LinkedList<String> getLibsInApk(Path apk) throws IOException { LinkedList<String> libs = new LinkedList<String>(); try (JarInputStream jar = new JarInputStream( Files.newInputStream(apk, new StandardOpenOption[] { StandardOpenOption.READ }))) { JarEntry jent;/*from ww w. ja v a 2 s . com*/ int pos; while ((jent = jar.getNextJarEntry()) != null) { if (!jent.isDirectory() && ((pos = jent.getName().indexOf("lib/")) == 0 || pos == 1)) { libs.add(jent.getName()); } } } return libs; }
From source file:org.jahia.utils.maven.plugin.osgi.DependenciesMojo.java
private int scanJar(File jarFile, boolean externalDependency, String packageDirectory, String version, boolean optional, ParsingContext parsingContext, String logPrefix) throws IOException { int scanned = 0; if (jarFile.isDirectory()) { getLog().debug(logPrefix + "Processing dependency directory " + jarFile + "..."); processDirectoryTlds(jarFile, version, parsingContext); processDirectory(jarFile, false, version, parsingContext); return scanned; }//from w w w .ja v a 2s.c om JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile)); try { JarEntry jarEntry = null; getLog().debug(logPrefix + "Processing JAR file " + jarFile + "..."); if (processJarManifest(jarFile, parsingContext, jarInputStream)) { getLog().debug(logPrefix + "Used OSGi bundle manifest information, but scanning for additional resources (taglibs, CNDs, etc)... "); } scanned = processJarInputStream(jarFile.getPath(), externalDependency, packageDirectory, version, optional, parsingContext, logPrefix, scanned, jarInputStream); } finally { jarInputStream.close(); } if (parsingContext.getBundleClassPath().size() > 0) { getLog().debug(logPrefix + "Processing embedded dependencies..."); JarFile jar = new JarFile(jarFile); for (String embeddedJar : parsingContext.getBundleClassPath()) { if (".".equals(embeddedJar)) { continue; } JarEntry jarEntry = jar.getJarEntry(embeddedJar); if (jarEntry != null) { getLog().debug(logPrefix + "Processing embedded JAR..." + jarEntry); InputStream jarEntryInputStream = jar.getInputStream(jarEntry); ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarEntryInputStream, entryOutputStream); JarInputStream entryJarInputStream = new JarInputStream( new ByteArrayInputStream(entryOutputStream.toByteArray())); processJarInputStream(jarFile.getPath() + "!" + jarEntry, externalDependency, packageDirectory, version, optional, parsingContext, logPrefix, scanned, entryJarInputStream); IOUtils.closeQuietly(jarEntryInputStream); IOUtils.closeQuietly(entryJarInputStream); } else { getLog().warn(logPrefix + "Couldn't find embedded JAR to parse " + embeddedJar + " in JAR " + jarFile); } } } if (parsingContext.getAdditionalFilesToParse().size() > 0) { getLog().debug(logPrefix + "Processing additional files to parse..."); JarFile jar = new JarFile(jarFile); for (String fileToParse : parsingContext.getAdditionalFilesToParse()) { JarEntry jarEntry = jar.getJarEntry(fileToParse); if (jarEntry != null) { InputStream jarEntryInputStream = jar.getInputStream(jarEntry); ByteArrayOutputStream entryOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarEntryInputStream, entryOutputStream); if (processNonTldFile(jarEntry.getName(), new ByteArrayInputStream(entryOutputStream.toByteArray()), jarFile.getPath(), optional, version, parsingContext)) { scanned++; } IOUtils.closeQuietly(jarEntryInputStream); } else { getLog().warn(logPrefix + "Couldn't find additional file to parse " + fileToParse + " in JAR " + jarFile); } } parsingContext.clearAdditionalFilesToParse(); } return scanned; }