List of usage examples for java.net URLClassLoader URLClassLoader
URLClassLoader(URL[] urls, AccessControlContext acc)
From source file:com.mellanox.hadoop.mapred.MapOutputLocation.java
protected void configureClasspath(JobConf conf) throws IOException { // get the task and the current classloader which will become the parent Task task = reduceTask;// ww w .j a va 2 s . c o m ClassLoader parent = conf.getClassLoader(); // get the work directory which holds the elements we are dynamically // adding to the classpath File workDir = new File(task.getJobFile()).getParentFile(); ArrayList<URL> urllist = new ArrayList<URL>(); // add the jars and directories to the classpath String jar = conf.getJar(); if (jar != null) { File jobCacheDir = new File(new Path(jar).getParent().toString()); File[] libs = new File(jobCacheDir, "lib").listFiles(); if (libs != null) { for (int i = 0; i < libs.length; i++) { urllist.add(libs[i].toURL()); } } urllist.add(new File(jobCacheDir, "classes").toURL()); urllist.add(jobCacheDir.toURL()); } urllist.add(workDir.toURL()); // create a new classloader with the old classloader as its parent // then set that classloader as the one used by the current jobconf URL[] urls = urllist.toArray(new URL[urllist.size()]); URLClassLoader loader = new URLClassLoader(urls, parent); conf.setClassLoader(loader); }
From source file:com.google.gdt.eclipse.designer.hosted.tdt.HostedModeSupport.java
/** * @return the {@link ClassLoader} for accessing gwt-dev classes mixed with design-time support * lib./*from w w w .j a va2 s . c o m*/ */ private ClassLoader getDevClassLoader0() throws Exception { // prepare gwt-dev.jar location String devLibLocation = Utils.getDevLibLocation(moduleDescription); if (devLibLocation == null) { throw new HostedModeException(HostedModeException.NO_DEV_LIB); } String gwtLocation = FilenameUtils.getFullPath(devLibLocation); // add 'dev' & 'dev-designtime' ClassLoader devClassLoader = devClassLoaders.get(gwtLocation); if (devClassLoader == null) { URL resolvedDevLibUrl = new File(devLibLocation).toURI().toURL(); Bundle bundle = Activator.getDefault().getBundle(); URL devDesignUrl = FileLocator.resolve(bundle.getEntry("/gwt-dev-designtime.jar")); if (devDesignUrl != null) { // workaround for Issue 258 (https://code.google.com/p/google-plugin-for-eclipse/issues/detail?id=258) devDesignUrl = new URL(StringUtils.replace(devDesignUrl.toString(), " ", "%20")); } devClassLoader = new URLClassLoader(new URL[] { devDesignUrl, resolvedDevLibUrl }, null); devClassLoaders.put(gwtLocation, devClassLoader); } return devClassLoader; }
From source file:com.cinchapi.concourse.server.plugin.PluginManager.java
/** * Get all the {@link Plugin plugins} in the {@code bundle} and * {@link #launch(String, Path, Class, List) launch} them each in a separate * JVM.// www.j a v a 2 s .co m * * @param bundle the path to a bundle directory, which is a sub-directory of * the {@link #home} directory. * @param runAfterInstallHook a flag that indicates whether the * {@link Plugin#afterInstall()} hook should be run */ protected void activate(String bundle, boolean runAfterInstallHook) { try { String lib = home + File.separator + bundle + File.separator + "lib" + File.separator; Path prefs = Paths.get(home, bundle, PluginConfiguration.PLUGIN_PREFS_FILENAME); Iterator<Path> content = Files.newDirectoryStream(Paths.get(lib)).iterator(); // Go through all the jars in the plugin's lib directory and compile // the appropriate classpath while identifying jars that might // contain plugin endpoints. List<URL> urls = Lists.newArrayList(); List<String> classpath = Lists.newArrayList(); while (content.hasNext()) { String filename = content.next().getFileName().toString(); URL url = new File(lib + filename).toURI().toURL(); if (!SYSTEM_JARS.contains(filename)) { // NOTE: by checking for exact name matches, we will // accidentally include system jars that contain different // versions. urls.add(url); } classpath.add(url.getFile()); } // Create a ClassLoader that only contains jars with possible plugin // endpoints and search for any applicable classes. URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[0]), null); Class parent = loader.loadClass(Plugin.class.getName()); Class realTimeParent = loader.loadClass(RealTimePlugin.class.getName()); Reflections reflection = new Reflections(new ConfigurationBuilder().addClassLoader(loader) .addUrls(ClasspathHelper.forClassLoader(loader))); Set<Class<?>> plugins = reflection.getSubTypesOf(parent); for (final Class<?> plugin : plugins) { if (runAfterInstallHook) { Object instance = Reflection.newInstance(plugin); Reflection.call(instance, "afterInstall"); } launch(bundle, prefs, plugin, classpath); startEventLoop(plugin.getName()); if (realTimeParent.isAssignableFrom(plugin)) { initRealTimeStream(plugin.getName()); } } } catch (IOException | ClassNotFoundException e) { Logger.error("An error occurred while trying to activate the plugin bundle '{}'", bundle, e); throw Throwables.propagate(e); } }
From source file:org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.java
/** * Add new elements to the classpath.// w w w. j a v a 2s .c o m * * @param newPaths * Array of classpath elements */ public static ClassLoader addToClassPath(ClassLoader cloader, String[] newPaths) throws Exception { URLClassLoader loader = (URLClassLoader) cloader; List<URL> curPath = Arrays.asList(loader.getURLs()); ArrayList<URL> newPath = new ArrayList<>(curPath.size()); // get a list with the current classpath components for (URL onePath : curPath) { newPath.add(onePath); } curPath = newPath; for (String onestr : newPaths) { URL oneurl = urlFromPathString(onestr); if (oneurl != null && !curPath.contains(oneurl)) { curPath.add(oneurl); } } return new URLClassLoader(curPath.toArray(new URL[0]), loader); }
From source file:org.mitre.ccv.mapred.CalculateKmerRevisedRelativeEntropy.java
@Override public int run(String[] args) throws Exception { JobConf conf = new JobConf(getConf()); boolean cleanLogs = false; // @TODO: use commons getopts List<String> other_args = new ArrayList<String>(); for (int i = 0; i < args.length; ++i) { try {//w w w . j a v a 2s.c o m if ("-m".equals(args[i])) { conf.setNumMapTasks(Integer.parseInt(args[++i])); } else if ("-r".equals(args[i])) { conf.setNumReduceTasks(Integer.parseInt(args[++i])); } else if ("-c".equals(args[i])) { cleanLogs = true; } else if ("-t".equals(args[i])) { conf.setBoolean(TEXT_OUTPUT, true); } else if ("-libjars".equals(args[i])) { conf.set("tmpjars", FileUtils.validateFiles(args[++i], conf)); URL[] libjars = FileUtils.getLibJars(conf); if (libjars != null && libjars.length > 0) { // Add libjars to client/tasks classpath conf.setClassLoader(new URLClassLoader(libjars, conf.getClassLoader())); // Adds libjars to our classpath Thread.currentThread().setContextClassLoader( new URLClassLoader(libjars, Thread.currentThread().getContextClassLoader())); } } else { other_args.add(args[i]); } } catch (NumberFormatException except) { System.out.println("ERROR: Integer expected instead of " + args[i]); return printUsage(); } catch (ArrayIndexOutOfBoundsException except) { System.out.println("ERROR: Required parameter missing from " + args[i - 1]); return printUsage(); } } // Make sure there are exactly 2 parameters left. if (other_args.size() != 3) { System.out.println("ERROR: Wrong number of parameters: " + other_args.size() + " instead of 3."); return printUsage(); } //return initJob(conf, inTable, sb.toString().trim(), new Path(other_args.get(1))); return initJob(conf, other_args.get(0), other_args.get(1), other_args.get(2), cleanLogs); }
From source file:org.apache.zeppelin.interpreter.InterpreterSettingManager.java
private boolean registerInterpreterFromResource(ClassLoader cl, String interpreterDir, String interpreterJson) throws IOException, RepositoryException { URL[] urls = recursiveBuildLibList(new File(interpreterDir)); ClassLoader tempClassLoader = new URLClassLoader(urls, cl); Enumeration<URL> interpreterSettings = tempClassLoader.getResources(interpreterJson); if (!interpreterSettings.hasMoreElements()) { return false; }// w w w .ja v a2 s.c o m for (URL url : Collections.list(interpreterSettings)) { try (InputStream inputStream = url.openStream()) { logger.debug("Reading {} from {}", interpreterJson, url); List<RegisteredInterpreter> registeredInterpreterList = getInterpreterListFromJson(inputStream); registerInterpreters(registeredInterpreterList, interpreterDir); } } return true; }
From source file:io.github.divinespear.maven.plugin.JpaSchemaGeneratorMojo.java
private ClassLoader getProjectClassLoader() throws MojoExecutionException { try {/* w w w . ja v a 2 s .co m*/ // compiled classes List<String> classfiles = this.project.getCompileClasspathElements(); if (this.scanTestClasses) { classfiles.addAll(this.project.getTestClasspathElements()); } // classpath to url List<URL> classURLs = new ArrayList<URL>(classfiles.size()); for (String classfile : classfiles) { classURLs.add(new File(classfile).toURI().toURL()); } // dependency artifacts to url ArtifactResolutionRequest sharedreq = new ArtifactResolutionRequest().setResolveRoot(true) .setResolveTransitively(true).setLocalRepository(this.session.getLocalRepository()) .setRemoteRepositories(this.project.getRemoteArtifactRepositories()); ArtifactRepository repository = this.session.getLocalRepository(); Set<Artifact> artifacts = this.project.getDependencyArtifacts(); for (Artifact artifact : artifacts) { if (!Artifact.SCOPE_TEST.equalsIgnoreCase(artifact.getScope())) { ArtifactResolutionRequest request = new ArtifactResolutionRequest(sharedreq) .setArtifact(artifact); ArtifactResolutionResult result = this.resolver.resolve(request); if (result.isSuccess()) { File file = repository.find(artifact).getFile(); if (file != null) { classURLs.add(file.toURI().toURL()); } } } } for (URL url : classURLs) { this.log.info(" * classpath: " + url); } return new URLClassLoader(classURLs.toArray(EMPTY_URLS), this.getClass().getClassLoader()); } catch (Exception e) { this.log.error(e); throw new MojoExecutionException("Error while creating classloader", e); } }
From source file:com.izforge.izpack.installer.multiunpacker.MultiVolumeUnpackerTest.java
/** * Creates a new {@link Resources} that reads resources from the supplied jar. * * @param installerJar the installer jar. * @return a new resource manager//from w ww.j ava 2 s. c o m * @throws IOException for any I/O error */ private Resources createResources(File installerJar) throws IOException { final URLClassLoader loader = new URLClassLoader(new URL[] { installerJar.toURI().toURL() }, getClass().getClassLoader()); return new ResourceManager(loader); }
From source file:org.interreg.docexplore.GeneralConfigPanel.java
String browseClasses(File file) { try {/*w w w . j av a 2s. co m*/ List<Class<?>> metaDataPlugins = new LinkedList<Class<?>>(); List<Class<?>> analysisPlugins = new LinkedList<Class<?>>(); List<Class<?>> clientPlugins = new LinkedList<Class<?>>(); List<Class<?>> serverPlugins = new LinkedList<Class<?>>(); List<Class<?>> inputPlugins = new LinkedList<Class<?>>(); List<URL> urls = Startup.extractDependencies(file.getName().substring(0, file.getName().length() - 4), file.getName()); urls.add(file.toURI().toURL()); URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[] {}), this.getClass().getClassLoader()); JarFile jarFile = new JarFile(file); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (!entry.getName().endsWith(".class") || entry.getName().indexOf('$') > 0) continue; String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.'); Class<?> clazz = null; try { clazz = loader.loadClass(className); System.out.println("Reading " + className); } catch (NoClassDefFoundError e) { System.out.println("Couldn't read " + className); } if (clazz == null) continue; if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) continue; if (MetaDataPlugin.class.isAssignableFrom(clazz)) metaDataPlugins.add(clazz); if (AnalysisPlugin.class.isAssignableFrom(clazz)) analysisPlugins.add(clazz); if (ClientPlugin.class.isAssignableFrom(clazz)) clientPlugins.add(clazz); if (ServerPlugin.class.isAssignableFrom(clazz)) serverPlugins.add(clazz); if (InputPlugin.class.isAssignableFrom(clazz)) inputPlugins.add(clazz); } jarFile.close(); @SuppressWarnings("unchecked") Pair<String, String>[] classes = new Pair[metaDataPlugins.size() + analysisPlugins.size() + clientPlugins.size() + serverPlugins.size() + inputPlugins.size()]; if (classes.length == 0) throw new Exception("Invalid plugin (no entry points were found)."); int cnt = 0; for (Class<?> clazz : metaDataPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "MetaData plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : analysisPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Analysis plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : clientPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader client plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : serverPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader server plugin") { public String toString() { return first + " (" + second + ")"; } }; for (Class<?> clazz : inputPlugins) classes[cnt++] = new Pair<String, String>(clazz.getName(), "Reader input plugin") { public String toString() { return first + " (" + second + ")"; } }; @SuppressWarnings("unchecked") Pair<String, String> res = (Pair<String, String>) JOptionPane.showInputDialog(this, "Please select an entry point for the plugin:", "Plugin entry point", JOptionPane.QUESTION_MESSAGE, null, classes, classes[0]); if (res != null) return res.first; } catch (Throwable e) { ErrorHandler.defaultHandler.submit(e); } return null; }
From source file:azkaban.webapp.AzkabanWebServer.java
private Map<String, Alerter> loadPluginAlerters(String pluginPath) { File alerterPluginPath = new File(pluginPath); if (!alerterPluginPath.exists()) { return Collections.<String, Alerter>emptyMap(); }/*from w w w .j a v a2s. com*/ Map<String, Alerter> installedAlerterPlugins = new HashMap<String, Alerter>(); ClassLoader parentLoader = getClass().getClassLoader(); File[] pluginDirs = alerterPluginPath.listFiles(); ArrayList<String> jarPaths = new ArrayList<String>(); for (File pluginDir : pluginDirs) { if (!pluginDir.isDirectory()) { logger.error("The plugin path " + pluginDir + " is not a directory."); continue; } // Load the conf directory File propertiesDir = new File(pluginDir, "conf"); Props pluginProps = null; if (propertiesDir.exists() && propertiesDir.isDirectory()) { File propertiesFile = new File(propertiesDir, "plugin.properties"); File propertiesOverrideFile = new File(propertiesDir, "override.properties"); if (propertiesFile.exists()) { if (propertiesOverrideFile.exists()) { pluginProps = PropsUtils.loadProps(null, propertiesFile, propertiesOverrideFile); } else { pluginProps = PropsUtils.loadProps(null, propertiesFile); } } else { logger.error("Plugin conf file " + propertiesFile + " not found."); continue; } } else { logger.error("Plugin conf path " + propertiesDir + " not found."); continue; } String pluginName = pluginProps.getString("alerter.name"); List<String> extLibClasspath = pluginProps.getStringList("alerter.external.classpaths", (List<String>) null); String pluginClass = pluginProps.getString("alerter.class"); if (pluginClass == null) { logger.error("Alerter class is not set."); } else { logger.info("Plugin class " + pluginClass); } URLClassLoader urlClassLoader = null; File libDir = new File(pluginDir, "lib"); if (libDir.exists() && libDir.isDirectory()) { File[] files = libDir.listFiles(); ArrayList<URL> urls = new ArrayList<URL>(); for (int i = 0; i < files.length; ++i) { try { URL url = files[i].toURI().toURL(); urls.add(url); } catch (MalformedURLException e) { logger.error(e); } } if (extLibClasspath != null) { for (String extLib : extLibClasspath) { try { File file = new File(pluginDir, extLib); URL url = file.toURI().toURL(); urls.add(url); } catch (MalformedURLException e) { logger.error(e); } } } urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), parentLoader); } else { logger.error("Library path " + propertiesDir + " not found."); continue; } Class<?> alerterClass = null; try { alerterClass = urlClassLoader.loadClass(pluginClass); } catch (ClassNotFoundException e) { logger.error("Class " + pluginClass + " not found."); continue; } String source = FileIOUtils.getSourcePathFromClass(alerterClass); logger.info("Source jar " + source); jarPaths.add("jar:file:" + source); Constructor<?> constructor = null; try { constructor = alerterClass.getConstructor(Props.class); } catch (NoSuchMethodException e) { logger.error("Constructor not found in " + pluginClass); continue; } Object obj = null; try { obj = constructor.newInstance(pluginProps); } catch (Exception e) { logger.error(e); } if (!(obj instanceof Alerter)) { logger.error("The object is not an Alerter"); continue; } Alerter plugin = (Alerter) obj; installedAlerterPlugins.put(pluginName, plugin); } return installedAlerterPlugins; }