Java Code Examples for java.lang.reflect.Proxy

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 activemq-apollo, under directory /apollo-util/src/main/scala/org/apache/activemq/apollo/util/.

Source file: ClassLoadingAwareObjectInputStream.java

  29 
vote

protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
  ClassLoader cl=Thread.currentThread().getContextClassLoader();
  Class[] cinterfaces=new Class[interfaces.length];
  for (int i=0; i < interfaces.length; i++) {
    cinterfaces[i]=load(interfaces[i],cl);
  }
  try {
    return Proxy.getProxyClass(cinterfaces[0].getClassLoader(),cinterfaces);
  }
 catch (  IllegalArgumentException e) {
    throw new ClassNotFoundException(null,e);
  }
}
 

Example 2

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

Source file: Neo4jManager.java

  29 
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 3

From project aether-core, under directory /aether-impl/src/test/java/org/eclipse/aether/internal/impl/.

Source file: DefaultRepositoryEventDispatcherTest.java

  29 
vote

@Test public void testDispatchHandlesAllEventTypes() throws Exception {
  DefaultRepositoryEventDispatcher dispatcher=new DefaultRepositoryEventDispatcher();
  ListenerHandler handler=new ListenerHandler();
  RepositoryListener listener=(RepositoryListener)Proxy.newProxyInstance(getClass().getClassLoader(),new Class<?>[]{RepositoryListener.class},handler);
  TestRepositorySystemSession session=new TestRepositorySystemSession();
  session.setRepositoryListener(listener);
  for (  RepositoryEvent.EventType type : RepositoryEvent.EventType.values()) {
    RepositoryEvent event=new RepositoryEvent.Builder(session,type).build();
    handler.methodName=null;
    dispatcher.dispatch(event);
    assertNotNull("not handled: " + type,handler.methodName);
    assertEquals("badly handled: " + type,type.name().replace("_","").toLowerCase(Locale.ENGLISH),handler.methodName.toLowerCase(Locale.ENGLISH));
  }
}
 

Example 4

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/util/.

Source file: CustomObjectInputStream.java

  29 
vote

/** 
 * Return a proxy class that implements the interfaces named in a proxy class descriptor. Do this using the class loader assigned to this Context.
 */
protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
  Class[] cinterfaces=new Class[interfaces.length];
  for (int i=0; i < interfaces.length; i++)   cinterfaces[i]=classLoader.loadClass(interfaces[i]);
  try {
    return Proxy.getProxyClass(classLoader,cinterfaces);
  }
 catch (  IllegalArgumentException e) {
    throw new ClassNotFoundException(null,e);
  }
}
 

Example 5

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

Source file: WifiDirectAutoAccept.java

  29 
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 6

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

Source file: FlexPilotDefaultFieldDecorator.java

  29 
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 7

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

Source file: ProxyFactoryImpl.java

  29 
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 8

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: RemoteServiceImpl.java

  29 
vote

public Object getProxy() throws ECFException {
  Object proxy;
  try {
    final String[] clazzes=registration.getClasses();
    final Class[] cs=new Class[clazzes.length + 1];
    for (int i=0; i < clazzes.length; i++)     cs[i]=Class.forName(clazzes[i]);
    cs[clazzes.length]=IRemoteServiceProxy.class;
    proxy=Proxy.newProxyInstance(this.getClass().getClassLoader(),cs,this);
  }
 catch (  final Exception e) {
    throw new ECFException(Messages.RemoteServiceImpl_EXCEPTION_CREATING_PROXY,e);
  }
  return proxy;
}
 

Example 9

From project android_build, under directory /tools/droiddoc/src/.

Source file: DroidDoc.java

  29 
vote

/** 
 * Filters out hidden elements.
 */
private static Object filterHidden(Object o,Class<?> expected){
  if (o == null) {
    return null;
  }
  Class type=o.getClass();
  if (type.getName().startsWith("com.sun.")) {
    return Proxy.newProxyInstance(type.getClassLoader(),type.getInterfaces(),new HideHandler(o));
  }
 else   if (o instanceof Object[]) {
    Class<?> componentType=expected.getComponentType();
    Object[] array=(Object[])o;
    List<Object> list=new ArrayList<Object>(array.length);
    for (    Object entry : array) {
      if ((entry instanceof Doc) && isHidden((Doc)entry)) {
        continue;
      }
      list.add(filterHidden(entry,componentType));
    }
    return list.toArray((Object[])Array.newInstance(componentType,list.size()));
  }
 else {
    return o;
  }
}
 

Example 10

From project ANNIS, under directory /annis-service/src/test/java/annis/test/.

Source file: TestHelper.java

  29 
vote

public static Object proxyTarget(Object proxy){
  if (!(proxy instanceof Proxy))   fail("Not a proxy: " + proxy);
  SingletonTargetSource targetSource=null;
  try {
    targetSource=(SingletonTargetSource)proxy.getClass().getMethod("getTargetSource").invoke(proxy);
  }
 catch (  Exception e) {
    fail(e.getMessage());
  }
  if (targetSource == null)   fail("Couldn't get target of annisDao proxy");
  return targetSource.getTarget();
}
 

Example 11

From project apb, under directory /modules/apb/src/apb/processors/.

Source file: ExcludeDoclet.java

  29 
vote

private static Object process(Object obj,Class expect){
  if (obj == null) {
    return null;
  }
  Class cls=obj.getClass();
  if (cls.getName().startsWith("com.sun.")) {
    return Proxy.newProxyInstance(cls.getClassLoader(),cls.getInterfaces(),new ExcludeHandler(obj));
  }
 else   if (obj instanceof Object[] && expect.isArray()) {
    Class componentType=expect.getComponentType();
    Object[] array=(Object[])obj;
    List<Object> list=new ArrayList<Object>(array.length);
    for (    Object entry : array) {
      if (!(entry instanceof Doc) || !exclude((Doc)entry)) {
        list.add(process(entry,componentType));
      }
    }
    return list.toArray((Object[])Array.newInstance(componentType,list.size()));
  }
 else {
    return obj;
  }
}
 

Example 12

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

Source file: AKBeanPostProcessor.java

  29 
vote

/** 
 * After properties set.
 */
public void afterPropertiesSet(){
  if (_classLoader == null) {
    _classLoader=Thread.currentThread().getContextClassLoader();
  }
  if (_framework == null) {
    throw new IllegalArgumentException("framework is required");
  }
  if (_proxyFactory == null) {
    _proxyFactory=Proxy.class;
  }
  try {
    _proxyFactoryMethod=_proxyFactory.getMethod("newProxyInstance",ClassLoader.class,Class[].class,InvocationHandler.class);
  }
 catch (  Exception e) {
    throw new IllegalArgumentException("proxy factory must implement newProxyInstance(...); " + "see java.lang.reflect.Proxy",e);
  }
}
 

