Example usage for javax.management.openmbean CompositeData get

List of usage examples for javax.management.openmbean CompositeData get

Introduction

In this page you can find the example usage for javax.management.openmbean CompositeData get.

Prototype

public Object get(String key);

Source Link

Document

Returns the value of the item whose name is key .

Usage

From source file:org.apache.hadoop.hbase.util.TestJSONMetricUtil.java

@Test
public void testGetLastGCInfo() {
    List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans();
    for (GarbageCollectorMXBean bean : gcBeans) {
        ObjectName on = bean.getObjectName();
        Object value = JSONMetricUtil.getValueFromMBean(on, "LastGcInfo");
        LOG.info("Collector Info: " + value);
        if (value != null && value instanceof CompositeData) {
            CompositeData cds = (CompositeData) value;
            assertNotNull(cds.get("duration"));
        }//  www .  ja va 2s  . c  o m
    }
}

From source file:org.trpr.platform.batch.impl.spring.jmx.JMXJobUtils.java

/**
 * Polls the JobAdministrator for last execution status of the specified job. Makes the current thread sleep for the specified duration between consecutive
 * checks//from   ww w  . j a v a2 s.  c  o  m
 * @param jobName the job to wait for execution completion
 * @param checkFrequency the sleep time in ms between status checks
 * @throws Exception all Runtime and Checked exceptions thrown, if any, when monitoring the specified job
 * @return the exist status as String
 */
public String waitForJobExecution(String jobName, long checkFrequency) throws Exception {
    while (true) {
        Thread.sleep(checkFrequency);
        TabularDataSupport batchStats = (TabularDataSupport) this.mbeanServer
                .invoke(this.jobAdministratorInstance.getObjectName(), JOB_METRICS, null, null);
        Set<Map.Entry<Object, Object>> stats = batchStats.entrySet();
        for (Map.Entry entry : stats) {
            CompositeData data = (CompositeData) entry.getValue();
            if (data.get(JOB_PARAM_NAME).equals(jobName) && data.get(JOB_PARAM_STATUS) != null) {
                String status = data.get("jobStatus").toString();
                for (String completedStatus : BATCH_COMPLETION_STATUSES) {
                    if (status.equalsIgnoreCase(completedStatus)) {
                        // job has completed execution, so exit.
                        return status;
                    }
                }
            }
        }
    }

}

From source file:org.wso2.andes.management.ui.views.ViewUtility.java

/**
 * Creates widgets for object messages and populates the content in hexadecimal format.
 * @param toolkit//from w  w w.java  2s.  c om
 * @param compositeHolder
 * @param data
 * @param itemName
 * @param encoding
 */
