Example #1
0
 public void test(TestHarness h) {
   ArrayType type = ArrayType.getPrimitiveArrayType(int[].class);
   h.check(!type.isValue(null), "Null value check");
   h.check(!type.isValue(3), "Non-array value check");
   h.check(type.isValue(new int[] {3}), "Primitive int array value check");
   h.check(!type.isValue(new Integer[] {3}), "Integer array value check");
   try {
     CompositeType ctype =
         new CompositeType(
             "Test",
             "Test",
             new String[] {"name"},
             new String[] {"Name"},
             new OpenType[] {SimpleType.STRING});
     Map<String, String> data = new HashMap<String, String>();
     data.put("name", "Bob");
     CompositeData cdata = new CompositeDataSupport(ctype, data);
     CompositeData[] cdataarr = new CompositeData[] {cdata};
     ArrayType type2 = new ArrayType(1, ctype);
     h.check(type2.isValue(cdataarr), "Composite data check");
     TabularType ttype = new TabularType("Test", "Test", ctype, new String[] {"name"});
     TabularData tdata = new TabularDataSupport(ttype);
     tdata.put(cdata);
     TabularData[] tdataarr = new TabularData[] {tdata};
     ArrayType type3 = new ArrayType(1, ttype);
     h.check(type3.isValue(tdataarr), "Tabular data check");
   } catch (OpenDataException e) {
     h.debug(e);
   }
 }
  /**
   * Adds the attribute to the given list.
   *
   * @param mBeanAttributes The attributes
   * @param root The root attribute
   * @param value The value
   */
  private void addAttributeRoots(
      List<AttributeNode> mBeanAttributes, AttributeNode root, Object value) {
    if (value instanceof CompositeData) {
      mBeanAttributes.add(root);
      CompositeData compositeData = (CompositeData) value;
      CompositeType type = compositeData.getCompositeType();
      for (String key : type.keySet()) {
        AttributeNode attribute = new AttributeNode(key, root);

        root.addChild(attribute);
        addAttributeItems(attribute, compositeData.get(key));
      }
    } else if (value instanceof TabularData) {
      mBeanAttributes.add(root);
      TabularData tabularData = (TabularData) value;
      for (Object keyList : tabularData.keySet()) {
        @SuppressWarnings("unchecked")
        Object[] keys = ((List<Object>) keyList).toArray(new Object[0]);
        AttributeNode attribute = new AttributeNode(String.valueOf(keys[0]), root);

        root.addChild(attribute);
        addAttributeItems(attribute, tabularData.get(keys));
      }
    } else if (value instanceof Long || value instanceof Integer || value instanceof Double) {
      root.setValidLeaf(true);
      root.setRgb(getRGB(root.getQualifiedName()));
      mBeanAttributes.add(root);
    }
  }
Example #3
0
  public static TabularData createTable(ResultSet rs) throws Exception {
    ResultSetMetaData rsMetaData = rs.getMetaData();
    int numCols = rsMetaData.getColumnCount();
    String[] headers = new String[numCols];
    OpenType[] allTypes = new OpenType[numCols];
    Vector[] values = new Vector[numCols];
    Object[] allValues = new Object[numCols];

    for (int i = 0; i < numCols; i++) {
      headers[i] = rsMetaData.getColumnName(i + 1);
      allTypes[i] = new ArrayType(1, SimpleType.STRING);
      values[i] = new Vector();
    }

    CompositeType ct =
        new CompositeType("column and values", "column and values", headers, headers, allTypes);
    TabularType tt = new TabularType("column and values", "column with values", ct, headers);
    TabularData td = new TabularDataSupport(tt);

    while (rs.next()) {
      for (int i = 0; i < numCols; i++) {
        values[i].add(rs.getString(i + 1));
      }
    }

    for (int i = 0; i < numCols; i++) {
      allValues[i] = (String[]) values[i].toArray(new String[0]);
    }

    CompositeData entry = new CompositeDataSupport(ct, headers, allValues);
    td.put(entry);
    return td;
  }
