/**
   * Adapts the source object to a view object.
   *
   * @param mapper An action that is invoked for each source object in the graph that is to be
   *     adapted. The action can influence how the source object is adapted via the provided {@link
   *     SourceObjectMapping}.
   */
  public <T, S> T adapt(
      Class<T> targetType, S sourceObject, Action<? super SourceObjectMapping> mapper) {
    if (sourceObject == null) {
      return null;
    }
    Class<? extends T> wrapperType = targetTypeProvider.getTargetType(targetType, sourceObject);
    DefaultSourceObjectMapping mapping =
        new DefaultSourceObjectMapping(sourceObject, targetType, wrapperType);
    mapper.execute(mapping);
    wrapperType = mapping.wrapperType.asSubclass(targetType);
    if (wrapperType.isInstance(sourceObject)) {
      return wrapperType.cast(sourceObject);
    }
    if (targetType.isEnum()) {
      return adaptToEnum(targetType, sourceObject);
    }

    MixInMethodInvoker mixInMethodInvoker = null;
    if (mapping.mixInType != null) {
      mixInMethodInvoker =
          new MixInMethodInvoker(
              mapping.mixInType, new AdaptingMethodInvoker(mapper, new ReflectionMethodInvoker()));
    }
    MethodInvoker overrideInvoker = chainInvokers(mixInMethodInvoker, mapping.overrideInvoker);
    Object proxy =
        Proxy.newProxyInstance(
            wrapperType.getClassLoader(),
            new Class<?>[] {wrapperType},
            new InvocationHandlerImpl(sourceObject, overrideInvoker, mapper));
    if (mixInMethodInvoker != null) {
      mixInMethodInvoker.setProxy(proxy);
    }
    return wrapperType.cast(proxy);
  }
 /**
  * Returns the per class aspect instance for the aspect with the given name for the perTarget
  * model
  *
  * @param name the name of the aspect
  * @param targetClass the targetClass class
  * @return the per class aspect instance
  */
 public static Object aspectOf(final String name, final Class targetClass) {
   try {
     Class aspectClass = Class.forName(name, false, targetClass.getClassLoader());
     return aspectOf(aspectClass, targetClass);
   } catch (ClassNotFoundException e) {
     // try to guess it from the system definitions if we have a uuid prefix
     String className =
         lookupAspectClassName(Thread.currentThread().getContextClassLoader(), name);
     if (className != null) {
       return aspectOf(className, targetClass);
     } else {
       throw new Error("Could not load aspect " + name + " from " + targetClass.getClassLoader());
     }
   }
 }
  /**
   * Create a default object of the given type. Prefers constructors with as few arguments as
   * possible. Creates an empty proxy for interfaces.
   *
   * @param type type to instantiate
   * @return default instance
   * @throws Exception if the default instance could not be created
   */
  private static Object instantiateType(Class<?> type) throws Exception {
    if (type.isPrimitive()) return Defaults.defaultValue(type);
    else if (type == Void.class) return null;
    else if (type.isArray()) return Array.newInstance(type, 0);
    else if (type.isInterface())
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          new Class[] {type},
          new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
              return null;
            }
          });

    // Take a constructor with as few params as possible
    Constructor constructor = type.getDeclaredConstructors()[0];
    for (Constructor<?> c : type.getDeclaredConstructors()) {
      if (c.getParameterTypes().length < constructor.getParameterTypes().length) constructor = c;
    }

    Object[] params = new Object[constructor.getParameterTypes().length];
    for (int i = 0; i < constructor.getParameterTypes().length; i++) {
      params[i] = instantiateType(constructor.getParameterTypes()[i]);
    }
    return constructor.newInstance(params);
  }
 protected ProxyListHandler(List<T> items, Class<T> type, Map<String, ProxyFilter> prop2Filter) {
   super(null, prop2Filter);
   this.items = Collections.unmodifiableList(items);
   this.type = type;
   ClassLoader cl = type.getClassLoader();
   this.proxy = Proxy.newProxyInstance(cl, new Class<?>[] {type}, this);
 }
 @Override
 public <T> T getService(Class<T> serviceClass) {
   //noinspection unchecked
   T service = (T) myServices.get(serviceClass);
   if (service == null) {
     final Iterator<T> iterator =
         ServiceLoader.load(serviceClass, serviceClass.getClassLoader()).iterator();
     if (!iterator.hasNext()) {
       throw new ServiceConfigurationError("Implementation for " + serviceClass + " not found");
     }
     service = iterator.next();
     if (iterator.hasNext()) {
       throw new ServiceConfigurationError(
           "More than one implementation for "
               + serviceClass
               + " found: "
               + service.getClass()
               + " and "
               + iterator.next().getClass());
     }
     myServices.putIfAbsent(serviceClass, service);
     //noinspection unchecked
     service = (T) myServices.get(serviceClass);
   }
   return service;
 }
 /**
  * Force initialization of the static members. As of Java 5, referencing a class doesn't force it
  * to initialize. Since this class requires that the classes be initialized to declare their
  * comparators, we force that initialization to happen.
  *
  * @param cls the class to initialize
  */
 private static void forceInit(Class<?> cls) {
   try {
     Class.forName(cls.getName(), true, cls.getClassLoader());
   } catch (ClassNotFoundException e) {
     throw new IllegalArgumentException("Can't initialize class " + cls, e);
   }
 }
  /**
   * There is a possible case that methods of particular object should be executed with classpath
   * different from the one implied by the current class' class loader. External system offers
   * {@link ParametersEnhancer#enhanceLocalProcessing(List)} method for defining that custom
   * classpath.
   *
   * <p>It's also possible that particular implementation of {@link ParametersEnhancer} is compiled
   * using dependency to classes which are provided by the {@link
   * ParametersEnhancer#enhanceLocalProcessing(List) expanded classpath}. E.g. a class <code>'A'
   * </code> might use method of class <code>'B'</code> and 'A' is located at the current
   * (system/plugin) classpath but <code>'B'</code> is not. We need to reload <code>'A'</code> using
   * its expanded classpath then, i.e. create new class loaded with that expanded classpath and load
   * <code>'A'</code> by it.
   *
   * <p>This method allows to do that.
   *
   * @param clazz custom classpath-aware class which instance should be created (is assumed to have
   *     a no-args constructor)
   * @param <T> target type
   * @return newly created instance of the given class loaded by custom classpath-aware loader
   * @throws IllegalAccessException as defined by reflection processing
   * @throws InstantiationException as defined by reflection processing
   * @throws NoSuchMethodException as defined by reflection processing
   * @throws InvocationTargetException as defined by reflection processing
   * @throws ClassNotFoundException as defined by reflection processing
   */
  @NotNull
  public static <T extends ParametersEnhancer> T reloadIfNecessary(@NotNull final Class<T> clazz)
      throws IllegalAccessException, InstantiationException, NoSuchMethodException,
          InvocationTargetException, ClassNotFoundException {
    T instance = clazz.newInstance();
    List<URL> urls = ContainerUtilRt.newArrayList();
    instance.enhanceLocalProcessing(urls);
    if (urls.isEmpty()) {
      return instance;
    }

    final ClassLoader baseLoader = clazz.getClassLoader();
    Method method = baseLoader.getClass().getMethod("getUrls");
    if (method != null) {
      //noinspection unchecked
      urls.addAll((Collection<? extends URL>) method.invoke(baseLoader));
    }
    UrlClassLoader loader =
        new UrlClassLoader(UrlClassLoader.build().urls(urls).parent(baseLoader.getParent())) {
          @Override
          protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            if (name.equals(clazz.getName())) {
              return super.loadClass(name, resolve);
            } else {
              try {
                return baseLoader.loadClass(name);
              } catch (ClassNotFoundException e) {
                return super.loadClass(name, resolve);
              }
            }
          }
        };
    //noinspection unchecked
    return (T) loader.loadClass(clazz.getName()).newInstance();
  }
  /**
   * Sets up the mocks defined in the given mock class.
   *
   * <p>If the type {@linkplain MockClass#realClass referred to} by the mock class is actually an
   * interface, then a {@linkplain #newEmptyProxy(ClassLoader, Class) new empty proxy} is created.
   *
   * @param mockClassOrInstance the mock class itself (given by its {@code Class} literal), or an
   *     instance of the mock class
   * @return the new proxy instance created for the mocked interface, or {@code null} otherwise
   * @throws IllegalArgumentException if a given mock class fails to specify the corresponding real
   *     class using the {@code @MockClass(realClass = ...)} annotation; or if a mock class defines
   *     a mock method for which no corresponding real method or constructor exists in the real
   *     class; or if the real method matching a mock method is {@code abstract}
   * @see #setUpMock(Class, Object)
   * @see #setUpMocks(Object...)
   * @see <a
   *     href="http://code.google.com/p/jmockit/source/browse/trunk/main/test/mockit/MockAnnotationsTest.java#696">
   *     Example</a>
   */
  public static <T> T setUpMock(Object mockClassOrInstance) {
    Class<?> mockClass;
    Object mock;

    if (mockClassOrInstance instanceof Class<?>) {
      mockClass = (Class<?>) mockClassOrInstance;
      mock = null;
    } else {
      mockClass = mockClassOrInstance.getClass();
      mock = mockClassOrInstance;
    }

    MockClassSetup setup = new MockClassSetup(mock, mockClass);
    Class<?> realClass = setup.getRealClass();
    T proxy = null;

    if (realClass.isInterface()) {
      //noinspection unchecked
      proxy = (T) newEmptyProxy(mockClass.getClassLoader(), realClass);
      setup.setRealClass(proxy.getClass());
    }

    setup.redefineMethods();

    return proxy;
  }
