Example usage for javax.management ObjectInstance getObjectName

List of usage examples for javax.management ObjectInstance getObjectName

Introduction

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

Prototype

public ObjectName getObjectName() 

Source Link

Document

Returns the object name part.

Usage

From source file:com.lmig.cf.metrics.opsmetrics.OpsMetrics.java

private Number getAttributeValue(MBeanServerConnection connection, ObjectInstance object, String attribute) {
    try {//from   w w  w.j  av  a  2  s  . c om
        return (Number) connection.getAttribute(object.getObjectName(), attribute);
    } catch (AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException
            | IOException e) {
        return 0;
    }
}

From source file:net.zcarioca.jmx.services.impl.MBeanObjectServiceImpl.java

/**
 * {@inheritDoc}/*w w  w  . j  a va  2 s  .c om*/
 */
@Override
public Set<MBeanDescriptor> findMBeansByDomain(final String domain) {
    return toMBeanObjectSet(getPlatformMBeanServer().queryMBeans(null, null), new Predicate() {
        @Override
        public boolean evaluate(Object object) {
            ObjectInstance objInst = (ObjectInstance) object;
            return StringUtils.equalsIgnoreCase(domain, objInst.getObjectName().getDomain());
        }
    });
}

From source file:com.lmig.cf.metrics.opsmetrics.OpsMetrics.java

private List<String> getAttributeNames(MBeanServerConnection connection, ObjectInstance objectInstance)
        throws Exception {
    MBeanInfo mbeanInfo = connection.getMBeanInfo(objectInstance.getObjectName());
    MBeanAttributeInfo[] attributes = mbeanInfo.getAttributes();
    return Arrays.asList(attributes).stream().map(attr -> attr.getName()).collect(Collectors.toList());
}

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  ww  .  j av  a  2 s .  com
 *
 * @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:gemlite.shell.commands.admin.Monitor.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@CliCommand(value = "list services", help = "list services")
public String services() {
    Set<ObjectInstance> names = jmxSrv.listMBeans();
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    if (names == null)
        return "no services";
    Object[] a = names.toArray();
    //???/*from ww  w  .  j a va2  s  . c  om*/
    Arrays.sort(a, (Comparator) new Comparator<ObjectInstance>() {
        @Override
        public int compare(ObjectInstance o1, ObjectInstance o2) {
            return (o1.getObjectName().toString()).compareTo(o2.getObjectName().toString());
        }
    });

    if (LogUtil.getCoreLog().isDebugEnabled())
        LogUtil.getCoreLog().debug("get names size:{} values:{}", names.size(), names.toString());

    //?service?
    for (int i = 0; i < a.length; i++) {
        ObjectInstance oi = (ObjectInstance) a[i];
        // service?,???
        HashMap<String, Object> service = new HashMap<String, Object>();
        service.put(oi.getObjectName().toString(), service);
        service.put("serviceName", service);
        try {
            Map<String, Object> map = jmxSrv.getAttributesValues(oi.getObjectName().toString());
            if (map.size() <= 0) {
                map.put("serviceName", oi.getObjectName().toString());
                LogUtil.getCoreLog().warn("jmxSrv.getAttributesValues is null ,ObjectName {}",
                        oi.getObjectName().toString());
                result.add(map);
            } else {
                result.add(map);
            }
        } catch (Exception e) {
            LogUtil.getCoreLog().error("jmxSrv.getAttributesValues is null ,ObjectName {},error:{}",
                    oi.getObjectName().toString(), e);
        }
    }

    LinkedHashMap<String, HashMap<String, Object>> rs = (LinkedHashMap<String, HashMap<String, Object>>) get(
            CommandMeta.LIST_SERVICES);
    if (rs == null)
        rs = new LinkedHashMap<String, HashMap<String, Object>>();
    for (Map<String, Object> map : result) {
        // ?
        HashMap<String, Object> service = rs.get(map.get("serviceName"));
        if (service == null) {
            service = new HashMap<String, Object>();
        }
        service.putAll(map);

        // ?
        rs.put((String) map.get("serviceName"), service);
    }

    // ws??
    put(CommandMeta.LIST_SERVICES, rs);
    if (!result.isEmpty())
        return result.toString();
    return "no services";
}

