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.apache.maven.plugins.help.EvaluateMojo.java
/** * @param xstreamObject not null/*from ww w .j a v a 2s.co m*/ * @param jarFile not null * @param packageFilter a package name to filter. */ private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) { JarInputStream jarStream = null; try { jarStream = new JarInputStream(new FileInputStream(jarFile)); JarEntry jarEntry = jarStream.getNextJarEntry(); while (jarEntry != null) { if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) { String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf(".")); name = name.replaceAll("/", "\\."); if (name.contains(packageFilter)) { try { Class<?> clazz = ClassUtils.getClass(name); String alias = StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(clazz)); xstreamObject.alias(alias, clazz); if (!clazz.equals(Model.class)) { xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field } } catch (ClassNotFoundException e) { getLog().error(e); } } } jarStream.closeEntry(); jarEntry = jarStream.getNextJarEntry(); } } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug("IOException: " + e.getMessage(), e); } } finally { IOUtil.close(jarStream); } }
From source file:spring.osgi.io.OsgiBundleResourcePatternResolver.java
/** * Checks the jar entries from the Bundle-Classpath for the given pattern. * * @param list paths/*from ww w .j a va 2 s .c o m*/ * @param url url * @param pattern pattern */ private void findBundleClassPathMatchingJarEntries(List<String> list, URL url, String pattern) throws IOException { // get the stream to the resource and read it as a jar JarInputStream jis = new JarInputStream(url.openStream()); Set<String> result = new LinkedHashSet<>(8); boolean patternWithFolderSlash = pattern.startsWith(FOLDER_SEPARATOR); // parse the jar and do pattern matching try { while (jis.available() > 0) { JarEntry jarEntry = jis.getNextJarEntry(); // if the jar has ended, the entry can be null (on Sun JDK at least) if (jarEntry != null) { String entryPath = jarEntry.getName(); // check if leading "/" is needed or not (it depends how the jar was created) if (entryPath.startsWith(FOLDER_SEPARATOR)) { if (!patternWithFolderSlash) { entryPath = entryPath.substring(FOLDER_SEPARATOR.length()); } } else { if (patternWithFolderSlash) { entryPath = FOLDER_SEPARATOR.concat(entryPath); } } if (getPathMatcher().match(pattern, entryPath)) { result.add(entryPath); } } } } finally { try { jis.close(); } catch (IOException io) { // ignore it - nothing we can't do about it } } if (logger.isTraceEnabled()) logger.trace("Found in nested jar [" + url + "] matching entries " + result); list.addAll(result); }
From source file:org.eclipse.gemini.blueprint.io.OsgiBundleResourcePatternResolver.java
/** * Checks the jar entries from the Bundle-Classpath for the given pattern. * /* www. ja va2 s . c o m*/ * @param list * @param ur */ private void findBundleClassPathMatchingJarEntries(List<String> list, URL url, String pattern) throws IOException { // get the stream to the resource and read it as a jar JarInputStream jis = new JarInputStream(url.openStream()); Set<String> result = new LinkedHashSet<String>(8); boolean patternWithFolderSlash = pattern.startsWith(FOLDER_SEPARATOR); // parse the jar and do pattern matching try { while (jis.available() > 0) { JarEntry jarEntry = jis.getNextJarEntry(); // if the jar has ended, the entry can be null (on Sun JDK at least) if (jarEntry != null) { String entryPath = jarEntry.getName(); // check if leading "/" is needed or not (it depends how the jar was created) if (entryPath.startsWith(FOLDER_SEPARATOR)) { if (!patternWithFolderSlash) { entryPath = entryPath.substring(FOLDER_SEPARATOR.length()); } } else { if (patternWithFolderSlash) { entryPath = FOLDER_SEPARATOR.concat(entryPath); } } if (getPathMatcher().match(pattern, entryPath)) { result.add(entryPath); } } } } finally { try { jis.close(); } catch (IOException io) { // ignore it - nothing we can't do about it } } if (logger.isTraceEnabled()) logger.trace("Found in nested jar [" + url + "] matching entries " + result); list.addAll(result); }
From source file:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java
private void processJarFile(InputStream inputStream, String jarFilePath, JarMetadata contextJarMetadata, boolean processMavenPom, int level, boolean lookForNotice, boolean lookForLicense, boolean processingSources) throws IOException { // if we don't need to find either a license or notice, don't process the jar at all if (!lookForLicense && !lookForNotice) { return;/*from w ww . ja v a 2s. c om*/ } final String indent = getIndent(level); output(indent, "Processing JAR " + jarFilePath + "...", false, true); // JarFile realJarFile = new JarFile(jarFile); JarInputStream jarInputStream = new JarInputStream(inputStream); String bundleLicense = null; Manifest manifest = jarInputStream.getManifest(); if (manifest != null && manifest.getMainAttributes() != null) { bundleLicense = manifest.getMainAttributes().getValue("Bundle-License"); if (bundleLicense != null) { output(indent, "Found Bundle-License attribute with value:" + bundleLicense); KnownLicense knownLicense = getKnowLicenseByName(bundleLicense); // this data is not reliable, especially on the ServiceMix repackaged bundles } } String pomFilePath = null; byte[] pomByteArray = null; final String jarFileName = getJarFileName(jarFilePath); if (contextJarMetadata == null) { contextJarMetadata = jarDatabase.get(jarFileName); if (contextJarMetadata == null) { // compute project name contextJarMetadata = new JarMetadata(jarFilePath, jarFileName); } jarDatabase.put(jarFileName, contextJarMetadata); } Notice notice; JarEntry curJarEntry = null; while ((curJarEntry = jarInputStream.getNextJarEntry()) != null) { if (!curJarEntry.isDirectory()) { final String fileName = curJarEntry.getName(); if (lookForNotice && isNotice(fileName, jarFilePath)) { output(indent, "Processing notice found in " + curJarEntry + "..."); InputStream noticeInputStream = jarInputStream; List<String> noticeLines = IOUtils.readLines(noticeInputStream); notice = new Notice(noticeLines); Map<String, Notice> notices = contextJarMetadata.getNoticeFiles(); if (notices == null) { notices = new TreeMap<>(); notices.put(fileName, notice); output(indent, "Found first notice " + curJarEntry); } else if (!notices.containsValue(notice)) { output(indent, "Found additional notice " + curJarEntry); notices.put(fileName, notice); } else { output(indent, "Duplicated notice in " + curJarEntry); notices.put(fileName, notice); duplicatedNotices.add(jarFilePath); } // IOUtils.closeQuietly(noticeInputStream); } else if (processMavenPom && fileName.endsWith("pom.xml")) { // remember pom file path in case we need it pomFilePath = curJarEntry.getName(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(jarInputStream, byteArrayOutputStream); pomByteArray = byteArrayOutputStream.toByteArray(); } else if (lookForLicense && isLicense(fileName, jarFilePath)) { output(indent, "Processing license found in " + curJarEntry + "..."); InputStream licenseInputStream = jarInputStream; List<String> licenseLines = IOUtils.readLines(licenseInputStream); LicenseFile licenseFile = new LicenseFile(jarFilePath, fileName, jarFilePath, licenseLines); resolveKnownLicensesByText(licenseFile); if (StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText()) && StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText().trim())) { KnownLicense knownLicense = new KnownLicense(); knownLicense.setId(FilenameUtils.getBaseName(jarFilePath) + "-additional-terms"); knownLicense .setName("Additional license terms from " + FilenameUtils.getBaseName(jarFilePath)); List<TextVariant> textVariants = new ArrayList<>(); TextVariant textVariant = new TextVariant(); textVariant.setId("default"); textVariant.setDefaultVariant(true); textVariant.setText(Pattern.quote(licenseFile.getAdditionalLicenseText())); textVariants.add(textVariant); knownLicense.setTextVariants(textVariants); knownLicense.setTextToUse(licenseFile.getAdditionalLicenseText()); knownLicense.setViral(licenseFile.getText().toLowerCase().contains("gpl")); knownLicenses.getLicenses().put(knownLicense.getId(), knownLicense); licenseFile.getKnownLicenses().add(knownLicense); licenseFile.getKnownLicenseKeys().add(knownLicense.getId()); } for (KnownLicense knownLicense : licenseFile.getKnownLicenses()) { SortedSet<LicenseFile> licenseFiles = knownLicensesFound.get(knownLicense); if (licenseFiles != null) { if (!licenseFiles.contains(licenseFile)) { licenseFiles.add(licenseFile); } knownLicensesFound.put(knownLicense, licenseFiles); } else { licenseFiles = new TreeSet<>(); licenseFiles.add(licenseFile); knownLicensesFound.put(knownLicense, licenseFiles); } } Map<String, LicenseFile> licenseFiles = contextJarMetadata.getLicenseFiles(); if (licenseFiles == null) { licenseFiles = new TreeMap<>(); } if (licenseFiles.containsKey(fileName)) { // warning we already have a license file here, what should we do ? output(indent, "License file already exists for " + jarFilePath + " will override it !", true, false); licenseFiles.remove(fileName); } licenseFiles.put(fileName, licenseFile); // IOUtils.closeQuietly(licenseInputStream); } else if (fileName.endsWith(".jar")) { InputStream embeddedJarInputStream = jarInputStream; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(embeddedJarInputStream, byteArrayOutputStream); final JarMetadata embeddedJarMetadata = new JarMetadata(jarFilePath, getJarFileName(fileName)); if (embeddedJarMetadata != null) { embeddedJarMetadata.setJarContents(byteArrayOutputStream.toByteArray()); contextJarMetadata.getEmbeddedJars().add(embeddedJarMetadata); } } else if (fileName.endsWith(".class")) { String className = fileName.substring(0, fileName.length() - ".class".length()).replaceAll("/", "."); int lastPoint = className.lastIndexOf("."); String packageName = null; if (lastPoint > 0) { packageName = className.substring(0, lastPoint); SortedSet<String> currentJarPackages = jarDatabase .get(FilenameUtils.getBaseName(jarFilePath)).getPackages(); if (currentJarPackages == null) { currentJarPackages = new TreeSet<>(); } currentJarPackages.add(packageName); } } } jarInputStream.closeEntry(); } jarInputStream.close(); jarInputStream = null; if (!contextJarMetadata.getEmbeddedJars().isEmpty()) { for (JarMetadata embeddedJarMetadata : contextJarMetadata.getEmbeddedJars()) { if (embeddedJarMetadata.getJarContents() != null) { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( embeddedJarMetadata.getJarContents()); processJarFile(byteArrayInputStream, contextJarMetadata.toString(), null, true, level, true, true, processingSources); } else { output(indent, "Couldn't find dependency for embedded JAR " + contextJarMetadata, true, false); } } } if (processMavenPom) { if (pomFilePath == null) { output(indent, "No POM found in " + jarFilePath); } else { output(indent, "Processing POM found at " + pomFilePath + " in " + jarFilePath + "..."); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pomByteArray); processJarPOM(byteArrayInputStream, pomFilePath, jarFilePath, contextJarMetadata, lookForNotice, lookForLicense, contextJarMetadata.getEmbeddedJars(), level + 1, processingSources); } } if (lookForLicense || lookForNotice) { if (lookForLicense) { output(indent, "No license found in " + jarFilePath); } if (lookForNotice) { output(indent, "No notice found in " + jarFilePath); } if (pomFilePath == null && lookForLicense && lookForNotice) { if (StringUtils.isBlank(contextJarMetadata.getVersion())) { output(indent, "Couldn't resolve version for JAR " + contextJarMetadata + ", can't query Maven Central repository without version !"); } else { List<Artifact> mavenCentralArtifacts = findArtifactInMavenCentral(contextJarMetadata.getName(), contextJarMetadata.getVersion(), contextJarMetadata.getClassifier()); if (mavenCentralArtifacts != null && mavenCentralArtifacts.size() == 1) { Artifact mavenCentralArtifact = mavenCentralArtifacts.get(0); Artifact resolvedArtifact = resolveArtifact(mavenCentralArtifact, level); if (resolvedArtifact != null) { // we have a copy of the local artifact, let's request the sources for it. if (!processingSources && !"sources".equals(contextJarMetadata.getClassifier())) { final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(), resolvedArtifact.getArtifactId(), "sources", "jar", resolvedArtifact.getVersion()); File sourceJar = getArtifactFile(artifact, level); if (sourceJar != null && sourceJar.exists()) { FileInputStream sourceJarInputStream = new FileInputStream(sourceJar); processJarFile(sourceJarInputStream, sourceJar.getPath(), contextJarMetadata, false, level + 1, lookForNotice, lookForLicense, true); IOUtils.closeQuietly(sourceJarInputStream); } } else { // we are already processing a sources artifact, we need to load the pom artifact to extract information from there final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(), resolvedArtifact.getArtifactId(), null, "pom", resolvedArtifact.getVersion()); File artifactPom = getArtifactFile(artifact, level); if (artifactPom != null && artifactPom.exists()) { output(indent, "Processing POM for " + artifact + "..."); processPOM(lookForNotice, lookForLicense, jarFilePath, contextJarMetadata, contextJarMetadata.getEmbeddedJars(), level + 1, new FileInputStream(artifactPom), processingSources); } } } else { output(indent, "===> Couldn't resolve artifact " + mavenCentralArtifact + " in Maven Central. Please resolve license and notice files manually!", false, true); } } else { output(indent, "===> Couldn't find nor POM, license or notice. Please check manually!", false, true); } } } } output(indent, "Done processing JAR " + jarFilePath + ".", false, true); }
From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java
private Manifest jarDirectoryAndReadManifest(Manifest fromJar, Manifest fromUser, boolean mergeEntries) throws IOException { // Create a jar with a manifest we'd expect to see merged. Path originalJar = folder.newFile("unexpected.jar"); JarOutputStream ignored = new JarOutputStream(Files.newOutputStream(originalJar), fromJar); ignored.close();//from w w w . j ava 2s . c om // Now create the actual manifest Path manifestFile = folder.newFile("actual_manfiest.mf"); try (OutputStream os = Files.newOutputStream(manifestFile)) { fromUser.write(os); } Path tmp = folder.newFolder(); Path output = tmp.resolve("example.jar"); JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), output, ImmutableSortedSet.of(originalJar), /* main class */ null, manifestFile, mergeEntries, /* blacklist */ ImmutableSet.of()); ExecutionContext context = TestExecutionContext.newInstance(); step.execute(context); // Now verify that the created manifest matches the expected one. try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) { return jis.getManifest(); } }
From source file:org.apache.sling.testing.clients.osgi.OsgiConsoleClient.java
/** * Get the symbolic name from a bundle file * @param bundleFile/* ww w .j a va 2 s . c o m*/ * @return * @throws IOException */ public static String getBundleSymbolicName(File bundleFile) throws IOException { String name = null; final JarInputStream jis = new JarInputStream(new FileInputStream(bundleFile)); try { final Manifest m = jis.getManifest(); if (m == null) { throw new IOException("Manifest is null in " + bundleFile.getAbsolutePath()); } name = m.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); } finally { jis.close(); } return name; }
From source file:org.eclipse.wb.internal.core.editor.palette.dialogs.ImportArchiveDialog.java
private void chooseArchive(IFile jarIFile, File jarFile) { try {// w ww .j ava 2s . c om // prepare path boolean canFile = jarIFile == null; m_jarPath = canFile ? jarFile.getAbsolutePath() : jarIFile.getLocation().toPortableString(); // load elements over manifest boolean ignoreManifest = m_ignoreManifestButton.getSelection(); m_elements = Collections.emptyList(); if (!ignoreManifest) { JarInputStream jarStream = new JarInputStream( canFile ? new FileInputStream(jarFile) : jarIFile.getContents(true)); m_elements = extractElementsFromJarByManifest(jarStream); jarStream.close(); } // check load all elements if (ignoreManifest || m_elements.isEmpty()) { if (!ignoreManifest) { String message = MessageFormat.format(Messages.ImportArchiveDialog_hasManifestMessage, m_jarPath); ignoreManifest = MessageDialog.openQuestion(getShell(), Messages.ImportArchiveDialog_hasManifestTitle, message); } if (ignoreManifest) { JarInputStream jarStream = new JarInputStream( canFile ? new FileInputStream(jarFile) : jarIFile.getContents(true)); m_elements = extractElementsFromJarAllClasses(jarStream); jarStream.close(); } } // sets elements m_classesViewer.setInput(m_elements.toArray()); // handle jar combo int removeIndex = m_fileArchiveCombo.indexOf(m_jarPath); if (removeIndex != -1) { m_fileArchiveCombo.remove(removeIndex); } m_fileArchiveCombo.add(m_jarPath, 0); int archiveCount = m_fileArchiveCombo.getItemCount(); if (archiveCount > JAR_COMBO_SIZE) { m_fileArchiveCombo.remove(JAR_COMBO_SIZE, archiveCount - 1); } if (!m_fileArchiveCombo.getText().equals(m_jarPath)) { m_fileArchiveCombo.setText(m_jarPath); m_fileArchiveCombo.setSelection(new Point(0, m_jarPath.length())); } // handle category if (m_elements.isEmpty()) { m_categoryText.setText(""); } else { // convert 'foo.jar' to 'foo' String categoryName = canFile ? jarFile.getName() : jarIFile.getName(); m_categoryText.setText(categoryName.substring(0, categoryName.length() - JAR_SUFFIX.length())); } } catch (Throwable t) { m_jarPath = null; m_elements = Collections.emptyList(); m_classesViewer.setInput(ArrayUtils.EMPTY_OBJECT_ARRAY); m_categoryText.setText(""); } finally { calculateFinish(); } }
From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java
/** * Fetch all the entries in the given (jar) input stream and look for the * plugin directory.//from ww w . j av a2 s . com * * @param is the input stream to analyse */ private Set<String> discoverJarPlugin(InputStream is) { Set<String> plugins = new HashSet<String>(); if (null == is) { return plugins; } JarEntry je = null; try { JarInputStream jis = new JarInputStream(is); do { je = jis.getNextJarEntry(); if (null != je) { String URL = je.toString(); if (URL.contains(PLUGIN_DIRECTORY) && URL.endsWith(PLUGIN_APSADMIN_PATH)) { plugins.add(URL); } } } while (je != null); } catch (Throwable t) { _logger.error("error in discoverJarPlugin", t); //ApsSystemUtils.logThrowable(t, this, "discoverJarPlugin"); } return plugins; }
From source file:org.apache.sling.testing.clients.osgi.OsgiConsoleClient.java
/** * Get the version form a bundle file/*from ww w.ja v a 2 s . co m*/ * @param bundleFile * @return * @throws IOException */ public static String getBundleVersionFromFile(File bundleFile) throws IOException { String version = null; final JarInputStream jis = new JarInputStream(new FileInputStream(bundleFile)); try { final Manifest m = jis.getManifest(); if (m == null) { throw new IOException("Manifest is null in " + bundleFile.getAbsolutePath()); } version = m.getMainAttributes().getValue(Constants.BUNDLE_VERSION); } finally { jis.close(); } return version; }
From source file:org.hyperic.hq.product.server.session.PluginManagerImpl.java
private File getFileAndValidateJar(String filename, byte[] bytes) throws PluginDeployException { ByteArrayInputStream bais = null; JarInputStream jis = null;/*from www . j a va2 s. c om*/ FileOutputStream fos = null; String file = null; try { bais = new ByteArrayInputStream(bytes); jis = new JarInputStream(bais); final Manifest manifest = jis.getManifest(); if (manifest == null) { throw new PluginDeployException("plugin.manager.jar.manifest.does.not.exist", filename); } file = TMP_DIR + File.separator + filename; fos = new FileOutputStream(file); fos.write(bytes); fos.flush(); final File rtn = new File(file); final URL url = new URL("jar", "", "file:" + file + "!/"); final JarURLConnection jarConn = (JarURLConnection) url.openConnection(); final JarFile jarFile = jarConn.getJarFile(); processJarEntries(jarFile, file, filename); return rtn; } catch (IOException e) { final File toRemove = new File(file); if (toRemove != null && toRemove.exists()) { toRemove.delete(); } throw new PluginDeployException("plugin.manager.file.ioexception", e, filename); } finally { close(jis); close(fos); } }