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

The following examples show how to use java.rmi.registry.LocateRegistry#getRegistry() . 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: RegistryContext.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the registry at a given host, port and socket factory.
 * If "host" is null, uses default host.
 * If "port" is non-positive, uses default port.
 * If "socketFactory" is null, uses the default socket.
 */
private static Registry getRegistry(String host, int port,
            RMIClientSocketFactory socketFactory)
        throws NamingException
{
    // %%% We could cache registry connections here.  The transport layer
    // may already reuse connections.
    try {
        if (socketFactory == null) {
            return LocateRegistry.getRegistry(host, port);
        } else {
            return LocateRegistry.getRegistry(host, port, socketFactory);
        }
    } catch (RemoteException e) {
        throw (NamingException)wrapRemoteException(e).fillInStackTrace();
    }
}
 
Example 2
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 3
Source File: RegistryContext.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the registry at a given host, port and socket factory.
 * If "host" is null, uses default host.
 * If "port" is non-positive, uses default port.
 * If "socketFactory" is null, uses the default socket.
 */
private static Registry getRegistry(String host, int port,
            RMIClientSocketFactory socketFactory)
        throws NamingException
{
    // %%% We could cache registry connections here.  The transport layer
    // may already reuse connections.
    try {
        if (socketFactory == null) {
            return LocateRegistry.getRegistry(host, port);
        } else {
            return LocateRegistry.getRegistry(host, port, socketFactory);
        }
    } catch (RemoteException e) {
        throw (NamingException)wrapRemoteException(e).fillInStackTrace();
    }
}
 
Example 4
Source File: RmiRegistryFactoryBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Locate or create the RMI registry.
 * @param registryHost the registry host to use (if this is specified,
 * no implicit creation of a RMI registry will happen)
 * @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 java.rmi.RemoteException if the registry couldn't be located or created
 */
protected Registry getRegistry(String registryHost, int registryPort,
		@Nullable RMIClientSocketFactory clientSocketFactory, @Nullable RMIServerSocketFactory serverSocketFactory)
		throws RemoteException {

	if (registryHost != null) {
		// Host explicitly specified: only lookup possible.
		if (logger.isDebugEnabled()) {
			logger.debug("Looking for RMI registry at port '" + registryPort + "' of host [" + registryHost + "]");
		}
		Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory);
		testRegistry(reg);
		return reg;
	}

	else {
		return getRegistry(registryPort, clientSocketFactory, serverSocketFactory);
	}
}
 
Example 5
Source File: JMXStartStopTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void testConnect(int port, int rmiPort) throws Exception {

        dbg_print("RmiRegistry lookup...");

        dbg_print("Using port: " + port);

        dbg_print("Using rmi port: " + rmiPort);

        Registry registry = LocateRegistry.getRegistry(port);

        // "jmxrmi"
        String[] relist = registry.list();
        for (int i = 0; i < relist.length; ++i) {
            dbg_print("Got registry: " + relist[i]);
        }

        String jmxUrlStr = (rmiPort != 0) ?
            String.format(
                "service:jmx:rmi://localhost:%d/jndi/rmi://localhost:%d/jmxrmi",
                rmiPort,
                port) :
            String.format(
                "service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi",
                port);

        JMXServiceURL url = new JMXServiceURL(jmxUrlStr);

        JMXConnector c = JMXConnectorFactory.connect(url, null);

        MBeanServerConnection conn = c.getMBeanServerConnection();
        ObjectName pattern = new ObjectName("java.lang:type=Memory,*");

        int count = listMBeans(conn,pattern,null);
        if (count == 0)
            throw new Exception("Expected at least one matching " +
                                "MBean for " + pattern);
    }
 
