Java Code Examples for java.lang.reflect.Proxy.getInvocationHandler()

The following are Jave code examples for showing how to use getInvocationHandler() of the java.lang.reflect.Proxy class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: MiPushFramework   File: CondomProcessTest.java   View Source Code Vote up 6 votes
@BeforeClass public static void checkInstallation() throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException {
	try {
		CondomProcess.installExcept(((Application) InstrumentationRegistry.getTargetContext().getApplicationContext()),
				new CondomOptions().addKit(new NullDeviceIdKit()), "");
		fail("CondomKit is incompatible with CondomProcess");
	} catch (final IllegalArgumentException ignored) {}

	// Install in default process intentionally, since test cases cannot run in secondary process.
	CondomProcess.installExcept(((Application) InstrumentationRegistry.getTargetContext().getApplicationContext()), new CondomOptions(), "");

	// Check IActivityManager proxy
	@SuppressLint("PrivateApi") final Object am_proxy = Class.forName("android.app.ActivityManagerNative").getMethod("getDefault").invoke(null);
	assertTrue(Proxy.isProxyClass(am_proxy.getClass()));
	sCondomProcessActivityManager = (CondomProcess.CondomProcessActivityManager) Proxy.getInvocationHandler(am_proxy);
	assertEquals(CondomProcess.CondomProcessActivityManager.class, sCondomProcessActivityManager.getClass());

	// Check IPackageManager proxy
	final PackageManager pm = context().getPackageManager();
	assertEquals("android.app.ApplicationPackageManager", pm.getClass().getName());
	final Field ApplicationPackageManager_mPm = pm.getClass().getDeclaredField("mPM");
	ApplicationPackageManager_mPm.setAccessible(true);
	final Object pm_proxy = ApplicationPackageManager_mPm.get(pm);
	assertTrue(Proxy.isProxyClass(pm_proxy.getClass()));
	sCondomProcessPackageManager = (CondomProcess.CondomProcessPackageManager) Proxy.getInvocationHandler(pm_proxy);
	assertEquals(CondomProcess.CondomProcessPackageManager.class, sCondomProcessPackageManager.getClass());
}
 
Example 2
Project: Reer   File: ProxyDispatchAdapter.java   View Source Code Vote up 6 votes
public Object invoke(Object target, Method method, Object[] parameters) throws Throwable {
    if (method.getName().equals("equals")) {
        Object parameter = parameters[0];
        if (parameter == null || !Proxy.isProxyClass(parameter.getClass())) {
            return false;
        }
        Object handler = Proxy.getInvocationHandler(parameter);
        if (!DispatchingInvocationHandler.class.isInstance(handler)) {
            return false;
        }

        DispatchingInvocationHandler otherHandler = (DispatchingInvocationHandler) handler;
        return otherHandler.type.equals(type) && otherHandler.dispatch == dispatch;
    }

    if (method.getName().equals("hashCode")) {
        return dispatch.hashCode();
    }
    if (method.getName().equals("toString")) {
        return type.getSimpleName() + " broadcast";
    }
    dispatch.dispatch(new MethodInvocation(method, parameters));
    return null;
}
 
Example 3
Project: lams   File: JobStoreSupport.java   View Source Code Vote up 6 votes
/**
 * <p>
 * Cleanup the given database connection.  This means restoring
 * any modified auto commit or transaction isolation connection
 * attributes, and then closing the underlying connection.
 * </p>
 * 
 * <p>
 * This is separate from closeConnection() because the Spring 
 * integration relies on being able to overload closeConnection() and
 * expects the same connection back that it originally returned
 * from the datasource. 
 * </p>
 * 
 * @see #closeConnection(Connection)
 */
protected void cleanupConnection(Connection conn) {
    if (conn != null) {
        if (conn instanceof Proxy) {
            Proxy connProxy = (Proxy)conn;
            
            InvocationHandler invocationHandler = 
                Proxy.getInvocationHandler(connProxy);
            if (invocationHandler instanceof AttributeRestoringConnectionInvocationHandler) {
                AttributeRestoringConnectionInvocationHandler connHandler =
                    (AttributeRestoringConnectionInvocationHandler)invocationHandler;
                    
                connHandler.restoreOriginalAtributes();
                closeConnection(connHandler.getWrappedConnection());
                return;
            }
        }
        
        // Wan't a Proxy, or was a Proxy, but wasn't ours.
        closeConnection(conn);
    }
}
 
