MBeans not appearing in JConsole - java

I´m developping a java Web Application in Netbeans. Now I want to monitorize my app using jconsole.
public static void main(String[] args) throws Exception {
String name="Example";
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName object = new ObjectName("org.javalobby.tnt.jmx:type=example");
mbs.registerMBean(name, object);
}
I also add the following lines to glassfish:
-Djava.rmi.server.hostname=myhost
-Dcom.sun.management.jmxremote.port=8686
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
The problem is my beans do not appear on JConsole. What I´m doing wrong?

You are passing string object as an MBean object. Follow the documentation as below.
Using this blog link to create a sample test mbean.
"An MBean is a managed Java object, similar to a JavaBeanTM, that
follows the design patterns set forth in the instrumentation level of
the JMX specification. An MBean can represent a device, an
application, or any resource that needs to be managed. MBeans expose a
management interface: a set of readable and/or writable attributes and
a set of invokable operations, along with a self-description.
A standard MBean is defined by writing a Java interface called
SomethingMBean and a Java class called Something that implements that
interface. Every method in the interface defines either an attribute
or an operation in the MBean. By default every method defines an
operation. Attributes and operations are simply methods which follow
certain design patterns. A standard MBean is composed of the MBean
interface which lists the methods for all exposed attributes and
operations, and the class which implements this interface and provides
the functionality of the instrumented resource."

Related

Porting a JavaService app (Windows Service) to run on Websphere - best parent class?

I've been asked to port an existing Java app that runs as a windows service to run on Websphere. It is implemented using JavaService.exe and a stop_method
The type signature of the parent service class is:
public abstract class ParentService {
public static void main(String args[]);
public void requestStop();
}
Note that the main method in the example above is the equivalent of the init method in a servlet (although it is static) - it is used for the same purpose.
What is the equivalent parent class for a continuously running object in the J2EE standard (or even in the Websphere custom standards?)
Assuming the big idea is mapping an init and a shutdown method to a Java interfaces in the Enterprise standards...
It turns out there are four alternatives (and three vendor specific ones):
EJB 3.1 #Startup
Startup Servlet
ServletContextListener
Resource Adapter to Perform as a Startup Class

Dynamically instantiate JMX MBeans

I have a white label/multi-tennant server providing the same services, but branded for multiple customers. I want to use JMX to monitor the status of each customer (nbr of calls, nbr of errors, etc).
I know how to use Spring JMX annotations to wire up my POJOs (per the code below). What I really want is one MBean per customer, but because the customers are dynamically loaded up at server startup time I don't know how to wire this up using annotations.
Is this possible? If not, is it possible to instantiate my MBeans at startup time ?
#Component
#ManagedResource(objectName = "TravelAPI:name=Customer")
public class CustomerStatus extends GeneralCustomerStatus {
#ManagedAttribute
String customerId;
.
.
.
}
What I really want is one MBean per customer, but because the customers are dynamically loaded up at server startup time I don't know how to wire this up using annotations.
What we do is to have the entity that is actually instantiating your dynamic objects, register them with JMX via the MBeanExporter. We inject the MBeanExporter instance into the factory entity and then call MBeanExporter.registerManagedResource(...).
For example we do something like:
...
mbeanExporter.registerManagedResource(beanInstance);
...
#Required
public void setMbeanExporter(MBeanExporter mbeanExporter) {
this.mbeanExporter = mbeanExporter;
}
We also use a NamingPolicy so that the dynamic objects can provide their own names to make them unique. See more details about that here:
Change #ManagedResource objectName dynamically
As an aside, my SimpleJMX package has some code to help with dynamic objects.

How to detect application type in Java code

