Example usage for javax.management MBeanServer getAttribute

List of usage examples for javax.management MBeanServer getAttribute

Introduction

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

Prototype

public Object getAttribute(ObjectName name, String attribute)
        throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException;

Source Link

Usage

From source file:org.wso2.carbon.andes.cluster.mgt.internal.managementBeans.ClusterManagementBeans.java

/**
 * Gets the current node's ID//w w w .j a v a  2s  . co m
 *
 * @return current node's ID
 * @throws ClusterMgtException
 */
public String getMyNodeID() throws ClusterMgtException {
    String myNodeID = "";
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName objectName = new ObjectName(
                "org.wso2.andes:type=ClusterManagementInformation," + "name=ClusterManagementInformation");
        Object result = mBeanServer.getAttribute(objectName, ClusterMgtConstants.MY_NODE_ID);

        if (result != null) {
            myNodeID = (String) result;
        }
        return myNodeID;

    } catch (MalformedObjectNameException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    } catch (InstanceNotFoundException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    } catch (ReflectionException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    } catch (AttributeNotFoundException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    } catch (MBeanException e) {
        throw new ClusterMgtException("Cannot access cluster information", e);
    }
}

From source file:org.wso2.carbon.andes.cluster.mgt.internal.managementBeans.ClusterManagementBeans.java

/**
 * Gets the IP addresses and ports of the nodes in a cluster
 *
 * @return A list of addresses of the nodes in a cluster
 * @throws ClusterMgtException//from  w  w w . j a v  a2  s  . c  o  m
 */
public List<String> getAllClusterNodeAddresses() throws ClusterMgtException {
    List<String> allClusterNodeAddresses = new ArrayList<String>();
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {

        ObjectName objectName = new ObjectName(
                "org.wso2.andes:type=ClusterManagementInformation," + "name=ClusterManagementInformation");
        Object result = mBeanServer.getAttribute(objectName, ClusterMgtConstants.ALL_CLUSTER_NODE_ADDRESSES);

        if (result != null) {
            allClusterNodeAddresses = (List<String>) result;
        }
        return allClusterNodeAddresses;

    } catch (MalformedObjectNameException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    } catch (ReflectionException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    } catch (MBeanException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    } catch (InstanceNotFoundException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    } catch (AttributeNotFoundException e) {
        throw new ClusterMgtException("Cannot get cluster node addresses. Check if clustering is enabled.", e);
    }
}

From source file:org.wso2.carbon.andes.cluster.mgt.internal.managementBeans.ClusterManagementBeans.java

/**
 * Gets the coordinator node's host address and port in a cluster
 *
 * @return The coordinator node's host address and port
 * @throws ClusterMgtException/*from ww  w  .j a  v  a2s .  c o  m*/
 */
public String getCoordinatorNodeAddress() throws ClusterMgtException {
    String coordinatorNodeAddress = StringUtils.EMPTY;
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        ObjectName objectName = new ObjectName(
                "org.wso2.andes:type=ClusterManagementInformation," + "name=ClusterManagementInformation");
        Object result = mBeanServer.getAttribute(objectName, ClusterMgtConstants.COORDINATOR_NODE_ADDRESS);
        if (result != null) {
            coordinatorNodeAddress = (String) result;
        }
        return coordinatorNodeAddress;

    } catch (MalformedObjectNameException e) {
        throw new ClusterMgtException("Cannot get coordinator node address. Check if clustering is enabled.",
                e);
    } catch (ReflectionException e) {
        throw new ClusterMgtException("Cannot get coordinator node address. Check if clustering is enabled.",
                e);
    } catch (MBeanException e) {
        throw new ClusterMgtException("Cannot get coordinator node address. Check if clustering is enabled.",
                e);
    } catch (InstanceNotFoundException e) {
        throw new ClusterMgtException("Cannot get coordinator node address. Check if clustering is enabled.",
                e);
    } catch (AttributeNotFoundException e) {
        throw new ClusterMgtException("Cannot get coordinator node address. Check if clustering is enabled.",
                e);
    }
}

From source file:com.googlecode.psiprobe.beans.ResourceResolverBean.java

/**
  * Returns the Server's global naming context
  */*from ww w .  j  a va2s .  c o m*/
  * @return the global JNDI context
  */