Example 4
Project: boohee_v5.6   File: Platform.java   View Source Code Vote up 6 votes
public String getSelectedProtocol(SSLSocket socket) {
    String str = null;
    try {
        JettyNegoProvider provider = (JettyNegoProvider) Proxy.getInvocationHandler(this
                .getMethod.invoke(null, new Object[]{socket}));
        if (!provider.unsupported && provider.selected == null) {
            Internal.logger.log(Level.INFO, "ALPN callback dropped: SPDY and HTTP/2 are " +
                    "disabled. Is alpn-boot on the boot class path?");
        } else if (!provider.unsupported) {
            str = provider.selected;
        }
        return str;
    } catch (InvocationTargetException e) {
        throw new AssertionError();
    } catch (IllegalAccessException e2) {
        throw new AssertionError();
    }
}
 
Example 5
Project: jdk8u-jdk   File: TestUtils.java   View Source Code Vote up 6 votes
/**
 * Transfroms a proxy implementing T in a proxy implementing T plus
 * NotificationEmitter
 *
 **/
public static <T> T makeNotificationEmitter(T proxy,
                    Class<T> mbeanInterface) {
    if (proxy instanceof NotificationEmitter)
        return proxy;
    if (proxy == null) return null;
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (!(handler instanceof MBeanServerInvocationHandler))
        throw new IllegalArgumentException("not a JMX Proxy");
    final MBeanServerInvocationHandler h =
            (MBeanServerInvocationHandler)handler;
    final ObjectName name = h.getObjectName();
    final MBeanServerConnection mbs = h.getMBeanServerConnection();
    final boolean isMXBean = h.isMXBean();
    final T newProxy;
    if (isMXBean)
        newProxy = JMX.newMXBeanProxy(mbs,name,mbeanInterface,true);
    else
        newProxy = JMX.newMBeanProxy(mbs,name,mbeanInterface,true);
    return newProxy;
}
 
Example 6
Project: openjdk-jdk10   File: RuntimeExceptionTest.java   View Source Code Vote up 6 votes
/**
 * Test the monitor notifications.
 */
public int monitorNotifications() throws Exception {

    server = MBeanServerFactory.newMBeanServer();

    MBeanServerForwarderInvocationHandler mbsfih =
        (MBeanServerForwarderInvocationHandler)
        Proxy.getInvocationHandler(server);

    mbsfih.setGetAttributeException(
        new RuntimeException("Test RuntimeException"));

    domain = server.getDefaultDomain();

    obsObjName = ObjectName.getInstance(domain + ":type=ObservedObject");
    server.registerMBean(new ObservedObject(), obsObjName);

    echo(">>> ----------------------------------------");
    int error = counterMonitorNotification();
    echo(">>> ----------------------------------------");
    error += gaugeMonitorNotification();
    echo(">>> ----------------------------------------");
    error += stringMonitorNotification();
    echo(">>> ----------------------------------------");
    return error;
}
 
Example 7
Project: gemini.blueprint   File: SimpleServiceJDKProxyCreator.java   View Source Code Vote up 6 votes
public boolean equals(Object other) {
	if (other == this) {
		return true;
	}
	if (other == null) {
		return false;
	}

	if (Proxy.isProxyClass(other.getClass())) {
		InvocationHandler ih = Proxy.getInvocationHandler(other);
		if (ih instanceof JDKHandler) {
			return reference.equals(((JDKHandler) ih).reference);
		}
	}
	return false;
}
 
Example 8
Project: openjdk-jdk10   File: RemoteObjectInvocationHandler.java   View Source Code Vote up 5 votes
/**
 * Handles java.lang.Object methods.
 **/
private Object invokeObjectMethod(Object proxy,
                                  Method method,
                                  Object[] args)
{
    String name = method.getName();

    if (name.equals("hashCode")) {
        return hashCode();

    } else if (name.equals("equals")) {
        Object obj = args[0];
        InvocationHandler hdlr;
        return
            proxy == obj ||
            (obj != null &&
             Proxy.isProxyClass(obj.getClass()) &&
             (hdlr = Proxy.getInvocationHandler(obj)) instanceof RemoteObjectInvocationHandler &&
             this.equals(hdlr));

    } else if (name.equals("toString")) {
        return proxyToString(proxy);

    } else {
        throw new IllegalArgumentException(
            "unexpected Object method: " + method);
    }
}
 
Example 9
Project: jdk8u-jdk   File: TestUtils.java   View Source Code Vote up 5 votes
/**
 * Returns the ObjectName of the MBean that a proxy object
 * is proxying.
 **/
