List of usage examples for java.rmi.registry LocateRegistry createRegistry
public static Registry createRegistry(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf) throws RemoteException
Registry
instance on the local host that uses custom socket factories for communication with that instance. From source file:org.apache.james.modules.server.JMXServer.java
private void doStart() { try {/*from ww w . j a v a 2s . c om*/ PropertiesConfiguration configuration = new PropertiesConfiguration( fileSystem.getFile(FileSystem.FILE_PROTOCOL_AND_CONF + "jmx.properties")); String address = configuration.getString("jmx.address"); int port = configuration.getInt("jmx.port"); String serviceURL = "service:jmx:rmi://" + address + "/jndi/rmi://" + address + ":" + port + "/jmxrmi"; RestrictingRMISocketFactory restrictingRMISocketFactory = new RestrictingRMISocketFactory(address); LocateRegistry.createRegistry(port, restrictingRMISocketFactory, restrictingRMISocketFactory); Map<String, ?> environment = ImmutableMap.of(); jmxConnectorServer = JMXConnectorServerFactory.newJMXConnectorServer(new JMXServiceURL(serviceURL), environment, ManagementFactory.getPlatformMBeanServer()); jmxConnectorServer.start(); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:net.timewalker.ffmq4.jmx.rmi.JMXOverRMIAgent.java
private void init() throws JMSException { try {// w w w. ja va2s .com log.info("Starting JMX agent"); // Get or create an RMI registry if (rmiListenAddr == null || rmiListenAddr.equals("auto")) rmiListenAddr = InetAddress.getLocalHost().getHostName(); // Connector JNDI name String jndiName = "jmxconnector-" + agentName; try { registry = LocateRegistry.getRegistry(rmiListenAddr, jndiRmiPort); registry.lookup(jndiName); // Remove the old registered connector registry.unbind(jndiName); log.debug("RMI registry found at " + rmiListenAddr + ":" + jndiRmiPort + " with connector already registered"); } catch (NotBoundException e) { // Registry already exists log.debug("RMI registry found at " + rmiListenAddr + ":" + jndiRmiPort); } catch (RemoteException e) { log.debug("Creating RMI registry at " + rmiListenAddr + ":" + jndiRmiPort); RMIServerSocketFactory ssf = new JMXOverRMIServerSocketFactory(10, rmiListenAddr, false); registry = LocateRegistry.createRegistry(jndiRmiPort, null, ssf); } // Get the JVM MBean server mBeanServer = ManagementFactory.getPlatformMBeanServer(); // Service URL JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + rmiListenAddr + "/jndi/rmi://" + rmiListenAddr + ":" + jndiRmiPort + "/" + jndiName); log.info("JMX Service URL : " + url); // Create and start the RMIConnectorServer Map<String, Object> env = new HashMap<>(); mBeanServerSocketFactory = new JMXOverRMIServerSocketFactory(10, rmiListenAddr, true); env.put(RMIConnectorServer.JNDI_REBIND_ATTRIBUTE, "true"); //env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, new JMXRMIClientSocketFactory(rmiListenAddr)); env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, mBeanServerSocketFactory); connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mBeanServer); connectorServer.start(); } catch (Exception e) { throw new FFMQException("Could not initialize JMX agent", "JMX_ERROR", e); } }
From source file:org.jgentleframework.integration.remoting.rmi.support.RmiExecutor.java
/** * Gets the registry.//from w w w. ja v a 2 s. co m * * @param registryPort * the registry port * @param clientSocketFactory * the client socket factory * @param serverSocketFactory * the server socket factory * @param autoCreateRegistry * the auto create registry * @return {@link Registry} * @throws RemoteException * the remote exception */ public static Registry getRegistry(boolean autoCreateRegistry, int registryPort, RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory) throws RemoteException { if (clientSocketFactory != null) { if (autoCreateRegistry) { return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory); } try { Registry reg = LocateRegistry.getRegistry(null, registryPort, clientSocketFactory); testRegistry(reg); return reg; } catch (RemoteException ex) { return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory); } } else { return getRegistry(autoCreateRegistry, registryPort); } }
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;//w w w . jav a 2 s. 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.springframework.remoting.rmi.RmiRegistryFactoryBean.java
/** * Locate or create the RMI registry.//from w w w. j a v a 2 s . c om * @param registryPort the registry port to use * @param clientSocketFactory the RMI client socket factory for the registry (if any) * @param serverSocketFactory the RMI server socket factory for the registry (if any) * @return the RMI registry * @throws RemoteException if the registry couldn't be located or created */ protected Registry getRegistry(int registryPort, @Nullable RMIClientSocketFactory clientSocketFactory, @Nullable RMIServerSocketFactory serverSocketFactory) throws RemoteException { if (clientSocketFactory != null) { if (this.alwaysCreate) { logger.info("Creating new RMI registry"); this.created = true; return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory); } if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "', using custom socket factory"); } synchronized (LocateRegistry.class) { try { // Retrieve existing registry. Registry reg = LocateRegistry.getRegistry(null, registryPort, clientSocketFactory); testRegistry(reg); return reg; } catch (RemoteException ex) { logger.debug("RMI registry access threw exception", ex); logger.info("Could not detect RMI registry - creating new one"); // Assume no registry found -> create new one. this.created = true; return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory); } } } else { return getRegistry(registryPort); } }
From source file:org.ut.biolab.medsavant.server.MedSavantServerEngine.java
public MedSavantServerEngine(String databaseHost, int databasePort, String rootUserName, String password) throws RemoteException, SQLException, SessionExpiredException { host = databaseHost;/*from w w w .j ava 2 s .com*/ port = databasePort; rootName = rootUserName; pass = password; try { // get the address of this host. thisAddress = (InetAddress.getLocalHost()).toString(); } catch (Exception e) { throw new RemoteException("Can't get inet address."); } listenOnPort = MedSavantServerUnicastRemoteObject.getListenPort(); if (!performPreemptiveSystemCheck()) { System.out.println("System check FAILED, see errors above"); System.exit(1); } System.out.println("Server Information:"); System.out.println(" SERVER VERSION: " + VersionSettings.getVersionString() + "\n" + " SERVER ADDRESS: " + thisAddress + "\n" + " LISTENING ON PORT: " + listenOnPort + "\n" + " EXPORT PORT: " + MedSavantServerUnicastRemoteObject.getExportPort() + "\n" + " MAX THREADS: " + maxThreads + "\n" + " MAX IO THREADS: " + MAX_IO_JOBS + "\n"); //+ " EXPORTING ON PORT: " + MedSavantServerUnicastRemoteObject.getExportPort()); try { // create the registry and bind the name and object. if (isTLSRequired()) { System.out.println("SSL/TLS Encryption is enabled, Client authentication is " + (isClientAuthRequired() ? "required." : "NOT required.")); } else { System.out.println("SSL/TLS Encryption is NOT enabled"); //registry = LocateRegistry.createRegistry(listenOnPort); } registry = LocateRegistry.createRegistry(listenOnPort, getDefaultClientSocketFactory(), getDefaultServerSocketFactory()); //TODO: get these from the user ConnectionController.setHost(databaseHost); ConnectionController.setPort(databasePort); System.out.println(); System.out.println("Database Information:"); System.out.println(" DATABASE ADDRESS: " + databaseHost + "\n" + " DATABASE PORT: " + databasePort); System.out.println(" DATABASE USER: " + rootUserName); if (password == null) { System.out.print(" PASSWORD FOR " + rootUserName + ": "); System.out.flush(); char[] pass = System.console().readPassword(); password = new String(pass); } System.out.print("Connecting to database ... "); try { ConnectionController.connectOnce(databaseHost, databasePort, "", rootUserName, password); } catch (SQLException ex) { System.out.println("FAILED"); throw ex; } System.out.println("OK"); bindAdapters(registry); System.out.println("\nServer initialized, waiting for incoming connections..."); EmailLogger.logByEmail("Server booted", "The MedSavant Server Engine successfully booted."); } catch (RemoteException e) { throw e; } catch (SessionExpiredException e) { throw e; } }
From source file:org.apache.geode.management.internal.ManagementAgent.java
/** * http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html #gdfvq * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors * https://blogs.oracle.com/jmxetc/entry/building_a_remotely_stoppable_connector * https://blogs.oracle.com/jmxetc/entry/jmx_connecting_through_firewalls_using * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors */// ww w . j av a 2 s . co m private void configureAndStart() throws IOException { // get the port for RMI Registry and RMI Connector Server final int port = this.config.getJmxManagerPort(); final String hostname; final InetAddress bindAddr; if (StringUtils.isBlank(this.config.getJmxManagerBindAddress())) { hostname = SocketCreator.getLocalHost().getHostName(); bindAddr = null; } else { hostname = this.config.getJmxManagerBindAddress(); bindAddr = InetAddress.getByName(hostname); } String jmxManagerHostnameForClients = this.config.getJmxManagerHostnameForClients(); if (StringUtils.isNotBlank(jmxManagerHostnameForClients)) { System.setProperty("java.rmi.server.hostname", jmxManagerHostnameForClients); } final SocketCreator socketCreator = SocketCreatorFactory .getSocketCreatorForComponent(SecurableCommunicationChannel.JMX); final boolean ssl = socketCreator.useSSL(); if (logger.isDebugEnabled()) { logger.debug("Starting jmx manager agent on port {}{}", port, (bindAddr != null ? (" bound to " + bindAddr) : "") + (ssl ? " using SSL" : "")); } RMIClientSocketFactory rmiClientSocketFactory = ssl ? new SslRMIClientSocketFactory() : null; RMIServerSocketFactory rmiServerSocketFactory = new GemFireRMIServerSocketFactory(socketCreator, bindAddr); // Following is done to prevent rmi causing stop the world gcs System.setProperty("sun.rmi.dgc.server.gcInterval", Long.toString(Long.MAX_VALUE - 1)); // Create the RMI Registry using the SSL socket factories above. // In order to use a single port, we must use these factories // everywhere, or nowhere. Since we want to use them in the JMX // RMI Connector server, we must also use them in the RMI Registry. // Otherwise, we wouldn't be able to use a single port. // Start an RMI registry on port <port>. registry = LocateRegistry.createRegistry(port, rmiClientSocketFactory, rmiServerSocketFactory); // Retrieve the PlatformMBeanServer. MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); // Environment map. why is this declared as HashMap? final HashMap<String, Object> env = new HashMap<>(); // Manually creates and binds a JMX RMI Connector Server stub with the // registry created above: the port we pass here is the port that can // be specified in "service:jmx:rmi://"+hostname+":"+port - where the // RMI server stub and connection objects will be exported. // Here we choose to use the same port as was specified for the // RMI Registry. We can do so because we're using \*the same\* client // and server socket factories, for the registry itself \*and\* for this // object. final RMIServerImpl stub = new RMIJRMPServerImpl(port, rmiClientSocketFactory, rmiServerSocketFactory, env); // Create an RMI connector server. // // As specified in the JMXServiceURL the RMIServer stub will be // registered in the RMI registry running in the local host on // port <port> with the name "jmxrmi". This is the same name the // out-of-the-box management agent uses to register the RMIServer // stub too. // // The port specified in "service:jmx:rmi://"+hostname+":"+port // is the second port, where RMI connection objects will be exported. // Here we use the same port as that we choose for the RMI registry. // The port for the RMI registry is specified in the second part // of the URL, in "rmi://"+hostname+":"+port // // We construct a JMXServiceURL corresponding to what we have done // for our stub... final JMXServiceURL url = new JMXServiceURL( "service:jmx:rmi://" + hostname + ":" + port + "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi"); // Create an RMI connector server with the JMXServiceURL // // JDK 1.5 cannot use JMXConnectorServerFactory because of // http://bugs.sun.com/view_bug.do?bug_id=5107423 // but we're using JDK 1.6 jmxConnectorServer = new RMIConnectorServer(new JMXServiceURL("rmi", hostname, port), env, stub, mbs) { @Override public JMXServiceURL getAddress() { return url; } @Override public synchronized void start() throws IOException { try { registry.bind("jmxrmi", stub); } catch (AlreadyBoundException x) { throw new IOException(x.getMessage(), x); } super.start(); } }; if (securityService.isIntegratedSecurity()) { shiroAuthenticator = new JMXShiroAuthenticator(this.securityService); env.put(JMXConnectorServer.AUTHENTICATOR, shiroAuthenticator); jmxConnectorServer.addNotificationListener(shiroAuthenticator, null, jmxConnectorServer.getAttributes()); // always going to assume authorization is needed as well, if no custom AccessControl, then // the CustomAuthRealm // should take care of that MBeanServerWrapper mBeanServerWrapper = new MBeanServerWrapper(this.securityService); jmxConnectorServer.setMBeanServerForwarder(mBeanServerWrapper); registerAccessControlMBean(); } else { /* Disable the old authenticator mechanism */ String pwFile = this.config.getJmxManagerPasswordFile(); if (pwFile != null && pwFile.length() > 0) { env.put("jmx.remote.x.password.file", pwFile); } String accessFile = this.config.getJmxManagerAccessFile(); if (accessFile != null && accessFile.length() > 0) { // Rewire the mbs hierarchy to set accessController ReadOpFileAccessController controller = new ReadOpFileAccessController(accessFile); controller.setMBeanServer(mbs); } } jmxConnectorServer.start(); if (logger.isDebugEnabled()) { logger.debug("Finished starting jmx manager agent."); } }
From source file:org.apache.jackrabbit.j2ee.RepositoryStartupServlet.java
/** * Registers the repository to an RMI registry configured in the web * application. See <a href="#registerAlgo">Registration with RMI</a> in the * class documentation for a description of the algorithms used to register * the repository with an RMI registry.//ww w. j av a2s .c o m * @throws ServletException if an error occurs. */ private void registerRMI() { RMIConfig rc = config.getRmiConfig(); if (!rc.isValid() || !rc.enabled()) { return; } // try to create remote repository Remote remote; try { Class<?> clazz = Class.forName(getRemoteFactoryDelegaterClass()); RemoteFactoryDelegater rmf = (RemoteFactoryDelegater) clazz.newInstance(); remote = rmf.createRemoteRepository(repository); } catch (RemoteException e) { log.warn("Unable to create RMI repository.", e); return; } catch (Throwable t) { log.warn("Unable to create RMI repository." + " The jcr-rmi jar might be missing.", t); return; } try { System.setProperty("java.rmi.server.useCodebaseOnly", "true"); Registry reg = null; // first try to create the registry, which will fail if another // application is already running on the configured host/port // or if the rmiHost is not local try { // find the server socket factory: use the default if the // rmiHost is not configured RMIServerSocketFactory sf; if (rc.getRmiHost().length() > 0) { log.debug("Creating RMIServerSocketFactory for host " + rc.getRmiHost()); InetAddress hostAddress = InetAddress.getByName(rc.getRmiHost()); sf = getRMIServerSocketFactory(hostAddress); } else { // have the RMI implementation decide which factory is the // default actually log.debug("Using default RMIServerSocketFactory"); sf = null; } // create a registry using the default client socket factory // and the server socket factory retrieved above. This also // binds to the server socket to the rmiHost:rmiPort. reg = LocateRegistry.createRegistry(rc.rmiPort(), null, sf); rmiRegistry = reg; } catch (UnknownHostException uhe) { // thrown if the rmiHost cannot be resolved into an IP-Address // by getRMIServerSocketFactory log.info("Cannot create Registry", uhe); } catch (RemoteException e) { // thrown by createRegistry if binding to the rmiHost:rmiPort // fails, for example due to rmiHost being remote or another // application already being bound to the port log.info("Cannot create Registry", e); } // if creation of the registry failed, we try to access an // potentially active registry. We do not check yet, whether the // registry is actually accessible. if (reg == null) { log.debug("Trying to access existing registry at " + rc.getRmiHost() + ":" + rc.getRmiPort()); try { reg = LocateRegistry.getRegistry(rc.getRmiHost(), rc.rmiPort()); } catch (RemoteException re) { log.warn("Cannot create the reference to the registry at " + rc.getRmiHost() + ":" + rc.getRmiPort(), re); } } // if we finally have a registry, register the repository with the // rmiName if (reg != null) { log.debug("Registering repository as " + rc.getRmiName() + " to registry " + reg); reg.bind(rc.getRmiName(), remote); // when successfull, keep references this.rmiRepository = remote; log.info("Repository bound via RMI with name: " + rc.getRmiUri()); } else { log.info("RMI registry missing, cannot bind repository via RMI"); } } catch (RemoteException e) { log.warn("Unable to bind repository via RMI: " + rc.getRmiUri(), e); } catch (AlreadyBoundException e) { log.warn("Unable to bind repository via RMI: " + rc.getRmiUri(), e); } }