From source file:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doShutdown(String[] vals) throws Exception {
    StringBuilder buf = new StringBuilder("service:jmx:rmi://localhost/jndi/rmi://localhost:");
    String serviceName = vals[0];

    buf.append(vals[1]).append("/").append(serviceName);
    String serviceUrl = buf.toString();

    JMXServiceURL url = new JMXServiceURL(serviceUrl);
    JMXConnector jmxc = null;/*from  www.j  av  a2 s . c om*/
    try {
        jmxc = JMXConnectorFactory.connect(url, null);

    } catch (Exception e) {
        throw new Exception("Unable to establish JMX connection at " + serviceUrl);
    }

    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

    Set<ObjectInstance> mBeansSet = mbsc.queryMBeans(new ObjectName(serviceName + ":*"), null);
    List<IServiceController> serviceProxies = new ArrayList<IServiceController>();
    Class serviceBusInterface = Class.forName(IServiceBusManager.class.getName());
    Class serviceControllerInterface = Class.forName(IServiceController.class.getName());

    for (ObjectInstance mBeanObject : mBeansSet) {
        ObjectName mbeanName = mBeanObject.getObjectName();
        Class mbeanClass = Class.forName(mBeanObject.getClassName());
        if (serviceBusInterface.isAssignableFrom(mbeanClass)) {
            IServiceBusManager requestConnector = JMX.newMBeanProxy(mbsc, mbeanName, IServiceBusManager.class,
                    true);
            System.out.print(mbeanName + " terminating....");
            requestConnector.disconnect();
            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ie) {

                }

                if (!requestConnector.isConnected()) {
                    break;
                }
            }
            System.out.println(" Done");
        } else if (serviceControllerInterface.isAssignableFrom(mbeanClass)) {
            // save off the service proxies to make sure we disconnect
            // all connectors before shutting down the service itself
            IServiceController mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, IServiceController.class, true);
            serviceProxies.add(mbeanProxy);
        }
    }

    for (IServiceController mbeanProxy : serviceProxies) {
        try {
            mbeanProxy.shutdown();
        } catch (UndeclaredThrowableException ex) {
        }
    }

    System.out.println("Service terminated");
}

From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java

/**
 * Try to find a nonssl connector to retrieve shared resources like stylesheets, images etc. Fallback: Use request
 * url.//from   w w  w  .java 2s  .c  o m
 *
 * @param request
 * @return
 */
private String getLocalURL(final HttpServletRequest request) {

    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);
    }
    String requestURL = request.getRequestURL().toString();
    log.warn("No mbeans of type '*:type=Connector,*' configured, using request url (assuming non-ssl): "
            + requestURL);
    return requestURL;
}

From source file:com.springsource.hq.plugin.tcserver.plugin.TomcatMeasurementPlugin.java

