List of usage examples for javax.management.remote JMXConnector getMBeanServerConnection
public MBeanServerConnection getMBeanServerConnection() throws IOException;
Returns an MBeanServerConnection
object representing a remote MBean server.
From source file:org.rhq.plugins.cassandra.CassandraNodeComponent.java
private boolean isStorageServiceReachable() { JMXConnector connector = null; try {/*from w w w.j ava2s . co m*/ Configuration pluginConfig = getResourceContext().getPluginConfiguration(); String url = pluginConfig.getSimpleValue("connectorAddress"); JMXServiceURL serviceURL = new JMXServiceURL(url); connector = JMXConnectorFactory.connect(serviceURL, null); MBeanServerConnection serverConnection = connector.getMBeanServerConnection(); ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService"); // query an attribute to make sure it is in fact available serverConnection.getAttribute(storageService, "NativeTransportRunning"); return true; } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Failed to make JMX connection to StorageService", e); } return false; } finally { if (connector != null) { try { connector.close(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("An error occurred closing the JMX connector", e); } } } } }
From source file:org.hyperic.hq.plugin.weblogic.jmx.WeblogicRuntimeDiscoverer.java
private RuntimeResourceReport discover(int serverId, AIPlatformValue aiplatform, ConfigResponse config) throws PluginException { String installpath = config.getValue(ProductPlugin.PROP_INSTALLPATH); // incase jaas is disabled; generatePlatform may use this. this.aiplatform = aiplatform; log.debug("discover using: " + config); String domainName = config.getValue(WeblogicMetric.PROP_DOMAIN); String serverName = config.getValue(WeblogicMetric.PROP_SERVER); RuntimeResourceReport rrr = new RuntimeResourceReport(serverId); Properties props = config.toProperties(); WeblogicDiscover discover = new WeblogicDiscover(this.version, props); try {/*from w ww .j a v a 2 s . c om*/ MBeanServer mServer = discover.getMBeanServer(); discover.init(mServer); NodeManagerQuery nodemgrQuery = new NodeManagerQuery(); ServerQuery serverQuery = new ServerQuery(); serverQuery.setDiscover(discover); ArrayList servers = new ArrayList(); discover.find(mServer, serverQuery, servers); WeblogicQuery[] serviceQueries = discover.getServiceQueries(); // ensure admin is first incase we need version serverQuery.sort(servers); String adminVersion = null; for (int i = 0; i < servers.size(); i++) { serverQuery = (ServerQuery) servers.get(i); if (!serverQuery.isRunning()) continue; if (serverQuery.isAdmin()) { adminVersion = serverQuery.getVersion(); } else if (serverQuery.getVersion() == null) { // will be the case if a server was create but never started // safely assume it was created by the admin server in this // case and hence is the same version. serverQuery.setVersion(adminVersion); } AIPlatformValue aPlatform; AIServerExtValue aServer = generateServer(serverQuery); // Set the ID, so when this report is processed at the server, // there is no mistaking this server in the report for any other // server // in appdef (or worse, not matching anything and adding a new // server). if (serverQuery.getName().equals(serverName) && serverQuery.getDiscover().getDomain().equals(domainName)) { aServer.setId(new Integer(serverId)); aServer.setPlaceholder(true); // maintain existing installpath, // MBeanServer CurrentDirectory might be different if (installpath != null) { aServer.setInstallPath(installpath); } aiplatform.addAIServerValue(aServer); rrr.addAIPlatform(aiplatform); } else { aPlatform = generatePlatform(serverQuery); aPlatform.addAIServerValue(aServer); rrr.addAIPlatform(aPlatform); } if (!serverQuery.isRunning()) { continue; } mServer = discover.getMBeanServer(serverQuery.getUrl()); ArrayList aServices = new ArrayList(); ArrayList services = new ArrayList(); for (int j = 0; j < serviceQueries.length; j++) { WeblogicQuery serviceQuery = serviceQueries[j]; serviceQuery.setParent(serverQuery); serviceQuery.setVersion(serverQuery.getVersion()); discover.find(mServer, serviceQuery, services); } // Dynamic services can only be discovered on WebLogic 9.1 or // higher if (DYNAMIC_SVC_SUPPORTED_WEBLOGIC_VERSION .compareTo(Double.valueOf(serverQuery.getVersion())) <= 0) { final JMXConnector jmxConnector = WeblogicUtil.getManagedServerConnection(props); Set serviceTypes = new HashSet(); try { discoverDynamicServices(discover, jmxConnector.getMBeanServerConnection(), serverQuery, services, serviceTypes); } catch (IOException e) { throw new PluginException("Error discovering dynamic services", e); } finally { try { jmxConnector.close(); } catch (IOException e) { } } final AIServiceTypeValue[] serviceTypeValues = new AIServiceTypeValue[serviceTypes.size()]; int count = 0; for (Iterator iterator = serviceTypes.iterator(); iterator.hasNext();) { serviceTypeValues[count] = ((ServiceType) iterator.next()).getAIServiceTypeValue(); count++; } aServer.setAiServiceTypes(serviceTypeValues); pluginUpdater.updateServiceTypes(plugin.getProductPlugin(), serviceTypes); } for (int k = 0; k < services.size(); k++) { boolean valid = true; ServiceQuery service = (ServiceQuery) services.get(k); if (service instanceof ApplicationQuery) { valid = ((ApplicationQuery) service).isEAR(); } if (valid) { aServices.add(generateService(service)); } else { log.debug("skipped service:" + service.getName()); } } AIServiceValue[] aiservices = (AIServiceValue[]) aServices.toArray(new AIServiceValue[0]); aServer.setAIServiceValues(aiservices); if (serverQuery.isAdmin()) { ArrayList mgrs = new ArrayList(); nodemgrQuery.setAdminServer(serverQuery); discover.find(mServer, nodemgrQuery, mgrs); for (int n = 0; n < mgrs.size(); n++) { nodemgrQuery = (NodeManagerQuery) mgrs.get(n); aServer = generateServer(nodemgrQuery); aPlatform = generatePlatform(nodemgrQuery); aPlatform.addAIServerValue(aServer); rrr.addAIPlatform(aPlatform); } } } } catch (WeblogicDiscoverException e) { throw new PluginException(e.getMessage(), e); } return rrr; }
From source file:org.kuali.test.ui.components.dialogs.JmxDlg.java
public void loadJMXData() { JMXConnector conn = null; try {//ww w . j av a 2 s . co m Set<String> hs = new HashSet<String>(); if (jmx.getPerformanceMonitoringAttributes() != null) { for (PerformanceMonitoringAttribute pma : jmx.getPerformanceMonitoringAttributes() .getPerformanceMonitoringAttributeArray()) { hs.add(pma.getType() + "." + pma.getName()); } } conn = Utils.getJMXConnector(getConfiguration(), jmx); if (conn != null) { MBeanServerConnection mbeanConn = conn.getMBeanServerConnection(); if (mbeanConn != null) { for (int i = 0; i < tabInfo.length; ++i) { MBeanInfo mbeanInfo = mbeanConn.getMBeanInfo(new ObjectName(tabInfo[i].getJmxBeanName())); if (mbeanInfo != null) { for (MBeanAttributeInfo att : mbeanInfo.getAttributes()) { AttributeWrapper aw = new AttributeWrapper(att); if (isValidAttributeType(aw.getType())) { tabInfo[i].getAttributeInfo().add(aw); if (hs.contains(tabInfo[i].getJmxBeanName() + "." + aw.getName())) { aw.setSelected(true); } } } getTablePanel(i).getTable().setTableData(tabInfo[i].getAttributeInfo()); } } } } } catch (Exception ex) { LOG.error(ex.toString(), ex); UIUtils.showError(this, "JMX Error", "Error occurred during JMX connection - " + ex.toString()); } finally { if (conn != null) { try { conn.close(); } catch (Exception ex) { } ; } } }
From source file:com.clustercontrol.jmx.factory.RunMonitorJmx.java
/** * JMX ??/*from ww w. j a v a 2 s .c o m*/ * * @param facilityId ID * @return ???????true */ @Override public boolean collect(String facilityId) { boolean result = false; if (m_now != null) { m_nodeDate = m_now.getTime(); } m_value = 0; exception = null; NodeInfo node = null; if (!m_isMonitorJob) { node = nodeInfo.get(facilityId); } else { try { // ?? node = new RepositoryControllerBean().getNode(facilityId); } catch (Exception e) { m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NODE_ATTRIBUTES.getMessage(); return false; } } JMXServiceURL url = null; try { String rmiFormat = HinemosPropertyUtil.getHinemosPropertyStr("monitor.jmx.rmi.format", "service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi"); String urlStr = String.format(rmiFormat, node.getAvailableIpAddress(), jmx.getPort()); m_log.debug("facilityId=" + facilityId + ", url=" + urlStr); url = new JMXServiceURL(urlStr); } catch (Exception e) { m_log.warn("fail to initialize JMXServiceURL : " + e.getMessage() + " (" + e.getClass().getName() + ")", e); exception = e; return result; } JMXConnector jmxc = null; try { Map<String, Object> env = new HashMap<>(); if (jmx.getAuthUser() != null) env.put(JMXConnector.CREDENTIALS, new String[] { jmx.getAuthUser(), jmx.getAuthPassword() }); System.setProperty("sun.rmi.transport.tcp.responseTimeout", Integer.toString(HinemosPropertyUtil .getHinemosPropertyNum("system.sun.rmi.transport.tcp.responseTimeout", Long.valueOf(10 * 1000)) .intValue())); jmxc = JMXConnectorFactory.connect(url, env); MBeanServerConnection mbsc = jmxc.getMBeanServerConnection(); JmxMasterInfo jmxMasterInfo = QueryUtil.getJmxMasterInfoPK(jmx.getMasterId()); Object value = mbsc.getAttribute(new ObjectName(jmxMasterInfo.getObjectName()), jmxMasterInfo.getAttributeName()); m_value = Double.parseDouble( searchTargetValue(value, Arrays.asList(KeyParser.parseKeys(jmxMasterInfo.getKeys()))) .toString()); // ?? if (m_convertFlg == ConvertValueConstant.TYPE_DELTA) { // ?? MonitorJmxValue valueEntity = null; Double prevValue = 0d; Long prevDate = 0l; if (!m_isMonitorJob) { // ?? // cache?? valueEntity = MonitorJmxCache.getMonitorJmxValue(m_monitorId, facilityId); // ??? prevValue = valueEntity.getValue(); if (valueEntity.getGetDate() != null) { prevDate = valueEntity.getGetDate(); } } else { // ?? valueEntity = new MonitorJmxValue(new MonitorJmxValuePK(m_monitorId, facilityId)); if (m_prvData instanceof MonitorJmxValue) { // ???? prevValue = ((MonitorJmxValue) m_prvData).getValue(); prevDate = ((MonitorJmxValue) m_prvData).getGetDate(); } } // JMX???? valueEntity.setValue(Double.valueOf(m_value)); valueEntity.setGetDate(m_nodeDate); if (!m_isMonitorJob) { // ???ID????? if (m_monitor.getMonitorFlg()) MonitorJmxCache.update(m_monitorId, facilityId, valueEntity); int m_validSecond = HinemosPropertyUtil .getHinemosPropertyNum("monitor.jmx.valid.second", Long.valueOf(15)).intValue(); // ??????????? int tolerance = (m_runInterval + m_validSecond) * 1000; if (prevDate > m_nodeDate - tolerance) { // ??null??? if (prevValue == null) { m_log.debug("collect() : prevValue is null"); m_prevNullchk = true; return false; } m_value = m_value - prevValue; } else { if (prevDate != 0l) { DateFormat df = DateFormat.getDateTimeInstance(); df.setTimeZone(HinemosTime.getTimeZone()); String[] args = { df.format(new Date(prevDate)) }; m_message = MessageConstant.MESSAGE_TOO_OLD_TO_CALCULATE.getMessage(args); return false; } else { // ???0?? m_nodeDate = 0l; } } } else { m_value = m_value - prevValue; m_curData = valueEntity; } } m_log.debug(jmxMasterInfo.getName() + " : " + m_value + " " + jmxMasterInfo.getMeasure()); result = true; } catch (NumberFormatException e) { m_log.info("collect() : " + e.getClass().getSimpleName() + ", " + e.getMessage()); String[] args = { Double.toString(m_value) }; m_message = MessageConstant.MESSAGE_COULD_NOT_GET_NUMERIC_VALUE.getMessage(args); return false; } catch (Exception e) { String message = e.getMessage(); if (message != null) { message = message.replaceAll("\n", ""); } m_log.warn("fail to access JMXService : " + message + " (" + e.getClass().getName() + ")"); exception = e; } finally { try { if (jmxc != null) { jmxc.close(); } } catch (IOException e) { m_log.info("fail to close JMXService : " + e.getMessage() + " (" + e.getClass().getName() + ")"); exception = e; } } return result; }
From source file:org.hyperic.hq.product.jmx.MxUtil.java
public static MBeanServerConnection getMBeanServer(Properties config) throws MalformedURLException, IOException { String jmxUrl = config.getProperty(MxUtil.PROP_JMX_URL); String jmxUsername = config.getProperty(MxUtil.PROP_JMX_USERNAME, ""); String jmxPassword = config.getProperty(MxUtil.PROP_JMX_PASSWORD, ""); boolean isCached = false; JMXConnector connector; ConnectorInstance instance = (ConnectorInstance) cache.get(jmxUrl); if (instance != null) { connector = instance.connector;/* www . j a v a2 s . c om*/ String username = instance.username; String password = instance.password; boolean usernameChanged = !username.equals(jmxUsername); boolean passwordChanged = !password.equals(jmxPassword); if (usernameChanged || passwordChanged) { if (log.isDebugEnabled()) { String diff = ""; if (usernameChanged) { diff += "user:" + diff(username, jmxUsername); } if (passwordChanged) { if (diff.length() != 0) { diff += ","; } diff += "pass:" + diff(mask(password), mask(jmxPassword)); } log.debug("Credentials changed (" + diff + ") reconnecting cached connection for: " + jmxUrl); } connector = connect(config, jmxUrl, jmxUsername, jmxPassword); } else { isCached = true; } } else { connector = connect(config, jmxUrl, jmxUsername, jmxPassword); log.debug("Caching connector for: " + jmxUrl); } try { return connector.getMBeanServerConnection(); } catch (IOException e) { if (isCached) { log.debug("Reconnecting cached connection for: " + jmxUrl); connector = connect(config, jmxUrl, jmxUsername, jmxPassword); return connector.getMBeanServerConnection(); } else { throw e; } } }
From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java
public boolean makeServerConnection(JMXConnector jmxConnector) throws IOException, MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, MalformedObjectNameException { MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection(); Set<ObjectName> mbeans = mBeanServerConnection.queryNames(new ObjectName("CoUGAR:name=healthChecker,*"), null);//from ww w . j a v a2 s . com if (!mbeans.isEmpty()) { mBeanServerConnection.getAttribute(mbeans.iterator().next(), "SystemInService"); return true; } return false; }
From source file:org.hyperic.hq.product.jmx.MxServerDetector.java
public Set discoverServiceTypes(ConfigResponse serverConfig) throws PluginException { JMXConnector connector = null; MBeanServerConnection mServer; Set serviceTypes = new HashSet(); //plugins need to define these properties at the plugin level to discover dynamic service types if (getProductPlugin().getPluginData().getProperty(MEASUREMENT_CLASS_PROPERTY) == null || getProductPlugin().getPluginData().getProperty(CONTROL_CLASS_PROPERTY) == null || getProductPlugin().getPluginData().getProperty(TEMPLATE_PROPERTY) == null) { return serviceTypes; }/*from w w w . j a v a2 s . c om*/ try { connector = MxUtil.getCachedMBeanConnector(serverConfig.toProperties()); mServer = connector.getMBeanServerConnection(); } catch (Exception e) { MxUtil.close(connector); throw new PluginException(e.getMessage(), e); } try { final Set objectNames = mServer.queryNames(new ObjectName(MBeanUtil.DYNAMIC_SERVICE_DOMAIN + ":*"), null); serviceTypes = serviceTypeFactory.create(getProductPlugin(), (ServerTypeInfo) getTypeInfo(), mServer, objectNames); } catch (Exception e) { throw new PluginException(e.getMessage(), e); } finally { MxUtil.close(connector); } return serviceTypes; }
From source file:io.github.albertopires.mjc.JConsoleM.java
private JConsoleM(ServerConfiguration serverConfiguration) throws Exception { JMXConnector jmxc = null; if (serverConfiguration.getAuthenticate()) { String urlStr = "service:jmx:http-remoting-jmx://" + serverConfiguration.getHost() + ":" + serverConfiguration.getPort(); Map<String, Object> env = new HashMap<String, Object>(); String[] creds = { serverConfiguration.getUser(), serverConfiguration.getPassword() }; env.put(JMXConnector.CREDENTIALS, creds); jmxc = JMXConnectorFactory.connect(new JMXServiceURL(urlStr), env); } else {//from ww w . j av a2 s .co m String urlStr = "service:jmx:rmi:///jndi/rmi://" + serverConfiguration.getHost() + ":" + serverConfiguration.getPort() + "/jmxrmi"; // String urlStr = "service:jmx:remote+http://" + serverConfiguration.getHost() + ":" + serverConfiguration.getPort(); JMXServiceURL url = new JMXServiceURL(urlStr); jmxc = JMXConnectorFactory.connect(url, null); } mbsc = jmxc.getMBeanServerConnection(); ncpu = getAvailableProcessors(); }
From source file:org.rhq.storage.installer.StorageInstaller.java
boolean verifyNodeIsUp(String address, int jmxPort, int retries, long timeout) throws Exception { String url = "service:jmx:rmi:///jndi/rmi://" + address + ":" + jmxPort + "/jmxrmi"; JMXServiceURL serviceURL = new JMXServiceURL(url); JMXConnector connector = null; MBeanServerConnection serverConnection = null; // Sleep a few seconds to work around https://issues.apache.org/jira/browse/CASSANDRA-5467 try {//from w ww. java 2 s. c o m Thread.sleep(3000); } catch (InterruptedException e) { } Map<String, String> env = new HashMap<String, String>(); for (int i = 0; i < retries; ++i) { try { connector = JMXConnectorFactory.connect(serviceURL, env); serverConnection = connector.getMBeanServerConnection(); ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService"); Boolean nativeTransportRunning = (Boolean) serverConnection.getAttribute(storageService, "NativeTransportRunning"); return nativeTransportRunning; } catch (Exception e) { if (i < retries) { if (log.isDebugEnabled()) { log.debug("The storage node is not up.", e); } else { Throwable rootCause = ThrowableUtil.getRootCause(e); log.info("The storage node is not up: " + rootCause.getClass().getName() + ": " + rootCause.getMessage()); } log.info("Checking storage node status again in " + (timeout * (i + 1)) + " ms..."); } Thread.sleep(timeout * (i + 1)); } } return false; }
From source file:org.kuali.test.runner.execution.TestExecutionContext.java
private void writePerformanceData(TestOperation op, long operationElaspedTime) { if (isPerformanceDataRequired()) { if (performanceData == null) { performanceData = new ArrayList<String[]>(); }//from ww w . j av a2s . c om String submitElementName = getLastHttpSubmitElementName(); ; if (op.getOperationType().equals(TestOperationType.HTTP_REQUEST)) { String[] rec = getInitializedPerformanceDataRecord(); rec[8] = Constants.PERFORMANCE_ATTRIBUTE_TYPE_CLIENT; rec[9] = Constants.CLIENT_PERFORMANCE_ATTRIBUTE_HTTP_RESPONSE_TIME; rec[10] = Constants.PRIMITIVE_LONG_TYPE; rec[11] = "" + operationElaspedTime; rec[12] = submitElementName; rec[13] = (op.getOperation().getHtmlRequestOperation().getMethod() + ": " + op.getOperation().getHtmlRequestOperation().getUrl()); performanceData.add(rec); } JmxConnection jmxconn = Utils.findJmxConnection(configuration, platform.getJmxConnectionName()); if ((jmxconn != null) && (jmxconn.getPerformanceMonitoringAttributes() != null)) { JMXConnector conn = null; try { conn = Utils.getJMXConnector(configuration, jmxconn); if (conn != null) { MBeanServerConnection mbeanconn = conn.getMBeanServerConnection(); for (PerformanceMonitoringAttribute att : jmxconn.getPerformanceMonitoringAttributes() .getPerformanceMonitoringAttributeArray()) { Object value = ""; if (ManagementFactory.MEMORY_MXBEAN_NAME.equals(att.getType())) { MemoryMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbeanconn, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class); value = getValueFromMXBeanObject(att.getName(), mbean); } else if (ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME.equals(att.getType())) { OperatingSystemMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbeanconn, att.getType(), OperatingSystemMXBean.class); value = getValueFromMXBeanObject(att.getName(), mbean); } else if (ManagementFactory.THREAD_MXBEAN_NAME.equals(att.getType())) { ThreadMXBean mbean = ManagementFactory.newPlatformMXBeanProxy(mbeanconn, att.getType(), ThreadMXBean.class); value = getValueFromMXBeanObject(att.getName(), mbean); } if ((value != null) && StringUtils.isNotBlank(value.toString())) { String[] rec = getInitializedPerformanceDataRecord(); int pos = att.getType().indexOf(Constants.SEPARATOR_EQUALS); if (pos > -1) { rec[8] = att.getType().substring(pos + 1); } else { rec[8] = att.getType(); } rec[9] = att.getName(); rec[10] = att.getType(); rec[11] = value.toString(); rec[12] = submitElementName; rec[13] = att.getDescription(); performanceData.add(rec); } } } } catch (Exception ex) { LOG.error(ex.toString(), ex); } finally { if (conn != null) { try { conn.close(); } catch (Exception ex) { } ; } } } } }