Example 13

From project arquillian-graphene, under directory /graphene-webdriver/graphene-webdriver-impl/src/main/java/org/jboss/arquillian/graphene/proxy/.

Source file: GrapheneProxy.java

  29 
vote

/** 
 * <p> Uses given proxy factory to create new proxy for given implementation class or interfaces with the given method handler. </p> <p> The returned proxy implements  {@link GrapheneProxyInstance} bydefault.
 * @param factory the {@link ProxyFactory} which will be used to createproxy
 * @param interceptor the {@link MethodHandler} for handling invocation
 * @param baseType the class or interface used as base type or null ifadditionalInterfaces list should be used instead
 * @param additionalInterfaces additional interfaces which should a createdproxy implement
 * @return the proxy for given implementation class or interfaces with thegiven method handler.
 */
@SuppressWarnings("unchecked") static <T>T createProxy(GrapheneProxyHandler interceptor,Class<T> baseType,Class<?>... additionalInterfaces){
  Class<?>[] ancillaryTypes=GrapheneProxyUtil.concatClasses(additionalInterfaces,GrapheneProxyInstance.class);
  if (baseType == null || baseType.isInterface()) {
    if (baseType != null) {
      ancillaryTypes=GrapheneProxyUtil.concatClasses(ancillaryTypes,baseType);
    }
    return (T)Proxy.newProxyInstance(GrapheneProxy.class.getClassLoader(),ancillaryTypes,interceptor);
  }
  return (T)ClassImposterizer.INSTANCE.imposterise(interceptor,baseType,ancillaryTypes);
}
 

Example 14

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/suite/utils/.

Source file: NullingProxy.java

  29 
vote

@Override public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {
  Nullify nullify=method.getAnnotation(Nullify.class);
  if (nullify != null) {
    if (ArrayUtils.contains(nullify.value(),nullified)) {
      return null;
    }
  }
  Object result=method.invoke(object,args);
  if (result == null) {
    return result;
  }
 else   if (method.getReturnType().isInterface()) {
    return Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{method.getReturnType()},new NullingHandler(result,nullified));
  }
 else   if (canBeProxied(result)) {
    return NullingProxy.handle(result,nullified);
  }
 else {
    return result;
  }
}
 

Example 15

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

Source file: FakeObject.java

  29 
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 16

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

Source file: OsgiServiceProxy.java

  29 
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 17

From project banshun, under directory /banshun/core/src/test/java/com/griddynamics/banshun/.

Source file: RegistryBeanTest.java

  29 
vote

protected void check(String configLocation){
  ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext(configLocation);
  Assert.assertTrue("have no exports due to laziness",hasNoExports(ctx));
  Object proxy=ctx.getBean("early-import");
  try {
    proxy.toString();
    Assert.fail("attempt to invoke proxy without export should lead to exception");
  }
 catch (  NoSuchBeanDefinitionException e) {
    Assert.assertEquals("invoke bean without proper export","just-bean",e.getBeanName());
  }
  ctx.getBean("export-declaration");
  Assert.assertSame(proxy,ctx.getBean("early-import"));
  Assert.assertFalse("have export ref",hasExport(ctx,"just-bean"));
  Assert.assertEquals("proxies should refer the same bean instance",proxy.toString(),ctx.getBean("late-import").toString());
  Assert.assertSame("proxies should be the same instance",proxy,ctx.getBean("late-import"));
  Assert.assertTrue("early import gives us a proxy",proxy instanceof Proxy);
  Assert.assertTrue("late import gives us a proxy",ctx.getBean("late-import") instanceof Proxy);
}
 

Example 18

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

Source file: LamaDaoFactoryBean.java

  29 
vote

@SuppressWarnings("unchecked") protected T createDAO(Class<T> daoClass){
  Definition definition=new Definition(daoClass);
  DataAccess dataAccess=dataAccessProvider.createDataAccess(daoClass);
  LamaDaoInvocationHandler handler=new LamaDaoInvocationHandler(dataAccess,definition);
  return (T)Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(),new Class[]{daoClass},handler);
}
 

Example 19

From project Blueprint, under directory /blueprint-core/src/main/java/org/codemined/blueprint/.

Source file: Stub.java

  29 
vote

private I createProxy(){
  try {
    return iface.cast(Proxy.newProxyInstance(iface.getClassLoader(),new Class[]{iface,BlueprintProxy.class},this));
  }
 catch (  ClassCastException e) {
    throw new BlueprintException("Error casting proxy instance to " + iface.getName(),e);
  }
catch (  IllegalArgumentException e) {
    throw new BlueprintException("Error creating proxy instance for " + iface.getName(),e);
  }
}
 

Example 20

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: ConnectionHandle.java

  29 
vote

/** 
 * This method will be intercepted by the proxy if it is enabled to return the internal target.
 * @return the target.
 */
public Object getProxyTarget(){
  try {
    return Proxy.getInvocationHandler(this.connection).invoke(null,this.getClass().getMethod("getProxyTarget"),null);
  }
 catch (  Throwable t) {
    throw new RuntimeException("BoneCP: Internal error - transaction replay log is not turned on?",t);
  }
}
 

Example 21

From project c10n, under directory /core/src/main/java/c10n/.

Source file: DefaultC10NMsgFactory.java

  29 
vote

@SuppressWarnings("unchecked") public <T>T get(Class<T> c10nInterface){
  if (null == c10nInterface) {
    throw new NullPointerException("c10nInterface is null");
  }
  return (T)Proxy.newProxyInstance(proxyClassloader,new Class[]{c10nInterface},C10NInvocationHandler.create(this,conf,localeMapping,c10nInterface));
}
 

Example 22

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

Source file: OsgiDefaultProxyCreator.java

  29 
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 23

From project camel-twitter, under directory /src/test/java/org/apache/camel/component/twitter/.

Source file: SearchEventTest.java

  29 
vote

@Test public void testSearchTimeline() throws Exception {
  resultEndpoint.expectedMinimumMessageCount(1);
  Status status=(Status)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{Status.class},new TwitterHandler());
  listener.onStatus(status);
  resultEndpoint.assertIsSatisfied();
}
 

Example 24

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

Source file: JndiLookupUtils.java

  29 
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 25

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

Source file: AbstractGenericDAO.java

  29 
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 26

From project cas, under directory /cas-server-core/src/test/java/org/jasig/cas/ticket/registry/support/.

Source file: JpaLockingStrategyTests.java

  29 
vote