Example #4
0
  public TabularData listEips() throws Exception {
    try {
      // find all EIPs
      Map<String, Properties> eips = context.findEips();

      TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.listEipsTabularType());

      // gather EIP detail for each eip
      for (Map.Entry<String, Properties> entry : eips.entrySet()) {
        String name = entry.getKey();
        String title = (String) entry.getValue().get("title");
        String description = (String) entry.getValue().get("description");
        String label = (String) entry.getValue().get("label");
        String type = (String) entry.getValue().get("class");
        String status = CamelContextHelper.isEipInUse(context, name) ? "in use" : "on classpath";
        CompositeType ct = CamelOpenMBeanTypes.listEipsCompositeType();
        CompositeData data =
            new CompositeDataSupport(
                ct,
                new String[] {"name", "title", "description", "label", "status", "type"},
                new Object[] {name, title, description, label, status, type});
        answer.put(data);
      }
      return answer;
    } catch (Exception e) {
      throw ObjectHelper.wrapRuntimeCamelException(e);
    }
  }
  @Test
  public void testByteArrayObject() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT, ModelType.BYTES);
    TypeConverter converter = getConverter(description);

    assertMapType(
        assertCast(TabularType.class, converter.getOpenType()),
        SimpleType.STRING,
        ArrayType.getPrimitiveArrayType(byte[].class));

    ModelNode node = new ModelNode();
    node.get("one").set(new byte[] {1, 2});
    node.get("two").set(new byte[] {3, 4});

    TabularData tabularData = assertCast(TabularData.class, converter.fromModelNode(node));
    Assert.assertEquals(2, tabularData.size());
    Assert.assertTrue(
        Arrays.equals(
            new byte[] {1, 2}, (byte[]) tabularData.get(new Object[] {"one"}).get("value")));
    Assert.assertTrue(
        Arrays.equals(
            new byte[] {3, 4}, (byte[]) tabularData.get(new Object[] {"two"}).get("value")));

    // Allow plain map as well? Yeah why not!
    Map<String, byte[]> map = new HashMap<String, byte[]>();
    map.put("one", new byte[] {1, 2});
    map.put("two", new byte[] {3, 4});
    Assert.assertEquals(node, converter.toModelNode(map));
  }
  @Test
  public void testSimpleTypeObject() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT, ModelType.LONG);
    TypeConverter converter = getConverter(description);

    assertMapType(
        assertCast(TabularType.class, converter.getOpenType()), SimpleType.STRING, SimpleType.LONG);

    ModelNode node = new ModelNode();
    node.get("one").set(1L);
    node.get("two").set(2L);

    TabularData tabularData = assertCast(TabularData.class, converter.fromModelNode(node));
    Assert.assertEquals(2, tabularData.size());
    Assert.assertEquals(Long.valueOf(1), tabularData.get(new Object[] {"one"}).get("value"));
    Assert.assertEquals(Long.valueOf(2), tabularData.get(new Object[] {"two"}).get("value"));

    Assert.assertEquals(node, converter.toModelNode(tabularData));

    // Allow plain map as well? Yeah why not!
    Map<String, Long> map = new HashMap<String, Long>();
    map.put("one", 1L);
    map.put("two", 2L);
    Assert.assertEquals(node, converter.toModelNode(map));
  }
  public void testManageMarshal() throws Exception {
    // JMX tests dont work well on AIX CI servers (hangs them)
    if (isPlatform("aix")) {
      return;
    }

    MockEndpoint foo = getMockEndpoint("mock:foo");
    foo.expectedMessageCount(1);

    template.sendBodyAndHeader("direct:start", "Hello World", "foo", "123");

    assertMockEndpointsSatisfied();

    // get the stats for the route
    MBeanServer mbeanServer = getMBeanServer();

    // get the object name for the delayer
    ObjectName on =
        ObjectName.getInstance("org.apache.camel:context=camel-1,type=processors,name=\"mysend\"");

    // should be on route1
    String routeId = (String) mbeanServer.getAttribute(on, "RouteId");
    assertEquals("route1", routeId);

    String camelId = (String) mbeanServer.getAttribute(on, "CamelId");
    assertEquals("camel-1", camelId);

    String state = (String) mbeanServer.getAttribute(on, "State");
    assertEquals(ServiceStatus.Started.name(), state);

    String name = (String) mbeanServer.getAttribute(on, "DataFormatName");
    assertEquals("string", name);

    String xml = (String) mbeanServer.invoke(on, "dumpProcessorAsXml", null, null);
    assertTrue(xml.contains("<marshal"));
    assertTrue(xml.contains("</marshal>"));
    assertTrue(xml.contains("<string charset=\"iso-8859-1\"/>"));

    TabularData data =
        (TabularData)
            mbeanServer.invoke(on, "explain", new Object[] {false}, new String[] {"boolean"});
    assertNotNull(data);
    assertEquals(2, data.size());

    data =
        (TabularData)
            mbeanServer.invoke(on, "explain", new Object[] {true}, new String[] {"boolean"});
    assertNotNull(data);
    assertEquals(4, data.size());

    String json = (String) mbeanServer.invoke(on, "informationJson", null, null);
    assertNotNull(json);
    assertTrue(
        json.contains(
            "\"description\": \"Marshals data into a specified format for transmission over a transport or component"));
  }
