Java Code Examples for java.lang.reflect.InvocationHandler

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project advanced, under directory /management/src/main/java/org/neo4j/management/.

Source file: Neo4jManager.java

  32 
vote

private static MBeanServerConnection getServer(Kernel kernel){
  if (kernel instanceof Proxy) {
    InvocationHandler handler=Proxy.getInvocationHandler(kernel);
    if (handler instanceof MBeanServerInvocationHandler) {
      return ((MBeanServerInvocationHandler)handler).getMBeanServerConnection();
    }
  }
 else   if (kernel instanceof Neo4jManager) {
    return ((Neo4jManager)kernel).server;
  }
  throw new UnsupportedOperationException("Cannot get server for kernel: " + kernel);
}
 

Example 2

From project ALP, under directory /workspace/alp-flexpilot/src/main/java/com/lohika/alp/flexpilot/pagefactory/.

Source file: FlexPilotDefaultFieldDecorator.java

  32 
vote

/** 
 * Proxy for locator.
 * @param loader ClassLoader 
 * @param locator FlexElementLocatorFactory
 * @return the flex element
 */
protected FlexElement proxyForLocator(ClassLoader loader,FlexElementLocator locator){
  InvocationHandler handler=new FlexPilotLocatingElementHandler(locator);
  FlexElement proxy;
  proxy=(FlexElement)Proxy.newProxyInstance(loader,new Class[]{FlexElement.class,WrapsElement.class,Locatable.class},handler);
  return proxy;
}
 

Example 3

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/beans/.

Source file: ProxyFactoryImpl.java

  32 
vote

@SuppressWarnings("unchecked") public <I,R extends ProxyMapper<I,? extends I>>R getProxyMapper(I proxy){
  if (proxy != null && Proxy.isProxyClass(proxy.getClass())) {
    InvocationHandler handler=Proxy.getInvocationHandler(proxy);
    if (handler instanceof ProxyMapper<?,?>) {
      return (R)handler;
    }
  }
  return null;
}
 

Example 4

From project bamboo-sonar-integration, under directory /bamboo-sonar-web/src/main/java/com/marvelution/bamboo/plugins/sonar/web/proxy/.

Source file: OsgiServiceProxy.java

  32 
vote

/** 
 * Static helper method to get a  {@link OsgiServiceProxy} {@link Proxy}
 * @param tracker the {@link ServiceTracker} to get a {@link Proxy} for
 * @param type the {@link Class} type of the Service Object
 * @return the {@link Proxy}
 */
@SuppressWarnings("unchecked") public static <T>T getServiceProxy(ServiceTracker tracker,Class<T> type){
  ServiceReference reference=tracker.getServiceReference();
  if (reference.isAssignableTo(reference.getBundle(),type.getName())) {
    InvocationHandler handler=new OsgiServiceProxy(tracker);
    return (T)Proxy.newProxyInstance(type.getClassLoader(),new Class[]{type},handler);
  }
 else {
    throw new OsgiContainerException("Service '" + reference.getBundle().getClass() + "' is not of type "+ type);
  }
}
 

Example 5

From project dci-examples, under directory /frontloading/java/ant-kutschera/lib/maxant-dci-tools-1.1.0/ch/maxant/dci/util/.

Source file: SimpleRoleAssigner.java

  32 
vote

/** 
 * casts the given objectToAssignRoleTo into a methodlessRoleInterface by using a dynamic proxy. This is used to simply narrow the interface of complex objects in order to make them easier to  understand during review. <br><br>
 * @param < T >
 * @param < U >
 * @param objectToAssignRoleTo
 * @param roleInterface
 * @param doCheck if true, or if system property ch.maxant.dci.util.checkAllRoleMethodsExist isset to true, then this method checks that ALL methods in the interface exist in the  domain object too. throws a  {@link UnsupportedOperationException} if a method cannot be found.
 * @return a dynamic proxy with the role interface.
 */
@SuppressWarnings("unchecked") public <T,U>U assignRole(T objectToAssignRoleTo,Class<? extends U> roleInterface){
  ClassLoader classLoader=objectToAssignRoleTo.getClass().getClassLoader();
  Class[] interfaces=new Class[]{roleInterface};
  InvocationHandler ih=new MyInvocationHandler(objectToAssignRoleTo);
  if (isSystemPropertyForCheckSet()) {
    doCheck(roleInterface,objectToAssignRoleTo,null);
  }
  return (U)Proxy.newProxyInstance(classLoader,interfaces,ih);
}
 

Example 6

From project Gemini-Blueprint, under directory /integration-tests/tests/src/test/java/org/eclipse/gemini/blueprint/iandt/proxycreator/.

Source file: JdkProxyTest.java

  32 
vote

public void testJDKProxyCreationUsingTheInterfaceClassLoaderInsteadOfTheHandlerOne() throws Exception {
  InvocationHandler handler=getInvocationHandler();
  SomeInterfaceImplementation target=new SomeInterfaceImplementation();
  SomeInterface proxy=createJDKProxy(handler,target);
  SomeInterfaceImplementation.INVOCATION=0;
  String str=proxy.doSmth();
  System.out.println("Proxy returned " + str);
  assertEquals(0,SomeInterfaceImplementation.INVOCATION);
  assertSame(handler,Proxy.getInvocationHandler(proxy));
}
 

Example 7

From project GNDMS, under directory /stuff/src/de/zib/gndms/stuff/mold/.

Source file: Mold.java

  32 
vote

/** 
 * Implements the  {@code Molder}-Interface at runtime for  {@code moldingParam} and returns a {@code Molder}&lt;D&gt; out of  {@code moldingParam}. Therefore  {@code moldingParam} must have a method {@code void mold(D obj)}, at least in a superclass.
 * @param moldingClassParam the Class of the instance supposed to mold a new instance
 * @param moldingParam the instance supposed to mold a new instance
 * @param moldedClassParam the Class of the instance to be molded
 * @return a {@code Molder}&lt;D&gt; out of  {@code moldingParam}
 */
public static <C,D>Molder<D> newMolderProxy(@NotNull Class<C> moldingClassParam,@NotNull C moldingParam,@NotNull Class<D> moldedClassParam){
  final @NotNull Method method;
  try {
    method=Molder.class.getMethod("mold",Object.class);
  }
 catch (  NoSuchMethodException e) {
    throw new RuntimeException("This should not happen",e);
  }
  final @NotNull InvocationHandler handler=new MoldInvocationHandler<C,D>(moldingClassParam,moldingParam,method,moldedClassParam);
  return (Molder<D>)Proxy.newProxyInstance(Molder.class.getClassLoader(),new Class[]{Molder.class},handler);
}
 

Example 8

From project hibernate-commons-annotations, under directory /src/main/java/org/hibernate/annotations/common/annotationfactory/.

Source file: AnnotationFactory.java

  32 
vote

@SuppressWarnings("unchecked") public static <T extends Annotation>T create(AnnotationDescriptor descriptor){
  ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
  Class<T> proxyClass=(Class<T>)Proxy.getProxyClass(classLoader,descriptor.type());
  InvocationHandler handler=new AnnotationProxy(descriptor);
  try {
    return getProxyInstance(proxyClass,handler);
  }
 catch (  RuntimeException e) {
    throw e;
  }
catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 9

From project hibernate-validator, under directory /engine/src/main/java/org/hibernate/validator/internal/util/annotationfactory/.

Source file: AnnotationFactory.java

  32 
vote

public static <T extends Annotation>T create(AnnotationDescriptor<T> descriptor){
  @SuppressWarnings("unchecked") Class<T> proxyClass=(Class<T>)Proxy.getProxyClass(ReflectionHelper.getClassLoaderFromClass(descriptor.type()),descriptor.type());
  InvocationHandler handler=new AnnotationProxy(descriptor);
  try {
    return getProxyInstance(proxyClass,handler);
  }
 catch (  RuntimeException e) {
    throw e;
  }
catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 10

From project hs4j, under directory /contributes/hs4j-kit/src/main/java/com/github/zhongl/hs4j/kit/proxy/.

Source file: ProxyFactory.java

  32 
vote

private void scanAndMapMethodToInvacationHandlerWith(Class<?> clazz){
  final Repository repository=clazz.getAnnotation(Repository.class);
  if (repository == null)   throw new IllegalArgumentException(Repository.class + " should be annotated to class: " + clazz);
  final String database=repository.database();
  final String table=repository.table();
  Method[] methods=clazz.getMethods();
  for (  Method method : methods) {
    InvocationHandler handler=createInvocationHandlerWith(method,database,table);
    if ((handler == null))     continue;
    invocationMap.put(method,handler);
  }
}
 

Example 11

From project Iglu, under directory /src/main/java/org/ijsberg/iglu/configuration/module/.

Source file: StandardComponent.java

  32 
vote

public Object invoke(Object proxy,Method method,Object[] parameters) throws Throwable {
  InvocationHandler handler=invocationHandlers.get(proxy.getClass().getInterfaces()[0]);
  if (handler == null) {
    handler=invocationHandlers.get(method.getDeclaringClass());
  }
  if (handler != null) {
    return handler.invoke(implementation,method,parameters);
  }
 else   return method.invoke(implementation,parameters);
}
 

Example 12

From project jboss-ejb-client, under directory /src/main/java/org/jboss/ejb/client/.

Source file: EJBInvocationHandler.java

  32 
vote

@SuppressWarnings("unchecked") static <T>EJBInvocationHandler<? extends T> forProxy(T proxy){
  InvocationHandler handler=Proxy.getInvocationHandler(proxy);
  if (handler instanceof EJBInvocationHandler) {
    return (EJBInvocationHandler<? extends T>)handler;
  }
  throw Logs.MAIN.proxyNotOurs(proxy,EJBClient.class.getName());
}
 

Example 13

From project jboss-jpa, under directory /mcint/src/test/java/org/jboss/jpa/mcint/test/common/.

Source file: DummyPersistenceUnit.java

  32 
vote

public EntityManagerFactory getContainerEntityManagerFactory(){
  ClassLoader loader=Thread.currentThread().getContextClassLoader();
  Class<?> interfaces[]={EntityManagerFactory.class};
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      throw new RuntimeException("NYI");
    }
  }
;
  return (EntityManagerFactory)Proxy.newProxyInstance(loader,interfaces,handler);
}
 

Example 14

From project jboss-rmi-api_spec, under directory /src/main/java/org/jboss/com/sun/corba/se/impl/presentation/rmi/.

Source file: InvocationHandlerFactoryImpl.java

  32 
vote

InvocationHandler getInvocationHandler(DynamicStub stub){
  InvocationHandler dynamicStubHandler=DelegateInvocationHandlerImpl.create(stub);
  InvocationHandler stubMethodHandler=new StubInvocationHandlerImpl(pm,classData,stub);
  final CompositeInvocationHandler handler=new CustomCompositeInvocationHandlerImpl(stub);
  handler.addInvocationHandler(DynamicStub.class,dynamicStubHandler);
  handler.addInvocationHandler(org.omg.CORBA.Object.class,dynamicStubHandler);
  handler.addInvocationHandler(Object.class,dynamicStubHandler);
  handler.setDefaultHandler(stubMethodHandler);
  return handler;
}
 

Example 15

From project kryo-serializers, under directory /src/main/java/de/javakaffee/kryoserializers/.

Source file: JdkProxySerializer.java

  32 
vote

/** 
 * {@inheritDoc}
 */
