Java Code Examples for java.net.URLClassLoader

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project fits_1, under directory /src/edu/harvard/hul/ois/fits/.

Source file: FitsJarMain.java

  38 
vote

public static void addPath(String s) throws Exception {
  File f=new File(s);
  URL u=f.toURI().toURL();
  URLClassLoader urlClassLoader=(URLClassLoader)ClassLoader.getSystemClassLoader();
  Class urlClass=URLClassLoader.class;
  Method method=urlClass.getDeclaredMethod("addURL",new Class[]{URL.class});
  method.setAccessible(true);
  method.invoke(urlClassLoader,new Object[]{u});
}
 

Example 2

From project ceres, under directory /ceres-core/src/test/java/com/bc/ceres/core/runtime/internal/.

Source file: ModuleScannerTest.java

  33 
vote

public void testClassPathScanner() throws IOException, CoreException {
  File modulesDir=new File(Config.getDirForAppB(),"modules");
  URL[] urls=getDirEntryUrls(modulesDir);
  URLClassLoader urlClassLoader=new URLClassLoader(urls,String.class.getClassLoader());
  ModuleImpl[] modules=new ModuleLoader(Logger.getAnonymousLogger()).loadModules(urlClassLoader,ProgressMonitor.NULL);
  testAppBContents(modulesDir,modules);
}
 

Example 3

From project CloudReports, under directory /src/main/java/cloudreports/extensions/.

Source file: ExtensionsLoader.java

  33 
vote

/** 
 * Loads an extension file using its URL.
 * @param url             the URL of the extension file.
 * @throws IOException     if the system classloader could not load theextension.
 * @since   1.0
 */
private static void addURL(URL url) throws IOException {
  URLClassLoader sysloader=(URLClassLoader)ClassLoader.getSystemClassLoader();
  Class<?> sysclass=URLClassLoader.class;
  try {
    Method method=sysclass.getDeclaredMethod("addURL",parameters);
    method.setAccessible(true);
    method.invoke(sysloader,new Object[]{url});
  }
 catch (  Throwable t) {
    throw new IOException("Error: could not add URL to system classloader");
  }
}
 

Example 4

From project EMF-IncQuery, under directory /plugins/org.eclipse.viatra2.emf.incquery.runtime/src/org/eclipse/viatra2/emf/incquery/runtime/util/.

Source file: ClassLoaderUtil.java

  33 
vote

/** 
 * Returns a  {@link ClassLoader} that is capable of loading classes definedin the project of the input file, or in any dependencies of that project.
 * @param file
 * @return {@link ClassLoader}
 * @throws CoreException
 * @throws MalformedURLException
 */
public static ClassLoader getClassLoader(IFile file) throws CoreException, MalformedURLException {
  if (file != null) {
    IProject project=file.getProject();
    IJavaProject jp=JavaCore.create(project);
    String[] classPathEntries=JavaRuntime.computeDefaultRuntimeClassPath(jp);
    List<URL> classURLs=getClassesAsURLs(classPathEntries);
    URL[] urls=(URL[])classURLs.toArray(new URL[classURLs.size()]);
    URLClassLoader loader=URLClassLoader.newInstance(urls,jp.getClass().getClassLoader());
    return loader;
  }
  return null;
}
 

Example 5

From project autopatch-maven-plugin, under directory /src/main/java/com/tacitknowledge/autopatch/maven/.

Source file: AbstractAutoPatchMojo.java

  32 
vote

/** 
 * Adds the classpath elements to a new class loader and sets it as the  current thread context's class loader.
 * @throws MalformedURLException if a classpath element contains a malformed url.
 */
protected void addClasspathElementsClassLoader() throws MalformedURLException {
  URL[] urls=new URL[classpathElements.size()];
  Iterator iter=classpathElements.iterator();
  int i=0;
  while (iter.hasNext()) {
    urls[i++]=new File((String)iter.next()).toURL();
  }
  URLClassLoader urlClassLoader=new URLClassLoader(urls,Thread.currentThread().getContextClassLoader());
  Thread.currentThread().setContextClassLoader(urlClassLoader);
}
 

Example 6

From project avro, under directory /lang/java/compiler/src/test/java/org/apache/avro/compiler/idl/.

Source file: TestIdl.java

  32 
vote

private String generate() throws Exception {
  ClassLoader cl=Thread.currentThread().getContextClassLoader();
  File file=new File(".");
  String currentWorkPath=file.toURI().toURL().toString();
  String newPath=currentWorkPath + "src" + File.separator+ "test"+ File.separator+ "idl"+ File.separator+ "putOnClassPath"+ File.separator;
  URL[] newPathURL=new URL[]{new URL(newPath)};
  URLClassLoader ucl=new URLClassLoader(newPathURL,cl);
  Idl parser=new Idl(in,ucl);
  Protocol p=parser.CompilationUnit();
  return p.toString(true);
}
 

Example 7

From project azkaban, under directory /azkaban-common/src/java/azkaban/common/utils/.

Source file: Utils.java

  32 
vote

public static List<String> getClassLoaderDescriptions(ClassLoader loader){
  List<String> values=new ArrayList<String>();
  while (loader != null) {
    if (loader instanceof URLClassLoader) {
      URLClassLoader urlLoader=(URLClassLoader)loader;
      for (      URL url : urlLoader.getURLs())       values.add(url.toString());
    }
 else {
      values.add(loader.getClass().getName());
    }
    loader=loader.getParent();
  }
  return values;
}
 

Example 8

From project BeeQueue, under directory /lib/src/hyperic-sigar-1.6.4/bindings/java/examples/.

Source file: Runner.java

  32 
vote

private static void addURLs(URL[] jars) throws Exception {
  URLClassLoader loader=(URLClassLoader)Thread.currentThread().getContextClassLoader();
  Method addURL=URLClassLoader.class.getDeclaredMethod("addURL",new Class[]{URL.class});
  addURL.setAccessible(true);
  for (int i=0; i < jars.length; i++) {
    addURL.invoke(loader,new Object[]{jars[i]});
  }
}
 

Example 9

From project fitnesse, under directory /src/util/.

Source file: FileUtil.java

  32 
vote

public static void addUrlToClasspath(URL u) throws Exception {
  URLClassLoader sysloader=(URLClassLoader)ClassLoader.getSystemClassLoader();
  Class<URLClassLoader> sysclass=URLClassLoader.class;
  Method method=sysclass.getDeclaredMethod("addURL",new Class[]{URL.class});
  method.setAccessible(true);
  method.invoke(sysloader,new Object[]{u});
}
 

Example 10

From project Gemini-Blueprint, under directory /integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/tcclManagement/.

Source file: ClientOnlyTcclTest.java

  32 
vote

public void testTCCLUnmanagedWithPredefinedClassLoader() throws Exception {
  URLClassLoader dummyCL=new URLClassLoader(new URL[0]);
  ClassLoader previous=Thread.currentThread().getContextClassLoader();
  try {
    Thread.currentThread().setContextClassLoader(dummyCL);
    ClassLoader cl=getUnmanagedTCCL().getTCCL();
    assertSame(dummyCL,cl);
  }
  finally {
    Thread.currentThread().setContextClassLoader(previous);
  }
}
 

Example 11

From project geronimo-xbean, under directory /xbean-classpath/src/main/java/org/apache/xbean/classpath/.

Source file: ContextClassPath.java

  32 
vote

public void addJarsToPath(File dir) throws Exception {
  ClassLoader contextClassLoader=getContextClassLoader();
  if (contextClassLoader instanceof URLClassLoader) {
    URLClassLoader loader=(URLClassLoader)contextClassLoader;
    this.addJarsToPath(dir,loader);
  }
}
 

Example 12

From project grails-ide, under directory /org.grails.ide.eclipse.test/src/org/grails/ide/eclipse/test/.

Source file: Grails20JUnitIntegrationTests.java

  32 
vote

@SuppressWarnings("rawtypes") public void testThatASTTransformGotExecuted() throws Exception {
  URLClassLoader classLoader=getRuntimeClassLoader(javaProject);
  Class testClass=Class.forName(testDomainClassName,false,classLoader);
  Method m=getMethod(testClass,"testSomething");
  assertAnnotation(m,"org.junit.Test");
}
 

Example 13

From project GraphWalker, under directory /src/main/java/org/graphwalker/.

Source file: ClassPathHack.java

  32 
vote

protected static void addURL(URL u) throws IOException {
  URLClassLoader sysloader=(URLClassLoader)ClassLoader.getSystemClassLoader();
  Class<?> sysclass=URLClassLoader.class;
  try {
    Method method=sysclass.getDeclaredMethod("addURL",parameters);
    method.setAccessible(true);
    method.invoke(sysloader,u);
  }
 catch (  Exception e) {
    Util.logStackTraceToError(e);
    throw new IOException("Error, could not add URL to system classloader");
  }
}
 

Example 14

From project griffon, under directory /subprojects/griffon-cli/src/main/groovy/org/codehaus/griffon/cli/.

Source file: GriffonScriptRunner.java

  32 
vote

public Gant createGantInstance(GantBinding binding){
  URLClassLoader classLoader=createClassLoader();
  Gant gant=new Gant(initBinding(binding),classLoader);
  gantCustomizer=new GantCustomizer(settings,binding,gant);
  return gant;
}
 

Example 15

From project gwt-maven-plugin, under directory /src/main/java/org/codehaus/mojo/gwt/webxml/.

Source file: MergeWebXmlMojo.java

  32 
vote

private ClassLoader getAnnotationSearchClassLoader() throws ClasspathBuilderException, MalformedURLException {
  Collection<File> classPathFiles=classpathBuilder.buildClasspathList(getProject(),Artifact.SCOPE_COMPILE,Collections.<Artifact>emptySet());
  List<URL> urls=new ArrayList<URL>(classPathFiles.size());
  for (  File file : classPathFiles) {
    urls.add(file.toURL());
  }
  URLClassLoader url=new URLClassLoader(urls.toArray(new URL[urls.size()]));
  return url;
}
 

Example 16

From project ig-undx, under directory /src/main/java/org/illegalaccess/undx/.

Source file: DalvikToJVM.java

  32 
vote

private static URLClassLoader getTestClassLoader(File f) throws MalformedURLException {
  URL url1=new URL("file://" + f.getAbsolutePath());
  URL url3=new URL("file://tmp/");
  URL url4=new URL("file://" + new File(".").getAbsolutePath());
  URL url5=new URL("file://" + askloc + "/android.jar");
  URLClassLoader ucl=new URLClassLoader(new URL[]{url4,url1,url3,url5});
  return ucl;
}
 

Example 17

From project javadrop, under directory /src/main/java/org/javadrop/.

Source file: JavadropMojo.java

  32 
vote

public void addURLToSystemClassLoader(URL url) throws IntrospectionException {
  URLClassLoader systemClassLoader=(URLClassLoader)ClassLoader.getSystemClassLoader();
  Class classLoaderClass=URLClassLoader.class;
  try {
    Method method=classLoaderClass.getDeclaredMethod("addURL",new Class[]{URL.class});
    method.setAccessible(true);
    method.invoke(systemClassLoader,new Object[]{url});
  }
 catch (  Throwable t) {
    t.printStackTrace();
    throw new IntrospectionException("Error when adding url to system ClassLoader ");
  }
}
 

Example 18

From project jboss-vfs, under directory /src/test/java/org/jboss/test/vfs/.