Beispiel #9
0
 public static Resource myres(Class<?> c) {
   ClassLoader cl = c.getClassLoader();
   if (cl instanceof Resource.ResClassLoader) {
     return (((Resource.ResClassLoader) cl).getres());
   } else {
     return (null);
   }
 }
  /**
   * Creates a new proxy with the specified URL. The returned object is a proxy with the interface
   * specified by api.
   *
   * <pre>
   * String url = "http://localhost:8080/ejb/hello");
   * HelloHome hello = (HelloHome) factory.create(HelloHome.class, url);
   * </pre>
   *
   * @param api the interface the proxy class needs to implement
   * @param url the URL where the client object is located.
   * @return a proxy to the object with the specified interface.
   */
  public Object create(Class api, String urlName, ClassLoader loader) throws MalformedURLException {
    URL url = new URL(urlName);

    HessianProxy handler = new HessianProxy(this, url);

    return Proxy.newProxyInstance(
        api.getClassLoader(), new Class[] {api, HessianRemoteObject.class}, handler);
  }
  /**
   * Create MBean for Object. Attempts to create an MBean for the object by searching the package
   * and class name space. For example an object of the type
   *
   * <PRE>
   *   class com.acme.MyClass extends com.acme.util.BaseClass
   * </PRE>
   *
   * Then this method would look for the following classes:
   *
   * <UL>
   *   <LI>com.acme.MyClassMBean
   *   <LI>com.acme.jmx.MyClassMBean
   *   <LI>com.acme.util.BaseClassMBean
   *   <LI>com.acme.util.jmx.BaseClassMBean
   * </UL>
   *
   * @param o The object
   * @return A new instance of an MBean for the object or null.
   */
  public static ModelMBean mbeanFor(Object o) {
    try {
      Class oClass = o.getClass();
      ClassLoader loader = oClass.getClassLoader();

      ModelMBean mbean = null;
      boolean jmx = false;
      Class[] interfaces = null;
      int i = 0;

      while (mbean == null && oClass != null) {
        Class focus = interfaces == null ? oClass : interfaces[i];
        String pName = focus.getPackage().getName();
        String cName = focus.getName().substring(pName.length() + 1);
        String mName = pName + (jmx ? ".jmx." : ".") + cName + "MBean";

        try {
          Class mClass = loader.loadClass(mName);
          if (log.isTraceEnabled()) log.trace("mbeanFor " + o + " mClass=" + mClass);
          mbean = (ModelMBean) mClass.newInstance();
          mbean.setManagedResource(o, "objectReference");
          if (log.isDebugEnabled()) log.debug("mbeanFor " + o + " is " + mbean);
          return mbean;
        } catch (ClassNotFoundException e) {
          if (e.toString().endsWith("MBean")) {
            if (log.isTraceEnabled()) log.trace(e.toString());
          } else log.warn(LogSupport.EXCEPTION, e);
        } catch (Error e) {
          log.warn(LogSupport.EXCEPTION, e);
          mbean = null;
        } catch (Exception e) {
          log.warn(LogSupport.EXCEPTION, e);
          mbean = null;
        }

        if (jmx) {
          if (interfaces != null) {
            i++;
            if (i >= interfaces.length) {
              interfaces = null;
              oClass = oClass.getSuperclass();
            }
          } else {
            interfaces = oClass.getInterfaces();
            i = 0;
            if (interfaces == null || interfaces.length == 0) {
              interfaces = null;
              oClass = oClass.getSuperclass();
            }
          }
        }
        jmx = !jmx;
      }
    } catch (Exception e) {
      LogSupport.ignore(log, e);
    }
    return null;
  }
 @Test
 public void testLoading() throws Exception {
   Class<?> type = classLoader.loadClass(Foo.class.getName());
   assertThat(type.getClassLoader(), is(classLoader));
   assertEquals(classLoader.loadClass(Foo.class.getName()), type);
   assertNotEquals(Foo.class, type);
   assertThat(type.getPackage(), notNullValue(Package.class));
   assertThat(type.getPackage(), is(Foo.class.getPackage()));
 }
 private static List<JavaSourceTransformer> getSourceTransformers() {
   final Class<JavaSourceTransformer> transformerClass = JavaSourceTransformer.class;
   final ServiceLoader<JavaSourceTransformer> loader =
       ServiceLoader.load(transformerClass, transformerClass.getClassLoader());
   final List<JavaSourceTransformer> transformers = new ArrayList<JavaSourceTransformer>();
   for (JavaSourceTransformer t : loader) {
     transformers.add(t);
   }
   return transformers;
 }
 /**
  * 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;
 }
Beispiel #15
0
 private static ClassLoader getClassLoader(final Class clazz) {
   if (System.getSecurityManager() == null) return clazz.getClassLoader();
   return (ClassLoader)
       AccessController.doPrivileged(
           new PrivilegedAction() {
             public Object run() {
               return clazz.getClassLoader();
             }
           });
 }
  private void populateInternalMap(Object bean, boolean includeSuperClass) {
    Class klass = bean.getClass();

    // If klass.getSuperClass is System class then includeSuperClass = false;

    if (klass.getClassLoader() == null) {
      includeSuperClass = false;
    }

    Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
      try {
        Method method = methods[i];
        String name = method.getName();
        String key = "";
        if (name.startsWith("get")) {
          key = name.substring(3);
        } else if (name.startsWith("is")) {
          key = name.substring(2);
        }
        if (key.length() > 0
            && Character.isUpperCase(key.charAt(0))
            && method.getParameterTypes().length == 0) {
          if (key.length() == 1) {
            key = key.toLowerCase();
          } else if (!Character.isUpperCase(key.charAt(1))) {
            key = key.substring(0, 1).toLowerCase() + key.substring(1);
          }

          Object result = method.invoke(bean, (Object[]) null);
          if (result == null) {
            map.put(key, NULL);
          } else if (result.getClass().isArray()) {
            map.put(key, new JSONArray(result, includeSuperClass));
          } else if (result instanceof Collection) { // List or Set
            map.put(key, new JSONArray((Collection) result, includeSuperClass));
          } else if (result instanceof Map) {
            map.put(key, new JSONObject((Map) result, includeSuperClass));
          } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper
            map.put(key, result);
          } else {
            if (result.getClass().getPackage().getName().startsWith("java")
                || result.getClass().getClassLoader() == null) {
              map.put(key, result.toString());
            } else { // User defined Objects
              map.put(key, new JSONObject(result, includeSuperClass));
            }
          }
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
  private boolean findAllTestedAndInjectableFieldsInTestClassHierarchy(
      @NotNull Class<?> testClass) {
    Class<?> classWithFields = testClass;

    do {
      Field[] fields = classWithFields.getDeclaredFields();
      findTestedAndInjectableFields(fields);
      classWithFields = classWithFields.getSuperclass();
    } while (classWithFields.getClassLoader() != null);

    return !testedFields.isEmpty();
  }
Beispiel #18
0
 /**
  * get class loader
  *
  * @param cls
  * @return class loader
  */
 public static ClassLoader getClassLoader(Class<?> cls) {
   ClassLoader cl = null;
   try {
     cl = Thread.currentThread().getContextClassLoader();
   } catch (Throwable ex) {
     // Cannot access thread context ClassLoader - falling back to system class loader...
   }
   if (cl == null) {
     // No thread context class loader -> use class loader of this class.
     cl = cls.getClassLoader();
   }
   return cl;
 }
  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);
    }
  }
 @Override
 public <T> Iterable<T> getExtensions(Class<T> extensionClass) {
   List<?> cached = myExtensions.get(extensionClass);
   if (cached == null) {
     final ServiceLoader<T> loader =
         ServiceLoader.load(extensionClass, extensionClass.getClassLoader());
     List<T> extensions = new ArrayList<T>();
     for (T t : loader) {
       extensions.add(t);
     }
     myExtensions.putIfAbsent(extensionClass, extensions);
     cached = myExtensions.get(extensionClass);
   }
   //noinspection unchecked
   return (List<T>) cached;
 }
  private static Set<MethodInfo> getGetterMethodInfo(Class<?> clazz) {

    Set<MethodInfo> methodInfos = METHOD_MAP.get(clazz);

    if (methodInfos == null) {

      methodInfos = new HashSet<MethodInfo>();

      boolean includeSuperClass = clazz.getClassLoader() != null;

      Method[] methods = includeSuperClass ? clazz.getMethods() : clazz.getDeclaredMethods();

      for (Method method : methods) {
        try {
          if (Modifier.isPublic(method.getModifiers())) {
            String name = method.getName();
            String key = "";
            if (name.startsWith("get")) {
              if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
                key = "";
              } else {
                key = name.substring(3);
              }
            } else if (name.startsWith("is")) {
              key = name.substring(2);
            }
            if (key.length() > 0
                && Character.isUpperCase(key.charAt(0))
                && method.getParameterTypes().length == 0) {
              if (key.length() == 1) {
                key = key.toLowerCase();
              } else if (!Character.isUpperCase(key.charAt(1))) {
                key = key.substring(0, 1).toLowerCase() + key.substring(1);
              }
              methodInfos.add(new MethodInfo(key, method));
            }
          }
        } catch (Exception ignored) {
        }
      }

      METHOD_MAP.putIfAbsent(clazz, methodInfos);
    }

    return methodInfos;
  }
