List of usage examples for java.net URLClassLoader URLClassLoader
public URLClassLoader(URL[] urls)
From source file:org.apache.hadoop.mapred.pipes.SubmitterToAccels.java
@Override public int run(String[] args) throws Exception { CommandLineParser cli = new CommandLineParser(); if (args.length == 0) { cli.printUsage();//from w w w. ja v a 2s .c om return 1; } cli.addOption("input", false, "input path to the maps", "path"); cli.addOption("output", false, "output path from the reduces", "path"); cli.addOption("cpubin", false, "URI to application cpu executable", "class"); cli.addOption("gpubin", false, "URI to application gpu executable", "class"); Parser parser = cli.createParser(); try { GenericOptionsParser genericParser = new GenericOptionsParser(getConf(), args); CommandLine results = parser.parse(cli.options, genericParser.getRemainingArgs()); JobConf job = new JobConf(getConf()); if (results.hasOption("input")) { FileInputFormat.setInputPaths(job, (String) results.getOptionValue("input")); } if (results.hasOption("output")) { FileOutputFormat.setOutputPath(job, new Path((String) results.getOptionValue("output"))); } if (results.hasOption("cpubin")) { setCPUExecutable(job, (String) results.getOptionValue("cpubin")); } if (results.hasOption("gpubin")) { setGPUExecutable(job, (String) results.getOptionValue("gpubin")); } // if they gave us a jar file, include it into the class path String jarFile = job.getJar(); if (jarFile != null) { final URL[] urls = new URL[] { FileSystem.getLocal(job).pathToFile(new Path(jarFile)).toURL() }; //FindBugs complains that creating a URLClassLoader should be //in a doPrivileged() block. ClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return new URLClassLoader(urls); } }); job.setClassLoader(loader); } runJob(job); return 0; } catch (ParseException pe) { LOG.info("Error :" + pe); cli.printUsage(); return 1; } }
From source file:org.jwebsocket.plugins.rpc.RPCPlugIn.java
/** * * @param aClassName//from ww w . ja va 2 s. com * @param aURL * @return */ public static Class loadClass(String aClassName, String aURL) { Class lClass = null; try { URLClassLoader lUCL = new URLClassLoader(new URL[] { new URL(aURL) }); // load class using previously defined class loader lClass = Class.forName(aClassName, true, lUCL); if (mLog.isDebugEnabled()) { mLog.debug("Class '" + lClass.getName() + "' loaded!"); } } catch (ClassNotFoundException ex) { mLog.error("Class not found exception: " + ex.getMessage()); } catch (MalformedURLException ex) { mLog.error("MalformesURL exception: " + ex.getMessage()); } return lClass; }
From source file:com.cubeia.maven.plugin.firebase.FirebaseRunPlugin.java
@SuppressWarnings("unchecked") private ClassLoader createClassLoader(FirebaseDirectory dir) throws MojoExecutionException { List<File> list = new LinkedList<File>(); list.add(dir.binDirectory);/* w w w. jav a 2 s.c o m*/ list.add(new File(dir.binDirectory, "firebase-bootstrap.jar")); list.addAll(FileUtils.listFiles(dir.commonLibDirectory, new String[] { "jar" }, false)); list.add(dir.firebaseDirectory); list.add(dir.confDirectory); File[] arr = new File[list.size()]; list.toArray(arr); try { URL[] urls = FileUtils.toURLs(arr); return new URLClassLoader(urls); } catch (IOException e) { throw new MojoExecutionException("Failed to create URL for class path", e); } }
From source file:com.buisonje.tools.xmldbloader.XmlDataSetDBLoader.java
/** * Instructs the {@link System}'s {@link ClassLoader} to load a JDBC driver class file from an external JAR. * @param jarFilePath the path to the class file to be loaded. * @throws IllegalArgumentException if no class could successfully loaded from the specified path. *//*from ww w. j a v a2 s. c o m*/ private void loadJdbcDriverClassFromJar(final String jarFilePath) throws IllegalArgumentException { try { URL u = new URL("jar:file:///" + jarFilePath + "!/"); URLClassLoader ucl = new URLClassLoader(new URL[] { u }); Reflections reflections = new Reflections(ucl); final Set<Class<? extends Driver>> detectedJdbcDrivers = reflections.getSubTypesOf(Driver.class); if (detectedJdbcDrivers.isEmpty()) { throw new IllegalArgumentException(String.format( "The supplied JAR file at \"%s\" contains no JDBC drivers (which should implement the interface \"%s\").", jarFilePath, Driver.class.getName())); } final int numberOfDetectedJdbcDrivers = detectedJdbcDrivers.size(); if (numberOfDetectedJdbcDrivers > 1) { LOGGER.warn( "Detected more than one ({}) JDBC drivers in the supplied JAR file at \"{}\". Choosing the first one...", numberOfDetectedJdbcDrivers, jarFilePath); } Driver driver = detectedJdbcDrivers.iterator().next().newInstance(); LOGGER.info("Loaded JDBC driver \"{}\".", driver.getClass().getName()); DriverManager.registerDriver(new DriverShim(driver)); } catch (InstantiationException e) { throw new IllegalArgumentException(String.format( "JAR file \"%s\" apparently contains a JDBC Driver that is incompatible with the Java version " + "on which the application is currently running (version %s). To solve this problem, either upgrade the Java version (recommended) or " + "downgrade the JDBC driver.", jarFilePath, System.getProperty("java.version")), e); } catch (Exception e) { throw new IllegalArgumentException( String.format("Unable to load JDBC Driver class from JAR \"%s\".", jarFilePath), e); } }
From source file:org.apache.drill.exec.expr.fn.FunctionImplementationRegistry.java
/** * Using given local path to jar creates unique class loader for this jar. * Class loader is closed to release opened connection to jar when validation is finished. * Scan jar content to receive list of all scanned classes * and starts validation process against local function registry. * Checks if received list of validated function is not empty. * * @param path local path to jar we need to validate * @return list of validated function signatures *//*from w w w .j a v a 2s. c o m*/ public List<String> validate(Path path) throws IOException { URL url = path.toUri().toURL(); URL[] urls = { url }; try (URLClassLoader classLoader = new URLClassLoader(urls)) { ScanResult jarScanResult = scan(classLoader, path, urls); List<String> functions = localFunctionRegistry.validate(path.getName(), jarScanResult); if (functions.isEmpty()) { throw new FunctionValidationException( String.format("Jar %s does not contain functions", path.getName())); } return functions; } }
From source file:org.hyperic.hq.product.server.session.ProductPluginDeployer.java
private void deployHqu(String plugin, File pluginFile, boolean initializing) throws Exception { URLClassLoader pluginClassloader = new URLClassLoader(new URL[] { pluginFile.toURI().toURL() }); final String prefix = HQU + "/"; URL hqu = pluginClassloader.getResource(prefix); if (hqu == null) { return;//from w w w.j a v a 2 s . co m } File destDir = new File(hquDir, plugin); boolean exists = destDir.exists(); log.info("Deploying " + plugin + " " + HQU + " to: " + destDir); unpackJar(pluginFile, destDir, prefix); if (!(initializing) && exists) { // update ourselves to avoid having to delete,sleep,unpack renditServer.removePluginDir(destDir.getName()); renditServer.addPluginDir(destDir); } // else Rendit watcher will deploy the new plugin }
From source file:org.apache.tomcat.maven.plugin.tomcat8.run.RunMojo.java
@Override protected void enhanceContext(final Context context) throws MojoExecutionException { super.enhanceContext(context); try {/*from ww w . j a v a2 s . com*/ ClassLoaderEntriesCalculatorRequest request = new ClassLoaderEntriesCalculatorRequest() // .setDependencies(dependencies) // .setLog(getLog()) // .setMavenProject(project) // .setAddWarDependenciesInClassloader(addWarDependenciesInClassloader) // .setUseTestClassPath(useTestClasspath); final ClassLoaderEntriesCalculatorResult classLoaderEntriesCalculatorResult = classLoaderEntriesCalculator .calculateClassPathEntries(request); final List<String> classLoaderEntries = classLoaderEntriesCalculatorResult.getClassPathEntries(); final List<File> tmpDirectories = classLoaderEntriesCalculatorResult.getTmpDirectories(); final List<String> jarPaths = extractJars(classLoaderEntries); List<URL> urls = new ArrayList<URL>(jarPaths.size()); for (String jarPath : jarPaths) { try { urls.add(new File(jarPath).toURI().toURL()); } catch (MalformedURLException e) { throw new MojoExecutionException(e.getMessage(), e); } } getLog().debug("classLoaderEntriesCalculator urls: " + urls); final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()])); final ClassRealm pluginRealm = getTomcatClassLoader(); context.setResources( new MyDirContext(new File(project.getBuild().getOutputDirectory()).getAbsolutePath(), // getPath(), // getLog()) { @Override public WebResource getClassLoaderResource(String path) { log.debug("RunMojo#getClassLoaderResource: " + path); URL url = urlClassLoader.getResource(StringUtils.removeStart(path, "/")); // search in parent (plugin) classloader if (url == null) { url = pluginRealm.getResource(StringUtils.removeStart(path, "/")); } if (url == null) { // try in reactors List<WebResource> webResources = findResourcesInDirectories(path, // classLoaderEntriesCalculatorResult.getBuildDirectories()); // so we return the first one if (!webResources.isEmpty()) { return webResources.get(0); } } if (url == null) { return new EmptyResource(this, getPath()); } return urlToWebResource(url, path); } @Override public WebResource getResource(String path) { log.debug("RunMojo#getResource: " + path); return super.getResource(path); } @Override public WebResource[] getResources(String path) { log.debug("RunMojo#getResources: " + path); return super.getResources(path); } @Override protected WebResource[] getResourcesInternal(String path, boolean useClassLoaderResources) { log.debug("RunMojo#getResourcesInternal: " + path); return super.getResourcesInternal(path, useClassLoaderResources); } @Override public WebResource[] getClassLoaderResources(String path) { try { Enumeration<URL> enumeration = urlClassLoader .findResources(StringUtils.removeStart(path, "/")); List<URL> urlsFound = new ArrayList<URL>(); List<WebResource> webResources = new ArrayList<WebResource>(); while (enumeration.hasMoreElements()) { URL url = enumeration.nextElement(); urlsFound.add(url); webResources.add(urlToWebResource(url, path)); } log.debug("RunMojo#getClassLoaderResources: " + path + " found : " + urlsFound.toString()); webResources.addAll(findResourcesInDirectories(path, classLoaderEntriesCalculatorResult.getBuildDirectories())); return webResources.toArray(new WebResource[webResources.size()]); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } private List<WebResource> findResourcesInDirectories(String path, List<String> directories) { try { List<WebResource> webResources = new ArrayList<WebResource>(); for (String directory : directories) { File file = new File(directory, path); if (file.exists()) { webResources.add(urlToWebResource(file.toURI().toURL(), path)); } } return webResources; } catch (MalformedURLException e) { throw new RuntimeException(e.getMessage(), e); } } private WebResource urlToWebResource(URL url, String path) { JarFile jarFile = null; try { // url.getFile is // file:/Users/olamy/mvn-repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar!/org/springframework/web/context/ContextLoaderListener.class int idx = url.getFile().indexOf('!'); if (idx >= 0) { String filePath = StringUtils.removeStart(url.getFile().substring(0, idx), "file:"); jarFile = new JarFile(filePath); JarEntry jarEntry = jarFile.getJarEntry(StringUtils.removeStart(path, "/")); return new JarResource(this, // getPath(), // filePath, // url.getPath().substring(0, idx), // jarEntry, // "", // null); } else { return new FileResource(this, webAppPath, new File(url.getFile()), true); } } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { IOUtils.closeQuietly(jarFile); } } }); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { for (File tmpDir : tmpDirectories) { try { FileUtils.deleteDirectory(tmpDir); } catch (IOException e) { // ignore } } } }); if (classLoaderEntries != null) { WebResourceSet webResourceSet = new FileResourceSet() { @Override public WebResource getResource(String path) { if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) { File file = new File(StringUtils.removeStartIgnoreCase(path, "/WEB-INF/LIB")); return new FileResource(context.getResources(), getPath(), file, true); } if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) { return new FileResource(context.getResources(), getPath(), new File(project.getBuild().getOutputDirectory()), true); } File file = new File(project.getBuild().getOutputDirectory(), path); if (file.exists()) { return new FileResource(context.getResources(), getPath(), file, true); } //if ( StringUtils.endsWith( path, ".class" ) ) { // so we search the class file in the jars for (String jarPath : jarPaths) { File jar = new File(jarPath); if (!jar.exists()) { continue; } try (JarFile jarFile = new JarFile(jar)) { JarEntry jarEntry = (JarEntry) jarFile .getEntry(StringUtils.removeStart(path, "/")); if (jarEntry != null) { return new JarResource(context.getResources(), // getPath(), // jarFile.getName(), // jar.toURI().toString(), // jarEntry, // path, // jarFile.getManifest()); } } catch (IOException e) { getLog().debug("skip error building jar file: " + e.getMessage(), e); } } } return new EmptyResource(null, path); } @Override public String[] list(String path) { if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) { return jarPaths.toArray(new String[jarPaths.size()]); } if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) { return new String[] { new File(project.getBuild().getOutputDirectory()).getPath() }; } return super.list(path); } @Override public Set<String> listWebAppPaths(String path) { if (StringUtils.equalsIgnoreCase("/WEB-INF/lib/", path)) { // adding outputDirectory as well? return new HashSet<String>(jarPaths); } File filePath = new File(getWarSourceDirectory(), path); if (filePath.isDirectory()) { Set<String> paths = new HashSet<String>(); String[] files = filePath.list(); if (files == null) { return paths; } for (String file : files) { paths.add(file); } return paths; } else { return Collections.emptySet(); } } @Override public boolean mkdir(String path) { return super.mkdir(path); } @Override public boolean write(String path, InputStream is, boolean overwrite) { return super.write(path, is, overwrite); } @Override protected void checkType(File file) { //super.checkType( file ); } }; context.getResources().addJarResources(webResourceSet); } } catch (TomcatRunException e) { throw new MojoExecutionException(e.getMessage(), e); } }
From source file:com.thinkbiganalytics.nifi.v2.thrift.ThriftConnectionPool.java
/** * using Thread.currentThread().getContextClassLoader() will ensure that you are using the ClassLoader for your NAR. * * @param urlString URL of the class/*from ww w . j a va 2 s . com*/ * @param drvName the driver string * @return the class loader * @throws InitializationException if there is a problem obtaining the ClassLoader */ protected ClassLoader getDriverClassLoader(String urlString, String drvName) throws InitializationException { if (urlString != null && urlString.length() > 0) { try { final URL[] urls = new URL[] { new URL(urlString) }; final URLClassLoader ucl = new URLClassLoader(urls); // Workaround which allows to use URLClassLoader for JDBC driver loading. // (Because the DriverManager will refuse to use a driver not loaded by the system ClassLoader.) final Class<?> clazz = Class.forName(drvName, true, ucl); if (clazz == null) { throw new InitializationException("Can't load Database Driver " + drvName); } final Driver driver = (Driver) clazz.newInstance(); DriverManager.registerDriver(new DriverShim(driver)); return ucl; } catch (final MalformedURLException e) { throw new InitializationException("Invalid Database Driver Jar Url", e); } catch (final Exception e) { throw new InitializationException("Can't load Database Driver", e); } } else { // That will ensure that you are using the ClassLoader for you NAR. return Thread.currentThread().getContextClassLoader(); } }
From source file:org.apache.drill.exec.expr.fn.FunctionImplementationRegistry.java
/** * Attempts to load and register functions from remote function registry. * First checks if there is no missing jars. * If yes, enters synchronized block to prevent other loading the same jars. * Again re-checks if there are no missing jars in case someone has already loaded them (double-check lock). * If there are still missing jars, first copies jars to local udf area and prepares {@link JarScan} for each jar. * Jar registration timestamp represented in milliseconds is used as suffix. * Then registers all jars at the same time. Returns true when finished. * In case if any errors during jars coping or registration, logs errors and proceeds. * * If no missing jars are found, checks current local registry version. * Returns false if versions match, true otherwise. * * @param version local function registry version * @return true if new jars were registered or local function registry version is different, false otherwise *//* w w w . j a v a2s. co m*/ public boolean loadRemoteFunctions(long version) { List<String> missingJars = getMissingJars(remoteFunctionRegistry, localFunctionRegistry); if (!missingJars.isEmpty()) { synchronized (this) { missingJars = getMissingJars(remoteFunctionRegistry, localFunctionRegistry); List<JarScan> jars = Lists.newArrayList(); for (String jarName : missingJars) { Path binary = null; Path source = null; URLClassLoader classLoader = null; try { binary = copyJarToLocal(jarName, remoteFunctionRegistry); source = copyJarToLocal(JarUtil.getSourceName(jarName), remoteFunctionRegistry); URL[] urls = { binary.toUri().toURL(), source.toUri().toURL() }; classLoader = new URLClassLoader(urls); ScanResult scanResult = scan(classLoader, binary, urls); localFunctionRegistry.validate(jarName, scanResult); jars.add(new JarScan(jarName, scanResult, classLoader)); } catch (Exception e) { deleteQuietlyLocalJar(binary); deleteQuietlyLocalJar(source); if (classLoader != null) { try { classLoader.close(); } catch (Exception ex) { logger.warn("Problem during closing class loader for {}", jarName, e); } } logger.error("Problem during remote functions load from {}", jarName, e); } } if (!jars.isEmpty()) { localFunctionRegistry.register(jars); return true; } } } return version != localFunctionRegistry.getVersion(); }
From source file:com.ms.commons.test.classloader.IntlTestURLClassPath.java
private static URL translateURL(URL url) throws Exception { URLClassLoader ucl = new URLClassLoader(new URL[] { url }); // URL?autoconfig List<URL> autoConfigXmlList = AutoConfigUtil.loadAllAutoConfigFilesWithFind(ucl); if ((autoConfigXmlList == null) || (autoConfigXmlList.size() == 0)) { return url; }/* ww w . j a va 2 s. c om*/ AutoConfigMap acm = AutoConfigUtil.loadAutoConfigMapWithFind(ucl, IntlTestProperties.PROPERTIES); // ??URL boolean urlTranslated = false; // String outputPath; if ("file".equals(url.getProtocol()) && !url.toString().toLowerCase().endsWith(".jar")) { outputPath = FileUtil.convertURLToFilePath(url); } else if (url.toString().toLowerCase().endsWith(".jar")) { String fileN = FileUtil.convertURLToFile(url).getName(); String jarUrlPath = fileN + "@" + url.toString().hashCode(); jarUrlPath = jarUrlPath.replace(".jar", "").replace("alibaba", ""); outputPath = TESTCASE_JAR_TEMP_DIR + File.separator + StringUtil.replaceNoWordChars(jarUrlPath); // ?????? File signature = new File(outputPath + File.separator + TESTCASE_JAR_SIGNATURE); StringBuilder refAst = new StringBuilder(); if (isOutOfDate(signature, url, refAst)) { // JAR??JAR?JAR?? FileUtil.clearAndMakeDirs(outputPath); expandJarTo(new JarFile(FileUtil.convertURLToFile(url)), outputPath); FileUtils.writeStringToFile(signature, refAst.toString()); } urlTranslated = true; } else { throw new RuntimeException("URL protocol unknow:" + url); } // ?autoconfig? System.err.println("Auto config for:" + url); for (AutoConfigItem antxConfigResourceItem : acm.values()) { AutoConfigUtil.autoConfigFile(ucl, IntlTestProperties.PROPERTIES, antxConfigResourceItem, outputPath, true); } return urlTranslated ? (new File(outputPath)).toURI().toURL() : url; }