@Override public Object read(final ByteBuffer buffer){
  final InvocationHandler invocationHandler=(InvocationHandler)_kryo.readClassAndObject(buffer);
  final Class<?>[] interfaces=_kryo.readObjectData(buffer,Class[].class);
  final ClassLoader classLoader=_kryo.getClassLoader();
  try {
    return Proxy.newProxyInstance(classLoader,interfaces,invocationHandler);
  }
 catch (  final RuntimeException e) {
    System.err.println(getClass().getName() + ".read:\n" + "Could not create proxy using classLoader "+ classLoader+ ","+ " have invoctaionhandler.classloader: "+ invocationHandler.getClass().getClassLoader()+ " have contextclassloader: "+ Thread.currentThread().getContextClassLoader());
    throw e;
  }
}
 

Example 16

From project Lily, under directory /cr/process/client/src/main/java/org/lilyproject/client/.

Source file: BalancingAndRetryingRepository.java

  32 
vote

public static Repository getInstance(LilyClient lilyClient){
  InvocationHandler typeManagerHandler=new TypeManagerInvocationHandler(lilyClient);
  TypeManager typeManager=(TypeManager)Proxy.newProxyInstance(TypeManager.class.getClassLoader(),new Class[]{TypeManager.class},typeManagerHandler);
  InvocationHandler repositoryHandler=new RepositoryInvocationHandler(lilyClient,typeManager);
  Repository repository=(Repository)Proxy.newProxyInstance(Repository.class.getClassLoader(),new Class[]{Repository.class},repositoryHandler);
  return repository;
}
 

Example 17

From project linkedin-utils, under directory /org.linkedin.util-core/src/main/java/org/linkedin/util/reflect/.

Source file: ReflectUtils.java

  32 
vote

/** 
 * Given a proxy returns the object proxied. If the object is not a proxy, then return the object itself.
 * @param proxy
 * @return the proxied object (or proxy if not an object proxy)
 */
@SuppressWarnings("unchecked") public static Object getProxiedObject(Object proxy){
  if (Proxy.isProxyClass(proxy.getClass())) {
    InvocationHandler invocationHandler=Proxy.getInvocationHandler(proxy);
    if (invocationHandler instanceof ObjectProxy) {
      ObjectProxy objectProxy=(ObjectProxy)invocationHandler;
      return getProxiedObject(objectProxy.getProxiedObject());
    }
 else     return proxy;
  }
 else   return proxy;
}
 

Example 18

From project mchange-commons-java, under directory /src/java/com/mchange/v1/cachedstore/.

Source file: CachedStoreFactory.java

  32 
vote

public static TweakableCachedStore createSynchronousCleanupSoftKeyCachedStore(CachedStore.Manager manager){
  final ManualCleanupSoftKeyCachedStore inner=new ManualCleanupSoftKeyCachedStore(manager);
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method m,    Object[] args) throws Throwable {
      inner.vacuum();
      return m.invoke(inner,args);
    }
  }
;
  return (TweakableCachedStore)Proxy.newProxyInstance(CachedStoreFactory.class.getClassLoader(),new Class[]{TweakableCachedStore.class},handler);
}
 

Example 19

From project memcached-session-manager, under directory /javolution-serializer/src/main/java/de/javakaffee/web/msm/serializer/javolution/.

Source file: ReflectionBinding.java

  32 
vote

@Override public final void write(final Object obj,final javolution.xml.XMLFormat.OutputElement output) throws XMLStreamException {
  final InvocationHandler invocationHandler=Proxy.getInvocationHandler(obj);
  output.add(invocationHandler,"handler");
  final String[] interfaceNames=getInterfaceNames(obj);
  output.add(interfaceNames,"interfaces");
}
 

Example 20

From project platform_frameworks_ex, under directory /variablespeed/tests/src/com/android/ex/variablespeed/.

Source file: DynamicProxy.java

  32 
vote

/** 
 * Dynamically adapts a given interface against a delegate object. <p> For the given  {@code clazz} object, which should be an interface, we return a new dynamicproxy object implementing that interface, which will forward all method calls made on the interface onto the delegate object. <p> In practice this means that you can make it appear as though  {@code delegate} implements the{@code clazz} interface, without this in practice being the case. As an example, if youcreate an interface representing the  {@link android.media.MediaPlayer}, you could pass this interface in as the first argument, and a real  {@link android.media.MediaPlayer} in as thesecond argument, and now calls to the interface will be automatically sent on to the real media player. The reason you may be interested in doing this in the first place is that this allows you to test classes that have dependencies that are final or cannot be easily mocked.
 */
@SuppressWarnings("unchecked") public static <T>T dynamicProxy(Class<T> clazz,final Object delegate){
  InvocationHandler invoke=new InvocationHandler(){
    @Override public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      try {
        return delegate.getClass().getMethod(method.getName(),method.getParameterTypes()).invoke(delegate,args);
      }
 catch (      InvocationTargetException e) {
        throw e.getCause();
      }
    }
  }
;
  return (T)Proxy.newProxyInstance(clazz.getClassLoader(),new Class<?>[]{clazz},invoke);
}
 

Example 21

From project qi4j-core, under directory /runtime/src/main/java/org/qi4j/runtime/association/.

Source file: AbstractAssociationInstance.java

  32 
vote

protected EntityReference getEntityReference(Object composite){
  if (composite == null) {
    return null;
  }
  InvocationHandler handler=Proxy.getInvocationHandler(composite);
  if (handler instanceof ProxyReferenceInvocationHandler) {
    handler=Proxy.getInvocationHandler(((ProxyReferenceInvocationHandler)handler).proxy());
  }
  EntityInstance instance=(EntityInstance)handler;
  return instance.identity();
}
 

Example 22

From project querydsl, under directory /querydsl-jpa/src/test/java/com/mysema/query/jpa/.

Source file: JPAProviderTest.java

  32 
vote

@Test public void Hibernate_For_Proxy(){
  factory=Persistence.createEntityManagerFactory("h2");
  em=factory.createEntityManager();
  InvocationHandler handler=new InvocationHandler(){
    @Override public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      return method.invoke(em,args);
    }
  }
;
  EntityManager proxy=(EntityManager)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{EntityManager.class},handler);
  assertEquals(JPAProvider.HIBERNATE,JPAProvider.get(proxy));
}
 

Example 23

From project remoting, under directory /src/main/java/hudson/remoting/.

Source file: RemoteInvocationHandler.java

  32 
vote

/** 
 * If the given object is a proxy to a remote object in the specified channel, return its object ID. Otherwise return -1. <p> This method can be used to get back the original reference when a proxy is sent back to the channel it came from. 
 */
public static int unwrap(Object proxy,Channel src){
  InvocationHandler h=Proxy.getInvocationHandler(proxy);
  if (h instanceof RemoteInvocationHandler) {
    RemoteInvocationHandler rih=(RemoteInvocationHandler)h;
    if (rih.channel == src)     return rih.oid;
  }
  return -1;
}
 

Example 24

From project riftsaw-ode, under directory /jacob/src/main/java/org/apache/ode/jacob/vpu/.

Source file: ChannelFactory.java

  32 
vote

public static Channel createChannel(CommChannel backend,Class type){
  InvocationHandler h=new ChannelInvocationHandler(backend);
  Class[] ifaces=new Class[]{Channel.class,type};
  Object proxy=Proxy.newProxyInstance(Channel.class.getClassLoader(),ifaces,h);
  return (Channel)proxy;
}
 

Example 25

From project sitebricks, under directory /sitebricks-options/src/main/java/com/google/sitebricks/options/.

Source file: OptionsModule.java

  32 
vote

private Object createJdkProxyHandler(Class<?> optionClass,final Map<String,String> concreteOptions){
  final InvocationHandler handler=new InvocationHandler(){
    @Inject OptionTypeConverter converter;
    @Override public Object invoke(    Object o,    Method method,    Object[] objects) throws Throwable {
      return converter.convert(concreteOptions.get(method.getName()),method.getReturnType());
    }
  }
;
  requestInjection(handler);
  return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class<?>[]{optionClass},handler);
}
 

Example 26

From project spring-data-neo4j, under directory /spring-data-neo4j/src/main/java/org/springframework/data/neo4j/support/conversion/.

Source file: EntityResultConverter.java

  32 
vote

@SuppressWarnings("unchecked") public R extractMapResult(Object value,Class returnType,MappingPolicy mappingPolicy){
  if (!Map.class.isAssignableFrom(value.getClass())) {
    throw new RuntimeException("MapResult can only be extracted from Map<String,Object>.");
  }
  InvocationHandler handler=new QueryResultProxy((Map<String,Object>)value,mappingPolicy,this);
  return (R)Proxy.newProxyInstance(returnType.getClassLoader(),new Class[]{returnType},handler);
}
 

Example 27

From project spring-js, under directory /src/main/java/org/springframework/instrument/classloading/jboss/.

Source file: JBossClassLoaderAdapter.java

  32 
vote

public void addTransformer(ClassFileTransformer transformer){
  InvocationHandler adapter=new JBossTranslatorAdapter(transformer);
  Object adapterInstance=Proxy.newProxyInstance(this.translatorClass.getClassLoader(),new Class[]{this.translatorClass},adapter);
  try {
    addTranslator.invoke(target,adapterInstance);
  }
 catch (  Exception ex) {
    throw new IllegalStateException("Could not add transformer on JBoss classloader " + classLoader,ex);
  }
}
 

Example 28

From project springfaces-v1, under directory /org.springframework.faces.mvc/src/main/java/org/springframework/faces/mvc/scope/.

Source file: CompositeScopeRegistrar.java

  32 
vote

/** 
 * Helper function that operates in an identical way to {@link #newFilteredRegistration(ConfigurableListableBeanFactory,ScopeAvailabilityFilter)} but that returns a{@link ConfigurableListableBeanFactory} instance rather than a {@link FilteredRegistration}. This method can be useful when working with an existing scope registrar. The only method from the returned bean factory that can be called is  {@link ConfigurableListableBeanFactory#registerScope(String,Scope)}.
 * @param beanFactory The bean factory that should have scopes registered
 * @param availabilityFilter The filter for this registration or <tt>null</tt> if no filter is required
 * @return A {@link ConfigurableListableBeanFactory} where <tt>registerScope</tt> is the only method that can beused
 * @see #newFilteredRegistrationBeanFactory(ConfigurableListableBeanFactory,ScopeAvailabilityFilter)
 */
protected ConfigurableListableBeanFactory newFilteredRegistrationBeanFactory(ConfigurableListableBeanFactory beanFactory,ScopeAvailabilityFilter availabilityFilter){
  final FilteredRegistration filteredRegistration=newFilteredRegistration(beanFactory,availabilityFilter);
  InvocationHandler invokationHandler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      if (REGISTER_SCOPE_METHOD.equals(method)) {
        filteredRegistration.registerScope((String)args[0],(Scope)args[1]);
        return null;
      }
      throw new IllegalStateException("Unexpected method call " + method);
    }
  }
;
  return (ConfigurableListableBeanFactory)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{ConfigurableListableBeanFactory.class},invokationHandler);
}
 

Example 29

From project alljoyn_java, under directory /samples/android/simple/wfd_service/src/org/alljoyn/bus/samples/wfdsimpleservice/.

Source file: WifiDirectAutoAccept.java

  31 
vote

/** 
 * Creating a new DialogListenerProxy object that also inherits the DialogListener interface. The caller does not need to have any awareness of the DialogListener interface. Returns null if the object could not be created.  This can happen if the DialogListener interface is not available at runtime.
 */
