Example usage for javax.management ObjectName toString

List of usage examples for javax.management ObjectName toString

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a string representation of the object name.

Usage

From source file:catalina.mbeans.GroupMBean.java

/**
 * Return the MBean Names of all users that are members of this group.
 *//*from w  w  w.j a  v  a2s  .  c om*/
public String[] getUsers() {

    Group group = (Group) this.resource;
    ArrayList results = new ArrayList();
    Iterator users = group.getUsers();
    while (users.hasNext()) {
        User user = null;
        try {
            user = (User) users.next();
            ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), user);
            results.add(oname.toString());
        } catch (MalformedObjectNameException e) {
            throw new IllegalArgumentException("Cannot create object name for user " + user);
        }
    }
    return ((String[]) results.toArray(new String[results.size()]));

}

From source file:org.apache.catalina.manager.JMXProxyServlet.java

public void listBeans(PrintWriter writer, String qry) {

    Set names = null;/* w ww.  j a  v  a 2 s. c  o m*/
    try {
        names = mBeanServer.queryNames(new ObjectName(qry), null);
        writer.println("OK - Number of results: " + names.size());
        writer.println();
    } catch (Exception e) {
        writer.println("Error - " + e.toString());
        return;
    }

    Iterator it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = (ObjectName) it.next();
        writer.println("Name: " + oname.toString());

        try {
            MBeanInfo minfo = mBeanServer.getMBeanInfo(oname);
            // can't be null - I thinl
            String code = minfo.getClassName();
            if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                code = (String) mBeanServer.getAttribute(oname, "modelerType");
            }
            writer.println("modelerType: " + code);

            MBeanAttributeInfo attrs[] = minfo.getAttributes();
            Object value = null;

            for (int i = 0; i < attrs.length; i++) {
                if (!attrs[i].isReadable())
                    continue;
                if (!isSupported(attrs[i].getType()))
                    continue;
                String attName = attrs[i].getName();
                if (attName.indexOf("=") >= 0 || attName.indexOf(":") >= 0 || attName.indexOf(" ") >= 0) {
                    continue;
                }

                try {
                    value = mBeanServer.getAttribute(oname, attName);
                } catch (Throwable t) {
                    log("Error getting attribute " + oname + " " + attName + " " + t.toString());
                    continue;
                }
                if (value == null)
                    continue;
                if ("modelerType".equals(attName))
                    continue;
                String valueString = value.toString();
                writer.println(attName + ": " + escape(valueString));
            }
        } catch (Exception e) {
            // Ignore
        }
        writer.println();
    }

}

From source file:catalina.mbeans.UserMBean.java

/**
 * Return the MBean Names of all roles assigned to this user.
 *///  www.  j  av a  2 s  .  c  o  m
public String[] getRoles() {

    User user = (User) this.resource;
    ArrayList results = new ArrayList();
    Iterator roles = user.getRoles();
    while (roles.hasNext()) {
        Role role = null;
        try {
            role = (Role) roles.next();
            ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), role);
            results.add(oname.toString());
        } catch (MalformedObjectNameException e) {
            throw new IllegalArgumentException("Cannot create object name for role " + role);
        }
    }
    return ((String[]) results.toArray(new String[results.size()]));

}

From source file:catalina.mbeans.UserMBean.java

/**
 * Return the MBean Names of all groups this user is a member of.
 *//* w w w . j a  va 2s.  c o m*/
public String[] getGroups() {

    User user = (User) this.resource;
    ArrayList results = new ArrayList();
    Iterator groups = user.getGroups();
    while (groups.hasNext()) {
        Group group = null;
        try {
            group = (Group) groups.next();
            ObjectName oname = MBeanUtils.createObjectName(managed.getDomain(), group);
            results.add(oname.toString());
        } catch (MalformedObjectNameException e) {
            throw new IllegalArgumentException("Cannot create object name for group " + group);
        }
    }
    return ((String[]) results.toArray(new String[results.size()]));

}

From source file:com.mtgi.jmx.export.naming.AppendNamingStrategyTest.java

