/**
   * 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);
  }
    public Class<? extends T> generate() {
      visitor.visitEnd();

      byte[] bytecode = visitor.toByteArray();
      return DEFINE_CLASS_METHOD.invoke(
          type.getClassLoader(), typeName, bytecode, 0, bytecode.length);
    }
Example #3
0
  void enableLionFS() {
    try {
      String version = System.getProperty("os.version");
      String[] tokens = version.split("\\.");
      int major = Integer.parseInt(tokens[0]), minor = 0;
      if (tokens.length > 1) minor = Integer.parseInt(tokens[1]);
      if (major < 10 || (major == 10 && minor < 7))
        throw new Exception("Operating system version is " + version);

      Class fsuClass = Class.forName("com.apple.eawt.FullScreenUtilities");
      Class argClasses[] = new Class[] {Window.class, Boolean.TYPE};
      Method setWindowCanFullScreen = fsuClass.getMethod("setWindowCanFullScreen", argClasses);
      setWindowCanFullScreen.invoke(fsuClass, this, true);

      Class fsListenerClass = Class.forName("com.apple.eawt.FullScreenListener");
      InvocationHandler fsHandler = new MyInvocationHandler(cc);
      Object proxy =
          Proxy.newProxyInstance(
              fsListenerClass.getClassLoader(), new Class[] {fsListenerClass}, fsHandler);
      argClasses = new Class[] {Window.class, fsListenerClass};
      Method addFullScreenListenerTo = fsuClass.getMethod("addFullScreenListenerTo", argClasses);
      addFullScreenListenerTo.invoke(fsuClass, this, proxy);

      canDoLionFS = true;
    } catch (Exception e) {
      vlog.debug("Could not enable OS X 10.7+ full-screen mode:");
      vlog.debug("  " + e.toString());
    }
  }
  /**
   * 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);
  }
Example #5
0
  private Object createListenerProxy(
      Class<?> listenerClass,
      final Class<?> eventClass,
      final Method listenerMethod,
      final Object controller) {
    Object proxy =
        Proxy.newProxyInstance(
            listenerClass.getClassLoader(),
            new Class<?>[] {listenerClass},
            new InvocationHandler() {

              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                if (args != null
                    && args.length > 0
                    && eventClass.isAssignableFrom(args[0].getClass())) {
                  getLogger()
                      .fine(
                          String.format(
                              "Forwarding method call %s -> %s.",
                              method.getName(), listenerMethod.getName()));
                  return listenerMethod.invoke(controller, args);
                }
                getLogger()
                    .fine(
                        String.format(
                            "Forwarding method call %s to %s.",
                            method.getName(), controller.getClass()));
                return method.invoke(controller, args);
              }
            });
    getLogger().fine(String.format("Created a proxy for %s.", listenerClass));
    return proxy;
  }
  /**
   * 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;
  }
  /**
   * 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);
  }
Example #8
0
 public <T> T getInterface(Object thiz, Class<T> iface) throws ScriptException {
   if (iface == null || !iface.isInterface()) {
     throw new IllegalArgumentException("interface Class expected");
   }
   AccessControlContext accCtxt = AccessController.getContext();
   return iface.cast(
       Proxy.newProxyInstance(
           iface.getClassLoader(),
           new Class[] {iface},
           new InterfaceImplementorInvocationHandler(thiz, accCtxt)));
 }
  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();
  }
  /**
   * 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);
  }
Example #11
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;
    }
  // Other notes to implementors:
  // <p>
  // No stable mapping is promised between the single-method interface and
  // the implementation class C.  Over time, several implementation
  // classes might be used for the same type.
  // <p>
  // If the implementation is able
  // to prove that a wrapper of the required type
  // has already been created for a given
  // method handle, or for another method handle with the
  // same behavior, the implementation may return that wrapper in place of
  // a new wrapper.
  // <p>
  // This method is designed to apply to common use cases
  // where a single method handle must interoperate with
  // an interface that implements a function-like
  // API.  Additional variations, such as single-abstract-method classes with
  // private constructors, or interfaces with multiple but related
  // entry points, must be covered by hand-written or automatically
  // generated adapter classes.
  //
  public static <T> T asInterfaceInstance(final Class<T> intfc, final MethodHandle target) {
    if (!intfc.isInterface() || !Modifier.isPublic(intfc.getModifiers()))
      throw new IllegalArgumentException("not a public interface: " + intfc.getName());
    final Method[] methods = getSingleNameMethods(intfc);
    if (methods == null)
      throw new IllegalArgumentException("not a single-method interface: " + intfc.getName());
    final MethodHandle[] vaTargets = new MethodHandle[methods.length];
    for (int i = 0; i < methods.length; i++) {
      Method sm = methods[i];
      MethodType smMT = MethodType.methodType(sm.getReturnType(), sm.getParameterTypes());
      MethodHandle checkTarget = target.asType(smMT); // make throw WMT
      checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class));
      vaTargets[i] = checkTarget.asSpreader(Object[].class, smMT.parameterCount());
    }
    return intfc.cast(
        Proxy.newProxyInstance(
            intfc.getClassLoader(),
            new Class[] {intfc, WrapperInstance.class},
            new InvocationHandler() {
              private Object getArg(String name) {
                if ((Object) name == "getWrapperInstanceTarget") return target;
                if ((Object) name == "getWrapperInstanceType") return intfc;
                throw new AssertionError();
              }

              public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                for (int i = 0; i < methods.length; i++) {
                  if (method.equals(methods[i])) return vaTargets[i].invokeExact(args);
                }
                if (method.getDeclaringClass() == WrapperInstance.class)
                  return getArg(method.getName());
                if (isObjectMethod(method)) return callObjectMethod(this, method, args);
                throw new InternalError("bad proxy method: " + method);
              }
            }));
  }
Example #13
0
 @SuppressWarnings({"unchecked"})
 private static <T> T proxy(Class<T> type, Map<Method, Call> methods) {
   return (T)
       Proxy.newProxyInstance(
           type.getClassLoader(), new Class[] {type}, new DynamicFinder(methods));
 }
 /**
  * Same as {@link #newEmptyProxy(ClassLoader, Class)}, but with the class loader obtained from the
  * interface to be proxied. Note that this may lead to a {@code NoClassDefFoundError} if that
  * interface was loaded by the boot class loader (usually, when it's a JRE class). Therefore, you
  * should only use this method for application-defined interfaces.
  *
  * <p>This method is just a convenience for some uses of the <em>Mockups</em> API. In <em>JMockit
  * Expectations</em> in particular, mocked instances will be automatically created and assigned to
  * any mock fields or parameters.
  *
  * @see <a
  *     href="http://code.google.com/p/jmockit/source/browse/trunk/main/test/integrationTests/textFile/TextFileUsingAnnotatedMockClassesTest.java#91">
  *     Example</a>
  */
 public static <E> E newEmptyProxy(Class<E> interfaceToBeProxied) {
   return newEmptyProxy(interfaceToBeProxied.getClassLoader(), interfaceToBeProxied);
 }
Example #15
0
 protected ClassLoader getDefaultClassLoader() {
   return targetClass.getClassLoader();
 }