List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:javadepchecker.Main.java
/** * Check for orphaned class files not owned by any package in dependencies * * @param pkg Gentoo package name/*from www . j a v a2 s . c o m*/ * @param deps collection of dependencies for the package * @return boolean if the dependency is found or not * @throws IOException */ private static boolean depsFound(Collection<String> pkgs, Collection<String> deps) throws IOException { boolean found = true; Collection<String> jars = new ArrayList<>(); String[] bootClassPathJars = System.getProperty("sun.boot.class.path").split(":"); // Do we need "java-config -r" here? for (String jar : bootClassPathJars) { File jarFile = new File(jar); if (jarFile.exists()) { jars.add(jar); } } pkgs.forEach((String pkg) -> { jars.addAll(getPackageJars(pkg)); }); if (jars.isEmpty()) { return false; } ArrayList<String> jarClasses = new ArrayList<>(); jars.forEach((String jarName) -> { try { JarFile jar = new JarFile(jarName); Collections.list(jar.entries()).forEach((JarEntry entry) -> { jarClasses.add(entry.getName()); }); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } }); for (String dep : deps) { if (!jarClasses.contains(dep)) { if (found) { System.out.println("Class files not found via DEPEND in package.env"); } System.out.println("\t" + dep); found = false; } } return found; }
From source file:com.cloudbees.sdk.ArtifactInstallFactory.java
/** * Installs the given artifact and all its transitive dependencies *//* ww w . java 2s . c om*/ public GAV install(GAV gav) throws Exception { Artifact a = toArtifact(gav); List<ArtifactResult> artifactResults = repo.get().resolveDependencies(gav).getArtifactResults(); Plugin plugin = new Plugin(); List<CommandProperties> command = plugin.getProperties(); List<String> jars = plugin.getJars(); List<URL> urls = new ArrayList<URL>(); for (ArtifactResult artifactResult : artifactResults) { URL artifactURL = artifactResult.getArtifact().getFile().toURI().toURL(); urls.add(artifactURL); jars.add(artifactResult.getArtifact().getFile().getAbsolutePath()); } ClassLoader cl = createClassLoader(urls, getClass().getClassLoader()); for (ArtifactResult artifactResult : artifactResults) { if (toString(artifactResult.getArtifact()).equals(toString(a))) { plugin.setArtifact(new GAV(artifactResult.getArtifact().toString()).toString()); // System.out.println("Analysing... " + plugin.getArtifact()); JarFile jarFile = new JarFile(artifactResult.getArtifact().getFile()); Enumeration<JarEntry> e = jarFile.entries(); while (e.hasMoreElements()) { JarEntry entry = e.nextElement(); if (entry.getName().endsWith(".class")) { String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6); Class c = Class.forName(className, false, cl); findCommand(true, command, c); } } } } XStream xStream = new XStream(); xStream.processAnnotations(Plugin.class); xStream.processAnnotations(CommandProperties.class); // System.out.println(xStream.toXML(plugin)); File xmlFile = new File(directoryStructure.getPluginDir(), a.getArtifactId() + ".bees"); OutputStreamWriter fos = null; try { xmlFile.getParentFile().mkdirs(); FileOutputStream outputStream = new FileOutputStream(xmlFile); fos = new OutputStreamWriter(outputStream, Charset.forName("UTF-8")); xStream.toXML(plugin, fos); } finally { IOUtils.closeQuietly(fos); } return new GAV(plugin.getArtifact()); }
From source file:com.amalto.core.jobox.watch.JoboxListener.java
public void contextChanged(String jobFile, String context) { File entity = new File(jobFile); String sourcePath = jobFile;/* w w w . j a v a 2 s .co m*/ int dotMark = jobFile.lastIndexOf("."); //$NON-NLS-1$ int separateMark = jobFile.lastIndexOf(File.separatorChar); if (dotMark != -1) { sourcePath = System.getProperty("java.io.tmpdir") + File.separatorChar //$NON-NLS-1$ + jobFile.substring(separateMark, dotMark); } try { JoboxUtil.extract(jobFile, System.getProperty("java.io.tmpdir") + File.separatorChar); //$NON-NLS-1$ } catch (Exception e1) { LOGGER.error("Extraction exception occurred.", e1); return; } List<File> resultList = new ArrayList<File>(); JoboxUtil.findFirstFile(null, new File(sourcePath), "classpath.jar", resultList); //$NON-NLS-1$ if (!resultList.isEmpty()) { JarInputStream jarIn = null; JarOutputStream jarOut = null; try { JarFile jarFile = new JarFile(resultList.get(0)); Manifest mf = jarFile.getManifest(); jarIn = new JarInputStream(new FileInputStream(resultList.get(0))); Manifest newManifest = jarIn.getManifest(); if (newManifest == null) { newManifest = new Manifest(); } newManifest.getMainAttributes().putAll(mf.getMainAttributes()); newManifest.getMainAttributes().putValue("activeContext", context); //$NON-NLS-1$ jarOut = new JarOutputStream(new FileOutputStream(resultList.get(0)), newManifest); byte[] buf = new byte[4096]; JarEntry entry; while ((entry = jarIn.getNextJarEntry()) != null) { if ("META-INF/MANIFEST.MF".equals(entry.getName())) { //$NON-NLS-1$ continue; } jarOut.putNextEntry(entry); int read; while ((read = jarIn.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); } } catch (Exception e) { LOGGER.error("Extraction exception occurred.", e); } finally { IOUtils.closeQuietly(jarIn); IOUtils.closeQuietly(jarOut); } // re-zip file if (entity.getName().endsWith(".zip")) { //$NON-NLS-1$ File sourceFile = new File(sourcePath); try { JoboxUtil.zip(sourceFile, jobFile); } catch (Exception e) { LOGGER.error("Zip exception occurred.", e); } } } }
From source file:com.liferay.ide.ui.editor.LiferayPropertiesSourceViewerConfiguration.java
@Override public IContentAssistant getContentAssistant(final ISourceViewer sourceViewer) { if (this.propKeys == null) { final IEditorInput input = this.getEditor().getEditorInput(); // first fine runtime location to get properties definitions final IPath appServerPortalDir = getAppServerPortalDir(input); final String propertiesEntry = getPropertiesEntry(input); PropKey[] keys = null;//w ww .ja v a2 s .c o m if (appServerPortalDir != null && appServerPortalDir.toFile().exists()) { try { final JarFile jar = new JarFile( appServerPortalDir.append("WEB-INF/lib/portal-impl.jar").toFile()); final ZipEntry lang = jar.getEntry(propertiesEntry); keys = parseKeys(jar.getInputStream(lang)); jar.close(); } catch (Exception e) { LiferayUIPlugin.logError("Unable to get portal properties file", e); } } else { return assitant; } final Object adapter = input.getAdapter(IFile.class); if (adapter instanceof IFile && isHookProject(((IFile) adapter).getProject())) { final ILiferayProject liferayProject = LiferayCore.create(((IFile) adapter).getProject()); final ILiferayPortal portal = liferayProject.adapt(ILiferayPortal.class); if (portal != null) { final Set<String> hookProps = new HashSet<String>(); Collections.addAll(hookProps, portal.getHookSupportedProperties()); final List<PropKey> filtered = new ArrayList<PropKey>(); for (PropKey pk : keys) { if (hookProps.contains(pk.getKey())) { filtered.add(pk); } } keys = filtered.toArray(new PropKey[0]); } } propKeys = keys; } if (propKeys != null && assitant == null) { final ContentAssistant ca = new ContentAssistant() { @Override public IContentAssistProcessor getContentAssistProcessor(final String contentType) { return new LiferayPropertiesContentAssistProcessor(propKeys, contentType); } }; ca.setInformationControlCreator(getInformationControlCreator(sourceViewer)); assitant = ca; } return assitant; }
From source file:kilim.tools.FlowAnalyzer.java
public static void analyzeJar(String jarFile, Detector detector) { try {/*from www. j a v a2 s . c o m*/ Enumeration<JarEntry> e = new JarFile(jarFile).entries(); while (e.hasMoreElements()) { ZipEntry en = (ZipEntry) e.nextElement(); String n = en.getName(); if (!n.endsWith(".class")) continue; n = n.substring(0, n.length() - 6).replace('/', '.'); analyzeClass(n, detector); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.norconex.commons.lang.ClassFinder.java
private static List<String> findSubTypesFromJar(File jarFile, Class<?> superClass) { List<String> classes = new ArrayList<String>(); ClassLoader loader = getClassLoader(jarFile); if (loader == null) { return classes; }// w ww. j a va 2 s. co m JarFile jar = null; try { jar = new JarFile(jarFile); } catch (IOException e) { LOG.error("Invalid JAR: " + jarFile, e); return classes; } Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String className = entry.getName(); className = resolveName(loader, className, superClass); if (className != null) { classes.add(className); } } try { jar.close(); } catch (IOException e) { LOG.error("Could not close JAR.", e); } return classes; }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleDeployMojo.java
/** * Change the version in jar/* www . j a v a 2s .c om*/ * * @param newVersion * @param file * @return * @throws MojoExecutionException */ protected File changeVersion(File file, String oldVersion, String newVersion) throws MojoExecutionException { String fileName = file.getName(); int pos = fileName.indexOf(oldVersion); fileName = fileName.substring(0, pos) + newVersion + fileName.substring(pos + oldVersion.length()); JarInputStream jis = null; JarOutputStream jos; OutputStream out = null; JarFile sourceJar = null; try { // now create a temporary file and update the version sourceJar = new JarFile(file); final Manifest manifest = sourceJar.getManifest(); manifest.getMainAttributes().putValue("Bundle-Version", newVersion); jis = new JarInputStream(new FileInputStream(file)); final File destJar = new File(file.getParentFile(), fileName); out = new FileOutputStream(destJar); jos = new JarOutputStream(out, manifest); jos.setMethod(JarOutputStream.DEFLATED); jos.setLevel(Deflater.BEST_COMPRESSION); JarEntry entryIn = jis.getNextJarEntry(); while (entryIn != null) { JarEntry entryOut = new JarEntry(entryIn.getName()); entryOut.setTime(entryIn.getTime()); entryOut.setComment(entryIn.getComment()); jos.putNextEntry(entryOut); if (!entryIn.isDirectory()) { IOUtils.copy(jis, jos); } jos.closeEntry(); jis.closeEntry(); entryIn = jis.getNextJarEntry(); } // close the JAR file now to force writing jos.close(); return destJar; } catch (IOException ioe) { throw new MojoExecutionException("Unable to update version in jar file.", ioe); } finally { if (sourceJar != null) { try { sourceJar.close(); } catch (IOException ex) { // close } } IOUtils.closeQuietly(jis); IOUtils.closeQuietly(out); } }
From source file:com.smartitengineering.util.simple.reflection.DefaultClassScannerImpl.java
private JarFile getJarFile(File file) { if (file == null) { return null; }//from w w w. j a v a 2 s . c o m try { return new JarFile(file); } catch (IOException ex) { throw new RuntimeException(ex); } }
From source file:hermes.impl.LoaderSupport.java
/** * Return ClassLoader given the list of ClasspathConfig instances. The * resulting loader can then be used to instantiate providers from those * libraries.//from w w w. j av a2 s. co m */ static List lookForFactories(final List loaderConfigs, final ClassLoader baseLoader) throws IOException { final List rval = new ArrayList(); for (Iterator iter = loaderConfigs.iterator(); iter.hasNext();) { final ClasspathConfig lConfig = (ClasspathConfig) iter.next(); if (lConfig.getFactories() != null) { log.debug("using cached " + lConfig.getFactories()); for (StringTokenizer tokens = new StringTokenizer(lConfig.getFactories(), ","); tokens .hasMoreTokens();) { rval.add(tokens.nextToken()); } } else if (lConfig.isNoFactories()) { log.debug("previously scanned " + lConfig.getJar()); } else { Runnable r = new Runnable() { public void run() { final List localFactories = new ArrayList(); boolean foundFactory = false; StringBuffer factoriesAsString = null; try { log.debug("searching " + lConfig.getJar()); ClassLoader l = createClassLoader(loaderConfigs, baseLoader); JarFile jarFile = new JarFile(lConfig.getJar()); ProgressMonitor monitor = null; int entryNumber = 0; if (HermesBrowser.getBrowser() != null) { monitor = new ProgressMonitor(HermesBrowser.getBrowser(), "Looking for factories in " + lConfig.getJar(), "Scanning...", 0, jarFile.size()); monitor.setMillisToDecideToPopup(0); monitor.setMillisToPopup(0); monitor.setProgress(0); } for (Enumeration iter = jarFile.entries(); iter.hasMoreElements();) { ZipEntry entry = (ZipEntry) iter.nextElement(); entryNumber++; if (monitor != null) { monitor.setProgress(entryNumber); monitor.setNote("Checking entry " + entryNumber + " of " + jarFile.size()); } if (entry.getName().endsWith(".class")) { String s = entry.getName().substring(0, entry.getName().indexOf(".class")); s = s.replaceAll("/", "."); try { if (s.startsWith("hermes.browser") || s.startsWith("hermes.impl") || s.startsWith("javax.jms")) { // NOP } else { Class clazz = l.loadClass(s); if (!clazz.isInterface()) { if (implementsOrExtends(clazz, ConnectionFactory.class)) { foundFactory = true; localFactories.add(s); if (factoriesAsString == null) { factoriesAsString = new StringBuffer(); factoriesAsString.append(clazz.getName()); } else { factoriesAsString.append(",").append(clazz.getName()); } log.debug("found " + clazz.getName()); } } /** * TODO: remove Class clazz = l.loadClass(s); * Class[] interfaces = clazz.getInterfaces(); * for (int i = 0; i < interfaces.length; i++) { * if * (interfaces[i].equals(TopicConnectionFactory.class) || * interfaces[i].equals(QueueConnectionFactory.class) || * interfaces[i].equals(ConnectionFactory.class)) { * foundFactory = true; localFactories.add(s); * if (factoriesAsString == null) { * factoriesAsString = new * StringBuffer(clazz.getName()); } else { * factoriesAsString.append(",").append(clazz.getName()); } * log.debug("found " + clazz.getName()); } } */ } } catch (Throwable t) { // NOP } } } } catch (IOException e) { log.error("unable to access jar/zip " + lConfig.getJar() + ": " + e.getMessage(), e); } if (!foundFactory) { lConfig.setNoFactories(true); } else { lConfig.setFactories(factoriesAsString.toString()); rval.addAll(localFactories); } } }; r.run(); } } return rval; }
From source file:org.ebayopensource.turmeric.eclipse.utils.classloader.SOAPluginClassLoader.java
/** * {@inheritDoc}/*from w ww. j a v a 2 s .com*/ */ @Override public URL findResource(String resourceName) { //logger.info("resource name in findresource is " + resourceName); try { URL retUrl = null; for (Bundle pluginBundle : pluginBundles) { retUrl = pluginBundle.getResource(resourceName); if (retUrl != null) { if (logger.isLoggable(Level.FINE)) { logger.fine("found resource using bundle " + resourceName); } return retUrl; } } } catch (Exception exception) { } for (URL url : m_jarURLs) { try { File file = FileUtils.toFile(url); JarFile jarFile; jarFile = new JarFile(file); JarEntry jarEntry = jarFile.getJarEntry(resourceName); if (jarEntry != null) { SOAToolFileUrlHandler handler = new SOAToolFileUrlHandler(jarFile, jarEntry); URL retUrl = new URL("jar", "", -1, new File(jarFile.getName()).toURI().toURL() + "!/" + jarEntry.getName(), handler); handler.setExpectedUrl(retUrl); return retUrl; } } catch (IOException e) { e.printStackTrace(); // KEEPME } } return super.findResource(resourceName); }