@Test
public void testNamingStrategy() throws MalformedObjectNameException {

    MetadataNamingStrategy delegate = new MetadataNamingStrategy();
    delegate.setAttributeSource(new AnnotationJmxAttributeSource());

    AppendNamingStrategy ans = new AppendNamingStrategy();
    ans.setDelegate(delegate);//from   w w  w .jav a  2  s .  c  om
    ans.setDomain("testApplication");

    ObjectName name = ans.getObjectName(new XmlBehaviorEventPersisterImpl(), "testPersister");
    assertNotNull("name is constructed", name);
    assertEquals("name has been transformed correctly",
            "testApplication:package=com.mtgi.analytics,name=BeetLog", name.toString());
    assertEquals("package name quoted properly", "com.mtgi.analytics", name.getKeyProperty("package"));
}

From source file:org.apache.openejb.server.cli.command.LocalJMXCommand.java

private void listMBeans() {
    final MBeanServer mBeanServer = LocalMBeanServer.get();

    final Set<ObjectName> names;
    try {/*from  w  w  w  .  j  av  a 2  s  .  c  om*/
        names = mBeanServer.queryNames(null, null);
    } catch (Exception e) {
        streamManager.writeErr(e);
        return;
    }

    final Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        streamManager.writeOut("Name: " + oname.toString());

        try {
            final MBeanInfo minfo = mBeanServer.getMBeanInfo(oname);
            String code = minfo.getClassName();
            if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                code = (String) mBeanServer.getAttribute(oname, "modelerType");
            }
            streamManager.writeOut("  + modelerType: " + code);

            MBeanAttributeInfo attrs[] = minfo.getAttributes();
            Object value = null;

            for (int i = 0; i < attrs.length; i++) {
                if (!attrs[i].isReadable()) {
                    continue;
                }

                final String attName = attrs[i].getName();
                if ("modelerType".equals(attName)) {
                    continue;
                }

                if (attName.indexOf("=") >= 0 || attName.indexOf(":") >= 0 || attName.indexOf(" ") >= 0) {
                    continue;
                }

                try {
                    value = mBeanServer.getAttribute(oname, attName);
                } catch (RuntimeMBeanException uoe) {
                    // ignored
                } catch (Throwable t) {
                    streamManager.writeErr(new Exception(t));
                    continue;
                }

                try {
                    String valueString = stringify(value);
                    streamManager.writeOut("  + " + attName + ": " + valueString);
                } catch (Throwable t) {
                    streamManager.writeErr(new Exception(t));
                }
            }
        } catch (Throwable t) {
            streamManager.writeErr(new Exception(t));
        }
        streamManager.writeOut("");
    }
}

From source file:org.helios.jzab.agent.commands.impl.jmx.JMXDiscoveryCommandProcessor.java

/**
 * Var parameters:<ol>/*from   w  w w .  j  ava2s. c  o  m*/
 *  <li><b>JMX Object Name</b>: The ObjectName pattern query.</li>
 *  <li><b>Domain</b>: (Optional) Defines the MBeanServer domain in which the target MBeans are registered. Can also be interpreted as a {@link JMXServiceURL} in which case a remote connection will be used to retrieve the attribute values.</li>
 * </ol>
 * {@inheritDoc}
 * @see org.helios.jzab.agent.commands.AbstractCommandProcessor#doExecute(java.lang.String, java.lang.String[])
 */