Example #8
0
 /**
  * {@inheritDoc}
  *
  * @see HibernateStats#getEntityStats()
  */
 public TabularData getEntityStats() {
   List<CompositeData> result = new ArrayList<CompositeData>();
   Statistics statistics = getStatistics();
   for (String entity : statistics.getEntityNames()) {
     EntityStats entityStats = new EntityStats(entity, statistics.getEntityStatistics(entity));
     result.add(entityStats.toCompositeData());
   }
   TabularData td = EntityStats.newTabularDataInstance();
   td.putAll(result.toArray(new CompositeData[result.size()]));
   return td;
 }
Example #9
0
 /**
  * {@inheritDoc}
  *
  * @see HibernateStats#getQueryStats()
  */
 public TabularData getQueryStats() {
   List<CompositeData> result = new ArrayList<CompositeData>();
   Statistics statistics = getStatistics();
   for (String query : statistics.getQueries()) {
     QueryStats queryStats = new QueryStats(query, statistics.getQueryStatistics(query));
     result.add(queryStats.toCompositeData());
   }
   TabularData td = QueryStats.newTabularDataInstance();
   td.putAll(result.toArray(new CompositeData[result.size()]));
   return td;
 }
Example #10
0
 /**
  * {@inheritDoc}
  *
  * @see HibernateStats#getCollectionStats()
  */
 public TabularData getCollectionStats() {
   List<CompositeData> result = new ArrayList<CompositeData>();
   Statistics statistics = getStatistics();
   for (String roleName : statistics.getCollectionRoleNames()) {
     CollectionStats collectionStats =
         new CollectionStats(roleName, statistics.getCollectionStatistics(roleName));
     result.add(collectionStats.toCompositeData());
   }
   TabularData td = CollectionStats.newTabularDataInstance();
   td.putAll(result.toArray(new CompositeData[result.size()]));
   return td;
 }