Source file: FileVFSUnitTestCase.java

  32 
vote

/** 
 * Validate that a URLClassLoader.findReource/getResourceAsStream calls for non-existing absolute resources that should fail as expected with null results. Related to JBMICROCONT-139.
 * @throws Exception
 */
public void testURLClassLoaderFindResourceFailure() throws Exception {
  VirtualFile testdir=getVirtualFile("/vfs/test");
  URL[] cp={testdir.toURL()};
  URLClassLoader ucl=new URLClassLoader(cp);
  URL qp=ucl.findResource("nosuch-quartz.props");
  assertNull("findResource(nosuch-quartz.props)",qp);
  InputStream is=ucl.getResourceAsStream("nosuch-quartz.props");
  assertNull("getResourceAsStream(nosuch-quartz.props)",is);
}
 

Example 19

From project jDcHub, under directory /jdchub-modules/WebManagementConsole/src/main/test/jdchub/module/.

Source file: ModuleMainTest.java

  32 
vote

@BeforeClass public void setUp() throws Exception {
  URLClassLoader classLoader=(URLClassLoader)ClassLoader.getSystemClassLoader();
  Class clazz=URLClassLoader.class;
  Method method=clazz.getDeclaredMethod("addURL",new Class[]{URL.class});
  method.setAccessible(true);
  method.invoke(classLoader,new Object[]{new File(ConfigurationManager.getInstance().getHubConfigDir()).toURI().toURL()});
  moduleMain=new ModuleMain();
}
 

Example 20

From project kabeja, under directory /core/src/main/java/org/kabeja/.

Source file: Loader.java

  32 
vote

public void launch(String[] args){
  args=parseMainClass(args);
  URLClassLoader cl=new URLClassLoader(getClasspath());
  try {
    Class clazz=cl.loadClass(this.mainClass);
    Object obj=clazz.newInstance();
    Method method=clazz.getDeclaredMethod("main",new Class[]{args.getClass()});
    method.invoke(obj,new Object[]{args});
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 21

From project liferay-maven-support, under directory /plugins/liferay-maven-plugin/src/main/java/com/liferay/maven/plugins/.

Source file: ServiceBuilderMojo.java

  32 
vote

protected void initPortalClassLoader() throws Exception {
  super.initPortalClassLoader();
  Class<?> clazz=getClass();
  URLClassLoader urlClassLoader=(URLClassLoader)clazz.getClassLoader();
  Method method=URLClassLoader.class.getDeclaredMethod("addURL",URL.class);
  method.setAccessible(true);
  File file=new File(implResourcesDir);
  URI uri=file.toURI();
  method.invoke(urlClassLoader,uri.toURL());
}
 

Example 22

From project m2e-core-tests, under directory /org.eclipse.m2e.tests/projects/MNGECLIPSE-369/cptest/src/main/java/com/cmaxinc/test/.

Source file: TestApp.java

  32 
vote

public static void main(String[] args){
  URLClassLoader cl=(URLClassLoader)new TestApp().getClass().getClassLoader();
  URL[] urls=cl.getURLs();
  for (  URL url : urls) {
    if (url.toExternalForm().indexOf("testlib") != -1)     System.out.println(url.toExternalForm());
  }
  System.out.println("");
  new VersionPrinter();
}
 

Example 23

From project maven-shared, under directory /maven-runtime/src/test/java/org/apache/maven/shared/runtime/.

Source file: DefaultMavenRuntimeTest.java

  32 
vote

public void testGetProjectPropertiesWithDefaultPackageClass() throws ClassNotFoundException, MavenRuntimeException, IOException {
  File jar=getPackage("testSingleJar/pom.xml");
  URLClassLoader classLoader=newClassLoader(jar);
  Class<?> klass=classLoader.loadClass("DefaultPackageClass");
  MavenProjectProperties properties=mavenRuntime.getProjectProperties(klass);
  assertMavenProjectProperties("org.apache.maven.shared.runtime.tests:testSingleJar:1.0",properties);
}
 

Example 24

From project apb, under directory /modules/apb-base/src/apb/testrunner/.

Source file: Main.java

  31 
vote

private static ClassLoader createClassLoader(TestRunnerOptions options) throws TestSetFailedException {
  try {
    final List<String> path=options.getClassPath();
    final List<File> files=new ArrayList<File>(path.size());
    for (    String s : path) {
      files.add(new File(s));
    }
    return new URLClassLoader(FileUtils.toURLArray(files));
  }
 catch (  MalformedURLException e) {
    throw new TestSetFailedException(e);
  }
}
 

Example 25

From project arquillian-container-gae, under directory /gae-cli/src/main/java/org/jboss/arquillian/container/appengine/cli/.

Source file: AppEngineCLIContainer.java

  31 
vote

protected void invokeAppEngine(ThreadGroup threads,String sdkDir,String appEngineClass,final Object args) throws Exception {
  File lib=new File(sdkDir,"lib");
  File tools=new File(lib,"appengine-tools-api.jar");
  if (tools.exists() == false)   throw new IllegalArgumentException("No AppEngine tools jar: " + tools);
  URL url=tools.toURI().toURL();
  URL[] urls=new URL[]{url};
  ClassLoader cl=new URLClassLoader(urls);
  Class<?> kickStartClass=cl.loadClass(appEngineClass);
  final Method main=kickStartClass.getMethod("main",String[].class);
  Runnable runnable=createRunnable(threads,main,args);
  appEngineThread=new Thread(threads,runnable,"AppEngine thread: " + getClass().getSimpleName());
  appEngineThread.start();
}
 

Example 26

From project arquillian-maven, under directory /plugin/src/main/java/org/jboss/arquillian/maven/.

Source file: BaseCommand.java

  31 
vote

protected ClassLoader getClassLoader() throws Exception {
  ClassLoader classLoader=getFromContext(ClassLoader.class);
  if (classLoader != null)   return classLoader;
synchronized (BaseCommand.class) {
    List<URL> urls=new ArrayList<URL>();
    List<String> classPathElements;
switch (classLoadingStrategy) {
case COMPILE:
      classPathElements=project.getCompileClasspathElements();
    break;
case TEST:
  classPathElements=project.getTestClasspathElements();
break;
case PLUGIN:
classPathElements=new ArrayList<String>();
break;
default :
classPathElements=new ArrayList<String>();
break;
}
for (String object : classPathElements) {
String path=(String)object;
urls.add(new File(path).toURI().toURL());
}
URLClassLoader urlClassLoader=new URLClassLoader(urls.toArray(new URL[]{}),BaseCommand.class.getClassLoader());
putInContext(ClassLoader.class,urlClassLoader);
return urlClassLoader;
}
}
 

Example 27

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/plugin/.

Source file: PluginManager.java

  31 
vote

/** 
 * Loads a plugin by the specified plugin directory and put it into the  specified holder.
 * @param pluginDir the specified plugin directory
 * @param holder the specified holder
 * @return loaded plugin
 * @throws Exception exception
 */
private AbstractPlugin load(final File pluginDir,final HashMap<String,HashSet<AbstractPlugin>> holder) throws Exception {
  final Properties props=new Properties();
  props.load(new FileInputStream(pluginDir.getPath() + File.separator + "plugin.properties"));
  final File defaultClassesFileDir=new File(pluginDir.getPath() + File.separator + "classes");
  final URL defaultClassesFileDirURL=defaultClassesFileDir.toURI().toURL();
  final String webRoot=StringUtils.substringBeforeLast(AbstractServletListener.getWebRoot(),File.separator);
  final String classesFileDirPath=webRoot + props.getProperty("classesDirPath");
  final File classesFileDir=new File(classesFileDirPath);
  final URL classesFileDirURL=classesFileDir.toURI().toURL();
  final URLClassLoader classLoader=new URLClassLoader(new URL[]{defaultClassesFileDirURL,classesFileDirURL},PluginManager.class.getClassLoader());
  classLoaders.add(classLoader);
  final String pluginClassName=props.getProperty(Plugin.PLUGIN_CLASS);
  LOGGER.log(Level.FINEST,"Loading plugin class[name={0}]",pluginClassName);
  final Class<?> pluginClass=classLoader.loadClass(pluginClassName);
  final AbstractPlugin ret=(AbstractPlugin)pluginClass.newInstance();
  setPluginProps(pluginDir,ret,props);
  registerEventListeners(props,classLoader,ret);
  register(ret,holder);
  return ret;
}
 

Example 28

From project big-data-plugin, under directory /src/org/pentaho/di/job/entries/hadoopjobexecutor/.

Source file: JarUtility.java

  31 
vote

/** 
 * Get the Main-Class declaration from a Jar's manifest.
 * @param jarUrl URL to the Jar file
 * @param parentClassLoader Class loader to delegate to when loading classes outside the jar.
 * @return Class defined by Main-Class manifest attribute, {@code null} if not defined.
 * @throws IOException Error opening jar file
 * @throws ClassNotFoundException Error locating the main class as defined in the manifest
 */
public Class<?> getMainClassFromManifest(URL jarUrl,ClassLoader parentClassLoader) throws IOException, ClassNotFoundException {
  if (jarUrl == null || parentClassLoader == null) {
    throw new NullPointerException();
  }
  JarFile jarFile;
  try {
    jarFile=new JarFile(new File(jarUrl.toURI()));
  }
 catch (  URISyntaxException ex) {
    throw new IOException("Error locating jar: " + jarUrl);
  }
catch (  IOException ex) {
    throw new IOException("Error opening job jar: " + jarUrl,ex);
  }
  try {
    Manifest manifest=jarFile.getManifest();
    String className=manifest == null ? null : manifest.getMainAttributes().getValue("Main-Class");
    if (className != null) {
      URLClassLoader cl=new URLClassLoader(new URL[]{jarUrl},parentClassLoader);
      return cl.loadClass(className);
    }
 else {
      return null;
    }
  }
  finally {
    jarFile.close();
  }
}
 

Example 29

From project c10n, under directory /tools/src/main/java/c10n/tools/search/.

Source file: DefaultC10NInterfaceSearch.java

  31 
vote

@Override public Set<Class<?>> find(String packagePrefix,Class<? extends Annotation> annotationClass){
  final Predicate<String> filter=new FilterBuilder.Include(FilterBuilder.prefix(packagePrefix));
  Reflections reflections=new Reflections(new ConfigurationBuilder().setUrls(cp).filterInputsBy(filter).setScanners(new TypeAnnotationsScanner().filterResultsBy(filter),new SubTypesScanner().filterResultsBy(filter)));
  Set<String> types=reflections.getStore().getTypesAnnotatedWith(annotationClass.getName());
  URL[] urls=cp.toArray(new URL[cp.size()]);
  return ImmutableSet.copyOf(Reflections.forNames(types,new URLClassLoader(urls)));
}
 

Example 30

From project capedwarf-green, under directory /common/src/test/java/org/jboss/test/capedwarf/common/serialization/test/.

Source file: RemotingTestCase.java

  31 
vote

@Test public void testFakeRemoting() throws Exception {
  File file=new File("/Users/alesj/java_lib/android-sdk-mac_86/platforms/android-1.5/android.jar");
  if (file.exists() == false)   return;
  ClassLoader cl=new URLClassLoader(new URL[]{file.toURI().toURL()});
  Class<?> jsonClass=cl.loadClass(JSONObject.class.getName());
  Object jsonInstance=jsonClass.newInstance();
  Method put=jsonClass.getMethod("put",String.class,Object.class);
  put.invoke(jsonInstance,"key","Dummy. ;-)");
  String toString=jsonInstance.toString();
  JSONObject jo=new JSONObject(new JSONTokener(new StringReader(toString)));
  System.out.println("jo.getString(\"key\") = " + jo.getString("key"));
}
 

Example 31

From project cargo-maven2-plugin-db, under directory /src/main/java/org/codehaus/cargo/maven2/configuration/.

Source file: Container.java

  31 
vote

private void setupEmbeddedExtraClasspath(EmbeddedLocalContainer container,CargoProject project) throws MojoExecutionException {
  if (getDependencies() != null) {
    URL[] dependencyURLs=new URL[getDependencies().length];
    for (int i=0; i < getDependencies().length; i++) {
      File pathFile=new File(getDependencies()[i].getDependencyPath(project));
      try {
        dependencyURLs[i]=pathFile.toURL();
      }
 catch (      MalformedURLException e) {
        throw new MojoExecutionException("Invalid classpath location [" + pathFile.getPath() + "]");
      }
    }
    URLClassLoader urlClassloader=new URLClassLoader(dependencyURLs,project.getEmbeddedClassLoader());
    project.setEmbeddedClassLoader(urlClassloader);
  }
}
 

Example 32

From project ceylon-runtime, under directory /api/src/main/java/ceylon/modules/api/runtime/.

Source file: AbstractRuntime.java

  31 
vote

protected Module readModule(String name,File moduleFile) throws Exception {
  final URL url=moduleFile.toURI().toURL();
  final ClassLoader parent=getClass().getClassLoader();
  final ClassLoader cl=new URLClassLoader(new URL[]{url},parent);
  return loadModule(cl,name);
}
 

Example 33

From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/.

Source file: Module.java

  31 
vote

public Module(String fileName){
  mDoc=new Doc(this);
  mDoc.setFileName(fileName);
  mDoc.addChapter(mHeader=createHeader());
  try {
    File homeDir=new File(System.getProperty("user.home"));
    File pluginDir=new File(homeDir,".chkbugreport-plugins");
    if (pluginDir.exists() && pluginDir.isDirectory()) {
      String files[]=pluginDir.list();
      for (      String fn : files) {
        if (fn.startsWith(".") || !fn.endsWith(".jar")) {
          continue;
        }
        File jar=new File(pluginDir,fn);
        JarInputStream jis=new JarInputStream(new FileInputStream(jar));
        Manifest mf=jis.getManifest();
        if (mf != null) {
          String pluginClassName=mf.getMainAttributes().getValue("ChkBugReport-Plugin");
          URL urls[]={jar.toURI().toURL()};
          URLClassLoader cl=new URLClassLoader(urls,getClass().getClassLoader());
          Class<?> extClass=Class.forName(pluginClassName,true,cl);
          ExternalPlugin ext=(ExternalPlugin)extClass.newInstance();
          System.out.println("Loading plugins from: " + jar.getAbsolutePath());
          ext.initExternalPlugin(this);
        }
      }
    }
  }
 catch (  Exception e) {
    System.err.println("Error loading external plugins");
    e.printStackTrace();
  }
}
 

Example 34

From project clirr-maven-plugin, under directory /src/main/java/org/codehaus/mojo/clirr/.

Source file: AbstractClirrMojo.java

  31 
vote

/** 
 * Create a ClassLoader, which includes the artifacts in <code>artifacts</code>, but excludes the artifacts in <code>previousArtifacts</code>. The intention is, that we let BCEL inspect the artifacts in the latter set, using a {@link ClassLoader}, which contains the dependencies. However, the {@link ClassLoader} must not contain the jar files, which are being inspected.
 * @param artifacts The artifacts, from which to build a {@link ClassLoader}.
 * @param previousArtifacts The artifacts being inspected, or null, if tereturned  {@link ClassLoader} should contain all the elements of<code>artifacts</code>.
 * @return A {@link ClassLoader} which may be used to inspect the classes inpreviousArtifacts.
 * @throws MalformedURLException Failed to convert a file to an URL.
 */
protected static ClassLoader createClassLoader(Collection<Artifact> artifacts,Set<Artifact> previousArtifacts) throws MalformedURLException {
  URLClassLoader cl=null;
  if (!artifacts.isEmpty()) {
    List<URL> urls=new ArrayList<URL>(artifacts.size());
    for (Iterator<Artifact> i=artifacts.iterator(); i.hasNext(); ) {
      Artifact artifact=i.next();
      if (previousArtifacts == null || !previousArtifacts.contains(artifact)) {
        urls.add(artifact.getFile().toURI().toURL());
      }
    }
    if (!urls.isEmpty()) {
      cl=new URLClassLoader(urls.toArray(new URL[urls.size()]));
    }
  }
  return cl;
}
 

Example 35

From project clustermeister, under directory /integration-tests/src/main/java/com/github/nethad/clustermeister/integration/sc07/.

Source file: JPPFClassloader.java

  31 
vote

private void debugOutput(){
  System.out.println("java system property class path:");
  System.out.println(System.getProperty("java.class.path"));
  URL[] urLs=classLoader.getURLs();
  DelegationModel delegationModel=AbstractJPPFClassLoader.getDelegationModel();
  ClassLoader scl=ClassLoader.getSystemClassLoader();
  URLClassLoader uscl=((URLClassLoader)scl);
  URL[] urLs2=uscl.getURLs();
  System.out.println("class loader url lenght = " + urLs.length);
  System.out.println("class loader urls:");
  for (  URL url : urLs) {
    System.out.println(url.getFile());
  }
  System.out.println("Delegation model: " + delegationModel);
  System.out.println("system class loader urls:");
  for (  URL url : urLs2) {
    System.out.println(url.getFile());
  }
}
 

Example 36

From project commons-logging, under directory /src/test/org/apache/commons/logging/pathable/.

Source file: GeneralTestCase.java

  31 
vote

/** 
 * Verify that the context classloader is a custom one, then reset it to a non-custom one.
 */
private static void checkAndSetContext(){
  ClassLoader contextLoader=Thread.currentThread().getContextClassLoader();
  assertEquals("ContextLoader is of unexpected type",contextLoader.getClass().getName(),PathableClassLoader.class.getName());
  URL[] noUrls=new URL[0];
  Thread.currentThread().setContextClassLoader(new URLClassLoader(noUrls));
}
 

Example 37

From project core_4, under directory /legacy-tests/src/test/java/org/ajax4jsf/application/.

Source file: ComponentLoaderTest.java

  31 
vote

protected void setUp() throws Exception {
  super.setUp();
  contextClassLoader=Thread.currentThread().getContextClassLoader();
  classLoader=new URLClassLoader(new URL[0],this.getClass().getClassLoader());
  Thread.currentThread().setContextClassLoader(classLoader);
  loader=new ComponentsLoaderImpl();
}
 

Example 38

From project crash, under directory /shell/core/src/main/java/org/crsh/standalone/.

Source file: Bootstrap.java

  31 
vote

public void bootstrap() throws Exception {
  URL[] urls=new URL[jars.size()];
  for (int i=0; i < urls.length; i++) {
    urls[i]=jars.get(i).toURI().toURL();
  }
  URLClassLoader classLoader=new URLClassLoader(urls,baseLoader);
  FS cmdFS=new FS();
  for (  File cmd : cmds) {
    cmdFS.mount(cmd);
  }
  cmdFS.mount(classLoader,Path.get("/crash/commands/"));
  FS confFS=new FS();
  for (  File conf : confs) {
    confFS.mount(conf);
  }
  confFS.mount(classLoader,Path.get("/crash/"));
  ServiceLoaderDiscovery discovery=new ServiceLoaderDiscovery(classLoader);
  StringBuilder info=new StringBuilder("Booting crash with classpath=");
  info.append(jars).append(" and mounts=[");
  for (int i=0; i < cmds.size(); i++) {
    if (i > 0) {
      info.append(',');
    }
    info.append(cmds.get(i).getAbsolutePath());
  }
  info.append(']');
  log.info(info.toString());
  PluginContext context=new PluginContext(discovery,attributes,cmdFS,confFS,classLoader);
  context.refresh();
  start(context);
}
 

Example 39

From project discovery, under directory /src/main/java/com/tacitknowledge/util/discovery/.

Source file: ClasspathUtils.java

  31 
vote

/** 
 * Returns the classpath as a list directory and archive names.
 * @return the classpath as a list of directory and archive file names; ifno components can be found then an empty list will be returned
 */
public static List getClasspathComponents(){
  List components=new LinkedList();
  ClassLoader cl=Thread.currentThread().getContextClassLoader();
  while ((null != cl) && (cl instanceof URLClassLoader)) {
    URLClassLoader ucl=(URLClassLoader)cl;
    components.addAll(getUrlClassLoaderClasspathComponents(ucl));
    try {
      cl=ucl.getParent();
    }
 catch (    SecurityException se) {
      cl=null;
    }
  }
  String classpath=System.getProperty("java.class.path");
  String separator=System.getProperty("path.separator");
  StringTokenizer st=new StringTokenizer(classpath,separator);
  while (st.hasMoreTokens()) {
    String component=st.nextToken();
    component=getCanonicalPath(component);
    components.add(component);
  }
  return new LinkedList(new HashSet(components));
}
 

Example 40

From project dolphin, under directory /texcel/analyse-sq/src/com/tan/loader/.

Source file: CompileLoader.java

  31 
vote

public static Class<?> compile(final String javaName,final String encoding){
  if (isEmpty(javaName))   return null;
  File classpath=new File(CURRENT_PATH + File.separatorChar);
  File javaFile=new File(classpath,javaName + ".java");
  if (classpath == null || !classpath.exists() || classpath.isFile()) {
    TanUtil.warnln("Class Path File's Path Wrong");
    return null;
  }
  if (javaFile == null || !javaFile.exists() || javaFile.isDirectory()) {
    TanUtil.warnln("Java File's Path Wrong");
    return null;
  }
  URL url=null;
  try {
    url=classpath.toURI().toURL();
    com.sun.tools.javac.Main.compileAbsolutePath(javaFile.getAbsolutePath(),encoding);
  }
 catch (  MalformedURLException e1) {
    e1.printStackTrace();
  }
  TanUtil.println("Loading... " + url);
  URLClassLoader loader=null;
  loader=new URLClassLoader(new URL[]{url});
  Class<?> c=null;
  try {
    c=loader.loadClass(javaName);
  }
 catch (  ClassNotFoundException e) {
    e.printStackTrace();
  }
  return c;
}
 

Example 41

From project edumips64, under directory /ui/.

Source file: GUIHelp.java

  31 
vote

/** 
 * Shows the Edumips64 help window. If the help system was not initialized properly, shows an error dialog instead.
 * @param parent the parent that owns this help dialog
 * @param helpId the help ID to display (an invalid ID will result in the top level help topic being displayed)
 */
public static void showHelp(Window parent,String helpId){
  HSurl=Main.class.getResource(CurrentLocale.getString("HELPDIR") + "/");
  String s=HSurl.getProtocol() + ":" + HSurl.getPath().replace("%20"," ");
  String s1=CurrentLocale.getString("HELPSET");
  try {
    URL aurl[]=GUIHelp.parseURLs(s);
    URLClassLoader urlclassloader=new URLClassLoader(aurl);
    url=HelpSet.findHelpSet(urlclassloader,s1);
    HelpSet helpset=new HelpSet(urlclassloader,url);
    helpBroker=helpset.createHelpBroker();
    helpBroker.initPresentation();
    helpBroker.setSize(new Dimension(800,600));
    ((DefaultHelpBroker)helpBroker).setActivationWindow(parent);
    helpBroker.initPresentation();
    helpBroker.setSize(helpBroker.getSize());
    helpBroker.setDisplayed(true);
  }
 catch (  HelpSetException helpsetexception) {
    System.err.println("Could not create HelpSet for " + url);
    System.err.println(helpsetexception);
  }
catch (  BadIDException bie) {
    helpBroker.setCurrentID(HELP_DEFAULT);
  }
}
 

Example 42

From project flapjack, under directory /flapjack-annotation/src/test/java/flapjack/annotation/.

Source file: RecordPackageClassScannerTest.java

  31 
vote

public void test_scan_ScanJar(){
  ClassLoader loader=Thread.currentThread().getContextClassLoader();
  URL url=loader.getResource("flapjack-annotation-test-helper.jar");
  Thread.currentThread().setContextClassLoader(new URLClassLoader(new URL[]{url},loader));
  RecordPackageClassScanner scanner=new RecordPackageClassScanner();
  List<Class<?>> classes=scanner.scan(Arrays.<String>asList("flapjack.annotation.test"));
  assertNotNull(classes);
  assertEquals(1,classes.size());
  assertEquals("flapjack.annotation.test.Dog",classes.get(0).getName());
}
 

Example 43

From project flexmojos, under directory /flexmojos-generator/flexmojos-generator-mojo/src/main/java/net/flexmojos/oss/generator/.

Source file: SimpleGeneratorMojo.java

  31 
vote

private ClassLoader initializeClassLoader() throws MojoExecutionException {
  List<String> classpaths=getClasspath();
  try {
    List<URL> classpathsUrls=new ArrayList<URL>();
    for (    String path : classpaths) {
      URL url=new File(path).toURI().toURL();
      classpathsUrls.add(url);
    }
    return new URLClassLoader(classpathsUrls.toArray(new URL[0]),currentThread().getContextClassLoader());
  }
 catch (  MalformedURLException e) {
    throw new MojoExecutionException("Unable to get dependency URL",e);
  }
}
 

Example 44

From project freemind, under directory /freemind/freemind/main/.

Source file: FreeMindCommon.java

  31 
vote

public ClassLoader getFreeMindClassLoader(){
  ClassLoader classLoader=this.getClass().getClassLoader();
  try {
    return new URLClassLoader(new URL[]{Tools.fileToUrl(new File(getFreemindBaseDir()))},classLoader);
  }
 catch (  MalformedURLException e) {
    freemind.main.Resources.getInstance().logException(e);
    return classLoader;
  }
}
 

Example 45

From project gatein-common, under directory /common/src/main/java/org/gatein/common/util/.

Source file: Tools.java

  31 
vote

public static String buildClassLoaderInfo(ClassLoader loader){
  if (loader == null) {
    throw new IllegalArgumentException("no loader");
  }
  StringBuffer buffer=new StringBuffer();
  buffer.append("ClassLoader[Name=").append(loader.getClass().getName());
  buffer.append(",HashCode=").append(loader.hashCode());
  buffer.append(",IdentityHashCode=").append(System.identityHashCode(loader));
  if (loader instanceof URLClassLoader) {
    URLClassLoader urlLoader=(URLClassLoader)loader;
    URL[] urls=urlLoader.getURLs();
    for (int i=0; i < urls.length; i++) {
      URL url=urls[i];
      buffer.append(",URL(").append(i).append(")=").append(url);
    }
  }
  try {
    Class uclClass=Thread.currentThread().getContextClassLoader().loadClass("org.jboss.mx.loading.UnifiedClassLoader");
    Class loaderClass=loader.getClass();
    if (uclClass.isAssignableFrom(loaderClass)) {
      URL url=(URL)loaderClass.getMethod("getURL",new Class[0]).invoke(loader,new Object[0]);
      buffer.append(",GetURL=").append(url);
    }
  }
 catch (  Exception e) {
    log.error("Cannot get UCL infos",e);
  }
  buffer.append("]");
  return buffer.toString();
}
 

Example 46

From project gitblit, under directory /src/com/gitblit/.

Source file: Launcher.java

  31 
vote

/** 
 * Adds a file to the classpath
 * @param f the file to be added
 * @throws IOException
 */
public static void addJarFile(File f) throws IOException {
  if (f.getName().indexOf("-sources") > -1 || f.getName().indexOf("-javadoc") > -1) {
    return;
  }
  URL u=f.toURI().toURL();
  if (DEBUG) {
    System.out.println("load=" + u.toExternalForm());
  }
  URLClassLoader sysloader=(URLClassLoader)ClassLoader.getSystemClassLoader();
  Class<?> sysclass=URLClassLoader.class;
  try {
    Method method=sysclass.getDeclaredMethod("addURL",PARAMETERS);
    method.setAccessible(true);
    method.invoke(sysloader,new Object[]{u});
  }
 catch (  Throwable t) {
    throw new IOException(MessageFormat.format("Error, could not add {0} to system classloader",f.getPath()),t);
  }
}
 

Example 47

From project GraphLab, under directory /src/graphlab/plugins/.

Source file: GraphLabDebugger.java

  31 
vote

protected URLClassLoader getExtensionsClassLoader(){
  try {
    return new URLClassLoader(new URL[]{new File("extensions").toURL()});
  }
 catch (  MalformedURLException e) {
    ExceptionHandler.catchException(e);
  }
  return null;
}
 

Example 48

From project hama, under directory /core/src/main/java/org/apache/hama/monitor/.

Source file: Configurator.java

  31 
vote

/** 
 * Load jar from specified path.
 * @param path to the jar file.
 * @param loader of the current thread.  
 * @return task to be run.
 */
private static Task load(File path,ClassLoader loader) throws IOException {
  JarFile jar=new JarFile(path);
  Manifest manifest=jar.getManifest();
  String pkg=manifest.getMainAttributes().getValue("Package");
  String main=manifest.getMainAttributes().getValue("Main-Class");
  if (null == pkg || null == main)   throw new NullPointerException("Package or main class not found " + "in menifest file.");
  String namespace=pkg + File.separator + main;
  namespace=namespace.replaceAll(File.separator,".");
  LOG.debug("Task class to be loaded: " + namespace);
  URLClassLoader child=new URLClassLoader(new URL[]{path.toURI().toURL()},loader);
  Thread.currentThread().setContextClassLoader(child);
  Class<?> taskClass=null;
  try {
    taskClass=Class.forName(namespace,true,child);
  }
 catch (  ClassNotFoundException cnfe) {
    LOG.warn("Task class is not found.",cnfe);
  }
  if (null == taskClass)   return null;
  try {
    return (Task)taskClass.newInstance();
  }
 catch (  InstantiationException ie) {
    LOG.warn("Unable to instantiate task class." + namespace,ie);
  }
catch (  IllegalAccessException iae) {
    LOG.warn(iae);
  }
  return null;
}
 

Example 49

From project hawtjni, under directory /hawtjni-generator/src/main/java/org/fusesource/hawtjni/generator/.

Source file: HawtJNI.java

  31 
vote

private void findClasses(ArrayList<JNIClass> jni,ArrayList<JNIClass> structs) throws UsageException {
  ArrayList<URL> urls=new ArrayList<URL>();
  for (  String classpath : classpaths) {
    String[] fileNames=classpath.replace(';',':').split(":");
    for (    String fileName : fileNames) {
      try {
        File file=new File(fileName);
        if (file.isDirectory()) {
          urls.add(new URL(url(file) + "/"));
        }
 else {
          urls.add(new URL(url(file)));
        }
      }
 catch (      Exception e) {
        throw new UsageException("Invalid class path.  Not a valid file: " + fileName);
      }
    }
  }
  LinkedHashSet<Class<?>> jniClasses=new LinkedHashSet<Class<?>>();
  try {
    URLClassLoader classLoader=new URLClassLoader(array(URL.class,urls),JniClass.class.getClassLoader());
    UrlSet urlSet=new UrlSet(classLoader);
    urlSet=urlSet.excludeJavaHome();
    ClassFinder finder=new ClassFinder(classLoader,urlSet.getUrls());
    collectMatchingClasses(finder,JniClass.class,jniClasses);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
  for (  Class<?> clazz : jniClasses) {
    ReflectClass rc=new ReflectClass(clazz);
    if (rc.getFlag(ClassFlag.STRUCT)) {
      structs.add(rc);
    }
    if (!rc.getNativeMethods().isEmpty()) {
      jni.add(rc);
    }
  }
}
 

Example 50

From project hecl, under directory /load/org/hecl/load/.

Source file: LoadCmd.java

  31 
vote

/** 
 * The <code>cmdCode</code> method implements the 'load' command.
 * @param interp an <code>Interp</code> value
 * @param argv a <code>Thing[]</code> value
 * @exception HeclException if an error occurs
 */
public Thing cmdCode(Interp interp,Thing[] argv) throws HeclException {
  try {
    Vector urlv=ListThing.get(argv[2]);
    int sz=urlv.size();
    URL[] urls=new URL[sz];
    for (int i=0; i < sz; i++) {
      URI uri=new URI(((Thing)urlv.elementAt(i)).toString());
      if (!uri.isAbsolute()) {
      }
      urls[i]=uri.toURL();
    }
    URLClassLoader ucl=new URLClassLoader(urls);
    Class c=ucl.loadClass(argv[1].toString());
    HeclModule module=(HeclModule)c.newInstance();
    module.loadModule(interp);
  }
 catch (  Exception e) {
    throw new HeclException(e.toString());
  }
  return null;
}
 

Example 51

From project hibernate-tools, under directory /src/test/org/hibernate/tool/test/jdbc2cfg/.

Source file: OneToOneTest.java

  31 
vote

public void testGenerateMappingAndReadable() throws MalformedURLException {
  cfg.buildMappings();
  HibernateMappingExporter hme=new HibernateMappingExporter(cfg,getOutputDir());
  hme.start();
  assertFileAndExists(new File(getOutputDir(),"Person.hbm.xml"));
  assertFileAndExists(new File(getOutputDir(),"AddressPerson.hbm.xml"));
  assertFileAndExists(new File(getOutputDir(),"AddressMultiPerson.hbm.xml"));
  assertFileAndExists(new File(getOutputDir(),"MultiPerson.hbm.xml"));
  assertFileAndExists(new File(getOutputDir(),"Middle.hbm.xml"));
  assertFileAndExists(new File(getOutputDir(),"Left.hbm.xml"));
  assertFileAndExists(new File(getOutputDir(),"Right.hbm.xml"));
  assertEquals(7,getOutputDir().listFiles().length);
  POJOExporter exporter=new POJOExporter(cfg,getOutputDir());
  exporter.setTemplatePath(new String[0]);
  exporter.getProperties().setProperty("ejb3","false");
  exporter.getProperties().setProperty("jdk5","false");
  exporter.start();
  ArrayList list=new ArrayList();
  List jars=new ArrayList();
  TestHelper.compile(getOutputDir(),getOutputDir(),TestHelper.visitAllFiles(getOutputDir(),list),"1.5",TestHelper.buildClasspath(jars));
  URL[] urls=new URL[]{getOutputDir().toURL()};
  ClassLoader oldLoader=Thread.currentThread().getContextClassLoader();
  URLClassLoader ucl=new URLClassLoader(urls,oldLoader);
  try {
    Thread.currentThread().setContextClassLoader(ucl);
    Configuration configuration=new Configuration().addFile(new File(getOutputDir(),"Person.hbm.xml")).addFile(new File(getOutputDir(),"AddressPerson.hbm.xml")).addFile(new File(getOutputDir(),"AddressMultiPerson.hbm.xml")).addFile(new File(getOutputDir(),"MultiPerson.hbm.xml")).addFile(new File(getOutputDir(),"Middle.hbm.xml")).addFile(new File(getOutputDir(),"Left.hbm.xml")).addFile(new File(getOutputDir(),"Right.hbm.xml"));
    configuration.buildMappings();
    ServiceRegistryBuilder builder=new ServiceRegistryBuilder();
    builder.applySettings(configuration.getProperties());
    new SchemaValidator(builder.buildServiceRegistry(),configuration).validate();
  }
  finally {
    Thread.currentThread().setContextClassLoader(oldLoader);
  }
}
 

Example 52

From project i18n, under directory /src/main/java/com/ovea/i18n/.

Source file: I18NBundleSkeleton.java

  31 
vote

protected I18NBundleSkeleton(String bundleName,ClassLoader classLoader,Locale locale,I18NServiceSkeleton.MissingKeyBehaviour missingKeyBehaviour){
  this.bundleName=bundleName;
  this.locale=locale;
  this.loader=new URLClassLoader(new URL[0],classLoader);
  this.missingKeyBehaviour=missingKeyBehaviour;
}
 

Example 53

From project ivyde, under directory /org.apache.ivyde.eclipse/src/java/org/apache/ivyde/common/ivysettings/.

Source file: IvySettingsModel.java

  31 
vote

private ClassLoader getClassLoader(IvySettingsFile sfile){
  if (sfile.getClasspathUrls().length > 0) {
    return new URLClassLoader(sfile.getClasspathUrls(),Ivy.class.getClassLoader());
  }
 else {
    return Ivy.class.getClassLoader();
  }
}
 

Example 54

From project javassist, under directory /src/test/test/javassist/convert/.

Source file: ArrayAccessReplaceTest.java

  31 
vote

public void setUp() throws Exception {
  ClassPool pool=new ClassPool(true);
  CtClass echoClass=pool.get(ArrayAccessReplaceTest.class.getName() + "$Echo");
  CtClass simpleClass=pool.get(ArrayAccessReplaceTest.class.getName() + "$Simple");
  CodeConverter converter=new CodeConverter();
  converter.replaceArrayAccess(echoClass,new CodeConverter.DefaultArrayAccessReplacementMethodNames());
  simpleClass.instrument(converter);
  simple=(SimpleInterface)simpleClass.toClass(new URLClassLoader(new URL[0],getClass().getClassLoader()),Class.class.getProtectionDomain()).newInstance();
}
 

Example 55

From project jetty-project, under directory /jetty-maven-plugin/src/main/java/org/mortbay/jetty/plugin/.

Source file: AbstractJettyMojo.java

  31 
vote

public void configurePluginClasspath() throws MojoExecutionException {
  if (useProvidedScope) {
    try {
      List<URL> provided=new ArrayList<URL>();
      URL[] urls=null;
      for (Iterator<Artifact> iter=projectArtifacts.iterator(); iter.hasNext(); ) {
        Artifact artifact=iter.next();
        if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !isPluginArtifact(artifact)) {
          provided.add(artifact.getFile().toURI().toURL());
          if (getLog().isDebugEnabled()) {
            getLog().debug("Adding provided artifact: " + artifact);
          }
        }
      }
      if (!provided.isEmpty()) {
        urls=new URL[provided.size()];
        provided.toArray(urls);
        URLClassLoader loader=new URLClassLoader(urls,getClass().getClassLoader());
        Thread.currentThread().setContextClassLoader(loader);
        getLog().info("Plugin classpath augmented with <scope>provided</scope> dependencies: " + Arrays.toString(urls));
      }
    }
 catch (    MalformedURLException e) {
      throw new MojoExecutionException("Invalid url",e);
    }
  }
}
 

Example 56

From project jspwiki, under directory /tests/org/apache/wiki/.

Source file: TestJDBCDataSource.java

  31 
vote

/** 
 * Initialization method that reads a File, and attempts to locate and load the JDBC driver from properties specified therein.
 * @param file the file containing the JDBC properties
 * @throws SQLException
 */
protected void initializeJDBC(File file) throws Exception {
  Properties properties;
  properties=new Properties();
  FileInputStream is=new FileInputStream(file);
  properties.load(is);
  is.close();
  m_jdbcURL=properties.getProperty(PROPERTY_DRIVER_URL);
  m_jdbcUser=properties.getProperty(PROPERTY_USER_ID);
  m_jdbcPassword=properties.getProperty(PROPERTY_USER_PASSWORD);
  String clazz=properties.getProperty(PROPERTY_DRIVER_CLASS);
  String driverFile=properties.getProperty(PROPERTY_DRIVER_JAR);
  final URL driverURL=new URL("file:" + driverFile);
  final ClassLoader parent=ClassLoader.getSystemClassLoader();
  URLClassLoader loader=AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>(){
    public URLClassLoader run(){
      return new URLClassLoader(new URL[]{driverURL},parent);
    }
  }
);
  Class driverClass=loader.loadClass(clazz);
  m_driver=(Driver)driverClass.newInstance();
}
 

Example 57

From project jsr107tck, under directory /cache-tests/src/test/java/org/jsr107/tck/.

Source file: CachingClassLoaderTest.java

  31 
vote

private ClassLoader createClassLoader() throws MalformedURLException {
  String domainJar=System.getProperty(DOMAINJAR,DEFAULT_DOMAINJAR);
  File file=new File(domainJar);
  if (!file.canRead()) {
    throw new IllegalArgumentException("can't find domain jar: " + domainJar);
  }
  URL urls[]=new URL[]{file.toURI().toURL()};
  ClassLoader parent=Thread.currentThread().getContextClassLoader();
  return new URLClassLoader(urls,parent);
}
 

Example 58

From project JsTestDriver, under directory /JsTestDriver/src/com/google/jstestdriver/.

Source file: PluginLoader.java

  31 
vote

/** 
 * For each plugin, the specified jar is loaded, then the specified class is extracted from the Jar.
 * @return a list of {@code Module}
 */
public List<Module> load(List<Plugin> plugins){
  List<Module> modules=new LinkedList<Module>();
  for (  Plugin plugin : plugins) {
    try {
      URLClassLoader urlClassLoader=new URLClassLoader(new URL[]{new URL("jar:file:" + plugin.getPathToJar() + "!/")},getClass().getClassLoader());
      Class<?> module=getPluginMainClass(plugin,urlClassLoader);
      modules.add(getModuleInstance(plugin,module));
    }
 catch (    MalformedURLException e) {
      throw new RuntimeException(e);
    }
catch (    ClassNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
  return modules;
}
 

Example 59

From project juzu, under directory /core/src/test/java/juzu/impl/common/.

Source file: DevClassLoaderTestCase.java

  31 
vote

@Test public void testLoad() throws Exception {
  JavaArchive classes=ShrinkWrap.create(JavaArchive.class).addClass(Dev.class).addAsResource(new StringAsset("classes_resource_value"),"classes_resource");
  JavaArchive lib=ShrinkWrap.create(JavaArchive.class).addClass(Lib.class).addAsResource(new StringAsset("lib_resource_value"),"lib_resource");
  File explodedDir=explode(classes,lib);
  File libJar=new File(explodedDir,"WEB-INF/lib/lib.jar");
  File classesDir=new File(explodedDir,"WEB-INF/classes");
  URLClassLoader cl=new URLClassLoader(new URL[]{classesDir.toURI().toURL(),libJar.toURI().toURL()},getParentClassLoader());
  Class<?> devClass=cl.loadClass(Dev.class.getName());
  assertNotSame(devClass,Dev.class);
  Class<?> libClass=cl.loadClass(Lib.class.getName());
  assertNotSame(libClass,Lib.class);
  InputStream classesResource=cl.getResourceAsStream("classes_resource");
  assertNotNull(classesResource);
  assertEquals("classes_resource_value",Tools.read(classesResource));
  InputStream libResource=cl.getResourceAsStream("lib_resource");
  assertNotNull(libResource);
  assertEquals("lib_resource_value",Tools.read(libResource));
  DevClassLoader devCL=new DevClassLoader(cl);
  try {
    devCL.loadClass(Dev.class.getName());
    fail();
  }
 catch (  ClassNotFoundException e) {
  }
  assertSame(libClass,devCL.loadClass(Lib.class.getName()));
  classesResource=devCL.getResourceAsStream("classes_resource");
  assertNull(classesResource);
  libResource=devCL.getResourceAsStream("lib_resource");
  assertNotNull(libResource);
  assertEquals("lib_resource_value",Tools.read(libResource));
}
 

Example 60

From project karaf, under directory /main/src/main/java/org/apache/karaf/main/.

Source file: Main.java

  31 
vote

private ClassLoader createClassLoader(ArtifactResolver resolver) throws Exception {
  List<URL> urls=new ArrayList<URL>();
  urls.add(resolver.resolve(config.frameworkBundle).toURL());
  File[] libs=new File(config.karafHome,"lib").listFiles();
  if (libs != null) {
    for (    File f : libs) {
      if (f.isFile() && f.canRead() && f.getName().endsWith(".jar")) {
        urls.add(f.toURI().toURL());
      }
    }
  }
  return new URLClassLoader(urls.toArray(new URL[urls.size()]),Main.class.getClassLoader());
}
 

Example 61

From project LateralGM, under directory /org/lateralgm/main/.

Source file: LGM.java

  31 
vote

public static void loadPlugins(){
  File dir=new File(workDir.getParent(),"plugins");
  if (!dir.exists())   dir=new File(workDir.getParent(),"Plugins");
  File[] ps=dir.listFiles(new CustomFileFilter(null,".jar"));
  if (ps == null)   return;
  for (  File f : ps) {
    if (!f.exists())     continue;
    try {
      String pluginEntry="LGM-Plugin";
      Manifest mf=new JarFile(f).getManifest();
      String clastr=mf.getMainAttributes().getValue(pluginEntry);
      if (clastr == null)       throw new Exception(Messages.format("LGM.PLUGIN_MISSING_ENTRY",pluginEntry));
      URLClassLoader ucl=new URLClassLoader(new URL[]{f.toURI().toURL()});
      ucl.loadClass(clastr).newInstance();
    }
 catch (    Exception e) {
      String msgInd="LGM.PLUGIN_LOAD_ERROR";
      System.out.println(Messages.format(msgInd,f.getName(),e.getClass().getName(),e.getMessage()));
      continue;
    }
  }
}
 

Example 62

From project liquibase, under directory /liquibase-core/src/main/java/liquibase/resource/.

Source file: FileSystemResourceAccessor.java

  31 
vote

public ClassLoader toClassLoader(){
  try {
    return new URLClassLoader(new URL[]{new URL("file://" + baseDirectory)});
  }
 catch (  MalformedURLException e) {
    throw new RuntimeException(e);
  }
}
 

Example 63

From project maven-hudson-dev-plugin, under directory /src/main/java/org/mortbay/jetty/plugin/.

Source file: AbstractJettyMojo.java

  31 
vote

public void configurePluginClasspath() throws MojoExecutionException {
  if (useProvidedScope) {
    try {
      List<URL> provided=new ArrayList<URL>();
      URL[] urls=null;
      for (Iterator<Artifact> iter=projectArtifacts.iterator(); iter.hasNext(); ) {
        Artifact artifact=iter.next();
        if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope()) && !isPluginArtifact(artifact)) {
          provided.add(artifact.getFile().toURI().toURL());
          if (getLog().isDebugEnabled()) {
            getLog().debug("Adding provided artifact: " + artifact);
          }
        }
      }
      if (!provided.isEmpty()) {
        urls=new URL[provided.size()];
        provided.toArray(urls);
        URLClassLoader loader=new URLClassLoader(urls,getClass().getClassLoader());
        Thread.currentThread().setContextClassLoader(loader);
        getLog().info("Plugin classpath augmented with <scope>provided</scope> dependencies: " + Arrays.toString(urls));
      }
    }
 catch (    MalformedURLException e) {
      throw new MojoExecutionException("Invalid url",e);
    }
  }
}
 

Example 64

From project asterisk-java, under directory /src/main/java/org/asteriskjava/fastagi/.

Source file: AbstractMappingStrategy.java

  30 
vote

/** 
 * Returns the ClassLoader to use for loading AgiScript classes and load other resources like the mapping properties file.<p> By default this method returns a class loader that searches for classes in the "agi" subdirectory (if it exists) and uses the context class loader of the current thread as the parent class loader.<p> You can override this method if you prefer using a different class loader.
 * @return the ClassLoader to use for loading AgiScript classes and loadother resources like the mapping properties file.
 * @since 1.0.0
 */
protected synchronized ClassLoader getClassLoader(){
  if (defaultClassLoader == null) {
    final ClassLoader parentClassLoader=Thread.currentThread().getContextClassLoader();
    final List<URL> dirUrls=new ArrayList<URL>();
    for (    String scriptPathEntry : DEFAULT_SCRIPT_PATH) {
      final File scriptDir=new File(scriptPathEntry);
      if (!scriptDir.isDirectory()) {
        continue;
      }
      try {
        dirUrls.add(scriptDir.toURI().toURL());
      }
 catch (      MalformedURLException e) {
      }
    }
    if (dirUrls.size() == 0) {
      return parentClassLoader;
    }
    defaultClassLoader=new URLClassLoader(dirUrls.toArray(new URL[dirUrls.size()]),parentClassLoader);
  }
  return defaultClassLoader;
}
 

Example 65

From project beanvalidation-api, under directory /src/test/java/javax/validation/.

Source file: ValidationTest.java

  30 
vote

@Test public void testCurrentClassLoaderIsUsedInCaseContextClassLoaderCannotLoadServiceFile(){
  ClassLoader contextClassLoader=Thread.currentThread().getContextClassLoader();
  ClassLoader dummyClassLoader=new URLClassLoader(new URL[]{},null);
  Thread.currentThread().setContextClassLoader(dummyClassLoader);
  try {
    Validation.buildDefaultValidatorFactory();
    fail();
  }
 catch (  ValidationException e) {
    assertEquals(e.getMessage(),"Unable to load Bean Validation provider");
  }
 finally {
    Thread.currentThread().setContextClassLoader(contextClassLoader);
  }
}
 

Example 66

From project cdk, under directory /maven-cdk-plugin/src/main/java/org/richfaces/builder/mojo/.

Source file: AbstractCDKMojo.java

  30 
vote

protected ClassLoader createProjectClassLoader(MavenProject project,boolean useCCL){
  ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
  try {
    List<?> compileClasspathElements=project.getCompileClasspathElements();
    String outputDirectory=project.getBuild().getOutputDirectory();
    URL[] urls=new URL[compileClasspathElements.size() + 1];
    int i=0;
    urls[i++]=new File(outputDirectory).toURI().toURL();
    for (Iterator<?> iter=compileClasspathElements.iterator(); iter.hasNext(); ) {
      String element=(String)iter.next();
      urls[i++]=new File(element).toURI().toURL();
    }
    if (useCCL) {
      classLoader=new URLClassLoader(urls,classLoader);
    }
 else {
      classLoader=new URLClassLoader(urls);
    }
  }
 catch (  MalformedURLException e) {
    getLog().error("Bad URL in classpath",e);
  }
catch (  DependencyResolutionRequiredException e) {
    getLog().error("Dependencies not resolved ",e);
  }
  return classLoader;
}
 

Example 67

From project DB-Builder, under directory /src/main/java/org/silverpeas/dbbuilder/util/.

Source file: DynamicLoader.java

  30 
vote

public DynamicLoader(){
  File jarDirectory=new File(Configuration.getPiecesFilesDir(),JAR_DIRECTORY);
  URL[] classpath=new URL[]{};
  if (jarDirectory.exists() && jarDirectory.isDirectory()) {
    @SuppressWarnings("unchecked") Collection<File> jars=FileUtils.listFiles(jarDirectory,new String[]{"jar"},true);
    List<URL> urls=new ArrayList<URL>(jars.size());
    DBBuilder.printMessage("We have found " + jars.size() + " jars files");
    for (    File jar : jars) {
      try {
        urls.add(jar.toURI().toURL());
        for (        URL url : urls) {
          DBBuilder.printError(url.toString());
        }
      }
 catch (      MalformedURLException ex) {
        Logger.getLogger(DynamicLoader.class.getName()).log(Level.SEVERE,null,ex);
      }
    }
    classpath=urls.toArray(new URL[urls.size()]);
  }
  ClassLoader parent=Thread.currentThread().getContextClassLoader();
  if (parent == null) {
    parent=getClass().getClassLoader();
  }
  loader=new URLClassLoader(classpath,parent);
}
 

Example 68

From project deadbolt, under directory /src/main/java/com/daemitus/deadbolt/listener/.

Source file: ListenerManager.java

  30 
vote

public void registerListeners(){
  loaded.clear();
  unloaded.clear();
  File dir=new File(plugin.getDataFolder() + "/listeners");
  if (!dir.exists()) {
    dir.mkdirs();
  }
  try {
    ClassLoader loader=new URLClassLoader(new URL[]{dir.toURI().toURL()},ListenerInterface.class.getClassLoader());
    for (    File file : dir.listFiles()) {
      String name=file.getName();
      if (!name.endsWith(".class")) {
        continue;
      }
      Class<?> clazz=loader.loadClass(name.substring(0,name.lastIndexOf(".")));
      Object object=clazz.newInstance();
      if (object instanceof ListenerInterface) {
        ListenerInterface listener=(ListenerInterface)object;
        unloaded.add(listener);
        Deadbolt.getLogger().log(Level.INFO,"[Deadbolt] Registered " + listener.getClass().getSimpleName());
      }
 else {
        Deadbolt.getLogger().log(Level.WARNING,String.format("[Deadbolt] " + clazz.getSimpleName() + " does not extend "+ DeadboltListener.class.getSimpleName()+ " properly"));
      }
    }
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
}
 

Example 69

From project eclim, under directory /org.eclim/java/org/eclim/eclipse/.

Source file: EclimDaemon.java

  30 
vote

/** 
 * Builds the classloader used for third party nailgun extensions dropped into eclim's ext dir.
 * @return The classloader.
 */
private ClassLoader getExtensionClassLoader() throws Exception {
  File extdir=new File(FileUtils.concat(Services.DOT_ECLIM,"resources/ext"));
  if (extdir.exists()) {
    FileFilter filter=new FileFilter(){
      public boolean accept(      File file){
        return file.isDirectory() || file.getName().endsWith(".jar");
      }
    }
;
    ArrayList<URL> urls=new ArrayList<URL>();
    listFileUrls(extdir,filter,urls);
    return new URLClassLoader(urls.toArray(new URL[urls.size()]),this.getClass().getClassLoader());
  }
  return null;
}
 

Example 70

From project GNDMS, under directory /infra/src/de/zib/gndms/infra/system/.

Source file: PluginLoader.java

  30 
vote

public URLClassLoader loadPlugins() throws IOException {
  final ArrayList<URL> jars;
  final File pluginDir=new File(pluginPath);
  final String[] list=pluginDir.list(new FilenameFilter(){
    @Override public boolean accept(    final File dir,    final String name){
      return name.matches(".*\\.jar");
    }
  }
);
  if (list != null) {
    jars=new ArrayList<URL>(list.length);
    for (int i=0; i < list.length; ++i)     jars.add(new URL("file://" + pluginPath + File.separator+ list[i]));
    return new URLClassLoader(jars.toArray(new URL[jars.size()]),this.getClass().getClassLoader());
  }
  return new URLClassLoader(new URL[]{},this.getClass().getClassLoader());
}
 

Example 71

From project gradle-intellij-gui, under directory /src/main/java/org/gradle/ideaplugin/util/.

Source file: GradleAccess.java

  30 
vote

@Nullable private static ClassLoader createGradleClassLoader(final List<URL> urls){
  if (urls == null)   return null;
  return new URLClassLoader(urls.toArray(new URL[urls.size()]),Thread.currentThread().getContextClassLoader()){
    /** 
 * Overrides the method from ClassLoader.  This implementation attempts to load the class using our classpath first.  Only if the class cannot be found does it delegate.  The delegation handles loading all the standard Java classes, and things from the ext and endorsed directories.
 * @author jmurph
 */
    @Override protected synchronized Class<?> loadClass(    String name,    boolean resolve) throws ClassNotFoundException {
      Class<?> c=findLoadedClass(name);
      if (c != null)       return c;
      try {
        c=findClass(name);
        if (resolve)         resolveClass(c);
        return c;
      }
 catch (      ClassNotFoundException e) {
        return super.loadClass(name,resolve);
      }
    }
  }
;
}
 

Example 72

From project jabox, under directory /jabox/src/launcher/main/.

Source file: Main.java

  30 
vote

public static void main(String[] args) throws Exception {
  System.setProperty("java.awt.headless","true");
  File me=whoAmI();
  URL jar=Main.class.getResource("winstone.jar");
  File tmpJar;
  try {
    tmpJar=File.createTempFile("winstone","jar");
  }
 catch (  IOException e) {
    String tmpdir=System.getProperty("java.io.tmpdir");
    IOException x=new IOException("Hudson has failed to create a temporary file in " + tmpdir);
    x.initCause(e);
    throw x;
  }
  copyStream(jar.openStream(),new FileOutputStream(tmpJar));
  tmpJar.deleteOnExit();
  File tempFile=File.createTempFile("dummy","dummy");
  deleteContents(new File(tempFile.getParent(),"winstone/" + me.getName()));
  tempFile.delete();
  ClassLoader cl=new URLClassLoader(new URL[]{tmpJar.toURL()});
  Class launcher=cl.loadClass("winstone.Launcher");
  Method mainMethod=launcher.getMethod("main",new Class[]{String[].class});
  List arguments=new ArrayList(Arrays.asList(args));
  arguments.add(0,"--warfile=" + me.getAbsolutePath());
  if (!hasWebRoot(arguments))   arguments.add("--webroot=" + new File(System.getProperty("user.home"),".jabox/war"));
  mainMethod.invoke(null,new Object[]{arguments.toArray(new String[0])});
}
 

Example 73

From project java-webserver, under directory /src/org/nikki/http/module/.

Source file: ModuleLoader.java

  30 
vote

/** 
 * Load a server module, the configuration can specify the source to be a jar file in the module directory
 * @param className The module main class
 * @param configuration The module configuration file
 */
public void loadModule(String className,ConfigurationNode configuration){
  try {
    ClassLoader loader=ModuleLoader.class.getClassLoader();
    if (configuration.has("source")) {
      loader=new URLClassLoader(new URL[]{new File(configuration.getString("source")).toURI().toURL()});
    }
    Class<?> cl=loader.loadClass(className);
    ServerModule module=(ServerModule)cl.newInstance();
    module.setServer(server);
    module.onLoad(configuration);
    register(module);
  }
 catch (  Exception e) {
    logger.log(Level.SEVERE,"Unable to load module : " + className,e);
  }
}
 

Example 74

From project jboss-reflect, under directory /src/test/java/org/jboss/test/beaninfo/test/.

Source file: BeanInfoCacheTestCase.java

  30 
vote

public void testClassLoaderCaching() throws Throwable {
  String className=BeanInfoEmpty.class.getName();
  Class<?> clazz=Class.forName(className);
  URL url1=clazz.getProtectionDomain().getCodeSource().getLocation();
  URL[] urls={url1};
  ClassLoader cl1=new URLClassLoader(urls,null);
  clazz=Class.forName(ClassInfo.class.getName());
  URL url2=clazz.getProtectionDomain().getCodeSource().getLocation();
  urls=new URL[]{url1,url2};
  ClassLoader cl2=new URLClassLoader(urls,null);
  Configuration configuration=getConfiguration();
  ClassInfo ci1=configuration.getClassInfo(className,cl1);
  ClassInfo ci2=configuration.getClassInfo(className,cl2);
  assertEquals(ci1,ci2);
  className="org.jboss.test.beaninfo.support.BeanInfoCache";
  BeanInfo bi1=configuration.getBeanInfo(className,cl1);
  BeanInfo bi2=configuration.getBeanInfo(className,cl2);
  assertFalse(bi1.equals(bi2));
}
 

Example 75

From project jbpm-plugin, under directory /jbpm/src/main/java/hudson/jbpm/.

Source file: ProcessClassLoaderCache.java

  30 
vote

public synchronized ClassLoader getClassLoader(ProcessDefinition def) throws IOException {
  ClassLoader cl=cache.get(def.getId());
  if (cl == null) {
    File pdCache=new File(cacheRoot,Long.toString(def.getId()));
    if (!pdCache.exists()) {
      FileDefinition fd=def.getFileDefinition();
      for (      Map.Entry<String,byte[]> entry : ((Map<String,byte[]>)fd.getBytesMap()).entrySet()) {
        File f=new File(pdCache,entry.getKey());
        f.getParentFile().mkdirs();
        FileOutputStream fos=new FileOutputStream(f);
        IOUtils.copy(new ByteArrayInputStream(entry.getValue()),fos);
        fos.close();
      }
    }
    cl=new URLClassLoader(new URL[]{new URL(pdCache.toURI().toURL(),"classes/")},Hudson.getInstance().getPluginManager().uberClassLoader){
      @Override public Class<?> loadClass(      String name) throws ClassNotFoundException {
        System.out.println(name);
        return super.loadClass(name);
      }
    }
;
    cache.put(def.getId(),cl);
  }
  return cl;
}
 

Example 76

From project jewelcli, under directory /jewelcli-maven-report-plugin/src/main/java/com/lexicalscope/jewelcli/maven/report/.

Source file: JewelCliReportMojo.java

  30 
vote

private ClassLoader getClassLoader() throws MavenReportException {
  final List<URL> urls=new ArrayList<URL>();
  try {
    for (    final Object object : project.getCompileClasspathElements()) {
      final String path=(String)object;
      final URL url=new File(path).toURL();
      getLog().debug("adding classpath element " + url);
      urls.add(url);
    }
  }
 catch (  final MalformedURLException e) {
    throw new MavenReportException("Unable to load command line interface class",e);
  }
catch (  final DependencyResolutionRequiredException e) {
    throw new MavenReportException("Unable to resolve dependencies of project",e);
  }
  return new URLClassLoader(urls.toArray(new URL[]{}),getClass().getClassLoader());
}
 

Example 77

From project jsf-test, under directory /maven-mockgenerator-plugin/src/main/java/org/jboss/mockgenerator/.

Source file: AbstractMockMojo.java

  30 
vote

@SuppressWarnings("unchecked") protected ClassLoader createProjectClassLoader(){
  ClassLoader classLoader=null;
  try {
    Collection<String> classpathElements=getClasspathElements();
    String outputDirectory=project.getBuild().getOutputDirectory();
    URL[] urls=new URL[classpathElements.size() + 1];
    int i=0;
    urls[i++]=new File(outputDirectory).toURI().toURL();
    for (Iterator<String> iter=classpathElements.iterator(); iter.hasNext(); ) {
      String element=iter.next();
      urls[i++]=new File(element).toURI().toURL();
    }
    classLoader=new URLClassLoader(urls);
  }
 catch (  MalformedURLException e) {
    getLog().error("Bad URL in classpath",e);
  }
  return classLoader;
}
 

Example 78

From project jtrek, under directory /src/org/gamehost/jtrek/javatrek/.

Source file: TrekServer.java

  30 
vote

public static void launchBot(String botType){
  try {
    String botString="org.gamehost.jtrek.javatrek.bot." + botType;
    TrekBot botPlayer;
    Class botClass;
    Class[] constArgs=new Class[]{TrekServer.class,String.class};
    Object[] actualArgs=new Object[]{TrekServer.getInstance(),"test"};
    Constructor botConst;
    try {
      ClassLoader botLoader=new URLClassLoader(new URL[]{new File("lib/.").toURL()});
      botClass=botLoader.loadClass(botString);
      botConst=botClass.getConstructor(constArgs);
      botPlayer=(TrekBot)botConst.newInstance(actualArgs);
      TrekServer.addBot(botPlayer);
    }
 catch (    MalformedURLException mue) {
      TrekLog.logException(mue);
    }
  }
 catch (  ClassNotFoundException cnfe) {
    TrekLog.logException(cnfe);
  }
catch (  NoSuchMethodException nsme) {
    TrekLog.logException(nsme);
  }
catch (  IllegalAccessException iae) {
    TrekLog.logException(iae);
  }
catch (  InstantiationException ie) {
    TrekLog.logException(ie);
  }
catch (  InvocationTargetException ite) {
    TrekLog.logException(ite);
  }
}
 

Example 79

From project knime-scripting, under directory /groovy4knime/src/de/mpicbg/tds/knime/scripting/groovy/.

Source file: GroovyScriptNodeModel.java

  30 
vote

private ClassLoader createClassLoader() throws MalformedURLException {
  IPreferenceStore prefStore=GroovyScriptingBundleActivator.getDefault().getPreferenceStore();
  String classpathAddons=prefStore.getString(GroovyScriptingPreferenceInitializer.GROOVY_CLASSPATH_ADDONS);
  classpathAddons.replace("\n",";");
  List<URL> urls=new ArrayList<URL>();
  for (  String classPathEntry : classpathAddons.split(";")) {
    classPathEntry=classPathEntry.trim();
    if (classPathEntry.trim().startsWith("#"))     continue;
    classPathEntry=classPathEntry.replace("{KNIME.HOME}",System.getProperty("osgi.syspath"));
    try {
      if (classPathEntry.endsWith("*")) {
        FilenameFilter jarFilter=new FilenameFilter(){
          public boolean accept(          File file,          String s){
            return s.endsWith(".jar");
          }
        }
;
        for (        File file : new File(classPathEntry).getParentFile().listFiles(jarFilter)) {
          urls.add(file.toURL());
        }
      }
 else {
        File file=new File(classPathEntry);
        if (file.exists()) {
          urls.add(file.toURL());
        }
      }
    }
 catch (    Throwable t) {
      logger.error("The url '" + classPathEntry + "' does not exist. Please correct the entry in Preferences > KNIME > Groovy Scripting");
    }
  }
  return new URLClassLoader(urls.toArray(new URL[0]),this.getClass().getClassLoader());
}
 

Example 80

From project maven-jdocbook-plugin, under directory /src/main/java/org/jboss/maven/plugins/jdocbook/.

Source file: AbstractDocBookMojo.java

  30 
vote

@SuppressWarnings({"unchecked"}) private ClassLoader buildResourceDelegateClassLoader(){
  List<URL> urls=new ArrayList<URL>();
  if (directoryLayout.getStagingDirectory().exists()) {
    try {
      urls.add(directoryLayout.getStagingDirectory().toURI().toURL());
    }
 catch (    MalformedURLException e) {
      throw new JDocBookProcessException("Unable to resolve staging directory to URL",e);
    }
  }
  for (  Artifact artifact : (Set<Artifact>)project.getArtifacts()) {
    if (artifact.getFile() != null) {
      try {
        urls.add(artifact.getFile().toURI().toURL());
      }
 catch (      MalformedURLException e) {
        getLog().warn("Uanble to retrieve artifact url [" + artifact.getId() + "]");
      }
    }
  }
  if (pluginArtifacts != null) {
    for (    Artifact artifact : (List<Artifact>)pluginArtifacts) {
      if (artifact.getFile() != null) {
        try {
          urls.add(artifact.getFile().toURI().toURL());
        }
 catch (        MalformedURLException e) {
          getLog().warn("Uanble to retrieve artifact url [" + artifact.getId() + "]");
        }
      }
    }
  }
  return new URLClassLoader(urls.toArray(new URL[urls.size()]),Thread.currentThread().getContextClassLoader());
}
 

Example 81

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.

Source file: Utils.java

  29 
vote

/** 
 * calculate local file based class path for class loader if possible (servlet classes must be located there)
 * @param cl class loader
 * @return class path in string
 * @throws UnsupportedEncodingException 
 */
static public String calculateClassPath(ClassLoader cl) throws UnsupportedEncodingException {
  StringBuffer classPath=new StringBuffer();
  boolean jspFound=false, servletFound=false;
  while (cl != null) {
    if (cl instanceof URLClassLoader) {
      boolean addClasses=false;
      if (jspFound == false) {
        jspFound=((URLClassLoader)cl).findResource("javax/servlet/jsp/JspPage.class") != null;
        addClasses|=jspFound;
      }
      if (servletFound == false) {
        servletFound=((URLClassLoader)cl).findResource("javax/servlet/http/HttpServlet.class") != null;
        addClasses|=servletFound;
      }
      if (addClasses) {
        URL[] urls=((URLClassLoader)cl).getURLs();
        for (int i=0; i < urls.length; i++) {
          String classFile=toFile(urls[i]);
          if (classFile == null)           continue;
          if (classPath.length() > 0)           classPath.append(File.pathSeparatorChar).append(classFile);
 else           classPath.append(classFile);
        }
      }
      if (jspFound && servletFound)       return classPath.toString();
    }
    cl=cl.getParent();
  }
  return System.getProperty("java.class.path");
}
 

Example 82

From project aerogear-controller, under directory /src/test/java/org/jboss/aerogear/controller/.

Source file: TypeNameExtractorTest.java

  29 
vote

@Test public void shouldDecapitalizeSomeCharsUntilItFindsOneUppercased() throws NoSuchMethodException {
  Assert.assertEquals("urlClassLoader",extractor.nameFor(URLClassLoader.class));
  Assert.assertEquals("bigDecimal",extractor.nameFor(BigDecimal.class));
  Assert.assertEquals("string",extractor.nameFor(String.class));
  Assert.assertEquals("aClass",extractor.nameFor(AClass.class));
  Assert.assertEquals("url",extractor.nameFor(URL.class));
}
 

Example 83

From project core_1, under directory /test/src/main/java/org/switchyard/test/.

Source file: SwitchYardTestKit.java

  29 
vote

private SwitchYardModel createSwitchYardModel(InputStream configModel,List<Scanner<V1SwitchYardModel>> scanners){
  Assert.assertNotNull("Test 'configModel' is null.",configModel);
  final SwitchYardModel returnModel;
  try {
    SwitchYardModel model=loadSwitchYardModel(configModel,false);
    ClassLoader classLoader=_testInstance.getClass().getClassLoader();
    if (scanners != null && !scanners.isEmpty() && classLoader instanceof URLClassLoader) {
      MergeScanner<V1SwitchYardModel> merge_scanner=new MergeScanner<V1SwitchYardModel>(V1SwitchYardModel.class,true,scanners);
      List<URL> scanURLs=getScanURLs((URLClassLoader)classLoader);
      ScannerInput<V1SwitchYardModel> scanner_input=new ScannerInput<V1SwitchYardModel>().setName(model.getName()).setURLs(scanURLs);
      V1SwitchYardModel scannedModel=merge_scanner.scan(scanner_input).getModel();
      returnModel=Models.merge(scannedModel,model,false);
    }
 else {
      returnModel=model;
    }
    returnModel.assertModelValid();
    return returnModel;
  }
 catch (  java.io.IOException ioEx) {
    throw new SwitchYardException("Failed to read switchyard config.",ioEx);
  }
}
 

Example 84

From project datasalt-utils, under directory /src/contrib/java/org/apache/solr/core/.

Source file: SolrResourceLoader.java

  29 
vote

private static URLClassLoader replaceClassLoader(final URLClassLoader oldLoader,final File base,final FileFilter filter){
  if (null != base && base.canRead() && base.isDirectory()) {
    File[] files=base.listFiles(filter);
    if (null == files || 0 == files.length)     return oldLoader;
    URL[] oldElements=oldLoader.getURLs();
    URL[] elements=new URL[oldElements.length + files.length];
    System.arraycopy(oldElements,0,elements,0,oldElements.length);
    for (int j=0; j < files.length; j++) {
      try {
        URL element=files[j].toURI().normalize().toURL();
        log.info("Adding '" + element.toString() + "' to classloader");
        elements[oldElements.length + j]=element;
      }
 catch (      MalformedURLException e) {
        SolrException.log(log,"Can't add element to classloader: " + files[j],e);
      }
    }
    return URLClassLoader.newInstance(elements,oldLoader.getParent());
  }
  return oldLoader;
}
 

Example 85

From project dawn-isenciaui, under directory /com.isencia.passerelle.workbench.model.ui/src/main/java/com/isencia/passerelle/workbench/model/ui/utils/.

Source file: ClassUtils.java

  29 
vote

public static URLClassLoader getURLClassLoader(IResource resource) throws MalformedURLException {
  IJavaElement javaElement=getJavaElement(resource);
  IJavaProject javaProject=javaElement.getJavaProject();
  URL[] urls=getPasserelleClassPath(javaProject);
  return getURLClassLoader(urls);
}
 

Example 86

From project dimdwarf, under directory /dimdwarf-core/src/main/java/net/orfjackal/dimdwarf/server/.

Source file: JRE.java

  29 
vote

public static boolean isJava7(){
  try {
    URLClassLoader.class.getMethod("close");
    return true;
  }
 catch (  NoSuchMethodException e) {
    return false;
  }
}
 

Example 87

From project droolsjbpm-tools, under directory /drools-eclipse/org.drools.eclipse/src/main/java/org/drools/eclipse/util/.

Source file: ProjectClassLoader.java

  29 
vote

public static URLClassLoader getProjectClassLoader(IEditorPart editor){
  IEditorInput input=editor.getEditorInput();
  if (input instanceof IFileEditorInput) {
    return getProjectClassLoader(((IFileEditorInput)input).getFile());
  }
  return null;
}
 

Example 88

From project graylog2-server, under directory /src/main/java/org/graylog2/plugins/.

Source file: PluginLoader.java

  29 
vote

public List<Class<? extends MessageFilter>> loadFilterPlugins(){
  List<Class<? extends MessageFilter>> filters=Lists.newArrayList();
  for (  File jarPath : getAllJars(FILTER_DIR)) {
    try {
      ClassLoader loader=URLClassLoader.newInstance(new URL[]{jarPath.toURI().toURL()},getClass().getClassLoader());
      Class<?> clazz=Class.forName(getClassNameFromJarName(jarPath.getName()),true,loader);
      filters.add(clazz.asSubclass(MessageFilter.class));
    }
 catch (    MalformedURLException ex) {
      LOG.error("Could not load plugin <" + jarPath.getAbsolutePath() + ">",ex);
      continue;
    }
catch (    ClassNotFoundException ex) {
      LOG.error("Could not load plugin <" + jarPath.getAbsolutePath() + ">",ex);
      continue;
    }
catch (    InvalidJarNameException ex) {
      LOG.error("Could not load plugin <" + jarPath.getAbsolutePath() + ">",ex);
      continue;
    }
  }
  return filters;
}
 

Example 89

From project guvnorng, under directory /guvnorng-repository/src/main/java/org/drools/repository/.

Source file: ClassUtil.java

  29 
vote

public static List<String> getResourceList(String regex,Class caller){
  ClasspathResourceFilter filter=new ClasspathResourceFilter(regex);
  ClassLoader classLoader;
  classLoader=Thread.currentThread().getContextClassLoader();
  if (classLoader instanceof URLClassLoader) {
    filter.filter((URLClassLoader)classLoader);
  }
  classLoader=caller.getClassLoader();
  if (classLoader instanceof URLClassLoader) {
    filter.filter((URLClassLoader)classLoader);
  }
  return filter.getResourceList();
}
 

Example 90

From project huahin-manager, under directory /src/main/java/org/huahinframework/manager/queue/.

Source file: RunQueue.java

  29 
vote

@SuppressWarnings("unchecked") @Override public Void call() throws Exception {
  try {
    File jarFile=new File(queue.getJar());
    URL[] urls={jarFile.toURI().toURL()};
    ClassLoader loader=URLClassLoader.newInstance(urls);
    Class<Tool> clazz=(Class<Tool>)loader.loadClass(queue.getClazz());
    ToolRunner.run(jobConf,clazz.newInstance(),queue.getArguments());
  }
 catch (  Exception e) {
    queue.setMessage(e.toString());
    QueueUtils.registerQueue(queuePath,queue);
    e.printStackTrace();
    log.error(e);
  }
  return null;
}
 

Example 91

From project IOCipherServer, under directory /src/Acme/.

Source file: Utils.java

  29 
vote

/** 
 * calculate local file based class path for class loader if possible (servlet classes must be located there)
 * @param cl class loader
 * @return class path in string
 */
static public String calculateClassPath(ClassLoader cl){
  StringBuffer classPath=new StringBuffer();
  boolean jspFound=false, servletFound=false;
  while (cl != null) {
    if (cl instanceof URLClassLoader) {
      boolean addClasses=false;
      if (jspFound == false) {
        jspFound=((URLClassLoader)cl).findResource("javax/servlet/jsp/JspPage.class") != null;
        addClasses|=jspFound;
      }
      if (servletFound == false) {
        servletFound=((URLClassLoader)cl).findResource("javax/servlet/http/HttpServlet.class") != null;
        addClasses|=servletFound;
      }
      if (addClasses) {
        URL[] urls=((URLClassLoader)cl).getURLs();
        for (int i=0; i < urls.length; i++) {
          String classFile=toFile(urls[i]);
          if (classFile == null)           continue;
          if (classPath.length() > 0)           classPath.append(File.pathSeparatorChar).append(classFile);
 else           classPath.append(classFile);
        }
      }
      if (jspFound && servletFound)       return classPath.toString();
    }
    cl=cl.getParent();
  }
  return System.getProperty("java.class.path");
}
 

Example 92

From project jetty-maven-plugin, under directory /src/main/java/org/mortbay/jetty/plugin/.

Source file: MavenWebInfConfiguration.java

  29 
vote

public void configure(WebAppContext context) throws Exception {
  JettyWebAppContext jwac=(JettyWebAppContext)context;
  if (jwac.getClassPathFiles() != null) {
    if (Log.isDebugEnabled())     Log.debug("Setting up classpath ...");
    Iterator itor=jwac.getClassPathFiles().iterator();
    while (itor.hasNext())     ((WebAppClassLoader)context.getClassLoader()).addClassPath(((File)itor.next()).getCanonicalPath());
    if (Log.isDebugEnabled())     Log.debug("Classpath = " + LazyList.array2List(((URLClassLoader)context.getClassLoader()).getURLs()));
  }
  super.configure(context);
  String[] existingServerClasses=context.getServerClasses();
  String[] newServerClasses=new String[2 + (existingServerClasses == null ? 0 : existingServerClasses.length)];
  newServerClasses[0]="org.apache.maven.";
  newServerClasses[1]="org.codehaus.plexus.";
  System.arraycopy(existingServerClasses,0,newServerClasses,2,existingServerClasses.length);
  if (Log.isDebugEnabled()) {
    Log.debug("Server classes:");
    for (int i=0; i < newServerClasses.length; i++)     Log.debug(newServerClasses[i]);
  }
  context.setServerClasses(newServerClasses);
}
 

Example 93

From project logback, under directory /logback-classic/src/test/java/ch/qos/logback/classic/spi/.

Source file: PackagingDataCalculatorTest.java

  29 
vote

@Test public void noClassDefFoundError_LBCLASSIC_125Test() throws MalformedURLException {
  ClassLoader cl=(URLClassLoader)makeBogusClassLoader();
  Thread.currentThread().setContextClassLoader(cl);
  Throwable t=new Throwable("x");
  ThrowableProxy tp=new ThrowableProxy(t);
  StackTraceElementProxy[] stepArray=tp.getStackTraceElementProxyArray();
  StackTraceElement bogusSTE=new StackTraceElement("com.Bogus","myMethod","myFile",12);
  stepArray[0]=new StackTraceElementProxy(bogusSTE);
  PackagingDataCalculator pdc=tp.getPackagingDataCalculator();
  pdc.calculate(tp);
}
 

Example 94

From project mapmaker, under directory /src/main/java/org/jason/mapmaker/server/servlet/.

Source file: JettyThreadParentFilter.java

  29 
vote

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  ClassLoader cl=Thread.currentThread().getContextClassLoader();
  if (ExtendedJettyClassLoader.isGwtJettyClassLoader(cl)) {
    Thread.currentThread().setContextClassLoader(new ExtendedJettyClassLoader((URLClassLoader)cl,ClassLoader.getSystemClassLoader(),includeSystemclasses));
  }
  chain.doFilter(request,response);
}