/**
  * Indicates if a class is recompilable. Recompilable means, that the classloader will try to
  * locate a groovy source file for this class and then compile it again, adding the resulting
  * class as entry to the cache. Giving null as class is like a recompilation, so the method should
  * always return true here. Only classes that are implementing GroovyObject are compilable and
  * only if the timestamp in the class is lower than Long.MAX_VALUE.
  *
  * <p>NOTE: First the parent loaders will be asked and only if they don't return a class the
  * recompilation will happen. Recompilation also only happen if the source file is newer.
  *
  * @param cls the class to be tested. If null the method should return true
  * @return true if the class should be compiled again
  * @see #isSourceNewer(URL, Class)
  */
 protected boolean isRecompilable(Class cls) {
   if (cls == null) return true;
   if (cls.getClassLoader() == this) return false;
   if (recompile == null && !config.getRecompileGroovySource()) return false;
   if (recompile != null && !recompile) return false;
   if (!GroovyObject.class.isAssignableFrom(cls)) return false;
   long timestamp = getTimeStamp(cls);
   if (timestamp == Long.MAX_VALUE) return false;
   return true;
 }
示例#2
0
  public static void main(String[] args) throws Exception {
    Class thisClass = MethodResultTest.class;
    Class exoticClass = Exotic.class;
    String exoticClassName = Exotic.class.getName();
    ClassLoader testClassLoader = thisClass.getClassLoader();
    if (!(testClassLoader instanceof URLClassLoader)) {
      System.out.println("TEST INVALID: Not loaded by a " + "URLClassLoader: " + testClassLoader);
      System.exit(1);
    }

    URLClassLoader tcl = (URLClassLoader) testClassLoader;
    URL[] urls = tcl.getURLs();
    ClassLoader shadowLoader =
        new ShadowLoader(
            urls,
            testClassLoader,
            new String[] {
              exoticClassName, ExoticMBeanInfo.class.getName(), ExoticException.class.getName()
            });
    Class cl = shadowLoader.loadClass(exoticClassName);
    if (cl == exoticClass) {
      System.out.println(
          "TEST INVALID: Shadow class loader loaded " + "same class as test class loader");
      System.exit(1);
    }
    Thread.currentThread().setContextClassLoader(shadowLoader);

    ObjectName on = new ObjectName("a:b=c");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    mbs.createMBean(Thing.class.getName(), on);

    final String[] protos = {"rmi", "iiop", "jmxmp"};

    boolean ok = true;
    for (int i = 0; i < protos.length; i++) {
      try {
        ok &= test(protos[i], mbs, on);
        System.out.println();
      } catch (Exception e) {
        System.out.println("TEST FAILED WITH EXCEPTION:");
        e.printStackTrace(System.out);
        ok = false;
      }
    }

    if (ok) System.out.println("Test passed");
    else {
      System.out.println("TEST FAILED");
      System.exit(1);
    }
  }