private static void handleBinaryMessageContent(FormToolkit toolkit, Composite compositeHolder,
        CompositeData data, String itemName, String encoding) {
    final String thisEncoding = encoding;
    final Byte[] arrayItems = (Byte[]) data.get(itemName);
    final byte[] byteArray = new byte[arrayItems.length];

    for (int i = 0; i < arrayItems.length; i++) {
        byteArray[i] = arrayItems[i];
    }

    try {
        //create a new composite to contain the widgets required to display object messages.
        final Composite localComposite = toolkit.createComposite(compositeHolder, SWT.NONE);
        localComposite.setData("currentBytePos", 0);
        localComposite.setData("startingBytePos", 0);
        GridLayout layout = new GridLayout(2, true);
        layout.marginWidth = 0;
        layout.marginHeight = 0;
        localComposite.setLayout(layout);
        localComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));

        int startContentSize = DEFAULT_CONTENT_SIZE;

        if (byteArray.length < DEFAULT_CONTENT_SIZE) {
            startContentSize = byteArray.length;
        }

        //create a text to display the hexadecimal views of object messages, it takes more space than ascii view as 
        //a hex uses 2 chars and 1 space, while ascii only uses 1 char and 1 space.
        final Text hexText = toolkit.createText(localComposite,
                displayByteFormat(localComposite, byteArray, startContentSize * 2, thisEncoding, "<<", true),
                SWT.READ_ONLY | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER);
        GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
        gridData.widthHint = 144; //set to 222 if not using any fonts
        gridData.heightHint = 200;
        hexText.setLayoutData(gridData);

        final Text asciiText = toolkit.createText(localComposite,
                displayByteFormat(localComposite, byteArray, startContentSize * 2, thisEncoding, "<<", false),
                SWT.READ_ONLY | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER);

        gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
        gridData.widthHint = 52;//set to 98 if not using any fonts
        gridData.heightHint = 200;
        asciiText.setLayoutData(gridData);

        //use a monospaced font for a better layout
        Font font = new Font(compositeHolder.getDisplay(), "Courier", 10, SWT.NORMAL);
        hexText.setFont(font);
        asciiText.setFont(font);

        final ScrollBar hexScrollBar = hexText.getVerticalBar();
        final ScrollBar asciiScrollBar = asciiText.getVerticalBar();

        //create a sub composite to contain all the buttons
        final Composite buttonComposite = toolkit.createComposite(localComposite, SWT.NONE);
        layout = new GridLayout(7, false);
        layout.marginWidth = 0;
        buttonComposite.setLayout(layout);
        buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1));

        _firstButton = toolkit.createButton(buttonComposite, "<<", SWT.PUSH);
        GridData layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
        layoutData.widthHint = 40;
        _firstButton.setLayoutData(layoutData);
        _firstButton.setToolTipText("See the first n bytes");

        _previousButton = toolkit.createButton(buttonComposite, "<", SWT.PUSH);
        layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
        layoutData.widthHint = 40;
        _previousButton.setLayoutData(layoutData);
        _previousButton.setToolTipText("See the previous n bytes");
        _previousButton.setEnabled(false);

        _hexNumTextToStart = toolkit.createText(buttonComposite, "0");
        layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
        layoutData.widthHint = 40;
        _hexNumTextToStart.setLayoutData(layoutData);
        _hexNumTextToStart.setEditable(false);

        final Text hexNumText = toolkit.createText(buttonComposite, "" + startContentSize);
        layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
        layoutData.widthHint = 40;
        hexNumText.setLayoutData(layoutData);

        _hexNumTextToEnd = toolkit.createText(buttonComposite, "" + (byteArray.length - startContentSize));
        layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
        layoutData.widthHint = 40;
        _hexNumTextToEnd.setLayoutData(layoutData);
        _hexNumTextToEnd.setEditable(false);

        _nextButton = toolkit.createButton(buttonComposite, ">", SWT.PUSH);
        layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
        layoutData.widthHint = 40;
        _nextButton.setLayoutData(layoutData);
        _nextButton.setToolTipText("See the next n bytes");
        _nextButton.setEnabled(true);

        _lastButton = toolkit.createButton(buttonComposite, ">>", SWT.PUSH);
        layoutData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
        layoutData.widthHint = 40;
        _lastButton.setToolTipText("See the last n bytes");
        _lastButton.setLayoutData(layoutData);

        SelectionListener listener = new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                if (e.widget instanceof Button) {
                    String numOfBytes = hexNumText.getText();
                    try {
                        int n = Integer.parseInt(numOfBytes);

                        //Reset range display if user requests a large value
                        if (n > byteArray.length) {
                            n = (byteArray.length > DEFAULT_CONTENT_SIZE) ? DEFAULT_CONTENT_SIZE
                                    : byteArray.length;
                            hexNumText.setText("" + n);
                        }

                        //rest if the user requests 0
                        if (n < 1) {
                            n = DEFAULT_CONTENT_SIZE;
                            hexNumText.setText("" + n);
                        }

                        Button button = (Button) e.widget;
                        hexText.setText(displayByteFormat(localComposite, byteArray, n * 2, thisEncoding,
                                button.getText(), true));
                        asciiText.setText(displayByteFormat(localComposite, byteArray, n * 2, thisEncoding,
                                button.getText(), false));
                    } catch (NumberFormatException exp) {
                        popupErrorMessage("Error", "Please input the number of bytes you wish to look at");
                    }
                }
                if (e.widget instanceof ScrollBar) {
                    //synchronize the movements of the two scrollbars
                    ScrollBar sb = (ScrollBar) e.widget;
                    if (sb.getParent().equals(hexText)) {
                        asciiScrollBar.setIncrement(sb.getIncrement());
                        asciiScrollBar.setSelection(sb.getSelection());
                    } else if (sb.getParent().equals(asciiText)) {
                        hexScrollBar.setSelection(sb.getSelection());
                        hexScrollBar.setIncrement(sb.getIncrement());
                    }
                }
            }
        };
        localComposite.addControlListener(new ControlAdapter() {
            public void controlResized(ControlEvent e) {
                //if the control is resized, set different parameters to make a single line displays the same contents.
                if (((GridLayout) localComposite.getLayout()).makeColumnsEqualWidth) {
                    ((GridLayout) localComposite.getLayout()).makeColumnsEqualWidth = false;
                    ((GridLayout) localComposite.getLayout()).numColumns = 2;
                    ((GridData) hexText.getLayoutData()).horizontalSpan = 1;
                    ((GridData) hexText.getLayoutData()).widthHint = 144;
                    ((GridData) asciiText.getLayoutData()).horizontalSpan = 1;
                    ((GridData) asciiText.getLayoutData()).widthHint = 52;
                    ((GridData) buttonComposite.getLayoutData()).horizontalSpan = 2;
                } else {
                    ((GridLayout) localComposite.getLayout()).makeColumnsEqualWidth = true;
                    ((GridLayout) localComposite.getLayout()).numColumns = 42; //set to 47 if not using any fonts
                    ((GridData) hexText.getLayoutData()).horizontalSpan = 25; // set to 30 if not using any fonts
                    ((GridData) asciiText.getLayoutData()).horizontalSpan = 17; // set to 17 if not using any fonts
                    ((GridData) buttonComposite.getLayoutData()).horizontalSpan = 42;
                }
            }
        });

        _firstButton.addSelectionListener(listener);
        _previousButton.addSelectionListener(listener);
        _nextButton.addSelectionListener(listener);
        _lastButton.addSelectionListener(listener);
        hexScrollBar.addSelectionListener(listener);
        asciiScrollBar.addSelectionListener(listener);
        //f.dispose();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.osgi.jmx.codec.OSGiServiceEvent.java

/**
 * Construct an OSGiServiceEvent from the CompositeData representing the
 * event//from   w  w  w . j  a  v a 2 s.co  m
 * 
 * @param data
 *            = the CompositeData representation of the event
 */
public OSGiServiceEvent(CompositeData data) {
    serviceId = (Long) data.get(SERVICE_ID);
    bundleId = (Long) data.get(BUNDLE_IDENTIFIER);
    location = (String) data.get(BUNDLE_LOCATION);
    interfaces = (String[]) data.get(OBJECT_CLASS);
    eventType = (Integer) data.get(ServiceStateMBean.EVENT_TYPE);
}

From source file:com.tomcat.monitor.jmx.obj.bean.MServer.java

/**
 * getValue form OpenMBean Value FIXME: SimpleType Umwandlung in skalare
 * Datentypen FIXME: Suche eine elegante Moeglichkeit an den Wert eines
 * Attributes in einem OpenMBean heranzukommen (BeanUtils...)?
 * <p/>//  w w  w .j a v a  2  s.c  o m
 * <p/>
 * Beispiele: attribute1 [key1] attribute1.attribute2 [key].attribute1
 * [key1].[key2] [key1].attribute1.[key2].attribute2
 * 
 * @param attributePath
 *           path to Mbean OpenMbean attribute
 * @param bean
 *           current value
 */
public Object accessValue(String attributePath, Object bean) {
    if (attributePath == null || "".equals(attributePath))
        return null;
    if (bean instanceof CompositeDataSupport) {
        CompositeDataSupport data = (CompositeDataSupport) bean;
        // FIXME This only supports direct key access
        return data.get(attributePath);
    } else if (bean instanceof TabularDataSupport) {
        TabularDataSupport data = (TabularDataSupport) bean;
        if (attributePath.startsWith("[")) {
            int endIndex = attributePath.indexOf("]");
            if (endIndex > 1) {
                String attributeKey = attributePath.substring(1, endIndex);
                CompositeData valuedata = data.get(new Object[] { attributeKey });
                Object value = valuedata.get("value");
                OpenType<?> type = valuedata.getCompositeType().getType("value");
                if (type instanceof SimpleType) {
                    // FIXME Es fehlt noch die Prfung ob attributePath
                    // nicht false ist, sprich das nach [].<xxxx> gefragt
                    // wahr.
                    return value;
                } else {
                    String nextAttributePath = attributePath.substring(endIndex);
                    if (nextAttributePath.startsWith(".")) {
                        // FIXME stimmt das oder endIndex
                        return accessValue(attributePath.substring(endIndex + 1), value);
                    }
                }
            }
        }
    }
    return null;
}

