ResourceTreeNode[] createBeans(ObjectName parent) throws Exception {
    // there is a bug in the current jsr77 implementation with regard to naming
    // of EJBModule that are part of EARs => I've used a workaround
    //
    ObjectInstance[] insts =
        getMBeansForQuery(
            JMX_JSR77_DOMAIN + ":EJBModule=" + parent.getKeyProperty("name") + ",*", null);

    ResourceTreeNode[] ejbs = new ResourceTreeNode[insts.length];
    for (int i = 0; i < insts.length; i++) {
      ObjectName objName = insts[i].getObjectName();
      String type = objName.getKeyProperty("j2eeType");

      String ejbName = objName.getKeyProperty("name");
      String containerUrl = "jboss.j2ee:service=EJB,jndiName=" + ejbName;
      containerUrl = java.net.URLEncoder.encode(containerUrl);
      containerUrl = "/jmx-console/HtmlAdaptor?action=inspectMBean&name=" + containerUrl;

      TreeNodeMenuEntry[] menus =
          new TreeNodeMenuEntry[] {
            new SimpleTreeNodeMenuEntryImpl(
                "View container in other window", new HttpLinkTreeAction(containerUrl, "_blank"))
          };

      String j2eeType = objName.getKeyProperty("j2eeType");
      String filename = "EJB.jsp";
      if (j2eeType.equalsIgnoreCase("StatelessSessionBean")) {
        filename = "StatelessEjb.jsp";
      } else if (j2eeType.equalsIgnoreCase("StatefulSessionBean")) {
        filename = "StatefulEjb.jsp";
      } else if (j2eeType.equalsIgnoreCase("EntityBean")) {
        filename = "EntityEjb.jsp";
      } else if (j2eeType.equalsIgnoreCase("MessageDrivenBean")) {
        filename = "MdbEjb.jsp";
      }

      ejbs[i] =
          createResourceNode(
              ejbName, // name
              type, // description
              "images/bean.gif", // Icon URL
              filename + "?ObjectName=" + encode(objName.toString()), // Default URL
              menus,
              null, // sub nodes
              null, // Sub-Resources
              objName.toString(),
              insts[i].getClassName());
    }

    return ejbs;
  }
 void addMBean(ObjectName beanName) {
   try {
     MBeanInfo info = _server.getMBeanInfo(beanName);
     MBeanAttributeInfo[] infos = info.getAttributes();
     _beanValueMap.put(beanName.toString(), new HashMap<String, Object>());
     for (MBeanAttributeInfo infoItem : infos) {
       Object val = _server.getAttribute(beanName, infoItem.getName());
       // System.out.println("         " + infoItem.getName() + " : " +
       // _server.getAttribute(beanName, infoItem.getName()) + " type : " + infoItem.getType());
       _beanValueMap.get(beanName.toString()).put(infoItem.getName(), val);
     }
   } catch (Exception e) {
     _logger.error("Error getting bean info, domain=" + _domain, e);
   }
 }
Example #3
0
 private Set<String> enumerateIndexes(ProbeDescSummary summary) {
   MBeanServerConnection mbean = cnx.getConnection().connection;
   Set<String> indexes = new HashSet<String>();
   for (String name : summary.specifics.get("mbeanNames").split(" *; *")) {
     try {
       Set<ObjectName> mbeanNames = mbean.queryNames(new ObjectName(name), null);
       Pattern p = Pattern.compile(summary.specifics.get("mbeanIndex"));
       for (ObjectName oneMbean : mbeanNames) {
         log(Level.DEBUG, "%s", oneMbean.getCanonicalName());
         Matcher m = p.matcher(oneMbean.toString());
         if (m.matches() && !m.group(1).isEmpty()) {
           log(Level.DEBUG, "index found: %s for %s", m.group(1), summary.name);
           indexes.add(m.group(1));
         }
       }
     } catch (MalformedObjectNameException e) {
       log(
           Level.WARN,
           "invalid name for auto discovery of probe %s: %s",
           summary.name,
           e.getMessage());
     } catch (IOException e) {
       log(
           Level.WARN,
           "Connection failed for auto discovery of probe %s: %s",
           summary.name,
           e.getMessage());
     }
   }
   return indexes;
 }
  protected Result describeMbean(
      @Nonnull MBeanServerConnection mbeanServer, @Nonnull ObjectName objectName)
      throws IntrospectionException, ReflectionException, InstanceNotFoundException, IOException {
    MBeanInfo mbeanInfo = mbeanServer.getMBeanInfo(objectName);
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    out.println("# MBEAN");
    out.println(objectName.toString());
    out.println();
    out.println("## OPERATIONS");
    List<MBeanOperationInfo> operations = Arrays.asList(mbeanInfo.getOperations());
    Collections.sort(
        operations,
        new Comparator<MBeanOperationInfo>() {
          @Override
          public int compare(MBeanOperationInfo o1, MBeanOperationInfo o2) {
            return o1.getName().compareTo(o1.getName());
          }
        });

    for (MBeanOperationInfo opInfo : operations) {
      out.print("* " + opInfo.getName() + "(");
      MBeanParameterInfo[] signature = opInfo.getSignature();
      for (int i = 0; i < signature.length; i++) {
        MBeanParameterInfo paramInfo = signature[i];
        out.print(paramInfo.getType() + " " + paramInfo.getName());
        if (i < signature.length - 1) {
          out.print(", ");
        }
      }

      out.print("):" + opInfo.getReturnType() /* + " - " + opInfo.getDescription() */);
      out.println();
    }
    out.println();
    out.println("## ATTRIBUTES");
    List<MBeanAttributeInfo> attributes = Arrays.asList(mbeanInfo.getAttributes());
    Collections.sort(
        attributes,
        new Comparator<MBeanAttributeInfo>() {
          @Override
          public int compare(MBeanAttributeInfo o1, MBeanAttributeInfo o2) {
            return o1.getName().compareTo(o2.getName());
          }
        });
    for (MBeanAttributeInfo attrInfo : attributes) {
      out.println(
          "* "
              + attrInfo.getName()
              + ": "
              + attrInfo.getType()
              + " - "
              + (attrInfo.isReadable() ? "r" : "")
              + (attrInfo.isWritable() ? "w" : "") /* + " - " +
                    attrInfo.getDescription() */);
    }

    String description = sw.getBuffer().toString();
    return new Result(objectName, description, description);
  }
  protected void undeployJsr77(
      MBeanServer server, VFSDeploymentUnit unit, ServiceDeployment metaData) {
    List<ServiceMetaData> beans = metaData.getServices();
    if (beans != null && beans.isEmpty() == false) {
      ListIterator<ServiceMetaData> iter = beans.listIterator(beans.size());
      while (iter.hasPrevious()) {
        ObjectName name = iter.previous().getObjectName();
        try {
          // Destroy JSR-77 MBean
          MBean.destroy(server, name.toString());
          log.debug("Destroy MBean, name: " + name);
        } catch (Throwable e) {
          log.debug("Failed to remove remove JSR-77 MBean", e);
        }
      }
    }

    // Remove JSR-77 SAR-Module
    String moduleName = unit.getSimpleName();
    try {
      ServiceModule.destroy(server, moduleName);
      log.debug("Removed JSR-77 SAR: " + moduleName);
    } catch (Throwable e) {
      log.debug("Failed to remove JSR-77 SAR: " + moduleName);
    }
  }
