List of usage examples for java.net URLClassLoader loadClass
public Class<?> loadClass(String name) throws ClassNotFoundException
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(/*w w w . j a va2 s . c o m*/ (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:com.haulmont.cuba.web.sys.singleapp.SingleAppWebServletListener.java
@Override public void contextInitialized(ServletContextEvent sce) { try {/*from w w w . ja v a 2s. c o m*/ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); //need to put the following class to WebAppClassLoader, to share it between for web and core contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory"); ServletContext servletContext = sce.getServletContext(); String dependenciesFile; try { dependenciesFile = IOUtils.toString(servletContext.getResourceAsStream("/WEB-INF/web.dependencies"), "UTF-8"); } catch (IOException e) { throw new RuntimeException("An error occurred while loading dependencies file", e); } String[] dependenciesNames = dependenciesFile.split("\\n"); URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> { try { return servletContext.getResource("/WEB-INF/lib/" + name); } catch (MalformedURLException e) { throw new RuntimeException("An error occurred while loading dependency " + name, e); } }).toArray(URL[]::new); URLClassLoader webClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader); Thread.currentThread().setContextClassLoader(webClassLoader); Class<?> appContextLoaderClass = webClassLoader.loadClass(getAppContextLoaderClassName()); appContextLoader = appContextLoaderClass.newInstance(); Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames", String.class); ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile); Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass, "contextInitialized", ServletContextEvent.class); ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce); Thread.currentThread().setContextClassLoader(contextClassLoader); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new RuntimeException("An error occurred while starting single WAR application", e); } }
From source file:me.jaimegarza.syntax.test.java.TestJavaPackedParser.java
@Test public void test03Runtime() throws ParsingException, AnalysisException, OutputException, MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { generateLanguageFile(packedArgs);//from w w w . j a va2 s .c om File source = new File(tmpLanguageFile); File sourceDir = source.getParentFile(); CompilationResult result = compileJavaFile(source, sourceDir); Assert.assertEquals(result.getErrors().length, 0, "Syntax errors found trying to execute"); URL urls[] = new URL[1]; urls[0] = sourceDir.toURI().toURL(); URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader()); String className = FilenameUtils.getBaseName(tmpLanguageFile); Class<?> clazz = classLoader.loadClass(className); Object parser = clazz.newInstance(); Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class); Method parse = parser.getClass().getMethod("parse"); Method getTotal = parser.getClass().getMethod("getTotal"); setVerbose.invoke(parser, true); parse.invoke(parser); Object o = getTotal.invoke(parser); Assert.assertTrue(o instanceof Integer); Integer i = (Integer) o; Assert.assertEquals((int) i, -17, "total does not match"); }
From source file:me.jaimegarza.syntax.test.java.TestJavaExpandedParser.java
@Test public void test03Runtime() throws ParsingException, AnalysisException, OutputException, MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { generateLanguageFile(expandedArgs);/*from ww w . jav a 2 s .co m*/ File source = new File(tmpLanguageFile); File sourceDir = source.getParentFile(); CompilationResult result = compileJavaFile(source, sourceDir); Assert.assertEquals(result.getErrors().length, 0, "Syntax errors found trying to execute"); URL urls[] = new URL[1]; urls[0] = sourceDir.toURI().toURL(); URLClassLoader classLoader = URLClassLoader.newInstance(urls, this.getClass().getClassLoader()); String className = FilenameUtils.getBaseName(tmpLanguageFile); Class<?> clazz = classLoader.loadClass(className); Object parser = clazz.newInstance(); Method setVerbose = parser.getClass().getMethod("setVerbose", boolean.class); Method parse = parser.getClass().getMethod("parse"); Method getTotal = parser.getClass().getMethod("getTotal"); setVerbose.invoke(parser, true); parse.invoke(parser); Object o = getTotal.invoke(parser); Assert.assertTrue(o instanceof Integer); Integer i = (Integer) o; Assert.assertEquals((int) i, -17, "total does not match"); }
From source file:com.haulmont.cuba.core.sys.singleapp.SingleAppCoreServletListener.java
@Override public void contextInitialized(ServletContextEvent sce) { try {/*from w ww . j a v a2 s . c o m*/ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); //need to put the following class to WebAppClassLoader, to share it between for web and core contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory"); ServletContext servletContext = sce.getServletContext(); String dependenciesFile; try { dependenciesFile = IOUtils .toString(servletContext.getResourceAsStream("/WEB-INF/core.dependencies"), "UTF-8"); } catch (IOException e) { throw new RuntimeException("An error occurred while loading dependencies file", e); } String[] dependenciesNames = dependenciesFile.split("\\n"); URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> { try { return servletContext.getResource("/WEB-INF/lib/" + name); } catch (MalformedURLException e) { throw new RuntimeException("An error occurred while loading dependency " + name, e); } }).toArray(URL[]::new); URLClassLoader coreClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader); Thread.currentThread().setContextClassLoader(coreClassLoader); Class<?> appContextLoaderClass = coreClassLoader.loadClass(getAppContextLoaderClassName()); appContextLoader = appContextLoaderClass.newInstance(); Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames", String.class); ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile); Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass, "contextInitialized", ServletContextEvent.class); ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce); Thread.currentThread().setContextClassLoader(contextClassLoader); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new RuntimeException("An error occurred while starting single WAR application", e); } }
From source file:org.sonar.core.plugins.PluginFileExtractor.java
private void completeDeprecatedMetadata(DefaultPluginMetadata metadata) throws IOException { String mainClass = metadata.getMainClass(); File pluginFile = metadata.getFile(); try {/*from ww w. j av a 2s .co m*/ // copy file in a temp directory because Windows+Oracle JVM Classloader lock the JAR file File tempFile = File.createTempFile(pluginFile.getName(), null); FileUtils.copyFile(pluginFile, tempFile); URLClassLoader pluginClassLoader = URLClassLoader.newInstance(new URL[] { tempFile.toURI().toURL() }, getClass().getClassLoader()); Plugin pluginInstance = (Plugin) pluginClassLoader.loadClass(mainClass).newInstance(); metadata.setKey(PluginKeyUtils.sanitize(pluginInstance.getKey())); metadata.setDescription(pluginInstance.getDescription()); metadata.setName(pluginInstance.getName()); } catch (Exception e) { throw new RuntimeException("The metadata main class can not be created. Plugin file=" + pluginFile.getName() + ", class=" + mainClass, e); } }
From source file:org.sonatype.mercury.gav.MercuryGavCli.java
@SuppressWarnings("unchecked") @Override/*w w w.j av a2 s . c om*/ public void invokePlexusComponent(CommandLine cli, PlexusContainer plexus) throws Exception { try { _mc = plexus.lookup(MercuryConfigurator.class); _monitor = _mc.getMonitor(cli); if (cli.hasOption(HELP)) { displayHelp(); return; } _repos = _mc.getRepositories(cli); if (Util.isEmpty(_mainArgs) || _mainArgs.size() < 2) { displayHelp(); return; } _executableGAV = _mainArgs.get(0); _executableClass = _mainArgs.get(1); ArtifactQueryList list = new ArtifactQueryList(new ArtifactMetadata(_executableGAV)); _mercury = plexus.lookup(PlexusMercury.class); List<ArtifactMetadata> deps = _mercury.resolve(_repos, ArtifactScopeEnum.runtime, list, null, null); if (deps == null) throw new Exception(LANG.getMessage("cli.no.dependencies", _executableGAV)); for (ArtifactMetadata md : deps) _monitor.message(md.toString()); _monitor.message("reading .."); List<Artifact> al = _mercury.read(_repos, deps); if (al == null) throw new Exception(LANG.getMessage("cli.no.artifacts", _executableGAV)); if (deps.size() != al.size()) throw new Exception( LANG.getMessage("cli.len.artifacts", _executableGAV, "" + deps.size(), "" + al.size())); URL[] artifacts = new URL[al.size()]; int count = 0; for (Artifact a : al) artifacts[count++] = a.getFile().toURL(); URLClassLoader cl = new URLClassLoader(artifacts); Class mainClass = cl.loadClass(_executableClass); Method[] methods = mainClass.getDeclaredMethods(); Method mainMethod = null; for (Method m : methods) if ("main".equals(m.getName())) { mainMethod = m; break; } if (mainMethod == null) throw new Exception(LANG.getMessage("cli.no.main", _executableClass)); String[] args = null; if (_mainArgs.size() > 2) { args = new String[_mainArgs.size() - 2]; for (int i = 2; i < _mainArgs.size(); i++) args[i - 2] = _mainArgs.get(i); } @SuppressWarnings("unused") Class[] params = mainMethod.getParameterTypes(); mainMethod.invoke(null, (Object) args); } catch (Exception e) { Util.say(LANG.getMessage("cli.error", e.getClass().getName(), e.getMessage()), _monitor); // e.printStackTrace(); } _monitor.message(LANG.getMessage("cli.done")); }
From source file:com.ut.healthelink.service.CCDtoTxt.java
public String TranslateCCDtoTxt(String fileLocation, String ccdFileName, int orgId) throws Exception { Organization orgDetails = organizationmanager.getOrganizationById(orgId); fileSystem dir = new fileSystem(); dir.setDir(orgDetails.getcleanURL(), "templates"); String templatefileName = orgDetails.getparsingTemplate(); URLClassLoader loader = new URLClassLoader( new URL[] { new URL("file://" + dir.getDir() + templatefileName) }); // Remove the .class extension Class cls = loader.loadClass(templatefileName.substring(0, templatefileName.lastIndexOf('.'))); Constructor constructor = cls.getConstructor(); Object CCDObj = constructor.newInstance(); Method myMethod = cls.getMethod("CCDtoTxt", new Class[] { File.class }); /* Get the uploaded CCD File */ fileLocation = fileLocation.replace("/Applications/bowlink/", "").replace("/home/bowlink/", "") .replace("/bowlink/", ""); dir.setDirByName(fileLocation);/*from w ww . jav a 2 s .co m*/ File ccdFile = new File(dir.getDir() + ccdFileName + ".xml"); /* Create the txt file that will hold the CCD fields */ String newfileName = new StringBuilder() .append(ccdFile.getName().substring(0, ccdFile.getName().lastIndexOf("."))).append(".") .append("txt").toString(); File newFile = new File(dir.getDir() + newfileName); if (newFile.exists()) { try { if (newFile.exists()) { int i = 1; while (newFile.exists()) { int iDot = newfileName.lastIndexOf("."); newFile = new File(dir.getDir() + newfileName.substring(0, iDot) + "_(" + ++i + ")" + newfileName.substring(iDot)); } newfileName = newFile.getName(); newFile.createNewFile(); } else { newFile.createNewFile(); } } catch (Exception e) { e.printStackTrace(); } } else { newFile.createNewFile(); newfileName = newFile.getName(); } FileWriter fw = new FileWriter(newFile, true); /* END */ String fileRecords = (String) myMethod.invoke(CCDObj, new Object[] { ccdFile }); fw.write(fileRecords); fw.close(); return newfileName; }
From source file:com.ut.healthelink.service.hl7toTxt.java
public String TranslateHl7toTxt(String fileLocation, String fileName, int orgId) throws Exception { Organization orgDetails = organizationmanager.getOrganizationById(orgId); fileSystem dir = new fileSystem(); dir.setDir(orgDetails.getcleanURL(), "templates"); String templatefileName = orgDetails.getparsingTemplate(); URLClassLoader loader = new URLClassLoader( new URL[] { new URL("file://" + dir.getDir() + templatefileName) }); // Remove the .class extension Class cls = loader.loadClass(templatefileName.substring(0, templatefileName.lastIndexOf('.'))); Constructor constructor = cls.getConstructor(); Object HL7Obj = constructor.newInstance(); Method myMethod = cls.getMethod("HL7toTxt", new Class[] { File.class }); /* Get the uploaded HL7 File */ fileLocation = fileLocation.replace("/Applications/bowlink/", "").replace("/home/bowlink/", "") .replace("/bowlink/", ""); dir.setDirByName(fileLocation);//from w w w . ja va 2s .c om File hl7File = new File(dir.getDir() + fileName + ".hr"); /* Create the output file */ String newfileName = new StringBuilder() .append(hl7File.getName().substring(0, hl7File.getName().lastIndexOf("."))).append(".") .append("txt").toString(); File newFile = new File(dir.getDir() + newfileName); if (newFile.exists()) { try { if (newFile.exists()) { int i = 1; while (newFile.exists()) { int iDot = newfileName.lastIndexOf("."); newFile = new File(dir.getDir() + newfileName.substring(0, iDot) + "_(" + ++i + ")" + newfileName.substring(iDot)); } newfileName = newFile.getName(); newFile.createNewFile(); } else { newFile.createNewFile(); } } catch (IOException e) { e.printStackTrace(); } } else { newFile.createNewFile(); newfileName = newFile.getName(); } FileWriter fw = new FileWriter(newFile, true); /* END */ String fileRecords = (String) myMethod.invoke(HL7Obj, new Object[] { hl7File }); fw.write(fileRecords); fw.close(); return newfileName; }
From source file:com.xiovr.unibot.plugin.impl.PluginLoaderImpl.java
private Class<?> loadClass(File jarFile, String paramName) { try {//from www.j a v a 2 s.c om Properties props = getPluginProps(jarFile); if (props == null) throw new IllegalArgumentException("No props file in " + jarFile.getName() + " found"); String pluginClassName = props.getProperty(paramName); if (pluginClassName == null || pluginClassName.length() == 0) { return null; } URL jarURL = jarFile.toURI().toURL(); // URLClassLoader classLoader = new URLClassLoader( // new URL[] { jarURL }, getClass().getClassLoader()); URLClassLoader classLoader = new URLClassLoader(new URL[] { jarURL }, org.springframework.util.ClassUtils.getDefaultClassLoader()); Class<?> pluginClass = classLoader.loadClass(pluginClassName); // classLoader.close(); return pluginClass; } catch (Exception e) { e.printStackTrace(); } return null; }