private LockingStrategy newLockTxProxy(final String appId,final String uniqueId,final int ttl){
  final JpaLockingStrategy lock=new JpaLockingStrategy();
  lock.entityManager=SharedEntityManagerCreator.createSharedEntityManager(factory);
  lock.setApplicationId(appId);
  lock.setUniqueId(uniqueId);
  lock.setLockTimeout(ttl);
  return (LockingStrategy)Proxy.newProxyInstance(JpaLockingStrategy.class.getClassLoader(),new Class[]{LockingStrategy.class},new TransactionalLockInvocationHandler(lock));
}
 

Example 27

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/dependency/.

Source file: Dependency.java

  29 
vote

private Object createNullableObject(){
  try {
    ClassLoader cl=new NullableClassLoader(getHandler().getInstanceManager().getClazz().getClassLoader(),getSpecification().getClassLoader());
    m_nullable=Proxy.newProxyInstance(cl,new Class[]{getSpecification(),Nullable.class},new NullableObject());
  }
 catch (  NoClassDefFoundError e) {
    throw new IllegalStateException("Cannot create the Nullable object, a referenced class cannot be loaded: " + e.getMessage());
  }
catch (  Throwable e) {
    throw new IllegalStateException("Cannot create the Nullable object, an unexpected error occurs: " + e.getMessage());
  }
  return m_nullable;
}
 

Example 28

From project codjo-webservices, under directory /codjo-webservices-common/src/main/java/com/tilab/wsig/wsdl/.

Source file: WSDLGeneratorUtils.java

  29 
vote

public static String[] getParameterNames(Method method){
  int numParams=method.getParameterTypes().length;
  if (numParams == 0)   return null;
  Class c=method.getDeclaringClass();
  if (Proxy.isProxyClass(c)) {
    return null;
  }
  try {
    ParamReader pr=new ParamReader(c);
    return pr.getParameterNames(method);
  }
 catch (  IOException e) {
    return null;
  }
}
 

Example 29

From project Collections, under directory /src/main/java/vanilla/java/collections/impl/.

Source file: ColumnHugeArrayList.java

  29 
vote

private T acquireProxy(long n){
  if (proxies.isEmpty()) {
    MyInvocationHandler<T> h=new MyInvocationHandler<T>(this,n);
    T ret=(T)Proxy.newProxyInstance(type.classLoader(),new Class[]{type.type()},h);
    h.proxy=ret;
    return ret;
  }
  return proxies.remove(proxies.size() - 1);
}
 

Example 30

From project commons-io, under directory /src/main/java/org/apache/commons/io/input/.

Source file: ClassLoaderObjectInputStream.java

  29 
vote

/** 
 * Create a proxy class that implements the specified interfaces using the specified ClassLoader or the super ClassLoader.
 * @param interfaces the interfaces to implement
 * @return a proxy class implementing the interfaces
 * @throws IOException in case of an I/O error
 * @throws ClassNotFoundException if the Class cannot be found
 * @see java.io.ObjectInputStream#resolveProxyClass(java.lang.String[])
 * @since 2.1
 */
@Override protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
  Class<?>[] interfaceClasses=new Class[interfaces.length];
  for (int i=0; i < interfaces.length; i++) {
    interfaceClasses[i]=Class.forName(interfaces[i],false,classLoader);
  }
  try {
    return Proxy.getProxyClass(classLoader,interfaceClasses);
  }
 catch (  IllegalArgumentException e) {
    return super.resolveProxyClass(interfaces);
  }
}
 

Example 31

From project components, under directory /bean/src/main/java/org/switchyard/component/bean/.

Source file: ClientProxyBean.java

  29 
vote

/** 
 * Public constructor.
 * @param serviceName   The name of the ESB Service being proxied to.
 * @param proxyInterface The proxy Interface.
 * @param qualifiers     The CDI bean qualifiers.  Copied from the injection point.
 * @param beanDeploymentMetaData Deployment metadata.
 */
public ClientProxyBean(String serviceName,Class<?> proxyInterface,Set<Annotation> qualifiers,BeanDeploymentMetaData beanDeploymentMetaData){
  this._serviceName=serviceName;
  this._serviceInterface=proxyInterface;
  if (qualifiers != null) {
    this._qualifiers=qualifiers;
  }
 else {
    this._qualifiers=new HashSet<Annotation>();
    this._qualifiers.add(new AnnotationLiteral<Default>(){
    }
);
    this._qualifiers.add(new AnnotationLiteral<Any>(){
    }
);
  }
  _proxyBean=Proxy.newProxyInstance(beanDeploymentMetaData.getDeploymentClassLoader(),new Class[]{_serviceInterface},new ClientProxyInvocationHandler(_serviceInterface));
}
 

Example 32

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

Source file: ServiceTracker.java

  29 
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 33

From project crash, under directory /shell/core/src/main/java/org/crsh/util/.

Source file: InterruptHandler.java

  29 
vote

public void install(){
  ClassLoader cl=Thread.currentThread().getContextClassLoader();
  Class<?> signalHandlerClass;
  Class<?> signalClass;
  Method handle;
  Object INT;
  try {
    signalHandlerClass=cl.loadClass("sun.misc.SignalHandler");
    signalClass=cl.loadClass("sun.misc.Signal");
    handle=signalClass.getDeclaredMethod("handle",signalClass,signalHandlerClass);
    Constructor ctor=signalClass.getConstructor(String.class);
    INT=ctor.newInstance("INT");
  }
 catch (  Exception e) {
    return;
  }
  Object proxy=Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class<?>[]{signalHandlerClass},handler);
  try {
    handle.invoke(null,INT,proxy);
  }
 catch (  Exception e) {
    log.error("Could not install signal handler",e);
  }
}
 

Example 34

From project cxf-dosgi, under directory /dsw/cxf-dsw/src/main/java/org/apache/cxf/dosgi/dsw/handlers/.

Source file: ServiceInvocationHandler.java

  29 
vote

public Object invoke(Object proxy,final Method m,Object[] params) throws Throwable {
  if (OBJECT_METHODS.contains(m)) {
    if (m.getName().equals("equals")) {
      params=new Object[]{Proxy.getInvocationHandler(params[0])};
    }
    return m.invoke(this,params);
  }
  ClassLoader oldCl=Thread.currentThread().getContextClassLoader();
  try {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    final Object[] paramsFinal=params;
    return AccessController.doPrivileged(new PrivilegedExceptionAction<Object>(){
      public Object run() throws Exception {
        return m.invoke(serviceObject,paramsFinal);
      }
    }
);
  }
 catch (  Throwable ex) {
    Throwable theCause=ex.getCause() == null ? ex : ex.getCause();
    Throwable theCauseCause=theCause.getCause() == null ? theCause : theCause.getCause();
    List<Class<?>> excTypes=exceptionsMap.get(m);
    if (excTypes != null) {
      for (      Class<?> type : excTypes) {
        if (type.isAssignableFrom(theCause.getClass())) {
          throw theCause;
        }
        if (type.isAssignableFrom(theCauseCause.getClass())) {
          throw theCauseCause;
        }
      }
    }
    throw new ServiceException(REMOTE_EXCEPTION_TYPE,theCause);
  }
 finally {
    Thread.currentThread().setContextClassLoader(oldCl);
  }
}
 

