@Override
  public String getRouteStatsAsXml(
      String routeId, String camelContextName, boolean fullStats, boolean includeProcessors)
      throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {
      String pattern =
          String.format(
              "%s:context=%s,type=routes,name=\"%s\"",
              found.getDomain(), found.getKeyProperty("context"), routeId);
      ObjectName on = ObjectName.getInstance(pattern);
      J4pExecResponse response =
          jolokia.execute(
              new J4pExecRequest(
                  on, "dumpRouteStatsAsXml(boolean,boolean)", fullStats, includeProcessors));
      if (response != null) {
        String xml = response.getValue();
        return xml;
      }
    }

    return null;
  }
 StatsProviderManagerDelegateImpl(
     ProbeClientMediator pcm,
     ProbeRegistry probeRegistry,
     MonitoringRuntimeDataRegistry mrdr,
     Domain domain,
     String iName,
     MonitoringService monitoringService) {
   this.pcm = pcm;
   this.mrdr = mrdr;
   this.domain = domain;
   this.instanceName = iName;
   this.monitoringService = monitoringService;
   this.probeRegistry = probeRegistry;
   // serverNode is special, construct that first if doesn't exist
   serverNode = constructServerPP();
   statsProviderRegistry = new StatsProviderRegistry(mrdr);
   if (logger.isLoggable(Level.FINE)) {
     logger.log(Level.FINE, " In the ctor : instance name " + instanceName);
     logger.log(Level.FINE, " In the ctor : MONITORING SERVER " + MONITORING_SERVER);
   }
   MONITORING_SERVER = AMXGlassfish.DEFAULT.serverMon(instanceName);
   DOMAIN = MONITORING_SERVER.getDomain();
   PP = MONITORING_SERVER.getKeyProperty(PARENT_PATH_KEY);
   TYPE = MONITORING_SERVER.getKeyProperty(TYPE_KEY);
   NAME = MONITORING_SERVER.getKeyProperty(NAME_KEY);
   PARENT_PATH = PP + "/" + TYPE + "[" + NAME + "]";
 }
 @Override
 public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
   oname = name;
   mserver = server;
   domain = name.getDomain();
   return name;
 }
 public HashMap<String, ArrayList<ObjectName>> getDomains(
     final MBeanServer mBeanServer, String mbeanDomain, String mBean)
     throws ReflectionException, InstanceNotFoundException, IntrospectionException,
         MalformedObjectNameException, NullPointerException {
   final HashMap<String, ArrayList<ObjectName>> result =
       new HashMap<String, ArrayList<ObjectName>>();
   ObjectName queryObjectName = null;
   if (mbeanDomain != null && !mbeanDomain.isEmpty())
     queryObjectName = new ObjectName(mbeanDomain + (mBean != null ? ":" + mBean : ":*"));
   final Set mbeans = mBeanServer.queryMBeans(queryObjectName, null);
   final Iterator iter = mbeans.iterator();
   while (iter.hasNext()) {
     final ObjectInstance objectInstance = (ObjectInstance) iter.next();
     final ObjectName objectName = objectInstance.getObjectName();
     final String domain = objectName.getDomain();
     //
     if (result.containsKey(domain)) {
       final ArrayList<ObjectName> list = result.get(domain);
       list.add(objectName);
       result.put(domain, list);
     } else {
       final ArrayList<ObjectName> list = new ArrayList<ObjectName>();
       list.add(objectName);
       result.put(domain, list);
     }
   }
   return result;
 }
  @Override
  public List<Map<String, String>> getEndpoints(String camelContextName) throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    List<Map<String, String>> answer = new ArrayList<Map<String, String>>();

    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {
      String pattern =
          String.format(
              "%s:context=%s,type=endpoints,*", found.getDomain(), found.getKeyProperty("context"));
      J4pSearchResponse sr = jolokia.execute(new J4pSearchRequest(pattern));

      List<J4pReadRequest> list = new ArrayList<J4pReadRequest>();
      for (ObjectName on : sr.getObjectNames()) {
        list.add(new J4pReadRequest(on, "CamelId", "EndpointUri", "State"));
      }

      List<J4pReadResponse> lrr = jolokia.execute(list);
      for (J4pReadResponse rr : lrr) {
        Map<String, String> row = new LinkedHashMap<String, String>();
        row.put("camelContextName", rr.getValue("CamelId").toString());
        row.put("uri", rr.getValue("EndpointUri").toString());
        row.put("state", rr.getValue("State").toString());
        answer.add(row);
      }
    }

    return answer;
  }
  @Override
  public List<Map<String, String>> getEndpointRuntimeStatistics(String camelContextName)
      throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    List<Map<String, String>> answer = new ArrayList<Map<String, String>>();

    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {
      String pattern =
          String.format(
              "%s:context=%s,type=services,name=DefaultRuntimeEndpointRegistry",
              found.getDomain(), found.getKeyProperty("context"));
      ObjectName on = ObjectName.getInstance(pattern);

      J4pExecResponse response = jolokia.execute(new J4pExecRequest(on, "endpointStatistics()"));
      if (response != null) {
        JSONObject data = response.getValue();
        for (Object obj : data.values()) {
          JSONObject data2 = (JSONObject) obj;
          JSONObject service = (JSONObject) data2.values().iterator().next();

          Map<String, String> row = new LinkedHashMap<String, String>();
          row.put("index", asString(service.get("index")));
          row.put("url", asString(service.get("url")));
          row.put("routeId", asString(service.get("routeId")));
          row.put("direction", asString(service.get("direction")));
          row.put("static", asString(service.get("static")));
          row.put("dynamic", asString(service.get("dynamic")));
          row.put("hits", asString(service.get("hits")));
          answer.add(row);
        }
      }

      // sort the list
      Collections.sort(
          answer,
          new Comparator<Map<String, String>>() {
            @Override
            public int compare(Map<String, String> endpoint1, Map<String, String> endpoint2) {
              // sort by route id
              String route1 = endpoint1.get("routeId");
              String route2 = endpoint2.get("routeId");
              int num = route1.compareTo(route2);
              if (num == 0) {
                // we want in before out
                String dir1 = endpoint1.get("direction");
                String dir2 = endpoint2.get("direction");
                num = dir1.compareTo(dir2);
              }
              return num;
            }
          });
    }

    return answer;
  }
 public static ObjectName buildObjectNameFilter(ObjectName mapName) throws Exception {
   StringBuffer sb = new StringBuffer();
   sb.append(mapName.getDomain()).append(':');
   sb.append(mapName.getKeyPropertyListString());
   sb.append(',');
   sb.append("*");
   return new ObjectName(sb.toString());
 }
  @Override
  public List<Map<String, String>> getRestServices(String camelContextName) throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    List<Map<String, String>> answer = new ArrayList<Map<String, String>>();

    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {
      String pattern =
          String.format(
              "%s:context=%s,type=services,name=DefaultRestRegistry",
              found.getDomain(), found.getKeyProperty("context"));
      ObjectName on = ObjectName.getInstance(pattern);

      J4pExecResponse response = jolokia.execute(new J4pExecRequest(on, "listRestServices()"));
      if (response != null) {
        JSONObject data = response.getValue();
        if (data != null) {
          for (Object obj : data.values()) {
            JSONObject data2 = (JSONObject) obj;
            JSONObject service = (JSONObject) data2.values().iterator().next();

            Map<String, String> row = new LinkedHashMap<String, String>();
            row.put("basePath", asString(service.get("basePath")));
            row.put("baseUrl", asString(service.get("baseUrl")));
            row.put("consumes", asString(service.get("consumes")));
            row.put("description", asString(service.get("description")));
            row.put("inType", asString(service.get("inType")));
            row.put("method", asString(service.get("method")));
            row.put("outType", asString(service.get("outType")));
            row.put("produces", asString(service.get("produces")));
            row.put("routeId", asString(service.get("routeId")));
            row.put("state", asString(service.get("state")));
            row.put("uriTemplate", asString(service.get("uriTemplate")));
            row.put("url", asString(service.get("url")));
            answer.add(row);
          }
        }
      }

      // sort the list
      Collections.sort(
          answer,
          new Comparator<Map<String, String>>() {
            @Override
            public int compare(Map<String, String> service1, Map<String, String> service2) {
              String url1 = service1.get("url");
              String url2 = service2.get("url");
              return url1.compareTo(url2);
            }
          });
    }

    return answer;
  }