Example 6
Source File: SelfTerminator.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        int registryPort =
            Integer.parseInt(System.getProperty("rmi.registry.port"));
        Registry registry =
            LocateRegistry.getRegistry("", registryPort);
        Remote stub = registry.lookup(LeaseCheckInterval.BINDING);
        Runtime.getRuntime().halt(0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: Client.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public String testStub() throws Exception {
try {
    Registry registry = LocateRegistry.getRegistry(port);
    Hello stub = (Hello) registry.lookup("Hello");
    String response = stub.sayHello();
    return response;
    } catch (Exception e) {
        System.err.println("Client exception: " + e.toString());
        throw e;
    }
}
 
Example 8
Source File: Client.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public String testStub() throws Exception {
try {
    Registry registry = LocateRegistry.getRegistry(port);
    Hello stub = (Hello) registry.lookup("Hello");
    String response = stub.sayHello();
    return response;
    } catch (Exception e) {
        System.err.println("Client exception: " + e.toString());
        throw e;
    }
}
 
Example 9
Source File: RegistryFilterTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@BeforeSuite
static void setupRegistry() {
    try {
        impl = TestLibrary.createRegistryOnEphemeralPort();
        port = TestLibrary.getRegistryPort(impl);
        registry = LocateRegistry.getRegistry("localhost", port);
    } catch (RemoteException ex) {
        Assert.fail("initialization of registry", ex);
    }

    System.out.printf("RMI Registry filter: %s%n", registryFilter);
}
 
Example 10
Source File: Server.java    From OpenDA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String getInstance(IStochModelFactory.OutputLevel outputLevel)  {
    String instanceID=null;

 try {
        nModels++;
        instanceID= FactoryBindingID+"_IRmiIStochModel_"+nModels;

        // Create a new model instance
        IStochModelInstance newStochModel = stochModelFactory.getInstance(outputLevel);
        // Create a new server instance and set the new model for this instance
        Server obj = new Server();
        obj.setModel(newStochModel);

        IRmiIStochModel stub = (IRmiIStochModel) UnicastRemoteObject.exportObject(obj, 0);

        // Register this insntance such that it will not be deleted.
        allStochModels.add(stub);

       // Bind the remote object's stub in the registry
     Registry registry = LocateRegistry.getRegistry();
     registry.bind(instanceID, stub);

     System.err.println("Server has created model "+instanceID);
 } catch (Exception e) {
     System.err.println("Server exception when creating new model: " + e.toString());
     e.printStackTrace();
 }
    return instanceID;
}
 
Example 11
Source File: NoConsoleOutput.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 {
    Registry registry = TestLibrary.createRegistryOnUnusedPort();
    int registryPort = TestLibrary.getRegistryPort(registry);
    Registry reg = LocateRegistry.getRegistry("", registryPort);
    FooImpl fooimpl = new FooImpl();
    UnicastRemoteObject.exportObject(fooimpl, 0);
    reg.rebind("foo", fooimpl);
    Foo foostub = (Foo) reg.lookup("foo");
    FooImpl fooimpl2 = new FooImpl();
    UnicastRemoteObject.exportObject(fooimpl2, 0);
    foostub.echo(fooimpl2);
    UnicastRemoteObject.unexportObject(fooimpl, true);
    UnicastRemoteObject.unexportObject(fooimpl2, true);
}
 
Example 12
Source File: readTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    try {
        testPkg.Server obj = new testPkg.Server();
        testPkg.Hello stub = (testPkg.Hello) UnicastRemoteObject.exportObject(obj, 0);
        // Bind the remote object's stub in the registry
        Registry registry =
            LocateRegistry.getRegistry(TestLibrary.READTEST_REGISTRY_PORT);
        registry.bind("Hello", stub);

        System.err.println("Server ready");

        // now, let's test client
        testPkg.Client client =
            new testPkg.Client(TestLibrary.READTEST_REGISTRY_PORT);
        String testStubReturn = client.testStub();
        if(!testStubReturn.equals(obj.hello)) {
            throw new RuntimeException("Test Fails : unexpected string from stub call");
        } else {
            System.out.println("Test passed");
        }
        registry.unbind("Hello");

    } catch (Exception e) {
        System.err.println("Server exception: " + e.toString());
        e.printStackTrace();
    }

}
 
Example 13
Source File: SelfTerminator.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        int registryPort =
            Integer.parseInt(System.getProperty("rmi.registry.port"));
        Registry registry =
            LocateRegistry.getRegistry("", registryPort);
        Remote stub = registry.lookup(LeaseCheckInterval.BINDING);
        Runtime.getRuntime().halt(0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 14
Source File: Client.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public String testStub() throws Exception {
try {
    Registry registry = LocateRegistry.getRegistry(port);
    Hello stub = (Hello) registry.lookup("Hello");
    String response = stub.sayHello();
    return response;
    } catch (Exception e) {
        System.err.println("Client exception: " + e.toString());
        throw e;
    }
}
 
Example 15
Source File: Gtp.java    From FancyBing with GNU General Public License v3.0 5 votes vote down vote up
public Gtp(InputStream in, OutputStream out, int port) throws Exception {
	this.in = in;
	this.out = out;
	
	// regist RMI service
       Registry registry = null; 
       registry = LocateRegistry.getRegistry("127.0.0.1", port);
   	game = (IGame) registry.lookup("FancyBing"); 
}
 
Example 16
Source File: PinClientSocketFactory.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.err.println("\nRegression test for bug 4486732\n");

    Factory factoryImpl = new FactoryImpl();
    Factory factoryStub =
        (Factory) UnicastRemoteObject.exportObject(factoryImpl, 0);
    for (int i = 0; i < SESSIONS; i++) {
        Session session = factoryStub.getSession();
        session.ping();
    }
    UnicastRemoteObject.unexportObject(factoryImpl, true);

    Registry registryImpl = LocateRegistry.createRegistry(PORT);
    CSF csf = new CSF();
    Reference<CSF> registryRef = new WeakReference<CSF>(csf);
    Registry registryStub = LocateRegistry.getRegistry("", PORT, csf);
    csf = null;
    registryStub.list();
    registryStub = null;
    UnicastRemoteObject.unexportObject(registryImpl, true);

    System.gc();
    // allow connections to time out
    Thread.sleep(3 * Long.getLong("sun.rmi.transport.connectionTimeout",
                                  15000));
    System.gc();

    if (CSF.deserializedInstances.size() != SESSIONS) {
        throw new Error("unexpected number of deserialized instances: " +
                        CSF.deserializedInstances.size());
    }

    int nonNullCount = 0;
    for (Reference<CSF> ref : CSF.deserializedInstances) {
        csf = ref.get();
        if (csf != null) {
            System.err.println("non-null deserialized instance: " + csf);
            nonNullCount++;
        }
    }
    if (nonNullCount > 0) {
        throw new Error("TEST FAILED: " +
                        nonNullCount + " non-null deserialized instances");
    }

    csf = registryRef.get();
    if (csf != null) {
        System.err.println("non-null registry instance: " + csf);
        throw new Error("TEST FAILED: non-null registry instance");
    }

    System.err.println("TEST PASSED");
}
 
Example 17
Source File: MultipleRegistries.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 {

        RemoteInterface server = null;
        RemoteInterface proxy = null;

        try {
            System.err.println("export object");
            server = new MultipleRegistries();
            proxy =
                (RemoteInterface) UnicastRemoteObject.exportObject(server, 0);

            System.err.println("proxy = " + proxy);

            System.err.println("export registries");
            Registry registryImpl1 = TestLibrary.createRegistryOnUnusedPort();
            int port1 = TestLibrary.getRegistryPort(registryImpl1);
            Registry registryImpl2 = TestLibrary.createRegistryOnUnusedPort();
            int port2 = TestLibrary.getRegistryPort(registryImpl2);
            System.err.println("bind remote object in registries");
            Registry registry1 = LocateRegistry.getRegistry(port1);
            Registry registry2 = LocateRegistry.getRegistry(port2);

            registry1.bind(NAME, proxy);
            registry2.bind(NAME, proxy);

            System.err.println("lookup remote object in registries");

            RemoteInterface remote1 = (RemoteInterface) registry1.lookup(NAME);
            RemoteInterface remote2 = (RemoteInterface) registry2.lookup(NAME);

            System.err.println("invoke methods on remote objects");
            remote1.passObject(remote1);
            remote2.passObject(remote2);

            System.err.println("TEST PASSED");

        } finally {
            if (proxy != null) {
                UnicastRemoteObject.unexportObject(server, true);
            }
        }
    }
 
