Example usage for javax.management ObjectName ObjectName

List of usage examples for javax.management ObjectName ObjectName

Introduction

In this page you can find the example usage for javax.management ObjectName ObjectName.

Prototype

public ObjectName(String name) throws MalformedObjectNameException 

Source Link

Document

Construct an object name from the given string.

Usage

From source file:azkaban.execapp.AzkabanExecutorServer.java

private void registerMbean(String name, Object mbean) {
    Class<?> mbeanClass = mbean.getClass();
    ObjectName mbeanName;/*from  www .  java2 s  . c om*/
    try {
        mbeanName = new ObjectName(mbeanClass.getName() + ":name=" + name);
        mbeanServer.registerMBean(mbean, mbeanName);
        logger.info("Bean " + mbeanClass.getCanonicalName() + " registered.");
        registeredMBeans.add(mbeanName);
    } catch (Exception e) {
        logger.error("Error registering mbean " + mbeanClass.getCanonicalName(), e);
    }

}

From source file:com.quinsoft.zeidon.utils.JoeUtils.java

public static void RegisterJmxBean(Object bean, String beanName, String jmxAppName) {
    try {/*from   w  w  w  . j  a va 2  s. c om*/
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

        if (!StringUtils.isBlank(jmxAppName))
            beanName += ",app=" + jmxAppName;

        ObjectName name = new ObjectName(beanName);

        // Make sure the bean doesn't already exist.  If it does, unregister it.
        try {
            mbs.getMBeanInfo(name); // Throws InstanceNotFoundException if not found.
            mbs.unregisterMBean(name); // Unregister a bean if it exists.
        } catch (InstanceNotFoundException e) {
            // If we get here then the mbean isn't currently registered.  This is valid
            // so we'll ignore it.
        }

        mbs.registerMBean(bean, name);
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).appendMessage("Bean Name = %s, app=%s", beanName, jmxAppName)
                .appendMessage("Bean class = %s", bean.getClass().getName());

    }

}

From source file:com.cisco.oss.foundation.monitoring.RMIMonitoringAgent.java

private void registerNotificationDetails() {
    try {//  w w  w .  ja  v  a2s. co m
        notificationDetails = new NotificationMXBean();
        String strNotifObjectName = Utility.getObjectName("NotificationMXBean", this.exposedObject);
        notificationObjectName = new ObjectName(strNotifObjectName);
        mbs.registerMBean(notificationDetails, notificationObjectName);
        isNotificationRegistered = true;
    } catch (MalformedObjectNameException e) {
        LOGGER.trace("Failed to register services" + e.getMessage());
    } catch (InstanceAlreadyExistsException e) {
        LOGGER.trace("Failed to register services" + e.getMessage());
    } catch (MBeanRegistrationException e) {
        LOGGER.trace("Failed to register services" + e.getMessage());
    } catch (NotCompliantMBeanException e) {
        LOGGER.trace("Failed to register services" + e.getMessage());
    } catch (IllegalArgumentException e) {
        LOGGER.trace("Failed to register services" + e.getMessage());
    }

}

From source file:ddf.metrics.collector.rrd4j.RrdJmxCollector.java

/**
 * Configures a scheduled threaded executor to poll the metric's MBean periodically and add a
 * sample to the RRD file with the metric's current value.
 *
 * @throws CollectorException//ww  w .jav  a  2  s . com
 */