Exemple #9
0
 /** Creates a tag list from an object name. */
 private TagList createTagList(ObjectName name) {
   Map<String, String> props = name.getKeyPropertyList();
   List<Tag> tags = Lists.newArrayList();
   for (Map.Entry<String, String> e : props.entrySet()) {
     String key = PROP_KEY_PREFIX + "." + e.getKey();
     tags.add(Tags.newTag(key, e.getValue()));
   }
   tags.add(Tags.newTag(DOMAIN_KEY, name.getDomain()));
   tags.add(CLASS_TAG);
   return SortedTagList.builder().withTags(tags).build();
 }
 @Test
 public void testInvalidMapperDefaults() {
   Properties props = new Properties();
   props.put("com.netflix.servo.DefaultMonitorRegistry.jmxMapperClass", "com.my.invalid.class");
   DefaultMonitorRegistry registry = new DefaultMonitorRegistry(props);
   BasicCounter counter =
       new BasicCounter(new MonitorConfig.Builder("testInvalidMapperDefaults").build());
   registry.register(counter);
   ObjectName expectedName =
       ObjectNameMapper.DEFAULT.createObjectName("com.netflix.servo", counter);
   assertEquals(expectedName.getDomain(), "com.netflix.servo");
   assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered(expectedName));
 }