private Object newDialogListener(){
  Object dialogListener;
  if (manager == null || channel == null || dialogInterface == null) {
    return null;
  }
  final Object object=new DialogListenerProxy(manager,channel);
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      Method proxyMethod=null;
      for (      Method m : DialogListenerProxy.class.getMethods()) {
        if (m.getName().equals(method.getName())) {
          proxyMethod=m;
          break;
        }
      }
      if (proxyMethod != null) {
        try {
          proxyMethod.invoke(object,args);
        }
 catch (        IllegalArgumentException ex) {
          Log.d(TAG,ex.getClass().getName());
        }
      }
 else {
        Log.d(TAG,"No method found: " + method.getName());
      }
      return null;
    }
  }
;
  dialogListener=Proxy.newProxyInstance(DialogListenerProxy.class.getClassLoader(),new Class[]{dialogInterface},handler);
  return dialogListener;
}
 

Example 30

From project android_external_guava, under directory /src/com/google/common/util/concurrent/.

Source file: SimpleTimeLimiter.java

  31 
vote

public <T>T newProxy(final T target,Class<T> interfaceType,final long timeoutDuration,final TimeUnit timeoutUnit){
  checkNotNull(target);
  checkNotNull(interfaceType);
  checkNotNull(timeoutUnit);
  checkArgument(timeoutDuration > 0,"bad timeout: " + timeoutDuration);
  checkArgument(interfaceType.isInterface(),"interfaceType must be an interface type");
  final Set<Method> interruptibleMethods=findInterruptibleMethods(interfaceType);
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    Object obj,    final Method method,    final Object[] args) throws Throwable {
      Callable<Object> callable=new Callable<Object>(){
        public Object call() throws Exception {
          try {
            return method.invoke(target,args);
          }
 catch (          InvocationTargetException e) {
            Throwables.throwCause(e,false);
            throw new AssertionError("can't get here");
          }
        }
      }
;
      return callWithTimeout(callable,timeoutDuration,timeoutUnit,interruptibleMethods.contains(method));
    }
  }
;
  return newProxy(interfaceType,handler);
}
 

Example 31

From project arkadiko, under directory /test/com/liferay/arkadiko/test/.

Source file: TestTwo.java

  31 
vote

public void testDeployBundleWithImplementation() throws Exception {
  InterfaceOne interfaceOne=null;
  HasDependencyOnInterfaceOne bean=(HasDependencyOnInterfaceOne)_context.getBean(HasDependencyOnInterfaceOne.class.getName());
  interfaceOne=bean.getInterfaceOne();
  assertTrue("interfaceOne is not a proxy",Proxy.isProxyClass(interfaceOne.getClass()));
  InvocationHandler ih=Proxy.getInvocationHandler(interfaceOne);
  assertTrue("ih not instanceof AKServiceTrackerInvocationHandler",ih instanceof AKServiceTrackerInvocationHandler);
  AKServiceTrackerInvocationHandler akih=(AKServiceTrackerInvocationHandler)ih;
  assertTrue("currentService not equal to originalService",akih.getCurrentService() == akih.getOriginalService());
  Bundle installedBundle=installAndStart(_context,"/bundles/bundle-one/bundle-one.jar");
  try {
    interfaceOne=bean.getInterfaceOne();
    assertTrue("interfaceOne is not a proxy",Proxy.isProxyClass(interfaceOne.getClass()));
    ih=Proxy.getInvocationHandler(interfaceOne);
    assertTrue("ih not instanceof AKServiceTrackerInvocationHandler",ih instanceof AKServiceTrackerInvocationHandler);
    akih=(AKServiceTrackerInvocationHandler)ih;
    assertFalse("currentService() is equal to originalService",akih.getCurrentService() == akih.getOriginalService());
  }
  finally {
    installedBundle.uninstall();
  }
  interfaceOne=bean.getInterfaceOne();
  assertTrue("interfaceOne is not a proxy",Proxy.isProxyClass(interfaceOne.getClass()));
  ih=Proxy.getInvocationHandler(interfaceOne);
  assertTrue("ih not instanceof AKServiceTrackerInvocationHandler",ih instanceof AKServiceTrackerInvocationHandler);
  akih=(AKServiceTrackerInvocationHandler)ih;
  assertTrue("currentService() is equal to originalService",akih.getCurrentService() == akih.getOriginalService());
}
 

Example 32

From project awaitility, under directory /awaitility/src/test/java/com/jayway/awaitility/proxy/.

Source file: ProxyCreatorTest.java

  31 
vote

@Test public void interceptsStandardMethodCalls() throws Exception {
  ClassWithMethods object=(ClassWithMethods)ProxyCreator.create(ClassWithMethods.class,new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      return "test";
    }
  }
);
  assertEquals("test",object.aMethod());
}
 

Example 33

From project backup-plugin, under directory /src/main/java/org/jvnet/hudson/plugins/backup/utils/.

Source file: FakeObject.java

  31 
vote

public static StaplerResponse getStaplerResponseFake(){
  return (StaplerResponse)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{StaplerResponse.class},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      return null;
    }
  }
);
}
 

Example 34

From project camel-osgi, under directory /component/src/main/java/org/apache/camel/osgi/service/util/.

Source file: OsgiDefaultProxyCreator.java

  31 
vote

@Override @SuppressWarnings("unchecked") public <T>T createProxy(BundleContext bundleContext,ServiceReference reference,ClassLoader classLoader){
  Bundle exportingBundle=reference.getBundle();
  if (exportingBundle == null) {
    throw new IllegalArgumentException(String.format("Service [%s] has been unregistered",reference));
  }
  InvocationHandler handler=new OsgiInvocationHandler(bundleContext,reference);
  String[] classNames=(String[])reference.getProperty(Constants.OBJECTCLASS);
  List<Class<?>> classes=new ArrayList<Class<?>>(classNames.length);
  for (  String className : classNames) {
    try {
      Class<?> clazz=classLoader.loadClass(className);
      if (clazz.isInterface()) {
        classes.add(clazz);
      }
    }
 catch (    ClassNotFoundException e) {
      throw new IllegalArgumentException(String.format("Unable to find class [%s] with classloader [%s]",className,classLoader));
    }
  }
  classes.add(OsgiProxy.class);
  classes.add(ServiceReference.class);
  return (T)Proxy.newProxyInstance(classLoader,classes.toArray(new Class<?>[classes.size()]),handler);
}
 

Example 35

From project core_4, under directory /api/src/main/java/org/richfaces/application/.

Source file: ServiceTracker.java

  31 
vote

/** 
 * Provides proxy which delegates to the given targetService
 * @param targetService the service to delegate operations to
 * @return proxy which delegates to the given targetService
 */
@SuppressWarnings("unchecked") public static <T>T getProxy(final Class<T> targetService){
  return (T)Proxy.newProxyInstance(getCurrentLoader(),new Class<?>[]{targetService},new InvocationHandler(){
    @Override public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      T service=ServiceTracker.getService(targetService);
      if (service == null) {
        throw new IllegalStateException("Failed to obtain service " + targetService.getSimpleName());
      }
      return method.invoke(service,args);
    }
  }
);
}
 

Example 36

From project etherpad, under directory /infrastructure/rhino1_7R1/src/org/mozilla/javascript/jdk13/.

Source file: VMBridge_jdk13.java

  31 
vote

protected Object newInterfaceProxy(Object proxyHelper,final ContextFactory cf,final InterfaceAdapter adapter,final Object target,final Scriptable topScope){
  Constructor c=(Constructor)proxyHelper;
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args){
      return adapter.invoke(cf,target,topScope,method,args);
    }
  }
;
  Object proxy;
  try {
    proxy=c.newInstance(new Object[]{handler});
  }
 catch (  InvocationTargetException ex) {
    throw Context.throwAsScriptRuntimeEx(ex);
  }
catch (  IllegalAccessException ex) {
    throw Kit.initCause(new IllegalStateException(),ex);
  }
catch (  InstantiationException ex) {
    throw Kit.initCause(new IllegalStateException(),ex);
  }
  return proxy;
}
 

Example 37

From project flyway, under directory /flyway-core/src/test/java/com/googlecode/flyway/core/.

Source file: FlywayMediumTest.java

  31 
vote

@Override protected Connection getConnectionFromDriver(String username,String password) throws SQLException {
  final Connection connection=super.getConnectionFromDriver(username,password);
  openConnectionCount++;
  return (Connection)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{Connection.class},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      if ("close".equals(method.getName())) {
        openConnectionCount--;
      }
      return method.invoke(connection,args);
    }
  }
);
}
 

Example 38

From project guice-jit-providers, under directory /extensions/assistedinject/src/com/google/inject/assistedinject/.

Source file: FactoryProvider.java

  31 
vote

public F get(){
  InvocationHandler invocationHandler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] creationArgs) throws Throwable {
      if (method.getDeclaringClass().equals(Object.class)) {
        return method.invoke(this,creationArgs);
      }
      AssistedConstructor<?> constructor=factoryMethodToConstructor.get(method);
      Object[] constructorArgs=gatherArgsForConstructor(constructor,creationArgs);
      Object objectToReturn=constructor.newInstance(constructorArgs);
      injector.injectMembers(objectToReturn);
      return objectToReturn;
    }
    public Object[] gatherArgsForConstructor(    AssistedConstructor<?> constructor,    Object[] factoryArgs){
      int numParams=constructor.getAllParameters().size();
      int argPosition=0;
      Object[] result=new Object[numParams];
      for (int i=0; i < numParams; i++) {
        Parameter parameter=constructor.getAllParameters().get(i);
        if (parameter.isProvidedByFactory()) {
          result[i]=factoryArgs[argPosition];
          argPosition++;
        }
 else {
          result[i]=parameter.getValue(injector);
        }
      }
      return result;
    }
  }
;
  @SuppressWarnings("unchecked") Class<F> factoryRawType=(Class)factoryType.getRawType();
  return factoryRawType.cast(Proxy.newProxyInstance(BytecodeGen.getClassLoader(factoryRawType),new Class[]{factoryRawType},invocationHandler));
}
 

Example 39

From project javassist, under directory /src/main/javassist/bytecode/annotation/.

Source file: AnnotationImpl.java

  31 
vote

/** 
 * Check that another annotation equals ourselves.
 * @param obj the other annotation
 * @return the true when equals false otherwise
 * @throws Exception for any problem
 */
private boolean checkEquals(Object obj) throws Exception {
  if (obj == null)   return false;
  if (obj instanceof Proxy) {
    InvocationHandler ih=Proxy.getInvocationHandler(obj);
    if (ih instanceof AnnotationImpl) {
      AnnotationImpl other=(AnnotationImpl)ih;
      return annotation.equals(other.annotation);
    }
  }
  Class otherAnnotationType=(Class)JDK_ANNOTATION_TYPE_METHOD.invoke(obj,(Object[])null);
  if (getAnnotationType().equals(otherAnnotationType) == false)   return false;
  Method[] methods=annotationType.getDeclaredMethods();
  for (int i=0; i < methods.length; ++i) {
    String name=methods[i].getName();
    MemberValue mv=annotation.getMemberValue(name);
    Object value=null;
    Object otherValue=null;
    try {
      if (mv != null)       value=mv.getValue(classLoader,pool,methods[i]);
      if (value == null)       value=getDefault(name,methods[i]);
      otherValue=methods[i].invoke(obj,(Object[])null);
    }
 catch (    RuntimeException e) {
      throw e;
    }
catch (    Exception e) {
      throw new RuntimeException("Error retrieving value " + name + " for annotation "+ annotation.getTypeName(),e);
    }
    if (value == null && otherValue != null)     return false;
    if (value != null && value.equals(otherValue) == false)     return false;
  }
  return true;
}
 

