List of usage examples for javax.management MBeanServer invoke
public Object invoke(ObjectName name, String operationName, Object params[], String signature[]) throws InstanceNotFoundException, MBeanException, ReflectionException;
From source file:org.nuxeo.ecm.webapp.seam.SeamHotReloadHelper.java
/** * Flushes resources for tomcat cache//from www . j a v a 2 s . c om * * @since 5.5 */ protected static void flushWebResources() throws ReflectiveOperationException, JMException { ObjectName on = new ObjectName("org.nuxeo:type=sdk,name=web-resources"); MBeanServer mbs = Framework.getLocalService(ServerLocator.class).lookupServer(); if (mbs.isRegistered(on)) { // only in tomcat container mbs.invoke(on, "flushWebResources", new Object[0], new String[0]); } }
From source file:org.onehippo.forge.camel.util.CamelContextUtils.java
/** * Finds the {@code ManagedCamelContextMBean} having {@code camelContextId} from the platform MBean server and invokes the {@code operation} * with {@code params} of which signature is like {@code signature} on the found {@code ManagedCamelContext} MBean. * If a blank {@code camelContextId} provided, then it invokes the operation on the first found {@code ManagedCamelContextMBean} MBean. * <p>Example code:</p>//from w ww . j av a 2s . c o m * <pre> * CamelContextUtils.invokeManagedCamelContextMBean("camel-1", "sendBody", new Object [] { "direct:test", body }, new String {} { String.class.getName(), Object.class.getName() });; * </pre> * @param camelContextId camel context ID * @param operation operation name * @param params parameters array * @param signature signature of parameters * @return operation return */ public static Object invokeManagedCamelContextMBean(final String camelContextId, final String operation, Object[] params, String[] signature) { Object ret = null; try { QueryExp expr = Query.isInstanceOf(new StringValueExp(CAMEL_CONTEXT_MBEAN_INSTANCE_TYPE)); MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName; if (StringUtils.isNotBlank(camelContextId)) { objectName = new ObjectName("org.apache.camel:name=" + camelContextId); } else { objectName = new ObjectName("org.apache.camel:*"); } Set<ObjectName> objectNames = mbeanServer.queryNames(objectName, expr); if (!objectNames.isEmpty()) { final ObjectName firstObjectName = objectNames.iterator().next(); ret = mbeanServer.invoke(firstObjectName, operation, params, signature); } else { throw new RuntimeException("No CamelContext found by name: " + objectName); } } catch (MalformedObjectNameException e) { throw new RuntimeException("MalformedObjectNameException: " + e, e); } catch (InstanceNotFoundException e) { throw new RuntimeException("InstanceNotFoundException: " + e, e); } catch (ReflectionException e) { throw new RuntimeException("ReflectionException: " + e, e); } catch (MBeanException e) { throw new RuntimeException("MBeanException: " + e, e); } return ret; }
From source file:org.openamf.invoker.JMXServiceInvoker.java
public Object invokeService() throws ServiceInvocationException { Object serviceResult = null;//from w ww . ja v a 2 s .c o m try { List serverList = MBeanServerFactory.findMBeanServer(null); if (serverList == null || serverList.size() == 0) { throw new Exception("MBeanServers not found"); } MBeanServer server = (MBeanServer) serverList.get(0); ObjectName objectName = new ObjectName(request.getServiceName()); Object[] parameters = request.getParameters().toArray(); String[] signature = new String[parameters.length]; for (int i = 0; i < parameters.length; i++) { signature[i] = parameters[i].getClass().getName(); } serviceResult = server.invoke(objectName, request.getServiceMethodName(), parameters, signature); } catch (Exception e) { throw new ServiceInvocationException(request, e); } return serviceResult; }
From source file:org.quartz.jobs.ee.jmx.JMXInvokerJob.java
private Object invoke(String objectName, String method, Object[] params, String[] types) throws Exception { MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0); ObjectName mbean = new ObjectName(objectName); if (server == null) { throw new Exception("Can't find mbean server"); }/* w w w. ja va 2s . c o m*/ getLog().info("invoking " + method); return server.invoke(mbean, method, params, types); }
From source file:org.rhq.enterprise.gui.startup.StartupServlet.java
/** * Starts the embedded agent, but only if the embedded agent is installed and it is enabled. * * @throws ServletException if the agent is installed and enabled but failed to start *//*from w w w .ja v a 2s. co m*/ private void startEmbeddedAgent() throws ServletException { // we can't use EmbeddedAgentBootstrapServiceMBean because if the embedded agent // isn't installed, that class will not be available; we must use JMX API final ObjectName agentBootstrapMBean = ObjectNameFactory.create("rhq:service=EmbeddedAgentBootstrap"); final String agentEnabledAttribute = "AgentEnabled"; final String startAgentMethod = "startAgent"; final String configurationOverridesAttribute = "ConfigurationOverrides"; final MBeanServer mbs = MBeanServerLocator.locateJBoss(); try { // this will fail if the embedded agent isn't installed String enabled = (String) mbs.getAttribute(agentBootstrapMBean, agentEnabledAttribute); // if we got this far, the embedded agent is at least installed // now check to see if its enabled - if so start it; any startup exceptions now are thrown try { if (Boolean.valueOf(enabled)) { log.info("The embedded Agent is installed and enabled - it will now be started..."); // NOTE: we cannot directly import AgentConfigurationConstants, so we hardcode the // actual constant values here - need to keep an eye on these in the unlikely event // the constant values change. String AgentConfigurationConstants_SERVER_TRANSPORT = "rhq.agent.server.transport"; String AgentConfigurationConstants_SERVER_BIND_ADDRESS = "rhq.agent.server.bind-address"; String AgentConfigurationConstants_SERVER_BIND_PORT = "rhq.agent.server.bind-port"; // Get the configuration overrides as set in the configuration file. // If the agent's bind address isn't overridden with a non-empty value, // then we need to get the Server bind address and use it for the agent's bind address. // If the agent's server endpoint address/port are empty, we again use the values // appropriate for the Server this agent is embedded in. // Note that we don't look for the values in persisted preferences - we assume they // are always present in the configuration overrides (which they should always be); Properties overrides; String serverTransport; String serverAddress; String serverPort; String agentAddress; overrides = (Properties) mbs.getAttribute(agentBootstrapMBean, configurationOverridesAttribute); serverTransport = overrides.getProperty(AgentConfigurationConstants_SERVER_TRANSPORT); serverAddress = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS); serverPort = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_PORT); agentAddress = overrides .getProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS); Server server = LookupUtil.getServerManager().getServer(); if (agentAddress == null || agentAddress.trim().equals("")) { overrides.setProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS, server.getAddress()); } if (serverAddress == null || serverAddress.trim().equals("")) { overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS, server.getAddress()); } if (serverPort == null || serverPort.trim().equals("")) { if (SecurityUtil.isTransportSecure(serverTransport)) { overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT, Integer.toString(server.getSecurePort())); } else { overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT, Integer.toString(server.getPort())); } } mbs.setAttribute(agentBootstrapMBean, new Attribute(configurationOverridesAttribute, overrides)); // We need to do the agent startup in a separate thread so we do not hang // this startup servlet. JBossAS 4.2 will not begin accepting HTTP requests // until this startup servlet has finished (this is different from JBossAS 4.0). // The agent needs to submit an HTTP request in order to complete its startup // (it needs to register with the server). // The side effect of this is the RHQ Server will still start even if the embedded // agent fails to start - this may not be a bad thing. We probably do not want // the entire RHQ Server to go down if its agent fails to start. Runnable agentStartRunnable = new Runnable() { public void run() { // this returns only when the agent has started and is registered (sends HTTP request) try { mbs.invoke(agentBootstrapMBean, startAgentMethod, new Object[0], new String[0]); } catch (Throwable t) { log.error("Failed to start the embedded Agent - it will not be available!", t); } } }; Thread agentStartThread = new Thread(agentStartRunnable, "Embedded Agent Startup"); agentStartThread.setDaemon(true); agentStartThread.start(); } else { log.debug("The embedded Agent is not enabled, so it will not be started."); } } catch (Throwable t) { throw new ServletException("Failed to start the embedded Agent.", t); } } catch (ServletException se) { throw se; } catch (Throwable t) { log.info("The embedded Agent is not installed, so it will not be started (" + t + ")."); } return; }
From source file:org.rhq.enterprise.server.core.StartupBean.java
/** * Starts the embedded agent, but only if the embedded agent is installed and it is enabled. * * @throws RuntimeException if the agent is installed and enabled but failed to start * * @deprecated we don't have an embedded agent anymore, leaving this in case we resurrect it */// w ww . j a va2s. c o m @Deprecated private void startEmbeddedAgent() throws RuntimeException { // we can't use EmbeddedAgentBootstrapServiceMBean because if the embedded agent // isn't installed, that class will not be available; we must use JMX API final ObjectName agentBootstrapMBean = ObjectNameFactory.create("rhq:service=EmbeddedAgentBootstrap"); final String agentEnabledAttribute = "AgentEnabled"; final String startAgentMethod = "startAgent"; final String configurationOverridesAttribute = "ConfigurationOverrides"; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { // this will fail if the embedded agent isn't installed String enabled = (String) mbs.getAttribute(agentBootstrapMBean, agentEnabledAttribute); // if we got this far, the embedded agent is at least installed // now check to see if its enabled - if so start it; any startup exceptions now are thrown try { if (Boolean.valueOf(enabled)) { log.info("The embedded Agent is installed and enabled - it will now be started..."); // NOTE: we cannot directly import AgentConfigurationConstants, so we hardcode the // actual constant values here - need to keep an eye on these in the unlikely event // the constant values change. String AgentConfigurationConstants_SERVER_TRANSPORT = "rhq.agent.server.transport"; String AgentConfigurationConstants_SERVER_BIND_ADDRESS = "rhq.agent.server.bind-address"; String AgentConfigurationConstants_SERVER_BIND_PORT = "rhq.agent.server.bind-port"; // Get the configuration overrides as set in the configuration file. // If the agent's bind address isn't overridden with a non-empty value, // then we need to get the Server bind address and use it for the agent's bind address. // If the agent's server endpoint address/port are empty, we again use the values // appropriate for the Server this agent is embedded in. // Note that we don't look for the values in persisted preferences - we assume they // are always present in the configuration overrides (which they should always be); Properties overrides; String serverTransport; String serverAddress; String serverPort; String agentAddress; overrides = (Properties) mbs.getAttribute(agentBootstrapMBean, configurationOverridesAttribute); serverTransport = overrides.getProperty(AgentConfigurationConstants_SERVER_TRANSPORT); serverAddress = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS); serverPort = overrides.getProperty(AgentConfigurationConstants_SERVER_BIND_PORT); agentAddress = overrides .getProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS); Server server = serverManager.getServer(); if (agentAddress == null || agentAddress.trim().equals("")) { overrides.setProperty(ServiceContainerConfigurationConstants.CONNECTOR_BIND_ADDRESS, server.getAddress()); } if (serverAddress == null || serverAddress.trim().equals("")) { overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_ADDRESS, server.getAddress()); } if (serverPort == null || serverPort.trim().equals("")) { if (SecurityUtil.isTransportSecure(serverTransport)) { overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT, Integer.toString(server.getSecurePort())); } else { overrides.setProperty(AgentConfigurationConstants_SERVER_BIND_PORT, Integer.toString(server.getPort())); } } mbs.setAttribute(agentBootstrapMBean, new Attribute(configurationOverridesAttribute, overrides)); // We need to do the agent startup in a separate thread so we do not hang // this startup servlet. JBossAS 4.2 will not begin accepting HTTP requests // until this startup servlet has finished (this is different from JBossAS 4.0). // The agent needs to submit an HTTP request in order to complete its startup // (it needs to register with the server). // The side effect of this is the RHQ Server will still start even if the embedded // agent fails to start - this may not be a bad thing. We probably do not want // the entire RHQ Server to go down if its agent fails to start. Runnable agentStartRunnable = new Runnable() { public void run() { // this returns only when the agent has started and is registered (sends HTTP request) try { mbs.invoke(agentBootstrapMBean, startAgentMethod, new Object[0], new String[0]); } catch (Throwable t) { log.error("Failed to start the embedded Agent - it will not be available!", t); } } }; Thread agentStartThread = new Thread(agentStartRunnable, "Embedded Agent Startup"); agentStartThread.setDaemon(true); agentStartThread.start(); } else { log.debug("The embedded Agent is not enabled, so it will not be started."); } } catch (Throwable t) { throw new RuntimeException("Failed to start the embedded Agent.", t); } } catch (RuntimeException se) { throw se; } catch (Throwable t) { log.info("The embedded Agent is not installed, so it will not be started (" + t + ")."); } return; }
From source file:org.rhq.plugins.jbossas.JBossASDiscoveryComponent.java
@Nullable private DiscoveredResourceDetails discoverJBossPcIsEmbeddedIn(ResourceDiscoveryContext context) { MBeanServer server = JBossMBeanUtility.getJBossMBeanServer(); try {/*from ww w. j ava 2 s . co m*/ String jnpAddress = null; String jnpPort = null; ObjectName namingObjectName = new ObjectName("jboss:service=Naming"); Set namingSet = server.queryNames(namingObjectName, null); if (namingSet.iterator().hasNext()) { jnpAddress = (String) server.getAttribute(namingObjectName, "BindAddress"); jnpPort = String.valueOf(server.getAttribute(namingObjectName, "Port")); } String bindAddress = null; ObjectName systemPropertiesObjectName = new ObjectName("jboss:name=SystemProperties,type=Service"); Set systemPropertiesSet = server.queryNames(systemPropertiesObjectName, null); if (systemPropertiesSet.iterator().hasNext()) { bindAddress = (String) server.invoke(systemPropertiesObjectName, "get", new Object[] { JBossProperties.BIND_ADDRESS }, new String[] { String.class.getName() }); } if (bindAddress == null) { bindAddress = jnpAddress; } ObjectName configObjectName = new ObjectName("jboss.system:type=ServerConfig"); Set set = server.queryNames(configObjectName, null); if (set.iterator().hasNext()) { // ServerConfig MBean found File homeDir = (File) server.getAttribute(configObjectName, "HomeDir"); JBossInstallationInfo installInfo; try { installInfo = new JBossInstallationInfo(homeDir); } catch (IOException e) { throw new IllegalStateException( "Failed to determine installation info for JBoss home dir [" + homeDir + "].", e); } File configDir = (File) server.getAttribute(configObjectName, "ServerHomeDir"); //if (isEmbeddedInServer(configDir)) { // return null; // abort - we are embedded, but we're inside the enterprise Server //} String configName = (String) server.getAttribute(configObjectName, "ServerName"); String version = (String) server.getAttribute(configObjectName, "SpecificationVersion"); Configuration pluginConfiguration = context.getDefaultPluginConfiguration(); // Set the connection type (used by JMX plugin to connect to the MBean server). pluginConfiguration.put(new PropertySimple(JMXDiscoveryComponent.CONNECTION_TYPE, InternalVMTypeDescriptor.class.getName())); pluginConfiguration .put(new PropertySimple(JBossASServerComponent.JBOSS_HOME_DIR_CONFIG_PROP, homeDir)); pluginConfiguration .put(new PropertySimple(JBossASServerComponent.CONFIGURATION_PATH_CONFIG_PROP, configDir)); pluginConfiguration .put(new PropertySimple(JBossASServerComponent.CONFIGURATION_SET_CONFIG_PROP, configName)); // Now set default values on any props that are still not set. setPluginConfigurationDefaults(pluginConfiguration); JBossProductType productType = installInfo.getProductType(); String name = formatServerName(bindAddress, jnpPort, context.getSystemInformation().getHostname(), configName, productType, isRhqServer(configDir)); String description = productType.NAME + " server that the RHQ Plugin Container is running within"; DiscoveredResourceDetails resource = new DiscoveredResourceDetails(context.getResourceType(), configDir.getAbsolutePath(), name, version, description, pluginConfiguration, null); return resource; } } catch (Exception e) { // JBoss MBean doesn't exist - not a JBoss server. log.debug("Not detected to be embedded in a JBoss AS Server", e); } return null; }
From source file:org.rhq.plugins.platform.PlatformComponent.java
public OperationResult invokeOperation(String name, Configuration parameters) throws Exception { if ("discovery".equals(name)) { Boolean detailed = parameters.getSimple("detailedDiscovery").getBooleanValue(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); String results = (String) mbs.invoke(new ObjectName("rhq.pc:type=PluginContainer"), "executeDiscovery", new Object[] { detailed }, new String[] { Boolean.class.getName() }); return new OperationResult(results); } else if ("viewProcessList".equals(name)) { OperationResult result = new OperationResult(); List<ProcessInfo> processes = this.resourceContext.getSystemInformation().getAllProcesses(); PropertyList processList = new PropertyList("processList"); for (ProcessInfo process : processes) { PropertyMap pm = new PropertyMap("process"); pm.put(new PropertySimple("pid", process.getPid())); pm.put(new PropertySimple("name", process.getBaseName())); pm.put(new PropertySimple("size", (process.getMemory() != null) ? process.getMemory().getSize() : "0")); pm.put(new PropertySimple("userTime", (process.getTime() != null) ? process.getTime().getUser() : "0")); pm.put(new PropertySimple("kernelTime", (process.getTime() != null) ? process.getTime().getSys() : "0")); processList.add(pm);// w w w . j a va 2 s .co m } result.getComplexResults().put(processList); return result; } throw new UnsupportedOperationException( "Operation [" + name + "] not supported on " + resourceContext.getResourceType() + "."); }
From source file:org.wso2.carbon.andes.core.QueueManagerServiceImpl.java
/** * {@inheritDoc}/*from w ww. j av a 2s. co m*/ */ @Override public long getNumberOfMessagesInDLCForQueue(String queueName) throws QueueManagerException { long messageCount = 0; MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); try { ObjectName objectName = new ObjectName( "org.wso2.andes:type=QueueManagementInformation,name=QueueManagementInformation"); String operationName = "getNumberOfMessagesInDLCForQueue"; Object[] parameters = new Object[] { queueName }; String[] signature = new String[] { String.class.getName() }; Object result = mBeanServer.invoke(objectName, operationName, parameters, signature); if (result != null) { messageCount = (Long) result; } return messageCount; } catch (MalformedObjectNameException | ReflectionException | MBeanException | InstanceNotFoundException e) { throw new QueueManagerException( "Cannot access mBean operations for message count in " + "DLC for a queue:" + queueName, e); } }
From source file:org.wso2.carbon.andes.core.QueueManagerServiceImpl.java
/** * {@inheritDoc}//from w w w.j a v a 2s . co m */ @Override public Message[] getMessageInDLCForQueue(String queueName, long nextMessageIdToRead, int maxMessageCount) throws QueueManagerException { List<Message> messageList = new ArrayList<>(); try { MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); ObjectName objectName = new ObjectName( "org.wso2.andes:type=QueueManagementInformation,name=QueueManagementInformation"); String operationName = "getMessageInDLCForQueue"; Object[] parameters = new Object[] { queueName, nextMessageIdToRead, maxMessageCount }; String[] signature = new String[] { String.class.getName(), long.class.getName(), int.class.getName() }; Object result = mBeanServer.invoke(objectName, operationName, parameters, signature); if (result != null) { CompositeData[] messageDataList = (CompositeData[]) result; for (CompositeData messageData : messageDataList) { Message message = new Message(); message.setMsgProperties((String) messageData.get(QueueManagementInformation.JMS_PROPERTIES)); message.setContentType((String) messageData.get(QueueManagementInformation.CONTENT_TYPE)); message.setMessageContent((String[]) messageData.get(QueueManagementInformation.CONTENT)); message.setJMSMessageId((String) messageData.get(QueueManagementInformation.JMS_MESSAGE_ID)); message.setJMSReDelivered( (Boolean) messageData.get(QueueManagementInformation.JMS_REDELIVERED)); message.setJMSDeliveredMode( (Integer) messageData.get(QueueManagementInformation.JMS_DELIVERY_MODE)); message.setJMSTimeStamp((Long) messageData.get(QueueManagementInformation.TIME_STAMP)); message.setDlcMsgDestination( (String) messageData.get(QueueManagementInformation.MSG_DESTINATION)); message.setAndesMsgMetadataId( (Long) messageData.get(QueueManagementInformation.ANDES_MSG_METADATA_ID)); messageList.add(message); } } } catch (InstanceNotFoundException | MBeanException | ReflectionException | MalformedObjectNameException e) { throw new QueueManagerException("Cannot get message in DLC for a queue : " + queueName, e); } return messageList.toArray(new org.wso2.carbon.andes.core.types.Message[messageList.size()]); }