List of usage examples for javax.management.remote JMXServiceURL JMXServiceURL
public JMXServiceURL(String serviceURL) throws MalformedURLException
Constructs a JMXServiceURL
by parsing a Service URL string.
From source file:org.apache.geode.tools.pulse.internal.data.JMXDataUpdater.java
/** * Get the jmx connection/*from ww w .j a v a 2 s. c o m*/ */ public JMXConnector connect(String username, String password) { // Reference to repository Repository repository = Repository.get(); try { String jmxSerURL = ""; logger.info("{}:{}", resourceBundle.getString("LOG_MSG_USE_LOCATOR_VALUE"), repository.getJmxUseLocator()); if (repository.getJmxUseLocator()) { JmxManagerInfo jmxManagerInfo = getManagerInfoFromLocator(repository); if (jmxManagerInfo.port == 0) { logger.info(resourceBundle.getString("LOG_MSG_LOCATOR_COULD_NOT_FIND_MANAGER")); } else { logger.info("{}: {}={} & {}={}, {}", resourceBundle.getString("LOG_MSG_LOCATOR_FOUND_MANAGER"), resourceBundle.getString("LOG_MSG_HOST"), jmxManagerInfo.host, resourceBundle.getString("LOG_MSG_PORT"), jmxManagerInfo.port, (jmxManagerInfo.ssl ? resourceBundle.getString("LOG_MSG_WITH_SSL") : resourceBundle.getString("LOG_MSG_WITHOUT_SSL"))); jmxSerURL = formJMXServiceURLString(jmxManagerInfo.host, String.valueOf(jmxManagerInfo.port)); } } else { logger.info("{}={} & {}={}", resourceBundle.getString("LOG_MSG_HOST"), this.serverName, resourceBundle.getString("LOG_MSG_PORT"), this.port); jmxSerURL = formJMXServiceURLString(this.serverName, this.port); } if (StringUtils.isNotBlank(jmxSerURL)) { JMXServiceURL url = new JMXServiceURL(jmxSerURL); String[] creds = { username, password }; Map<String, Object> env = new HashMap<String, Object>(); env.put(JMXConnector.CREDENTIALS, creds); if (repository.isUseSSLManager()) { // use ssl to connect env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory()); } logger.info("Connecting to jmxURL : {}", jmxSerURL); this.conn = JMXConnectorFactory.connect(url, env); this.mbs = this.conn.getMBeanServerConnection(); cluster.setConnectedFlag(true); } } catch (Exception e) { cluster.setConnectedFlag(false); cluster.setConnectionErrorMsg(e.getMessage()); logger.fatal(e.getMessage(), e); if (this.conn != null) { try { this.conn.close(); } catch (Exception e1) { logger.fatal(e1.getMessage(), e1); } this.conn = null; } } return this.conn; }
From source file:org.wso2.andes.server.management.JMXManagedObjectRegistry.java
public void start() throws IOException, ConfigurationException { CurrentActor.get().message(ManagementConsoleMessages.STARTUP()); //check if system properties are set to use the JVM's out-of-the-box JMXAgent if (areOutOfTheBoxJMXOptionsSet()) { CurrentActor.get().message(ManagementConsoleMessages.READY(true)); return;/*from w w w .j a va2s.c o m*/ } IApplicationRegistry appRegistry = ApplicationRegistry.getInstance(); int port = appRegistry.getConfiguration().getJMXManagementPort(); //Socket factories for the RMIConnectorServer, either default or SLL depending on configuration RMIClientSocketFactory csf; RMIServerSocketFactory ssf; //check ssl enabled option in config, default to true if option is not set boolean sslEnabled = appRegistry.getConfiguration().getManagementSSLEnabled(); if (sslEnabled) { //set the SSL related system properties used by the SSL RMI socket factories to the values //given in the configuration file, unless command line settings have already been specified String keyStorePath; if (System.getProperty("javax.net.ssl.keyStore") != null) { keyStorePath = System.getProperty("javax.net.ssl.keyStore"); } else { keyStorePath = appRegistry.getConfiguration().getManagementKeyStorePath(); } //check the keystore path value is valid if (keyStorePath == null) { throw new ConfigurationException("JMX management SSL keystore path not defined, " + "unable to start SSL protected JMX ConnectorServer"); } else { //ensure the system property is set System.setProperty("javax.net.ssl.keyStore", keyStorePath); //check the file is usable File ksf = new File(keyStorePath); if (!ksf.exists()) { throw new FileNotFoundException("Cannot find JMX management SSL keystore file " + ksf + "\n" + "Check broker configuration, or see create-example-ssl-stores script" + "in the bin/ directory if you need to generate an example store."); } if (!ksf.canRead()) { throw new FileNotFoundException( "Cannot read JMX management SSL keystore file: " + ksf + ". Check permissions."); } CurrentActor.get().message(ManagementConsoleMessages.SSL_KEYSTORE(ksf.getAbsolutePath())); } //check the key store password is set if (System.getProperty("javax.net.ssl.keyStorePassword") == null) { if (appRegistry.getConfiguration().getManagementKeyStorePassword() == null) { throw new ConfigurationException("JMX management SSL keystore password not defined, " + "unable to start requested SSL protected JMX server"); } else { System.setProperty("javax.net.ssl.keyStorePassword", appRegistry.getConfiguration().getManagementKeyStorePassword()); } } //create the SSL RMI socket factories csf = new SslRMIClientSocketFactory(); ssf = new SslRMIServerSocketFactory(); } else { //Do not specify any specific RMI socket factories, resulting in use of the defaults. csf = null; ssf = null; } //add a JMXAuthenticator implementation the env map to authenticate the RMI based JMX connector server RMIPasswordAuthenticator rmipa = new RMIPasswordAuthenticator(); rmipa.setAuthenticationManager(appRegistry.getAuthenticationManager()); HashMap<String, Object> env = new HashMap<String, Object>(); env.put(JMXConnectorServer.AUTHENTICATOR, rmipa); /* * Start a RMI registry on the management port, to hold the JMX RMI ConnectorServer stub. * Using custom socket factory to prevent anyone (including us unfortunately) binding to the registry using RMI. * As a result, only binds made using the object reference will succeed, thus securing it from external change. */ System.setProperty("java.rmi.server.randomIDs", "true"); if (_useCustomSocketFactory) { _rmiRegistry = LocateRegistry.createRegistry(port, null, new CustomRMIServerSocketFactory()); } else { _rmiRegistry = LocateRegistry.createRegistry(port, null, null); } CurrentActor.get().message(ManagementConsoleMessages.LISTENING("RMI Registry", port)); /* * We must now create the RMI ConnectorServer manually, as the JMX Factory methods use RMI calls * to bind the ConnectorServer to the registry, which will now fail as for security we have * locked it from any RMI based modifications, including our own. Instead, we will manually bind * the RMIConnectorServer stub to the registry using its object reference, which will still succeed. * * The registry is exported on the defined management port 'port'. We will export the RMIConnectorServer * on 'port +1'. Use of these two well-defined ports will ease any navigation through firewall's. */ final RMIServerImpl rmiConnectorServerStub = new RMIJRMPServerImpl(port + PORT_EXPORT_OFFSET, csf, ssf, env); String localHost; try { localHost = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ex) { localHost = "127.0.0.1"; } final String hostname = localHost; final JMXServiceURL externalUrl = new JMXServiceURL("service:jmx:rmi://" + hostname + ":" + (port + PORT_EXPORT_OFFSET) + "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi"); final JMXServiceURL internalUrl = new JMXServiceURL("rmi", hostname, port + PORT_EXPORT_OFFSET); _cs = new RMIConnectorServer(internalUrl, env, rmiConnectorServerStub, _mbeanServer) { @Override public synchronized void start() throws IOException { try { //manually bind the connector server to the registry at key 'jmxrmi', like the out-of-the-box agent _rmiRegistry.bind("jmxrmi", rmiConnectorServerStub); } catch (AlreadyBoundException abe) { //key was already in use. shouldnt happen here as its a new registry, unbindable by normal means. //IOExceptions are the only checked type throwable by the method, wrap and rethrow IOException ioe = new IOException(abe.getMessage()); ioe.initCause(abe); throw ioe; } //now do the normal tasks super.start(); } @Override public synchronized void stop() throws IOException { try { if (_rmiRegistry != null) { _rmiRegistry.unbind("jmxrmi"); } } catch (NotBoundException nbe) { //ignore } //now do the normal tasks super.stop(); } @Override public JMXServiceURL getAddress() { //must return our pre-crafted url that includes the full details, inc JNDI details return externalUrl; } }; //Add the custom invoker as an MBeanServerForwarder, and start the RMIConnectorServer. MBeanServerForwarder mbsf = MBeanInvocationHandlerImpl.newProxyInstance(); _cs.setMBeanServerForwarder(mbsf); NotificationFilterSupport filter = new NotificationFilterSupport(); filter.enableType(JMXConnectionNotification.OPENED); filter.enableType(JMXConnectionNotification.CLOSED); filter.enableType(JMXConnectionNotification.FAILED); // Get the handler that is used by the above MBInvocationHandler Proxy. // which is the MBeanInvocationHandlerImpl and so also a NotificationListener _cs.addNotificationListener((NotificationListener) Proxy.getInvocationHandler(mbsf), filter, null); _cs.start(); String connectorServer = (sslEnabled ? "SSL " : "") + "JMX RMIConnectorServer"; CurrentActor.get().message(ManagementConsoleMessages.LISTENING(connectorServer, port + PORT_EXPORT_OFFSET)); CurrentActor.get().message(ManagementConsoleMessages.READY(false)); }
From source file:org.helios.collector.jmx.connection.AbstractMBeanServerConnectionFactory.java
/** * Creates and returns a JMXServiceURL for a proxy connection to this proxy MBeanServer * @param shared true for shared physical connections, false for a dedicated connection * @return JMXServiceURL/*w w w . j av a 2 s . c o m*/ */ protected JMXServiceURL getServiceURL(boolean shared) { String url = null; try { //url = MessageFormat.format(LOCAL_JMX_SERVICE_TEMPLATE, hostId, vmId, defaultDomain, shared); url = hspProtocol.formatServiceURL(objectName, shared); return new JMXServiceURL(url); } catch (Exception e) { throw new RuntimeException("Failed to create LocalServiceURL for [" + url + "]", e); } }
From source file:org.mule.module.management.agent.AbstractJmxAgent.java
public void start() throws MuleException { try {/*ww w .j a v a 2 s . c o m*/ // TODO cleanup rmi registry creation too initRMI(); if (connectorServerUrl == null) { return; } logger.info("Creating and starting JMX agent connector Server"); JMXServiceURL url = new JMXServiceURL(connectorServerUrl); if (connectorServerProperties == null) { connectorServerProperties = new HashMap<String, Object>(DEFAULT_CONNECTOR_SERVER_PROPERTIES); } if (!credentials.isEmpty()) { connectorServerProperties.put(JMXConnectorServer.AUTHENTICATOR, this.getJmxAuthenticator()); } connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, connectorServerProperties, mBeanServer); connectorServer.start(); } catch (ExportException e) { throw new JmxManagementException(CoreMessages.failedToStart("Jmx Agent"), e); } catch (Exception e) { throw new JmxManagementException(CoreMessages.failedToStart("Jmx Agent"), e); } }
From source file:org.apereo.portal.jmx.JavaManagementServerBean.java
/** * Generates the JMXServiceURL for the two specified ports. * //w w w . j a va 2 s . c o m * @return A JMXServiceURL for this host using the two specified ports. * @throws IllegalStateException If localhost cannot be resolved or if the JMXServiceURL is malformed. */ protected JMXServiceURL getServiceUrl(final int portOne, int portTwo) { final String jmxHost; if (this.host == null) { final InetAddress inetHost; try { inetHost = InetAddress.getLocalHost(); } catch (UnknownHostException uhe) { throw new IllegalStateException("Cannot resolve localhost InetAddress.", uhe); } jmxHost = inetHost.getHostName(); } else { jmxHost = this.host; } final String jmxUrl = "service:jmx:rmi://" + jmxHost + ":" + portTwo + "/jndi/rmi://" + jmxHost + ":" + portOne + "/server"; final JMXServiceURL jmxServiceUrl; try { jmxServiceUrl = new JMXServiceURL(jmxUrl); } catch (MalformedURLException mue) { throw new IllegalStateException("Failed to create JMXServiceURL for url String '" + jmxUrl + "'", mue); } if (this.logger.isDebugEnabled()) { this.logger.debug("Generated JMXServiceURL='" + jmxServiceUrl + "' from String " + jmxUrl + "'."); } return jmxServiceUrl; }
From source file:org.jumpmind.symmetric.JmxCommand.java
protected <T> T execute(IJmxTemplate<T> template) throws Exception { String host = "localhost"; String url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + System.getProperty("jmx.agent.port", "31418") + "/jmxrmi"; JMXServiceURL serviceUrl = new JMXServiceURL(url); JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceUrl, null); TypedProperties properties = getTypedProperties(); String engineName = properties.get(ParameterConstants.ENGINE_NAME, "unknown"); try {// w w w .jav a 2s . com MBeanServerConnection mbeanConn = jmxConnector.getMBeanServerConnection(); return template.execute(engineName, mbeanConn); } finally { jmxConnector.close(); } }
From source file:org.jboss.as.test.integration.domain.rbac.JmxRBACProviderHostScopedRolesTestCase.java
private void test(String userName) throws Exception { String urlString = System.getProperty("jmx.service.url", "service:jmx:remoting-jmx://" + NetworkUtils.formatPossibleIpv6Address(masterClientConfig.getHostControllerManagementAddress()) + ":12345"); JmxManagementInterface jmx = JmxManagementInterface.create(new JMXServiceURL(urlString), userName, RbacAdminCallbackHandler.STD_PASSWORD, null // not needed, as the only thing from JmxManagementInterface used in this test is getConnection() );/* w ww .j a v a 2 s .co m*/ try { getAttribute(userName, jmx); setAttribute(userName, jmx); dumpServices(userName, jmx); operationReadOnly(userName, jmx); operationWriteOnly(userName, jmx); operationReadWrite(userName, jmx); operationUnknown(userName, jmx); deactivateMBeanSensitivity(); getAttribute(userName, jmx); setAttribute(userName, jmx); dumpServices(userName, jmx); operationReadOnly(userName, jmx); operationWriteOnly(userName, jmx); operationReadWrite(userName, jmx); operationUnknown(userName, jmx); } finally { jmx.close(); } }
From source file:org.jboss.wsf.test.JBossWSTestHelper.java
private static MBeanServerConnection getServerConnection(String jmxServiceUrl) { final String urlString = System.getProperty("jmx.service.url", jmxServiceUrl); JMXServiceURL serviceURL = null; JMXConnector connector = null; try {/*from w ww.j a va 2 s. co m*/ serviceURL = new JMXServiceURL(urlString); } catch (MalformedURLException e1) { throw new IllegalStateException(e1); } //add more tries to get the connection. Workaround to fix some test failures caused by connection is not established in 5 seconds for (int i = 0; i < AS_SERVER_CONN_RETRIEVAL_ATTEMPTS && connector == null; i++) { try { connector = JMXConnectorFactory.connect(serviceURL, null); } catch (IOException ex) { throw new IllegalStateException("Cannot obtain MBeanServerConnection to: " + urlString, ex); } catch (RuntimeException e) { if (e.getMessage().contains("WAITING") && i < AS_SERVER_CONN_RETRIEVAL_ATTEMPTS - 1) { continue; } else { throw e; } } } try { return connector.getMBeanServerConnection(); } catch (Exception e) { throw new IllegalStateException("Cannot obtain MBeanServerConnection to: " + urlString, e); } }
From source file:com.pivotal.gemfire.tools.pulse.internal.data.JMXDataUpdater.java
private JMXConnector getJMXConnection() { JMXConnector connection = null; // Reference to repository Repository repository = Repository.get(); try {/* ww w. jav a 2 s. c o m*/ String jmxSerURL = ""; if (LOGGER.infoEnabled()) { LOGGER.info(resourceBundle.getString("LOG_MSG_USE_LOCATOR_VALUE") + ":" + repository.getJmxUseLocator()); } if (repository.getJmxUseLocator()) { String locatorHost = repository.getJmxHost(); int locatorPort = Integer.parseInt(repository.getJmxPort()); if (LOGGER.infoEnabled()) { LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + locatorHost + " & " + resourceBundle.getString("LOG_MSG_PORT") + " : " + locatorPort); } InetAddress inetAddr = InetAddress.getByName(locatorHost); if ((inetAddr instanceof Inet4Address) || (inetAddr instanceof Inet6Address)) { if (inetAddr instanceof Inet4Address) { // Locator has IPv4 Address if (LOGGER.infoEnabled()) { LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV4_ADDRESS") + " - " + inetAddr.toString()); } } else { // Locator has IPv6 Address if (LOGGER.infoEnabled()) { LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_IPV6_ADDRESS") + " - " + inetAddr.toString()); } } JmxManagerInfo jmxManagerInfo = JmxManagerFinder.askLocatorForJmxManager(inetAddr, locatorPort, 15000, repository.isUseSSLLocator()); if (jmxManagerInfo.port == 0) { if (LOGGER.infoEnabled()) { LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_COULD_NOT_FIND_MANAGER")); } } else { if (LOGGER.infoEnabled()) { LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_FOUND_MANAGER") + " : " + resourceBundle.getString("LOG_MSG_HOST") + " : " + jmxManagerInfo.host + " & " + resourceBundle.getString("LOG_MSG_PORT") + " : " + jmxManagerInfo.port + (jmxManagerInfo.ssl ? resourceBundle.getString("LOG_MSG_WITH_SSL") : resourceBundle.getString("LOG_MSG_WITHOUT_SSL"))); } jmxSerURL = formJMXServiceURLString(jmxManagerInfo.host, String.valueOf(jmxManagerInfo.port)); } } /* * else if (inetAddr instanceof Inet6Address) { // Locator has IPv6 * Address if(LOGGER.infoEnabled()){ * LOGGER.info(resourceBundle.getString * ("LOG_MSG_LOCATOR_IPV6_ADDRESS")); } // update message to display * on UI cluster.setConnectionErrorMsg(resourceBundle.getString( * "LOG_MSG_JMX_CONNECTION_IPv6_ADDRESS")); * * } */else { // Locator has Invalid locator Address if (LOGGER.infoEnabled()) { LOGGER.info(resourceBundle.getString("LOG_MSG_LOCATOR_BAD_ADDRESS")); } // update message to display on UI cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_BAD_ADDRESS")); } } else { if (LOGGER.infoEnabled()) { LOGGER.info(resourceBundle.getString("LOG_MSG_HOST") + " : " + this.serverName + " & " + resourceBundle.getString("LOG_MSG_PORT") + " : " + this.port); } jmxSerURL = formJMXServiceURLString(this.serverName, this.port); } if (StringUtils.isNotNullNotEmptyNotWhiteSpace(jmxSerURL)) { JMXServiceURL url = new JMXServiceURL(jmxSerURL); // String[] creds = {"controlRole", "R&D"}; String[] creds = { this.userName, this.userPassword }; Map<String, Object> env = new HashMap<String, Object>(); env.put(JMXConnector.CREDENTIALS, creds); if (repository.isUseSSLManager()) { // use ssl to connect env.put("com.sun.jndi.rmi.factory.socket", new SslRMIClientSocketFactory()); } connection = JMXConnectorFactory.connect(url, env); // Register Pulse URL if not already present in the JMX Manager registerPulseUrlToManager(connection); } } catch (Exception e) { if (e instanceof UnknownHostException) { // update message to display on UI cluster.setConnectionErrorMsg(resourceBundle.getString("LOG_MSG_JMX_CONNECTION_UNKNOWN_HOST")); } // write errors StringWriter swBuffer = new StringWriter(); PrintWriter prtWriter = new PrintWriter(swBuffer); e.printStackTrace(prtWriter); LOGGER.severe("Exception Details : " + swBuffer.toString() + "\n"); if (this.conn != null) { try { this.conn.close(); } catch (Exception e1) { LOGGER.severe("Error closing JMX connection " + swBuffer.toString() + "\n"); } this.conn = null; } } return connection; }
From source file:org.red5.server.jmx.JMXAgent.java
public void init() { //environmental var holder HashMap env = null;/*from w w w.j av a2s . co m*/ if (enableHtmlAdapter) { // setup the adapter try { //instance an html adaptor int port = htmlAdapterPort == null ? 8082 : Integer.valueOf(htmlAdapterPort); html = new HtmlAdaptorServer(port); ObjectName htmlName = new ObjectName( JMXFactory.getDefaultDomain() + ":type=HtmlAdaptorServer,port=" + port); log.debug("Created HTML adaptor on port: " + port); //add the adaptor to the server mbs.registerMBean(html, htmlName); //start the adaptor html.start(); log.info("JMX HTML connector server successfully started"); } catch (Exception e) { log.error("Error in setup of JMX subsystem (HTML adapter)", e); } } else { log.info("JMX HTML adapter was not enabled"); } if (enableRmiAdapter) { // Create an RMI connector server log.debug("Create an RMI connector server"); try { Registry r = null; try { //lookup the registry r = LocateRegistry.getRegistry(Integer.valueOf(rmiAdapterPort)); //ensure we are not already registered with the registry for (String regName : r.list()) { if (regName.equals("red5")) { //unbind connector from rmi registry r.unbind("red5"); } } } catch (RemoteException re) { log.info("RMI Registry server was not found on port " + rmiAdapterPort); //if we didnt find the registry and the user wants it created if (startRegistry) { log.info("Starting an internal RMI registry"); // create registry for rmi port 9999 r = LocateRegistry.createRegistry(Integer.valueOf(rmiAdapterPort)); } } JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + rmiAdapterPort + "/red5"); //if SSL is requested to secure rmi connections if (enableSsl) { // Environment map log.debug("Initialize the environment map"); env = new HashMap(); // Provide SSL-based RMI socket factories SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory(); SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory(); env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf); env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf); } //if authentication is requested if (StringUtils.isNotBlank(remoteAccessProperties)) { //if ssl is not used this will be null if (null == env) { env = new HashMap(); } //check the existance of the files //in the war version the full path is needed File file = new File(remoteAccessProperties); if (!file.exists()) { log.debug("Access file was not found on path, will prepend config_root"); //pre-pend the system property set in war startup remoteAccessProperties = System.getProperty("red5.config_root") + '/' + remoteAccessProperties; remotePasswordProperties = System.getProperty("red5.config_root") + '/' + remotePasswordProperties; } env.put("jmx.remote.x.access.file", remoteAccessProperties); env.put("jmx.remote.x.password.file", remotePasswordProperties); } // create the connector server cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs); // add a listener for shutdown cs.addNotificationListener(this, null, null); // Start the RMI connector server log.debug("Start the RMI connector server"); cs.start(); log.info("JMX RMI connector server successfully started"); } catch (ConnectException e) { log.warn("Could not establish RMI connection to port " + rmiAdapterPort + ", please make sure \"rmiregistry\" is running and configured to listen on this port."); } catch (IOException e) { String errMsg = e.getMessage(); if (errMsg.indexOf("NameAlreadyBoundException") != -1) { log.error("JMX connector (red5) already registered, you will need to restart your rmiregistry"); } else { log.error("{}", e); } } catch (Exception e) { log.error("Error in setup of JMX subsystem (RMI connector)", e); } } else { log.info("JMX RMI adapter was not enabled"); } }