protected javax.naming.Context getGlobalNamingContext() {

    javax.naming.Context globalContext = null;
    MBeanServer mBeanServer = getMBeanServer();
    if (mBeanServer != null) {
        try {
            ObjectName name = new ObjectName("Catalina:type=Server");
            Server server = (Server) mBeanServer.getAttribute(name, "managedResource");
            //getGlobalNamingContext() was added to Server interface in Tomcat 7.0.11
            if (server instanceof StandardServer) {
                globalContext = ((StandardServer) server).getGlobalNamingContext();
            }
        } catch (Exception e) {
            logger.error("There was an error getting globalContext through JMX server:", e);
        }
    }

    return globalContext;
}

From source file:psiprobe.beans.ResourceResolverBean.java

/**
 * Returns the Server's global naming context.
 *
 * @return the global JNDI context/*from  w w  w.ja  v a2s .  c om*/
 */
protected javax.naming.Context getGlobalNamingContext() {

    javax.naming.Context globalContext = null;
    MBeanServer mbeanServer = getMBeanServer();
    if (mbeanServer != null) {
        try {
            ObjectName name = new ObjectName("Catalina:type=Server");
            Server server = (Server) mbeanServer.getAttribute(name, "managedResource");
            // getGlobalNamingContext() was added to Server interface in Tomcat 7.0.11
            if (server instanceof StandardServer) {
                globalContext = server.getGlobalNamingContext();
            }
        } catch (Exception e) {
            logger.error("There was an error getting globalContext through JMX server:", e);
        }
    }

    return globalContext;
}

From source file:org.apache.hadoop.hdfs.server.datanode.TestDataNodeMetrics.java

@Test(timeout = 60000)
public void testTimeoutMetric() throws Exception {
    final Configuration conf = new HdfsConfiguration();
    final Path path = new Path("/test");

    final MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();

    final List<FSDataOutputStream> streams = Lists.newArrayList();
    try {/*from  ww w  .  j av  a 2  s .  c o  m*/
        final FSDataOutputStream out = cluster.getFileSystem().create(path, (short) 2);
        final DataNodeFaultInjector injector = Mockito.mock(DataNodeFaultInjector.class);
        Mockito.doThrow(new IOException("mock IOException")).when(injector).writeBlockAfterFlush();
        DataNodeFaultInjector.instance = injector;
        streams.add(out);
        out.writeBytes("old gs data\n");
        out.hflush();

        /* Test the metric. */
        final MetricsRecordBuilder dnMetrics = getMetrics(cluster.getDataNodes().get(0).getMetrics().name());
        assertCounter("DatanodeNetworkErrors", 1L, dnMetrics);

        /* Test JMX datanode network counts. */
        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        final ObjectName mxbeanName = new ObjectName("Hadoop:service=DataNode,name=DataNodeInfo");
        final Object dnc = mbs.getAttribute(mxbeanName, "DatanodeNetworkCounts");
        final String allDnc = dnc.toString();
        assertTrue("expected to see loopback address", allDnc.indexOf("127.0.0.1") >= 0);
        assertTrue("expected to see networkErrors", allDnc.indexOf("networkErrors") >= 0);
    } finally {
        IOUtils.cleanup(LOG, streams.toArray(new Closeable[0]));
        if (cluster != null) {
            cluster.shutdown();
        }
        DataNodeFaultInjector.instance = new DataNodeFaultInjector();
    }
}

From source file:org.jboss.console.plugins.monitor.ManageSnapshotServlet.java