Example 35

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

Source file: BehaviourInjector.java

  29 
vote

/** 
 * see public methods.  this one also has the parameter injectContext, telling it if it should  inject the context or not.  normally, you call this method with true, but it calls itself with false.
 */
@SuppressWarnings("unchecked") private <S,T,U>U assignRole(S domainObjectToInjectInto,Class<? extends T> roleImplClass,Class<? extends U> roleInterface,String name,boolean injectContext){
  Object roleInstance;
  try {
    roleInstance=roleImplClass.newInstance();
  }
 catch (  Exception e) {
    throw new RuntimeException("unable to instantiate role implementation class " + roleImplClass.getName(),e);
  }
  injectResources(roleInstance);
  ClassLoader classLoader=getClassLoader(domainObjectToInjectInto);
  Class[] interfaces=new Class[]{roleInterface};
  MyInvocationHandler ih=new MyInvocationHandler(domainObjectToInjectInto,roleInstance);
  U proxy=(U)Proxy.newProxyInstance(classLoader,interfaces,ih);
  injectSelf(roleInstance,proxy);
  injectDataObject(roleInstance,domainObjectToInjectInto);
  if (injectContext) {
    Context ctx=assignRole(this,CurrentContext_Role.class,Context.class,name,false);
    injectCurrentContext(roleInstance,ctx);
  }
  if (isSystemPropertyForCheckSet()) {
    doCheck(roleInterface,domainObjectToInjectInto,roleImplClass);
  }
  collectInjectionInfo(roleImplClass,roleInterface,proxy,name);
  doAfterInjection(roleInstance);
  return proxy;
}
 

Example 36

From project dozer, under directory /core/src/main/java/org/dozer/.

Source file: DozerBeanMapper.java

  29 
vote

protected Mapper getMappingProcessor(){
  initMappings();
  Mapper processor=new MappingProcessor(customMappings,globalConfiguration,cacheManager,statsMgr,customConverters,eventManager,getCustomFieldMapper(),customConvertersWithId);
  if (statsMgr.isStatisticsEnabled()) {
    processor=(Mapper)Proxy.newProxyInstance(processor.getClass().getClassLoader(),processor.getClass().getInterfaces(),new StatisticsInterceptor(processor,statsMgr));
  }
  return processor;
}
 

Example 37

From project drools-chance, under directory /drools-shapes/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/model/.

Source file: TraitMantle.java

  29 
vote

public static <T>T wrap(Object obj,Map<String,Object> map,Class<T> trait){
  TraitMantle mantle=new TraitMantle(map,obj);
  Class[] interfaces=null;
  if (obj.getClass().getInterfaces().length > 0) {
    interfaces=obj.getClass().getInterfaces();
    interfaces=Arrays.copyOf(interfaces,interfaces.length + 1);
    interfaces[interfaces.length - 1]=trait;
    for (    Class itf : obj.getClass().getInterfaces()) {
      mantle.types.add(itf);
    }
  }
 else {
    interfaces=new Class[]{trait};
  }
  T proxy=(T)Proxy.newProxyInstance(TraitMantle.class.getClassLoader(),interfaces,mantle);
  mantle.types.add(IThing.class);
  if (trait != IThing.class) {
    bindImpl(mantle,trait);
  }
  mantle.proxy=proxy;
  return proxy;
}
 

Example 38

From project drools-semantics, under directory /src/main/java/org/drools/semantics/model/.

Source file: TraitMantle.java

  29 
vote

public static <T>T wrap(Object obj,Map<String,Object> map,Class<T> trait){
  TraitMantle mantle=new TraitMantle(map,obj);
  Class[] interfaces=null;
  if (obj.getClass().getInterfaces().length > 0) {
    interfaces=obj.getClass().getInterfaces();
    interfaces=Arrays.copyOf(interfaces,interfaces.length + 1);
    interfaces[interfaces.length - 1]=trait;
    for (    Class itf : obj.getClass().getInterfaces()) {
      mantle.types.add(itf);
    }
  }
 else {
    interfaces=new Class[]{trait};
  }
  T proxy=(T)Proxy.newProxyInstance(TraitMantle.class.getClassLoader(),interfaces,mantle);
  mantle.types.add(IThing.class);
  if (trait != IThing.class) {
    bindImpl(mantle,trait);
  }
  mantle.proxy=proxy;
  return proxy;
}
 

Example 39

From project ehour, under directory /eHour-service/src/main/java/net/rrm/ehour/export/service/.

Source file: ExportServiceImpl.java

  29 
vote

@Override public String exportDatabase(){
  String xmlDocument=null;
  StringWriter stringWriter=new StringWriter();
  XMLOutputFactory factory=XMLOutputFactory.newInstance();
  try {
    XMLStreamWriter writer=factory.createXMLStreamWriter(stringWriter);
    PrettyPrintHandler handler=new PrettyPrintHandler(writer);
    XMLStreamWriter prettyPrintWriter=(XMLStreamWriter)Proxy.newProxyInstance(XMLStreamWriter.class.getClassLoader(),new Class[]{XMLStreamWriter.class},handler);
    exportDatabase(prettyPrintWriter);
    xmlDocument=stringWriter.toString();
  }
 catch (  XMLStreamException e) {
    LOGGER.error(e);
  }
  return xmlDocument;
}
 

Example 40

From project elasticsearch-osem, under directory /src/main/java/org/elasticsearch/osem/common/springframework/util/.

Source file: ClassUtils.java

  29 
vote

/** 
 * Return a descriptive name for the given object's type: usually simply the class name, but component type class name + "[]" for arrays, and an appended list of implemented interfaces for JDK proxies.
 * @param value the value to introspect
 * @return the qualified name of the class
 */
public static String getDescriptiveType(Object value){
  if (value == null) {
    return null;
  }
  Class<?> clazz=value.getClass();
  if (Proxy.isProxyClass(clazz)) {
    StringBuilder result=new StringBuilder(clazz.getName());
    result.append(" implementing ");
    Class<?>[] ifcs=clazz.getInterfaces();
    for (int i=0; i < ifcs.length; i++) {
      result.append(ifcs[i].getName());
      if (i < ifcs.length - 1) {
        result.append(',');
      }
    }
    return result.toString();
  }
 else   if (clazz.isArray()) {
    return getQualifiedNameForArray(clazz);
  }
 else {
    return clazz.getName();
  }
}
 

