Java Code Examples for java.rmi.registry.LocateRegistry#createRegistry()

The following examples show how to use java.rmi.registry.LocateRegistry#createRegistry() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RmiServiceExporter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Locate or create the RMI registry for this exporter.
 * @param registryPort the registry port to use
 * @return the RMI registry
 * @throws RemoteException if the registry couldn't be located or created
 */
protected Registry getRegistry(int registryPort) throws RemoteException {
	if (this.alwaysCreateRegistry) {
		logger.debug("Creating new RMI registry");
		return LocateRegistry.createRegistry(registryPort);
	}
	if (logger.isDebugEnabled()) {
		logger.debug("Looking for RMI registry at port '" + registryPort + "'");
	}
	synchronized (LocateRegistry.class) {
		try {
			// Retrieve existing registry.
			Registry reg = LocateRegistry.getRegistry(registryPort);
			testRegistry(reg);
			return reg;
		}
		catch (RemoteException ex) {
			logger.trace("RMI registry access threw exception", ex);
			logger.debug("Could not detect RMI registry - creating new one");
			// Assume no registry found -> create new one.
			return LocateRegistry.createRegistry(registryPort);
		}
	}
}
 
Example 2
Source File: JstatdTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private Registry startRegistry()
        throws InterruptedException, RemoteException {
    Registry registry = null;
    try {
        System.out.println("Start rmiregistry on port " + port);
        registry = LocateRegistry
                .createRegistry(Integer.parseInt(port));
    } catch (RemoteException e) {
        if (e.getMessage().contains("Port already in use")) {
            System.out.println("Port already in use. Trying to restart with a new one...");
            Thread.sleep(100);
            return null;
        } else {
            throw e;
        }
    }
    return registry;
}
 
Example 3
Source File: AddrInUse.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void run() {

        /*
         * Attempt to create (i.e. export) a registry on the port that
         * has already been bound, and record the result.
         */
        try {
            LocateRegistry.createRegistry(port);
            synchronized (this) {
                exportSucceeded = true;
                notifyAll();
            }
        } catch (Throwable t) {
            synchronized (this) {
                exportException = t;
                notifyAll();
            }
        }
    }
 
Example 4
Source File: RmiServiceExporter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Locate or create the RMI registry for this exporter.
 * @param registryPort the registry port to use
 * @return the RMI registry
 * @throws RemoteException if the registry couldn't be located or created
 */
protected Registry getRegistry(int registryPort) throws RemoteException {
	if (this.alwaysCreateRegistry) {
		logger.debug("Creating new RMI registry");
		return LocateRegistry.createRegistry(registryPort);
	}
	if (logger.isDebugEnabled()) {
		logger.debug("Looking for RMI registry at port '" + registryPort + "'");
	}
	synchronized (LocateRegistry.class) {
		try {
			// Retrieve existing registry.
			Registry reg = LocateRegistry.getRegistry(registryPort);
			testRegistry(reg);
			return reg;
		}
		catch (RemoteException ex) {
			logger.trace("RMI registry access threw exception", ex);
			logger.debug("Could not detect RMI registry - creating new one");
			// Assume no registry found -> create new one.
			return LocateRegistry.createRegistry(registryPort);
		}
	}
}
 
Example 5
Source File: RmiRegistryFactoryBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Locate or create the RMI registry.
 * @param registryPort the registry port to use
 * @return the RMI registry
 * @throws RemoteException if the registry couldn't be located or created
 */
protected Registry getRegistry(int registryPort) throws RemoteException {
	if (this.alwaysCreate) {
		logger.debug("Creating new RMI registry");
		this.created = true;
		return LocateRegistry.createRegistry(registryPort);
	}
	if (logger.isDebugEnabled()) {
		logger.debug("Looking for RMI registry at port '" + registryPort + "'");
	}
	synchronized (LocateRegistry.class) {
		try {
			// Retrieve existing registry.
			Registry reg = LocateRegistry.getRegistry(registryPort);
			testRegistry(reg);
			return reg;
		}
		catch (RemoteException ex) {
			logger.trace("RMI registry access threw exception", ex);
			logger.debug("Could not detect RMI registry - creating new one");
			// Assume no registry found -> create new one.
			this.created = true;
			return LocateRegistry.createRegistry(registryPort);
		}
	}
}
 