public static ObjectName getObjectName(Object proxy) {
    if (!(proxy instanceof Proxy))
        throw new IllegalArgumentException("not a "+Proxy.class.getName());
    final Proxy p = (Proxy) proxy;
    final InvocationHandler handler =
            Proxy.getInvocationHandler(proxy);
    if (handler instanceof MBeanServerInvocationHandler)
        return ((MBeanServerInvocationHandler)handler).getObjectName();
    throw new IllegalArgumentException("not a JMX Proxy");
}
 
Example 10
Project: hadoop   File: RpcClientUtil.java   View Source Code Vote up 5 votes
private static ProtocolMetaInfoPB getProtocolMetaInfoProxy(Object proxy,
    Configuration conf) throws IOException {
  RpcInvocationHandler inv = (RpcInvocationHandler) Proxy
      .getInvocationHandler(proxy);
  return RPC
      .getProtocolEngine(ProtocolMetaInfoPB.class, conf)
      .getProtocolMetaInfoProxy(inv.getConnectionId(), conf,
          NetUtils.getDefaultSocketFactory(conf)).getProxy();
}
 
Example 11
Project: lams   File: BshScriptUtils.java   View Source Code Vote up 5 votes
private boolean isProxyForSameBshObject(Object other) {
	if (!Proxy.isProxyClass(other.getClass())) {
		return false;
	}
	InvocationHandler ih = Proxy.getInvocationHandler(other);
	return (ih instanceof BshObjectInvocationHandler &&
			this.xt.equals(((BshObjectInvocationHandler) ih).xt));
}
 
Example 12
Project: container   File: ProviderHook.java   View Source Code Vote up 5 votes
public static IInterface createProxy(boolean external, String authority, IInterface provider) {
	if (provider instanceof Proxy && Proxy.getInvocationHandler(provider) instanceof ProviderHook) {
		return provider;
	}
	ProviderHook.HookFetcher fetcher = ProviderHook.fetchHook(authority);
	if (fetcher != null) {
		ProviderHook hook = fetcher.fetch(external, provider);
		IInterface proxyProvider = ProviderHook.createProxy(provider, hook);
		if (proxyProvider != null) {
			provider = proxyProvider;
		}
	}
	return provider;
}
 
Example 13
Project: lams   File: DynamicProxyConverter.java   View Source Code Vote up 5 votes
@Override
public void marshal(final Object source, final HierarchicalStreamWriter writer, final MarshallingContext context) {
    final InvocationHandler invocationHandler = Proxy.getInvocationHandler(source);
    addInterfacesToXml(source, writer);
    writer.startNode("handler");
    final String attributeName = mapper.aliasForSystemAttribute("class");
    if (attributeName != null) {
        writer.addAttribute(attributeName, mapper.serializedClass(invocationHandler.getClass()));
    }
    context.convertAnother(invocationHandler);
    writer.endNode();
}
 
Example 14
Project: lams   File: JRubyScriptUtils.java   View Source Code Vote up 5 votes
private boolean isProxyForSameRubyObject(Object other) {
	if (!Proxy.isProxyClass(other.getClass())) {
		return false;
	}
	InvocationHandler ih = Proxy.getInvocationHandler(other);
	return (ih instanceof RubyObjectInvocationHandler &&
			this.rubyObject.equals(((RubyObjectInvocationHandler) ih).rubyObject));
}
 
Example 15
Project: openjdk-jdk10   File: CompositeDataInvocationHandler.java   View Source Code Vote up 5 votes
private boolean equals(Object proxy, Object other) {
    if (other == null)
        return false;

    final Class<?> proxyClass = proxy.getClass();
    final Class<?> otherClass = other.getClass();
    if (proxyClass != otherClass)
        return false;
    InvocationHandler otherih = Proxy.getInvocationHandler(other);
    if (!(otherih instanceof CompositeDataInvocationHandler))
        return false;
    CompositeDataInvocationHandler othercdih =
        (CompositeDataInvocationHandler) otherih;
    return compositeData.equals(othercdih.compositeData);
}
 
Example 16
Project: hadoop-oss   File: RpcClientUtil.java   View Source Code Vote up 5 votes
private static ProtocolMetaInfoPB getProtocolMetaInfoProxy(Object proxy,
    Configuration conf) throws IOException {
  RpcInvocationHandler inv = (RpcInvocationHandler) Proxy
      .getInvocationHandler(proxy);
  return RPC
      .getProtocolEngine(ProtocolMetaInfoPB.class, conf)
      .getProtocolMetaInfoProxy(inv.getConnectionId(), conf,
          NetUtils.getDefaultSocketFactory(conf)).getProxy();
}
 
