public AppletControl(String u, int w, int h, String user, String p) {

    PARAMETERS.put("RemoteHost", u.split("//")[1].split(":")[0]);
    PARAMETERS.put("RemotePort", u.split(":")[2].split("/")[0]);
    System.out.println(PARAMETERS.toString());
    this.url = u;
    URL[] url = new URL[1];
    try {

      url[0] = new URL(u);
      URLClassLoader load = new URLClassLoader(url);
      try {
        try {
          app = (Applet) load.loadClass("aplug").newInstance();
          app.setSize(w, h);
          app.setStub(this);
          app.setVisible(true);
        } catch (InstantiationException ex) {
          ex.printStackTrace();
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        }
      } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
      }
    } catch (MalformedURLException ex) {
      ex.printStackTrace();
    }
  }
Example #2
0
  @SuppressWarnings("deprecation")
  public static void main(String[] args) {
    try {

      File fl = new File("testfile");
      int idx = fl.getAbsolutePath().lastIndexOf("testfile");

      String path = fl.getAbsolutePath().substring(0, idx);

      String phoenixHome = path + "src/test/resources/james-server/";

      ArrayList<URL> classLoaderURLList = new ArrayList<URL>();

      System.setProperty("phoenix.home", phoenixHome);

      classLoaderURLList.add(new File(phoenixHome + "bin/phoenix-loader.jar").toURL());

      URL classLoaderURLArray[] = classLoaderURLList.toArray(new URL[classLoaderURLList.size()]);

      // System.setProperty( "catalina.home", "C:\\Program Files\\Apache Software Foundation\\Tomcat
      // 5.5");
      URLClassLoader childClassLoader =
          new URLClassLoader(classLoaderURLArray, JamesLoader.class.getClassLoader());

      final Class<?> mainClass =
          childClassLoader.loadClass("org.apache.avalon.phoenix.launcher.Main");
      final Class<?>[] paramTypes = new Class[] {args.getClass()};
      final Method method = mainClass.getMethod("main", paramTypes);
      Object main_instance = mainClass.newInstance();
      method.invoke(main_instance, new Object[] {args});
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public NationClassLoader(URL[] urls, Vector nations) {
    super(urls);

    for (int i = 0; i < urls.length; i++) {
      file = urls[i].getFile();
      fileTmp = new File(file);
      System.out.println(
          "NationClassLoader - Does " + fileTmp.toString() + " exists : " + fileTmp.exists());
      name = file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf("."));

      runtimeObject = null;
      try {
        jarLoader = URLClassLoader.newInstance(new URL[] {urls[i]});
        System.out.println(
            "NationClassLoader - JARloader trying : " + jarLoader.getURLs()[0].toString());
        runtimeObject = jarLoader.loadClass(name + "/" + name).newInstance();
      } catch (Exception e) {
        System.err.println("NationClassLoader - Stinking error : " + e);
      }

      if (runtimeObject != null) {
        natFile = (nationFile2) runtimeObject;
        nations.addElement(natFile);
      }
    }
  }
Example #4
0
  private ClassLoader addToClassPath(ClassLoader classLoader, String[] newPaths)
      throws ExecutorException {
    URLClassLoader loader = (URLClassLoader) classLoader;
    List<URL> curPath = Arrays.asList(loader.getURLs());
    List<URL> newPath = Lists.newArrayList();

    for (URL onePath : curPath) {
      newPath.add(onePath);
    }
    curPath = newPath;
    if (newPaths != null) {
      for (String onestr : newPaths) {
        if (StringUtils.indexOf(onestr, FILE_PREFIX) == 0) {
          onestr = StringUtils.substring(onestr, CQLConst.I_7);
        }

        URL oneurl = getFileURL(onestr);

        if (!curPath.contains(oneurl)) {
          curPath.add(oneurl);
        }
      }
    }

    return new URLClassLoader(curPath.toArray(new URL[0]), loader);
  }
Example #5
0
  private static Stream<String> apps() {
    if (cl instanceof URLClassLoader) {
      URLClassLoader ucl = (URLClassLoader) cl;

      return Stream.of(ucl.getURLs())
          .map(propagating(url -> Paths.get(url.toURI())))
          .flatMap(
              propagating(
                  path -> {
                    if (Files.isRegularFile(path)) {
                      return zipContents(path);
                    } else if (Files.isDirectory(path)) {
                      return Files.walk(path)
                          .map(subpath -> path.relativize(subpath))
                          .map(subpath -> subpath.toString())
                          .filter(subpath -> subpath.endsWith(".class"))
                          .map(Scanner::toClassName);
                    } else {
                      return Stream.empty();
                    }
                  }))
          .filter(x -> !x.startsWith("com.cakemanny.app."))
          .filter(implementsInterface(App.class));
    } else {
      return Stream.empty();
    }
  }
 /**
  * Handle notification of the creation of a new classloader.
  *
  * @param logger the logging channel
  * @param label the classloader label
  * @param category the classloader category
  * @param classloader the new classloader to report
  */
 private static void classloaderConstructed(
     Logger logger, String label, Category category, ClassLoader classloader) {
   if (logger.isTraceEnabled()) {
     int id = System.identityHashCode(classloader);
     StringBuffer buffer = new StringBuffer();
     buffer.append("new ");
     buffer.append(category.toString());
     buffer.append(" classloader for " + label);
     buffer.append("\n           id: " + id);
     ClassLoader parent = classloader.getParent();
     if (null != parent) {
       int pid = System.identityHashCode(parent);
       buffer.append("\n      extends: " + pid);
     }
     if (classloader instanceof URLClassLoader) {
       URLClassLoader loader = (URLClassLoader) classloader;
       URL[] urls = loader.getURLs();
       if (urls.length == 1) {
         buffer.append("\n     contains: 1 entry");
       } else {
         buffer.append("\n     contains: " + urls.length + " entries");
       }
       for (int i = 0; i < urls.length; i++) {
         URL url = urls[i];
         buffer.append("\n         [" + (i + 1) + "] " + url.toString());
       }
     }
     logger.trace(buffer.toString());
   }
 }
  public void testWithNoPackage() throws Exception {

    RecorderLocator.clearRecorders();

    final URLClassLoader ourClassLoader =
        (URLClassLoader) BlockingClassLoader.class.getClassLoader();

    final BlockingClassLoader blockingClassLoader =
        new BlockingClassLoader(
            ourClassLoader, Arrays.<String>asList(AnotherClass.class.getName()));

    final NoPackageURLClassLoader cl =
        new NoPackageURLClassLoader(ourClassLoader.getURLs(), blockingClassLoader);

    final Class<?> noPackageClass = cl.loadClass(AnotherClass.class.getName());
    final Method noPackageMethod = noPackageClass.getMethod("getOne");

    assertEquals(1, noPackageMethod.invoke(null));
    m_recorderStubFactory.assertNoMoreCalls();

    final Object result = m_instrumenter.createInstrumentedProxy(null, m_recorder, noPackageClass);
    assertSame(noPackageClass, result);
    m_recorderStubFactory.assertNoMoreCalls();

    assertEquals(1, noPackageMethod.invoke(null));
    m_recorderStubFactory.assertSuccess("start");
    m_recorderStubFactory.assertSuccess("end", true);
    m_recorderStubFactory.assertNoMoreCalls();
  }
Example #8
0
 public static String toString(ClassLoader loader) {
   if (loader instanceof URLClassLoader) {
     URLClassLoader ul = (URLClassLoader) loader;
     return "URLClassLoader" + Arrays.asList(ul.getURLs()).toString();
   }
   return String.valueOf(loader);
 }
Example #9
0
 @SuppressWarnings("unchecked")
 private static void loadBots() {
   logger.info("Loading available bots");
   final Collection<File> botJars =
       FileUtils.listFiles(botsDirecotry, new String[] {"jar"}, false);
   for (File botJar : botJars) {
     try {
       JarFile jar = new JarFile(botJar);
       ZipEntry entry = jar.getEntry("bot.yml");
       if (entry == null) throw new RuntimeException("Bot has no bot.yml file!");
       InputStream is = jar.getInputStream(entry);
       YAMLNode n = new YAMLNode(new Yaml().loadAs(is, Map.class), true);
       String mainClass = n.getString("mainClass");
       String type = n.getString("type");
       URLClassLoader loader =
           new URLClassLoader(new URL[] {botJar.toURI().toURL()}, Chatty.class.getClassLoader());
       BOT_INFO.put(type, new BotClassInfo(loader.loadClass(mainClass).asSubclass(Bot.class), n));
       logger.info("Loaded bot '{}'", type);
     } catch (Exception e) {
       logger.error("Failed to load bot from {}", botJar.getName());
       e.printStackTrace();
     }
   }
   logger.info("Loaded {} bot(s)", BOT_INFO.size());
 }
Example #10
0
  /** Initializes the cache. */
  protected void initialize() {
    String part;
    File file;
    URLClassLoader sysLoader;
    URL[] urls;

    m_Cache = new Hashtable<String, HashSet<String>>();

    sysLoader = (URLClassLoader) getClass().getClassLoader();
    urls = sysLoader.getURLs();
    for (URL url : urls) {
      if (VERBOSE) System.out.println("Classpath-part: " + part);

      file = null;
      part = url.toString();
      if (part.startsWith("file:")) {
        part = part.replace(" ", "%20");
        try {
          file = new File(new java.net.URI(part));
        } catch (URISyntaxException e) {
          e.printStackTrace();
        }
      } else {
        file = new File(part);
      }
      if (file == null) {
        System.err.println("Skipping: " + part);
        continue;
      }

      // find classes
      if (file.isDirectory()) initFromDir(file);
      else if (file.exists()) initFromJar(file);
    }
  }
  public static ClassLoader newClassLoader(final Class... userClasses) throws Exception {

    Set<URL> userClassUrls = new HashSet<>();
    for (Class anyUserClass : userClasses) {
      ProtectionDomain protectionDomain = anyUserClass.getProtectionDomain();
      CodeSource codeSource = protectionDomain.getCodeSource();
      URL classLocation = codeSource.getLocation();
      userClassUrls.add(classLocation);
    }
    StringTokenizer tokenString =
        new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator);
    String pathIgnore = System.getProperty("java.home");
    if (pathIgnore == null) {
      pathIgnore = userClassUrls.iterator().next().toString();
    }

    List<URL> urls = new ArrayList<>();
    while (tokenString.hasMoreElements()) {
      String value = tokenString.nextToken();
      URL itemLocation = new File(value).toURI().toURL();
      if (!userClassUrls.contains(itemLocation)
          && itemLocation.toString().indexOf(pathIgnore) >= 0) {
        urls.add(itemLocation);
      }
    }
    URL[] urlArray = urls.toArray(new URL[urls.size()]);

    ClassLoader masterClassLoader = URLClassLoader.newInstance(urlArray, null);
    ClassLoader appClassLoader =
        URLClassLoader.newInstance(userClassUrls.toArray(new URL[0]), masterClassLoader);
    return appClassLoader;
  }