Example 18
Source File: MultipleRegistries.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        RemoteInterface server = null;
        RemoteInterface proxy = null;

        try {
            System.err.println("export object");
            server = new MultipleRegistries();
            proxy =
                (RemoteInterface) UnicastRemoteObject.exportObject(server, 0);

            System.err.println("proxy = " + proxy);

            System.err.println("export registries");
            Registry registryImpl1 = TestLibrary.createRegistryOnUnusedPort();
            int port1 = TestLibrary.getRegistryPort(registryImpl1);
            Registry registryImpl2 = TestLibrary.createRegistryOnUnusedPort();
            int port2 = TestLibrary.getRegistryPort(registryImpl2);
            System.err.println("bind remote object in registries");
            Registry registry1 = LocateRegistry.getRegistry(port1);
            Registry registry2 = LocateRegistry.getRegistry(port2);

            registry1.bind(NAME, proxy);
            registry2.bind(NAME, proxy);

            System.err.println("lookup remote object in registries");

            RemoteInterface remote1 = (RemoteInterface) registry1.lookup(NAME);
            RemoteInterface remote2 = (RemoteInterface) registry2.lookup(NAME);

            System.err.println("invoke methods on remote objects");
            remote1.passObject(remote1);
            remote2.passObject(remote2);

            System.err.println("TEST PASSED");

        } finally {
            if (proxy != null) {
                UnicastRemoteObject.unexportObject(server, true);
            }
        }
    }
 
Example 19
Source File: HandshakeFailure.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        /*
         * Listen on port...
         */
        ServerSocket serverSocket = new ServerSocket(PORT);

        /*
         * (Attempt RMI call to port in separate thread.)
         */
        Registry registry = LocateRegistry.getRegistry(PORT);
        Connector connector = new Connector(registry);
        Thread t = new Thread(connector);
        t.setDaemon(true);
        t.start();

        /*
         * ...accept one connection from port and send non-JRMP data.
         */
        Socket socket = serverSocket.accept();
        socket.getOutputStream().write("Wrong way".getBytes());
        socket.close();

        /*
         * Wait for call attempt to finish, and analyze result.
         */
        t.join(TIMEOUT);
        synchronized (connector) {
            if (connector.success) {
                throw new RuntimeException(
                    "TEST FAILED: remote call succeeded??");
            }
            if (connector.exception == null) {
                throw new RuntimeException(
                    "TEST FAILED: remote call did not time out");
            } else {
                System.err.println("remote call failed with exception:");
                connector.exception.printStackTrace();
                System.err.println();

                if (connector.exception instanceof MarshalException) {
                    System.err.println(
                        "TEST FAILED: MarshalException thrown, expecting " +
                        "java.rmi.ConnectException or ConnectIOException");
                } else if (connector.exception instanceof ConnectException ||
                           connector.exception instanceof ConnectIOException)
                {
                    System.err.println(
                        "TEST PASSED: java.rmi.ConnectException or " +
                        "ConnectIOException thrown");
                } else {
                    throw new RuntimeException(
                        "TEST FAILED: unexpected Exception thrown",
                        connector.exception);
                }
            }
        }
    }
 
Example 20
Source File: HandshakeTimeout.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        System.setProperty("sun.rmi.transport.tcp.handshakeTimeout",
                           String.valueOf(TIMEOUT / 2));

        /*
         * Listen on port, but never process connections made to it.
         */
        ServerSocket serverSocket = new ServerSocket(PORT);

        /*
         * Attempt RMI call to port in separate thread.
         */
        Registry registry = LocateRegistry.getRegistry(PORT);
        Connector connector = new Connector(registry);
        Thread t = new Thread(connector);
        t.setDaemon(true);
        t.start();

        /*
         * Wait for call attempt to finished, and analyze result.
         */
        t.join(TIMEOUT);
        synchronized (connector) {
            if (connector.success) {
                throw new RuntimeException(
                    "TEST FAILED: remote call succeeded??");
            }
            if (connector.exception == null) {
                throw new RuntimeException(
                    "TEST FAILED: remote call did not time out");
            } else {
                System.err.println("remote call failed with exception:");
                connector.exception.printStackTrace();
                System.err.println();

                if (connector.exception instanceof MarshalException) {
                    System.err.println(
                        "TEST FAILED: MarshalException thrown, expecting " +
                        "java.rmi.ConnectException or ConnectIOException");
                } else if (connector.exception instanceof ConnectException ||
                           connector.exception instanceof ConnectIOException)
                {
                    System.err.println(
                        "TEST PASSED: java.rmi.ConnectException or " +
                        "ConnectIOException thrown");
                } else {
                    throw new RuntimeException(
                        "TEST FAILED: unexpected Exception thrown",
                        connector.exception);
                }
            }
        }
    }