From source file:org.jolokia.jmx.JolokiaMBeanServerTest.java

@Test
public void simple() throws NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanException,
        MalformedObjectNameException, AttributeNotFoundException, ReflectionException,
        InstanceNotFoundException, ParseException, InvalidTargetObjectTypeException, NoSuchMethodException,
        IntrospectionException {//from w  ww.ja  v  a  2 s.c  om
    JolokiaMBeanServer server = new JolokiaMBeanServer();

    ObjectName oName = new ObjectName("test:type=jsonMBean");
    server.registerMBean(new JsonAnnoTest(), oName);

    CompositeData chiliCD = (CompositeData) server.getAttribute(oName, "Chili");
    assertEquals((String) chiliCD.get("name"), "Bhut Jolokia");
    assertEquals(chiliCD.get("scoville"), 1000000L);

    MBeanServer pServer = ManagementFactory.getPlatformMBeanServer();
    String chiliS = (String) pServer.getAttribute(oName, "Chili");
    JSONObject chiliJ = (JSONObject) new JSONParser().parse(chiliS);
    assertEquals(chiliJ.get("name"), "Bhut Jolokia");
    assertEquals(chiliJ.get("scoville"), 1000000L);

    server.unregisterMBean(oName);
    Assert.assertFalse(pServer.isRegistered(oName));
    Assert.assertFalse(server.isRegistered(oName));
}

From source file:org.jolokia.converter.json.CompositeDataExtractor.java

/** {@inheritDoc} */
@SuppressWarnings("PMD.PreserveStackTrace")
public Object extractObject(ObjectToJsonConverter pConverter, Object pValue, Stack<String> pPathParts,
        boolean jsonify) throws AttributeNotFoundException {
    CompositeData cd = (CompositeData) pValue;

    String pathPart = pPathParts.isEmpty() ? null : pPathParts.pop();
    if (pathPart != null) {
        try {/* www . ja v  a  2  s . c o  m*/
            return pConverter.extractObject(cd.get(pathPart), pPathParts, jsonify);
        } catch (InvalidKeyException exp) {
            return pConverter.getValueFaultHandler()
                    .handleException(new AttributeNotFoundException("Invalid path '" + pathPart + "'"));
        }
    } else {
        return jsonify ? extractCompleteCdAsJson(pConverter, cd, pPathParts) : cd;
    }
}

From source file:com.haulmont.cuba.web.app.ui.statistics.ThreadsDatasource.java