Example 40

From project jboss-ejb3-singleton, under directory /aop-impl/src/main/java/org/jboss/ejb3/singleton/aop/impl/.

Source file: AOPBasedSingletonContainer.java

  31 
vote

/** 
 * @see org.jboss.ejb3.EJBContainer#getEnc()
 */
@Override public Context getEnc(){
  if (this.javaComp == null) {
    ClassLoader tccl=Thread.currentThread().getContextClassLoader();
    Class<?> interfaces[]={Context.class};
    InvocationHandler handler=new InvocationHandler(){
      public Object invoke(      Object proxy,      Method method,      Object[] args) throws Throwable {
        try {
          if (AOPBasedSingletonContainer.this.javaComp == null) {
            throw new IllegalStateException("java:comp is not expected to be used before CREATE of EJB container. Failing bean: " + AOPBasedSingletonContainer.this.getBeanClassName());
          }
          return method.invoke(AOPBasedSingletonContainer.this.javaComp.getContext(),args);
        }
 catch (        InvocationTargetException e) {
          throw e.getTargetException();
        }
      }
    }
;
    return (Context)Proxy.newProxyInstance(tccl,interfaces,handler);
  }
  return this.javaComp.getContext();
}
 

Example 41

From project junit-rules, under directory /src/test/java/junit/rules/jndi/.

Source file: StubJndiContextTest.java

  31 
vote

/** 
 */
@Before public void setUp(){
  stubJndiContext.bind("jdbc/dataSource",Proxy.newProxyInstance(DataSource.class.getClassLoader(),new Class[]{DataSource.class},new InvocationHandler(){
    @Override public Object invoke(    final Object proxy,    final Method method,    final Object[] args) throws Throwable {
      throw new UnsupportedOperationException("Not yet implemented");
    }
  }
));
}
 

Example 42

From project junit.contrib, under directory /assertthrows/src/test/java/org/junit/contrib/assertthrows/proxy/.

Source file: InterfaceProxyFactoryTest.java

  31 
vote

<T>T createProxy(final T obj){
  return InterfaceProxyFactory.getInstance().createProxy(obj,new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Exception {
      buff.append(method.getName());
      Object o=method.invoke(obj,args);
      buff.append(" = ").append(o);
      methodCallCount++;
      return o;
    }
  }
);
}
 

Example 43

From project kevoree-library, under directory /android/org.kevoree.library.android.osmdroid/src/main/java/net/wigle/wigleandroid/.

Source file: ZoomButtonsController.java

  31 
vote

public void setOnZoomListener(final OnZoomListener listener){
  if (controller != null) {
    try {
      final InvocationHandler handler=new InvocationHandler(){
        public Object invoke(        Object object,        Method method,        Object[] args){
          logger.info("invoke: " + method.getName() + " listener: "+ listener);
          if ("onZoom".equals(method.getName())) {
            listener.onZoom((Boolean)args[0]);
          }
 else           if ("onVisibilityChanged".equals(method.getName())) {
            listener.onVisibilityChanged((Boolean)args[0]);
          }
 else {
            logger.info("unhandled listener method: " + method);
          }
          return null;
        }
      }
;
      Object proxy=Proxy.newProxyInstance(LISTENER_CLASS.getClassLoader(),new Class[]{LISTENER_CLASS},handler);
      setOnZoomListener.invoke(controller,proxy);
    }
 catch (    Exception ex) {
      logger.error("setOnZoomListener exception: " + ex);
    }
  }
}
 

Example 44

From project lmock, under directory /src/com/vmware/lmock/impl/.

Source file: Mock.java

  31 
vote

/** 
 * Gets the proxy object that THEORETICALLY wraps a mock object.
 * @param < T > the type of the requested object
 * @param object the requested object
 * @return The corresponding proxy object, always valid.
 * @throws MockReferenceException The specified object is not a mock.
 */
protected static <T>Mock getProxyOrThrow(T object) throws MockReferenceException {
  logger.trace("getProxyOrThrow",null,"object=",object);
  try {
    InvocationHandler handler=Proxy.getInvocationHandler(object);
    if (handler instanceof Mock) {
      return (Mock)handler;
    }
 else {
      throw new MockReferenceException("referencing a non-mock object");
    }
  }
 catch (  Exception e) {
    throw new MockReferenceException("referencing a non-mock object",e);
  }
}
 

Example 45

From project makegood, under directory /com.piece_framework.makegood.aspect/lib/javassist-3.11.0/src/main/javassist/bytecode/annotation/.

Source file: AnnotationImpl.java

  31 
vote

/** 
 * Check that another annotation equals ourselves.
 * @param obj the other annotation
 * @return the true when equals false otherwise
 * @throws Exception for any problem
 */
private boolean checkEquals(Object obj) throws Exception {
  if (obj == null)   return false;
  if (obj instanceof Proxy) {
    InvocationHandler ih=Proxy.getInvocationHandler(obj);
    if (ih instanceof AnnotationImpl) {
      AnnotationImpl other=(AnnotationImpl)ih;
      return annotation.equals(other.annotation);
    }
  }
  Class otherAnnotationType=(Class)JDK_ANNOTATION_TYPE_METHOD.invoke(obj,(Object[])null);
  if (getAnnotationType().equals(otherAnnotationType) == false)   return false;
  Method[] methods=annotationType.getDeclaredMethods();
  for (int i=0; i < methods.length; ++i) {
    String name=methods[i].getName();
    MemberValue mv=annotation.getMemberValue(name);
    Object value=null;
    Object otherValue=null;
    try {
      if (mv != null)       value=mv.getValue(classLoader,pool,methods[i]);
      if (value == null)       value=getDefault(name,methods[i]);
      otherValue=methods[i].invoke(obj,(Object[])null);
    }
 catch (    RuntimeException e) {
      throw e;
    }
catch (    Exception e) {
      throw new RuntimeException("Error retrieving value " + name + " for annotation "+ annotation.getTypeName(),e);
    }
    if (value == null && otherValue != null)     return false;
    if (value != null && value.equals(otherValue) == false)     return false;
  }
  return true;
}
 

Example 46

From project maven3-support, under directory /maven3-plugin/src/main/java/org/hudsonci/maven/plugin/builder/internal/.

Source file: StartProcessing.java

  31 
vote

/** 
 * Initializes  {@link Callback} via {@link CallbackManager}. Sets up invoke handlers to deal with  {@link Callback#close()}.
 */
public Object call() throws Exception {
  log.debug("Preparing to start processing");
  final Object lock=new Object();
  InvocationHandler chain;
  chain=new RemoteInvokeHandler(invoker);
  chain=new CallbackCloseAwareHandler(chain){
    @Override protected void onClose(){
      log.debug("Close invoked; notifying to stop processing");
synchronized (lock) {
        lock.notifyAll();
      }
    }
  }
;
  RecordingHandler recorder=null;
  if (recordFile != null) {
    chain=recorder=new RecordingHandler(chain,recordFile);
  }
  chain=new ObjectLocalHandler(chain);
  Callback callback=(Callback)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{Callback.class},chain);
  log.debug("Prepared callback: {}",callback);
  CallbackManager.set(callback);
  log.debug("Started");
synchronized (lock) {
    lock.wait();
  }
  if (recorder != null) {
    recorder.close();
  }
  log.debug("Processing stopped");
  return null;
}
 

Example 47

From project mawLib, under directory /src/mxj/trunk/smsLib-mxj/src/org/smslib/helper/.

Source file: SerialPort.java

  31 
vote

/** 
 * Registers a SerialPortEventListener object to listen for SerialEvents. Interest in specific events may be expressed using the notifyOnXXX calls. The serialEvent method of SerialPortEventListener will be called with a SerialEvent object describing the event. The current implementation only allows one listener per SerialPort. Once a listener is registered, subsequent call attempts to addEventListener will throw a TooManyListenersException without effecting the listener already registered. All the events received by this listener are generated by one dedicated thread that belongs to the SerialPort object. After the port is closed, no more event will be generated. Another call to open() of the port's CommPortIdentifier object will return a new CommPort object, and the lsnr has to be added again to the new CommPort object to receive event from this port.
 * @param lsnr The SerialPortEventListener object whose serialEvent method will be called with a SerialEvent describing the event.
 * @throws java.util.TooManyListenersException (Wrapped as RuntimeException) If an initial attempt to attach a listener succeeds, subsequent attempts will throw TooManyListenersException without effecting the first listener.
 */
public void addEventListener(final SerialPortEventListener lsnr){
  try {
    Method method=ReflectionHelper.getMethodOnlyByName(classSerialPort,"addEventListener");
    Class<?> eventI=method.getParameterTypes()[0];
    InvocationHandler handler=new SerialPortEventListenerHandler(lsnr);
    Class<?> proxyClass=Proxy.getProxyClass(eventI.getClassLoader(),eventI);
    method.invoke(this.realObject,proxyClass.getConstructor(InvocationHandler.class).newInstance(handler));
  }
 catch (  InvocationTargetException e) {
    throw new RuntimeException(new RuntimeException(e.getTargetException().toString()));
  }
catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 48

From project narya, under directory /core/src/main/java/com/threerings/presents/peer/util/.

Source file: PeerUtil.java

  31 
vote

/** 
 * Creates a proxy object implementing the specified provider interface (a subinterface of {@link InvocationProvider} that forwards requests to the given service implementation(a subinterface of  {@link InvocationService} corresponding to the provider interface)on the specified client.  This is useful for server entities that need to call a method either on the current server (with <code>null</code> as the caller parameter) or on a peer server.
 * @param clazz the subclass of {@link InvocationProvider} desired to be implemented
 * @param svc the implementation of the corresponding subclass of {@link InvocationService}
 * @param client the client to pass to the service methods
 */
public static <S extends InvocationProvider,T extends InvocationService<?>>S createProviderProxy(Class<S> clazz,final T svc,final Client client){
  return clazz.cast(Proxy.newProxyInstance(clazz.getClassLoader(),new Class<?>[]{clazz},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      Method smethod=_pmethods.get(method);
      if (smethod == null) {
        Class<?>[] ptypes=method.getParameterTypes();
        _pmethods.put(method,smethod=svc.getClass().getMethod(method.getName(),ArrayUtil.splice(ptypes,0,1)));
      }
      return smethod.invoke(svc,ArrayUtil.splice(args,0,1));
    }
  }
));
}
 

Example 49

From project nuxeo-tycho-osgi, under directory /nuxeo-runtime/nuxeo-runtime/src/main/java/org/nuxeo/runtime/remoting/transporter/.

Source file: TransporterClient.java

  31 
vote

/** 
 * Needs to be called by user when no longer need to make calls on remote POJO. Otherwise will maintain remote connection until this is called.
 */
public static void destroyTransporterClient(Object transporterClient){
  if (transporterClient instanceof Proxy) {
    InvocationHandler handler=Proxy.getInvocationHandler(transporterClient);
    if (handler instanceof TransporterClient) {
      TransporterClient client=(TransporterClient)handler;
      client.disconnect();
    }
 else {
      throw new IllegalArgumentException("Object is not a transporter client.");
    }
  }
 else {
    throw new IllegalArgumentException("Object is not a transporter client.");
  }
}
 

Example 50

From project openengsb-framework, under directory /components/services/src/test/java/org/openengsb/core/services/internal/.

Source file: UserDataManagerImplTest.java

  31 
vote