Imagine we have a java package. This package can be used anywhere. However, there are some codes in this package which are context dependant. For instance, if the application which uses this package is a web app we need to perform some tasks by calling a function while performing other tasks if the application was a console application by calling the very same function.
Here is my question:
Is there any way in java that within the code we can detect if the application was run as a web app or a console?
I appreciate any help :)
As a real world example, the ways we load properties files are different for web and console applications.
For web applications we probably use this.getClass().getClassLoader().getResourceAsStream(url) and for console apps we use new FileInputStream(physical path).
It might be better to set a build property somewhere rather then trying to detect your application type, because I don't think there is a reliable way to do that.
Moreover you shouldn't try to detect application type because your view layer (either web, desktop or console) should be easily interchangeable according to modern architectural principles.
In response to your last comment.
As user384706 said DI is the correct choice here IMO.
I will give an example with spring.
In both your console and web app parts you can have:
public class WebOrConsoleServiceImpl {
private PropertyProvider propertyProvider = new NullPropertyProvider();
// and
public void setPropertyProvider(PropertyProvider impl) {
this.propertyProvider = impl;
}
// and in your service logic
public void logic() {
final Properties props = propertyProvider.loadProperties();
// do stuff
}
}
Where your loadProperties() method would be overriden for different implementations of your PropertyProvider.
And in your spring context you can have:
<bean id="consolePropertyProvider" class="com.company.ConsolePropertyProvider"/>
<bean id="myConsoleService" class="com.company.MyConsoleService">
<property name="propertyProvider" ref="consolePropertyProvider" />
</bean>
And the same pair of bean definitions for your WebService and WebPropertyProvider.
Just use dependency injection
Just place all the appropriate parameters to configure your library via setters and let the container or application configure it accordingly using DI.
So you will not need any checks which IMHO is a bad approach
The J2EE way. If your package is used in a web application then, I am assuming that you are in a J2EE container then, you can add a Reference in the naming at deploy time. You can also register an MDB that can listen to the changes to this reference and modify behavior of your code at runtime. Sweet right?
Other standard way in which you can pass the context of the caller is through a parametrized Factory or through properties.
One non-standard way - for fun is to get the stack trace and look for who the caller is or look for j2ee context etc.

avaStatic factory pattern with EJB3/JBoss

