List of usage examples for java.util.jar JarFile JarFile
public JarFile(File file) throws IOException
From source file:com.dragome.compiler.utils.FileManager.java
public FileManager(List<File> classPath, FileFilter classpathFilter) { this.classpathFilter = classpathFilter; Log.getLogger().debug("Resolving class path " + classPath); for (File file : classPath) { if (!file.exists()) { DragomeJsCompiler.errorCount++; Log.getLogger().error("Cannot find resource on class path: " + file.getAbsolutePath()); continue; }//ww w . j a v a 2s . co m if (file.getName().endsWith(".jar")) { try { path.add(new JarFile(file)); } catch (IOException e) { throw new RuntimeException(e); } } else { path.add(file); } } }
From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginDescriptorBuilder.java
public GoPluginDescriptor build(File pluginJarFile, boolean isBundledPlugin) { if (!pluginJarFile.exists()) { throw new RuntimeException( String.format("Plugin jar does not exist: %s", pluginJarFile.getAbsoluteFile())); }//from w ww . jav a2 s .c o m InputStream pluginXMLStream = null; JarFile jarFile = null; try { jarFile = new JarFile(pluginJarFile); ZipEntry entry = jarFile.getEntry(PLUGIN_XML); if (entry == null) { return GoPluginDescriptor.usingId(pluginJarFile.getName(), pluginJarFile.getAbsolutePath(), getBundleLocation(bundlePathLocation, pluginJarFile.getName()), isBundledPlugin); } pluginXMLStream = jarFile.getInputStream(entry); return GoPluginDescriptorParser.parseXML(pluginXMLStream, pluginJarFile.getAbsolutePath(), getBundleLocation(bundlePathLocation, pluginJarFile.getName()), isBundledPlugin); } catch (Exception e) { LOGGER.warn("Could not load plugin with jar filename:" + pluginJarFile.getName(), e); String cause = e.getCause() != null ? String.format("%s. Cause: %s", e.getMessage(), e.getCause().getMessage()) : e.getMessage(); return GoPluginDescriptor .usingId(pluginJarFile.getName(), pluginJarFile.getAbsolutePath(), getBundleLocation(bundlePathLocation, pluginJarFile.getName()), isBundledPlugin) .markAsInvalid(Arrays.asList( String.format("Plugin with ID (%s) is not valid: %s", pluginJarFile.getName(), cause)), e); } finally { IOUtils.closeQuietly(pluginXMLStream); closeQuietly(jarFile); } }
From source file:org.commonjava.maven.galley.filearc.internal.ZipListing.java
@Override public ListingResult call() { final File src = getArchiveFile(resource.getLocationUri()); if (!src.canRead() || src.isDirectory()) { return null; }//from w w w. j ava 2 s.co m final boolean isJar = isJar(resource.getLocationUri()); final TreeSet<String> filenames = new TreeSet<String>(); ZipFile zf = null; try { if (isJar) { zf = new JarFile(src); } else { zf = new ZipFile(src); } final String path = resource.getPath(); final int pathLen = path.length(); for (final ZipEntry entry : Collections.list(zf.entries())) { String name = entry.getName(); if (name.startsWith(path)) { name = name.substring(pathLen); if (name.startsWith("/") && name.length() > 1) { name = name.substring(1); if (name.indexOf("/") < 0) { filenames.add(name); } } } } } catch (final IOException e) { error = new TransferException("Failed to get listing for: %s to: %s. Reason: %s", e, resource, e.getMessage()); } finally { if (zf != null) { try { zf.close(); } catch (final IOException e) { } } } if (!filenames.isEmpty()) { OutputStream stream = null; try { stream = target.openOutputStream(TransferOperation.DOWNLOAD); stream.write(join(filenames, "\n").getBytes("UTF-8")); return new ListingResult(resource, filenames.toArray(new String[filenames.size()])); } catch (final IOException e) { error = new TransferException("Failed to write listing to: %s. Reason: %s", e, target, e.getMessage()); } finally { closeQuietly(stream); } } return null; }
From source file:org.apache.hama.monitor.Configurator.java
/** * Load jar from specified path.//ww w. j a v a 2 s .com * * @param path to the jar file. * @param loader of the current thread. * @return task to be run. */ private static Task load(File path, ClassLoader loader) throws IOException { JarFile jar = new JarFile(path); Manifest manifest = jar.getManifest(); String pkg = manifest.getMainAttributes().getValue("Package"); String main = manifest.getMainAttributes().getValue("Main-Class"); if (null == pkg || null == main) throw new NullPointerException("Package or main class not found " + "in menifest file."); String namespace = pkg + File.separator + main; namespace = namespace.replaceAll(File.separator, "."); LOG.debug("Task class to be loaded: " + namespace); URLClassLoader child = new URLClassLoader(new URL[] { path.toURI().toURL() }, loader); Thread.currentThread().setContextClassLoader(child); Class<?> taskClass = null; try { taskClass = Class.forName(namespace, true, child); // task class } catch (ClassNotFoundException cnfe) { LOG.warn("Task class is not found.", cnfe); } if (null == taskClass) return null; try { return (Task) taskClass.newInstance(); } catch (InstantiationException ie) { LOG.warn("Unable to instantiate task class." + namespace, ie); } catch (IllegalAccessException iae) { LOG.warn(iae); } return null; }
From source file:org.atricore.idbus.kernel.main.util.ClassFinderImpl.java
public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException { try {/*from w ww .ja v a 2s. co m*/ ArrayList<Class> classes = new ArrayList<Class>(); URLClassLoader ucl = (URLClassLoader) cl; URL[] srcURL = ucl.getURLs(); String path = pkg.replace('.', '/'); //Read resources as URL from class loader. for (URL url : srcURL) { if ("file".equals(url.getProtocol())) { File f = new File(url.toURI().getPath()); //If file is not of type directory then its a jar file if (f.exists() && !f.isDirectory()) { try { JarFile jf = new JarFile(f); Enumeration<JarEntry> entries = jf.entries(); //read all entries in jar file while (entries.hasMoreElements()) { JarEntry je = entries.nextElement(); String clazzName = je.getName(); if (clazzName != null && clazzName.endsWith(".class")) { //Add to class list here. clazzName = clazzName.substring(0, clazzName.length() - 6); clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.'); //We are only going to add the class that belong to the provided package. if (clazzName.startsWith(pkg + ".")) { try { Class clazz = forName(clazzName, false, cl); // Don't add any interfaces or JAXWS specific classes. // Only classes that represent data and can be marshalled // by JAXB should be added. if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg) && ClassUtils.getDefaultPublicConstructor(clazz) != null && !ClassUtils.isJAXWSClass(clazz)) { if (log.isDebugEnabled()) { log.debug("Adding class: " + clazzName); } classes.add(clazz); } //catch Throwable as ClassLoader can throw an NoClassDefFoundError that //does not extend Exception, so lets catch everything that extends Throwable //rather than just Exception. } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Tried to load class " + clazzName + " while constructing a JAXBContext. This class will be skipped. Processing Continues."); log.debug(" The reason that class could not be loaded:" + e.toString()); log.trace(JavaUtils.stackToString(e)); } } } } } } catch (IOException e) { throw new ClassNotFoundException( "An IOException error was thrown when trying to read the jar file."); } } } } return classes; } catch (Exception e) { throw new ClassNotFoundException(e.getMessage()); } }
From source file:net.jselby.pc.bukkit.BukkitLoader.java
@SuppressWarnings("unchecked") public void loadPlugin(File file) throws ZipException, IOException, InvalidPluginException, InvalidDescriptionException { if (file.getName().endsWith(".jar")) { JarFile jarFile = new JarFile(file); URL[] urls = { new URL("jar:file:" + file + "!/") }; URLClassLoader cl = URLClassLoader.newInstance(urls); ZipEntry bukkit = jarFile.getEntry("plugin.yml"); String bukkitClass = ""; PluginDescriptionFile reader = null; if (bukkit != null) { reader = new PluginDescriptionFile(new InputStreamReader(jarFile.getInputStream(bukkit))); bukkitClass = reader.getMain(); System.out.println("Loading plugin " + reader.getName() + "..."); }/*from w w w . j av a 2s . com*/ jarFile.close(); try { //addToClasspath(file); JavaPluginLoader pluginLoader = new JavaPluginLoader(PoweredCube.getInstance().getBukkitServer()); Plugin plugin = pluginLoader.loadPlugin(file); Class<JavaPlugin> pluginClass = (Class<JavaPlugin>) plugin.getClass().getSuperclass(); for (Method method : pluginClass.getDeclaredMethods()) { if (method.getName().equalsIgnoreCase("init") || method.getName().equalsIgnoreCase("initialize")) { method.setAccessible(true); method.invoke(plugin, null, PoweredCube.getInstance().getBukkitServer(), reader, new File("plugins" + File.separator + reader.getName()), file, cl); } } // Load the plugin, using its default methods BukkitPluginManager mgr = (BukkitPluginManager) Bukkit.getPluginManager(); mgr.registerPlugin((JavaPlugin) plugin); plugin.onLoad(); plugin.onEnable(); } catch (Exception e1) { e1.printStackTrace(); } catch (Error e1) { e1.printStackTrace(); } jarFile.close(); } }
From source file:interactivespaces.resource.analysis.OsgiResourceAnalyzer.java
@Override public NamedVersionedResourceCollection<NamedVersionedResourceWithData<String>> getResourceCollection( File baseDir) {//from w w w .j a v a 2 s .co m NamedVersionedResourceCollection<NamedVersionedResourceWithData<String>> resources = NamedVersionedResourceCollection .newNamedVersionedResourceCollection(); File[] files = baseDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(".jar"); } }); if (files != null) { for (File file : files) { JarFile jarFile = null; try { jarFile = new JarFile(file); Manifest manifest = jarFile.getManifest(); Attributes attributes = manifest.getMainAttributes(); String name = attributes.getValue(OSGI_HEADER_SYMBOLIC_NAME); String version = attributes.getValue(OSGI_HEADER_VERSION); if (name != null && version != null) { NamedVersionedResourceWithData<String> resource = new NamedVersionedResourceWithData<String>( name, Version.parseVersion(version), file.getAbsolutePath()); resources.addResource(resource.getName(), resource.getVersion(), resource); } else { log.warn(String.format( "Resource %s is not a proper OSGi bundle (missing symbolic name and/or version) and is being ignored.", file.getAbsolutePath())); } } catch (IOException e) { log.error(String.format("Could not open resource file jar manifest for %s", file.getAbsolutePath()), e); } finally { // For some reason Closeables does not work with JarFile despite it // claiming it is Closeable in the Javadoc. if (jarFile != null) { try { jarFile.close(); } catch (IOException e) { // Don't care. } } } } } return resources; }
From source file:com.github.dirkraft.jash.ShExecutableJarBundler.java
@Override public List<String> validateAndInit() throws Exception { List<String> errors = super.validateAndInit(); if (!jarFile.isFile()) { errors.add(jarFile + " is not a file."); return errors; }//from www . j av a 2 s .com JarFile jar = new JarFile(jarFile); Manifest manifest = jar.getManifest(); String mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS); ClassLoader jarClassLoader = URLClassLoader.newInstance(new URL[] { jarFile.toURI().toURL() }); try { ClassUtils.getClass(jarClassLoader, mainClass, false); } catch (ClassNotFoundException e) { errors.add("Could not find Main-Class: " + mainClass + " in jar " + jarFile.getAbsolutePath()); return errors; } _targetBinary = outputDir.toPath().resolve(commandName).toFile(); if (_targetBinary.exists()) { errors.add("Target binary path " + _targetBinary.getAbsolutePath() + " is occupied. Will not overwrite, so aborting."); } return errors; }
From source file:com.wavemaker.commons.classloader.ThrowawayFileClassLoader.java
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (this.classPath == null) { throw new ClassNotFoundException("invalid search root: " + this.classPath); } else if (name == null) { throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage()); }/*w w w . ja v a2 s .c om*/ String classNamePath = name.replace('.', '/') + ".class"; byte[] fileBytes = null; try { InputStream is = null; JarFile jarFile = null; for (Resource entry : this.classPath) { if (entry.getFilename().toLowerCase().endsWith(".jar")) { jarFile = new JarFile(entry.getFile()); ZipEntry ze = jarFile.getEntry(classNamePath); if (ze != null) { is = jarFile.getInputStream(ze); break; } else { jarFile.close(); } } else { Resource classFile = entry.createRelative(classNamePath); if (classFile.exists()) { is = classFile.getInputStream(); break; } } } if (is != null) { try { fileBytes = IOUtils.toByteArray(is); is.close(); } finally { if (jarFile != null) { jarFile.close(); } } } } catch (IOException e) { throw new ClassNotFoundException(e.getMessage(), e); } if (name.contains(".")) { String packageName = name.substring(0, name.lastIndexOf('.')); if (getPackage(packageName) == null) { definePackage(packageName, "", "", "", "", "", "", null); } } Class<?> ret; if (fileBytes == null) { ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader); } else { ret = defineClass(name, fileBytes, 0, fileBytes.length); } if (ret == null) { throw new ClassNotFoundException( "Couldn't find class " + name + " in expected classpath: " + this.classPath); } return ret; }
From source file:com.wavemaker.common.util.ThrowawayFileClassLoader.java
@Override protected Class<?> findClass(String name) throws ClassNotFoundException { if (this.classPath == null) { throw new ClassNotFoundException("invalid search root: " + this.classPath); } else if (name == null) { throw new ClassNotFoundException(MessageResource.NULL_CLASS.getMessage()); }//from ww w .ja v a2s .co m String classNamePath = name.replace('.', '/') + ".class"; byte[] fileBytes = null; try { InputStream is = null; JarFile jarFile = null; for (Resource entry : this.classPath) { if (entry.getFilename().toLowerCase().endsWith(".jar")) { jarFile = new JarFile(entry.getFile()); ZipEntry ze = jarFile.getEntry(classNamePath); if (ze != null) { is = jarFile.getInputStream(ze); break; } else { jarFile.close(); } } else { Resource classFile = entry.createRelative(classNamePath); if (classFile.exists()) { is = classFile.getInputStream(); break; } } } if (is != null) { try { fileBytes = IOUtils.toByteArray(is); is.close(); } finally { if (jarFile != null) { jarFile.close(); } } } } catch (IOException e) { throw new ClassNotFoundException(e.getMessage(), e); } if (name.contains(".")) { String packageName = name.substring(0, name.lastIndexOf('.')); if (getPackage(packageName) == null) { definePackage(packageName, "", "", "", "", "", "", null); } } Class<?> ret; if (fileBytes == null) { ret = ClassLoaderUtils.loadClass(name, this.parentClassLoader); } else { ret = defineClass(name, fileBytes, 0, fileBytes.length); } if (ret == null) { throw new ClassNotFoundException( "Couldn't find class " + name + " in expected classpath: " + this.classPath); } return ret; }