Exemple #11
0
  /** Process a "start" event for this Host. */
  public void start() {

    if (log.isDebugEnabled()) log.debug(sm.getString("hostConfig.start"));

    try {
      ObjectName hostON = new ObjectName(host.getObjectName());
      oname = new ObjectName(hostON.getDomain() + ":type=Deployer,host=" + host.getName());
      Registry.getRegistry(null, null).registerComponent(this, oname, this.getClass().getName());
    } catch (Exception e) {
      log.error(sm.getString("hostConfig.jmx.register", oname), e);
    }

    if (host.getDeployOnStartup()) deployApps();
  }
  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;
  }
 @Test
 public void testCustomJmxObjectMapper() {
   Properties props = new Properties();
   props.put(
       "com.netflix.servo.DefaultMonitorRegistry.jmxMapperClass",
       "com.netflix.servo.DefaultMonitorRegistryTest$ChangeDomainMapper");
   DefaultMonitorRegistry registry = new DefaultMonitorRegistry(props);
   BasicCounter counter =
       new BasicCounter(new MonitorConfig.Builder("testCustomJmxObjectMapper").build());
   registry.register(counter);
   ObjectName expectedName =
       new ChangeDomainMapper().createObjectName("com.netflix.servo", counter);
   assertEquals(expectedName.getDomain(), "com.netflix.servo.Renamed");
   assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered(expectedName));
 }
 public static ObjectName buildObjectName(ObjectName mapName, Object key) throws Exception {
   StringBuffer sb = new StringBuffer();
   sb.append(mapName.getDomain()).append(':');
   sb.append(mapName.getKeyPropertyListString());
   sb.append(',');
   if (key instanceof String) {
     sb.append("key=").append(ObjectName.quote(key.toString()));
   } else {
     sb.append("name=")
         .append(key.getClass().getName())
         .append('@')
         .append(Integer.toHexString(key.hashCode()));
   }
   return new ObjectName(sb.toString());
 }
 /** @since Java DMK 1.5 */
 public String[] getDomains() {
   if (interceptor instanceof MBeanServerInterceptor) {
     return ((MBeanServerInterceptor) interceptor).getDomains();
   }
   final Set names = interceptor.queryNames(null, null);
   final Set tmpSet = new HashSet(1);
   for (final Iterator i = names.iterator(); i.hasNext(); ) {
     final ObjectName x = (ObjectName) i.next();
     final String domain = x.getDomain();
     if (tmpSet.contains(domain)) continue;
     tmpSet.add(domain);
   }
   final String[] result = new String[tmpSet.size()];
   return (String[]) tmpSet.toArray(result);
 }
  @Override
  public void resumeRoute(String camelContextName, String routeId) throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {
      String pattern =
          String.format(
              "%s:context=%s,type=routes,name=\"%s\"",
              found.getDomain(), found.getKeyProperty("context"), routeId);
      ObjectName on = ObjectName.getInstance(pattern);
      jolokia.execute(new J4pExecRequest(on, "resume()"));
    }
  }
 /**
  * Unregisters all runtime MBeans that are registered in the same domain as the
  * MessageBrokerControl for the target MessageBroker.
  *
  * @param broker The MessageBroker component that has been stopped.
  */
 public static void unregisterRuntimeMBeans(MessageBroker broker) {
   MBeanServer server = MBeanServerLocatorFactory.getMBeanServerLocator().getMBeanServer();
   ObjectName brokerMBean = broker.getControl().getObjectName();
   String domain = brokerMBean.getDomain();
   try {
     ObjectName pattern = new ObjectName(domain + ":*");
     Set names = server.queryNames(pattern, null);
     Iterator iter = names.iterator();
     while (iter.hasNext()) {
       ObjectName on = (ObjectName) iter.next();
       server.unregisterMBean(on);
     }
   } catch (Exception e) {
     // We're generally unregistering these during shutdown (possibly JVM shutdown)
     // so there's nothing to really do here because we aren't guaranteed access to
     // resources like system log files, localized messaging, etc.
   }
 }
  /**
   * see: <code>
   * org.apache.karaf.management.KarafMBeanServerGuard#getNameSegments(javax.management.ObjectName)
   * </code> Assuming <strong>full</strong> {@link ObjectName} (not null, not containing wildcards
   * and other funny stuff), split objectName to elements used then co contruct ordered list of PIDs
   * to check for MBean permissions.
   *
   * @return
   */
  public static List<String> nameSegments(ObjectName objectName) {
    List<String> segments = new ArrayList<>();
    segments.add(objectName.getDomain());
    for (String s : objectName.getKeyPropertyListString().split(",")) {
      int index = s.indexOf('=');
      if (index < 0) {
        continue;
      }
      String key = objectName.getKeyProperty(s.substring(0, index));
      if (s.substring(0, index).equals("type")) {
        segments.add(1, key);
      } else {
        segments.add(key);
      }
    }

    return segments;
  }
  /**
   * Refreshes the content provider.
   *
   * @param jvm The active JVM
   */
  public void refresh(IActiveJvm jvm) {
    domains = new HashMap<String, MBeanDomain>();

    // add or update elements
    for (ObjectName objectName : getObjectNames(jvm)) {
      MBeanInfo mBeanInfo = getMBeanInfo(jvm, objectName);
      if (mBeanInfo == null) {
        continue;
      }

      List<AttributeNode> mBeanAttributes = new ArrayList<AttributeNode>();
      for (MBeanAttributeInfo attributeInfo : mBeanInfo.getAttributes()) {
        String attributeName = attributeInfo.getName();

        Object value = getContents(jvm, objectName, attributeName);
        addAttributeRoots(
            mBeanAttributes, new AttributeNode(attributeName, null, objectName), value);
      }

      for (AttributeNode node : mBeanAttributes.toArray(new AttributeNode[0])) {
        validateAttributes(node);
        if (node.getChildren().size() == 0 && !node.isValidLeaf()) {
          mBeanAttributes.remove(node);
        }
      }
      if (mBeanAttributes.size() == 0) {
        continue;
      }

      attributes.put(objectName, mBeanAttributes);

      String domainName = objectName.getDomain();
      MBeanDomain domain;
      if (domains.containsKey(domainName)) {
        domain = domains.get(domainName);
      } else {
        domain = new MBeanDomain(domainName);
      }
      domain.refresh(objectName, jvm);
      domains.put(domainName, domain);
    }
  }
 @Override
 public ObjectName getObjectName(Object managedBean, String beanKey)
     throws MalformedObjectNameException {
   ObjectName objectName = this.namingStrategy.getObjectName(managedBean, beanKey);
   String domain = objectName.getDomain();
   Hashtable<String, String> table =
       new Hashtable<String, String>(objectName.getKeyPropertyList());
   String name = objectName.getKeyProperty("name");
   if (name != null) {
     table.remove("name");
     String[] parts = StringUtils.delimitedListToStringArray(name, ".");
     table.put("type", parts[0]);
     if (parts.length > 1) {
       table.put(parts.length > 2 ? "name" : "value", parts[1]);
     }
     if (parts.length > 2) {
       table.put("value", name.substring(parts[0].length() + parts[1].length() + 2));
     }
   }
   return new ObjectName(domain, table);
 }
  @Override
  public List<Map<String, Object>> browseInflightExchanges(
      String camelContextName, int limit, boolean sortByLongestDuration) throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    List<Map<String, Object>> answer = new ArrayList<Map<String, Object>>();

    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {
      String pattern =
          String.format(
              "%s:context=%s,type=services,name=DefaultInflightRepository",
              found.getDomain(), found.getKeyProperty("context"));
      ObjectName on = ObjectName.getInstance(pattern);
      J4pExecResponse er =
          jolokia.execute(
              new J4pExecRequest(on, "browse(int,boolean)", limit, sortByLongestDuration));
      if (er != null) {
        JSONObject data = er.getValue();
        if (data != null) {
          for (Object obj : data.values()) {
            JSONObject inflight = (JSONObject) obj;

            Map<String, Object> row = new LinkedHashMap<String, Object>();
            row.put("exchangeId", asString(inflight.get("exchangeId")));
            row.put("fromRouteId", asString(inflight.get("fromRouteId")));
            row.put("routeId", asString(inflight.get("routeId")));
            row.put("nodeId", asString(inflight.get("nodeId")));
            row.put("elapsed", asString(inflight.get("elapsed")));
            row.put("duration", asString(inflight.get("duration")));
            answer.add(row);
          }
        }
      }
    }

    return answer;
  }
  @Override
  public String getRestApiDocAsJson(String camelContextName) throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {
      String pattern =
          String.format(
              "%s:context=%s,type=services,name=DefaultRestRegistry",
              found.getDomain(), found.getKeyProperty("context"));
      ObjectName on = ObjectName.getInstance(pattern);

      J4pExecResponse response = jolokia.execute(new J4pExecRequest(on, "apiDocAsJson()"));
      if (response != null) {
        String json = response.getValue();
        return json;
      }
    }

    return null;
  }
  @Override
  public void resetRouteStats(String camelContextName) throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    ObjectName found = lookupCamelContext(camelContextName);

    if (found != null) {
      String pattern =
          String.format(
              "%s:context=%s,type=routes,name=*",
              found.getDomain(), found.getKeyProperty("context"));
      J4pSearchResponse sr = jolokia.execute(new J4pSearchRequest(pattern));

      List<J4pExecRequest> list = new ArrayList<J4pExecRequest>();
      for (ObjectName on : sr.getObjectNames()) {
        list.add(new J4pExecRequest(on, "reset(boolean)", true));
      }

      jolokia.execute(list);
    }
  }
  /**
   * If we have access to {@link ConfigurationAdmin}, we can add RBAC information
   *
   * @param result
   */
  @Override
  @SuppressWarnings("unchecked")
  public void decorate(Map<String, Object> result) throws Exception {
    try {
      ServiceReference<ConfigurationAdmin> cmRef =
          bundleContext.getServiceReference(ConfigurationAdmin.class);
      ServiceReference<JMXSecurityMBean> jmxSecRef =
          bundleContext.getServiceReference(JMXSecurityMBean.class);
      if (cmRef != null && jmxSecRef != null) {
        ConfigurationAdmin configAdmin = bundleContext.getService(cmRef);
        JMXSecurityMBean jmxSec = bundleContext.getService(jmxSecRef);
        if (configAdmin != null && jmxSec != null) {
          // 1. each pair of MBean/operation has to be marked with RBAC flag (can/can't invoke)
          // 2. the information is provided by
          // org.apache.karaf.management.JMXSecurityMBean.canInvoke(java.util.Map)
          // 3. we'll peek into available configadmin jmx.acl* configs, to see which
          // MBeans/operations have to
          //    be examined and which will produce same results
          // 4. only then we'll prepare Map as parameter for canInvoke()

          Configuration[] configurations = configAdmin.listConfigurations("(service.pid=jmx.acl*)");
          List<String> allJmxAclPids = new LinkedList<>();
          for (Configuration cfg : configurations) {
            allJmxAclPids.add(cfg.getPid());
          }
          if (allJmxAclPids.size() == 0) {
            return;
          }

          Map<String, Map<String, Object>> domains =
              (Map<String, Map<String, Object>>) result.get("domains");

          // cache contains MBeanInfos for different MBeans/ObjectNames
          Map<String, Map<String, Object>> cache =
              (Map<String, Map<String, Object>>) result.get("cache");
          // new cache will contain MBeanInfos + RBAC info
          Map<String, Map<String, Object>> rbacCache = new HashMap<>();

          // the fact that some MBeans share JSON MBeanInfo doesn't mean that they can share RBAC
          // info
          // - each MBean's name may have RBAC information configured in different PIDs.

          // when iterating through all reapeating MBeans that share MBeanInfo (that doesn't have
          // RBAC info
          // yet), we have to decide if it'll use shared info after RBAC check or will switch to
          // dedicated
          // info. we have to be careful not to end with most MBeans *not* sharing MBeanInfo (in
          // case if
          // somehow the shared info will be "special case" from RBAC point of view)

          Map<String, List<String>> queryForMBeans = new HashMap<>();
          Map<String, List<String>> queryForMBeanOperations = new HashMap<>();

          for (String domain : domains.keySet()) {
            Map<String, Object> domainMBeansCheck = new HashMap<>(domains.get(domain));
            Map<String, Object> domainMBeans = domains.get(domain);
            for (String name : domainMBeansCheck.keySet()) {
              Object mBeanInfo = domainMBeansCheck.get(name);
              String fullName = domain + ":" + name;
              ObjectName n = new ObjectName(fullName);
              if (mBeanInfo instanceof Map) {
                // not shared JSONified MBeanInfo
                prepareKarafRbacInvocations(
                    fullName,
                    (Map<String, Object>) mBeanInfo,
                    queryForMBeans,
                    queryForMBeanOperations);
              } else /*if (mBeanInfo instanceof String)*/ {
                // shared JSONified MBeanInfo

                // shard mbeanNames sharing MBeanInfo by the hierarchy of jmx.acl* PIDs used to
                // check RBAC info
                String key = (String) mBeanInfo;
                String pidListKey = pidListKey(allJmxAclPids, n);
                if (!rbacCache.containsKey(key + ":" + pidListKey)) {
                  // shallow copy - we can share op/not/attr/desc, but we put specific
                  // canInvoke/opByString keys
                  HashMap<String, Object> sharedMBeanAndRbacInfo = new HashMap<>(cache.get(key));
                  rbacCache.put(key + ":" + pidListKey, sharedMBeanAndRbacInfo);
                  // we'll be checking RBAC only for single (first) MBean having this pidListKey
                  prepareKarafRbacInvocations(
                      fullName, sharedMBeanAndRbacInfo, queryForMBeans, queryForMBeanOperations);
                }
                // switch key from shared MBeanInfo-only to shared MBean+RbacInfo
                domainMBeans.put(name, key + ":" + pidListKey);
              }
            }
          }

          // RBAC per MBeans (can invoke *any* operation or attribute?)
          TabularData dataForMBeans = jmxSec.canInvoke(queryForMBeans);
          Collection<?> results = dataForMBeans.values();
          for (Object cd : results) {
            ObjectName objectName = new ObjectName((String) ((CompositeData) cd).get("ObjectName"));
            boolean canInvoke =
                ((CompositeData) cd).get("CanInvoke") != null
                    ? (Boolean) ((CompositeData) cd).get("CanInvoke")
                    : false;
            Object mBeanInfoOrKey =
                domains.get(objectName.getDomain()).get(objectName.getKeyPropertyListString());
            Map<String, Object> mBeanInfo;
            if (mBeanInfoOrKey instanceof Map) {
              mBeanInfo = (Map<String, Object>) mBeanInfoOrKey;
            } else /*if (mBeanInfoOrKey instanceof String) */ {
              mBeanInfo = rbacCache.get(mBeanInfoOrKey.toString());
            }
            if (mBeanInfo != null) {
              mBeanInfo.put("canInvoke", canInvoke);
            }
          }

          // RBAC per { MBean,operation } (can invoke status for each operation)
          TabularData dataForMBeanOperations = jmxSec.canInvoke(queryForMBeanOperations);
          results = dataForMBeanOperations.values();
          for (Object cd : results) {
            ObjectName objectName = new ObjectName((String) ((CompositeData) cd).get("ObjectName"));
            String method = (String) ((CompositeData) cd).get("Method");
            boolean canInvoke =
                ((CompositeData) cd).get("CanInvoke") != null
                    ? (Boolean) ((CompositeData) cd).get("CanInvoke")
                    : false;
            Object mBeanInfoOrKey =
                domains.get(objectName.getDomain()).get(objectName.getKeyPropertyListString());
            Map<String, Object> mBeanInfo;
            if (mBeanInfoOrKey instanceof Map) {
              mBeanInfo = (Map<String, Object>) mBeanInfoOrKey;
            } else /*if (mBeanInfoOrKey instanceof String) */ {
              mBeanInfo = rbacCache.get(mBeanInfoOrKey.toString());
            }
            if (mBeanInfo != null) {
              ((Map<String, Object>)
                      ((Map<String, Object>) mBeanInfo.get("opByString")).get(method))
                  .put("canInvoke", canInvoke);
            }
          }

          result.remove("cache");
          result.put("cache", rbacCache);
        }
      }
    } catch (Exception e) {
      LOG.error(e.getMessage(), e);
      // simply do not decorate
    }
  }
 private String getPath(final ObjectName name) {
   return name.getDomain();
 }
 public MBean(ObjectName objectName, MBeanInfo mBeanInfo) {
   _domainName = objectName.getDomain();
   _mBeanName = objectName.getKeyPropertyListString();
   _mBeanInfo = mBeanInfo;
   _loaded = true;
 }
  @Override
  public List<Map<String, String>> getRoutes(String camelContextName, String filter)
      throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    List<Map<String, String>> answer = new ArrayList<Map<String, String>>();

    ObjectName found = camelContextName != null ? lookupCamelContext(camelContextName) : null;
    if (found != null) {

      String pattern =
          String.format(
              "%s:context=%s,type=routes,*", found.getDomain(), found.getKeyProperty("context"));
      J4pSearchResponse sr = jolokia.execute(new J4pSearchRequest(pattern));

      List<J4pReadRequest> list = new ArrayList<J4pReadRequest>();
      for (ObjectName on : sr.getObjectNames()) {
        list.add(new J4pReadRequest(on, "CamelId", "RouteId", "State"));
      }

      List<J4pReadResponse> lrr = jolokia.execute(list);
      for (J4pReadResponse rr : lrr) {
        String routeId = rr.getValue("RouteId").toString();
        if (filter == null || routeId.matches(filter)) {
          Map<String, String> row = new LinkedHashMap<String, String>();
          row.put("camelContextName", rr.getValue("CamelId").toString());
          row.put("routeId", routeId);
          row.put("state", rr.getValue("State").toString());
          answer.add(row);
        }
      }

    } else {
      List<Map<String, String>> camelContexts = this.getCamelContexts();
      for (Map<String, String> row : camelContexts) {
        List<Map<String, String>> routes = getRoutes(row.get("name"), filter);
        answer.addAll(routes);
      }
    }

    // sort the list
    Collections.sort(
        answer,
        new Comparator<Map<String, String>>() {
          @Override
          public int compare(Map<String, String> o1, Map<String, String> o2) {
            // group by camel context first, then by route name
            String c1 = o1.get("camelContextName");
            String c2 = o2.get("camelContextName");

            int answer = c1.compareTo(c2);
            if (answer == 0) {
              // okay from same camel context, then sort by route id
              answer = o1.get("routeId").compareTo(o2.get("routeId"));
            }
            return answer;
          }
        });
    return answer;
  }
  @Override
  public Map<String, Object> getCamelContextInformation(String camelContextName) throws Exception {
    if (jolokia == null) {
      throw new IllegalStateException("Need to connect to remote jolokia first");
    }

    Map<String, Object> answer = new LinkedHashMap<String, Object>();

    ObjectName found = lookupCamelContext(camelContextName);
    if (found != null) {

      String pattern =
          String.format(
              "%s:context=%s,type=services,name=DefaultTypeConverter",
              found.getDomain(), found.getKeyProperty("context"));
      ObjectName tc = ObjectName.getInstance(pattern);

      String pattern2 =
          String.format(
              "%s:context=%s,type=services,name=DefaultAsyncProcessorAwaitManager",
              found.getDomain(), found.getKeyProperty("context"));
      ObjectName am = ObjectName.getInstance(pattern2);

      List<J4pReadRequest> list = new ArrayList<J4pReadRequest>();
      list.add(new J4pReadRequest(found));
      list.add(new J4pReadRequest(tc));
      list.add(new J4pReadRequest(am));

      List<J4pReadResponse> rr = jolokia.execute(list);
      if (rr != null && rr.size() > 0) {
        // camel context attributes
        J4pReadResponse first = rr.get(0);
        for (String key : first.getAttributes()) {
          answer.put(asKey(key), first.getValue(key));
        }

        // type converter attributes
        if (rr.size() >= 2) {
          J4pReadResponse second = rr.get(1);
          for (String key : second.getAttributes()) {
            answer.put("typeConverter." + asKey(key), second.getValue(key));
          }
        }

        // async processor await manager attributes
        if (rr.size() >= 3) {
          J4pReadResponse second = rr.get(2);
          for (String key : second.getAttributes()) {
            answer.put("asyncProcessorAwaitManager." + asKey(key), second.getValue(key));
          }
        }
      }

      // would be great if there was an api in jolokia to read optional (eg ignore if an mbean does
      // not exists)
      answer.put("streamCachingEnabled", false);
      try {
        pattern =
            String.format(
                "%s:context=%s,type=services,name=DefaultStreamCachingStrategy",
                found.getDomain(), found.getKeyProperty("context"));
        ObjectName sc = ObjectName.getInstance(pattern);

        // there is only a mbean if stream caching is enabled
        J4pReadResponse rsc = jolokia.execute(new J4pReadRequest(sc));
        if (rsc != null) {
          for (String key : rsc.getAttributes()) {
            answer.put("streamCaching." + asKey(key), rsc.getValue(key));
          }
        }
        answer.put("streamCachingEnabled", true);
      } catch (J4pRemoteException e) {
        // ignore
        boolean ignore = InstanceNotFoundException.class.getName().equals(e.getErrorType());
        if (!ignore) {
          throw e;
        }
      }

      // store some data using special names as that is what the core-commands expects
      answer.put("name", answer.get("camelId"));
      answer.put("status", answer.get("state"));
      answer.put("version", answer.get("camelVersion"));
      answer.put("suspended", "Suspended".equals(answer.get("state")));
      TimeUnit unit = TimeUnit.valueOf((String) answer.get("timeUnit"));
      long timeout = (Long) answer.get("timeout");
      answer.put("shutdownTimeout", "" + unit.toSeconds(timeout));
      answer.put("applicationContextClassLoader", answer.get("applicationContextClassName"));
    }

    return answer;
  }
  public MBean(ObjectName objectName) {
    this(objectName.getDomain(), objectName.getKeyPropertyListString());

    _objectName = objectName;
  }