@Override
protected Object doExecute(String commandName, String... args) throws Exception {
    if (commandName == null || commandName.trim().isEmpty())
        throw new IllegalArgumentException("Null or empty command name", new Throwable());
    if (args == null || args.length < 1)
        throw new IllegalArgumentException("Invalid argument count for command [" + commandName
                + "] with args [" + (args == null ? 0 : args.length) + "]", new Throwable());
    commandName = commandName.trim();
    Map<String, String> tokens = new HashMap<String, String>();
    ObjectName objectName = null;
    try {
        objectName = extractTokens(args[0].trim(), tokens);
    } catch (Exception e) {
        log.error("Invalid ObjectName Requested [{}], Error:[{}]", args[0], e.getMessage());
        throw new RuntimeException(e);
    }
    String domain = null;
    if (args.length > 3) {
        domain = args[3];
    }
    MBeanServerConnection server = null;
    Set<JSONObject> results = new HashSet<JSONObject>();
    try {
        server = getServerForDomain(domain);
        //return JMXHelper.getAttribute(server, compoundDelimiter, on, attrName);

        for (ObjectName on : server.queryNames(objectName, null)) {
            for (Map.Entry<String, String> entry : tokens.entrySet()) {
                String resolvedValue = resolveValue(on.toString(), entry.getKey(), args[0].trim());
                log.debug("Resolved Value [{}] for Token [{}]", resolvedValue, entry.getKey());
                //result.append("\n").append(entry.getValue()).append("--->").append(resolvedValue);
                results.add(new JSONObject(Collections.singletonMap(entry.getKey(), resolvedValue)));
            }
        }
        return results.toArray(new JSONObject[results.size()]);
    } catch (Exception e) {
        log.debug("Failed to get MBeanServerConnection for domain [{}]", domain, e);
        log.error("Failed to get MBeanServerConnection for domain [{}]", domain);
        throw new RuntimeException(e);
    }
}

From source file:com.mtgi.jmx.export.naming.AppendNamingStrategyTest.java

@Test
public void testPackage() throws MalformedObjectNameException {

    Object inst = new XmlBehaviorEventPersisterImpl();
    String beanName = "aName";

    ObjectNamingStrategy mock = createMock(ObjectNamingStrategy.class);
    expect(mock.getObjectName(inst, beanName))
            .andReturn(ObjectName.getInstance("topLevel:package=com.mtgi.analytics,group=stuff,name=foobar"))
            .once();//from   w  w w.  j a  v  a 2  s. c  o m
    replay(mock);

    AppendNamingStrategy ans = new AppendNamingStrategy();
    ans.setDelegate(mock);
    ans.setValue("testPersister");
    ans.setDomain("testApplication");

    ObjectName name = ans.getObjectName(inst, beanName);
    assertNotNull("name is constructed", name);
    assertEquals("name has been transformed correctly",
            "testApplication:package=com.mtgi.analytics.topLevel,group=stuff.foobar,name=testPersister",
            name.toString());
}

From source file:org.openmrs.module.jmx.impl.JMXServiceImpl.java

/**
 * @see org.openmrs.module.jmx.JMXService#unregisterBean(String)
 *//*  w  w w .jav  a  2s .c  om*/
@Override
public void unregisterMBean(String folder, String name) {
    try {
        ObjectName objName = getObjectName(folder, name);
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        if (beanServer.isRegistered(objName))
            beanServer.unregisterMBean(objName);

        log.debug("Unregistered MBean: " + objName.toString());

    } catch (MalformedObjectNameException e) {
        log.error("Invalid MBean name", e);
    } catch (Exception e) {
        log.error("Unable to unregister MBean", e);
    }
}

From source file:com.mtgi.jmx.export.naming.AppendNamingStrategyTest.java

@Test
public void testNewKey() throws MalformedObjectNameException {
    MetadataNamingStrategy delegate = new MetadataNamingStrategy();
    delegate.setAttributeSource(new AnnotationJmxAttributeSource());

    AppendNamingStrategy ans = new AppendNamingStrategy();
    ans.setDelegate(delegate);/*from www .  ja v  a2  s.co  m*/
    ans.setValue("testPersister");
    ans.setDomain("testApplication");

    ObjectName name = ans.getObjectName(new XmlBehaviorEventPersisterImpl(), "testPersister");
    assertNotNull("name is constructed", name);
    assertEquals("name has been transformed correctly",
            "testApplication:package=com.mtgi.analytics,group=BeetLog,name=testPersister", name.toString());
    assertEquals("package name quoted properly", "com.mtgi.analytics", name.getKeyProperty("package"));
}