List of usage examples for java.net URLClassLoader URLClassLoader
public URLClassLoader(URL[] urls)
From source file:de.teamgrit.grit.checking.testing.JavaProjectTester.java
/** * Runs tests in testLocation on the source code given in the parameter. * * @param submissionBinariesLocation//www . j a v a2s.c om * The path to the compiled binaries of the submission. * * @return the {@link TestOutput} containing the test results. * * @throws ClassNotFoundException * Throws if the loaded Classes are not found * @throws IOException * Throws if the sourceCodeLocation is malformed or the * {@link URLClassLoader} can't be closed. */ @Override public TestOutput testSubmission(Path submissionBinariesLocation) throws ClassNotFoundException, IOException { // if there are no tests create and empty TestOutput with didTest false if ((testLocation == null) || testLocation.toString().isEmpty()) { return new TestOutput(null, false); } else { List<Result> results = new LinkedList<>(); // create the classloader URL submissionURL = submissionBinariesLocation.toUri().toURL(); URL testsURL = testLocation.toUri().toURL(); // URLClassLoader loader = // new URLClassLoader(new URL[] { submissionURL, testsURL }); URLClassLoader loader = new URLClassLoader(new URL[] { testsURL, submissionURL }); // iterate submission source code files and load the .class files. /* * We need to iterate all files in a directory and thus are using * the apache commons io utility FileUtils.listFiles. This needs a) * the directory, and b) a file filter for which we also use the * one supplied by apache commons io. */ Path submissionBin = submissionBinariesLocation.toAbsolutePath(); List<Path> exploreDirectory = exploreDirectory(submissionBin, ExplorationType.CLASSFILES); for (Path path : exploreDirectory) { String quallifiedName = getQuallifiedName(submissionBin, path); loader.loadClass(quallifiedName); } // iterate tests, load them and run them Path testLoc = testLocation.toAbsolutePath(); List<Path> exploreDirectory2 = exploreDirectory(testLoc, ExplorationType.SOURCEFILES); for (Path path : exploreDirectory2) { String unitTestName = getQuallifiedNameFromSource(path); try { Class<?> testerClass = loader.loadClass(unitTestName); Result runClasses = JUnitCore.runClasses(testerClass); results.add(runClasses); } catch (Throwable e) { LOGGER.severe("can't load class: " + unitTestName); LOGGER.severe(e.getMessage()); } } loader.close(); // creates new TestOutput from results and returns it return new TestOutput(results, true); } }
From source file:org.deventropy.shared.utils.ClassUtilTest.java
@Test public void testCallerClassloader() throws Exception { // Write the source file - see // http://stackoverflow.com/questions/2946338/how-do-i-programmatically-compile-and-instantiate-a-java-class final File sourceFolder = workingFolder.newFolder(); // Prepare source somehow. final String source = "package test; public class Test { }"; // Save source in .java file. final File sourceFile = new File(sourceFolder, "test/Test.java"); sourceFile.getParentFile().mkdirs(); FileUtils.writeStringToFile(sourceFile, source, "UTF-8"); // Compile the file final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); final Iterable<? extends JavaFileObject> compilationUnit = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(sourceFile)); compiler.getTask(null, fileManager, null, null, null, compilationUnit).call(); // Create the class loader final URLClassLoader urlcl = new URLClassLoader(new URL[] { sourceFolder.toURI().toURL() }); final Class<?> loadedClass = urlcl.loadClass("test.Test"); final ContextClNullingObject testObj = new ContextClNullingObject(loadedClass.newInstance()); final Thread worker = new Thread(testObj); worker.start();/*from www . jav a 2 s . co m*/ worker.join(); assertEquals(urlcl, testObj.getReturnedCl()); urlcl.close(); }
From source file:com.chaschev.install.InstallMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { try {//from w w w . j a va 2 s . co m // FindAvailableVersions.main(null); initialize(); Artifact artifact = new DefaultArtifact(artifactName); DependencyResult dependencyResult = resolveArtifact(artifact); artifact = dependencyResult.getRoot().getArtifact(); List<ArtifactResult> dependencies = dependencyResult.getArtifactResults(); if (className != null) { new ExecObject(getLog(), artifact, dependencies, className, parseArgs(), systemProperties) .execute(); } Class<?> installation = new URLClassLoader(new URL[] { artifact.getFile().toURI().toURL() }) .loadClass("Installation"); List<Object[]> entries = (List<Object[]>) OpenBean2.getStaticFieldValue(installation, "shortcuts"); if (installTo == null) { installTo = findPath(); } File installToDir = new File(installTo); File classPathFile = writeClasspath(artifact, dependencies, installToDir); for (Object[] entry : entries) { String shortCut = (String) entry[0]; String className = entry[1] instanceof String ? entry[1].toString() : ((Class) entry[1]).getName(); File file; if (SystemUtils.IS_OS_WINDOWS) { file = new File(installToDir, shortCut + ".bat"); FileUtils.writeStringToFile(file, createLaunchScript(className, classPathFile)); } else { file = new File(installToDir, shortCut); FileUtils.writeStringToFile(file, createLaunchScript(className, classPathFile)); try { file.setExecutable(true, false); } catch (Exception e) { getLog().warn( "could not make '" + file.getAbsolutePath() + "' executable: " + e.toString()); } } getLog().info("created a shortcut: " + file.getAbsolutePath() + " -> " + className); } } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { getLog().error(e.toString(), e); throw new MojoExecutionException(e.toString()); } } }
From source file:com.twosigma.beaker.sql.JDBCClient.java
public void loadDrivers(List<String> pathList) { synchronized (this) { dsMap = new HashMap<>(); drivers = new HashSet<>(); Set<URL> urlSet = new HashSet<>(); String dbDriverString = System.getenv("BEAKER_JDBC_DRIVER_LIST"); if (dbDriverString != null && !dbDriverString.isEmpty()) { String[] dbDriverList = dbDriverString.split(File.pathSeparator); for (String s : dbDriverList) { try { urlSet.add(toURL(s)); } catch (MalformedURLException e) { logger.error(e.getMessage()); }// w ww.ja va2 s .co m } } if (pathList != null) { for (String path : pathList) { path = path.trim(); if (path.startsWith("--") || path.startsWith("#")) { continue; } try { urlSet.add(toURL(path)); } catch (MalformedURLException e) { logger.error(e.getMessage()); } } } URLClassLoader loader = new URLClassLoader(urlSet.toArray(new URL[urlSet.size()])); ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class, loader); Iterator<Driver> driversIterator = loadedDrivers.iterator(); try { while (driversIterator.hasNext()) { Driver d = driversIterator.next(); drivers.add(d); } } catch (Throwable t) { logger.error(t.getMessage()); } } }
From source file:edu.rosehulman.sws.extension.AbstractPlugin.java
private void parseRouteLine(String line) { // split line on any amount of white space in between parts String[] routeParts = line.split("\\s+"); String path = routeParts[0].replaceAll(".*[/\\\\].*", File.separator); String routeKey = getServeltRouteKey(path, routeParts[1]); String routeServletClass = routeParts[2]; // create new servlet instance frome routeServlet name Class<?> servletClass;//from w w w.j a v a 2 s . c o m try { URL location = getClass().getProtectionDomain().getCodeSource().getLocation(); ClassLoader classLoader = new URLClassLoader( new URL[] { new File(location.getFile()).toURI().toURL() }); servletClass = classLoader.loadClass(routeServletClass); Constructor<?> servletConstructor = servletClass.getConstructor(); Object servletObj = servletConstructor.newInstance(); IServlet servlet = (IServlet) servletObj; servlet.setPlugin(this); this.servletMap.put(routeKey, servlet); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.apache.maven.archetype.common.DefaultArchetypeArtifactManager.java
public ClassLoader getArchetypeJarLoader(File archetypeFile) throws UnknownArchetype { try {//from w ww .j a va2 s . co m URL[] urls = new URL[1]; urls[0] = archetypeFile.toURI().toURL(); return new URLClassLoader(urls); } catch (MalformedURLException e) { throw new UnknownArchetype(e); } }
From source file:com.streamsets.datacollector.cluster.TestTarFileCreator.java
@Test public void testCreateLibsTarGz() throws Exception { File apiLibDir = new File(tempDir, "api-lib"); File containerLibDir = new File(tempDir, "container-lib"); File streamsetsLibsDir = new File(tempDir, "streamsets-libs"); File userLibsDir = new File(tempDir, "user-libs"); URLClassLoader apiCl = new URLClassLoader(new URL[] { createJar(apiLibDir).toURL() }); URLClassLoader containerCL = new URLClassLoader(new URL[] { createJar(containerLibDir).toURL() }); Map<String, List<URL>> streamsetsLibsCl = new LinkedHashMap<>(); Map<String, List<URL>> userLibsCL = new LinkedHashMap<>(); streamsetsLibsCl.put("abc123", ImmutableList.copyOf(// w w w . ja v a2 s . c o m new URLClassLoader(new URL[] { createJar(new File(streamsetsLibsDir, "abc123")).toURL() }) .getURLs())); streamsetsLibsCl.put("abc456", ImmutableList.copyOf( new URLClassLoader(new URL[] { createJar(new File(streamsetsLibsDir, "abc456")).toURL() }) .getURLs())); userLibsCL.put("yxz456", ImmutableList .copyOf(new URLClassLoader(new URL[] { createJar(new File(userLibsDir, "yxz456")).toURL(), createJar(new File(tempDir, "yxz789")).toURL() }).getURLs())); File staticWebDir = new File(tempDir, "static-web-dir"); Assert.assertTrue(staticWebDir.mkdir()); createJar(new File(staticWebDir, "subdir")); File tarFile = new File(tempDir, "libs.tar.gz"); TarFileCreator.createLibsTarGz(ImmutableList.copyOf(apiCl.getURLs()), ImmutableList.copyOf(containerCL.getURLs()), streamsetsLibsCl, userLibsCL, staticWebDir, tarFile); TarInputStream tis = new TarInputStream(new GZIPInputStream(new FileInputStream(tarFile))); readDir("api-lib/", tis); readJar(tis); readDir("container-lib/", tis); readJar(tis); readDir("streamsets-libs/", tis); readDir("streamsets-libs/abc123/", tis); readDir("streamsets-libs/abc123/lib/", tis); readJar(tis); readDir("streamsets-libs/abc456/", tis); readDir("streamsets-libs/abc456/lib/", tis); readJar(tis); readDir("user-libs/", tis); readDir("user-libs/yxz456/", tis); readDir("user-libs/yxz456/lib/", tis); readJar(tis); readJar(tis); readJar(tis); readDir("libs-common-lib/", tis); }
From source file:de.nec.nle.siafu.model.SimulationData.java
/** * Instantiates a SimulationData object using the provided path. * // w ww . j a v a 2 s .co m * @param givenPath the path to the data */ protected SimulationData(final File givenPath) { try { classLoader = new URLClassLoader(new URL[] { givenPath.toURI().toURL() }); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.pentaho.hadoop.mapreduce.test.TestSubmitMapReduceJob.java
@Test public void submitJob() throws Exception { String[] args = { "hdfs://" + hostname + ":" + hdfsPort + "/junit/wordcount/input", "hdfs://" + hostname + ":" + hdfsPort + "/junit/wordcount/output" }; JobConf conf = new JobConf(); conf.setJobName("wordcount"); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(IntWritable.class); File jar = new File("./test-res/pentaho-mapreduce-sample.jar"); URLClassLoader loader = new URLClassLoader(new URL[] { jar.toURI().toURL() }); conf.setMapperClass(/*from w w w .j a v a 2 s. com*/ (Class<? extends Mapper>) loader.loadClass("org.pentaho.hadoop.mapreduce.sample.MRWordCount$Map")); conf.setCombinerClass((Class<? extends Reducer>) loader .loadClass("org.pentaho.hadoop.mapreduce.sample.MRWordCount$Reduce")); conf.setReducerClass((Class<? extends Reducer>) loader .loadClass("org.pentaho.hadoop.mapreduce.sample.MRWordCount$Reduce")); conf.setInputFormat(TextInputFormat.class); conf.setOutputFormat(TextOutputFormat.class); FileInputFormat.setInputPaths(conf, new Path(args[0])); FileOutputFormat.setOutputPath(conf, new Path(args[1])); conf.set("fs.default.name", "hdfs://" + hostname + ":" + hdfsPort); conf.set("mapred.job.tracker", hostname + ":" + trackerPort); conf.setJarByClass(loader.loadClass("org.pentaho.hadoop.mapreduce.sample.MRWordCount")); conf.setWorkingDirectory(new Path("/tmp/wordcount")); JobClient jobClient = new JobClient(conf); ClusterStatus status = jobClient.getClusterStatus(); assertEquals(State.RUNNING, status.getJobTrackerState()); RunningJob runningJob = jobClient.submitJob(conf); System.out.print("Running " + runningJob.getJobName() + ""); while (!runningJob.isComplete()) { System.out.print("."); Thread.sleep(500); } System.out.println(); System.out.println("Finished " + runningJob.getJobName() + "."); FileObject file = fsManager.resolveFile(buildHDFSURL("/junit/wordcount/output/part-00000")); String output = IOUtils.toString(file.getContent().getInputStream()); assertEquals("Bye\t1\nGoodbye\t1\nHadoop\t2\nHello\t2\nWorld\t2\n", output); }
From source file:de.fuberlin.wiwiss.r2r.FunctionFactoryLoader.java
/** * tries to instantiate an FunctionFactory object. * It tries to load the class referenced by the TransformationFunction URI from the class path first. * The it tries to load it from the code location. * @param URI The URI of the TransformationFunction * @return the FunctionFactory object described by the information found at the given URI or null. * @throws MalformedURLException//from w w w . ja v a 2 s . co m */ public FunctionFactory getFunctionFactory(String URI) throws MalformedURLException { boolean loadFromURLs = Config.getProperty("r2r.FunctionManager.loadFromURLs", "false") .equalsIgnoreCase("true"); FunctionFactory functionFactory = null; String codeLocation = null; String qualifiedClassName = null; String error = null; String query = "DESCRIBE <" + URI + ">"; Model model = repository.executeDescribeQuery(query); if (model.isEmpty()) { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> not found in repository."); return null; } Resource funcRes = model.getResource(URI); StmtIterator it = funcRes.listProperties(model.getProperty(R2R.qualifiedClassName)); if (it.hasNext()) qualifiedClassName = it.next().getString(); else { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> did not specify a qualified class name for loading!"); return null; } try { // First try to load from class path functionFactory = loadFunctionFactory(qualifiedClassName, ClassLoader.getSystemClassLoader()); // If FunctionFactory has been loaded, return it if (functionFactory != null) return functionFactory; if (!loadFromURLs) { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> could not be loaded from class path and loading by URL is disabled!"); return null; } // Now try the original code location it = funcRes.listProperties(model.getProperty(R2R.codeLocation)); if (it.hasNext()) codeLocation = it.next().getString(); else { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> could not be loaded from class path and did not specify any further code location!"); return null; } final String cl = codeLocation; URLClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { try { return new URLClassLoader(new URL[] { new URL(cl) }); } catch (MalformedURLException e) { if (log.isDebugEnabled()) log.debug("Malformed URL for code location: " + cl); return null; } } }); functionFactory = loadFunctionFactory(qualifiedClassName, loader); if (functionFactory != null) return functionFactory; else { if (log.isDebugEnabled()) log.debug("External Function <" + URI + "> could not be loaded: class " + qualifiedClassName + " could not be loaded from " + codeLocation + "."); return null; } } catch (InstantiationException e) { error = e.toString(); } catch (IllegalAccessException e) { error = e.toString(); } catch (ClassCastException e) { error = e.toString(); } if (error != null && log.isDebugEnabled()) log.debug("External Function <" + URI + "> could not be loaded: " + error); return functionFactory; }