Example 41

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 42

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

Source file: VMBridge_jdk13.java

  29 
vote

protected Object getInterfaceProxyHelper(ContextFactory cf,Class[] interfaces){
  ClassLoader loader=interfaces[0].getClassLoader();
  Class cl=Proxy.getProxyClass(loader,interfaces);
  Constructor c;
  try {
    c=cl.getConstructor(new Class[]{InvocationHandler.class});
  }
 catch (  NoSuchMethodException ex) {
    throw Kit.initCause(new IllegalStateException(),ex);
  }
  return c;
}
 

Example 43

From project evp-portlet, under directory /docroot/WEB-INF/service/com/liferay/evp/model/.

Source file: GrantRequestClp.java

  29 
vote

@Override public GrantRequest toEscapedModel(){
  if (isEscapedModel()) {
    return this;
  }
 else {
    return (GrantRequest)Proxy.newProxyInstance(GrantRequest.class.getClassLoader(),new Class[]{GrantRequest.class},new AutoEscapeBeanHandler(this));
  }
}
 

Example 44

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

Source file: DynamicProxyDemo.java

  29 
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 45

From project fastjson, under directory /src/main/java/com/alibaba/fastjson/parser/deserializer/.

Source file: JavaBeanDeserializer.java

  29 
vote

public Object createInstance(DefaultJSONParser parser,Type type){
  if (type instanceof Class) {
    if (clazz.isInterface()) {
      Class<?> clazz=(Class<?>)type;
      ClassLoader loader=Thread.currentThread().getContextClassLoader();
      final JSONObject obj=new JSONObject();
      Object proxy=Proxy.newProxyInstance(loader,new Class<?>[]{clazz},obj);
      return proxy;
    }
  }
  if (beanInfo.getDefaultConstructor() == null) {
    return null;
  }
  Object object;
  try {
    Constructor<?> constructor=beanInfo.getDefaultConstructor();
    if (constructor.getParameterTypes().length == 0) {
      object=constructor.newInstance();
    }
 else {
      object=constructor.newInstance(parser.getContext().getObject());
    }
  }
 catch (  Exception e) {
    throw new JSONException("create instance error, class " + clazz.getName(),e);
  }
  if (parser.isEnabled(Feature.InitStringFieldAsEmpty)) {
    for (    FieldInfo fieldInfo : beanInfo.getFieldList()) {
      if (fieldInfo.getFieldClass() == String.class) {
        try {
          fieldInfo.set(object,"");
        }
 catch (        Exception e) {
          throw new JSONException("create instance error, class " + clazz.getName(),e);
        }
      }
    }
  }
  return object;
}
 

Example 46

From project fest-reflect, under directory /src/main/java/org/fest/reflect/field/.

Source file: DecoratedInvoker.java

  29 
vote

/** 
 * Ignores any exception of the  {@code exceptionClass} type which comes from the preceding decorator.
 * @param exceptionClass the exception to ignore - usually a checked exception of decorator method
 * @return the DecoratedResultInvoker ignoring given exception type.
 */
public DecoratedInvoker<T> ignoringDecoratorExceptionsOfType(Class<?> exceptionClass){
  RuntimeExceptionShield runtimeExceptionShield=new RuntimeExceptionShield(decorator,exceptionClass);
  @SuppressWarnings("unchecked") T exceptionSafeDecorator=(T)Proxy.newProxyInstance(decorator.getClass().getClassLoader(),new Class[]{expectedType},runtimeExceptionShield);
  decoratorInvocationHandler.setDecorator(exceptionSafeDecorator);
  return newInvoker(target,exceptionSafeDecorator,expectedType,invoker,decoratorInvocationHandler);
}
 

Example 47

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

Source file: FlywayMediumTest.java

  29 
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 48

From project galaxy, under directory /src/co/paralleluniverse/galaxy/core/.

Source file: BackupImpl.java

  29 
vote

static BackupMonitor createMonitor(MonitoringType monitoringType,String name){
  if (monitoringType == null)   return (BackupMonitor)Proxy.newProxyInstance(Cache.class.getClassLoader(),new Class<?>[]{BackupMonitor.class},DegenerateInvocationHandler.INSTANCE);
 else switch (monitoringType) {
case JMX:
    return new JMXBackupMonitor(name);
case METRICS:
  return new MetricsBackupMonitor();
}
throw new IllegalArgumentException("Unknown MonitoringType " + monitoringType);
}
 

Example 49

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

Source file: RpcProxyFactory.java

  29 
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 50

From project Gemini-Blueprint, under directory /core/src/test/java/org/eclipse/gemini/blueprint/config/.

Source file: OsgiReferenceNamespaceHandlerTest.java

  29 
vote

public void testSimpleReference() throws Exception {
  Object factoryBean=appContext.getBean("&serializable");
  assertTrue(factoryBean instanceof OsgiServiceProxyFactoryBean);
  OsgiServiceProxyFactoryBean proxyFactory=(OsgiServiceProxyFactoryBean)factoryBean;
  Class<?>[] intfs=(Class[])TestUtils.getFieldValue(proxyFactory,"interfaces");
  assertEquals(1,intfs.length);
  assertSame(Serializable.class,intfs[0]);
  Object bean=appContext.getBean("serializable");
  assertTrue(bean instanceof Serializable);
  assertTrue(Proxy.isProxyClass(bean.getClass()));
}
 

Example 51

From project geolatte-common, under directory /src/main/java/org/geolatte/common/reflection/.

Source file: EntityClassReader.java

  29 
vote

/** 
 * Wraps the given object in a feature interface. This method will first validate whether the class it represents is indeed a feature (containing exactly one geometry and id) and will then generate a wrapper around the original object that obeys to the Feature interface. If this method is invoked multiple times on the same object, the same wrapper will be returned in each of these calls.
 * @param objectToTransform the object for which a feature is desired.
 * @return a feature wrapper around the given object
 * @throws InvalidObjectReaderException If the class of objectToTransform does not correspond with the entityclassof this reader
 * @throws IllegalArgumentException     if the given objectToTransform is null
 */
public Feature asFeature(Object objectToTransform) throws InvalidObjectReaderException {
  if (objectToTransform == null) {
    throw new IllegalArgumentException("Given object may not be null");
  }
  if (objectToTransform.getClass() != entityClass) {
    throw new InvalidObjectReaderException("Class of target object does not correspond with entityclass of this reader.");
  }
  Feature proxy=(Feature)Proxy.newProxyInstance(entityClass.getClassLoader(),new Class[]{Feature.class},new ObjectInvocationHandler(objectToTransform));
  return proxy;
}
 

Example 52

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

Source file: Mold.java

  29 
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 53

