List of usage examples for java.net URLClassLoader URLClassLoader
public URLClassLoader(URL[] urls)
From source file:com.massfords.maven.spel.SpelPlugin.java
/** * Scans the source code for this module to look for instances of the * annotations we're looking for./*from w ww .j a v a 2 s . c o m*/ * * @throws MojoExecutionException thrown if there are errors during analysis */ public void execute() throws MojoExecutionException { // There's nothing to do if there are no annotations configured. if (annotations == null || annotations.isEmpty()) { getLog().warn("There are no annotations configured so there's nothing for this plugin to do."); return; } int processedCount = 0; try { // these paths should include our module's source root plus any generated code List<String> compileSourceOutputs = Collections.singletonList(project.getBuild().getOutputDirectory()); URL[] sourceFiles = buildMavenClasspath(compileSourceOutputs); // the project classpath includes the source roots plus the transitive // dependencies according to our Mojo annotation's requiresDependencyResolution // attribute. URL[] projectClasspath = buildMavenClasspath(this.projectClasspathElements); URLClassLoader projectClassloader = new URLClassLoader(projectClasspath); // todo - is there any savings to be had here by caching the reflections but tweaking the filters for the given module? Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(sourceFiles) .addClassLoaders(projectClassloader).setScanners(new MethodAnnotationsScanner()) // todo here is where to filter the packages // .filterInputsBy(new Predicate<String>() { // @Override // public boolean apply(String input) { // return true; // } // }) ); // using the newly created classloaders and reflections API, scan the // classpath looking for instances of the annotations processedCount += processAnnotations(projectClassloader, reflections); } catch (SpelValidationException e) { if (failOnError) { throw new MojoExecutionException("A fatal error occurred while validating Spel annotations," + " see stack trace for details.", e); } } catch (Throwable e) { throw new MojoExecutionException( "A fatal error occurred while validating Spel annotations," + " see stack trace for details.", e); } getLog().info(String.format("Processed %d annotations", processedCount)); report.createReportFile( new File(this.project.getModel().getBuild().getDirectory(), "spel-maven-plugin/report.json")); if (failOnError && report.hasErrors()) { throw new MojoExecutionException("Spel validation failed on one or more annotations. See the specific" + "error output for more information."); } }
From source file:com.mulesoft.jockey.maven.GenerateMojo.java
protected ClassLoader getCompileClassLoader() throws Exception { if (classLoader == null) { List<URL> urls = new ArrayList<URL>(); for (Object object : project.getCompileClasspathElements()) { String path = (String) object; urls.add(new File(path).toURL()); }// w w w .j av a2s .com classLoader = new URLClassLoader(urls.toArray(new URL[] {})); } return classLoader; }
From source file:com.wavemaker.commons.io.ResourceURLTest.java
@Test public void shouldWorkViaClassLoader() throws Exception { Folder jail = this.root.getFolder("jail").jail(); URLClassLoader classLoader = new URLClassLoader(new URL[] { ResourceURL.get(jail) }); assertThat(IOUtils.toString(classLoader.getResourceAsStream("/a/b/c.txt")), Matchers.is(Matchers.equalTo("c"))); assertThat(classLoader.getResource("/x/y/z.txt").toString(), Matchers.is(Matchers.equalTo("rfs:/x/y/z.txt"))); }
From source file:generate.MapGenerateAction.java
@Override public String execute() { String file_path = "/home/chanakya/NetBeansProjects/Concepto/UploadedFiles"; try {/* www .j a v a 2 s . co m*/ File fileToCreate = new File(file_path, concept_map.getUploadedFileFileName()); FileUtils.copyFile(concept_map.getUploadedFile(), fileToCreate); } catch (Throwable t) { System.out.println("E1: " + t.getMessage()); return ERROR; } try { List<String> temp_text = FileUtils.readLines(concept_map.getUploadedFile()); StringBuilder text = new StringBuilder(); for (String s : temp_text) { text.append(s); } concept_map.setInput_text(text.toString()); } catch (IOException e) { //e.printStackTrace(); System.out.println("E2: " + e.getMessage()); return ERROR; } String temp_filename = concept_map.getUploadedFileFileName().split("\\.(?=[^\\.]+$)")[0]; temp_filename = temp_filename.trim(); try { String temp = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar " + file_path + " " + temp_filename; System.out.println(temp); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCore.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; System.out.println(args[0]); System.out.println(args[1]); try { mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException e) { System.out.println("This is the exception: " + e.getTargetException().toString()); } } catch (IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E3: " + e.getMessage()); return ERROR; } try { String temp2 = "java -jar /home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar " + file_path + " " + temp_filename; System.out.println(temp2); File jarfile = new File("/home/chanakya/NetBeansProjects/Concepto/src/java/generate/MajorCoreII.jar"); JarFile jar = new JarFile(jarfile); Manifest manifest = jar.getManifest(); Attributes attrs = manifest.getMainAttributes(); String mainClassName = attrs.getValue(Attributes.Name.MAIN_CLASS); System.out.println(mainClassName); URL url = new URL("file", null, jarfile.getAbsolutePath()); ClassLoader cl = new URLClassLoader(new URL[] { url }); Class mainClass = cl.loadClass(mainClassName); Method mainMethod = mainClass.getMethod("main", new Class[] { String[].class }); String[] args = new String[2]; args[0] = file_path; args[1] = temp_filename; mainMethod.invoke(mainClass, new Object[] { args }); } catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException | NoSuchMethodException | ClassNotFoundException | IOException e) { System.out.println("E4: " + e.getMessage()); return ERROR; } String cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/add_to_graph.py \"/home/chanakya/NetBeansProjects/Concepto/UploadedFiles/" + temp_filename + "_OllieOutput.txt\""; String[] finalCommand; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; System.out.println("CMD: " + cmd); try { //ProcessBuilder builder = new ProcessBuilder(finalCommand); //builder.redirectErrorStream(true); //Process process = builder.start(); Process process = Runtime.getRuntime().exec(finalCommand); int exitVal = process.waitFor(); System.out.println("Process exitValue2: " + exitVal); } catch (Throwable t) { System.out.println("E5: " + t.getMessage()); return ERROR; } cmd = "python /home/chanakya/NetBeansProjects/Concepto/src/java/generate/json_correct.py"; finalCommand = new String[3]; finalCommand[0] = "/bin/sh"; finalCommand[1] = "-c"; finalCommand[2] = cmd; try { //Process process = Runtime.getRuntime().exec(finalCommand); ProcessBuilder builder = new ProcessBuilder(finalCommand); // builder.redirectErrorStream(true); Process process = builder.start(); int exitVal = process.waitFor(); System.out.println("Process exitValue3: " + exitVal); } catch (Throwable t) { System.out.println("E6: " + t.getMessage()); return ERROR; } try { List<String> temp_text_1 = FileUtils .readLines(FileUtils.getFile("/home/chanakya/NetBeansProjects/Concepto/web", "new_graph.json")); StringBuilder text_1 = new StringBuilder(); for (String s : temp_text_1) { text_1.append(s); } concept_map.setOutput_text(text_1.toString()); } catch (IOException e) { System.out.println("E7: " + e.getMessage()); return ERROR; } Random rand = new Random(); int unique_id = rand.nextInt(99999999); System.out.println("Going In DB"); try { MongoClient mongo = new MongoClient(); DB db = mongo.getDB("Major"); DBCollection collection = db.getCollection("ConceptMap"); BasicDBObject document = new BasicDBObject(); document.append("InputText", concept_map.getInput_text()); document.append("OutputText", concept_map.getOutput_text()); document.append("ChapterName", concept_map.getChapter_name()); document.append("ChapterNumber", concept_map.getChapter_number()); document.append("SectionName", concept_map.getSection_name()); document.append("SectionNumber", concept_map.getSection_number()); document.append("UniqueID", Integer.toString(unique_id)); collection.insert(document); //collection.save(document); } catch (MongoException e) { System.out.println("E8: " + e.getMessage()); return ERROR; } catch (UnknownHostException ex) { Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex); System.out.println("E9"); return ERROR; } System.out.println("Out DB"); return SUCCESS; }
From source file:com.pros.jsontransform.plugin.PluginManager.java
@SuppressWarnings("rawtypes") private Class loadPlugin(final String pluginClassName) throws ObjectTransformerException { Class pluginClass = null;// w ww . j a v a 2s. c om try { if (urlClassLoader == null) { File folder = new File(pluginFolder); File[] listOfFiles = folder.listFiles(); int jarCount = 0; URL[] jarUrls = new URL[listOfFiles.length]; for (int i = 0; i < listOfFiles.length; i++) { File jarFile = listOfFiles[i]; if (jarFile.isFile() && jarFile.getName().endsWith(".jar")) { jarUrls[jarCount++] = jarFile.toURI().toURL(); } } if (jarCount == 0) { throw new ObjectTransformerException("Cannot load plugin " + pluginClassName + " No jars found in plugin folder " + pluginFolder); } urlClassLoader = new URLClassLoader(jarUrls); } pluginClass = urlClassLoader.loadClass(pluginClassName); } catch (Exception ex) { throw new ObjectTransformerException("Cannot load plugin " + pluginClassName, ex); } return pluginClass; }
From source file:org.raml.jaxrs.codegen.core.MediaTypeGeneratorTestCase.java
private void run(final JaxrsVersion jaxrsVersion, final boolean useJsr303Annotations) throws Exception { final Set<String> generatedSources = new HashSet<String>(); final Configuration configuration = new Configuration(); configuration.setJaxrsVersion(jaxrsVersion); configuration.setUseJsr303Annotations(useJsr303Annotations); configuration.setOutputDirectory(codegenOutputFolder.getRoot()); configuration.setBasePackageName(TEST_BASE_PACKAGE); String dirPath = getClass().getResource("/org/raml").getPath(); configuration.setSourceDirectory(new File(dirPath)); generatedSources.addAll(new Generator().run( new InputStreamReader( getClass().getResourceAsStream("/org/raml/mediatype/application_octet-stream.yaml")), configuration));//from w w w. j a va 2 s.c o m // test compile the classes final JavaCompiler compiler = new JavaCompilerFactory().createCompiler("eclipse"); final JavaCompilerSettings settings = compiler.createDefaultSettings(); settings.setSourceVersion("1.5"); settings.setTargetVersion("1.5"); settings.setDebug(true); final String[] sources = generatedSources.toArray(EMPTY_STRING_ARRAY); final FileResourceReader sourceReader = new FileResourceReader(codegenOutputFolder.getRoot()); final FileResourceStore classWriter = new FileResourceStore(compilationOutputFolder.getRoot()); final CompilationResult result = compiler.compile(sources, sourceReader, classWriter, Thread.currentThread().getContextClassLoader(), settings); assertThat(ToStringBuilder.reflectionToString(result.getErrors(), ToStringStyle.SHORT_PREFIX_STYLE), result.getErrors(), is(emptyArray())); assertThat(ToStringBuilder.reflectionToString(result.getWarnings(), ToStringStyle.SHORT_PREFIX_STYLE), result.getWarnings(), is(emptyArray())); // test load the classes with Jersey final URLClassLoader resourceClassLoader = new URLClassLoader( new URL[] { compilationOutputFolder.getRoot().toURI().toURL() }); final ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(resourceClassLoader); final ResourceConfig config = new PackagesResourceConfig(TEST_BASE_PACKAGE); Set<Class<?>> classes = config.getClasses(); Iterator<Class<?>> it = classes.iterator(); Class<?> something = it.next(); Method[] methods = something.getDeclaredMethods(); Method methodWithInputStreamParam = methods[0]; assertEquals(InputStream.class.getName(), methodWithInputStreamParam.getParameterTypes()[0].getName()); } finally { Thread.currentThread().setContextClassLoader(initialClassLoader); } }
From source file:io.syndesis.maven.ExtractConnectorDescriptorsMojo.java
private URLClassLoader createClassLoader(File jar) throws MalformedURLException { return AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { try { return new URLClassLoader(new URL[] { jar.toURI().toURL() }); } catch (MalformedURLException e) { return null; }/*from w ww. jav a 2 s . com*/ } }); }
From source file:org.cloudfoundry.tools.io.ResourceURLTest.java
@Test public void shouldWorkViaClassLoader() throws Exception { Folder jail = this.root.getFolder("jail").jail(); URLClassLoader classLoader = new URLClassLoader(new URL[] { ResourceURL.get(jail) }); assertThat(IOUtils.toString(classLoader.getResourceAsStream("/a/b/c.txt")), is(equalTo("c"))); assertThat(classLoader.getResource("/x/y/z.txt").toString(), startsWith("rfs:")); assertThat(classLoader.getResource("/x/y/z.txt").toString(), endsWith("/x/y/z.txt")); }
From source file:org.lazydoc.plugin.LazyDocMojo.java
private ClassLoader getClassLoader() throws MojoExecutionException, DependencyResolutionRequiredException { List<URL> classpathURLs = new ArrayList<URL>(); this.addRelevantPluginDependenciesToClasspath(classpathURLs); this.addRelevantProjectDependenciesToClasspath(classpathURLs); for (URL classpath : classpathURLs) { getLog().debug("Classpath: " + classpath.toString()); }//from w w w . j a v a2 s. c om return new URLClassLoader(classpathURLs.toArray(new URL[classpathURLs.size()])); }
From source file:com.varaneckas.hawkscope.plugin.PluginManager.java
private void processPlugin(final File pluginDir, final String jar) { try {/*from ww w . j a va2s .c o m*/ final File jarFile = new File(pluginDir.getAbsolutePath() + "/" + jar); final URLClassLoader classLoader = new URLClassLoader(new URL[] { jarFile.toURI().toURL() }); final Reader r = new InputStreamReader(classLoader.getResourceAsStream("plugin.loader")); String pluginClass = ""; int c = 0; while ((c = r.read()) != -1) { pluginClass += (char) c; } r.close(); log.debug("Processing Plugin: " + pluginClass); if (!isPluginEnabled(pluginClass)) { log.debug("Plugin disabled, skipping"); getAllPlugins().add(new DisabledPlugin(pluginClass)); return; } Class<?> p = classLoader.loadClass(pluginClass); Method creator = null; try { creator = p.getMethod("getInstance", new Class[] {}); } catch (final NoSuchMethodException no) { log.debug("Plugin does not implement a singleton getter"); } Plugin plugin; if (creator == null) { plugin = (Plugin) p.newInstance(); } else { plugin = (Plugin) creator.invoke(p, new Object[] {}); } creator = null; p = null; if (plugin != null) { log.debug("Adding plugin: " + plugin); getAllPlugins().add(plugin); } } catch (final Exception e) { log.warn("Failed loading plugin: " + jar, e); } }