Example 6
Source File: ReuseDefaultPort.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.err.println("\nRegression test for bug 6269166\n");
    RMISocketFactory.setSocketFactory(new SF());
    Remote impl = new ReuseDefaultPort();
    Remote stub = UnicastRemoteObject.exportObject(impl, 0);
    System.err.println("- exported object: " + stub);
    try {
        Registry registry = LocateRegistry.createRegistry(PORT);
        System.err.println("- exported registry: " + registry);
        System.err.println("TEST PASSED");
    } finally {
        UnicastRemoteObject.unexportObject(impl, true);
    }
}
 
Example 7
Source File: CloseServerSocket.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
        System.err.println("\nRegression test for bug 4457683\n");

        verifyPortFree(PORT);
        Registry registry = LocateRegistry.createRegistry(PORT);
        System.err.println("- exported registry: " + registry);
        verifyPortInUse(PORT);
        UnicastRemoteObject.unexportObject(registry, true);
        System.err.println("- unexported registry");
        Thread.sleep(1000);        // work around BindException (bug?)
        verifyPortFree(PORT);

        /*
         * The follow portion of this test is disabled temporarily
         * because 4457683 was partially backed out because of
         * 6269166; for now, only server sockets originally opened for
         * exports on non-anonymous ports will be closed when all of
         * the corresponding remote objects have been exported.  A
         * separate bug will be filed to represent the remainder of
         * 4457683 for anonymous-port exports.
         */

//      SSF ssf = new SSF();
//      Remote impl = new CloseServerSocket();
//      Remote stub = UnicastRemoteObject.exportObject(impl, 0, null, ssf);
//      System.err.println("- exported object: " + stub);
//      UnicastRemoteObject.unexportObject(impl, true);
//      System.err.println("- unexported object");
//      synchronized (ssf) {
//          if (!ssf.serverSocketClosed) {
//              throw new RuntimeException("TEST FAILED: " +
//                                         "server socket not closed");
//          }
//      }

        System.err.println("TEST PASSED");
    }
 
Example 8
Source File: Server.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static String start() throws Exception {
    int serverPort = 12345;
    ObjectName name = new ObjectName("test", "foo", "bar");
    MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
    SteMBean bean = new Ste();
    jmxServer.registerMBean(bean, name);
    boolean exported = false;
    Random rnd = new Random(System.currentTimeMillis());
    do {
        try {
            LocateRegistry.createRegistry(serverPort);
            exported = true;
        } catch (ExportException ee) {
            if (ee.getCause() instanceof BindException) {
                serverPort = rnd.nextInt(10000) + 4096;
            } else {
                throw ee;
            }
        }

    } while (!exported);
    JMXServiceURL serverUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + serverPort + "/test");
    JMXConnectorServer jmxConnector = JMXConnectorServerFactory.newJMXConnectorServer(serverUrl, null, jmxServer);
    jmxConnector.start();

    return serverUrl.toString();
}
 
Example 9
Source File: ReuseDefaultPort.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.err.println("\nRegression test for bug 6269166\n");
    RMISocketFactory.setSocketFactory(new SF());
    Remote impl = new ReuseDefaultPort();
    Remote stub = UnicastRemoteObject.exportObject(impl, 0);
    System.err.println("- exported object: " + stub);
    try {
        Registry registry = LocateRegistry.createRegistry(PORT);
        System.err.println("- exported registry: " + registry);
        System.err.println("TEST PASSED");
    } finally {
        UnicastRemoteObject.unexportObject(impl, true);
    }
}
 
Example 10
Source File: RmiRegistryFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Locate or create the RMI registry.
 * @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.debug("Creating new RMI registry");
			this.created = true;
			return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("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.trace("RMI registry access threw exception", ex);
				logger.debug("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);
	}
}
 
Example 11
Source File: RMIRegistries.java    From openAGV with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a reference to a working local registry, if one already existed or a new one could be
 * installed.
 * This method first checks if a local registry at the given port is available and usable. If so,
 * a reference to it is returned, otherwise a new one is created. If that is not possible, either,
 * no reference is returned.
 *
 * @param port The port at which the registry should be listening.
 * @return A reference to a working local registry, if getting or creating a working one was
 * possible.
 */
public Optional<Registry> lookupOrInstallRegistry(int port) {
  Registry registry;
  String[] boundNames;
  LOG.debug("Checking for local RMI registry...");
  try {
    // Try to get a reference to an operating registry and test it.
    registry = LocateRegistry.getRegistry(port);
    boundNames = registry.list();
  }
  catch (RemoteException exc) {
    // No registry available, yet...
    LOG.debug("Local RMI registry unavailable, trying to create one...");
    try {
      // Try to create a new local registry and test it.
      registry = LocateRegistry.createRegistry(port,
                                               socketFactoryProvider.getClientSocketFactory(),
                                               socketFactoryProvider.getServerSocketFactory());
      boundNames = registry.list();
    }
    catch (RemoteException anotherExc) {
      // Couldn't create a working registry, either - give up.
      LOG.warn("Could not get or create a usable registry, giving up.",
               anotherExc);
      registry = null;
    }
  }
  return Optional.ofNullable(registry);
}
 
Example 12
Source File: Server.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static String start() throws Exception {
    int serverPort = 12345;
    ObjectName name = new ObjectName("test", "foo", "bar");
    MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
    SteMBean bean = new Ste();
    jmxServer.registerMBean(bean, name);
    boolean exported = false;
    Random rnd = new Random(System.currentTimeMillis());
    do {
        try {
            LocateRegistry.createRegistry(serverPort);
            exported = true;
        } catch (ExportException ee) {
            if (ee.getCause() instanceof BindException) {
                serverPort = rnd.nextInt(10000) + 4096;
            } else {
                throw ee;
            }
        }

    } while (!exported);
    JMXServiceURL serverUrl = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + serverPort + "/test");
    JMXConnectorServer jmxConnector = JMXConnectorServerFactory.newJMXConnectorServer(serverUrl, null, jmxServer);
    jmxConnector.start();

    return serverUrl.toString();
}
 
Example 13
Source File: RmiServiceExporter.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Locate or create the RMI registry for this exporter.
 * @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.alwaysCreateRegistry) {
			logger.debug("Creating new RMI registry");
			return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("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.trace("RMI registry access threw exception", ex);
				logger.debug("Could not detect RMI registry - creating new one");
				// Assume no registry found -> create new one.
				return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory);
			}
		}
	}

	else {
		return getRegistry(registryPort);
	}
}
 
Example 14
Source File: InheritedChannelNotServerSocket.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.err.println("\nRegression test for bug 6261402\n");
    System.setProperty("java.rmi.activation.port",
                       Integer.toString(TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_ACTIVATION_PORT));
    RMID rmid = null;
    Callback obj = null;
    try {
        /*
         * Export callback object and bind in registry.
         */
        System.err.println("export callback object and bind in registry");
        obj = new CallbackImpl();
        Callback proxy =
            (Callback) UnicastRemoteObject.exportObject(obj, 0);
        Registry registry =
            LocateRegistry.createRegistry(
                TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_REGISTRY_PORT);
        registry.bind("Callback", proxy);

        /*
         * Start rmid.
         */
        System.err.println("start rmid with inherited channel");
        RMID.removeLog();
        rmid = RMID.createRMID(System.out, System.err, true, true,
                               TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_ACTIVATION_PORT);
        rmid.addOptions(new String[]{
            "-Djava.nio.channels.spi.SelectorProvider=" +
            "InheritedChannelNotServerSocket$SP"});
        rmid.start();

        /*
         * Get activation system and wait to be notified via callback
         * from rmid's selector provider.
         */
        System.err.println("get activation system");
        ActivationSystem system = ActivationGroup.getSystem();
        System.err.println("ActivationSystem = " + system);
        synchronized (lock) {
            while (!notified) {
                lock.wait();
            }
        }
        System.err.println("TEST PASSED");
    } finally {
        if (obj != null) {
            UnicastRemoteObject.unexportObject(obj, true);
        }
        ActivationLibrary.rmidCleanup(rmid);
    }
}
 