From project guice-jit-providers, under directory /core/src/com/google/inject/internal/.

Source file: ConstructionContext.java

  29 
vote

public Object createProxy(Errors errors,Class<?> expectedType) throws ErrorsException {
  if (!expectedType.isInterface()) {
    throw errors.cannotSatisfyCircularDependency(expectedType).toException();
  }
  if (invocationHandlers == null) {
    invocationHandlers=new ArrayList<DelegatingInvocationHandler<T>>();
  }
  DelegatingInvocationHandler<T> invocationHandler=new DelegatingInvocationHandler<T>();
  invocationHandlers.add(invocationHandler);
  ClassLoader classLoader=BytecodeGen.getClassLoader(expectedType);
  return expectedType.cast(Proxy.newProxyInstance(classLoader,new Class[]{expectedType,CircularDependencyProxy.class},invocationHandler));
}
 

Example 54

From project Guit, under directory /src/main/java/com/guit/junit/.

Source file: ConstantInjector.java

  29 
vote

@Override public void injectMembers(I i){
  try {
    field.set(i,Proxy.newProxyInstance(field.getType().getClassLoader(),new Class[]{field.getType()},new ConstantInvocationHandler()));
  }
 catch (  IllegalAccessException e) {
    throw new RuntimeException(e);
  }
}
 

Example 55

From project guvnorng, under directory /guvnorng-repository/src/main/java/org/drools/repository/.

Source file: ClassUtil.java

  29 
vote

/** 
 * Resolve a proxy for the specified interfaces.
 * @param interfaces The interfaces associated with the proxy.
 * @param caller The class of the caller.
 * @return The specified proxy class.
 * @throws ClassNotFoundException If the class cannot be found.
 */
public static Class resolveProxy(final String[] interfaces,final Class caller) throws ClassNotFoundException {
  final int numInterfaces=(interfaces == null ? 0 : interfaces.length);
  if (numInterfaces == 0) {
    throw new ClassNotFoundException("Cannot generate proxy with no interfaces");
  }
  final Class[] interfaceClasses=new Class[numInterfaces];
  for (int count=0; count < numInterfaces; count++) {
    interfaceClasses[count]=forName(interfaces[count],caller);
  }
  final ClassLoader proxyClassLoader;
  final ClassLoader threadClassLoader=Thread.currentThread().getContextClassLoader();
  if (threadClassLoader != null) {
    proxyClassLoader=threadClassLoader;
  }
 else {
    final ClassLoader classLoader=caller.getClassLoader();
    if (classLoader != null) {
      proxyClassLoader=classLoader;
    }
 else {
      proxyClassLoader=ClassLoader.getSystemClassLoader();
    }
  }
  return Proxy.getProxyClass(proxyClassLoader,interfaceClasses);
}
 

Example 56

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/sql/.

Source file: ConnectionInvocationHandler.java

  29 
vote

/** 
 * @see net.sf.hajdbc.sql.AbstractChildInvocationHandler#postInvoke(java.lang.Object,java.lang.reflect.Method,java.lang.Object[])
 */
@Override protected void postInvoke(Connection object,Method method,Object[] parameters){
  if (method.equals(closeMethod)) {
    this.transactionContext.close();
    this.getParentProxy().removeChild(this);
  }
 else   if (method.equals(releaseSavepointMethod)) {
    @SuppressWarnings("unchecked") SQLProxy<Z,D,Savepoint,SQLException> proxy=(SQLProxy<Z,D,Savepoint,SQLException>)Proxy.getInvocationHandler(parameters[0]);
    this.removeChild(proxy);
  }
}
 

Example 57

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

Source file: IOUtil.java

  29 
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 58

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

Source file: AnnotationFactory.java

  29 
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 59

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

Source file: AnnotationFactory.java

  29 
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 60

From project incubator-deltaspike, under directory /deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/metadata/.

Source file: AnnotationInstanceProvider.java

  29 
vote

/** 
 * {@inheritDoc}
 */
@Override public Object invoke(Object proxy,Method method,Object[] args) throws Exception {
  if ("hashCode".equals(method.getName())) {
    return hashCode();
  }
 else   if ("equals".equals(method.getName())) {
    if (Proxy.isProxyClass(args[0].getClass())) {
      if (Proxy.getInvocationHandler(args[0]) instanceof AnnotationInstanceProvider) {
        return equals(Proxy.getInvocationHandler(args[0]));
      }
    }
    return equals(args[0]);
  }
 else   if ("annotationType".equals(method.getName())) {
    return annotationType();
  }
 else   if ("toString".equals(method.getName())) {
    return toString();
  }
 else {
    if (memberValues.containsKey(method.getName())) {
      return memberValues.get(method.getName());
    }
 else {
      return method.getDefaultValue();
    }
  }
}
 

Example 61

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

Source file: AnnotationImpl.java

  29 
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 62

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

Source file: EJBClient.java

  29 
vote

/** 
 * Get an asynchronous view of a proxy.  Any  {@code void} method on the proxy will be invoked fully asynchronouslywithout a server round-trip delay.  Any method which returns a  {@link java.util.concurrent.Future Future} willcontinue to be asynchronous.  Any other method invoked on the returned proxy will return  {@code null} (the futureresult can be acquired by wrapping the remote call with  {@link #getFutureResult(Object)} or by using {@link #getFutureResult()}). If an asynchronous view is passed in, the same view is returned.
 * @param proxy the proxy interface instance
 * @param < T >   the proxy type
 * @return the asynchronous view
 * @throws IllegalArgumentException if the given object is not a valid proxy
 */
@SuppressWarnings("unchecked") public static <T>T asynchronous(final T proxy) throws IllegalArgumentException {
  final InvocationHandler invocationHandler=Proxy.getInvocationHandler(proxy);
  if (invocationHandler instanceof EJBInvocationHandler) {
    final EJBInvocationHandler remoteInvocationHandler=(EJBInvocationHandler)invocationHandler;
    if (true) {
      return proxy;
    }
 else {
      return (T)Proxy.newProxyInstance(proxy.getClass().getClassLoader(),proxy.getClass().getInterfaces(),remoteInvocationHandler.getAsyncHandler());
    }
  }
 else {
    throw log.unknownProxy(proxy);
  }
}
 

Example 63

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

Source file: AOPBasedSingletonContainer.java

  29 
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 64

From project jboss-ejb3-tx2, under directory /antediluvian/src/test/java/org/jboss/ejb3/test/tx/common/.

Source file: StatefulContainer.java

  29 
vote

/** 
 * For proxied access.
 * @param < I >
 * @param intf
 * @return
 * @throws Throwable
 */