private long getTotalGarbageCollectionTime(MBeanServerConnection connection)
        throws MetricUnreachableException, MetricNotFoundException, PluginException {

    long totalGcTimeMillis = 0;

    try {/*w w w . j  a v a  2 s. com*/

        // Use of the MXBean replaced by plain old JMX query for TCS-71
        //
        // Set<ObjectName> garbageCollectors = connection.queryNames(
        // new ObjectName("java.lang:type=GarbageCollector,*"), null);
        // for (ObjectName garbageCollectorName : garbageCollectors) {
        // GarbageCollectorMXBean garbageCollector = getGarbageCollectorMXBean(
        // connection, garbageCollectorName);
        // long collectionTime = garbageCollector.getCollectionTime();

        ObjectName gcObjName = new ObjectName("java.lang:type=GarbageCollector,*");
        Set<ObjectInstance> garbageCollectors = connection.queryMBeans(gcObjName, null);

        for (ObjectInstance instance : garbageCollectors) {
            ObjectName instanceName = instance.getObjectName();
            Long l = (Long) connection.getAttribute(instance.getObjectName(), "CollectionTime");
            long collectionTime = l.longValue();
            LOGGER.debug(instanceName + "::CollectionTime=" + collectionTime);

            if (collectionTime > -1) {
                totalGcTimeMillis += collectionTime;
            }
        }
    } catch (MalformedObjectNameException e) {
        throw new MetricInvalidException("Error querying for GarbageCollector MBeans: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new MetricUnreachableException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (AttributeNotFoundException e) {
        throw new MetricNotFoundException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (InstanceNotFoundException e) {
        throw new MetricNotFoundException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (MBeanException e) {
        throw new PluginException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (ReflectionException e) {
        throw new PluginException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    } catch (NullPointerException e) {
        throw new PluginException("Error querying for GarbageCollector MBeans:" + e.getMessage(), e);
    }

    return totalGcTimeMillis;
}

From source file:com.stumbleupon.hbaseadmin.JMXQuery.java

protected String doSubCommand(MBeanServerConnection mbsc, ObjectInstance instance, String subCommand)
        throws Exception {
    final MBeanAttributeInfo[] attributeInfo = mbsc.getMBeanInfo(instance.getObjectName()).getAttributes();

    final MBeanOperationInfo[] operationInfo = mbsc.getMBeanInfo(instance.getObjectName()).getOperations();

    Object result = null;/*from   ww w. j  a  va2s.  c om*/

    if (Character.isUpperCase(subCommand.charAt(0))) {
        if ((!(isFeatureInfo(attributeInfo, subCommand))) && (isFeatureInfo(operationInfo, subCommand))) {
            result = doBeanOperation(mbsc, instance, subCommand, operationInfo);
        } else {
            result = doAttributeOperation(mbsc, instance, subCommand, attributeInfo);
        }
    } else if ((!(isFeatureInfo(operationInfo, subCommand))) && (isFeatureInfo(attributeInfo, subCommand))) {
        result = doAttributeOperation(mbsc, instance, subCommand, attributeInfo);
    } else {
        result = doBeanOperation(mbsc, instance, subCommand, operationInfo);
    }

    if (result instanceof CompositeData) {
        result = recurseCompositeData(new StringBuffer("\n"), "", "", (CompositeData) result);
    } else if (result instanceof TabularData) {
        result = recurseTabularData(new StringBuffer("\n"), "", "", (TabularData) result);
    } else if (result instanceof String[]) {
        String[] strs = (String[]) (String[]) result;
        StringBuffer buffer = new StringBuffer("\n");

        for (int i = 0; i < strs.length; ++i) {
            buffer.append(strs[i]);
            buffer.append("\n");
        }

        result = buffer;
    }

    return result.toString();
}

From source file:com.stumbleupon.hbaseadmin.JMXQuery.java

protected void listOptions(MBeanServerConnection mbsc, ObjectInstance instance)
        throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException {
    final MBeanInfo info = mbsc.getMBeanInfo(instance.getObjectName());
    final MBeanAttributeInfo[] attributes = info.getAttributes();

    if (attributes.length > 0) {
        System.out.println("Attributes:");

        for (int i = 0; i < attributes.length; ++i) {
            System.out.println(' ' + attributes[i].getName() + ": " + attributes[i].getDescription() + " (type="
                    + attributes[i].getType() + ")");
        }//from w w  w.j av a 2 s .  c  o m
    }

    MBeanOperationInfo[] operations = info.getOperations();

    if (operations.length > 0) {
        System.out.println("Operations:");

        for (int i = 0; i < operations.length; ++i) {
            final MBeanParameterInfo[] params = operations[i].getSignature();
            final StringBuffer paramsStrBuffer = new StringBuffer();

            if (params != null) {
                for (int j = 0; j < params.length; ++j) {
                    paramsStrBuffer.append("\n   name=");
                    paramsStrBuffer.append(params[j].getName());
                    paramsStrBuffer.append(" type=");
                    paramsStrBuffer.append(params[j].getType());
                    paramsStrBuffer.append(" ");
                    paramsStrBuffer.append(params[j].getDescription());
                }
            }
            System.out.println(' ' + operations[i].getName() + ": " + operations[i].getDescription()
                    + "\n  Parameters " + params.length + ", return type=" + operations[i].getReturnType()
                    + paramsStrBuffer.toString());
        }
    }
}