public void updateSamples() throws CollectorException {
    LOGGER.trace("ENTERING: updateSamples");

    if (executor == null) {
        executor = new ScheduledThreadPoolExecutor(1);
    }

    final Runnable updater = new Runnable() {
        public void run() {
            Object attr = null;
            try {
                attr = localMBeanServer.getAttribute(new ObjectName(mbeanName), mbeanAttributeName);

                LOGGER.trace("Sampling attribute {} from MBean {}", mbeanAttributeName, mbeanName);

                // Cast the metric's sampled value to the appropriate data type
                double val = 0;
                if (attr instanceof Integer) {
                    val = (Integer) attr;
                } else if (attr instanceof Long) {
                    val = ((Long) attr).intValue();
                } else if (attr instanceof Float) {
                    val = ((Float) attr);
                } else if (attr instanceof Double) {
                    val = ((Double) attr);
                } else {
                    throw new IllegalArgumentException(
                            "Unsupported type " + attr + " for attribute " + mbeanAttributeName);
                }

                LOGGER.trace("MBean attribute {} has value = {}", mbeanAttributeName, val);

                // If first time this metric has been sampled, then need to create a
                // sample in the RRD file
                if (sample == null) {
                    sample = rrdDb.createSample();
                }

                try {
                    long now = System.currentTimeMillis() / MILLIS_PER_SECOND;
                    long lastUpdateTime = rrdDb.getLastUpdateTime();

                    // Add metric's sample to RRD file with current timestamp
                    if (now - rrdDb.getLastUpdateTime() >= minimumUpdateTimeDelta) {
                        updateSample(now, val);
                    } else {
                        LOGGER.debug(
                                "Skipping sample update because time between updates is less than {} seconds",
                                minimumUpdateTimeDelta);

                        sampleSkipCount++;

                        LOGGER.debug("now = {},   lastUpdateTime = {}   (sampleSkipCount = {})", now,
                                lastUpdateTime, sampleSkipCount);
                    }
                } catch (IllegalArgumentException iae) {
                    LOGGER.error("Dropping sample of datasource {}", rrdDataSourceName, iae);
                }
            } catch (MalformedObjectNameException e) {
                LOGGER.warn("Problems getting MBean attribute {}", mbeanAttributeName, e);
            } catch (AttributeNotFoundException e) {
                LOGGER.warn("Problems getting MBean attribute {}", mbeanAttributeName, e);
            } catch (InstanceNotFoundException e) {
                LOGGER.warn("Problems getting MBean attribute {}", mbeanAttributeName, e);
            } catch (MBeanException e) {
                LOGGER.warn("Problems getting MBean attribute {}", mbeanAttributeName, e);
            } catch (ReflectionException e) {
                LOGGER.warn("Problems getting MBean attribute {}", mbeanAttributeName, e);
            } catch (IOException e) {
                LOGGER.warn("Error updating RRD", e);
            }
        }
    };

    // Setup threaded scheduler to retrieve this MBean attribute's value
    // at the specified sample rate
    LOGGER.debug("Setup ScheduledThreadPoolExecutor for MBean {}", mbeanName);
    executor.scheduleWithFixedDelay(updater, 0, sampleRate, TimeUnit.SECONDS);

    LOGGER.trace("EXITING: updateSamples");
}

From source file:catalina.mbeans.MBeanFactory.java

/**
 * Create a new HttpsConnector/* ww  w.ja va  2  s. c  om*/
 *
 * @param parent MBean Name of the associated parent component
 * @param address The IP address on which to bind
 * @param port TCP port number to listen on
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createHttpsConnector(String parent, String address, int port) throws Exception {

    Object retobj = null;

    try {

        // Create a new CoyoteConnector instance
        // use reflection to avoid j-t-c compile-time circular dependencies
        Class cls = Class.forName("org.apache.coyote.tomcat4.CoyoteConnector");
        Constructor ct = cls.getConstructor(null);
        retobj = ct.newInstance(null);
        Class partypes1[] = new Class[1];
        // Set address
        String str = new String();
        partypes1[0] = str.getClass();
        Method meth1 = cls.getMethod("setAddress", partypes1);
        Object arglist1[] = new Object[1];
        arglist1[0] = address;
        meth1.invoke(retobj, arglist1);
        // Set port number
        Class partypes2[] = new Class[1];
        partypes2[0] = Integer.TYPE;
        Method meth2 = cls.getMethod("setPort", partypes2);
        Object arglist2[] = new Object[1];
        arglist2[0] = new Integer(port);
        meth2.invoke(retobj, arglist2);
        // Set scheme
        Class partypes3[] = new Class[1];
        partypes3[0] = str.getClass();
        Method meth3 = cls.getMethod("setScheme", partypes3);
        Object arglist3[] = new Object[1];
        arglist3[0] = new String("https");
        meth3.invoke(retobj, arglist3);
        // Set secure
        Class partypes4[] = new Class[1];
        partypes4[0] = Boolean.TYPE;
        Method meth4 = cls.getMethod("setSecure", partypes4);
        Object arglist4[] = new Object[1];
        arglist4[0] = new Boolean(true);
        meth4.invoke(retobj, arglist4);
        // Set factory 
        Class serverSocketFactoryCls = Class.forName("org.apache.catalina.net.ServerSocketFactory");
        Class coyoteServerSocketFactoryCls = Class
                .forName("org.apache.coyote.tomcat4.CoyoteServerSocketFactory");
        Constructor factoryConst = coyoteServerSocketFactoryCls.getConstructor(null);
        Object factoryObj = factoryConst.newInstance(null);
        Class partypes5[] = new Class[1];
        partypes5[0] = serverSocketFactoryCls;
        Method meth5 = cls.getMethod("setFactory", partypes5);
        Object arglist5[] = new Object[1];
        arglist5[0] = factoryObj;
        meth5.invoke(retobj, arglist5);
    } catch (Exception e) {
        throw new MBeanException(e);
    }

    try {
        // Add the new instance to its parent component
        ObjectName pname = new ObjectName(parent);
        Server server = ServerFactory.getServer();
        Service service = server.findService(pname.getKeyProperty("name"));
        service.addConnector((Connector) retobj);
    } catch (Exception e) {
        // FIXME
        // disply error message 
        // the user needs to use keytool to configure SSL first
        // addConnector will fail otherwise
        return null;
    }

    // Return the corresponding MBean name
    ManagedBean managed = registry.findManagedBean("CoyoteConnector");
    ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), (Connector) retobj);
    return (oname.toString());

}

From source file:com.cubeia.firebase.server.lobby.systemstate.StateLobby.java

/**
 * Add MBean info to JMX./*  w  w  w  .ja  va 2 s  . c o  m*/
 * Will be called from the constructor.
 *
 */
private void initJmx() {
    try {
        MBeanServer mbs = getMBeanServer();
        ObjectName monitorName = new ObjectName("com.cubeia.firebase.lobby:type=SysLobby");
        if (!mbs.isRegistered(monitorName)) {
            mbs.registerMBean(this, monitorName);
        }
    } catch (Exception e) {
        log.error("failed to start JMX for State Lobby", e);
    }
}

From source file:com.web.server.SARDeployer.java

/**
 * This method undeployed the SAR//from w w w  . j ava2s  .com
 * @param dir
 * @return
 */