Example 17
Project: tomcat7   File: TestStatementCache.java   View Source Code Vote up 5 votes
/**
 * Helper method that finds interceptor instance in interceptor chain of a
 * proxied class.
 *
 * @param proxy
 *            Proxy class
 * @param clazz
 *            Interceptor class that we are looking for
 * @return Instance of <code>clazz</code>
 */
private static <T extends JdbcInterceptor> T findInterceptor(Object proxy,
        Class<T> clazz) {
    JdbcInterceptor interceptor = (JdbcInterceptor) Proxy
            .getInvocationHandler(proxy);
    while (interceptor != null) {
        if (clazz.isInstance(interceptor)) {
            return clazz.cast(interceptor);
        }
        interceptor = interceptor.getNext();
    }
    return null;
}
 
Example 18
Project: hadoop-oss   File: RetryInvocationHandler.java   View Source Code Vote up 5 votes
@VisibleForTesting
static boolean isRpcInvocation(Object proxy) {
  if (proxy instanceof ProtocolTranslator) {
    proxy = ((ProtocolTranslator) proxy).getUnderlyingProxyObject();
  }
  if (!Proxy.isProxyClass(proxy.getClass())) {
    return false;
  }
  final InvocationHandler ih = Proxy.getInvocationHandler(proxy);
  return ih instanceof RpcInvocationHandler;
}
 
Example 19
Project: openjdk-jdk10   File: MXBeanTest.java   View Source Code Vote up 5 votes
private static boolean proxyEqual(Object proxy1, Object proxy2,
                                  NamedMXBeans namedMXBeans) {
    if (proxy1.getClass() != proxy2.getClass())
        return proxy1.equals(proxy2);
    InvocationHandler ih1 = Proxy.getInvocationHandler(proxy1);
    InvocationHandler ih2 = Proxy.getInvocationHandler(proxy2);
    if (!(ih1 instanceof CompositeDataInvocationHandler)
        || !(ih2 instanceof CompositeDataInvocationHandler))
        return proxy1.equals(proxy2);
    CompositeData cd1 =
        ((CompositeDataInvocationHandler) ih1).getCompositeData();
    CompositeData cd2 =
        ((CompositeDataInvocationHandler) ih2).getCompositeData();
    return compositeDataEqual(cd1, cd2, namedMXBeans);
}
 
Example 20
Project: GitHub   File: EventListenerManager.java   View Source Code Vote up 4 votes
public static void addEventMethod(
        //根据页面或view holder生成的ViewFinder
        ViewFinder finder,
        //根据当前注解ID生成的ViewInfo
        ViewInfo info,
        //注解对象
        Event event,
        //页面或view holder对象
        Object handler,
        //当前注解方法
        Method method) {
    try {
        View view = finder.findViewByInfo(info);

        if (view != null) {
            // 注解中定义的接口,比如Event注解默认的接口为View.OnClickListener
            Class<?> listenerType = event.type();
            // 默认为空,注解接口对应的Set方法,比如setOnClickListener方法
            String listenerSetter = event.setter();
            if (TextUtils.isEmpty(listenerSetter)) {
                listenerSetter = "set" + listenerType.getSimpleName();
            }


            String methodName = event.method();

            boolean addNewMethod = false;
            /*
                根据View的ID和当前的接口类型获取已经缓存的接口实例对象,
                比如根据View.id和View.OnClickListener.class两个键获取这个View的OnClickListener对象
             */
            Object listener = listenerCache.get(info, listenerType);
            DynamicHandler dynamicHandler = null;
            /*
                如果接口实例对象不为空
                获取接口对象对应的动态代理对象
                如果动态代理对象的handler和当前handler相同
                则为动态代理对象添加代理方法
             */
            if (listener != null) {
                dynamicHandler = (DynamicHandler) Proxy.getInvocationHandler(listener);
                addNewMethod = handler.equals(dynamicHandler.getHandler());
                if (addNewMethod) {
                    dynamicHandler.addMethod(methodName, method);
                }
            }

            // 如果还没有注册此代理
            if (!addNewMethod) {

                dynamicHandler = new DynamicHandler(handler);

                dynamicHandler.addMethod(methodName, method);

                // 生成的代理对象实例,比如View.OnClickListener的实例对象
                listener = Proxy.newProxyInstance(
                        listenerType.getClassLoader(),
                        new Class<?>[]{listenerType},
                        dynamicHandler);

                listenerCache.put(info, listenerType, listener);
            }

            Method setEventListenerMethod = view.getClass().getMethod(listenerSetter, listenerType);
            setEventListenerMethod.invoke(view, listener);
        }
    } catch (Throwable ex) {
        LogUtil.e(ex.getMessage(), ex);
    }
}