private void setupUserManager(){
  final UserDataManagerImpl userManager=new UserDataManagerImpl();
  userManager.setEntityManager(entityManager);
  InvocationHandler invocationHandler=new InvocationHandler(){
    @Override public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      entityManager.getTransaction().begin();
      Object result;
      try {
        result=method.invoke(userManager,args);
      }
 catch (      InvocationTargetException e) {
        entityManager.getTransaction().rollback();
        throw e.getCause();
      }
      entityManager.getTransaction().commit();
      return result;
    }
  }
;
  this.userManager=(UserDataManager)Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class<?>[]{UserDataManager.class},invocationHandler);
  Dictionary<String,Object> props=new Hashtable<String,Object>();
  props.put(Constants.PROVIDED_CLASSES_KEY,TestPermission.class.getName());
  props.put(Constants.DELEGATION_CONTEXT_KEY,org.openengsb.core.api.Constants.DELEGATION_CONTEXT_PERMISSIONS);
  ClassProvider permissionProvider=new ClassProviderImpl(bundle,Sets.newHashSet(TestPermission.class.getName()));
  registerService(permissionProvider,props,ClassProvider.class);
}
 

Example 51

From project pad, under directory /infrastructure/rhino1_7R1/src/org/mozilla/javascript/jdk13/.

Source file: VMBridge_jdk13.java

  31 
vote

protected Object newInterfaceProxy(Object proxyHelper,final ContextFactory cf,final InterfaceAdapter adapter,final Object target,final Scriptable topScope){
  Constructor c=(Constructor)proxyHelper;
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args){
      return adapter.invoke(cf,target,topScope,method,args);
    }
  }
;
  Object proxy;
  try {
    proxy=c.newInstance(new Object[]{handler});
  }
 catch (  InvocationTargetException ex) {
    throw Context.throwAsScriptRuntimeEx(ex);
  }
catch (  IllegalAccessException ex) {
    throw Kit.initCause(new IllegalStateException(),ex);
  }
catch (  InstantiationException ex) {
    throw Kit.initCause(new IllegalStateException(),ex);
  }
  return proxy;
}
 

Example 52

From project pegadi, under directory /client/src/main/java/org/pegadi/client/.

Source file: ApplicationLauncher.java

  31 
vote

/** 
 * This method registers a listener for the Quit-menuitem on OS X application menu. To avoid platform dependent compilation, reflection is utilized. <p/> Basically what happens, is this: <p/> Application app = Application.getApplication(); app.addApplicationListener(new ApplicationAdapter() { public void handleQuit(ApplicationEvent e) { e.setHandled(false); conditionalExit(); } });
 */
private void registerOSXApplicationMenu(){
  try {
    ClassLoader cl=getClass().getClassLoader();
    final Class comAppleEawtApplicationClass=cl.loadClass("com.apple.eawt.Application");
    final Class comAppleEawtApplicationListenerInterface=cl.loadClass("com.apple.eawt.ApplicationListener");
    final Class comAppleEawtApplicationEventClass=cl.loadClass("com.apple.eawt.ApplicationEvent");
    final Method applicationEventSetHandledMethod=comAppleEawtApplicationEventClass.getMethod("setHandled",new Class[]{boolean.class});
    InvocationHandler handler=new InvocationHandler(){
      public Object invoke(      Object proxy,      Method method,      Object[] args) throws Throwable {
        if (method.getName().equals("handleQuit")) {
          applicationEventSetHandledMethod.invoke(args[0],new Object[]{Boolean.FALSE});
          conditionalExit();
        }
        return null;
      }
    }
;
    Object applicationListenerProxy=Proxy.newProxyInstance(cl,new Class[]{comAppleEawtApplicationListenerInterface},handler);
    Method applicationGetApplicationMethod=comAppleEawtApplicationClass.getMethod("getApplication",new Class[0]);
    Object theApplicationObject=applicationGetApplicationMethod.invoke(null,new Object[0]);
    Method addApplicationListenerMethod=comAppleEawtApplicationClass.getMethod("addApplicationListener",new Class[]{comAppleEawtApplicationListenerInterface});
    addApplicationListenerMethod.invoke(theApplicationObject,new Object[]{applicationListenerProxy});
  }
 catch (  Exception e) {
    log.info("we are not on OSX");
  }
}
 

Example 53

From project platform_external_guava, under directory /src/com/google/common/util/concurrent/.

Source file: SimpleTimeLimiter.java

  31 
vote

public <T>T newProxy(final T target,Class<T> interfaceType,final long timeoutDuration,final TimeUnit timeoutUnit){
  checkNotNull(target);
  checkNotNull(interfaceType);
  checkNotNull(timeoutUnit);
  checkArgument(timeoutDuration > 0,"bad timeout: " + timeoutDuration);
  checkArgument(interfaceType.isInterface(),"interfaceType must be an interface type");
  final Set<Method> interruptibleMethods=findInterruptibleMethods(interfaceType);
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    Object obj,    final Method method,    final Object[] args) throws Throwable {
      Callable<Object> callable=new Callable<Object>(){
        public Object call() throws Exception {
          try {
            return method.invoke(target,args);
          }
 catch (          InvocationTargetException e) {
            Throwables.throwCause(e,false);
            throw new AssertionError("can't get here");
          }
        }
      }
;
      return callWithTimeout(callable,timeoutDuration,timeoutUnit,interruptibleMethods.contains(method));
    }
  }
;
  return newProxy(interfaceType,handler);
}
 

Example 54

From project platform_external_javassist, under directory /src/main/javassist/bytecode/annotation/.

Source file: AnnotationImpl.java

  31 
vote

/** 
 * Check that another annotation equals ourselves.
 * @param obj the other annotation
 * @return the true when equals false otherwise
 * @throws Exception for any problem
 */
private boolean checkEquals(Object obj) throws Exception {
  if (obj == null)   return false;
  if (obj instanceof Proxy) {
    InvocationHandler ih=Proxy.getInvocationHandler(obj);
    if (ih instanceof AnnotationImpl) {
      AnnotationImpl other=(AnnotationImpl)ih;
      return annotation.equals(other.annotation);
    }
  }
  Class otherAnnotationType=(Class)JDK_ANNOTATION_TYPE_METHOD.invoke(obj,(Object[])null);
  if (getAnnotationType().equals(otherAnnotationType) == false)   return false;
  Method[] methods=annotationType.getDeclaredMethods();
  for (int i=0; i < methods.length; ++i) {
    String name=methods[i].getName();
    MemberValue mv=annotation.getMemberValue(name);
    Object value=null;
    Object otherValue=null;
    try {
      if (mv != null)       value=mv.getValue(classLoader,pool,methods[i]);
      if (value == null)       value=getDefault(name,methods[i]);
      otherValue=methods[i].invoke(obj,(Object[])null);
    }
 catch (    RuntimeException e) {
      throw e;
    }
catch (    Exception e) {
      throw new RuntimeException("Error retrieving value " + name + " for annotation "+ annotation.getTypeName(),e);
    }
    if (value == null && otherValue != null)     return false;
    if (value != null && value.equals(otherValue) == false)     return false;
  }
  return true;
}
 

Example 55

From project Possom, under directory /data-model-javabean-impl/src/main/java/no/sesat/search/datamodel/.

Source file: DataModelFactoryImpl.java

  31 
vote

@SuppressWarnings("unchecked") public DataModel instantiate(){
  try {
    final Class<DataModel> cls=DataModel.class;
    final PropertyDescriptor[] propDescriptors=Introspector.getBeanInfo(DataModel.class).getPropertyDescriptors();
    final Property[] properties=new Property[propDescriptors.length];
    for (int i=0; i < properties.length; ++i) {
      properties[i]=new Property(propDescriptors[i].getName(),propDescriptors[i] instanceof MappedPropertyDescriptor ? new MapDataObjectSupport(Collections.EMPTY_MAP) : null);
    }
    final InvocationHandler handler=new BeanDataModelInvocationHandler(new BeanDataModelInvocationHandler.PropertyInitialisor(DataModel.class,properties));
    return (DataModel)ConcurrentProxy.newProxyInstance(cls.getClassLoader(),new Class[]{cls},handler);
  }
 catch (  IntrospectionException ie) {
    throw new IllegalStateException("Need to introspect DataModel properties before instantiation");
  }
}
 

Example 56

From project prevayler, under directory /extras/facade/src/main/java/org/prevayler/contrib/facade/.

Source file: PrevaylerTransactionsFacade.java

  31 
vote

/** 
 * @since 0_2
 */
public static Object create(final Class p_intf,final Prevayler p_prevayler,final TransactionType.Determiner p_determiner,final TransactionHint p_hint){
  return Proxy.newProxyInstance(p_intf.getClassLoader(),new Class[]{p_intf},new InvocationHandler(){
    public Object invoke(    Object p_proxy,    Method p_method,    Object[] p_args) throws Throwable {
      return p_determiner.determineTransactionType(p_method).execute(p_prevayler,p_method,p_args,p_hint);
    }
  }
);
}
 

Example 57

From project rave, under directory /rave-components/rave-commons/src/test/java/org/apache/rave/synchronization/.

Source file: SynchronizingAspectTest.java

  31 
vote

@Test public void testStaticDiscriminatorStaticIdEmptyConditionJdkProxy() throws Throwable {
  String expectedDiscriminator="StaticDiscriminator";
  String expectedId="staticId";
  String expectedResult="testStaticDiscriminatorStaticIdEmptyCondition";
  InvocationHandler handler=new InvocationHandler(){
    @Override public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      if (method.getName().equals("getTargetClass")) {
        return DefaultTestService.class;
      }
 else       if (method.getName().equals("testStaticDiscriminatorStaticIdEmptyCondition")) {
        return "testStaticDiscriminatorStaticIdEmptyCondition";
      }
 else {
        throw new RuntimeException();
      }
    }
  }
;
  TestService service=(TestService)Proxy.newProxyInstance(DefaultTestService.class.getClassLoader(),new Class[]{TestService.class,TargetClassAware.class},handler);
  Method expectedMethod=service.getClass().getDeclaredMethod("testStaticDiscriminatorStaticIdEmptyCondition",TestObject.class);
  TestObject argument=new TestObject(1L,"Jesse");
  Object[] joinPointArgs={argument};
  ProceedingJoinPoint joinPoint=prepareJoinPoint(expectedDiscriminator,expectedId,service,expectedMethod,argument,joinPointArgs);
  String result=(String)aspect.synchronizeInvocation(joinPoint);
  assertThat(result,is(expectedResult));
}
 

Example 58

From project Rhino-for-J2ME-CDC1.1, under directory /src/org/mozilla/javascript/jdk13/.

Source file: VMBridge_jdk13.java

  31 
vote

protected Object newInterfaceProxy(Object proxyHelper,final ContextFactory cf,final InterfaceAdapter adapter,final Object target,final Scriptable topScope){
  Constructor c=(Constructor)proxyHelper;
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args){
      return adapter.invoke(cf,target,topScope,method,args);
    }
  }
;
  Object proxy;
  try {
    proxy=c.newInstance(new Object[]{handler});
  }
 catch (  InvocationTargetException ex) {
    throw Context.throwAsScriptRuntimeEx(ex);
  }
catch (  IllegalAccessException ex) {
    throw Kit.initCause(new IllegalStateException(),ex);
  }
catch (  InstantiationException ex) {
    throw Kit.initCause(new IllegalStateException(),ex);
  }
  return proxy;
}
 

Example 59

From project servicemix4-features, under directory /camel/servicemix-camel/src/test/java/org/apache/servicemix/camel/nmr/.

Source file: AttachmentTest.java

  31 
vote

private <T>T createPort(QName serviceName,QName portName,Class<T> serviceEndpointInterface,boolean enableMTOM) throws Exception {
  Bus bus=BusFactory.getDefaultBus();
  ReflectionServiceFactoryBean serviceFactory=new JaxWsServiceFactoryBean();
  serviceFactory.setBus(bus);
  serviceFactory.setServiceName(serviceName);
  serviceFactory.setServiceClass(serviceEndpointInterface);
  serviceFactory.setWsdlURL(getClass().getResource("/wsdl/mtom_xop.wsdl"));
  Service service=serviceFactory.create();
  EndpointInfo ei=service.getEndpointInfo(portName);
  JaxWsEndpointImpl jaxwsEndpoint=new JaxWsEndpointImpl(bus,service,ei);
  SOAPBinding jaxWsSoapBinding=new SOAPBindingImpl(ei.getBinding(),jaxwsEndpoint);
  jaxWsSoapBinding.setMTOMEnabled(enableMTOM);
  Client client=new ClientImpl(bus,jaxwsEndpoint);
  InvocationHandler ih=new JaxWsClientProxy(client,jaxwsEndpoint.getJaxwsBinding());
  Object obj=Proxy.newProxyInstance(serviceEndpointInterface.getClassLoader(),new Class[]{serviceEndpointInterface,BindingProvider.class},ih);
  return serviceEndpointInterface.cast(obj);
}
 

Example 60

From project sisu-guice, under directory /extensions/assistedinject/src/com/google/inject/assistedinject/.

Source file: FactoryProvider.java

  31 
vote

public F get(){
  InvocationHandler invocationHandler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] creationArgs) throws Throwable {
      if (method.getDeclaringClass().equals(Object.class)) {
        return method.invoke(this,creationArgs);
      }
      AssistedConstructor<?> constructor=factoryMethodToConstructor.get(method);
      Object[] constructorArgs=gatherArgsForConstructor(constructor,creationArgs);
      Object objectToReturn=constructor.newInstance(constructorArgs);
      injector.injectMembers(objectToReturn);
      return objectToReturn;
    }
    public Object[] gatherArgsForConstructor(    AssistedConstructor<?> constructor,    Object[] factoryArgs){
      int numParams=constructor.getAllParameters().size();
      int argPosition=0;
      Object[] result=new Object[numParams];
      for (int i=0; i < numParams; i++) {
        Parameter parameter=constructor.getAllParameters().get(i);
        if (parameter.isProvidedByFactory()) {
          result[i]=factoryArgs[argPosition];
          argPosition++;
        }
 else {
          result[i]=parameter.getValue(injector);
        }
      }
      return result;
    }
  }
;
  @SuppressWarnings("unchecked") Class<F> factoryRawType=(Class)factoryType.getRawType();
  return factoryRawType.cast(Proxy.newProxyInstance(BytecodeGen.getClassLoader(factoryRawType),new Class[]{factoryRawType},invocationHandler));
}
 

Example 61

From project spring-insight-plugins, under directory /collection-plugins/jdbc/src/test/java/com/springsource/insight/plugin/jdbc/.

Source file: JdbcConnectionCloseOperationCollectionAspectTest.java

  31 
vote

@Test public void testCloseException() throws Exception {
  Class<?>[] interfaces={Connection.class};
  final SQLException toThrow=new SQLException("testCloseException");
  InvocationHandler h=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      if ("close".equals(method.getName())) {
        throw toThrow;
      }
      return null;
    }
  }
;
  Connection conn=(Connection)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),interfaces,h);
  final String URL="jdbc:test:testCloseException";
  tracker.startTracking(conn,URL);
  try {
    conn.close();
    fail("Unexpected closure success");
  }
 catch (  SQLException e) {
    assertSame("Mismatched thrown exception",toThrow,e);
  }
  assertCloseDetails(URL);
}
 

Example 62

From project titanpad, under directory /infrastructure/rhino1_7R1/src/org/mozilla/javascript/jdk13/.

Source file: VMBridge_jdk13.java

  31 
vote

protected Object newInterfaceProxy(Object proxyHelper,final ContextFactory cf,final InterfaceAdapter adapter,final Object target,final Scriptable topScope){
  Constructor c=(Constructor)proxyHelper;
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args){
      return adapter.invoke(cf,target,topScope,method,args);
    }
  }
;
  Object proxy;
  try {
    proxy=c.newInstance(new Object[]{handler});
  }
 catch (  InvocationTargetException ex) {
    throw Context.throwAsScriptRuntimeEx(ex);
  }
catch (  IllegalAccessException ex) {
    throw Kit.initCause(new IllegalStateException(),ex);
  }
catch (  InstantiationException ex) {
    throw Kit.initCause(new IllegalStateException(),ex);
  }
  return proxy;
}
 

Example 63

From project tycho, under directory /tycho-core/src/main/java/org/eclipse/tycho/core/osgitools/.

Source file: StandalonePluginConverter.java

  31 
vote

/** 
 * create a dummy BundleContext. This workaround allows us to reuse  {@link PluginConverterImpl}outside a running OSGi framework
 */
private static BundleContext createDummyContext(){
  return (BundleContext)Proxy.newProxyInstance(BundleContext.class.getClassLoader(),new Class[]{BundleContext.class},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      return null;
    }
  }
);
}
 

Example 64

From project zen-project, under directory /zen-webservice/src/main/java/com/nominanuda/hyperapi/async/.

Source file: AbstractAsyncInvoker.java

  31 
vote

@SuppressWarnings("unchecked") public <T,Z>Z async(final Z delegee,final SuccessCallback<T> ss,final ErrorCallback ee){
  InvocationHandler handler=new InvocationHandler(){
    public Object invoke(    final Object proxy,    final Method m,    final Object[] args) throws Throwable {
      Callable<T> task=new Callable<T>(){
        public T call() throws Exception {
          try {
            T res=(T)m.invoke(delegee,args);
            invokeSuccessCb(res,ss);
            return res;
          }
 catch (          InvocationTargetException e) {
            invokeErrorCb(ee,(Exception)e.getTargetException());
            return null;
          }
catch (          Exception e) {
            e.printStackTrace();
            throw e;
          }
        }
      }
;
      FutureTask<T> fut=new FutureTask<T>(task);
      executeFutureTask(fut);
      futures.add(fut);
      return null;
    }
  }
;
  Object proxy=Proxy.newProxyInstance(getClass().getClassLoader(),delegee.getClass().getInterfaces(),handler);
  return (Z)proxy;
}
 

Example 65

From project Blitz, under directory /src/com/laxser/blitz/lama/provider/.

Source file: DataAccessProviderMock.java

  30 
vote

@Override public DataAccess createDataAccess(Class<?> daoClass){
  if (logger.isWarnEnabled()) {
    logger.warn("lama is not configured, return mock instance");
  }
  return (DataAccess)Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(),new Class[]{DataAccess.class},new InvocationHandler(){
    @Override public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      if (method.getDeclaringClass() == DataAccess.class) {
        if (logger.isWarnEnabled()) {
          logger.warn("lama is not configured");
        }
        throw new IllegalStateException("lama is not configured");
      }
      return method.invoke(proxy,args);
    }
  }
);
}
 

Example 66

From project capedwarf-blue, under directory /common/src/main/java/org/jboss/capedwarf/common/jndi/.

Source file: JndiLookupUtils.java

  30 
vote

@SuppressWarnings({"unchecked"}) public static <T>T lazyLookup(final String propertyKey,final Class<T> expected,final String... names){
  if (propertyKey == null)   throw new IllegalArgumentException("Null property key.");
  if (expected == null)   throw new IllegalArgumentException("Null expected class");
  if (expected.isInterface()) {
    return expected.cast(Proxy.newProxyInstance(expected.getClassLoader(),new Class[]{expected},new InvocationHandler(){
      private volatile Object delegate;
      public Object invoke(      Object proxy,      Method method,      Object[] args) throws Throwable {
        if (delegate == null) {
synchronized (this) {
            if (delegate == null)             delegate=lookup(propertyKey,expected,names);
          }
        }
        return method.invoke(delegate,args);
      }
    }
));
  }
 else {
    final MethodHandler handler=new MethodHandler(){
      private volatile Object delegate;
      public Object invoke(      Object self,      Method thisMethod,      Method proceed,      Object[] args) throws Throwable {
        if (delegate == null) {
synchronized (this) {
            if (delegate == null)             delegate=lookup(propertyKey,expected,names);
          }
        }
        return thisMethod.invoke(delegate,args);
      }
    }
;
    return BytecodeUtils.proxy(expected,handler);
  }
}
 

Example 67

From project capedwarf-green, under directory /server-api/src/main/java/org/jboss/capedwarf/server/api/dao/impl/.

Source file: AbstractGenericDAO.java

  30 
vote

@SuppressWarnings({"unchecked"}) @Transactional(TransactionPropagationType.REQUIRED) @Proxying(ProxyingEnum.DISABLE) public StatelessDAO<T> statelessView(final boolean autoClose){
  return (StatelessDAO<T>)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{StatelessDAO.class},new InvocationHandler(){
    private StatelessDAO<T> delegate;
    /** 
 * Lazy get delegate.
 * @return the delegate
 */
    private synchronized StatelessDAO<T> getDelegate(){
      if (delegate == null)       delegate=new StatelessAdapter2DAOBridge<T>(statelessAdapterFactory.createStatelessAdapter(getEM()));
      return delegate;
    }
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      StatelessDAO<T> bridge=getDelegate();
      try {
        return method.invoke(bridge,args);
      }
  finally {
        if (autoClose)         bridge.close();
      }
    }
  }
);
}
 

Example 68

From project exo-training, under directory /design-pattern/src/main/java/org/example/visitor/proxy/dynamic/.

Source file: DynamicProxyDemo.java

  30 
vote

public static void main(String[] args){
  MyClass prox=(MyClass)Proxy.newProxyInstance(MyClass.class.getClassLoader(),new Class[]{MyClass.class},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      System.out.println("Proxy = " + proxy.getClass());
      System.out.println("Method = " + method);
      if (args != null) {
        System.out.println("args = ");
        for (int i=0; i < args.length; i++)         System.out.println("\t" + args[i]);
      }
      return null;
    }
  }
);
  System.out.println("about to call methodA");
  prox.methodA("hello");
  System.out.println("finish calling methodA");
  prox.methodB(47);
  prox.methodC("hello",47);
}
 

Example 69

From project gecko, under directory /src/test/java/com/taobao/gecko/example/rpc/client/.

Source file: RpcProxyFactory.java

  30 
vote

@SuppressWarnings("unchecked") public <T>T proxyRemote(final String uri,final String beanName,Class<T> serviceClass) throws IOException, InterruptedException {
  try {
    this.remotingClient.connect(uri);
    this.remotingClient.awaitReadyInterrupt(uri);
  }
 catch (  NotifyRemotingException e) {
    throw new IOException(e);
  }
  return (T)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class<?>[]{serviceClass},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      RpcRequest request=new RpcRequest(beanName,method.getName(),args);
      RpcResponse response=null;
      try {
        response=(RpcResponse)RpcProxyFactory.this.remotingClient.invokeToGroup(uri,request);
      }
 catch (      Exception e) {
        throw new RpcRuntimeException("Rpc failure",e);
      }
      if (response == null) {
        throw new RpcRuntimeException("Rpc failure,no response from rpc server");
      }
      if (response.getResponseStatus() == ResponseStatus.NO_ERROR) {
        return response.getResult();
      }
 else {
        throw new RpcRuntimeException("Rpc failure:" + response.getErrorMsg());
      }
    }
  }
);
}
 

Example 70

From project HBase-Lattice, under directory /hbl/src/main/java/com/inadco/hbl/util/.

Source file: IOUtil.java

  30 
vote

/** 
 * a wrapping proxy for interfaces implementing Closeable. it implements two-state fail-fast state pattern which basically has two states: before close and after. any attempt to call resource method after it has been closed would fail. <P> But it does not to make attempt to wait till the end of current invocations to complete if close() is called, which means it may be possible to actually attempt to invoke close() twice if attempts to close made before any of them had actually completed. Which is why it is fail-fast detection, i.e. no attempt to serialize invocations is made. <P>
 */
public static <T extends Closeable>T wrapCloseable(final T delegate,Class<T> iface){
  return iface.cast(Proxy.newProxyInstance(delegate.getClass().getClassLoader(),new Class<?>[]{iface},new InvocationHandler(){
    private boolean m_closedState=false;
    @Override public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      if (m_closedState) {
        throw new IOException("attempt to invoke a closed resource.");
      }
      try {
        if (method.equals(s_closeMethod)) {
          m_closedState=true;
        }
 else         if (method.equals(s_equalsMethod) && proxy == args[0]) {
          args[0]=delegate;
        }
        return method.invoke(delegate,args);
      }
 catch (      InvocationTargetException exc) {
        throw exc.getTargetException();
      }
    }
  }
));
}
 

Example 71

From project jolokia, under directory /agent/osgi/src/test/java/org/jolokia/osgi/.

Source file: JolokiaActivatorTest.java

  30 
vote

private Filter createFilterMockWithToString(final String filter,final String additionalFilter){
  return (Filter)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{Filter.class},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      if (method.getName().equals("toString")) {
        if (additionalFilter == null) {
          return filter;
        }
 else {
          return "(&" + filter + additionalFilter+ ")";
        }
      }
      throw new UnsupportedOperationException("Sorry this is a very limited proxy implementation of Filter");
    }
  }
);
}
 

Example 72

From project jpropel-light, under directory /src/propel/core/utils/.

Source file: ReflectionUtils.java

  30 
vote

/** 
 * Quick-and-dirty proxy-ing utility method, allows dynamic dispatch on any object using a specified interface. The run-time object and the interface given need not have an inheritance relationship. Method calls to interface methods are routed to the given run-time object. TODO: support overloaded methods.
 * @throws NullPointerException An argument is null
 * @throws IllegalArgumentException The interface class type is not an actual interface type
 */
@Validate @SuppressWarnings("unchecked") public static <T>T proxy(@NotNull final Object obj,@NotNull final Class<T> interfaceType){
  if (!interfaceType.isInterface())   throw new IllegalArgumentException(interfaceType.getName() + " is not an interface!");
  return (T)Proxy.newProxyInstance(interfaceType.getClassLoader(),new Class[]{interfaceType},new InvocationHandler(){
    /** 
 * Dispatches method invocations to the original object, using reflection
 */
    @Override public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      String methodName=method.getName();
      Method dispatchedMethod=getMethod(obj.getClass(),methodName,true);
      if (dispatchedMethod == null)       throw new NoSuchMethodException("methodName=" + methodName);
      return dispatchedMethod.invoke(obj,args);
    }
  }
);
}
 

Example 73

From project jsf-test, under directory /stage/src/main/java/org/jboss/test/faces/staging/.

Source file: StagingServer.java

  30 
vote

/** 
 * Create instance of the  {@link InvocationHandler} for the proxy objects.This handler fire events to the registered  {@link InvocationListener} (if present ) after target object method call.
 * @return the invocationHandler
 */
InvocationHandler getInvocationHandler(final Object target){
  return new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      InvocationListener listener=getInvocationListener();
      try {
        Object result=method.invoke(target,args);
        if (null != listener) {
          listener.afterInvoke(new InvocationEvent(target,method,args,result));
        }
        return result;
      }
 catch (      Throwable e) {
        if (null != listener) {
          listener.processException(new InvocationErrorEvent(target,method,args,e));
        }
        throw e;
      }
    }
  }
;
}
 

Example 74

From project karaf, under directory /shell/console/src/main/java/org/apache/karaf/shell/console/impl/.

Source file: Converters.java

  30 
vote

public Object convert(Class<?> desiredType,final Object in) throws Exception {
  if (desiredType == Bundle.class) {
    return convertBundle(in);
  }
  if (desiredType == ServiceReference.class) {
    return convertServiceReference(in);
  }
  if (desiredType == Class.class) {
    try {
      return Class.forName(in.toString());
    }
 catch (    ClassNotFoundException e) {
      return null;
    }
  }
  if (desiredType.isAssignableFrom(String.class) && in instanceof InputStream) {
    return read(((InputStream)in));
  }
  if (in instanceof Function && desiredType.isInterface() && desiredType.getDeclaredMethods().length == 1) {
    return Proxy.newProxyInstance(desiredType.getClassLoader(),new Class[]{desiredType},new InvocationHandler(){
      Function command=((Function)in);
      public Object invoke(      Object proxy,      Method method,      Object[] args) throws Throwable {
        return command.execute(null,Arrays.asList(args));
      }
    }
);
  }
  return null;
}
 

Example 75

From project l2jserver2, under directory /l2jserver2-common/src/main/java/com/l2jserver/service/cache/.

Source file: EhCacheService.java

  30 
vote

@Override public <T extends Cacheable>T decorate(final Class<T> interfaceType,final T instance){
  Preconditions.checkNotNull(interfaceType,"interfaceType");
  Preconditions.checkNotNull(instance,"instance");
  Preconditions.checkArgument(interfaceType.isInterface(),"interfaceType is not an interface");
  log.debug("Decorating {} with cache",interfaceType);
  @SuppressWarnings("unchecked") final T proxy=(T)Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{interfaceType},new InvocationHandler(){
    @Override public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      if (method.isAnnotationPresent(IgnoreCaching.class))       return method.invoke(instance,args);
      final MethodInvocation invocation=new MethodInvocation(method,args);
      Object result=interfaceCache.get(invocation);
      if (result == null)       return doInvoke(invocation,proxy,method,args);
      return result;
    }
    private Object doInvoke(    MethodInvocation invocation,    Object proxy,    Method method,    Object[] args) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
      Object result=method.invoke(instance,args);
      interfaceCache.put(invocation,result);
      return result;
    }
  }
);
  return proxy;
}
 

Example 76

From project legacy-maven-support, under directory /maven-plugin/src/main/java/hudson/maven/.

Source file: MojoInfo.java

  30 
vote

/** 
 * Intercept the invocation from the mojo to its injected component (designated by the given field name.) <p> Often for a  {@link MavenReporter} to really figure out what's going on in a build, you'd liketo intercept one of the components that Maven is injecting into the mojo, and inspect its parameter and return values. <p> This mehod provides a way to do this. You specify the name of the field in the Mojo class that receives the injected component, then pass in  {@link InvocationInterceptor}, which will in turn be invoked for every invocation on that component.
 * @throws NoSuchFieldException if the specified field is not found on the mojo class, or it is found but the type is not an interface.
 * @since 1.232
 */
public void intercept(String fieldName,final InvocationInterceptor interceptor) throws NoSuchFieldException {
  for (Class c=mojo.getClass(); c != Object.class; c=c.getSuperclass()) {
    Field f;
    try {
      f=c.getDeclaredField(fieldName);
    }
 catch (    NoSuchFieldException e) {
      continue;
    }
    f.setAccessible(true);
    Class<?> type=f.getType();
    if (!type.isInterface())     throw new NoSuchFieldException(fieldName + " is of type " + type+ " and it's not an interface");
    try {
      final Object oldObject=f.get(mojo);
      Object newObject=Proxy.newProxyInstance(type.getClassLoader(),new Class[]{type},new InvocationHandler(){
        public Object invoke(        Object proxy,        Method method,        Object[] args) throws Throwable {
          return interceptor.invoke(proxy,method,args,new InvocationHandler(){
            public Object invoke(            Object proxy,            Method method,            Object[] args) throws Throwable {
              return method.invoke(oldObject,args);
            }
          }
);
        }
      }
);
      f.set(mojo,newObject);
    }
 catch (    IllegalAccessException e) {
      IllegalAccessError x=new IllegalAccessError(e.getMessage());
      x.initCause(e);
      throw x;
    }
  }
}
 

Example 77

From project openengsb-connector-trac, under directory /src/main/java/org/openengsb/connector/trac/internal/models/xmlrpc/.

Source file: TrackerDynamicProxy.java

  30 
vote

/** 
 * Creates an object, which is implementing the given interface. The objects methods are internally calling an XML-RPC server by using the factories client.
 */
@SuppressWarnings("unchecked") public <T>T newInstance(ClassLoader classLoader,final Class<T> clazz){
  return (T)Proxy.newProxyInstance(classLoader,new Class[]{clazz},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws InvocationTargetException, IllegalAccessException, XmlRpcException {
      if (isObjectMethodLocal() && method.getDeclaringClass().equals(Object.class)) {
        return method.invoke(proxy,args);
      }
      String classname=clazz.getName().replaceFirst(clazz.getPackage().getName() + ".","").toLowerCase();
      classname=classname.replace("$",".");
      String methodName=classname + "." + method.getName();
      Object result=client.execute(methodName,args);
      TypeConverter typeConverter=typeConverterFactory.getTypeConverter(method.getReturnType());
      return typeConverter.convert(result);
    }
  }
);
}
 

Example 78

From project org.ops4j.pax.web, under directory /pax-web-runtime/src/main/java/org/ops4j/pax/web/service/internal/.

Source file: HttpServiceStarted.java

  30 
vote

private ServletPlus makeProxyServlet(final Servlet servlet){
  return (ServletPlus)Proxy.newProxyInstance(ServletPlus.class.getClassLoader(),new Class[]{ServletPlus.class},new InvocationHandler(){
    private boolean initCalled=false;
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      Method initMethod=Servlet.class.getMethod("init",ServletConfig.class);
      Method getterMethod=ServletPlus.class.getMethod("isInitialized",null);
      if (method.equals(initMethod)) {
        LOG.debug("init called on " + servlet);
        initCalled=true;
      }
 else       if (method.equals(getterMethod)) {
        LOG.debug("isInitialized called for servlet: " + servlet + ". Return: "+ initCalled);
        return initCalled;
      }
      return method.invoke(servlet,args);
    }
  }
);
}
 

Example 79

From project Solbase-Solr, under directory /contrib/dataimporthandler/src/test/java/org/apache/solr/handler/dataimport/.

Source file: TestClobTransformer.java

  30 
vote

@Test public void simple() throws Exception {
  List<Map<String,String>> flds=new ArrayList<Map<String,String>>();
  Map<String,String> f=new HashMap<String,String>();
  f.put(DataImporter.COLUMN,"dsc");
  f.put(ClobTransformer.CLOB,"true");
  f.put(DataImporter.NAME,"description");
  flds.add(f);
  Context ctx=AbstractDataImportHandlerTest.getContext(null,new VariableResolverImpl(),null,Context.FULL_DUMP,flds,Collections.EMPTY_MAP);
  Transformer t=new ClobTransformer();
  Map<String,Object> row=new HashMap<String,Object>();
  Clob clob=(Clob)Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{Clob.class},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      if (method.getName().equals("getCharacterStream")) {
        return new StringReader("hello!");
      }
      return null;
    }
  }
);
  row.put("dsc",clob);
  t.transformRow(row,ctx);
  Assert.assertEquals("hello!",row.get("dsc"));
}
 