public boolean deleteDir(File dir) {
    String fileName = dir.getName();
    System.out.println("Dirname to be deleted" + fileName);
    Sar sar = null;
    try {
        sar = (Sar) sardigester.parse(new InputSource(
                new FileInputStream(deployDirectory + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
    } catch (IOException | SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    URLClassLoader sarClassLoader = (URLClassLoader) sarsMap.get(fileName);
    if (sarClassLoader != null) {
        ClassLoaderUtil.closeClassLoader(sarClassLoader);
        CopyOnWriteArrayList mbeans = sar.getMbean();
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        System.out.println(mbs);
        ObjectName objName;
        try {
            for (int index = 0; index < mbeans.size(); index++) {
                Mbean mbean = (Mbean) mbeans.get(index);
                System.out.println(mbean.getObjectname());
                System.out.println(mbean.getCls());
                objName = new ObjectName(mbean.getObjectname());
                if (mbs.isRegistered(objName)) {
                    mbs.invoke(objName, "stopService", null, null);
                    //mbs.invoke(objName, "destroy", null, null);
                    mbs.unregisterMBean(objName);
                }
            }
            sarsMap.remove(fileName);
        } catch (MalformedObjectNameException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanRegistrationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstanceNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ReflectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MBeanException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return recursiveDelete(dir);

}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Unregister MBeans loaded by the web application class loader
 *///from  w ww.  ja v a 2  s. c  om
protected void unregisterMBeans() {
    try {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
        for (ObjectName objectName : allMBeanNames) {
            try {
                final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
                if (isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
                    warn("MBean '" + objectName + "' was loaded in web application; unregistering");
                    mBeanServer.unregisterMBean(objectName);
                }
            } catch (Exception e) { // MBeanRegistrationException / InstanceNotFoundException
                error(e);
            }
        }
    } catch (Exception e) { // MalformedObjectNameException
        error(e);
    }
}

From source file:com.cisco.oss.foundation.monitoring.RMIMonitoringAgent.java

private void registerConnections() {
    try {//from w  ww . ja v  a  2s . co  m
        String strMonConfigObjectName = Utility.getObjectName("ConnectionInfo", this.exposedObject);
        connetctionsObjectName = new ObjectName(strMonConfigObjectName);
        mbs.registerMBean(ConnectionInfo.INSTANCE, connetctionsObjectName);
    } catch (MalformedObjectNameException e) {
        LOGGER.trace("Failed to register connetctions" + e.getMessage());
    } catch (InstanceAlreadyExistsException e) {
        LOGGER.trace("Failed to register connetctions" + e.getMessage());
    } catch (MBeanRegistrationException e) {
        LOGGER.trace("Failed to register connetctions" + e.getMessage());
    } catch (NotCompliantMBeanException e) {
        LOGGER.trace("Failed to register connetctions" + e.getMessage());
    }
}

From source file:com.app.server.SARDeployer.java

/**
 * This method undeployed the SAR/*w  w w .j  a  v  a2 s.  c om*/
 * @param dir
 * @return
 */
public boolean deleteDir(File dir) {
    String fileName = dir.getName();
    //log.info("Dirname to be deleted"+fileName);
    Sar sar = null;
    fileName = fileName.substring(0, fileName.indexOf('.'));
    fileName += "sar";
    try {
        sar = (Sar) sardigester.parse(new InputSource(new FileInputStream(
                serverConfig.getDeploydirectory() + "/" + fileName + "/META-INF/" + "mbean-service.xml")));
    } catch (Exception e) {
        log.error("Could not able to parse sar " + serverConfig.getDeploydirectory() + "/" + fileName
                + "/META-INF/" + "mbean-service.xml", e);
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
    URLClassLoader sarClassLoader = (URLClassLoader) sarsMap.get(fileName);
    if (sarClassLoader != null) {
        ClassLoaderUtil.closeClassLoader(sarClassLoader);
        CopyOnWriteArrayList mbeans = sar.getMbean();
        //log.info(mbeanServer);
        ObjectName objName;
        try {
            for (int index = 0; index < mbeans.size(); index++) {
                Mbean mbean = (Mbean) mbeans.get(index);
                //log.info(mbean.getObjectname());
                //log.info(mbean.getCls());
                objName = new ObjectName(mbean.getObjectname());
                if (mbeanServer.isRegistered(objName)) {
                    if (((String) mbeanServer.getAttribute(objName, "Deployer")).equals("true")) {
                        mbeanServer.invoke(objName, "undeploy", null, null);
                    }
                    mbeanServer.invoke(objName, "stop", null, null);
                    mbeanServer.invoke(objName, "destroy", null, null);
                    //mbs.invoke(objName, "stopService", null, null);
                    //mbs.invoke(objName, "destroy", null, null);
                    mbeanServer.unregisterMBean(objName);
                }
            }
        } catch (Exception e) {
            log.error("Could not able to undeploy stop and destroy sar in " + dir.getName(), e);
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
    }
    return recursiveDelete(new File(serverConfig.getDeploydirectory() + "/" + fileName + "/"));

}