public <I>I constructProxy(Class<I> intf) throws Throwable {
  Object id=construct();
  ClassLoader loader=Thread.currentThread().getContextClassLoader();
  Class<?> interfaces[]={intf};
  Object proxy=Proxy.newProxyInstance(loader,interfaces,new ProxyInvocationHandler(id));
  return intf.cast(proxy);
}
 

Example 65

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

Source file: DummyPersistenceUnit.java

  29 
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 66

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

Source file: AbstractClassResolver.java

  29 
vote

/** 
 * {@inheritDoc}  The base implementation uses the class loader returned from {@code getClassLoader()} and loadseach interface by name, returning a proxy class from that class loader.
 */
public Class<?> resolveProxyClass(final Unmarshaller unmarshaller,final String[] interfaces) throws IOException, ClassNotFoundException {
  final ClassLoader classLoader=getClassLoaderChecked();
  final int length=interfaces.length;
  Class<?>[] classes=new Class<?>[length];
  for (int i=0; i < length; i++) {
    classes[i]=loadClass(interfaces[i]);
  }
  return Proxy.getProxyClass(classLoader,classes);
}
 

Example 67

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

Source file: ObjectStreamClass.java

  29 
vote

private ObjectStreamClass(Class<?> cl,ObjectStreamClass superdesc,boolean serial,boolean extern){
  ofClass=cl;
  if (Proxy.isProxyClass(cl)) {
    forProxyClass=true;
  }
  name=cl.getName();
  superclass=superdesc;
  serializable=serial;
  if (!forProxyClass) {
    externalizable=extern;
  }
  insertDescriptorFor(this);
}
 

Example 68

From project jdbi, under directory /src/test/java/org/skife/jdbi/v2/sqlobject/.

Source file: TestDoublyTransactional.java

  29 
vote

@Override public void setUp() throws Exception {
  final JdbcDataSource ds=new JdbcDataSource(){
    private static final long serialVersionUID=1L;
    @Override public Connection getConnection() throws SQLException {
      final Connection real=super.getConnection();
      return (Connection)Proxy.newProxyInstance(real.getClass().getClassLoader(),new Class<?>[]{Connection.class},new TxnIsolationCheckingInvocationHandler(real));
    }
  }
;
  ds.setURL("jdbc:h2:mem:test" + new Random().nextInt() + ";MVCC=TRUE");
  dbi=new DBI(ds);
  dbi.registerMapper(new SomethingMapper());
  handle=dbi.open();
  handle.execute("create table something (id int primary key, name varchar(100))");
}
 

Example 69

From project jdonframework, under directory /JdonAccessory/src/com/jdon/bussinessproxy/remote/.

Source file: ServiceHTTPImp.java

  29 
vote

/** 
 * ?????????????????
 * @param EJBDefinition
 * @return
 */