protected void doit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter("action");
    if (action == null) {
        error("unknown action: ", req, resp);
        return;/*from  www.  jav  a2 s.  co m*/
    }
    action = action.trim();
    MBeanServer mbeanServer = MBeanServerLocator.locateJBoss();
    ObjectName monitorObjectName;
    String attribute = null;
    try {
        monitorObjectName = new ObjectName(req.getParameter("monitorObjectName"));
        attribute = (String) mbeanServer.getAttribute(monitorObjectName, "ObservedAttribute");
    } catch (Exception ex) {
        error("Malformed Monitor ObjectName: " + req.getParameter("monitorObjectName"), req, resp);
        return;
    }
    if (action.equals("Start Snapshot")) {
        Object[] nullArgs = {};
        String[] nullSig = {};
        try {
            mbeanServer.invoke(monitorObjectName, "startSnapshot", nullArgs, nullSig);
        } catch (Exception ex) {
            error("Problem invoking startSnapshot: " + ex.toString(), req, resp);
            return;
        }
        req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
        return;
    } else if (action.equals("Stop Snapshot")) {
        Object[] nullArgs = {};
        String[] nullSig = {};
        try {
            mbeanServer.invoke(monitorObjectName, "endSnapshot", nullArgs, nullSig);
        } catch (Exception ex) {
            error("Problem invoking endSnapshot: " + ex.toString(), req, resp);
            return;
        }
        req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
        return;
    } else if (action.equals("Clear Dataset")) {
        Object[] nullArgs = {};
        String[] nullSig = {};
        try {
            mbeanServer.invoke(monitorObjectName, "clearData", nullArgs, nullSig);
        } catch (Exception ex) {
            error("Problem invoking clearData: " + ex.toString(), req, resp);
            return;
        }
        req.setAttribute("error", "Dataset Cleared!");
        req.getRequestDispatcher("/manageSnapshot.jsp").forward(req, resp);
        return;
    } else if (action.equals("Remove Snapshot")) {
        try {
            log.debug("removing snapshot: " + monitorObjectName.toString());
            mbeanServer.unregisterMBean(monitorObjectName);
            req.getRequestDispatcher("/ServerInfo.jsp").forward(req, resp);
        } catch (Exception ex) {
            error("Failed to Remove Monitor: " + ex.toString(), req, resp);
        }
        return;
    } else if (action.equals("Show Dataset")) {
        ArrayList data = null;
        long start, end = 0;
        try {
            data = (ArrayList) mbeanServer.getAttribute(monitorObjectName, "Data");
            start = ((Long) mbeanServer.getAttribute(monitorObjectName, "StartTime")).longValue();
            end = ((Long) mbeanServer.getAttribute(monitorObjectName, "EndTime")).longValue();
        } catch (Exception ex) {
            error("Problem invoking getData: " + ex.toString(), req, resp);
            return;
        }
        resp.setContentType("text/html");
        PrintWriter writer = resp.getWriter();
        writer.println("<html>");
        writer.println("<body>");
        writer.println("<b>Start Time:</b> " + start + "ms<br>");
        writer.println("<b>End Time:</b> " + end + "ms<br>");
        writer.println("<b>Total Time:</b> " + (end - start) + "ms<br>");
        writer.println("<br><table border=\"0\">");
        for (int i = 0; i < data.size(); i++) {
            writer.println("<tr><td>" + data.get(i) + "</td></tr");
        }
        writer.println("</table></body></html>");
        return;
    } else if (action.equals("Graph Dataset")) {
        ArrayList data = null;
        long start, end = 0;
        try {
            data = (ArrayList) mbeanServer.getAttribute(monitorObjectName, "Data");
            start = ((Long) mbeanServer.getAttribute(monitorObjectName, "StartTime")).longValue();
            end = ((Long) mbeanServer.getAttribute(monitorObjectName, "EndTime")).longValue();
        } catch (Exception ex) {
            error("Problem invoking getData: " + ex.toString(), req, resp);
            return;
        }
        XYSeries set = new XYSeries(attribute, false, false);
        for (int i = 0; i < data.size(); i++) {
            set.add(new Integer(i), (Number) data.get(i));
        }
        DefaultTableXYDataset dataset = new DefaultTableXYDataset(false);
        dataset.addSeries(set);
        JFreeChart chart = ChartFactory.createXYLineChart("JMX Attribute: " + attribute, "count", attribute,
                dataset, PlotOrientation.VERTICAL, true, true, false);
        resp.setContentType("image/png");
        OutputStream out = resp.getOutputStream();
        ChartUtilities.writeChartAsPNG(out, chart, 400, 300);
        out.close();
        return;
    }
    error("Unknown Action", req, resp);
    return;
}

From source file:org.taverna.server.master.interaction.InteractionFeedSupport.java

@PostConstruct
void determinePorts() {
    try {//from  w w  w .ja v a 2 s . c om
        MBeanServer mbs = getPlatformMBeanServer();
        for (ObjectName obj : mbs.queryNames(new ObjectName("*:type=Connector,*"),
                match(attr("protocol"), value("HTTP/1.1")))) {
            String scheme = mbs.getAttribute(obj, "scheme").toString();
            String port = obj.getKeyProperty("port");
            endPoints.put(scheme, new URL(scheme + "://localhost:" + port));
        }
        getLog(getClass()).info("installed feed port publication mapping for " + endPoints.keySet());
    } catch (Exception e) {
        getLog(getClass()).error("failure in determining local port mapping", e);
    }
}

From source file:de.thorstenberger.examServer.pdf.PDFExporter.java

/**
 * use jmx, query catalina mbean to find non ssl connectors (-Dcom.sun.management.jmxremote) FIXME tomcat specific
 * code/*  w  w  w .j  av a2 s  . c  o m*/
 *
 * @param request
 * @return
 */
private String getServerUrl() {

    final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    try {
        for (final Object mbean : beanServer.queryMBeans(new ObjectName("*:type=Connector,*"), null)) {
            final ObjectInstance oi = (ObjectInstance) mbean;
            final Boolean isSecure = (Boolean) beanServer.getAttribute(oi.getObjectName(), "secure");
            final String protocol = (String) beanServer.getAttribute(oi.getObjectName(), "protocol");
            final int port = (Integer) beanServer.getAttribute(oi.getObjectName(), "port");
            if (!isSecure && protocol.startsWith("HTTP")) {
                log.debug(String.format("Using unsecured tomcat connector at port %d", port));
                return "http://localhost:" + port;
            }
        }
    } catch (final MalformedObjectNameException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final NullPointerException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final AttributeNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final InstanceNotFoundException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final MBeanException e) {
        log.warn("Could not access JMX mbeans.", e);
    } catch (final ReflectionException e) {
        log.warn("Could not access JMX mbeans.", e);
    }
    log.warn(
            "No mbeans of type '*:type=Connector,*' configured, using default url (assuming non-ssl http connector on port 8080).");
    return "http://localhost:8080";
}

From source file:com.mtgi.analytics.aop.config.v11.XmlPersisterConfigurationTest.java

@Test
public void testXmlPersisterConfiguration() throws Exception {
    assertNotNull("custom tracking manager configured", xmlTracking);
    assertEquals("application name set", "testApp", xmlTracking.getApplication());
    assertEquals("correct persister type provided", XmlBehaviorEventPersisterImpl.class,
            xmlTracking.getPersister().getClass());

    XmlBehaviorEventPersisterImpl persister = (XmlBehaviorEventPersisterImpl) xmlTracking.getPersister();
    assertFalse("default setting overridden", persister.isBinary());
    assertFalse("default setting overridden", persister.isCompress());

    File location = new File(persister.getFile());
    assertTrue("custom file name [" + persister.getFile() + "]", location.getName().startsWith("xml-tracking"));
    assertEquals("custom XML attributes can be post-processed by property resolver",
            new File(System.getProperty("java.io.tmpdir")).getCanonicalPath(),
            location.getParentFile().getCanonicalPath());

    TaskExecutor executor = xmlTracking.getExecutor();
    assertSame("application executor is used", testExecutor, executor);

    List<String> triggers = Arrays.asList(testScheduler.getTriggerNames("beet"));
    assertEquals("flush and rotate jobs scheduled in application scheduler", 2, triggers.size());
    assertTrue("flush job scheduled", triggers.contains("xmlTracking_flush_trigger"));
    assertTrue("rotate job scheduled",
            triggers.contains("org.springframework.scheduling.quartz.CronTriggerBean_rotate_trigger"));

    SchedulerFactory factory = new StdSchedulerFactory();
    assertEquals("private scheduler was not created", 1, factory.getAllSchedulers().size());
    assertSame(testScheduler, factory.getAllSchedulers().iterator().next());

    //verify that MBeans have been registered
    MBeanServer server = JmxUtils.locateMBeanServer();
    assertNotNull("manager mbean found", server.getMBeanInfo(
            new ObjectName("testApp:package=com.mtgi.analytics,group=xmlTracking,name=BeetManager")));
    ObjectName logName = new ObjectName("testApp:package=com.mtgi.analytics,group=xmlTracking,name=BeetLog");
    assertNotNull("log mbean found", server.getMBeanInfo(logName));

    assertEquals(persister.getFileSize(), server.getAttribute(logName, "FileSize"));
}