Questions on JMX Example - java

I have written sample JMX MBean "PoolMBean" based on my uderstanding of MBeans. I have written this to manage and monitor the connection pool. My question here is, is this the way Mbeans are written? Are there any issues in this Mbean code not related to connection pool?
1) What kind of objects can an Mbean method return?
package pool;
import java.util.Date;
public class Connection {
public Date createdAt;
protected int usedCount;
protected boolean isAvailable = true;
public Connection newConnection(){
Connection con= null;
/**
* Code for creating Connection
*/
return con;
}
public void writeDate(){
/**
* Code to write data in the stream
*/
usedCount++;
}
}
package pool;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.management.MBeanServer;
import javax.management.ObjectName;
public class ConnectionPool {
public static int maxPoolSize = 20;
public int currentPoolSize = 10;
public LinkedList<Connection> totalPool = new LinkedList<Connection>();
public LinkedList<Connection> availablePool = new LinkedList<Connection>();
public static ConnectionPool cp = new ConnectionPool();
private ConnectionPool(){
}
public synchronized Connection getConnection(){
Connection con = null;
/**
*
*/
availablePool.remove(con);
con.isAvailable = false;
return con;
}
public synchronized void returnConnection(Connection con){
/**
*
*/
availablePool.addFirst(con);
con.isAvailable = true;
}
public static void main(String a[]){
try{
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
Pool mbean = new Pool();
ObjectName name = new ObjectName("test.conMbean:key1=Pool");
server.registerMBean(mbean, name);
System.out.println("Let me see out put");
System.in.read();
}catch (Exception e) {
e.printStackTrace();
}
}
}
package pool;
public interface PoolMBean {
public int getCurrentPoolSize();
public int getMaxPoolSize();
public void setMaxPoolSize(int maxSize);
}
package pool;
public class Pool implements PoolMBean {
#Override
public int getCurrentPoolSize() {
return ConnectionPool.cp.currentPoolSize;
}
#Override
public int getMaxPoolSize() {
return ConnectionPool.maxPoolSize;
}
#Override
public void setMaxPoolSize(int maxSize) {
ConnectionPool.maxPoolSize = maxSize;
}
}
Added this based on "yazan jber" answer provided below.
1) What kind of objects can a Mbean method return? For example if the PoolMBean hasgetStatistics() which returns totalPool LinkedList object. In this case in JConsole the value is displaying Unavailable, but when I tried with HashMap with String objects it worked? So the JConsole can't read everything, What it can read is my question here?
I have gone through the Oracle MXBean annotation API doc, the description here is bit complicated. What I got from this link is there are OpenType,ArrayType, CompositeType, SimpleType and TabularType these deals with only
java.lang.Void,
java.lang.Boolean,
java.lang.Character,
java.lang.Byte,
java.lang.Short,
java.lang.Integer,
java.lang.Long,
java.lang.Float,
java.lang.Double,
java.lang.String,
java.math.BigDecimal,
java.math.BigInteger,
java.util.Date,
javax.management.ObjectName,
CompositeData.class.getName(),
TabularData.class.getName()
these objects. MBean should return any one of this OpenType.
If we want to return any other type that new type should implement CompositeData interface, I didn't get much how this implementation will help Jconsole to read open objects, it is another complicated question?
To Track individual components in my application we should have our own MBeans? If my understanding is right I can use simple java class for this purpose, the extra benefit I'm getting here is the JConsole UI, Isn't it?

Your CompositeData will have a method to return its CompositeType. The type defines the attribute names (keys) of your CompositeData. JConsole, and other JMX clients, may use these keys to access data from the CompositeData.