I'm fairly new to EJBs and full blown application servers like JBoss, having written and worked with special purpose standalone Java applications for most of my career, with limited use of Java EE. I'm wondering about the best way to adapt a commonly used design pattern to EJB3 and JBoss: the static factory pattern. In fact this is Item #1 in Joshua Bloch's Effective Java book (2nd edition)
I'm currently working with the following factory:
public class CredentialsProcessorFactory {
private static final Log log = LogFactory.getLog(CredentialsProcessorFactory.class);
private static Map<CredentialsType, CredentialsProcessor> PROCESSORS =
new HashMap<CredentialsType, CredentialsProcessor>();
static {
PROCESSORS.put(CredentialsType.CSV, new CSVCredentialsProcessor());
}
private CredentialsProcessorFactory() {}
public static CredentialsProcessor getProcessor(CredentialsType type) {
CredentialsProcessor p = PROCESSORS.get(type);
if(p == null)
throw new IllegalArgumentException("No CredentialsProcessor registered for type " + type.toString());
return p;
}
However, in the implementation classes of CredentialsProcessor, I require injected resources such as a PersistenceContext, so I have made the CredentialsProcessor interface a #Local interface, and each of the impl's marked with #Stateless. Now I can look them up in JNDI and use the injected resources.
But now I have a disconnect because I am not using the factory anymore. My first thought was to change the getProcessor(CredentialsType) method to do a JNDI lookup and return the SLSB instance that is required, but then I need to configure and pass the proper qualified JNDI name. Before I go down that path, I wanted to do more research on accepted practices.
How is this design pattern treated in EJB3 / Java EE?-
When you start playing with factories and "real" Java POJO code, you basically need rely on JNDI.
The dependency injection only works on the managed components of an EJB server, and that's basically Servlets and EJBs.
When you're talking generic java code that wants to refer to EJBs, they need to lookup the resources themselves via JNDI.
The best thing to do, in that case, is simply write a wrapper lookup class filled with static functions to do your JNDI lookups, rather than calling JNDI directly in each implementation. And then use that in your implementations.
That's just a generic overall rule.
Now, for your specific case, consider this.
You have:
static {
PROCESSORS.put(CredentialsType.CSV, new CSVCredentialsProcessor());
}
That's no different from:
static {
PROCESSORS.put(CredentialsType.CSV, "java:comp/env/ejb/CSVCredentialProcessorSessionBean");
}
Then, in your getProcessor() code:
Context c = new InitialContext();
return (CredentialsProcessor) c.lookup(PROCESSORS.get(type));
See, basically, the code is identical, and your factory interface is the same to the clients.
You have to "hard code" the JNDI lookup key, but you're "hard coding" the class names now anyway, so how is this different?
There's some potential portability concerns across containers, in that everyone seems to like to use different JNDI identifiers for bean names. Most of that can be tweaked in the deployment, but if not, then you can pull these keys out in to a config file, or whatever.
In Java EE 6, there are guaranteed portable names. If you're not porting containers today, then don't worry about this at all.
So, basically, it's not really a disconnect at all.
With EJB3, you generally don't need to do JNDI lookups. EJB3 supports dependency injection of EJBs and several other types of resources. If your bean attribute is annotated with #EJB, the dependency will automatically be injected by the container.
Not having to do a JNDI lookup means you can test your EJB like a POJO for unit testing purposes. You can just manually inject mock implementations of dependencies and test them without having to deploy them in a container.

How to expose a Stateless EJB method as MBean (on Jboss)?

I have a stateless EJB (3) that uses internal cache which is refreshed automatically every 24 hours. I would like to expose a MBean method to be able to force cache expiration or even cache reload on this EJB via JMX console on Jboss 4.2.
Can someone share an example on how to code this scenario? I'm totally new to JMX when it comes to creating my own beans.
Should I create an MBean that calls my EJB or is it possible to expose a specific EJB method as an Mbean interface by using annotation on EJB itself?
EJB looks like this:
#Stateless
#Local(BusinessCalendar.class)
public class BusinessCalendarBean implements BusinessCalendar {
synchronized private LocalDateKitCalculatorsFactory getCalculatorFactory() {
LocalDateKitCalculatorsFactory ldkc = (LocalDateKitCalculatorsFactory) CacheService.get(CACHE_KEY);
if (ldkc == null) {
ldkc = getCalculatorFactory();
CacheService.put(CACHE_KEY, ldkc);
}
return ldkc;
}
public function expireCache() {
// I would like to expose this as JMX managed method
}
...
}
Update:
This is surely valid for WildFly 10+, jBOSS EAP 6.x or 7.x. But I suspect the mechanisms are no longer proprietary and shall work very similarly in other app servers.
JBoss specific annotations #Service / #Management were removed when JavaEE 6 standardized Singletons. A MBean (always a singleton so that all JMX clients see the same consistent JMX data application-wide) becomes an EE6+ Singleton exposed via JMX as follows:
define an interface with a name ending in "...MXBean" (compulsory)
create a #Singleton and #Startup class that implements this interface
define #PostConstruct and #PreDestroy methods to register/unregister the MBean
the register/unregister code is like:
objectName = new javax.management.ObjectName("com.acme.example.jmx:type=" + this.getClass().getName());
platformMBeanServer = java.lang.management.ManagementFactory.getPlatformMBeanServer();
platformMBeanServer.registerMBean(this, objectName);
The getters/setters defined in your "...MXBean" interface become JMX attributes, other methods are mapped to operations as specified in JMX Specifications under "lexical design patterns"
Have you looked at the online JBoss configuration guide yet? This may be of some help:
http://www.redhat.com/docs/en-US/JBoss_Enterprise_Application_Platform/4.2.0.cp08/html/Server_Configuration_Guide/EJB3_Services-Message_Driven_Beans.html

Categories