Example #11
0
 /** {@inheritDoc} */
 public TabularData getCacheRegionStats() {
   List<CompositeData> list = new ArrayList<CompositeData>();
   Statistics statistics = getStatistics();
   for (String region : statistics.getSecondLevelCacheRegionNames()) {
     CacheRegionStats l2CacheStats =
         new CacheRegionStats(region, statistics.getSecondLevelCacheStatistics(region));
     list.add(l2CacheStats.toCompositeData());
   }
   TabularData td = CacheRegionStats.newTabularDataInstance();
   td.putAll(list.toArray(new CompositeData[list.size()]));
   return td;
 }
  public void testManageChoice() throws Exception {
    // JMX tests dont work well on AIX CI servers (hangs them)
    if (isPlatform("aix")) {
      return;
    }

    getMockEndpoint("mock:foo").expectedMessageCount(2);
    getMockEndpoint("mock:bar").expectedMessageCount(1);

    template.sendBodyAndHeader("direct:start", "Hello World", "foo", "123");
    template.sendBodyAndHeader("direct:start", "Bye World", "foo", "456");
    template.sendBodyAndHeader("direct:start", "Hi World", "bar", "789");

    assertMockEndpointsSatisfied();

    // get the stats for the route
    MBeanServer mbeanServer = getMBeanServer();

    // get the object name for the delayer
    ObjectName on =
        ObjectName.getInstance("org.apache.camel:context=camel-1,type=processors,name=\"mysend\"");

    // should be on route1
    String routeId = (String) mbeanServer.getAttribute(on, "RouteId");
    assertEquals("route1", routeId);

    String camelId = (String) mbeanServer.getAttribute(on, "CamelId");
    assertEquals("camel-1", camelId);

    String state = (String) mbeanServer.getAttribute(on, "State");
    assertEquals(ServiceStatus.Started.name(), state);

    TabularData data = (TabularData) mbeanServer.invoke(on, "choiceStatistics", null, null);
    assertNotNull(data);
    assertEquals(2, data.size());

    data =
        (TabularData)
            mbeanServer.invoke(on, "explain", new Object[] {false}, new String[] {"boolean"});
    assertNotNull(data);
    assertEquals(3, data.size());

    data =
        (TabularData)
            mbeanServer.invoke(on, "explain", new Object[] {true}, new String[] {"boolean"});
    assertNotNull(data);
    assertEquals(4, data.size());

    String json = (String) mbeanServer.invoke(on, "informationJson", null, null);
    assertNotNull(json);
    assertTrue(json.contains("\"description\": \"Routes messages based on a series of predicates"));
  }
Example #13
0
 public TabularData listCoordinations(String regexFilter) {
   Pattern p = Pattern.compile(regexFilter);
   TabularData td = new TabularDataSupport(COORDINATIONS_TYPE);
   for (CoordinationImpl c : coordinations.values()) {
     if (p.matcher(c.getName()).matches()) {
       try {
         td.put(fromCoordination(c));
       } catch (OpenDataException e) {
         // TODO: log
       }
     }
   }
   return td;
 }
Example #14
0
  @Override
  public TabularData getConnectionList() throws JMException {
    CompositeType rowType = JdbcConnectionStat.Entry.getCompositeType();
    String[] indexNames = rowType.keySet().toArray(new String[rowType.keySet().size()]);

    TabularType tabularType =
        new TabularType("ConnectionListStatistic", "ConnectionListStatistic", rowType, indexNames);
    TabularData data = new TabularDataSupport(tabularType);

    for (Map.Entry<Long, JdbcConnectionStat.Entry> entry : getConnections().entrySet()) {
      data.put(entry.getValue().getCompositeData());
    }

    return data;
  }
  protected void setUp() throws Exception {
    TabularData sqlList = JdbcStatManager.getInstance().getSqlList();
    if (sqlList.size() > 0) {
      for (Object item : JdbcStatManager.getInstance().getSqlList().values()) {
        String text = JSONUtils.toJSONString(item);
        System.out.println(text);
      }
    }

    Assert.assertEquals(0, JdbcStatManager.getInstance().getSqlList().size());

    dataSource = new DruidDataSource();
    dataSource.setUrl("jdbc:mock:xx");
    dataSource.setFilters("mergeStat");
    dataSource.setDbType("mysql");
  }