Example 15
Source File: MapNullValuesTest.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        int errorCount = 0;

        MapNullValuesTest test = new MapNullValuesTest();

        // Create an RMI registry
        //
        echo("");
        echo(dashedMessage("Start RMI registry"));
        Registry reg = null;
        port = 7500;
        while (port++ < 7550) {
            try {
                reg = LocateRegistry.createRegistry(port);
                echo("\nRMI registry running on port " + port);
                break;
            } catch (RemoteException e) {
                // Failed to create RMI registry...
                //
                echo("\nFailed to create RMI registry on port " + port);
                e.printStackTrace(System.out);
            }
        }
        if (reg == null) {
            System.exit(1);
        }

        // Run tests
        //
        errorCount += test.mapToHashtableTests();
        errorCount += test.jmxConnectorServerFactoryTests();
        errorCount += test.jmxConnectorFactoryTests();
        errorCount += test.nullKeyFactoryTests();

        if (errorCount == 0) {
            echo("\nNull values for key/value pairs in Map Tests PASSED!");
        } else {
            echo("\nNull values for key/value pairs in Map Tests FAILED!");
            System.exit(1);
        }
    }
 
Example 16
Source File: RmidViaInheritedChannel.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.setProperty("java.rmi.activation.port",
                       Integer.toString(TestLibrary.RMIDVIAINHERITEDCHANNEL_ACTIVATION_PORT));
    RMID rmid = null;
    Callback obj = null;

    try {
        /*
         * Export callback object and bind in registry.
         */
        System.err.println("export callback object and bind in registry");
        obj = new RmidViaInheritedChannel();
        Callback proxy = (Callback)
            UnicastRemoteObject.exportObject(obj, 0);
        Registry registry =
            LocateRegistry.createRegistry(
                TestLibrary.RMIDVIAINHERITEDCHANNEL_REGISTRY_PORT);
        registry.bind("Callback", proxy);

        /*
         * Start rmid.
         */
        System.err.println("start rmid with inherited channel");
        RMID.removeLog();
        rmid = RMID.createRMID(System.out, System.err, true, false,
                               TestLibrary.RMIDVIAINHERITEDCHANNEL_ACTIVATION_PORT);
        rmid.addOptions(new String[]{
            "-Djava.nio.channels.spi.SelectorProvider=RmidViaInheritedChannel$RmidSelectorProvider"});
        if (System.getProperty("os.name").startsWith("Windows") &&
            System.getProperty("os.version").startsWith("5."))
        {
            /* Windows XP/2003 or older
             * Need to expand ephemeral range to include RMI test ports
             */
            rmid.addOptions(new String[]{
                "-Djdk.net.ephemeralPortRange.low=1024",
                "-Djdk.net.ephemeralPortRange.high=64000"
            });
        }
        rmid.start();

        /*
         * Get activation system and wait to be notified via callback
         * from rmid's selector provider.
         */
        System.err.println("get activation system");
        ActivationSystem system = ActivationGroup.getSystem();
        System.err.println("ActivationSystem = " + system);
        synchronized (lock) {
            while (!notified) {
                lock.wait();
            }
        }
        System.err.println("TEST PASSED");

    } finally {
        if (obj != null) {
            UnicastRemoteObject.unexportObject(obj, true);
        }
        ActivationLibrary.rmidCleanup(rmid);
    }
}
 
Example 17
Source File: JMXReporter.java    From flink with Apache License 2.0 2 votes vote down vote up
/**
 * Starts an RMI Registry that allows clients to lookup the JMX IP/port.
 *
 * @param port rmi port to use
 * @throws IOException
 */
private void startRmiRegistry(int port) throws IOException {
	rmiRegistry = LocateRegistry.createRegistry(port);
}
 
Example 18
Source File: TestLibrary.java    From TencentKona-8 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Creates an RMI {@link Registry} on an ephemeral port.
 *
 * @returns an RMI Registry
 * @throws RemoteException if there was a problem creating a Registry.
 */
public static Registry createRegistryOnEphemeralPort() throws RemoteException {
    return LocateRegistry.createRegistry(0);
}
 
Example 19
Source File: JMXReporter.java    From Flink-CEPplus with Apache License 2.0 2 votes vote down vote up
/**
 * Starts an RMI Registry that allows clients to lookup the JMX IP/port.
 *
 * @param port rmi port to use
 * @throws IOException
 */
private void startRmiRegistry(int port) throws IOException {
	rmiRegistry = LocateRegistry.createRegistry(port);
}
 
Example 20
Source File: TestLibrary.java    From jdk8u60 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Creates an RMI {@link Registry} on a random, un-reserved port.
 *
 * @returns an RMI Registry, using a random port.
 * @throws RemoteException if there was a problem creating a Registry.
 */
public static Registry createRegistryOnUnusedPort() throws RemoteException {
    return LocateRegistry.createRegistry(getUnusedRandomPort());
}