@Override
protected void loadData(Map<String, Object> params) {
    JmxInstance node = (JmxInstance) params.get("node");
    ManagedBeanInfo threadingBean = jmxControlAPI.getManagedBean(node, "java.lang:type=Threading");
    int nCPUs = (int) getAttributeValue(node, "java.lang:type=OperatingSystem", "AvailableProcessors");

    final long[] allThreadsIds = (long[]) getAttributeValue(node, "java.lang:type=Threading", "AllThreadIds");
    ManagedBeanOperation getThreadInfo = jmxControlAPI.getOperation(threadingBean, "getThreadInfo",
            new String[] { "[J" });
    CompositeData[] threadsInfo = (CompositeData[]) jmxControlAPI.invokeOperation(getThreadInfo,
            new Object[] { allThreadsIds });

    final long currentUptime = (long) getAttributeValue(node, "java.lang:type=Runtime", "Uptime");
    ManagedBeanOperation getThreadCpuTime = jmxControlAPI.getOperation(threadingBean, "getThreadCpuTime",
            new String[] { "[J" });
    long[] threadCpuTime = (long[]) jmxControlAPI.invokeOperation(getThreadCpuTime,
            new Object[] { allThreadsIds });
    if (prevUptime > 0L && currentUptime > prevUptime) {
        // elapsedTime is in ms
        long elapsedTime = currentUptime - prevUptime;
        for (int i = 0; i < allThreadsIds.length; i++) {
            // elapsedCpu is in ns
            Long threadId = allThreadsIds[i];
            Long prevCpuTimeLong = prevThread2CpuTime.get(threadId); //for new threads returns null.
            long prevCpuTime = prevCpuTimeLong != null ? prevCpuTimeLong : 0L;
            long elapsedCpu = threadCpuTime[i] - prevCpuTime;
            // cpuUsage could go higher than 100% because elapsedTime
            // and elapsedCpu are not fetched simultaneously. Limit to 99%.
            double cpuUsage = Math.min(99d, elapsedCpu / (elapsedTime * 1000000d /*convert to ns*/
                    / 100 /*percents*/ * nCPUs));
            getThreadSnapshot(threadId).setCpu(cpuUsage);
        }//ww w .  j a  v a2s  .c om
    }
    prevUptime = currentUptime;
    for (int i = 0; i < allThreadsIds.length; i++) {
        long time = threadCpuTime[i] != -1L ? threadCpuTime[i] : 0L;
        prevThread2CpuTime.put(allThreadsIds[i], time);
    }

    ManagedBeanOperation findDeadlockedThreads = jmxControlAPI.getOperation(threadingBean,
            "findDeadlockedThreads", null);
    Long[] deadlockedThreads = (Long[]) jmxControlAPI.invokeOperation(findDeadlockedThreads, null);
    Set<Long> deadLockedThreadsSet = new HashSet<>();
    if (deadlockedThreads != null) {
        CollectionUtils.addAll(deadLockedThreadsSet, deadlockedThreads);
    }
    Set<Long> allThreadsSet = new HashSet<>();
    CollectionUtils.addAll(allThreadsSet, ArrayUtils.toObject(allThreadsIds));

    //remove all terminated threads.
    Collection<ThreadSnapshot> toRemove = new LinkedList<>();
    for (ThreadSnapshot snapshot : getItems()) {
        if (!allThreadsSet.contains(snapshot.getThreadId())) {
            toRemove.add(snapshot);
        }
    }
    for (ThreadSnapshot snapshot : toRemove) {
        removeItem(snapshot);
    }

    //update visual data.
    for (int i = 0; i < threadsInfo.length; i++) {
        CompositeData info = threadsInfo[i];
        if (info != null) {
            Long threadId = (Long) info.get("threadId");
            ThreadSnapshot item = getThreadSnapshot(threadId);
            item.setName((String) info.get("threadName"));
            item.setStatus(info.get("threadState").toString());
            item.setDeadLocked(deadLockedThreadsSet.contains(threadId));
        } else {
            removeItem(getThreadSnapshot(allThreadsIds[i])); //no thread info available.
        }
    }

}

From source file:com.alibaba.dragoon.common.protocol.MBeanServerMessageHandler.java

private Object getAttributeInternal(GetAttribute message, String attributeName) throws Exception {
    String[] items = attributeName.split("\\.");
    Object value = null;//  w  ww  . j  a v a 2 s .c  o m
    Object current = null;
    for (int i = 0; i < items.length; ++i) {
        if (i == 0) {
            current = mbeanServer.getAttribute(message.getObjectName(), items[i]);
            if (current instanceof List) {
                try {
                    current = deepCopyList(current);
                } catch (ArrayIndexOutOfBoundsException e) {
                    // FIXME high risk
                    current = deepCopyList(current);
                }
            }
        } else {
            if (current instanceof CompositeData) {
                CompositeData compositeDate = (CompositeData) current;
                current = compositeDate.get(items[i]);
            } else if (current instanceof Map) {
                Map<?, ?> map = (Map<?, ?>) current;
                current = map.get(items[i]);
            } else {
                current = null;
            }
        }

        if (current == null) {
            break;
        }

        if (i == items.length - 1) {
            value = current;
        }
    }

    return value;
}

From source file:org.apache.qpid.systest.management.jmx.ConnectionManagementTest.java

private void assertFlowBlocked(final CompositeData row, boolean flowBlocked) {
    assertNotNull(row);//  w  ww. jav a2s . com
    assertEquals("Unexpected flow blocked", flowBlocked, row.get(ManagedConnection.FLOW_BLOCKED));
}