I have this JNDI custom-resource configured on my Glassfish server:
I also have a web application deployed, and at some point, I want to get the value configured for the "version" additional property of my custom-resource.
My factory class is like that:
public class TestCRFactory implements ObjectFactory {
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) {
if (obj instanceof Reference) {
Reference ref = (Reference) obj;
Enumeration<RefAddr> addrs = ref.getAll();
while (addrs.hasMoreElements()) {
RefAddr addr = addrs.nextElement();
if (addr.getType().equals("version")) {
String version = (String) addr.getContent();
System.out.println(version); // it shows me "1"
}
}
}
}
}
If I lookup the object:
Context context = new InitialContext();
Object obj = context.lookup("test/TestCR");
My code works, and I can get the "version" property in the factory class with no problem.
But now I want to get the "version" property without lookup the object and invoke the factory class. I just want to do something like that, via MBeanServer:
import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import javax.management.ObjectName;
...
boolean existsObject = false;
String name = "amx:pp=/domain/resources,type=custom-resource,name=test/TestCR";
ObjectName objName = new ObjectName(name);
try {
MBeanServer mbean = ManagementFactory.getPlatformMBeanServer();
existsObject = mbean.getObjectInstance(objName) != null; // this line works
if (existsObject) {
Object attr = mbean.getAttribute(objName, "version"); // this line doesn't work. it doesn't give me the "version" property I want.
}
} catch (Throwable e) {
existsObject = false;
}
My question is: what am I doing wrong? Should I put the property name at the end of name
variable? Or something like that?
I got it!
Just using the getAttribute
method like this:
getAttribute("amx:pp=/domain/resources/custom-resource[test/TestCR],type=property,name=version", "Value");
So my final code was:
boolean existsObject = false;
ObjectName objName = new ObjectName("amx:pp=/domain/resources,type=custom-resource,name=test/TestCR");
try {
MBeanServer mbean = ManagementFactory.getPlatformMBeanServer();
existsObject = mbean.getObjectInstance(objName) != null;
if (existsObject) {
Object attr = mbean.getAttribute("amx:pp=/domain/resources/custom-resource[test/TestCR],type=property,name=version", "Value");
// here 'attr' var is indicating '1', as I've set! (I tested with other values too)
}
} catch (Throwable e) {
existsObject = false;
}