blob: 0b4c20b9e453699056e021d3775411cd56894e2f [file] [log] [blame]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>dynamic-proxy-to-access-mbean</title>
<meta name="description" content="Apache TomEE">
<meta name="author" content="Apache TomEE">
<meta name="google-translate-customization" content="f36a520c08f4c9-0a04e86a9c075ce9-g265f3196f697cf8f-10">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate, max-age=0">
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Le styles -->
<link href="./../../resources/css/bootstrap.css" rel="stylesheet">
<link href="./../../resources/css/prettify.css" rel="stylesheet">
<!--link href="./../../resources/css/bootstrap-mods.css" rel="stylesheet"-->
<link href="./../../resources/css/main.css" rel="stylesheet">
<link href="./../../resources/font-awesome-4.6.3/css/font-awesome.min.css" rel="stylesheet">
<script type="text/javascript">
var t = encodeURIComponent(document.title.replace(/^\s+|\s+$/g,""));
var u = encodeURIComponent(""+document.URL);
function fbshare () {
window.open(
"http://www.facebook.com/sharer/sharer.php?u="+u,
'Share on Facebook',
'width=640,height=426');
};
function gpshare () {
window.open(
"https://plus.google.com/share?url="+u,
'Share on Google+',
'width=584,height=385');
};
function twshare () {
window.open(
"https://twitter.com/intent/tweet?url="+u+"&text="+t,
'Share on Twitter',
'width=800,height=526');
};
function pinshare () {
window.open("//www.pinterest.com/pin/create/button/?url="+u+"&media=http%3A%2F%2Ftomee.apache.org%2Fresources%2Fimages%2Ffeather-logo.png&description="+t,
'Share on Pinterest',
'width=800,height=526');
};
</script>
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="./../../favicon.ico">
<link rel="apple-touch-icon" href="./../../resources/images/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="./../../resources/images/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="./../../resources/images/apple-touch-icon-114x114.png">
<script src="./../../resources/js/prettify.js" type="text/javascript"></script>
<script src="./../../resources/js/jquery-latest.js"></script>
<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
<script src="./../../resources/js/common.js"></script>
<script src="./../../resources/js/prettyprint.js"></script>
<!--script src="//assets.pinterest.com/js/pinit.js" type="text/javascript" async></script//-->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2717626-1']);
_gaq.push(['_setDomainName', 'apache.org']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div class="topbar" data-dropdown="dropdown">
<div class="fill">
<div class="container">
<a class="brand" href="./../../index.html">Apache TomEE</a>
<ul class="nav">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
Apache
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<!-- <li><a href="./../../misc/whoweare.html">Who we are?</a></li> -->
<!-- <li><a href="./../../misc/heritage.html">Heritage</a></li> -->
<li><a href="http://www.apache.org">Apache Home</a></li>
<!-- <li><a href="./../../misc/resources.html">Resources</a></li> -->
<li><a href="./../../misc/contact.html">Contact</a></li>
<li><a href="./../../misc/legal.html">Legal</a></li>
<li><a href="http://www.apache.org/foundation/sponsorship.html">Sponsorship</a></li>
<li><a href="http://www.apache.org/foundation/thanks.html">Thanks</a></li>
<li class="divider"/>
<li><a href="http://www.apache.org/security">Security</a></li>
</ul>
</li>
<li><a href="./../../index.html">Home</a></li>
<li><a href="./../../downloads.html">Downloads</a></li>
<li><a href="./../../documentation.html">Documentation</a></li>
<li><a href="./../../examples-trunk/index.html">Examples</a></li>
<li><a href="./../../support.html">Support</a></li>
<li><a href="./../../contribute.html">Contribute</a></li>
<li><a href="./../../security/index.html">Security</a></li>
</ul>
<!-- Google CSE Search Box Begins -->
<FORM class="pull-right" id="searchbox_010475492895890475512:_t4iqjrgx90" action="http://www.google.com/cse">
<INPUT type="hidden" name="cx" value="010475492895890475512:_t4iqjrgx90">
<INPUT type="hidden" name="cof" value="FORID:0">
<INPUT size="18" width="130" style="width:130px" name="q" type="text" placeholder="Search">
</FORM>
<!--<SCRIPT type="text/javascript" src="http://www.google.com/coop/cse/brand?form=searchbox_010475492895890475512:_t4iqjrgx90"></SCRIPT>-->
<!-- Google CSE Search Box Ends -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="span8">
<small><a href="./../../index.html">Home</a>&nbsp;&raquo&nbsp;<a href="./../../examples/">Examples</a>&nbsp;&raquo&nbsp;<a href="./../../examples/dynamic-proxy-to-access-mbean/">Dynamic Proxy To Access Mbean</a></small><br>
</div>
<div class="span8">
</div>
</div>
&nbsp;
<div class="page-header">
<h1>dynamic-proxy-to-access-mbean
<div style="float: right; position: relative; bottom: -10px; ">
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<a onclick="javascript:gpshare()" class="gp-share sprite" title="Share on Google+">share [gp]</a>
<a onclick="javascript:fbshare()" class="fb-share sprite" title="Share on Facebook">share [fb]</a>
<a onclick="javascript:twshare()" class="tw-share sprite" title="Share on Twitter">share [tw]</a>
<a onclick="javascript:pinshare()" class="pin-share sprite" title="Share on Pinterest">share [pin]</a>
<a data-toggle="modal" href="#edit" class="edit-page" title="Contribute to this Page">contribute</a>
</div>
</h1>
</div>
<p><em>Help us document this example! Click the blue pencil icon in the upper right to edit this page.</em></p>
<h2>Example</h2>
<p>Acessing MBean is something simple through the JMX API but it is often technical and not very interesting.</p>
<p>This example simplify this work simply doing it generically in a proxy.</p>
<p>So from an user side you simple declare an interface to access your MBeans.</p>
<p>Note: the example implementation uses a local MBeanServer but enhancing the example API
it is easy to imagine a remote connection with user/password if needed.</p>
<h2>ObjectName API (annotation)</h2>
<p>Simply an annotation to get the object</p>
<pre><code>package org.superbiz.dynamic.mbean;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface ObjectName {
String value();
// for remote usage only
String url() default "";
String user() default "";
String password() default "";
}
</code></pre>
<h2>DynamicMBeanHandler (thr proxy implementation)</h2>
<pre><code>package org.superbiz.dynamic.mbean;
import javax.annotation.PreDestroy;
import javax.management.Attribute;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Need a @PreDestroy method to disconnect the remote host when used in remote mode.
*/
public class DynamicMBeanHandler implements InvocationHandler {
private final Map&lt;Method, ConnectionInfo&gt; infos = new ConcurrentHashMap&lt;Method, ConnectionInfo&gt;();
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final String methodName = method.getName();
if (method.getDeclaringClass().equals(Object.class) &amp;&amp; "toString".equals(methodName)) {
return getClass().getSimpleName() + " Proxy";
}
if (method.getAnnotation(PreDestroy.class) != null) {
return destroy();
}
final ConnectionInfo info = getConnectionInfo(method);
final MBeanInfo infos = info.getMBeanInfo();
if (methodName.startsWith("set") &amp;&amp; methodName.length() &gt; 3 &amp;&amp; args != null &amp;&amp; args.length == 1
&amp;&amp; (Void.TYPE.equals(method.getReturnType()) || Void.class.equals(method.getReturnType()))) {
final String attributeName = attributeName(infos, methodName, method.getParameterTypes()[0]);
info.setAttribute(new Attribute(attributeName, args[0]));
return null;
} else if (methodName.startsWith("get") &amp;&amp; (args == null || args.length == 0) &amp;&amp; methodName.length() &gt; 3) {
final String attributeName = attributeName(infos, methodName, method.getReturnType());
return info.getAttribute(attributeName);
}
// operation
return info.invoke(methodName, args, getSignature(method));
}
public Object destroy() {
for (ConnectionInfo info : infos.values()) {
info.clean();
}
infos.clear();
return null;
}
private String[] getSignature(Method method) {
String[] args = new String[method.getParameterTypes().length];
for (int i = 0; i &lt; method.getParameterTypes().length; i++) {
args[i] = method.getParameterTypes()[i].getName();
}
return args; // note: null should often work...
}
private String attributeName(MBeanInfo infos, String methodName, Class&lt;?&gt; type) {
String found = null;
String foundBackUp = null; // without checking the type
final String attributeName = methodName.substring(3, methodName.length());
final String lowerName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4, methodName.length());
for (MBeanAttributeInfo attribute : infos.getAttributes()) {
final String name = attribute.getName();
if (attributeName.equals(name)) {
foundBackUp = attributeName;
if (attribute.getType().equals(type.getName())) {
found = name;
}
} else if (found == null &amp;&amp; ((lowerName.equals(name) &amp;&amp; !attributeName.equals(name))
|| lowerName.equalsIgnoreCase(name))) {
foundBackUp = name;
if (attribute.getType().equals(type.getName())) {
found = name;
}
}
}
if (found == null &amp;&amp; foundBackUp == null) {
throw new UnsupportedOperationException("cannot find attribute " + attributeName);
}
if (found != null) {
return found;
}
return foundBackUp;
}
private synchronized ConnectionInfo getConnectionInfo(Method method) throws Exception {
if (!infos.containsKey(method)) {
synchronized (infos) {
if (!infos.containsKey(method)) { // double check for synchro
org.superbiz.dynamic.mbean.ObjectName on = method.getAnnotation(org.superbiz.dynamic.mbean.ObjectName.class);
if (on == null) {
Class&lt;?&gt; current = method.getDeclaringClass();
do {
on = method.getDeclaringClass().getAnnotation(org.superbiz.dynamic.mbean.ObjectName.class);
current = current.getSuperclass();
} while (on == null &amp;&amp; current != null);
if (on == null) {
throw new UnsupportedOperationException("class or method should define the objectName to use for invocation: " + method.toGenericString());
}
}
final ConnectionInfo info;
if (on.url().isEmpty()) {
info = new LocalConnectionInfo();
((LocalConnectionInfo) info).server = ManagementFactory.getPlatformMBeanServer(); // could use an id...
} else {
info = new RemoteConnectionInfo();
final Map&lt;String, String[]&gt; environment = new HashMap&lt;String, String[]&gt;();
if (!on.user().isEmpty()) {
environment.put(JMXConnector.CREDENTIALS, new String[]{ on.user(), on.password() });
}
// ((RemoteConnectionInfo) info).connector = JMXConnectorFactory.newJMXConnector(new JMXServiceURL(on.url()), environment);
((RemoteConnectionInfo) info).connector = JMXConnectorFactory.connect(new JMXServiceURL(on.url()), environment);
}
info.objectName = new ObjectName(on.value());
infos.put(method, info);
}
}
}
return infos.get(method);
}
private abstract static class ConnectionInfo {
protected ObjectName objectName;
public abstract void setAttribute(Attribute attribute) throws Exception;
public abstract Object getAttribute(String attribute) throws Exception;
public abstract Object invoke(String operationName, Object params[], String signature[]) throws Exception;
public abstract MBeanInfo getMBeanInfo() throws Exception;
public abstract void clean();
}
private static class LocalConnectionInfo extends ConnectionInfo {
private MBeanServer server;
@Override public void setAttribute(Attribute attribute) throws Exception {
server.setAttribute(objectName, attribute);
}
@Override public Object getAttribute(String attribute) throws Exception {
return server.getAttribute(objectName, attribute);
}
@Override
public Object invoke(String operationName, Object[] params, String[] signature) throws Exception {
return server.invoke(objectName, operationName, params, signature);
}
@Override public MBeanInfo getMBeanInfo() throws Exception {
return server.getMBeanInfo(objectName);
}
@Override public void clean() {
// no-op
}
}
private static class RemoteConnectionInfo extends ConnectionInfo {
private JMXConnector connector;
private MBeanServerConnection connection;
private void before() throws IOException {
connection = connector.getMBeanServerConnection();
}
private void after() throws IOException {
// no-op
}
@Override public void setAttribute(Attribute attribute) throws Exception {
before();
connection.setAttribute(objectName, attribute);
after();
}
@Override public Object getAttribute(String attribute) throws Exception {
before();
try {
return connection.getAttribute(objectName, attribute);
} finally {
after();
}
}
@Override
public Object invoke(String operationName, Object[] params, String[] signature) throws Exception {
before();
try {
return connection.invoke(objectName, operationName, params, signature);
} finally {
after();
}
}
@Override public MBeanInfo getMBeanInfo() throws Exception {
before();
try {
return connection.getMBeanInfo(objectName);
} finally {
after();
}
}
@Override public void clean() {
try {
connector.close();
} catch (IOException e) {
// no-op
}
}
}
}
</code></pre>
<h2>Dynamic Proxies</h2>
<h3>DynamicMBeanClient (the dynamic JMX client)</h3>
<pre><code>package org.superbiz.dynamic.mbean;
import org.apache.openejb.api.Proxy;
import org.superbiz.dynamic.mbean.DynamicMBeanHandler;
import org.superbiz.dynamic.mbean.ObjectName;
import javax.ejb.Singleton;
/**
* @author rmannibucau
*/
@Singleton
@Proxy(DynamicMBeanHandler.class)
@ObjectName(DynamicMBeanClient.OBJECT_NAME)
public interface DynamicMBeanClient {
static final String OBJECT_NAME = "test:group=DynamicMBeanClientTest";
int getCounter();
void setCounter(int i);
int length(String aString);
}
</code></pre>
<h3>DynamicMBeanClient (the dynamic JMX client)</h3>
<pre><code>package org.superbiz.dynamic.mbean;
import org.apache.openejb.api.Proxy;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
@Singleton
@Proxy(DynamicMBeanHandler.class)
@ObjectName(value = DynamicRemoteMBeanClient.OBJECT_NAME, url = "service:jmx:rmi:///jndi/rmi://localhost:8243/jmxrmi")
public interface DynamicRemoteMBeanClient {
static final String OBJECT_NAME = "test:group=DynamicMBeanClientTest";
int getCounter();
void setCounter(int i);
int length(String aString);
@PreDestroy void clean();
}
</code></pre>
<h2>The MBean used for the test</h2>
<h3>SimpleMBean</h3>
<pre><code>package org.superbiz.dynamic.mbean.simple;
public interface SimpleMBean {
int length(String s);
int getCounter();
void setCounter(int c);
}
</code></pre>
<h2>Simple</h2>
<pre><code>package org.superbiz.dynamic.mbean.simple;
public class Simple implements SimpleMBean {
private int counter = 0;
@Override public int length(String s) {
if (s == null) {
return 0;
}
return s.length();
}
@Override public int getCounter() {
return counter;
}
@Override public void setCounter(int c) {
counter = c;
}
}
</code></pre>
<h2>DynamicMBeanClientTest (The test)</h2>
<pre><code>package org.superbiz.dynamic.mbean;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.superbiz.dynamic.mbean.simple.Simple;
import javax.ejb.EJB;
import javax.ejb.embeddable.EJBContainer;
import javax.management.Attribute;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import static junit.framework.Assert.assertEquals;
public class DynamicMBeanClientTest {
private static ObjectName objectName;
private static EJBContainer container;
@EJB private DynamicMBeanClient localClient;
@EJB private DynamicRemoteMBeanClient remoteClient;
@BeforeClass public static void start() {
container = EJBContainer.createEJBContainer();
}
@Before public void injectAndRegisterMBean() throws Exception {
container.getContext().bind("inject", this);
objectName = new ObjectName(DynamicMBeanClient.OBJECT_NAME);
ManagementFactory.getPlatformMBeanServer().registerMBean(new Simple(), objectName);
}
@After public void unregisterMBean() throws Exception {
if (objectName != null) {
ManagementFactory.getPlatformMBeanServer().unregisterMBean(objectName);
}
}
@Test public void localGet() throws Exception {
assertEquals(0, localClient.getCounter());
ManagementFactory.getPlatformMBeanServer().setAttribute(objectName, new Attribute("Counter", 5));
assertEquals(5, localClient.getCounter());
}
@Test public void localSet() throws Exception {
assertEquals(0, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, "Counter")).intValue());
localClient.setCounter(8);
assertEquals(8, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, "Counter")).intValue());
}
@Test public void localOperation() {
assertEquals(7, localClient.length("openejb"));
}
@Test public void remoteGet() throws Exception {
assertEquals(0, remoteClient.getCounter());
ManagementFactory.getPlatformMBeanServer().setAttribute(objectName, new Attribute("Counter", 5));
assertEquals(5, remoteClient.getCounter());
}
@Test public void remoteSet() throws Exception {
assertEquals(0, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, "Counter")).intValue());
remoteClient.setCounter(8);
assertEquals(8, ((Integer) ManagementFactory.getPlatformMBeanServer().getAttribute(objectName, "Counter")).intValue());
}
@Test public void remoteOperation() {
assertEquals(7, remoteClient.length("openejb"));
}
@AfterClass public static void close() {
if (container != null) {
container.close();
}
}
}
</code></pre>
<div class="page-header">&nbsp;</div>
<h4>APIs Used</h4>
<ul><li><a href="http://docs.oracle.com/javaee/6/api/javax/annotation/PreDestroy.html">javax.annotation.PreDestroy</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/ejb/EJB.html">javax.ejb.EJB</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/ejb/Singleton.html">javax.ejb.Singleton</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/ejb/embeddable/EJBContainer.html">javax.ejb.embeddable.EJBContainer</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/management/Attribute.html">javax.management.Attribute</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/management/MBeanAttributeInfo.html">javax.management.MBeanAttributeInfo</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/management/MBeanInfo.html">javax.management.MBeanInfo</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/management/MBeanServer.html">javax.management.MBeanServer</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/management/MBeanServerConnection.html">javax.management.MBeanServerConnection</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/management/ObjectName.html">javax.management.ObjectName</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/management/remote/JMXConnector.html">javax.management.remote.JMXConnector</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/management/remote/JMXConnectorFactory.html">javax.management.remote.JMXConnectorFactory</a></li>
<li><a href="http://docs.oracle.com/javaee/6/api/javax/management/remote/JMXServiceURL.html">javax.management.remote.JMXServiceURL</a></li>
</ul>
<h3>Source</h3>
<ul>
<li>Apache <a href="http://svn.apache.org/repos/asf/tomee/tomee//examples/dynamic-proxy-to-access-mbean">dynamic-proxy-to-access-mbean</a></li>
<li>Github <a href="https://github.com/apache/tomee/tree//examples/dynamic-proxy-to-access-mbean">dynamic-proxy-to-access-mbean</a></li>
</ul>
<pre>
svn co http://svn.apache.org/repos/asf/tomee/tomee//examples/dynamic-proxy-to-access-mbean
cd dynamic-proxy-to-access-mbean
mvn clean install
</pre>
<div id="edit" class="modal hide fade in" style="display: none; ">
<div class="modal-header">
<a class="close" data-dismiss="modal">x</a>
<h3>Thank you for contributing to the documentation!</h3>
</div>
<div class="modal-body">
<h4>Any help with the documentation is greatly appreciated.</h4>
<p>All edits are reviewed before going live, so feel free to do much more than fix typos or links. If you see a page that could benefit from an entire rewrite, we'd be thrilled to review it. Don't be surprised if we like it so much we ask you for help with other pages :)</p>
<small>NOTICE: unless indicated otherwise on the pages in question, all editable content available from apache.org is presumed to be licensed under the Apache License (AL) version 2.0 and hence all submissions to apache.org treated as formal Contributions under the license terms.</small>
<!--[if gt IE 6]>
<h4>Internet Explorer Users</h4>
<p>If you are not an Apache committer, click the Yes link and enter a <i>anonymous</i> for the username and leave the password empty</p>
<![endif]-->
</div>
<div class="modal-footer">
Do you have an Apache ID?
<a href="javascript:void(location.href='https://cms.apache.org/redirect?uri='+escape(location.href))" class="btn">Yes</a>
<a href="javascript:void(location.href='https://anonymous:@cms.apache.org/redirect?uri='+escape(location.href))" class="btn">No</a>
</div>
</div>
<script src="./../../resources/js/bootstrap-modal.js"></script>
<footer>
<p>Copyright &copy; 1999-2016 The Apache Software Foundation, Licensed under the Apache License, Version 2.0.
Apache TomEE, TomEE, Apache, the Apache feather logo, and the Apache TomEE project logo are trademarks of The Apache Software Foundation.
All other marks mentioned may be trademarks or registered trademarks of their respective owners.</p>
</footer>
</div> <!-- /container -->
<!-- Javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="./../../resources/js/bootstrap-dropdown.js"></script>
</body>
</html>