Example #12
0
  /** March through the classloaders to find one that can return urls. */
  @SuppressWarnings("resource")
  private URL[] getUrls() {
    Set<URL> urlSet = new HashSet<URL>();

    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    while (true) {
      if (cl == null) {
        return urlSet.toArray(new URL[urlSet.size()]);
      }

      if (!(cl instanceof URLClassLoader)) {
        cl = cl.getParent();
        continue;
      }

      URLClassLoader ucl = (URLClassLoader) cl;
      URL[] urls = ucl.getURLs();
      urlSet.addAll(Arrays.asList(urls));

      if (cl == ClassLoader.getSystemClassLoader()) {
        return urlSet.toArray(new URL[urlSet.size()]);
      }

      cl = cl.getParent();
    }
  }
Example #13
0
  public Object getPlugin(String protocol) throws InstantiationException, IllegalAccessException {
    String className = this.map.get(protocol);
    List<URL> urlList = new ArrayList<URL>();
    Class c1 = null;
    try {
      // load all class of plugin
      URL classesUrl = new URL("file:" + this.pluginDirPath + "/WEB-INF/classes/");
      urlList.add(classesUrl);

      // load lib of plugin
      File libDir = new File(this.pluginDirPath + "/WEB-INF/lib");
      for (File lib : libDir.listFiles()) {
        URL url = new URL("file:" + lib.getAbsolutePath());
        urlList.add(url);
      }

      URL[] urlArray = (URL[]) urlList.toArray(new URL[0]);
      URLClassLoader urlClassLoader1 =
          new URLClassLoader(urlArray, this.getClass().getClassLoader());
      c1 = urlClassLoader1.loadClass(className);
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return c1.newInstance();
  }
Example #14
0
  public static void main(String[] args) {
    if (System.getProperty("profile") != null) {
      System.out.println("Starting");
      System.setProperty("profile", String.valueOf(System.nanoTime()));
    }

    try {
      URL[] urls = getJarUrls();
      ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
      URLClassLoader loader;
      if (parentLoader != null) loader = new URLClassLoader(urls, parentLoader);
      else loader = new URLClassLoader(urls);

      Class beesClass = loader.loadClass(BEES_CLASS);
      Thread.currentThread().setContextClassLoader(loader);

      Method mainMethod = beesClass.getDeclaredMethod("main", String[].class);
      Object obj = mainMethod.invoke(null, new Object[] {args});
      int returnValue = 0;
      if (obj instanceof Integer) {
        returnValue = ((Integer) obj).intValue();
      }
      System.exit(returnValue);

    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
Example #15
0
 @SuppressWarnings("unchecked")
 private static void startPlugins() {
   logger.info("Loading available plugins");
   final Collection<File> botJars =
       FileUtils.listFiles(pluginsDirecotry, new String[] {"jar"}, false);
   for (File botJar : botJars) {
     try {
       JarFile jar = new JarFile(botJar);
       ZipEntry ze = jar.getEntry("plugin.yml");
       if (ze == null) throw new RuntimeException("Plugin has no plugin.yml file!");
       InputStream is = jar.getInputStream(ze);
       YAMLNode n = new YAMLNode(new Yaml().loadAs(is, Map.class), true);
       String mainClass = n.getString("mainClass");
       String name = n.getString("name");
       URLClassLoader loader =
           new URLClassLoader(new URL[] {botJar.toURI().toURL()}, Chatty.class.getClassLoader());
       Plugin plugin = loader.loadClass(mainClass).asSubclass(Plugin.class).newInstance();
       plugin.start();
       PLUGIN_INFO.put(name, new PluginInfo(name, plugin, n));
       logger.info("Loaded plugin '{}'", name);
     } catch (Exception e) {
       logger.error("Failed to load plugin from {}", botJar.getName());
       e.printStackTrace();
     }
   }
   logger.info("Loaded {} plugin(s)", PLUGIN_INFO.size());
 }
Example #16
0
 protected static boolean addToClasspath(String jar) {
   Method method;
   URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
   URL[] urls = sysLoader.getURLs();
   log0(lvl, "before adding to classpath: " + jar);
   for (int i = 0; i < urls.length; i++) {
     log0(lvl, "%d: %s", i, urls[i]);
   }
   Class sysclass = URLClassLoader.class;
   try {
     jar = FileManager.slashify(new File(jar).getAbsolutePath(), false);
     if (Settings.isWindows()) {
       jar = "/" + jar;
     }
     URL u = (new URI("file", jar, null)).toURL();
     method = sysclass.getDeclaredMethod("addURL", new Class[] {URL.class});
     method.setAccessible(true);
     method.invoke(sysLoader, new Object[] {u});
   } catch (Exception ex) {
     log0(-1, ex.getMessage());
     return false;
   }
   urls = sysLoader.getURLs();
   log0(lvl, "after adding to classpath");
   for (int i = 0; i < urls.length; i++) {
     log0(lvl, "%d: %s", i, urls[i]);
   }
   return true;
 }
  private static String getMainClass(URL jar) {
    URL[] jarURLs1 = {jar};
    URLClassLoader classLoader = new URLClassLoader(jarURLs1);
    Enumeration<URL> resources;

    try {
      // Each plugin .jar file has to contain a resource named "plugin"
      // which should contain the name of the main plugin class.
      resources = classLoader.getResources("plugin");

      if (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        char[] name;

        // Determine the plugin main class name from the contents of
        // the plugin file.
        try (InputStreamReader in = new InputStreamReader(url.openStream())) {
          name = new char[512];
          in.read(name);
        }

        return new String(name).trim();
      }
    } catch (IOException e) {
      LOGGER.error("Can't load plugin resources", e);
    }

    return null;
  }
Example #18
0
  public void invoke(Request request, Response response) throws IOException, ServletException {

    String servletName = ((HttpServletRequest) request).getRequestURI();
    servletName = servletName.substring(servletName.lastIndexOf("/") + 1);
    URLClassLoader loader = null;
    try {
      URL[] urls = new URL[1];
      URLStreamHandler streamHandler = null;
      File classPath = new File(WEB_ROOT);
      String repository =
          (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
      urls[0] = new URL(null, repository, streamHandler);
      loader = new URLClassLoader(urls);
    } catch (IOException e) {
      System.out.println(e.toString());
    }
    Class myClass = null;
    try {
      myClass = loader.loadClass(servletName);
    } catch (ClassNotFoundException e) {
      System.out.println(e.toString());
    }

    Servlet servlet = null;

    try {
      servlet = (Servlet) myClass.newInstance();
      servlet.service((HttpServletRequest) request, (HttpServletResponse) response);
    } catch (Exception e) {
      System.out.println(e.toString());
    } catch (Throwable e) {
      System.out.println(e.toString());
    }
  }
Example #19
0
 @SuppressWarnings({"rawtypes", "unchecked", "resource"})
 @Override
 public Object createExecutableExtension(String propertyName) throws CoreException {
   try {
     String className = attributes.get(propertyName);
     IProject project = getProject();
     IJavaProject javaProject = JavaCore.create(project);
     String[] classPathEntries = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
     List<URL> urlList = new ArrayList<URL>();
     for (int i = 0; i < classPathEntries.length; i++) {
       String entry = classPathEntries[i];
       IPath path = new Path(entry);
       URL url = path.toFile().toURI().toURL();
       urlList.add(url);
     }
     ClassLoader parentClassLoader = javaProject.getClass().getClassLoader();
     URL[] urls = (URL[]) urlList.toArray(new URL[urlList.size()]);
     URLClassLoader classLoader = new URLClassLoader(urls, parentClassLoader);
     ClassLoader cl = classLoader.getParent();
     Class clazz = classLoader.loadClass(className);
     return clazz.getConstructor().newInstance();
   } catch (Exception ex) {
     ex.printStackTrace();
     throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ex.getMessage()));
   }
 }
Example #20
0
  public static void loadJARs(Iterable<Path> jars) {
    ClassLoader cl = IoUtil.class.getClassLoader();
    if (!(cl instanceof URLClassLoader)) {
      throw noAddURL("Not loaded by URLClassLoader", null);
    }

    @SuppressWarnings("resource") // Leave open so classes can be loaded.
    URLClassLoader urlClassLoader = (URLClassLoader) cl;

    Method addURL;
    try {
      addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
      addURL.setAccessible(true);
    } catch (SecurityException | NoSuchMethodException e) {
      throw noAddURL("Method addURL not available", e);
    }

    Set<URL> have = Sets.newHashSet(Arrays.asList(urlClassLoader.getURLs()));
    for (Path path : jars) {
      try {
        URL url = path.toUri().toURL();
        if (have.add(url)) {
          addURL.invoke(cl, url);
        }
      } catch (MalformedURLException | IllegalArgumentException | IllegalAccessException e) {
        throw noAddURL("addURL " + path + " failed", e);
      } catch (InvocationTargetException e) {
        throw noAddURL("addURL " + path + " failed", e.getCause());
      }
    }
  }
Example #21
0
  /**
   * Gets the library path name.
   *
   * @param containingJarName the containing jar name
   * @return the library path name
   */
  public String getLibraryPathName(final String containingJarName) {

    String result = null;
    final URLClassLoader sysLoader = getURLClassLoader();

    /* Recherche répertoire lib */
    final String startClass = ClasspathBooter.class.getName().replace('.', '/');
    if (sysLoader != null) {
      final URL startClassUrl = sysLoader.getResource(startClass + SUFFIX_CLASS);
      if (startClassUrl != null) {
        final String path = startClassUrl.getPath();
        if (!isEmpty(path) && !isEmpty(containingJarName)) { // Ne
          if (path.matches(".*" + containingJarName + ".*")) {
            result = path;
            int p = result.indexOf("!");
            if (p != -1) {
              result = result.substring(0, p);
            }
            p = result.lastIndexOf("/");
            result = path.substring(0, p + 1);
          }
        }
      }
    }

    return result;
  }
Example #22
0
 @SuppressWarnings("resource")
 private InitStep loadInitStep(Path jar) {
   try {
     URLClassLoader pluginLoader =
         new URLClassLoader(
             new URL[] {jar.toUri().toURL()}, InitPluginStepsLoader.class.getClassLoader());
     try (JarFile jarFile = new JarFile(jar.toFile())) {
       Attributes jarFileAttributes = jarFile.getManifest().getMainAttributes();
       String initClassName = jarFileAttributes.getValue("Gerrit-InitStep");
       if (initClassName == null) {
         return null;
       }
       @SuppressWarnings("unchecked")
       Class<? extends InitStep> initStepClass =
           (Class<? extends InitStep>) pluginLoader.loadClass(initClassName);
       return getPluginInjector(jar).getInstance(initStepClass);
     } catch (ClassCastException e) {
       ui.message(
           "WARN: InitStep from plugin %s does not implement %s (Exception: %s)\n",
           jar.getFileName(), InitStep.class.getName(), e.getMessage());
       return null;
     } catch (NoClassDefFoundError e) {
       ui.message(
           "WARN: Failed to run InitStep from plugin %s (Missing class: %s)\n",
           jar.getFileName(), e.getMessage());
       return null;
     }
   } catch (Exception e) {
     ui.message(
         "WARN: Cannot load and get plugin init step for %s (Exception: %s)\n",
         jar, e.getMessage());
     return null;
   }
 }
Example #23
0
  private static void loadJar(String jar) {
    System.out.println("start load from " + jar);
    try {
      URL url = new URL(jar);
      URLClassLoader loader = new URLClassLoader(new URL[] {url});

      Class<?> c = loader.loadClass("ny.test.TestPrint");

      // c.getm

      Object o = c.newInstance();
      ((TestJni) o).testJniPrint("test");

      loader.close();

    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InstantiationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 /**
  * Builds a {@link java.util.Vector} containing Strings which each name a file who's name matches
  * the pattern set by setPattern(String). The classpath is searched recursively, so use with
  * caution.
  *
  * @return Vector<String> containing matching filenames
  */
 public Vector<String> findMatches() {
   Vector<String> matches = new Vector<String>();
   URLClassLoader cl = getURLClassLoader();
   if (cl == null) {
     throw new XWorkException("unable to attain an URLClassLoader");
   }
   URL[] parentUrls = cl.getURLs();
   compiledPattern = (int[]) patternMatcher.compilePattern(pattern);
   for (URL url : parentUrls) {
     if (!"file".equals(url.getProtocol())) {
       continue;
     }
     URI entryURI;
     try {
       entryURI = url.toURI();
     } catch (URISyntaxException e) {
       continue;
     }
     File entry = new File(entryURI);
     Vector<String> results = checkEntries(entry.list(), entry, "");
     if (results != null) {
       matches.addAll(results);
     }
   }
   return matches;
 }
 /** Maybe connect, if not keep track of the problem. */
 private synchronized void tryToConnect() {
   if (connected || exception != null) {
     return;
   }
   try {
     URLClassLoader l;
     String cnb = url.getHost();
     if (cnb.isEmpty()) {
       l = globalClassLoader.get();
     } else {
       l = classLoaderMap.get().get(cnb);
       if (l == null) {
         throw new IOException("no loader for " + cnb);
       }
     }
     String path = url.getPath().substring(1);
     URL u = l.getResource(path);
     if (u == null) {
       throw new FileNotFoundException(path + " in " + Arrays.toString(l.getURLs()));
     }
     real = u.openConnection();
     real.connect();
     connected = true;
   } catch (IOException ioe) {
     exception = ioe;
   }
 }
Example #26
0
  public HashMap<String, Class<?>> loadServiceJar() {
    List<JarConfig> list_confi = loadConfig();
    HashMap<String, Class<?>> map = new HashMap<String, Class<?>>();
    URL[] url = new URL[list_confi.size()];
    for (int i = 0; i < url.length; ++i) {
      try {
        url[i] = new File(list_confi.get(i).getPath()).toURI().toURL();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      }
    }

    ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader();
    // First the load jar files delegate to application class loader, if not found
    // Using URL class loader as the second choice
    URLClassLoader classLoader = new URLClassLoader(url, parentClassLoader);

    for (int i = 0; i < list_confi.size(); ++i) {
      try {
        String Name = classLoader.loadClass(list_confi.get(i).getName()).getName();
        Class<?> cl = classLoader.loadClass(list_confi.get(i).getClName());
        map.put(Name, cl);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return map;
  }
Example #27
0
 protected List<URL> getResources(String relPath, ClassLoader... classLoaders) {
   List<URL> answer = new ArrayList<URL>();
   for (ClassLoader classLoader : classLoaders) {
     try {
       Enumeration<URL> resources = classLoader.getResources(relPath);
       while (resources.hasMoreElements()) {
         URL url = resources.nextElement();
         if (url != null) {
           answer.add(url);
         }
       }
     } catch (IOException e) {
       LOG.warn(
           "Failed to load resources for path "
               + relPath
               + " from class loader "
               + classLoader
               + ". Reason:  "
               + e,
           e);
     }
     // Lets add all the parent class loaders...
     if (classLoader instanceof URLClassLoader) {
       URLClassLoader loader = (URLClassLoader) classLoader;
       answer.addAll(Arrays.asList(loader.getURLs()));
     }
   }
   return answer;
 }
Example #28
0
  public static void main(String[] args) throws Exception {
    String rt = "\r\n";
    String src =
        "package com.bjsxt.proxy;"
            + rt
            + "public class TankTimeProxy implements Moveable {"
            + rt
            + "    public TankTimeProxy(Moveable t) {"
            + rt
            + "        super();"
            + rt
            + "        this.t = t;"
            + rt
            + "    }"
            + rt
            + "    Moveable t;"
            + rt
            + "    @Override"
            + rt
            + "    public void move() {"
            + rt
            + "        long start = System.currentTimeMillis();"
            + rt
            + "        System.out.println(\"starttime:\" + start);"
            + rt
            + "        t.move();"
            + rt
            + "        long end = System.currentTimeMillis();"
            + rt
            + "        System.out.println(\"time:\" + (end-start));"
            + rt
            + "    }"
            + rt
            + "}";
    String fileName = System.getProperty("user.dir") + "/src/com/bjsxt/proxy/TankTimeProxy.java";
    File f = new File(fileName);
    FileWriter fw = new FileWriter(f);
    fw.write(src);
    fw.flush();
    fw.close();

    // compile
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
    Iterable units = fileMgr.getJavaFileObjects(fileName);
    CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units);
    t.call();
    fileMgr.close();

    // load into memory and create an instance
    URL[] urls = new URL[] {new URL("file:/" + System.getProperty("user.dir") + "/src")};
    URLClassLoader ul = new URLClassLoader(urls);
    Class c = ul.loadClass("com.bjsxt.proxy.TankTimeProxy");
    System.out.println(c);

    Constructor ctr = c.getConstructor(Moveable.class);
    Moveable m = (Moveable) ctr.newInstance(new Tank());
    m.move();
  }
Example #29
0
 public static DatabaseBridge loadBridge(File file) {
   DatabaseBridge theBridge = null;
   PluginDescriptionFile bridgeDescription = null;
   try {
     // Load the jar
     JarFile jar = new JarFile(file);
     // Load the info about the bridge
     JarEntry entry = jar.getJarEntry("bridge.yml");
     InputStream stream = jar.getInputStream(entry);
     bridgeDescription = new PluginDescriptionFile(stream);
     // Get the main class
     String main = bridgeDescription.getMain();
     try {
       URL test =
           new URL(
               "http://guardian.nekotech.tk:8080/job/Guardian-MySQL/Guardian-MySQL-RB/api/json");
       HttpURLConnection connection = (HttpURLConnection) test.openConnection();
       connection.connect();
       JSONObject object =
           (JSONObject) new JSONParser().parse(new InputStreamReader(connection.getInputStream()));
       String version = bridgeDescription.getVersion();
       if (!version.equals("Unknown")
           && Integer.parseInt(version) < Integer.parseInt(object.get("number").toString())) {
         BukkitUtils.info("Guardian-Bridge is out of date, please download the latest");
       }
     } catch (Exception ex) {
       BukkitUtils.severe("Error occurred while checking if Guardian is up to date", ex);
     }
     // Clean it all up
     stream.close();
     jar.close();
     // Get a new classloader
     URLClassLoader classLoader =
         new URLClassLoader(
             new URL[] {file.toURI().toURL()}, DatabaseBridge.class.getClassLoader());
     // Load the class
     Class<?> clazz = classLoader.loadClass(main);
     // Construct it
     Object object = clazz.newInstance();
     // Verify it
     if (!(object instanceof DatabaseBridge)) {
       return null;
     }
     // Its all good
     theBridge = (DatabaseBridge) object;
   } catch (FileNotFoundException ex) {
     BukkitUtils.severe("Database bridge does not contain a valid bridge.yml");
   } catch (ZipException ex) {
     BukkitUtils.severe("The database bridge appears to be an invalid jar file");
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   Guardian.getInstance().getConf().bridgeDescription = bridgeDescription;
   BukkitUtils.info(
       "Loading " + bridgeDescription.getName() + " v" + bridgeDescription.getVersion());
   // Lets return it
   return theBridge;
 }
  /**
   * @see
   *     org.overlord.commons.dev.server.discovery.IModuleDiscoveryStrategy#discover(org.overlord.commons.dev.server.discovery.ModuleDiscoveryContext)
   */
  @Override
  public DevServerModule discover(ModuleDiscoveryContext context) {
    URLClassLoader urlCL = (URLClassLoader) getClass().getClassLoader();
    TreeSet<URL> sortedURLs =
        new TreeSet<URL>(
            new Comparator<URL>() {
              @Override
              public int compare(URL o1, URL o2) {
                return o1.toExternalForm().compareTo(o2.toExternalForm());
              }
            });
    sortedURLs.addAll(Arrays.asList(urlCL.getURLs()));

    String moduleUrl = null;

    // Look for something that looks like a maven path
    String groupIdAsPath = groupId.replace('.', '/');
    for (URL url : sortedURLs) {
      String urlstr = url.toExternalForm();
      if (urlstr.contains(groupIdAsPath)
          && urlstr.contains("/" + artifactId + "-")) { // $NON-NLS-1$ //$NON-NLS-2$
        moduleUrl = urlstr;
        break;
      }
    }

    if (moduleUrl == null) return null;

    debug("Module URL: " + moduleUrl); // $NON-NLS-1$

    try {
      String pathToWar = moduleUrl.replace("-classes.jar", ".war"); // $NON-NLS-1$ //$NON-NLS-2$
      URL warUrl = new URL(pathToWar);
      File war = new File(warUrl.toURI());
      debug("WAR: " + war); // $NON-NLS-1$

      if (war.isFile()) {
        File workDir = new File(context.getTargetDir(), war.getName());
        debug("Work Dir: " + workDir); // $NON-NLS-1$

        DevServerModule module = new DevServerModule();
        module.setInIDE(false);
        module.setWorkDir(workDir);
        module.setModuleDir(workDir);
        module.clean();
        workDir.mkdirs();
        try {
          org.overlord.commons.dev.server.util.ArchiveUtils.unpackToWorkDir(war, workDir);
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
        return module;
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return null;
  }