Beispiel #22
0
  private void populateMap(Object bean) {
    final Class klass = bean.getClass();

    // If klass is a System class then set includeSuperClass to false.

    final boolean includeSuperClass = klass.getClassLoader() != null;

    final Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods();
    for (final Method method : methods) {
      try {
        if (Modifier.isPublic(method.getModifiers())) {
          final String name = method.getName();
          String key = "";
          if (name.startsWith("get")) {
            if (name.equals("getClass") || name.equals("getDeclaringClass")) {
              key = "";
            } else {
              key = name.substring(3);
            }
          } else if (name.startsWith("is")) {
            key = name.substring(2);
          }
          if ((key.length() > 0)
              && Character.isUpperCase(key.charAt(0))
              && (method.getParameterTypes().length == 0)) {
            if (key.length() == 1) {
              key = key.toLowerCase();
            } else if (!Character.isUpperCase(key.charAt(1))) {
              key = key.substring(0, 1).toLowerCase() + key.substring(1);
            }

            final Object result = method.invoke(bean, (Object[]) null);
            if (result != null) {
              this.map.put(key, JSONObject.wrap(result));
            }
          }
        }
      } catch (final Exception ignore) {
      }
    }
  }
  /**
   * Will inject this bundle context code inside the dotCMS context
   *
   * @param className a reference class inside this bundle jar
   * @param reload if a redefinition should be done or not
   * @throws Exception
   */
  private void injectContext(String className, Boolean reload) throws Exception {

    // Get the location of this OSGI bundle jar source code using a known class inside this bundle
    Class clazz = Class.forName(className, false, getFelixClassLoader());
    URL classURL = clazz.getProtectionDomain().getCodeSource().getLocation();

    // Verify if we have our UrlOsgiClassLoader on the main class loaders
    UrlOsgiClassLoader urlOsgiClassLoader =
        activatorUtil.findCustomURLLoader(ClassLoader.getSystemClassLoader());
    if (urlOsgiClassLoader != null) {

      if (!urlOsgiClassLoader.contains(
          classURL)) { // Verify if this URL is already in our custom ClassLoader
        urlOsgiClassLoader.addURL(classURL);
      }

      // The ClassLoader and the class content is already in the system ClassLoader, so we need to
      // reload the jar contents
      if (reload) {
        urlOsgiClassLoader.reload(classURL);
      }
    } else {

      // Getting the reference of a known class in order to get the base/main class loader
      Class baseClass = getContextClassLoader().loadClass("org.quartz.Job");
      // Creates our custom class loader in order to use it to inject the class code inside dotcms
      // context
      urlOsgiClassLoader = new UrlOsgiClassLoader(classURL, baseClass.getClassLoader());

      // We may have classes we want to override from e beginning, for example a custom
      // implementation of a dotCMS class
      if (reload) {
        urlOsgiClassLoader.reload(classURL);
      }

      // Linking our custom class loader with the dotCMS class loaders hierarchy.
      urlOsgiClassLoader.linkClassLoaders();
    }
  }