It is perhaps too late to answer this question - however I wanted to take a shot at this given that I am currently studying JMX.
Questions answered :
Yes, the posted code looks to me to be the correct way to write MBeans within an application.
It is recommended to have custom defined MBeans to manage the resources exposed by an application. What resources warrant management is usually a design-time decision. However, from what I understand; we would want to manage resources that would have impact on the performance and stability of the system and hence would want to administer. A good example would be the Apache Solr related classes which implement the SoltInfoMBean management interface, so that these objects can be managed from the Solr Administration console.
While you can have your own custom implementation to track individual components of the system, the advantage of using MBeans to perform the tracking is not limited to jConsole** UI support alone. With the use of standard JMX interfaces, you provide facilities like Out-of-the-box management capabilities with any management applications that confirms to the JMX spec. Also it would support management over various communication protocols such as RMI, SNMP etc without the management console and the managed applications worry about the nitty-gritties of underlying protocol. This page provides a good set of reasons to use JMX interfaces to add monitoring capabilities to your application.
Hope this helps.

I didn't run the code but it looks fine, you can return any serializable object if the JMX client is Java and has access to the same serializable class, see this link

Related

Jersey + Grizzly Http Container + shared ServiceLocator + custom Worker Thread Pool

I need to change the thread pool of the underlying Grizzly transport layer.
According to the docs of GrizzlyHttpServerFactory:
Should you need to fine tune the underlying Grizzly transport layer, you can obtain direct access to the corresponding Grizzly structures with server.getListener("grizzly").getTransport().
and
To make certain options take effect, you need to work with an inactive HttpServer instance (that is the one that has not been started yet). To obtain such an instance, use one of the below factory methods with start parameter set to false
Since I like to put my self in the worse situations :-) the method I need shuld be:
HttpServer server= GrizzlyHttpServerFactory
.createHttpServer(getURI(), this.config, serviceLocator, false);
but the only method available (nearest to my case) is:
public static HttpServer createHttpServer(final URI uri,
final GrizzlyHttpContainer handler, final boolean secure,
final SSLEngineConfigurator sslEngineConfigurator, final boolean start) {
//....
}
If I understand the GrizzlyHttpContainer is private so I should use:
GrizzlyHttpContainer httpContainer =
new GrizzlyHttpContainerProvider().createContainer(GrizzlyHttpContainer.class, config);
But, since I'm sharing a ServiceLocator between resources and internal classes (a couple of ActiveMQ subscribers). I wonder if it were possible to achieve something like this:
GrizzlyHttpContainer httpContainer =
new GrizzlyHttpContainerProvider()
.createContainer(GrizzlyHttpContainer.class, configuration, serviceLocator);
Ideally what i need is a method like this:
public class GrizzlyHttpContainerProvider implements ContainerProvider {
#Override
public <T> T createContainer(Class<T> type, Application application, Object parentContext) throws ProcessingException {
if (HttpHandler.class == type || GrizzlyHttpContainer.class == type) {
return type.cast(new GrizzlyHttpContainer(application, parentContext));
}
return null;
}
}
Any suggestion about how to achieve this?
I'd would prefer a cleaner solution then creating the server with one of the provided methods that (for my case) auto start the server. Then stop it (waiting for termination somehow) and then finally:
this.server.getListener("grizzly").getTransport().setWorkerThreadPool(....);
and restarting it.
Best Regards,
Luca
Edit
This is cheating :-) ... this is the "dark way" (don't do it at home):
private GrizzlyHttpContainer getGrizzlyHttpContainer(final Application application,
final Object context) {
try {
Class<?> cls = Class.forName(
"org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer");
Constructor<?> cons = cls.getDeclaredConstructor(Application.class, Object.class);
//System.out.println("Constructor Name--->>>"+cons.getName());
cons.setAccessible(true);
return (GrizzlyHttpContainer)cons.newInstance(application, context);
} catch (Exception err) {
return null;
}
}

Creating MBean in Java

I am trying to make a class implement an MBean Interface so I can interrogate the properties at runtime. The class I am trying to interrogate is as follows
public class ProfileCache implements ProfileCacheInterfaceMBean{
private Logger logger = Logger.getLogger(ProfileCache.class);
private ConcurrentMap<String, Profile> cache;
public ProfileCache(ConcurrentMap<String, Profile> cache){
this.cache = cache;
}
/**
* Update the cache entry for a given user id
* #param userid the user id to update for
* #param profile the new profile to store
* #return true if the cache update
*/
public boolean updateCache(String userid, Profile profile) {
if (cache == null || cache.size() == 0) {
throw new RuntimeException("Unable to update the cache");
}
if (cache.containsKey(userid)) {
if (profile != null) {
cache.put(userid, profile);
logger.info("Updated the cache for user: "
+ userid + " profile: " + profile);
return true;
}
}
return false;
}
#Override
public ConcurrentMap<String, Profile> getCache() {
if(cache == null){
cache = new ConcurrentHashMap<String, Profile>();
}
return cache;
}
}
The interface looks like this
import com.vimba.profile.Profile;
public interface ProfileCacheInterfaceMBean {
ConcurrentMap<String, Profile> getCache();
}
And i start the MBean like this
cacheImpl = new ProfileCache(factory.createCacheFromDB());
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName profileCache = new ObjectName("org.javalobby.tnt.jmx:type=ProfileCacheInterfaceMBean");
mbs.registerMBean(cacheImpl, profileCache);
However i keep getting the below exception and I am not sure what I need to change
javax.management.NotCompliantMBeanException: MBean class com.vimba.cache.ProfileCache does not implement DynamicMBean, and neither follows the Standard MBean conventions (javax.management.NotCompliantMBeanException: Class com.vimba.cache.ProfileCache is not a JMX compliant Standard MBean) nor the MXBean conventions (javax.management.NotCompliantMBeanException: com.vimba.cache.ProfileCache: Class com.vimba.cache.ProfileCache is not a JMX compliant MXBean)
I think potentially it's because it returns a Map?
Having just encountered this exception and looked at the current answers as well as https://blogs.oracle.com/jmxetc/entry/javax_management_standardmbean_when_and I thought it might help to emphasize and clarify the following already elucidated to:
The NotCompliantMBeanException is caused, among other things, by failing to follow this convention 'ConcreteClassName' implements 'ConcreteClassNameMBean'
I resolved this by updating the original name of my mbean interface from 'OrignalNameMBean' to 'OriginalNameMXBean' allowing the mbean to be registered without following the convention
Another solution would be to follow the convention.
I had the same issue ("does not implement DynamicMBean, and neither follows the Standard MBean conventions") and this article helped me to resolve the problem (see Using StandardMBean section: https://blogs.oracle.com/jmxetc/entry/javax_management_standardmbean_when_and).
I have to explicitly construct a
StandardMBean mbean = new StandardMBean(mBeanImpl, MBeanInterface.class);
then register the mbean:
mbServer.registerMBean(mbean, mBeanName);
It works.
When I register the mBeanImpl with the mbServer, I got the above exception.
The implementing mbean class can declare as many methods as it likes that are not defined in mbeans interface... There is no requirement that the implementing class can/must only implement the interface methods.
In many of the cases this problem is caused because the mbean interface and implementation class are not in the same package!
You can change interface name from SomethingMBean to SomethingMXBean,such as HelloMBean to HelloMXBean,from jdk's source code i saw this:
public static boolean isMXBeanInterface(Class<?> interfaceClass) {
if (!interfaceClass.isInterface())
return false;
if (!Modifier.isPublic(interfaceClass.getModifiers()) &&
!Introspector.ALLOW_NONPUBLIC_MBEAN) {
return false;
}
MXBean a = interfaceClass.getAnnotation(MXBean.class);
if (a != null)
return a.value();
return interfaceClass.getName().endsWith("MXBean");
}
if not endsWith "MXBean",it will return false,then cause throw IllegalArgumentException
jdk version:1.8.0_25
class is "JMX",line 376
Just change interface suffix from 'MBean' to 'MXBean'.
This works for me.
Just change your implementation class name from ProfileCache to ProfileCacheInterface. It should work now. Moreover your implementation class can have any number of its own methods and those methods needs not to be mentioned in the MBean interface.
JMX's standard mbean naming convention is like this
public interface SomeBeanNameMBean{
...
}
public class SomeBeanName implements SomeBeanNameMBean{
...
//implements all the methods of SomeBeanNameMBean
...
//implement other class's own methods if needed
}
I faced the same problem like 'Exception in thread "main" javax.management.NotCompliantMBeanException', in my case I kept MBean interface and implementation classes in differnet package. To resolve the issue, I moved both MBean interface and the implementation class to same package.
In the all the examples I've seen for MBean implementations, I've never seen a class define a method that was not defined in the interface. E.g., ProfileCache has method updateCache, but ProfileCacheInterfaceMBean does not. Try removing the updateCache method from ProfileCache and see if it will work.

Using a java XmlType annotated object on the client side to access a database on the server side with a web service

I am developing a java web service as well as a java client for the service and I am wondering if my design is even possible within the constraints of a SOAP-based, document style web service. On the server side I have a database which I am using a utility class to connect to and a couple other database "handler" classes that manipulate the database. My web service has WebMethods that return the handler classes. Each of the handler classes is annotated with the #XmlType annotation so that they can be bound to XML types. My question is if my client calls one of the webmethods and gets one of the database handler can I in turn manipulate the database on the server side through the methods of the handler (which are not annotated #WebMethod). Is something like this possible with SOAP-based web services?
I have example code below.
Here is the functionality of my utility class.
public class DBUtil {
public static getConnection() {
return DriverManager.getConnection(url, username, password);
}
}
Here is an example of one of my database handlers.
#XmlType
public class Handler1 {
public LinkedList<String> listDatabases() {
Connection con = DBUtil.getConnection();
LinkedList<String> list = new LinkedList<String>();
//use con to query database and fill list with know database names
return list;
}
public LinkedList<UserData> listUser(String database) {
//UserData is a user defined type that store information about user names
//and their privileges
Connection con = DBUtil.getConnection();
//query database and fill a LinkedList list with one UserData object
//for each database user
return list;
}
}
My other handler classes contain similar methods for querying and modifying tables.
Below is my web service.
#WebService()
#SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
public class WSDatabaseImp implements WSDatabase {
//WSDatabase is my SEI
public WSDatabaseImp() {}
#WebMethod
public Handler1 getHandler1() {
return new Handler1();
}
//more get HandlerX methods
}
What I want to do is use Handler1 and such in my client to manipulate the database. The code below demonstrates what I want to do and assumes that I have run run wsimport that generate the artifacts.
public class Client {
public static void main(String[] args) {
WSDatabaseImpService service = new WSDatabaseImpService();
WSDatabaseImp port = service.getWSDatabaseImpPort();
Handler1 h = service.getHandler1();
LinkedList<String> list = h.listDatabases();
for(String s: list)
System.out.println(s);
}
}
Is this design possible? Thank you so much for your help.

Java Static Factory conversion

On my Client/Server Desktop application. I have this problem of how I should properly code my JDBC class with my Models to ensure all persistence request can support concurrency. i.e., multiple models want to request update to its persistence counterpart simultaneously [without atmost delay].
The scenario goes like this. Following the classes located in the server application.
Persitence Package:
abstract class AbstractService {
// other fields
private final String tName, tId;
private final String sqlStatement;
public AbstractService(final String tName, final String tId) {
this.tName = tName;
this.tId = tId;
this.sqlStatement = ""; // SELECT statement
}
// java.sql.Connection() createConnection()
// methods
}
public class T1Service extends AbstractService {
private final String sqlDMLStatements;
public T1Service() {
super("t1", "t1Id");
this.sqlDMLStatements = ""; // other DML statements
}
// methods having return types of List<E>, Object, Boolean, etc.
// i.e., public List<E> listAll()
}
Communication class [Client class]
import java.net.*;
import java.io.*;
public class Client extends Observable{
private Socket socket;
private ObjectInputStream input;
private ObjectOutputStream output;
private Object message;
// Constructor
// Getters/Setters
// Other methods like open or close input/output
private class ReceiverRunnable implements Runnable
#Override
public void run() {
while(running) { // if socket is still open and I/O stream are open/initialized
try { message = input.readObject(); }
catch(Exception e) {}
finally { setChanged(); notifyObservers(); }
}
}
}
}
The Main Class [Server class]
import java.net.*;
public class Server {
private List<Client> clientList; // holds all active connections with the server
private T1Service t1Service
private class ConnectionRunnable implements Runnable {
#Override public void run() {
while(running) { // serverSocket is open
Client client = new Client(ServerSocket.accept(), /* other parameters */);
client.addObserver(new ClientObserver(client));
clientList.add(client);
}
}
}
private class ClientObserver implements Observer {
private Client client;
// Constructor
public void update(Observable o, Object arg) {
// Check the contents of 'message' to determine what to reply
// i.e., message.equals("Broadcast") {
// synchronized(clientList) {
// for(Client element : clientList) {
// element.getOutput().writeObject(replyObject);
// element.getOutput()..flush();
// }
// }
// i.e., message.equals("T1") {
// synchronized(t1Service) {
// client.getOutput().writeObject(t1.findAll());
// client.getOutput().flush();
// }
}
}
}
Since this is a Client/Server applcation, multiple request from the client are simultaneously feed to the server. The server process the request sending the appropriate reply to the approriate client. Note: All of the objects sent between Client & Server an instance of java.io.Serializable.
Having this kind of scenario and looking into the block of Server.ClientServer.update() we may have a performance issue or I should say a delay in processing the N client(s) request due to Intrinsic Locks. But since I have to the rules concurrency and synchronization to ensure that Server.T1Service won't get confused to the queue of N clients request to it. Here's are the questions:
According to the Item 1 of Effective Java - Second Edition regarding Static Factory, would this let me create a new class reference to the methods inside the classes of Persistence package?
Would each Client element inside List<Client> would form a concurrency issue having N client update their message field simultaneously triggering the ClientObsver.update() wherein the reference object(s) of this Observer is only a single instance in the parent class. I was avoiding creating multiple instance of T1Service due to memory concerns.
If we are going to go by the contents of Effective Java - Second Edition, how can I convert my persitence class in a way they can be read easily, easily instantiated, and support concurreny?
you may also want to review Actors, for example ones in Akka
basic idea of actors is avoiding of synchronization at all, using sending events. Akka will guarantee that one actor will never be invoked by two threads in parallel. So you may define actor, which does something with the global variables, and then simply send a message to it.
works like a charm usually :)
Is my theory of [Item 1] Static Factory correct?
Yes, you can use a static factory instead of constructors. Typically this is when you the construction logic is complex and shared between various subtypes to warrant a factory pattern. Additionally the factory may provide means for dependency injection outside of a DI framework.
Would it then solve the concurrency issue of the converted static factory global objects?
If you need to synchronize construction, then a static factory works well, just add synchronized to the method declaration on your factory methods. If you need to synchronize methods on the objects themselves then this will not help.
Is it advisable for me to convert to static factory if where dealing with concurrent access to a global object and where wanted real-time access to the methods of each global object?
As I answered above, it depends on what you are trying to achieve. For constructor synchronization use a factory.

