下面列出了怎么用javax.management.openmbean.TabularData的API类实例代码及写法,或者点击链接到github查看源代码。
public TabularData getAllTriggers(String instanceId)
throws SchedulerException {
SchedulingContext cntx = new SchedulingContext(instanceId);
List<Trigger> triggerList = new ArrayList<Trigger>();
for (String triggerGroupName : scheduler.getTriggerGroupNames(cntx)) {
for (String triggerName : scheduler.getTriggerNames(cntx,
triggerGroupName)) {
triggerList.add(scheduler.getTrigger(cntx, triggerName,
triggerGroupName));
}
}
return TriggerSupport.toTabularData(triggerList
.toArray(new Trigger[triggerList.size()]));
}
private void verifyEquals(TabularData actualData, Map<String, Long>
expectedData) {
if (actualData == null || expectedData == null) {
fail("Data should not be null.");
}
for (Object obj : actualData.values()) {
assertTrue(obj instanceof CompositeData);
CompositeData cds = (CompositeData) obj;
assertEquals(2, cds.values().size());
Iterator<?> it = cds.values().iterator();
String key = it.next().toString();
String value = it.next().toString();
long num = Long.parseLong(value);
assertTrue(expectedData.containsKey(key));
assertEquals(expectedData.remove(key).longValue(), num);
}
assertTrue(expectedData.isEmpty());
}
@Override
final Object fromNonNullOpenValue(Object openValue)
throws InvalidObjectException {
final TabularData table = (TabularData) openValue;
final Collection<CompositeData> rows = cast(table.values());
final Map<Object, Object> valueMap =
sortedMap ? newSortedMap() : newInsertionOrderMap();
for (CompositeData row : rows) {
final Object key =
keyMapping.fromOpenValue(row.get("key"));
final Object value =
valueMapping.fromOpenValue(row.get("value"));
if (valueMap.put(key, value) != null) {
final String msg =
"Duplicate entry in TabularData: key=" + key;
throw new InvalidObjectException(msg);
}
}
return valueMap;
}
private static Object convertFromTabularDataToMap( Object value ) {
final TabularData data = ( TabularData ) value;
final Set<List<?>> keys = ( Set<List<?>> ) data.keySet();
final Map<String, Object> map = new HashMap<>();
for ( final List<?> key : keys ) {
final Object subValue = convertValue( data.get( key.toArray() ) );
if ( key.size() == 1 ) {
map.put( convertValue( key.get( 0 ) ).toString(), subValue );
} else {
map.put( convertValue( key ).toString(), subValue );
}
}
value = map;
return value;
}
private static Map<String, String> createMap(Object o) {
if (o instanceof TabularData) {
TabularData td = (TabularData) o;
Collection<?> values = td.values();
Map<String, String> map = new HashMap<>(values.size());
for (Object value : td.values()) {
if (value instanceof CompositeData) {
CompositeData cdRow = (CompositeData) value;
Object k = cdRow.get("key");
Object v = cdRow.get("value");
if (k instanceof String && v instanceof String) {
map.put((String) k, (String) v);
}
}
}
return Collections.unmodifiableMap(map);
}
return Collections.emptyMap();
}
@Override
public String toString() {
if(value == null) return null;
if(value.getClass().isArray()) {
String name =
Utils.getArrayClassName(value.getClass().getName());
int length = Array.getLength(value);
return name + "[" + length +"]";
}
if(value instanceof CompositeData ||
value instanceof TabularData)
return value.getClass().getName();
return value.toString();
}
@Override
@Effector(description="Updates the OSGi Service's properties, adding (and overriding) the given key-value pairs")
public void updateServiceProperties(
@EffectorParam(name="serviceName", description="Name of the OSGi service") String serviceName,
Map<String,String> additionalVals) {
TabularData table = (TabularData) jmxHelper.operation(OSGI_COMPENDIUM, "getProperties", serviceName);
try {
for (Map.Entry<String, String> entry: additionalVals.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
CompositeData data = new CompositeDataSupport(
JmxConstants.PROPERTY_TYPE,
MutableMap.of(JmxConstants.KEY, key, JmxConstants.TYPE, "String", JmxConstants.VALUE, value));
table.remove(data.getAll(new String[] {JmxConstants.KEY}));
table.put(data);
}
} catch (OpenDataException e) {
throw Exceptions.propagate(e);
}
LOG.info("Updating monterey-service configuration with changes {}", additionalVals);
if (LOG.isTraceEnabled()) LOG.trace("Updating monterey-service configuration with new configuration {}", table);
jmxHelper.operation(OSGI_COMPENDIUM, "update", serviceName, table);
}
private static Map<String, String> createMap(Object o) {
if (o instanceof TabularData) {
TabularData td = (TabularData) o;
Collection<?> values = td.values();
Map<String, String> map = new HashMap<>(values.size());
for (Object value : td.values()) {
if (value instanceof CompositeData) {
CompositeData cdRow = (CompositeData) value;
Object k = cdRow.get("key");
Object v = cdRow.get("value");
if (k instanceof String && v instanceof String) {
map.put((String) k, (String) v);
}
}
}
return Collections.unmodifiableMap(map);
}
return Collections.emptyMap();
}
@Override
final Object fromNonNullOpenValue(Object openValue)
throws InvalidObjectException {
final TabularData table = (TabularData) openValue;
final Collection<CompositeData> rows = cast(table.values());
final Map<Object, Object> valueMap =
sortedMap ? newSortedMap() : newInsertionOrderMap();
for (CompositeData row : rows) {
final Object key =
keyMapping.fromOpenValue(row.get("key"));
final Object value =
valueMapping.fromOpenValue(row.get("value"));
if (valueMap.put(key, value) != null) {
final String msg =
"Duplicate entry in TabularData: key=" + key;
throw new InvalidObjectException(msg);
}
}
return valueMap;
}
@Override
final Object fromNonNullOpenValue(Object openValue)
throws InvalidObjectException {
final TabularData table = (TabularData) openValue;
final Collection<CompositeData> rows = cast(table.values());
final Map<Object, Object> valueMap =
sortedMap ? newSortedMap() : newInsertionOrderMap();
for (CompositeData row : rows) {
final Object key =
keyMapping.fromOpenValue(row.get("key"));
final Object value =
valueMapping.fromOpenValue(row.get("value"));
if (valueMap.put(key, value) != null) {
final String msg =
"Duplicate entry in TabularData: key=" + key;
throw new InvalidObjectException(msg);
}
}
return valueMap;
}
protected static StringBuffer recurseTabularData(StringBuffer buffer, String indent, String name,
TabularData data) {
addNameToBuffer(buffer, indent, name);
java.util.Collection c = data.values();
for (Iterator i = c.iterator(); i.hasNext();) {
Object obj = i.next();
if (obj instanceof CompositeData) {
recurseCompositeData(buffer, indent + " ", "", (CompositeData) obj);
} else if (obj instanceof TabularData) {
recurseTabularData(buffer, indent, "", (TabularData) obj);
} else {
buffer.append(obj);
}
}
return buffer;
}
protected static StringBuffer recurseCompositeData(StringBuffer buffer, String indent, String name,
CompositeData data) {
indent = addNameToBuffer(buffer, indent, name);
for (Iterator i = data.getCompositeType().keySet().iterator(); i.hasNext();) {
String key = (String) i.next();
Object o = data.get(key);
if (o instanceof CompositeData) {
recurseCompositeData(buffer, indent + " ", key, (CompositeData) o);
} else if (o instanceof TabularData) {
recurseTabularData(buffer, indent, key, (TabularData) o);
} else {
buffer.append(indent);
buffer.append(key);
buffer.append(": ");
buffer.append(o);
buffer.append("\n");
}
}
return buffer;
}
protected static StringBuffer recurseCompositeData(StringBuffer buffer, String indent, String name,
CompositeData data) {
indent = addNameToBuffer(buffer, indent, name);
for (Iterator i = data.getCompositeType().keySet().iterator(); i.hasNext();) {
String key = (String) i.next();
Object o = data.get(key);
if (o instanceof CompositeData) {
recurseCompositeData(buffer, indent + " ", key, (CompositeData) o);
} else if (o instanceof TabularData) {
recurseTabularData(buffer, indent, key, (TabularData) o);
} else {
buffer.append(indent);
buffer.append(key);
buffer.append(": ");
buffer.append(o);
buffer.append("\n");
}
}
return buffer;
}
@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));
}
@Override
public String toString() {
if (userData == null) {
return null;
}
if (userData.getClass().isArray()) {
String name =
Utils.getArrayClassName(userData.getClass().getName());
int length = Array.getLength(userData);
return name + "[" + length + "]";
}
if (userData instanceof CompositeData ||
userData instanceof TabularData) {
return userData.getClass().getName();
}
return userData.toString();
}
@Test
public void testGetExecutionCount() throws Exception {
final JobSchedulerViewMBean view = getJobSchedulerMBean();
assertNotNull(view);
assertTrue(view.getAllJobs().isEmpty());
scheduleMessage(10000, 1000, 10);
assertFalse(view.getAllJobs().isEmpty());
TabularData jobs = view.getAllJobs();
assertEquals(1, jobs.size());
String jobId = null;
for (Object key : jobs.keySet()) {
jobId = ((List<?>) key).get(0).toString();
}
final String fixedJobId = jobId;
LOG.info("Attempting to get execution count for Job: {}", jobId);
assertEquals(0, view.getExecutionCount(jobId));
assertTrue("Should execute again", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
return view.getExecutionCount(fixedJobId) > 0;
}
}));
}
@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").set(new ValueExpression("${this.should.not.exist.!!!!!:1}"));
node.get("two").set(new ValueExpression("${this.should.not.exist.!!!!!:2}"));
TabularData tabularData = assertCast(TabularData.class, converter.fromModelNode(node));
Assert.assertEquals(2, tabularData.size());
Assert.assertEquals((long) 1, tabularData.get(new Object[] {"one"}).get("value"));
Assert.assertEquals((long) 2, tabularData.get(new Object[] {"two"}).get("value"));
}
@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));
}
@Override
public String toString() {
if (userData == null) {
return null;
}
if (userData.getClass().isArray()) {
String name =
Utils.getArrayClassName(userData.getClass().getName());
int length = Array.getLength(userData);
return name + "[" + length + "]";
}
if (userData instanceof CompositeData ||
userData instanceof TabularData) {
return userData.getClass().getName();
}
return userData.toString();
}
private TabularData toTabularData(final String typeName, final String description, final Table table)
{
final OpenType<?>[] types = new OpenType<?>[table.getColumnNames().size()];
for (int i = 0; i < types.length; i++)
{
types[i] = SimpleType.STRING;
}
try
{
final String[] keys = table.getColumnNames().toArray(new String[table.getColumnNames().size()]);
final CompositeType ct = new CompositeType(
typeName, description, keys, keys, types);
final TabularType type = new TabularType(typeName, description, ct, keys);
final TabularDataSupport data = new TabularDataSupport(type);
for (final Collection<String> line : table.getLines())
{
data.put(new CompositeDataSupport(ct, keys, line.toArray(new Object[line.size()])));
}
return data;
}
catch (final OpenDataException e)
{
throw new IllegalArgumentException(e);
}
}
@Override
final Object fromNonNullOpenValue(Object openValue)
throws InvalidObjectException {
final TabularData table = (TabularData) openValue;
final Collection<CompositeData> rows = cast(table.values());
final Map<Object, Object> valueMap =
sortedMap ? newSortedMap() : newInsertionOrderMap();
for (CompositeData row : rows) {
final Object key =
keyMapping.fromOpenValue(row.get("key"));
final Object value =
valueMapping.fromOpenValue(row.get("value"));
if (valueMap.put(key, value) != null) {
final String msg =
"Duplicate entry in TabularData: key=" + key;
throw new InvalidObjectException(msg);
}
}
return valueMap;
}
@Override
public String toString() {
if (userData == null) {
return null;
}
if (userData.getClass().isArray()) {
String name =
Utils.getArrayClassName(userData.getClass().getName());
int length = Array.getLength(userData);
return name + "[" + length + "]";
}
if (userData instanceof CompositeData ||
userData instanceof TabularData) {
return userData.getClass().getName();
}
return userData.toString();
}
@Override
final Object fromNonNullOpenValue(Object openValue)
throws InvalidObjectException {
final TabularData table = (TabularData) openValue;
final Collection<CompositeData> rows = cast(table.values());
final Map<Object, Object> valueMap =
sortedMap ? newSortedMap() : newInsertionOrderMap();
for (CompositeData row : rows) {
final Object key =
keyMapping.fromOpenValue(row.get("key"));
final Object value =
valueMapping.fromOpenValue(row.get("value"));
if (valueMap.put(key, value) != null) {
final String msg =
"Duplicate entry in TabularData: key=" + key;
throw new InvalidObjectException(msg);
}
}
return valueMap;
}
@Override
public TabularData getConfigSources()
{
ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader(appConfigClassLoader);
String typeName = "ConfigSources";
OpenType<?>[] types = new OpenType<?>[]{SimpleType.INTEGER, SimpleType.STRING};
String[] keys = new String[]{"Ordinal", "ConfigSource"};
CompositeType ct = new CompositeType(typeName, typeName, keys, keys, types);
TabularType type = new TabularType(typeName, typeName, ct, keys);
TabularDataSupport configSourceInfo = new TabularDataSupport(type);
ConfigSource[] configSources = ConfigResolver.getConfigSources();
for (ConfigSource configSource : configSources)
{
configSourceInfo.put(
new CompositeDataSupport(ct, keys,
new Object[]{configSource.getOrdinal(), configSource.getConfigName()}));
}
return configSourceInfo;
}
catch (OpenDataException e)
{
throw new RuntimeException(e);
}
finally
{
// set back the original TCCL
Thread.currentThread().setContextClassLoader(originalCl);
}
}
/**
* @param tabularData
* @return array of region statistics
*/
public static TabularData toTabularData(
final List<JobExecutionContext> executingJobs)
throws SchedulerException {
List<CompositeData> list = new ArrayList<CompositeData>();
for (final Iterator<JobExecutionContext> iter = executingJobs
.iterator(); iter.hasNext();) {
list.add(toCompositeData(iter.next()));
}
TabularData td = new TabularDataSupport(TABULAR_TYPE);
td.putAll(list.toArray(new CompositeData[list.size()]));
return td;
}
@Test
public void testNodeCount() throws Exception {
ObjectName bean = new ObjectName(
"Hadoop:service=SCMNodeManager,"
+ "name=SCMNodeManagerInfo");
TabularData data = (TabularData) mbs.getAttribute(bean, "NodeCount");
Map<String, Integer> nodeCount = scm.getScmNodeManager().getNodeCount();
Map<String, Long> nodeCountLong = new HashMap<>();
nodeCount.forEach((k, v) -> nodeCountLong.put(k, new Long(v)));
verifyEquals(data, nodeCountLong);
}
private void checkAttributeValues(MBeanServerConnection connection, ObjectName name,
String roInt, String undefinedInt, String i, String bigInt, String bigDecimal,
String bool, byte[] bytes, String dbl, String s, List<String> list, String lng,
String type, String tblKey1, String tblValue1, String tblKey2, String tblValue2) throws Exception {
Assert.assertEquals(roInt, assertCast(String.class, connection.getAttribute(name, "roInt")));
if (undefinedInt == null) {
Assert.assertNull(connection.getAttribute(name, "undefinedInt"));
} else {
Assert.assertEquals(undefinedInt, assertCast(String.class, connection.getAttribute(name, "undefinedInt")));
}
Assert.assertEquals(i, assertCast(String.class, connection.getAttribute(name, "int")));
Assert.assertEquals(bigInt, assertCast(String.class, connection.getAttribute(name, "bigint")));
Assert.assertEquals(bigDecimal, assertCast(String.class, connection.getAttribute(name, "bigdec")));
Assert.assertEquals(bool, assertCast(String.class, connection.getAttribute(name, "boolean")));
assertEqualByteArray(bytes, assertCast(byte[].class, connection.getAttribute(name, "bytes")));
Assert.assertEquals(dbl, assertCast(String.class, connection.getAttribute(name, "double")));
Assert.assertEquals(s, assertCast(String.class, connection.getAttribute(name, "string")));
String[] listValue = assertCast(String[].class, connection.getAttribute(name, "list"));
Assert.assertEquals(list.size(), listValue.length);
for (int ctr = 0; ctr < list.size(); ctr++) {
Assert.assertEquals(list.get(ctr), listValue[ctr]);
}
Assert.assertEquals(lng, assertCast(String.class, connection.getAttribute(name, "long")));
Assert.assertEquals(type, assertCast(String.class, connection.getAttribute(name, "type")));
TabularData tabularData = assertCast(TabularData.class, connection.getAttribute(name, "map"));
Assert.assertEquals(2, tabularData.size());
Assert.assertEquals(tblValue1, assertCast(String.class, tabularData.get(new Object[]{tblKey1}).get("value")));
Assert.assertEquals(tblValue2, assertCast(String.class, tabularData.get(new Object[]{tblKey2}).get("value")));
}
public static TabularData toTabularData(Trigger[] triggers) {
TabularData tData = new TabularDataSupport(TABULAR_TYPE);
if (triggers != null) {
ArrayList<CompositeData> list = new ArrayList<CompositeData>();
for (Trigger trigger : triggers) {
list.add(toCompositeData(trigger));
}
tData.putAll(list.toArray(new CompositeData[list.size()]));
}
return tData;
}
public static Map<String, MemoryUsage>
getMemoryUsageAfterGc(CompositeData cd) {
try {
TabularData td = (TabularData) cd.get(MEMORY_USAGE_AFTER_GC);
//return (Map<String,MemoryUsage>)
return cast(memoryUsageMapType.toJavaTypeData(td));
} catch (InvalidObjectException | OpenDataException e) {
// Should never reach here
throw new AssertionError(e);
}
}
private static TabularData makeTable() throws OpenDataException {
TabularData td = new TabularDataSupport(tt);
for (Map.Entry<String, Integer> entry : stringToValue.entrySet()) {
CompositeData cd = new CompositeDataSupport(
ct,
new String[] {"name", "int"},
new Object[] {entry.getKey(), entry.getValue()});
td.put(cd);
}
return td;
}