Example #6
0
 /**
  * Returns the objectName used to register the MBean. If the MBean is not registered, return an
  * empty string.
  *
  * @return the objectName used to register the MBean.
  * @see org.apache.felix.ipojo.Handler#getDescription()
  */
 public String getUsedObjectName() {
   if (m_objectName != null) {
     return m_objectName.toString();
   } else {
     return "";
   }
 }
  private int getHttpsPort() {
    try {
      MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
      QueryExp query = Query.eq(Query.attr("Scheme"), Query.value("https"));
      Set<ObjectName> objectNames = mBeanServer.queryNames(null, query);

      if (objectNames != null && objectNames.size() > 0) {
        for (ObjectName objectName : objectNames) {
          String name = objectName.toString();
          if (name.indexOf("port=") > -1) {
            String[] parts = name.split("port=");
            String port = parts[1];
            try {
              int portNum = Integer.parseInt(port);
              return portNum;
            } catch (NumberFormatException e) {
              logger.error("Error parsing https port:" + port);
              return -1;
            }
          }
        }
      }
    } catch (Throwable t) {
      logger.error("Error getting https port:", t);
    }

    return -1;
  }
 /**
  * Allows a named object to be created.
  *
  * @param objectName The object name of the object.
  * @param object A reference to the object.
  */
 public NamedObject(ObjectName objectName, Object object) {
   if (objectName.isPattern()) {
     throw new RuntimeOperationsException(
         new IllegalArgumentException("Invalid name->" + objectName.toString()));
   }
   this.name = objectName;
   this.object = object;
 }
 /**
  * Allows a named object to be created.
  *
  * @param objectName The string representation of the object name of the object.
  * @param object A reference to the object.
  * @exception MalformedObjectNameException The string passed does not have the format of a valid
  *     ObjectName
  */
 public NamedObject(String objectName, Object object) throws MalformedObjectNameException {
   ObjectName objName = new ObjectName(objectName);
   if (objName.isPattern()) {
     throw new RuntimeOperationsException(
         new IllegalArgumentException("Invalid name->" + objName.toString()));
   }
   this.name = objName;
   this.object = object;
 }
