All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.jolokia.jvmagent.spring.backend.SpringReadHandler Maven / Gradle / Ivy

There is a newer version: 2.2.8
Show newest version
package org.jolokia.jvmagent.spring.backend;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.management.*;

import org.jolokia.server.core.request.JolokiaReadRequest;
import org.jolokia.server.core.service.api.JolokiaContext;
import org.jolokia.server.core.util.RequestType;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ReflectionUtils;

/**
 * @author roland
 * @since 02.12.13
 */
public class SpringReadHandler extends SpringCommandHandler {

    protected SpringReadHandler(ApplicationContext pAppContext, JolokiaContext pContext) {
        super(pAppContext, pContext, RequestType.READ);
    }

    @Override
    public Object handleRequest(JolokiaReadRequest pJmxReq, Object pPreviousResult) throws InstanceNotFoundException, AttributeNotFoundException {
        ObjectName oName = pJmxReq.getObjectName();
        String beanName = oName.getKeyProperty("name");
        if (beanName == null) {
            throw new IllegalArgumentException("No bean name given with property 'name' when requesting " + oName);
        }
        ApplicationContext ctx = getApplicationContext();
        try {
            Object bean = ctx.getBean(beanName);
            Class clazz = bean.getClass();
            String attribute = pJmxReq.getAttributeName();

            // Try get method first
            Method getter = ReflectionUtils.findMethod(
                    clazz, "get" + attribute.substring(0, 1).toUpperCase() + attribute.substring(1));
            if (getter != null) {
                return ReflectionUtils.invokeMethod(getter,bean);
            }

            // Next: Direct field access
            Field field = ReflectionUtils.findField(clazz,attribute);
            if (field != null) {
                boolean isAccessible = field.isAccessible();
                field.setAccessible(true);
                try {
                    return ReflectionUtils.getField(field,bean);
                } finally {
                    field.setAccessible(isAccessible);
                }
            }

            throw new AttributeNotFoundException("No attribute " + attribute +
                                                 " found on bean " + beanName + "(class " + clazz + ") while processing " + oName);

        } catch (NoSuchBeanDefinitionException exp) {
            throw (InstanceNotFoundException)
                    new InstanceNotFoundException("No bean with name " + beanName + " found in application context").initCause(exp);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy