KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > mx4j > remote > rmi > ClientUnmarshaller


1 /*
2  * Copyright (C) MX4J.
3  * All rights reserved.
4  *
5  * This software is distributed under the terms of the MX4J License version 1.0.
6  * See the terms of the MX4J License in the documentation provided with this software.
7  */

8
9 package mx4j.remote.rmi;
10
11 import java.lang.reflect.Method JavaDoc;
12 import java.lang.reflect.Proxy JavaDoc;
13 import java.security.AccessController JavaDoc;
14 import java.security.PrivilegedAction JavaDoc;
15
16 import javax.management.MBeanServerConnection JavaDoc;
17
18 import mx4j.remote.ClientProxy;
19
20 /**
21  * An MBeanServerConnection proxy that performs the setting of the appropriate context classloader
22  * to allow classloading of classes sent by the server but not known to the client, in methods like
23  * {@link MBeanServerConnection#getAttribute}, {@link MBeanServerConnection#invoke} and so on.
24  *
25  * @author <a HREF="mailto:biorn_steedom@users.sourceforge.net">Simone Bordet</a>
26  * @version $Revision: 1.2 $
27  */

28 public class ClientUnmarshaller extends ClientProxy
29 {
30    private final ClassLoader JavaDoc classLoader;
31
32    private ClientUnmarshaller(MBeanServerConnection JavaDoc target, ClassLoader JavaDoc loader)
33    {
34       super(target);
35       this.classLoader = loader;
36    }
37
38    public static MBeanServerConnection JavaDoc newInstance(MBeanServerConnection JavaDoc target, ClassLoader JavaDoc loader)
39    {
40       ClientUnmarshaller handler = new ClientUnmarshaller(target, loader);
41       return (MBeanServerConnection JavaDoc)Proxy.newProxyInstance(handler.getClass().getClassLoader(), new Class JavaDoc[]{MBeanServerConnection JavaDoc.class}, handler);
42    }
43
44    public Object JavaDoc invoke(Object JavaDoc proxy, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc
45    {
46       if (classLoader == null)
47       {
48          return chain(proxy, method, args);
49       }
50       else
51       {
52          ClassLoader JavaDoc old = Thread.currentThread().getContextClassLoader();
53          try
54          {
55             setContextClassLoader(classLoader);
56             return chain(proxy, method, args);
57          }
58          finally
59          {
60             setContextClassLoader(old);
61          }
62       }
63    }
64
65    private Object JavaDoc chain(Object JavaDoc proxy, Method JavaDoc method, Object JavaDoc[] args) throws Throwable JavaDoc
66    {
67       return super.invoke(proxy, method, args);
68    }
69
70    private void setContextClassLoader(final ClassLoader JavaDoc loader)
71    {
72       AccessController.doPrivileged(new PrivilegedAction JavaDoc()
73       {
74          public Object JavaDoc run()
75          {
76             Thread.currentThread().setContextClassLoader(loader);
77             return null;
78          }
79       });
80    }
81 }
82
Popular Tags