Example #16
0
  @Override
  public TabularData getSqlList() throws JMException {
    Map<String, JdbcSqlStat> sqlStatMap = this.getSqlStatMap();
    CompositeType rowType = JdbcSqlStat.getCompositeType();
    String[] indexNames = rowType.keySet().toArray(new String[rowType.keySet().size()]);

    TabularType tabularType =
        new TabularType("SqlListStatistic", "SqlListStatistic", rowType, indexNames);
    TabularData data = new TabularDataSupport(tabularType);

    for (Map.Entry<String, JdbcSqlStat> entry : sqlStatMap.entrySet()) {
      data.put(entry.getValue().getCompositeData());
    }

    return data;
  }
  /**
   * Reads in the numeric value of mapped to the tabularDataKey value specified when this object was
   * created
   *
   * @param jmxConnection
   * @param f
   * @param beanName
   * @throws Exception
   */
  protected void readValueFromBean(
      MBeanServerConnection jmxConnection, AggregateFunction f, ObjectName beanName)
      throws Exception {
    checkBeanExists(jmxConnection, beanName);
    Object attribute = safelyGetAttribute(jmxConnection, beanName);

    if (!(attribute instanceof TabularData)) {
      raiseValueException("The attribute was not of type TabularData");
    }

    TabularData tabularData = (TabularData) attribute;
    Object[] key = {tabularDataKey};

    if (!tabularData.containsKey(key)) {
      raiseValueException("No value is available for the key Object[] {" + tabularDataKey + "}");
    }

    CompositeData compositeData = null;
    try {
      compositeData = tabularData.get(key);
    } catch (InvalidKeyException k) {
      raiseValueException("The TabularDataKey " + tabularDataKey + " was invalid", k);
    }

    if (compositeData == null) {
      raiseValueException(
          "Even after checking the TabularDataKey "
              + tabularDataKey
              + " existed, we were still return a null value");
      // key asynchronously removed on remote server?, probably possible, but never seen it
    }

    Object value = getValueFromCompositeData(compositeData, "value");
    if (value == null) {
      raiseValueException(
          "The value attribute of the CompositeDataItem with tabular key "
              + tabularDataKey
              + " was null");
    }

    Double v = convertToDouble(value);

    // yippee! after all this checking we actually have a value!
    f.addValue(v);
  }
  @Test
  public void testSimpleTypeObjectExpressions() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT, ModelType.LONG);
    description.get(EXPRESSIONS_ALLOWED).set(true);
    TypeConverter converter = getConverter(description);

    assertMapType(
        assertCast(TabularType.class, converter.getOpenType()), SimpleType.STRING, SimpleType.LONG);

    ModelNode node = new ModelNode();
    node.get("one").setExpression("${this.should.not.exist.!!!!!:1}");
    node.get("two").setExpression("${this.should.not.exist.!!!!!:2}");

    TabularData tabularData = assertCast(TabularData.class, converter.fromModelNode(node));
    Assert.assertEquals(2, tabularData.size());
    Assert.assertEquals(Long.valueOf(1), tabularData.get(new Object[] {"one"}).get("value"));
    Assert.assertEquals(Long.valueOf(2), tabularData.get(new Object[] {"two"}).get("value"));
  }
Example #19
0
 private static String getProperty(TabularData td, String propName) {
   CompositeData cd = td.get(new Object[] {propName});
   if (cd != null) {
     String key = (String) cd.get("key");
     if (!propName.equals(key)) {
       throw new RuntimeException(
           "TEST FAILED: " + key + " property found" + " but expected to be " + propName);
     }
     return (String) cd.get("value");
   }
   return null;
 }
  @Test
  public void testSimpleTypeObjectEmpty() throws Exception {
    ModelNode description = createDescription(ModelType.OBJECT, ModelType.LONG);
    TypeConverter converter = getConverter(description);

    assertMapType(
        assertCast(TabularType.class, converter.getOpenType()), SimpleType.STRING, SimpleType.LONG);

    ModelNode node = new ModelNode();
    node.get("one").set("");
    node.get("two").set("");

    TabularData tabularData = assertCast(TabularData.class, converter.fromModelNode(node));
    Assert.assertEquals(2, tabularData.size());
    Assert.assertNull(tabularData.get(new Object[] {"one"}).get("value"));
    Assert.assertNull(tabularData.get(new Object[] {"two"}).get("value"));

    ModelNode expected = new ModelNode();
    expected.get("one");
    expected.get("two");

    Assert.assertEquals(expected, converter.toModelNode(tabularData));
  }
  /**
   * Gets the initial file name.
   *
   * @param jvm The active JVM
   * @return The file name, or <tt>null</tt> if file name is specified
   * @throws JvmCoreException
   */
  String getInitialFileName(IActiveJvm jvm) throws JvmCoreException {

    ObjectName objectName;
    try {
      objectName = new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
    } catch (MalformedObjectNameException e) {
      throw new JvmCoreException(IStatus.ERROR, e.getMessage(), e);
    } catch (NullPointerException e) {
      throw new JvmCoreException(IStatus.ERROR, e.getMessage(), e);
    }

    TabularData initialName =
        (TabularData)
            jvm.getMBeanServer().getAttribute(objectName, "SystemProperties"); // $NON-NLS-1$
    CompositeData compisiteData = initialName.get(new Object[] {"user.home"}); // $NON-NLS-1$
    String home = compisiteData.values().toArray(new String[0])[1];
    StringBuffer initialFileName = new StringBuffer(home);
    initialFileName
        .append(File.separator)
        .append(new Date().getTime())
        .append('.')
        .append(SnapshotType.Hprof.getExtension());
    return initialFileName.toString();
  }