Example 80

From project springfaces, under directory /springfaces-integrationtest/springfaces-selenium/src/main/java/org/springframework/springfaces/integrationtest/selenium/.

Source file: WebDriverUtils.java

  30 
vote

/** 
 * Decorate the specified  {@link WebElement} with a version that will {@link #waitOnUrlChange(WebDriver,String) wait for a URL change} after each call. Particularly useful when dealing with AJAX driven redirect.<p> For example: <code> waitOnUrlChange(searchButton).click(); </code>
 * @param webDriver the web driver
 * @param source the source element
 * @return a decorated {@link WebElement}
 * @see #waitOnUrlChange(WebDriver,String)
 */
public static WebElement waitOnUrlChange(final WebDriver webDriver,final WebElement source){
  Assert.notNull(webDriver,"WebDriver must not be null");
  Assert.notNull(source,"Source must not be null");
  final String url=webDriver.getCurrentUrl();
  Object proxy=Proxy.newProxyInstance(source.getClass().getClassLoader(),new Class<?>[]{WebElement.class},new InvocationHandler(){
    public Object invoke(    Object proxy,    Method method,    Object[] args) throws Throwable {
      try {
        return method.invoke(source,args);
      }
  finally {
        waitOnUrlChange(webDriver,url);
      }
    }
  }
);
  return (WebElement)proxy;
}
 

Example 81

From project enterprise, under directory /consistency-check/src/main/java/org/neo4j/consistency/report/.

Source file: ConsistencyReporter.java

  29 
vote

@SuppressWarnings("unchecked") ProxyFactory(Class<T> type) throws LinkageError {
  try {
    this.constructor=(Constructor<? extends T>)Proxy.getProxyClass(ConsistencyReporter.class.getClassLoader(),type).getConstructor(InvocationHandler.class);
  }
 catch (  NoSuchMethodException e) {
    throw withCause(new LinkageError("Cannot access Proxy constructor for " + type.getName()),e);
  }
}
 

Example 82

From project jboss-marshalling, under directory /api/src/main/java/org/jboss/marshalling/cloner/.

Source file: SerializingCloner.java

  29 
vote

private static InvocationHandler getInvocationHandler(final Object orig){
  try {
    return (InvocationHandler)proxyInvocationHandler.get(orig);
  }
 catch (  IllegalAccessException e) {
    throw new IllegalAccessError(e.getMessage());
  }
}
 

Example 83

From project jetty-session-redis, under directory /src/main/java/com/ovea/jetty/session/serializer/jboss/serial/persister/.

Source file: ProxyPersister.java

  29 
vote

public Object readData(ClassLoader loader,StreamingClass streaming,ClassMetaData metaData,int referenceId,ObjectsCache cache,ObjectInput input,ObjectSubstitutionInterface substitution) throws IOException {
  try {
    Object handler=input.readObject();
    Class proxy=(Class)input.readObject();
    Constructor constructor=proxy.getConstructor(new Class[]{InvocationHandler.class});
    Object obj=constructor.newInstance(new Object[]{handler});
    cache.putObjectInCacheRead(referenceId,obj);
    return obj;
  }
 catch (  ClassNotFoundException e) {
    throw new SerializationException(e);
  }
catch (  NoSuchMethodException e) {
    throw new SerializationException(e);
  }
catch (  IllegalAccessException e) {
    throw new SerializationException(e);
  }
catch (  InstantiationException e) {
    throw new SerializationException(e);
  }
catch (  InvocationTargetException e) {
    throw new SerializationException(e);
  }
}
 

Example 84

From project Opal, under directory /opal-system/src/main/java/com/lyndir/lhunath/opal/system/util/.

Source file: TypeUtils.java

  29 
vote

/** 
 * Creates a proxy instance of the given type that triggers the given  {@code invocationHandler} whenever a method is invoked on it.The instance is created without invoking its constructor.
 * @param type              The class that defines the methods that can be invoked on the proxy.
 * @param invocationHandler The handler that will be invoked for each method invoked on the proxy.
 * @param < T >               The type of the proxy object.
 * @return An instance of the given <code>type</code> .
 */
public static <T>T newProxyInstance(final Class<T> type,final InvocationHandler invocationHandler){
  MethodInterceptor interceptor=new MethodInterceptor(){
    @Override @SuppressWarnings({"ProhibitedExceptionDeclared"}) public Object intercept(    final Object o,    final Method method,    final Object[] objects,    final MethodProxy methodProxy) throws Throwable {
      return invocationHandler.invoke(o,method,objects);
    }
  }
;
  Enhancer enhancer=newEnhancer(type);
  enhancer.setCallbackType(interceptor.getClass());
  Class<?> mockClass=enhancer.createClass();
  Enhancer.registerCallbacks(mockClass,new Callback[]{interceptor});
  Factory mock=(Factory)objenesis.newInstance(mockClass);
  mock.getCallback(0);
  return type.cast(mock);
}
 

Example 85

From project openwebbeans, under directory /webbeans-impl/src/main/java/org/apache/webbeans/proxy/asm/.

Source file: AsmProxyFactory.java

  29 
vote

public static Object newProxyInstance(ClassLoader classLoader,InvocationHandler handler,Class classToSubclass,final Class... interfaces) throws IllegalArgumentException {
  try {
    final Class proxyClass=GENERATOR.getProxyClass(classLoader,classToSubclass,interfaces);
    final Object object=GENERATOR.constructProxy(proxyClass,handler);
    return object;
  }
 catch (  Throwable e) {
    throw new InternalError(printStackTrace(e));
  }
}
 

Example 86

From project persistence_1, under directory /impl/src/main/java/org/jboss/seam/persistence/hibernate/.

Source file: HibernateManagedSessionBeanLifecycle.java

  29 
vote

public HibernateManagedSessionBeanLifecycle(Set<Annotation> qualifiers,ClassLoader loader,BeanManager manager){
  this.manager=manager;
  Set<Class<?>> additionalinterfaces=persistenceProvider.getAdditionalSessionInterfaces();
  Class<?>[] interfaces=new Class[additionalinterfaces.size() + 3];
  int count=0;
  for (  Class<?> i : additionalinterfaces) {
    interfaces[count++]=i;
  }
  interfaces[count++]=Session.class;
  interfaces[count++]=Serializable.class;
  interfaces[count++]=ManagedPersistenceContext.class;
  proxyClass=Proxy.getProxyClass(loader,interfaces);
  try {
    proxyConstructor=proxyClass.getConstructor(InvocationHandler.class);
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
  this.qualifiers=new Annotation[qualifiers.size()];
  int i=0;
  for (  Annotation a : qualifiers) {
    this.qualifiers[i++]=a;
  }
}
 

Example 87

From project solder, under directory /api/src/main/java/org/jboss/solder/reflection/.

Source file: AnnotationInstanceProvider.java

  29 
vote

/** 
 * <p> Returns an instance of the given annotation type with attribute values specified in the map. </p> <p/> <ul> <li> For  {@link Annotation}, array and enum types the values must exactly match the declared return type of the attribute or a  {@link ClassCastException}will result.</li> <p/> <li> For character types the the value must be an instance of  {@link Character}or  {@link String}.</li> <p/> <li> Numeric types do not have to match exactly, as they are converted using {@link Number}.</li> </ul> <p/> <p> If am member does not have a corresponding entry in the value map then the annotations default value will be used. </p> <p/> <p> If the annotation member does not have a default value then a NullMemberException will be thrown </p>
 * @param annotationType the type of the annotation instance to generate
 * @param values         the attribute values of this annotation
 */
public <T extends Annotation>T get(Class<T> annotationType,Map<String,?> values){
  if (annotationType == null) {
    throw new IllegalArgumentException("Must specify an annotation");
  }
  Class<?> clazz=cache.get(annotationType);
  if (clazz == null) {
    clazz=Proxy.getProxyClass(annotationType.getClassLoader(),annotationType,Serializable.class);
    cache.put(annotationType,clazz);
  }
  AnnotationInvocationHandler handler=new AnnotationInvocationHandler(values,annotationType);
  try {
    return annotationType.cast(clazz.getConstructor(new Class[]{InvocationHandler.class}).newInstance(new Object[]{handler}));
  }
 catch (  IllegalArgumentException e) {
    throw new IllegalStateException("Error instantiating proxy for annotation. Annotation type: " + annotationType,e);
  }
catch (  InstantiationException e) {
    throw new IllegalStateException("Error instantiating proxy for annotation. Annotation type: " + annotationType,e);
  }
catch (  IllegalAccessException e) {
    throw new IllegalStateException("Error instantiating proxy for annotation. Annotation type: " + annotationType,e);
  }
catch (  InvocationTargetException e) {
    throw new IllegalStateException("Error instantiating proxy for annotation. Annotation type: " + annotationType,e.getCause());
  }
catch (  SecurityException e) {
    throw new IllegalStateException("Error accessing proxy constructor for annotation. Annotation type: " + annotationType,e);
  }
catch (  NoSuchMethodException e) {
    throw new IllegalStateException("Error accessing proxy constructor for annotation. Annotation type: " + annotationType,e);
  }
}
 

Example 88

From project torquebox, under directory /modules/core/src/main/java/org/torquebox/core/injection/.

Source file: AnnotationInstanceProvider.java

  29 
vote

/** 
 * <p> Returns an instance of the given annotation type with attribute values specified in the map. </p> <ul> <li> For  {@link Annotation}, array and enum types the values must exactly match the declared return type of the attribute or a  {@link ClassCastException}will result.</li> <li> For character types the the value must be an instance of  {@link Character}or  {@link String}.</li> <li> Numeric types do not have to match exactly, as they are converted using {@link Number}.</li> </ul> <p> If am member does not have a corresponding entry in the value map then the annotations default value will be used. </p> <p> If the annotation member does not have a default value then a NullMemberException will be thrown </p>
 * @param annotationType the type of the annotation instance to generate
 * @param values the attribute values of this annotation
 */
public <T extends Annotation>T get(Class<T> annotationType,Map<String,?> values){
  if (annotationType == null) {
    throw new IllegalArgumentException("Must specify an annotation");
  }
  Class<?> clazz=cache.get(annotationType);
  if (clazz == null) {
    clazz=Proxy.getProxyClass(annotationType.getClassLoader(),annotationType,Serializable.class);
    cache.put(annotationType,clazz);
  }
  AnnotationInvocationHandler handler=new AnnotationInvocationHandler(values,annotationType);
  try {
    return annotationType.cast(clazz.getConstructor(new Class[]{InvocationHandler.class}).newInstance(new Object[]{handler}));
  }
 catch (  IllegalArgumentException e) {
    throw new IllegalStateException("Error instantiating proxy for annotation. Annotation type: " + annotationType,e);
  }
catch (  InstantiationException e) {
    throw new IllegalStateException("Error instantiating proxy for annotation. Annotation type: " + annotationType,e);
  }
catch (  IllegalAccessException e) {
    throw new IllegalStateException("Error instantiating proxy for annotation. Annotation type: " + annotationType,e);
  }
catch (  InvocationTargetException e) {
    throw new IllegalStateException("Error instantiating proxy for annotation. Annotation type: " + annotationType,e.getCause());
  }
catch (  SecurityException e) {
    throw new IllegalStateException("Error accessing proxy constructor for annotation. Annotation type: " + annotationType,e);
  }
catch (  NoSuchMethodException e) {
    throw new IllegalStateException("Error accessing proxy constructor for annotation. Annotation type: " + annotationType,e);
  }
}