List of usage examples for java.net URLClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
From source file:org.onecmdb.core.utils.transform.jdbc.JDBCDataSourceWrapper.java
public void setupDataSource(Properties p) throws IOException { // Load this under the provieded DriverLib class path. URLClassLoader loader = new URLClassLoader(getDriverLibURL(), this.getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(loader); try {// ww w . jav a2 s . c o m Class driver = loader.loadClass(p.getProperty("jdbc.driverClass")); try { Object instance = driver.newInstance(); System.out.println("Instance...." + instance); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } /* Class cl = null; String clazz = "org.apache.commons.dbcp.BasicDataSource"; try { cl = loader.loadClass(clazz); } catch (ClassNotFoundException e) { throw new IOException("Can't load class '" + clazz + "', using driver lib '" + driverLib + "'"); } BasicDataSource jdbcSrc; try { jdbcSrc = (BasicDataSource) cl.newInstance(); } catch (Exception e) { throw new IOException("Can't instanciate class '" + clazz + "', using driver lib '" + driverLib + "'"); } */ ClassLoaderBasicDataSource jdbcSrc = new ClassLoaderBasicDataSource(); jdbcSrc.setDriverClassLoader(loader); jdbcSrc.setUrl(p.getProperty("db.url")); jdbcSrc.setUrl(p.getProperty("jdbc.url")); jdbcSrc.setDriverClassName(p.getProperty("db.driverClass")); jdbcSrc.setDriverClassName(p.getProperty("jdbc.driverClass")); jdbcSrc.setUsername(p.getProperty("db.user")); jdbcSrc.setUsername(p.getProperty("jdbc.user")); jdbcSrc.setPassword(p.getProperty("db.password")); jdbcSrc.setPassword(p.getProperty("jdbc.password")); /* String clazz2 = "org.onecmdb.core.utils.transform.jdbc.ClassLoaderBasicDataSource"; try { cl = loader.loadClass(clazz2); } catch (ClassNotFoundException e) { throw new IOException("Can't load class '" + clazz + "', using driver lib '" + driverLib + "'"); } ClassLoaderBasicDataSource jdbcSrc1; try { jdbcSrc1 = (ClassLoaderBasicDataSource) cl.newInstance(); jdbcSrc1.setDs(jdbcSrc); } catch (Exception e) { throw new IOException("Can't instanciate class '" + clazz + "', using driver lib '" + driverLib + "'"); } */ setDataSource(jdbcSrc); }
From source file:net.sourceforge.fullsync.cli.Main.java
@Override public void launchGui(Injector injector) throws Exception { String arch = "x86"; //$NON-NLS-1$ String osName = System.getProperty("os.name").toLowerCase(); //$NON-NLS-1$ String os = "unknown"; //$NON-NLS-1$ if (-1 != System.getProperty("os.arch").indexOf("64")) { //$NON-NLS-1$ //$NON-NLS-2$ arch = "x86_64"; //$NON-NLS-1$ }//from w ww . j a v a2s. co m if (-1 != osName.indexOf("linux")) { //$NON-NLS-1$ os = "gtk.linux"; //$NON-NLS-1$ } else if (-1 != osName.indexOf("windows")) { //$NON-NLS-1$ os = "win32.win32"; //$NON-NLS-1$ } else if (-1 != osName.indexOf("mac")) { //$NON-NLS-1$ os = "cocoa.macosx"; //$NON-NLS-1$ } CodeSource cs = getClass().getProtectionDomain().getCodeSource(); String libDirectory = cs.getLocation().toURI().toString().replaceAll("^(.*)/[^/]+\\.jar$", "$1/"); //$NON-NLS-1$ //$NON-NLS-2$ List<URL> jars = new ArrayList<>(); jars.add(new URL(libDirectory + "net.sourceforge.fullsync-fullsync-assets.jar")); //$NON-NLS-1$ jars.add(new URL(libDirectory + "net.sourceforge.fullsync-fullsync-ui.jar")); //$NON-NLS-1$ // add correct SWT implementation to the class-loader jars.add(new URL(libDirectory + String.format("org.eclipse.platform-org.eclipse.swt.%s.%s.jar", os, arch))); //$NON-NLS-1$ // instantiate an URL class-loader with the constructed class-path and load the UI URLClassLoader cl = new URLClassLoader(jars.toArray(new URL[jars.size()]), Main.class.getClassLoader()); Thread.currentThread().setContextClassLoader(cl); Class<?> cls = cl.loadClass("net.sourceforge.fullsync.ui.GuiController"); //$NON-NLS-1$ Method launchUI = cls.getDeclaredMethod("launchUI", Injector.class); //$NON-NLS-1$ launchUI.invoke(null, injector); }
From source file:interactivespaces.workbench.project.test.JavaTestRunner.java
/** * Run the given tests in the given class loader. This method is somewhat complicated, since it needs to use * reflection to isolate the test runner in a separate class loader that does not derive from the current class. * * @param testCompilationFolder// w w w . j a v a 2 s . c om * the folder containing the test classes * @param classLoader * classLoader to use for running tests * @param context * the build context * * @return {@code true} if all tests passed */ private boolean runTestsInIsolation(File testCompilationFolder, URLClassLoader classLoader, ProjectTaskContext context) { try { // This code is equivalent to TestRunnerBridge.runTests(testClassNames, // classLoader), except // that it is sanitized through the test class loader. Class<?> testRunnerClass = classLoader.loadClass(ISOLATED_TESTRUNNER_CLASSNAME); Method runner = testRunnerClass.getMethod(ISOLATED_TESTRUNNER_METHODNAME, File.class, URLClassLoader.class, Log.class); Object testRunner = testRunnerClass.newInstance(); Object result = runner.invoke(testRunner, testCompilationFolder, classLoader, context.getWorkbenchTaskContext().getWorkbench().getLog()); return (Boolean) result; } catch (Exception e) { context.getWorkbenchTaskContext().getWorkbench().getLog().error("Error running tests", e); throw new InteractiveSpacesException("Error running tests", e); } }
From source file:org.apache.drill.jdbc.ITTestShadedJar.java
@Test public void executeJdbcAllQuery() throws Exception { // print class path for debugging System.out.println("java.class.path:"); System.out.println(System.getProperty("java.class.path")); final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true);/* w w w . j a v a2s. c o m*/ method.invoke(loader, getJdbcUrl()); Class<?> clazz = loader.loadClass("org.apache.drill.jdbc.Driver"); try { Driver driver = (Driver) clazz.newInstance(); try (Connection c = driver.connect("jdbc:drill:drillbit=localhost:31010", null)) { String path = Paths.get("").toAbsolutePath().toString() + "/src/test/resources/types.json"; printQuery(c, "select * from dfs.`" + path + "`"); } } catch (Exception ex) { throw ex; } }
From source file:org.apache.drill.jdbc.ITTestShadedJar.java
@Test public void testDatabaseVersion() throws Exception { // print class path for debugging System.out.println("java.class.path:"); System.out.println(System.getProperty("java.class.path")); final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader(); Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true);//from w w w . j av a 2 s.com method.invoke(loader, getJdbcUrl()); Class<?> clazz = loader.loadClass("org.apache.drill.jdbc.Driver"); try { Driver driver = (Driver) clazz.newInstance(); try (Connection c = driver.connect("jdbc:drill:drillbit=localhost:31010", null)) { DatabaseMetaData metadata = c.getMetaData(); assertEquals("Apache Drill JDBC Driver", metadata.getDriverName()); assertEquals("Apache Drill Server", metadata.getDatabaseProductName()); //assertEquals() } } catch (Exception ex) { throw ex; } }
From source file:com.datatorrent.stram.StramLocalClusterTest.java
@Test public void testDynamicLoading() throws Exception { String generatedJar = generatejar("POJO"); URLClassLoader uCl = URLClassLoader.newInstance(new URL[] { new File(generatedJar).toURI().toURL() }); Class<?> pojo = uCl.loadClass("POJO"); DynamicLoaderApp app = new DynamicLoaderApp(); app.generatedJar = generatedJar;/* w w w .j a va 2 s. com*/ app.pojo = pojo; LocalMode lma = LocalMode.newInstance(); lma.prepareDAG(app, new Configuration()); LocalMode.Controller lc = lma.getController(); lc.runAsync(); DynamicLoaderApp.latch.await(); Assert.assertTrue(DynamicLoaderApp.passed); lc.shutdown(); }
From source file:net.sourceforge.vulcan.maven.MavenBuildPlugin.java
void createConfigurationFactory() throws ConfigException { // find maven2 home for (MavenHome home : config.getMavenHomes()) { if (MavenBuildTool.isMaven2(home.getDirectory())) { maven2HomeDirectory = home.getDirectory(); maven2ProfileName = home.getDescription(); break; }/* ww w . j a va 2s . com*/ } if (maven2HomeDirectory == null) { throw new ConfigException("maven.maven2.required", null); } // create classloader final URLClassLoader classLoader = new PackageFilteringClassLoader(createURLs(maven2HomeDirectory), getClass().getClassLoader(), MavenIntegration.class.getPackage().getName()); // load integration provider try { configuratorFactory = (MavenProjectConfiguratorFactory) classLoader .loadClass(MavenIntegration.class.getName()).newInstance(); } catch (Exception e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new RuntimeException(e); } }
From source file:org.bigtester.ate.experimentals.DynamicClassLoader.java
/** * F2 test./*from w w w . ja v a 2s .com*/ * * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException * @throws MalformedURLException */ @Test public void f2Test() throws InstantiationException, IllegalAccessException, ClassNotFoundException, MalformedURLException { /** Compilation Requirements *********************************************************************************************/ DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null); // This sets up the class path that the compiler will use. // I've added the .jar file that contains the DoStuff interface within // in it... List<String> optionList = new ArrayList<String>(); optionList.add("-classpath"); optionList.add(System.getProperty("java.class.path") + ";dist/InlineCompiler.jar"); File helloWorldJava = new File(System.getProperty("user.dir") + "/generated-code/caserunners/org/bigtester/ate/model/project/CaseRunner8187856223134148550.java"); Iterable<? extends JavaFileObject> compilationUnit = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava)); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnit); /********************************************************************************************* Compilation Requirements **/ if (task.call()) { /** Load and execute *************************************************************************************************/ System.out.println("Yipe"); // Create a new custom class loader, pointing to the directory that // contains the compiled // classes, this should point to the top of the package structure! URLClassLoader classLoader = new URLClassLoader(new URL[] { new File(System.getProperty("user.dir") + "/generated-code/caserunners/").toURI().toURL() }); // Load the class from the classloader by name.... Class<?> loadedClass = classLoader .loadClass("org.bigtester.ate.model.project.CaseRunner8187856223134148550"); // Create a new instance... Object obj = loadedClass.newInstance(); // Santity check if (obj instanceof IRunTestCase) { ((IRunTestCase) obj).setCurrentExecutingTCName("test case name example"); Assert.assertEquals(((IRunTestCase) obj).getCurrentExecutingTCName(), "test case name example"); System.out.println("pass"); } /************************************************************************************************* Load and execute **/ } else { for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { System.out.format("Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getSource().toUri()); } } }
From source file:interactivespaces.workbench.project.test.IsolatedClassloaderJavaTestRunner.java
/** * Run the given tests in the given class loader. This method is somewhat complicated, since it needs to use * reflection to isolate the test runner in a separate class loader that does not derive from the current class. * * @param testCompilationFolder/*from w w w . jav a2s. com*/ * the folder containing the test classes * @param classLoader * classLoader to use for running tests * @param context * the build context * * @throws InteractiveSpacesException * the tests failed */ private void runTestsInIsolation(File testCompilationFolder, URLClassLoader classLoader, ProjectTaskContext context) throws InteractiveSpacesException { boolean result = false; try { // This code is equivalent to TestRunnerBridge.runTests(testClassNames, // classLoader), except // that it is sanitized through the test class loader. Class<?> testRunnerClass = classLoader.loadClass(ISOLATED_TESTRUNNER_CLASSNAME); Method runner = testRunnerClass.getMethod(ISOLATED_TESTRUNNER_METHODNAME, File.class, URLClassLoader.class, Log.class); Object testRunner = testRunnerClass.newInstance(); result = (Boolean) runner.invoke(testRunner, testCompilationFolder, classLoader, context.getWorkbenchTaskContext().getWorkbench().getLog()); } catch (Exception e) { // This catch here for the reflection errors context.getWorkbenchTaskContext().getWorkbench().getLog().error("Error running tests", e); throw new InteractiveSpacesException("Error running tests", e); } if (!result) { throw new SimpleInteractiveSpacesException("Unit tests failed"); } }
From source file:com.massfords.maven.spel.SpelPlugin.java
/** * Initializes the class for the given SpelAnnotation if it can be loaded * from the current classpath. This method handles the possibility that the * annotation cannot be loaded in case the user configured the plugin at * a parent module or similar in the idea that child modules would inherit * the configuration.//from w ww . j av a2 s . co m * * @param projectClassloader * @param sa */ private void initAnnotationType(URLClassLoader projectClassloader, SpelAnnotation sa) { if (sa.getClazz() == null) { try { //noinspection unchecked Class<? extends Annotation> clazz = (Class<? extends Annotation>) projectClassloader .loadClass(sa.getName()); sa.setClazz(clazz); getLog().info(String.format("Loaded annotation %s", sa.getName())); } catch (Exception e) { getLog().warn("Could not find and instantiate class for annotation with name: " + sa.getName()); } } if (sa.getExpressionRootClass() == null && sa.getExpressionRoot() != null) { try { //noinspection unchecked Class<?> clazz = projectClassloader.loadClass(sa.getExpressionRoot()); sa.setExpressionRootClass(clazz); getLog().info(String.format("Loaded annotation expressionRoot %s", sa.getExpressionRoot())); } catch (Exception e) { getLog().warn("Could not find and instantiate class for annotation expressionRoot with name: " + sa.getExpressionRoot()); } } }