What are Dynamic Proxy classes and why would I use one?

What is a use case for using a dynamic proxy?
How do they relate to bytecode generation and reflection?
Any recommended reading?
I highly recommend this resource.
First of all, you must understand what the proxy pattern use case. Remember that the main intent of a proxy is to control access to
the target object, rather than to enhance the functionality of the
target object. The access control includes synchronization, authentication, remote access (RPC), lazy instantiation (Hibernate, Mybatis), AOP (transaction).
In contrast with static proxy, the dynamic proxy generates bytecode which requires Java reflection at runtime. With the dynamic approach you don't need to create the proxy class, which can lead to more convenience.
A dynamic proxy class is a class that implements a list of
interfaces specified at runtime such that a method invocation through
one of the interfaces on an instance of the class will be encoded and
dispatched to another object through a uniform interface. It can be
used to create a type-safe proxy object for a list of interfaces
without requiring pre-generation of the proxy class. Dynamic proxy
classes are useful to an application or library that needs to provide
type-safe reflective dispatch of invocations on objects that present
interface APIs.
Dynamic Proxy Classes
I just came up with an interesting use for a dynamic proxy.
We were having some trouble a non-critical service that is coupled with another dependant service and wanted to explore ways of being fault-tolerant when that dependant service becomes unavailable.
So I wrote a LoadSheddingProxy that takes two delegates - one is the remote impl for the 'normal' service (after the JNDI lookup). The other object is a 'dummy' load-shedding impl. There is simple logic surrounding each method invoke that catches timeouts and diverts to the dummy for a certain length of time before retrying. Here's how I use it:
// This is part of your ServiceLocator class
public static MyServiceInterface getMyService() throws Exception
{
MyServiceInterface loadShedder = new MyServiceInterface() {
public Thingy[] getThingys(Stuff[] whatever) throws Exception {
return new Thingy[0];
}
//... etc - basically a dummy version of your service goes here
}
Context ctx = JndiUtil.getJNDIContext(MY_CLUSTER);
try {
MyServiceInterface impl = ((MyServiceHome) PortableRemoteObject.narrow(
ctx.lookup(MyServiceHome.JNDI_NAME),
MyServiceHome.class)).create();
// Here's where the proxy comes in
return (MyService) Proxy.newProxyInstance(
MyServiceHome.class.getClassLoader(),
new Class[] { MyServiceInterface.class },
new LoadSheddingProxy(MyServiceHome.JNDI_NAME, impl, loadShedder, 60000)); // 10 minute retry
} catch (RemoteException e) { // If we can't even look up the service we can fail by shedding load too
logger.warn("Shedding load");
return loadShedder;
} finally {
if (ctx != null) {
ctx.close();
}
}
}
And here's the proxy:
public class LoadSheddingProxy implements InvocationHandler {
static final Logger logger = ApplicationLogger.getLogger(LoadSheddingProxy.class);
Object primaryImpl, loadDumpingImpl;
long retry;
String serviceName;
// map is static because we may have many instances of a proxy around repeatedly looked-up remote objects
static final Map<String, Long> servicesLastTimedOut = new HashMap<String, Long>();
public LoadSheddingProxy(String serviceName, Object primaryImpl, Object loadDumpingImpl, long retry)
{
this.serviceName = serviceName;
this.primaryImpl = primaryImpl;
this.loadDumpingImpl = loadDumpingImpl;
this.retry = retry;
}
public Object invoke(Object obj, Method m, Object[] args) throws Throwable
{
try
{
if (!servicesLastTimedOut.containsKey(serviceName) || timeToRetry()) {
Object ret = m.invoke(primaryImpl, args);
servicesLastTimedOut.remove(serviceName);
return ret;
}
return m.invoke(loadDumpingImpl, args);
}
catch (InvocationTargetException e)
{
Throwable targetException = e.getTargetException();
// DETECT TIMEOUT HERE SOMEHOW - not sure this is the way to do it???
if (targetException instanceof RemoteException) {
servicesLastTimedOut.put(serviceName, Long.valueOf(System.currentTimeMillis()));
}
throw targetException;
}
}
private boolean timeToRetry() {
long lastFailedAt = servicesLastTimedOut.get(serviceName).longValue();
return (System.currentTimeMillis() - lastFailedAt) > retry;
}
}
The class java.lang.reflect.Proxy allows you to implement interfaces dynamically by handling method calls in an InvocationHandler. It is considered part of Java's reflection facility, but has nothing to do with bytecode generation.
Sun has a tutorial about the use of the Proxy class. Google helps, too.
One use case is hibernate - it gives you objects implementing your model classes interface but under getters and setters there resides db related code. I.e. you use them as if they are just simple POJO, but actually there is much going on under cover.
For example - you just call a getter of lazily loaded property, but really the property (probably whole big object structure) gets fetched from the database.
You should check cglib library for more info.

Categories