Beispiel #24
0
 public static Result routeAndCall(
     Class<? extends Routes> router, FakeRequest fakeRequest, long timeout) {
   try {
     Routes routes =
         (Routes)
             router
                 .getClassLoader()
                 .loadClass(router.getName() + "$")
                 .getDeclaredField("MODULE$")
                 .get(null);
     if (routes.routes().isDefinedAt(fakeRequest.getWrappedRequest())) {
       return invokeHandler(
           routes.routes().apply(fakeRequest.getWrappedRequest()), fakeRequest, timeout);
     } else {
       return null;
     }
   } catch (RuntimeException e) {
     throw e;
   } catch (Throwable t) {
     throw new RuntimeException(t);
   }
 }
Beispiel #25
0
    @Override
    public ConfigBeanProxy compute(final Class<?> proxyType) throws ComputationErrorException {

      ClassLoader cl;
      if (System.getSecurityManager() != null) {
        cl =
            AccessController.doPrivileged(
                new PrivilegedAction<ClassLoader>() {
                  @Override
                  public ClassLoader run() {
                    return proxyType.getClassLoader();
                  }
                });
      } else {
        cl = proxyType.getClassLoader();
      }

      ConfigBeanProxy retVal =
          (ConfigBeanProxy) Proxy.newProxyInstance(cl, new Class[] {proxyType}, dom);

      return retVal;
    }
  /**
   * Create {@link us.ihmc.simulationconstructionset.gui.actions.ActionsTest.MethodCallTester} with
   * a proxy object for the given interface that logs all method calls.
   *
   * @param interfaceClass interface to proxy
   * @param forwardInstance interface implementation that will be called when a call is logged (can
   *     be null)
   * @param <T> interface type
   * @return method tester instance
   */
  private static <T> MethodCallTester<T> createMethodTesterForInterface(
      Class<T> interfaceClass, final T forwardInstance) {
    final List<MethodInvocation> invocations = new ArrayList<>();

    //noinspection unchecked
    T mock =
        (T)
            Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class[] {interfaceClass},
                new InvocationHandler() {
                  @Override
                  public Object invoke(Object proxy, Method method, Object[] args)
                      throws Throwable {
                    invocations.add(new MethodInvocation(method.getName(), args));
                    if (forwardInstance != null) return method.invoke(forwardInstance, args);
                    return null;
                  }
                });

    return new MethodCallTester<>(mock, interfaceClass, invocations);
  }