Example #22
0
 private int getInstancesNum(MBeanServerConnection connection, ObjectName name) throws Exception {
   TabularData instances = (TabularData) connection.getAttribute(name, "Instances");
   return instances.size();
 }
Example #23
0
  /**
   * 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
    }
  }
Example #24
0
  @Override
  public TabularData listComponents() throws Exception {
    try {
      // find all components
      Map<String, Properties> components = context.findComponents();

      TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.listComponentsTabularType());

      // gather component detail for each component
      for (Map.Entry<String, Properties> entry : components.entrySet()) {
        String name = entry.getKey();
        String title = null;
        String syntax = null;
        String description = null;
        String label = null;
        String deprecated = null;
        String status = context.hasComponent(name) != null ? "in use" : "on classpath";
        String type = (String) entry.getValue().get("class");
        String groupId = null;
        String artifactId = null;
        String version = null;

        // a component may have been given a different name, so resolve its default name by its java
        // type
        // as we can find the component json information from the default component name
        String defaultName = context.resolveComponentDefaultName(type);
        String target = defaultName != null ? defaultName : name;

        // load component json data, and parse it to gather the component meta-data
        String json = context.getComponentParameterJsonSchema(target);
        List<Map<String, String>> rows = JsonSchemaHelper.parseJsonSchema("component", json, false);
        for (Map<String, String> row : rows) {
          if (row.containsKey("title")) {
            title = row.get("title");
          } else if (row.containsKey("syntax")) {
            syntax = row.get("syntax");
          } else if (row.containsKey("description")) {
            description = row.get("description");
          } else if (row.containsKey("label")) {
            label = row.get("label");
          } else if (row.containsKey("deprecated")) {
            deprecated = row.get("deprecated");
          } else if (row.containsKey("javaType")) {
            type = row.get("javaType");
          } else if (row.containsKey("groupId")) {
            groupId = row.get("groupId");
          } else if (row.containsKey("artifactId")) {
            artifactId = row.get("artifactId");
          } else if (row.containsKey("version")) {
            version = row.get("version");
          }
        }

        CompositeType ct = CamelOpenMBeanTypes.listComponentsCompositeType();
        CompositeData data =
            new CompositeDataSupport(
                ct,
                new String[] {
                  "name",
                  "title",
                  "syntax",
                  "description",
                  "label",
                  "deprecated",
                  "status",
                  "type",
                  "groupId",
                  "artifactId",
                  "version"
                },
                new Object[] {
                  name,
                  title,
                  syntax,
                  description,
                  label,
                  deprecated,
                  status,
                  type,
                  groupId,
                  artifactId,
                  version
                });
        answer.put(data);
      }
      return answer;
    } catch (Exception e) {
      throw ObjectHelper.wrapRuntimeCamelException(e);
    }
  }