示例#3
0
  /** 获取类的class文件位置的URL。这个方法是本类最基础的方法,供其它方法调用。 */
  public URL getClassLocationURL(final Class cls) {
    if (cls == null) {
      throw new IllegalArgumentException("class that input is null");
    }
    URL result = null;
    final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
    final ProtectionDomain pd = cls.getProtectionDomain();
    if (pd != null) {
      final CodeSource cs = pd.getCodeSource();
      if (cs != null) {
        result = cs.getLocation();
      }
      if (result != null) {
        if ("file".equals(result.getProtocol())) {
          try {
            if (result.toExternalForm().endsWith(".jar")
                || result.toExternalForm().endsWith(".zip")) {
              result =
                  new URL(
                      "jar:".concat(result.toExternalForm()).concat("!/").concat(clsAsResource));
            } else if (new File(result.getFile()).isDirectory()) {
              result = new URL(result, clsAsResource);
            }
          } catch (MalformedURLException ignore) {
          }
        }
      }
    }

    if (result == null) {
      final ClassLoader clsLoader = cls.getClassLoader();
      result =
          clsLoader != null
              ? clsLoader.getResource(clsAsResource)
              : ClassLoader.getSystemResource(clsAsResource);
    }
    return result;
  }
  static void initializePlugins(@Nullable StartupProgress progress) {
    configureExtensions();

    final IdeaPluginDescriptorImpl[] pluginDescriptors = loadDescriptors(progress);

    final Class callerClass = ReflectionUtil.findCallerClass(1);
    assert callerClass != null;
    final ClassLoader parentLoader = callerClass.getClassLoader();

    final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>();
    final HashMap<String, String> disabledPluginNames = new HashMap<String, String>();
    for (IdeaPluginDescriptorImpl descriptor : pluginDescriptors) {
      if (descriptor.getPluginId().getIdString().equals(CORE_PLUGIN_ID)) {
        final List<String> modules = descriptor.getModules();
        if (modules != null) {
          ourAvailableModules.addAll(modules);
        }
      }

      if (!shouldSkipPlugin(descriptor, pluginDescriptors)) {
        result.add(descriptor);
      } else {
        descriptor.setEnabled(false);
        disabledPluginNames.put(descriptor.getPluginId().getIdString(), descriptor.getName());
        initClassLoader(parentLoader, descriptor);
      }
    }

    prepareLoadingPluginsErrorMessage(filterBadPlugins(result, disabledPluginNames));

    final Map<PluginId, IdeaPluginDescriptorImpl> idToDescriptorMap =
        new HashMap<PluginId, IdeaPluginDescriptorImpl>();
    for (final IdeaPluginDescriptorImpl descriptor : result) {
      idToDescriptorMap.put(descriptor.getPluginId(), descriptor);
    }

    final IdeaPluginDescriptor corePluginDescriptor =
        idToDescriptorMap.get(PluginId.getId(CORE_PLUGIN_ID));
    assert corePluginDescriptor != null
        : CORE_PLUGIN_ID
            + " not found; platform prefix is "
            + System.getProperty(PlatformUtilsCore.PLATFORM_PREFIX_KEY);
    for (IdeaPluginDescriptorImpl descriptor : result) {
      if (descriptor != corePluginDescriptor) {
        descriptor.insertDependency(corePluginDescriptor);
      }
    }

    mergeOptionalConfigs(idToDescriptorMap);

    // sort descriptors according to plugin dependencies
    Collections.sort(result, getPluginDescriptorComparator(idToDescriptorMap));

    for (int i = 0; i < result.size(); i++) {
      ourId2Index.put(result.get(i).getPluginId(), i);
    }

    int i = 0;
    for (final IdeaPluginDescriptorImpl pluginDescriptor : result) {
      if (pluginDescriptor.getPluginId().getIdString().equals(CORE_PLUGIN_ID)
          || pluginDescriptor.isUseCoreClassLoader()) {
        pluginDescriptor.setLoader(parentLoader, true);
      } else {
        final List<File> classPath = pluginDescriptor.getClassPath();
        final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
        final ClassLoader[] parentLoaders = getParentLoaders(idToDescriptorMap, dependentPluginIds);

        final ClassLoader pluginClassLoader =
            createPluginClassLoader(
                classPath.toArray(new File[classPath.size()]),
                parentLoaders.length > 0 ? parentLoaders : new ClassLoader[] {parentLoader},
                pluginDescriptor);
        pluginDescriptor.setLoader(pluginClassLoader, true);
      }

      pluginDescriptor.registerExtensions();
      if (progress != null) {
        progress.showProgress(
            "", PLUGINS_PROGRESS_MAX_VALUE + (i++ / (float) result.size()) * 0.35f);
      }
    }

    ourPlugins = pluginDescriptors;
  }
示例#5
0
 /**
  * Loads a resource relative to a specific class into a byte array.
  *
  * @param c Class (resource must come from same classloader)
  * @param sName Name of resource (relative path to class)
  * @return Byte array containing file in memory
  * @throws IOException If it doesn't exist or there is any other error loading
  */
 public static byte[] loadResource(Class c, String sName) throws IOException {
   return loadResource(
       c.getClassLoader(),
       "/" + c.getName().replace('.', '/').replaceFirst("/[^/]*$", "") + "/" + sName);
 }