public Object getServiceFromProxy(TargetMetaDef targetMetaDef){
  RemoteInvocationHandler handler=null;
  Object dynamicProxy=null;
  try {
    Debug.logVerbose("[JdonFramework] ---> create a new ProxyInstance",module);
    handler=new RemoteInvocationHandler(targetMetaDef);
    ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
    Class serviceClass=classLoader.loadClass(targetMetaDef.getClassName());
    dynamicProxy=Proxy.newProxyInstance(classLoader,new Class[]{serviceClass},handler);
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  return dynamicProxy;
}
 

Example 70

From project jetty-project, under directory /jetty-reverse-http/reverse-http-gateway/src/test/java/org/mortbay/jetty/rhttp/gateway/.

Source file: HostTargetIdRetrieverTest.java

  29 
vote

public void testHostTargetIdRetrieverNoSuffix(){
  String host="test";
  Class<HttpServletRequest> klass=HttpServletRequest.class;
  HttpServletRequest request=(HttpServletRequest)Proxy.newProxyInstance(klass.getClassLoader(),new Class<?>[]{klass},new Request(host));
  HostTargetIdRetriever retriever=new HostTargetIdRetriever(null);
  String result=retriever.retrieveTargetId(request);
  assertEquals(host,result);
}
 

Example 71

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

Source file: ClassMetaData.java

  29 
vote

public ClassMetaData(Class clazz){
  setClassName(clazz.getName());
  setClazz(clazz);
  setShaHash(HashStringUtil.hashName(clazz.getName()));
  setProxy(Proxy.isProxyClass(clazz));
  lookupInternalMethods(clazz);
  try {
    setConstructor(findConstructor(clazz));
  }
 catch (  NoSuchMethodException e) {
    setConstructor(null);
  }
  setExternalizable(Externalizable.class.isAssignableFrom(clazz));
  setSerializable(Serializable.class.isAssignableFrom(clazz));
  setImmutable(Immutable.class.isAssignableFrom(clazz));
  exploreSlots(clazz);
}
 

Example 72

From project jftp, under directory /src/main/java/com/myjavaworld/jftp/.

Source file: OSXAdapter.java

  29 
vote

/** 
 * Registers a handler for a specific event.
 * @param handlerClassName the event handler interface name (e.g. com.apple.eawt.AboutHandler).
 * @param registrationMethodName the name of the method defined in the com.apple.eawt.Application class for registering the above event handler.
 */
private static void registerHandler(String handlerClassName,String registrationMethodName){
  try {
    Class<?> handlerClass=Class.forName(handlerClassName);
    Object proxy=Proxy.newProxyInstance(handlerClass.getClassLoader(),new Class[]{handlerClass},eventHandler);
    Method method=macOSXApplication.getClass().getMethod(registrationMethodName,handlerClass);
    method.invoke(macOSXApplication,proxy);
  }
 catch (  Throwable t) {
    System.err.println("Unable to register event handler: " + handlerClassName);
    t.printStackTrace();
  }
}
 

Example 73

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

Source file: JolokiaActivatorTest.java

  29 
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 74

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

Source file: ReflectionUtils.java

  29 
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 75

From project jRapidRPC, under directory /jRapidRPC/src/main/java/ru/fractalizer/jrapidrpc/client/simple/.

Source file: SimpleTCPClient.java

  29 
vote

/** 
 * Creates a client socket and connects to the server. If successful, returns an RPC object which methods you can call. All calls will be forwarded to the server
 * @param serviceInterface An RPC interface, defining methods of RPC communication
 * @return A proxy object which methods you can call. All calls will be forwarded to server
 * @throws IOException Is thrown on any connection problem
 */
public <T>T connect(Class<T> serviceInterface) throws IOException {
  if (!serviceInterface.isInterface()) {
    throw new IllegalArgumentException("serviceInterface must be of interface type!");
  }
  try {
    socket=new Socket(this.serverHost,this.serverPort);
    outputStream=socket.getOutputStream();
    inputStream=socket.getInputStream();
  }
 catch (  IOException e) {
    if (inputStream != null) {
      inputStream.close();
    }
    if (outputStream != null) {
      outputStream.close();
    }
    if (socket != null) {
      socket.close();
    }
    throw e;
  }
  return (T)Proxy.newProxyInstance(this.getClass().getClassLoader(),new Class[]{serviceInterface},this);
}
 

Example 76

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

Source file: FacesMock.java

  29 
vote

private static IMocksControl getControl(Object mock){
  if (mock instanceof FacesMockController.MockObject) {
    FacesMockController.MockObject mockObject=(FacesMockController.MockObject)mock;
    return mockObject.getControl();
  }
 else {
    Class<? extends Object> mockClass=mock.getClass();
    if (isMockClass(mockClass)) {
      try {
        Method getControl=mockClass.getMethod("getControl");
        if (IMocksControl.class.equals(getControl.getReturnType())) {
          return (IMocksControl)getControl.invoke(mock);
        }
      }
 catch (      SecurityException e) {
      }
catch (      NoSuchMethodException e) {
      }
catch (      IllegalArgumentException e) {
      }
catch (      IllegalAccessException e) {
      }
catch (      InvocationTargetException e) {
      }
    }
    return ((ObjectMethodsFilter)Proxy.getInvocationHandler(mock)).getDelegate().getControl();
  }
}
 

Example 77

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

Source file: StubJndiContextTest.java

  29 
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 78

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

Source file: InterfaceProxyFactory.java

  29 
vote

@SuppressWarnings("unchecked") public <T>T createProxy(T obj,final InvocationHandler handler){
  Class<?> c=obj.getClass();
  Class<?>[] interfaces=c.getInterfaces();
  if (interfaces.length == 0) {
    throw new IllegalArgumentException("Can not create a proxy using the " + InterfaceProxyFactory.class.getSimpleName() + ", because the class "+ c.getName()+ " does not implement any interfaces");
  }
  return (T)Proxy.newProxyInstance(c.getClassLoader(),interfaces,handler);
}
 

Example 79

From project Kairos, under directory /src/test/org/apache/nutch/searcher/response/.

Source file: TestRequestUtils.java

  29 
vote

/** 
 * Create a mock HttpServletRequest.
 */
private HttpServletRequest createMockHttpServletRequest(Map parameters){
  MockHttpServletRequestInvocationHandler handler=new MockHttpServletRequestInvocationHandler();
  handler.setParameterMap(parameters);
  ClassLoader cl=getClass().getClassLoader();
  Class[] interfaces=new Class[]{HttpServletRequest.class};
  return (HttpServletRequest)Proxy.newProxyInstance(cl,interfaces,handler);
}
 

Example 80

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

Source file: Converters.java

  29 
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 81

From project karaf-cellar, under directory /dosgi/src/main/java/org/apache/karaf/cellar/dosgi/.

Source file: RemoteServiceFactory.java

  29 
vote

@Override public Object getService(Bundle bundle,ServiceRegistration registration){
  ClassLoader classLoader=new RemoteServiceProxyClassLoader(bundle);
  List<Class> interfaces=new ArrayList<Class>();
  String interfaceName=description.getServiceClass();
  try {
    interfaces.add(classLoader.loadClass(interfaceName));
  }
 catch (  ClassNotFoundException e) {
  }
  RemoteServiceInvocationHandler handler=new RemoteServiceInvocationHandler(description.getId(),interfaceName,clusterManager,executionContext);
  return Proxy.newProxyInstance(classLoader,interfaces.toArray(new Class[interfaces.size()]),handler);
}
 

Example 82

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

Source file: ZoomButtonsController.java

  29 
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 83

From project koneki.ldt, under directory /plugins/com.naef.jnlua/src/com/naef/jnlua/.

Source file: LuaState.java

  29 
vote

/** 
 * Returns a proxy object implementing the specified list of interfaces in Lua. The table at the specified stack index contains the method names from the interfaces as keys and the Lua functions implementing the interface methods as values. The returned object always implements the {@link LuaValueProxy} interface in addition to the specified interfaces.
 * @param index the stack index containing the table
 * @param interfaces the interfaces
 * @return the proxy object
 */
public synchronized LuaValueProxy getProxy(int index,Class<?>[] interfaces){
  pushValue(index);
  if (!isTable(index)) {
    throw new IllegalArgumentException(String.format("index %d is not a table",index));
  }
  Class<?>[] allInterfaces=new Class<?>[interfaces.length + 1];
  System.arraycopy(interfaces,0,allInterfaces,0,interfaces.length);
  allInterfaces[allInterfaces.length - 1]=LuaValueProxy.class;
  int reference=ref(REGISTRYINDEX);
  try {
    Object proxy=Proxy.newProxyInstance(classLoader,allInterfaces,new LuaInvocationHandler(reference));
    reference=-1;
    return (LuaValueProxy)proxy;
  }
  finally {
    if (reference >= 0) {
      unref(REGISTRYINDEX,reference);
    }
  }
}
 

Example 84

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

Source file: JdkProxySerializer.java

  29 
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 85

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

Source file: EhCacheService.java

  29 
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 86

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

Source file: MojoInfo.java

  29 
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 87

From project liferay-meetups-portlet, under directory /src/main/java/fr/smile/socialnetworking/model/impl/.

Source file: MeetupsEntryModelImpl.java

  29 
vote

@Override public MeetupsEntry toEscapedModel(){
  if (isEscapedModel()) {
    return (MeetupsEntry)this;
  }
 else {
    if (_escapedModelProxy == null) {
      _escapedModelProxy=(MeetupsEntry)Proxy.newProxyInstance(_classLoader,_escapedModelProxyInterfaces,new AutoEscapeBeanHandler(this));
    }
    return _escapedModelProxy;
  }
}
 

Example 88

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

Source file: BalancingAndRetryingRepository.java

  29 
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 89

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

Source file: ObjectProxyBuilder.java

  29 
vote

/** 
 * Convenient call which creates a proxy using the handler and the interface. It will also check that the object bien proxied (if implements <code>ObjectProxy</code>) properly implement the interface...
 * @return the proxy (which implement all the interface)
 */
@SuppressWarnings("unchecked") public static <T>T createProxy(InvocationHandler handler,Class<T> itface){
  if (handler instanceof ObjectProxy) {
    ObjectProxy proxy=(ObjectProxy)handler;
    if (!ReflectUtils.isSubClassOrInterfaceOf(proxy.getProxiedObject().getClass(),itface))     throw new IllegalArgumentException(proxy.getProxiedObject().getClass() + " does not extend " + itface);
  }
  return (T)Proxy.newProxyInstance(itface.getClassLoader(),new Class<?>[]{itface},handler);
}
 

Example 90

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

Source file: Mock.java

  29 
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);
  }
}