Example #10
0
  /** Registers the Dynamic Mbean. */
  public void start() {
    // create the corresponding MBean
    if (m_registerCallbacks) {
      m_MBean =
          new DynamicMBeanWRegisterImpl(
              m_jmxConfigFieldMap,
              m_instanceManager,
              m_preRegisterMeth,
              m_postRegisterMeth,
              m_preDeregisterMeth,
              m_postDeregisterMeth);
    } else {
      m_MBean = new DynamicMBeanImpl(m_jmxConfigFieldMap, m_instanceManager);
    }

    if (m_usesMOSGi) {
      // use whiteboard pattern to register MBean

      if (m_serviceRegistration != null) {
        m_serviceRegistration.unregister();
      }

      // Register the ManagedService
      BundleContext bundleContext = m_instanceManager.getContext();
      Properties properties = new Properties();
      try {
        m_objectName = new ObjectName(getObjectNameString());

        properties.put("jmxagent.objectName", m_objectName.toString());

        m_serviceRegistration =
            bundleContext.registerService(
                javax.management.DynamicMBean.class.getName(), m_MBean, properties);

        m_registered = true;
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else {
      try {
        m_objectName = new ObjectName(getObjectNameString());
        ObjectInstance instance =
            ManagementFactory.getPlatformMBeanServer().registerMBean(m_MBean, m_objectName);

        // we must retrieve object name used to register the MBean.
        // It can have been changed by preRegister method of
        // MBeanRegistration interface.
        if (m_registerCallbacks) {
          m_objectName = instance.getObjectName();
        }

        m_registered = true;
      } catch (Exception e) {
        error("Registration of MBean failed.", e);
      }
    }
  }
Example #11
0
 private void verifyUnexpectedBeans(Set<ObjectName> children) {
   if (allClients != null) {
     for (ZooKeeper zkc : allClients) {
       Iterator<ObjectName> childItr = children.iterator();
       while (childItr.hasNext()) {
         ObjectName clientBean = childItr.next();
         if (clientBean.toString().contains(getHexSessionId(zkc.getSessionId()))) {
           LOG.info("found name:" + zkc.getSessionId() + " client bean:" + clientBean.toString());
           childItr.remove();
         }
       }
     }
   }
   for (ObjectName bean : children) {
     LOG.info("unexpected:" + bean.toString());
   }
   TestCase.assertEquals("Unexpected bean exists!", 0, children.size());
 }
Example #12
0
 protected void onEnvironmentSet() {
   deploymentDir = environment.getProperty("branch-file", File.class);
   classLoader = environment.getProperty("branch-cl", ClassLoader.class);
   ObjectName parentObjectName = environment.getProperty("parentObjectName", ObjectName.class);
   if (deploymentDir == null || !deploymentDir.isDirectory())
     throw new IllegalArgumentException(
         "The passed deployment directory was invalid [" + deploymentDir + "]");
   String[] dirPair = dirPair(deploymentDir);
   if (dirPair.length == 1) {
     dirPair = new String[] {"root", deploymentDir.getName()};
     // throw new IllegalArgumentException("The passed deployment directory [" + deploymentDir + "]
     // is invalid: [" + dirPair[0] + "]");
   }
   Path path = Paths.get(this.deploymentDir.getPath());
   dirKey = dirPair[0];
   if ("branch".equals(dirKey)) {
     throw new IllegalArgumentException(
         "The passed deployment directory ["
             + deploymentDir
             + "] has an illegal key: ["
             + dirPair[0]
             + "]");
   }
   dirValue = dirPair[1];
   if ("lib".equals(dirValue) || "xlib".equals(dirValue)) {
     dirKey = "ext";
     dirPair[0] = "ext";
   }
   //		ObjectName parentObjectName = findParent(deploymentDir.getParentFile());
   if (parentObjectName != null) {
     // env.put("branch-parent", parentBranch);
     parentBranch = environment.getProperty("branch-parent", DeploymentBranch.class);
     objectName =
         JMXHelper.objectName(
             new StringBuilder(parentObjectName.toString())
                 .append(",")
                 .append(dirKey)
                 .append("=")
                 .append(dirValue));
     if (parentBranch == null && JMXHelper.isRegistered(parentObjectName)) {
       parentBranch = (DeploymentBranch) JMXHelper.getAttribute(parentObjectName, "ParentBranch");
     }
     root = false;
   } else {
     objectName =
         JMXHelper.objectName(
             new StringBuilder(OBJECT_NAME_BASE)
                 .append(",")
                 .append(dirKey)
                 .append("=")
                 .append(dirValue));
     parentBranch = null;
     root = true;
   }
 }
  /**
   * @throws Exception
   * @see org.apache.activemq.Service#stop()
   */
  @Override
  public void doStop(ServiceStopper stopper) throws Exception {
    this.letter.stop();

    if (brokerService != null && brokerService.isUseJmx()) {
      ObjectName brokerObjectName = brokerService.getBrokerObjectName();
      brokerService
          .getManagementContext()
          .unregisterMBean(createPersistenceAdapterName(brokerObjectName.toString(), toString()));
    }
  }
 private static void checkPlatformMBeans() throws Exception {
   MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
   Set<ObjectName> mbeanNames = mbs.queryNames(null, null);
   for (ObjectName name : mbeanNames) {
     if (!mbs.isInstanceOf(name, NotificationBroadcaster.class.getName())) {
       System.out.println(name + ": not a NotificationBroadcaster");
     } else {
       MBeanInfo mbi = mbs.getMBeanInfo(name);
       check(name.toString(), mbi.getNotifications());
     }
   }
 }
 private void addMBeanExpressionSupport(Map<String, String> descriptions) {
   if (legacy) {
     descriptions.put(DESC_MBEAN_EXPR, "true");
     descriptions.put(DESC_MBEAN_EXPR_DESCR, MESSAGES.descriptorMBeanExpressionSupportFalse());
     if (configuredDomains.getExprDomain() != null) {
       ObjectName alternate = configuredDomains.getMirroredObjectName(name);
       descriptions.put(DESC_ALTERNATE_MBEAN, alternate.toString());
       descriptions.put(
           DESC_ALTERNATE_MBEAN_DESCR, MESSAGES.descriptorAlternateMBeanExpressions(alternate));
     }
   } else {
     descriptions.put(DESC_MBEAN_EXPR, "false");
     descriptions.put(DESC_MBEAN_EXPR_DESCR, MESSAGES.descriptorMBeanExpressionSupportTrue());
     if (configuredDomains.getLegacyDomain() != null) {
       ObjectName alternate = configuredDomains.getMirroredObjectName(name);
       descriptions.put(DESC_ALTERNATE_MBEAN, alternate.toString());
       descriptions.put(
           DESC_ALTERNATE_MBEAN_DESCR, MESSAGES.descriptorAlternateMBeanLegacy(alternate));
     }
   }
 }
Example #16
0
 /**
  * @see com.ixora.rms.agents.impl.jmx.JMXAbstractAgent#acceptCounter(javax.management.ObjectName,
  *     javax.management.MBeanAttributeInfo)
  */
 protected boolean acceptCounter(ObjectName oname, MBeanAttributeInfo ainfo) {
   if (ainfo.getName().equals("Name")) {
     return false;
   }
   String soname = oname.toString();
   if (soname.startsWith("java.lang:type=MemoryPool,name=")) {
     if (ainfo.getName().indexOf("Threshold") >= 0) {
       return false;
     }
   }
   return true;
 }
Example #17
0
 /**
  * @see com.ixora.rms.agents.impl.jmx.JMXAbstractAgent#acceptCounter(javax.management.ObjectName,
  *     java.lang.String, java.lang.String, javax.management.openmbean.OpenType)
  */
 protected boolean acceptCounter(
     ObjectName oname, String attrName, String sitem, OpenType<?> otype) {
   String soname = oname.toString();
   if (soname.startsWith("java.lang:type=GarbageCollector")) {
     if (attrName.equals("LastGcInfo")) {
       if (sitem.equals("id")) {
         return false;
       }
     }
   }
   return true;
 }
  @Test
  public void testObjectName() {
    ManagedBeanDefinition definition = new ManagedBeanDefinition();
    definition.setType(HelloBean.class);
    ObjectName objectName = definition.createObjectName();

    Assert.assertEquals(objectName.toString(), "com.consol.citrus.jmx.mbean:type=HelloBean");

    definition = new ManagedBeanDefinition();
    definition.setObjectDomain(HelloBean.class.getPackage().getName());
    definition.setObjectName("type=HelloBean,name=Hello");
    objectName = definition.createObjectName();

    Assert.assertEquals(
        objectName.toString(), "com.consol.citrus.jmx.mbean:type=HelloBean,name=Hello");

    definition = new ManagedBeanDefinition();
    definition.setObjectDomain(HelloBean.class.getPackage().getName());
    definition.setName(HelloBean.class.getSimpleName());
    objectName = definition.createObjectName();

    Assert.assertEquals(objectName.toString(), "com.consol.citrus.jmx.mbean:name=HelloBean");
  }
  private ObjectName replacePrefix(ObjectName objectName) {
    if (null != prefix) {
      String domain = objectName.getDomain();
      if ("prefix".equals(domain)) {
        try {
          //	prefix:
          return new ObjectName(prefix + objectName.toString().substring(7));
        } catch (Exception e) {
          logger.warn("failed to add prefix {} to ObjectName{}", prefix, objectName);
        }
      }
    }

    return objectName;
  }
Example #20
0
 public CtxObj(
     String objName,
     ObjectName mbean,
     String objType,
     byte valueType,
     String attrName,
     String counter) {
   this.objName = objName;
   this.mbean = mbean;
   this.mbeanHash = HashUtil.hash(mbean.toString());
   this.objType = objType;
   this.valueType = valueType;
   this.attrName = attrName;
   this.counter = counter;
 }
 /**
  * {@collect.stats} Return a string describing this object.
  *
  * @return a description of this RoleUnresolved object.
  */
 public String toString() {
   StringBuilder result = new StringBuilder();
   result.append("role name: " + roleName);
   if (roleValue != null) {
     result.append("; value: ");
     for (Iterator objNameIter = roleValue.iterator(); objNameIter.hasNext(); ) {
       ObjectName currObjName = (ObjectName) (objNameIter.next());
       result.append(currObjName.toString());
       if (objNameIter.hasNext()) {
         result.append(", ");
       }
     }
   }
   result.append("; problem type: " + problemType);
   return result.toString();
 }
Example #22
0
  public Set<String> findJMXBeans(String filter) throws MalformedObjectNameException, IOException {
    MBeanServerConnection server = getMBeanServerConnection();
    Set<String> answer = new HashSet<String>();

    String filters[] = filter.split("\\|");
    for (int i = 0; i < filters.length; i++) {
      for (ObjectName item : server.queryNames(new ObjectName(filters[i]), null)) {
        answer.add(item.toString());
      }
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("The filter: " + filter + " matches the following MBeans: " + answer);
    }
    return answer;
  }
  /**
   * Return the MBean Name for the specified role name (if any); otherwise return <code>null</code>.
   *
   * @param rolename Role name to look up
   */
  public String findRole(String rolename) {

    UserDatabase database = (UserDatabase) this.resource;
    Role role = database.findRole(rolename);
    if (role == null) {
      return (null);
    }
    try {
      ObjectName oname = MBeanUtils.createObjectName(managedRole.getDomain(), role);
      return (oname.toString());
    } catch (MalformedObjectNameException e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Cannot create object name for role [" + rolename + "]");
      iae.initCause(e);
      throw iae;
    }
  }
Example #24
0
 /**
  * @see
  *     com.ixora.rms.agents.impl.jmx.JMXAbstractAgent#getCounterDescription(javax.management.ObjectName,
  *     javax.management.openmbean.CompositeType, java.lang.String)
  */
 protected String[] getCounterNameAndDescription(
     ObjectName oname, String attrName, CompositeType ct, String item) {
   String soname = oname.toString();
   if (soname.startsWith("java.lang:type=GarbageCollector") && attrName.equals("LastGcInfo")) {
     return new String[] {"GarbageCollector." + item, "GarbageCollector." + item + ".desc"};
   }
   if (soname.startsWith("java.lang:type=MemoryPool,name=")
       || soname.startsWith("java.lang:type=Memory")) {
     if (attrName.equals("Usage")
         || attrName.equals("PeakUsage")
         || attrName.equals("CollectionUsage")
         || attrName.equals("HeapMemoryUsage")
         || attrName.equals("NonHeapMemoryUsage"))
       return new String[] {"Memory." + item, "Memory." + item + ".desc"};
   }
   return super.getCounterNameAndDescription(oname, attrName, ct, item);
 }
Example #25
0
 /**
  * Initializes the initial variables and registers the class to the MBean server. <br>
  * <br>
  * <b>NOTE: This should be run before any other operations are performed. Operations will NOT be
  * usable until this is called (and until destroy() is called).</b>
  *
  * @throws ApplicationServiceException if an error occurs during registration.
  */
 public void init() throws ApplicationServiceException {
   try {
     try {
       LOGGER.debug(
           "Registering application service MBean under object name: {}", objectName.toString());
       mBeanServer.registerMBean(this, objectName);
     } catch (InstanceAlreadyExistsException iaee) {
       // Try to remove and re-register
       LOGGER.debug("Re-registering Application Service MBean");
       mBeanServer.unregisterMBean(objectName);
       mBeanServer.registerMBean(this, objectName);
     }
   } catch (Exception e) {
     LOGGER.warn("Could not register mbean.", e);
     throw new ApplicationServiceException(e);
   }
 }
  protected void deployJsr77(MBeanServer server, VFSDeploymentUnit unit, ServiceDeployment metaData)
      throws Throwable {
    ObjectName sarName = ServiceModule.create(server, unit.getSimpleName(), unit.getRoot().toURL());
    if (sarName != null) {
      log.debug("Created ServiceModule: " + sarName);
    }

    List<ServiceMetaData> beans = metaData.getServices();
    if (beans != null && beans.isEmpty() == false) {
      for (ServiceMetaData bean : beans) {
        ObjectName mbeanName = bean.getObjectName();
        // Create JSR-77 MBean
        MBean.create(server, sarName.toString(), mbeanName);
        log.debug("Create MBean, name: " + mbeanName + ", SAR Module: " + sarName);
      }
    }
  }
  /**
   * Return the MBean Name for the specified group name (if any); otherwise return <code>null</code>
   * .
   *
   * @param groupname Group name to look up
   */
  public String findGroup(String groupname) {

    UserDatabase database = (UserDatabase) this.resource;
    Group group = database.findGroup(groupname);
    if (group == null) {
      return (null);
    }
    try {
      ObjectName oname = MBeanUtils.createObjectName(managedGroup.getDomain(), group);
      return (oname.toString());
    } catch (MalformedObjectNameException e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Cannot create object name for group [" + groupname + "]");
      iae.initCause(e);
      throw iae;
    }
  }
  /**
   * Return the MBean Name for the specified user name (if any); otherwise return <code>null</code>.
   *
   * @param username User name to look up
   */
  public String findUser(String username) {

    UserDatabase database = (UserDatabase) this.resource;
    User user = database.findUser(username);
    if (user == null) {
      return (null);
    }
    try {
      ObjectName oname = MBeanUtils.createObjectName(managedUser.getDomain(), user);
      return (oname.toString());
    } catch (MalformedObjectNameException e) {
      IllegalArgumentException iae =
          new IllegalArgumentException("Cannot create object name for user [" + username + "]");
      iae.initCause(e);
      throw iae;
    }
  }
  /**
   * Return a map of session mbean names to the user principals for those sessions. The
   * serviceManagementBean stores them as session ID to user principals, and we have to convert the
   * session ID to mbean name here. Gross, but it's the only way to not have JMX-specific stuff in
   * the ServiceManagementBean.
   */
  @Override
  public Map<String, Map<String, String>> getLoggedInSessions() {
    // First, get the map of session ID to user principals for that session.
    Map<Long, Map<String, String>> sessionPrincipalMap =
        serviceManagementBean.getLoggedInSessions();

    Map<String, Map<String, String>> result = new HashMap<>();

    for (Map.Entry<Long, Map<String, String>> entry : sessionPrincipalMap.entrySet()) {
      long sessionId = entry.getKey();
      Map<String, String> userPrincipals = entry.getValue();
      ObjectName sessionMBeanName =
          managementServiceHandler.getSessionMXBean(sessionId).getObjectName();
      result.put(sessionMBeanName.toString(), userPrincipals);
    }

    return result;
  }
    public void registerCircuitBreaker(final CircuitBreaker circuitBreaker, final String name)
        throws JMException {
      ObjectName mbeanObjectName = null;

      ObjectName serviceName = Qi4jMBeans.findServiceName(server, application.name(), name);
      if (serviceName != null) {
        mbeanObjectName = new ObjectName(serviceName.toString() + ",name=Circuit breaker");
      } else {
        try {
          mbeanObjectName = new ObjectName("CircuitBreaker:name=" + name);
        } catch (MalformedObjectNameException e) {
          throw new IllegalArgumentException("Illegal name:" + name);
        }
      }

      CircuitBreakerJMX bean = new CircuitBreakerJMX(circuitBreaker, mbeanObjectName);

      try {
        server.registerMBean(bean, mbeanObjectName);
        registeredCircuitBreakers.put(circuitBreaker, mbeanObjectName);
      } catch (InstanceAlreadyExistsException e) {
        e.printStackTrace();
      } catch (MBeanRegistrationException e) {
        e.printStackTrace();
      } catch (NotCompliantMBeanException e) {
        e.printStackTrace();
      }

      // Add logger
      circuitBreaker.addPropertyChangeListener(
          new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
              if (evt.getPropertyName().equals("status")) {
                if (evt.getNewValue().equals(CircuitBreaker.Status.on))
                  LoggerFactory.getLogger(CircuitBreakerManagement.class)
                      .info("Circuit breaker " + name + " is now on");
                else
                  LoggerFactory.getLogger(CircuitBreakerManagement.class)
                      .error("Circuit breaker " + name + " is now off");
              }
            }
          });
    }