Beispiel #27
0
 public static Result routeAndCall(
     Class<? extends Router> router, RequestBuilder requestBuilder, long timeout) {
   try {
     Request request = requestBuilder.build();
     Router routes =
         (Router)
             router
                 .getClassLoader()
                 .loadClass(router.getName() + "$")
                 .getDeclaredField("MODULE$")
                 .get(null);
     if (routes.routes().isDefinedAt(request._underlyingRequest())) {
       return invokeHandler(routes.routes().apply(request._underlyingRequest()), request, timeout);
     } else {
       return null;
     }
   } catch (RuntimeException e) {
     throw e;
   } catch (Throwable t) {
     throw new RuntimeException(t);
   }
 }
 private URL locateResource(
     String publicName, String category, String defaultName, boolean verbose, File publicRoot)
     throws IOException {
   URL u = null;
   boolean custom = false;
   if (publicName != null) {
     if (publicRoot != null) {
       File publicResource = new File(publicRoot, publicName);
       if (publicResource.exists() && publicResource.isFile()) {
         u = publicResource.toURI().toURL();
       }
     } else {
       u = baseResourceLoader.getClassLoader().getResource(publicName);
     }
     custom = (u != null);
   }
   if (u == null && defaultName != null) {
     u = baseResourceLoader.getResource(defaultName);
   }
   String msg = null;
   if (custom) {
     msg =
         MessageFormat.format(
             I18N.getString("message.using-custom-resource-from-classpath"),
             category == null ? "" : "[" + category + "] ",
             publicName);
   } else if (u != null) {
     msg =
         MessageFormat.format(
             I18N.getString("message.using-default-resource-from-classpath"),
             category == null ? "" : "[" + category + "] ",
             publicName);
   }
   if (verbose && u != null) {
     Log.info(msg);
   }
   return u;
 }
  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;
  }
 private InnerLoader findClassLoader(Class clazz) {
   ClassLoader cl = clazz.getClassLoader();
   if (cl == null) cl = this.getClass().getClassLoader();
   return new InnerLoader(cl);
 }