Java Examples for java.rmi.registry.LocateRegistry

The following java examples will help you to understand the usage of java.rmi.registry.LocateRegistry. These source code samples are taken from different open source projects.

Example 1
Project: jdk7u-jdk-master  File: AppleUserImpl.java View source code
/**
     * Entry point for the "juicer" server process.  Create and export
     * an apple user implementation in an rmiregistry running on localhost.
     */
public static void main(String[] args) {
    String durationString = null;
    boolean othervm = false;
    boolean exit = false;
    try {
        // parse command line args
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.equals("-hours")) {
                if (durationString != null) {
                    usage();
                }
                i++;
                int hours = Integer.parseInt(args[i]);
                durationString = hours + " hours";
                testDuration = hours * 60 * 60 * 1000;
            } else if (arg.equals("-seconds")) {
                if (durationString != null) {
                    usage();
                }
                i++;
                long seconds = Long.parseLong(args[i]);
                durationString = seconds + " seconds";
                testDuration = seconds * 1000;
            } else if (arg.equals("-maxLevel")) {
                i++;
                maxLevel = Integer.parseInt(args[i]);
            } else if (arg.equals("-othervm")) {
                othervm = true;
            } else if (arg.equals("-exit")) {
                exit = true;
            } else {
                usage();
            }
        }
        if (durationString == null) {
            durationString = testDuration + " milliseconds";
        }
    } catch (Throwable t) {
        usage();
        throw new RuntimeException("TEST FAILED: Bad argument");
    }
    AppleUserImpl user = null;
    long startTime = 0;
    Thread server = null;
    int exitValue = 0;
    try {
        user = new AppleUserImpl();
        synchronized (user) {
            // create new registry and bind new AppleUserImpl in registry
            LocateRegistry.createRegistry(2006);
            LocateRegistry.getRegistry(2006).rebind("AppleUser", user);
            // start the other server if applicable
            if (othervm) {
                // the other server must be running in a separate process
                logger.log(Level.INFO, "Application server must be " + "started in separate process");
            } else {
                Class app = Class.forName("ApplicationServer");
                server = new Thread((Runnable) app.newInstance());
                logger.log(Level.INFO, "Starting application server " + "in same process");
                server.start();
            }
            // wait for other server to call startTest method
            logger.log(Level.INFO, "Waiting for application server " + "process to start");
            while (!startTestNotified) {
                user.wait();
            }
        }
        startTime = System.currentTimeMillis();
        logger.log(Level.INFO, "Test starting");
        // wait for exception to be reported or first thread to complete
        logger.log(Level.INFO, "Waiting " + durationString + " for " + "test to complete or exception to be thrown");
        synchronized (lock) {
            while (status == null && !finished) {
                lock.wait();
            }
        }
        if (status != null) {
            throw new RuntimeException("TEST FAILED: " + "juicer server reported an exception", status);
        } else {
            logger.log(Level.INFO, "TEST PASSED");
        }
    } catch (Exception e) {
        logger.log(Level.INFO, "TEST FAILED");
        exitValue = 1;
        if (exit) {
            e.printStackTrace();
        }
        throw new RuntimeException("TEST FAILED: " + "unexpected exception", e);
    } finally {
        long actualDuration = System.currentTimeMillis() - startTime;
        logger.log(Level.INFO, "Test finished");
        try {
            UnicastRemoteObject.unexportObject(user, true);
        } catch (NoSuchObjectException ignore) {
        }
        logger.log(Level.INFO, "Test duration was " + (actualDuration / 1000) + " seconds " + "(" + (actualDuration / 3600000) + " hours)");
        System.gc();
        System.gc();
        if (exit) {
            System.exit(exitValue);
        }
    }
}
Example 2
Project: ManagedRuntimeInitiative-master  File: MapNullValuesTest.java View source code
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) {
            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 3
Project: openjdk8-jdk-master  File: AppleUserImpl.java View source code
/**
     * Entry point for the "juicer" server process.  Create and export
     * an apple user implementation in an rmiregistry running on localhost.
     */
public static void main(String[] args) {
    String durationString = null;
    boolean othervm = false;
    boolean exit = false;
    try {
        // parse command line args
        for (int i = 0; i < args.length; i++) {
            String arg = args[i];
            if (arg.equals("-hours")) {
                if (durationString != null) {
                    usage();
                }
                i++;
                int hours = Integer.parseInt(args[i]);
                durationString = hours + " hours";
                testDuration = hours * 60 * 60 * 1000;
            } else if (arg.equals("-seconds")) {
                if (durationString != null) {
                    usage();
                }
                i++;
                long seconds = Long.parseLong(args[i]);
                durationString = seconds + " seconds";
                testDuration = seconds * 1000;
            } else if (arg.equals("-maxLevel")) {
                i++;
                maxLevel = Integer.parseInt(args[i]);
            } else if (arg.equals("-othervm")) {
                othervm = true;
            } else if (arg.equals("-exit")) {
                exit = true;
            } else {
                usage();
            }
        }
        if (durationString == null) {
            durationString = testDuration + " milliseconds";
        }
    } catch (Throwable t) {
        usage();
        throw new RuntimeException("TEST FAILED: Bad argument");
    }
    AppleUserImpl user = null;
    long startTime = 0;
    Thread server = null;
    int exitValue = 0;
    try {
        user = new AppleUserImpl();
        synchronized (user) {
            // create new registry and bind new AppleUserImpl in registry
            Registry registry = TestLibrary.createRegistryOnUnusedPort();
            registryPort = TestLibrary.getRegistryPort(registry);
            LocateRegistry.getRegistry(registryPort).rebind("AppleUser", user);
            // start the other server if applicable
            if (othervm) {
                // the other server must be running in a separate process
                logger.log(Level.INFO, "Application server must be " + "started in separate process");
            } else {
                Class app = Class.forName("ApplicationServer");
                java.lang.reflect.Constructor appConstructor = app.getDeclaredConstructor(new Class[] { Integer.TYPE });
                server = new Thread((Runnable) appConstructor.newInstance(registryPort));
                logger.log(Level.INFO, "Starting application server " + "in same process");
                server.start();
            }
            // wait for other server to call startTest method
            logger.log(Level.INFO, "Waiting for application server " + "process to start");
            while (!startTestNotified) {
                user.wait();
            }
        }
        startTime = System.currentTimeMillis();
        logger.log(Level.INFO, "Test starting");
        // wait for exception to be reported or first thread to complete
        logger.log(Level.INFO, "Waiting " + durationString + " for " + "test to complete or exception to be thrown");
        synchronized (lock) {
            while (status == null && !finished) {
                lock.wait();
            }
        }
        if (status != null) {
            throw new RuntimeException("TEST FAILED: " + "juicer server reported an exception", status);
        } else {
            logger.log(Level.INFO, "TEST PASSED");
        }
    } catch (Exception e) {
        logger.log(Level.INFO, "TEST FAILED");
        exitValue = 1;
        if (exit) {
            e.printStackTrace();
        }
        throw new RuntimeException("TEST FAILED: " + "unexpected exception", e);
    } finally {
        long actualDuration = System.currentTimeMillis() - startTime;
        logger.log(Level.INFO, "Test finished");
        try {
            UnicastRemoteObject.unexportObject(user, true);
        } catch (NoSuchObjectException ignore) {
        }
        logger.log(Level.INFO, "Test duration was " + (actualDuration / 1000) + " seconds " + "(" + (actualDuration / 3600000) + " hours)");
        System.gc();
        System.gc();
        if (exit) {
            System.exit(exitValue);
        }
    }
}
Example 4
Project: openjdk-master  File: Main.java View source code
/**
     * Setup benchmark server.
     */
static void setupServer() {
    switch(runmode) {
        case SAMEVM:
            try {
                serverImpl = new BenchServerImpl();
                server = (BenchServer) RemoteObject.toStub(serverImpl);
            } catch (RemoteException e) {
                die("Error: failed to create local server: " + e);
            }
            if (verbose)
                System.out.println("Benchmark server created locally");
            break;
        case CLIENT:
            try {
                Registry reg = LocateRegistry.getRegistry(host, port);
                server = (BenchServer) reg.lookup(REGNAME);
            } catch (NotBoundExceptionRemoteException |  e) {
                die("Error: failed to connect to server: " + e);
            }
            if (server == null) {
                die("Error: server not found");
            }
            if (verbose) {
                System.out.println("Connected to benchmark server on " + host + ":" + port);
            }
            break;
        case SERVER:
            try {
                Registry reg = LocateRegistry.createRegistry(port);
                serverImpl = new BenchServerImpl();
                reg.bind(REGNAME, serverImpl);
            } catch (AlreadyBoundExceptionRemoteException |  e) {
                die("Error: failed to initialize server: " + e);
            }
            if (verbose) {
                System.out.println("Benchmark server started on port " + port);
            }
            break;
        default:
            throw new InternalError("illegal runmode");
    }
}
Example 5
Project: btpka3.github.com-master  File: MyServer.java View source code
public static void main(String[] args) throws Exception {
    // start RMI server
    // or CMD/> rmiregistry 9999
    LocateRegistry.createRegistry(9999);
    // setup MBeanServer
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    MyServer s = new MyServer();
    ObjectName objName = new ObjectName("MyServer:type=Hello");
    mbs.registerMBean(s, objName);
    // start JMXConnectorServer
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    System.out.println("MBeanServer start");
}
Example 6
Project: interface_sdk-master  File: ModuleRMIHelper.java View source code
@Override
protected ModuleManagerRemote getManager() throws ModuleManagerCommunicationException {
    Registry registry;
    try {
        registry = LocateRegistry.getRegistry("localhost", ModuleManagerRunner.RMI_REGISTRY_PORT);
        ModuleManagerRemote obj = (ModuleManagerRemote) registry.lookup(ModuleManagerRunner.RMI_SERVER_NAME);
        log.debug("Got an instance of ModuleManager via RMI?");
        return obj;
    } catch (RemoteException e) {
        throw new ModuleManagerCommunicationException();
    } catch (NotBoundException e) {
        throw new ModuleManagerCommunicationException();
    }
}
Example 7
Project: eclipselink.runtime-master  File: DistributedCacheMergeTest.java View source code
protected void setup() throws Exception {
    originalSession = getExecutor().getSession();
    originalSession.getIdentityMapAccessor().initializeAllIdentityMaps();
    createObject();
    try {
        LocateRegistry.createRegistry(41099);
    } catch (Exception e) {
    }
    cluster1Session = buildSession("cluster1");
    cluster1Session.login();
    cluster2Session = buildSession("cluster2");
    cluster2Session.login();
    // Let the Cache-sync get configured.
    Thread.sleep(5000);
    policy1 = disableOptimisticLocking(cluster1Session);
    policy2 = disableOptimisticLocking(cluster2Session);
}
Example 8
Project: JBossAS51-master  File: JMXConnectorServerService.java View source code
public void start() throws Exception {
    // the address to expose in the urls
    String host = System.getProperty("java.rmi.server.hostname");
    // check to see if registry already created
    rmiRegistry = LocateRegistry.getRegistry(host, registryPort);
    if (rmiRegistry != null) {
        try {
            rmiRegistry.list();
        } catch (RemoteException e) {
            log.debug("No registry running at host '" + host + "', port '" + registryPort + "'.  Will create one.");
            rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
        }
    } else {
        rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
    }
    String serviceURL = "service:jmx:rmi://" + host + "/jndi/rmi://" + host + ":" + registryPort + jndiPath;
    JMXServiceURL url = new JMXServiceURL(serviceURL);
    // create new connector server and start it
    final Map<String, Object> environment = new HashMap<String, Object>();
    final DefaultSocketFactory clientSocketFactory = new DefaultSocketFactory();
    clientSocketFactory.setBindAddress(bindAddress.getHostAddress());
    environment.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, clientSocketFactory);
    connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, mbeanServer);
    connectorServer.start();
    log.info("JMX Connector server: " + serviceURL);
}
Example 9
Project: org.ops4j.pax.swissbox-master  File: RemoteFrameworkImpl.java View source code
private void export() throws RemoteException, AccessException {
    String port = System.getProperty(RMI_PORT_KEY, "1099");
    name = System.getProperty(RMI_NAME_KEY);
    timeout = Long.parseLong(System.getProperty(TIMEOUT_KEY, "10000"));
    registry = LocateRegistry.getRegistry(Integer.parseInt(port));
    URL location1 = getClass().getProtectionDomain().getCodeSource().getLocation();
    URL location2 = Bundle.class.getProtectionDomain().getCodeSource().getLocation();
    URL location3 = ServiceLookup.class.getProtectionDomain().getCodeSource().getLocation();
    System.setProperty("java.rmi.server.codebase", location1 + " " + location2 + " " + location3);
    Remote remote = UnicastRemoteObject.exportObject(this, 0);
    registry.rebind(name, remote);
}
Example 10
Project: JBossAS_5_1_EDG-master  File: JMXConnectorServerService.java View source code
public void start() throws Exception {
    // the address to expose in the urls
    String host = System.getProperty("java.rmi.server.hostname");
    // check to see if registry already created
    rmiRegistry = LocateRegistry.getRegistry(host, registryPort);
    if (rmiRegistry != null) {
        try {
            rmiRegistry.list();
        } catch (RemoteException e) {
            log.debug("No registry running at host '" + host + "', port '" + registryPort + "'.  Will create one.");
            rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
        }
    } else {
        rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
    }
    String serviceURL = "service:jmx:rmi://" + host + "/jndi/rmi://" + host + ":" + registryPort + jndiPath;
    JMXServiceURL url = new JMXServiceURL(serviceURL);
    // create new connector server and start it
    final Map<String, Object> environment = new HashMap<String, Object>();
    final DefaultSocketFactory clientSocketFactory = new DefaultSocketFactory();
    clientSocketFactory.setBindAddress(bindAddress.getHostAddress());
    environment.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, clientSocketFactory);
    connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, mbeanServer);
    connectorServer.start();
    log.info("JMX Connector server: " + serviceURL);
}
Example 11
Project: spring-framework-2.5.x-master  File: RmiClientInterceptor.java View source code
/**
	 * Create the RMI stub, typically by looking it up.
	 * <p>Called on interceptor initialization if "cacheStub" is "true";
	 * else called for each invocation by {@link #getStub()}.
	 * <p>The default implementation looks up the service URL via
	 * <code>java.rmi.Naming</code>. This can be overridden in subclasses.
	 * @return the RMI stub to store in this interceptor
	 * @throws RemoteLookupFailureException if RMI stub creation failed
	 * @see #setCacheStub
	 * @see java.rmi.Naming#lookup
	 */
protected Remote lookupStub() throws RemoteLookupFailureException {
    try {
        Remote stub = null;
        if (this.registryClientSocketFactory != null) {
            // RMIClientSocketFactory specified for registry access.
            // Unfortunately, due to RMI API limitations, this means
            // that we need to parse the RMI URL ourselves and perform
            // straight LocateRegistry.getRegistry/Registry.lookup calls.
            URL url = new URL(null, getServiceUrl(), new DummyURLStreamHandler());
            String protocol = url.getProtocol();
            if (protocol != null && !"rmi".equals(protocol)) {
                throw new MalformedURLException("Invalid URL scheme '" + protocol + "'");
            }
            String host = url.getHost();
            int port = url.getPort();
            String name = url.getPath();
            if (name != null && name.startsWith("/")) {
                name = name.substring(1);
            }
            Registry registry = LocateRegistry.getRegistry(host, port, this.registryClientSocketFactory);
            stub = registry.lookup(name);
        } else {
            // Can proceed with standard RMI lookup API...
            stub = Naming.lookup(getServiceUrl());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Located RMI stub with URL [" + getServiceUrl() + "]");
        }
        return stub;
    } catch (MalformedURLException ex) {
        throw new RemoteLookupFailureException("Service URL [" + getServiceUrl() + "] is invalid", ex);
    } catch (NotBoundException ex) {
        throw new RemoteLookupFailureException("Could not find RMI service [" + getServiceUrl() + "] in RMI registry", ex);
    } catch (RemoteException ex) {
        throw new RemoteLookupFailureException("Lookup of RMI stub failed", ex);
    }
}
Example 12
Project: open-mika-master  File: Naming.java View source code
private static Registry getRegistry(String url, StringBuffer name) throws MalformedURLException, RemoteException {
    int port = Registry.REGISTRY_PORT;
    String host = "localhost";
    if (url.startsWith("rmi:")) {
        url = url.substring(4);
    }
    if (url.startsWith("//")) {
        int index = url.indexOf("/", 2);
        if (index == -1) {
            throw new MalformedURLException("no name specified in: " + url);
        }
        host = url.substring(2, index);
        url = url.substring(index + 1);
        index = host.indexOf(":");
        if (index != -1) {
            try {
                port = Integer.parseInt(host.substring(index + 1));
            } catch (NumberFormatException nfe) {
                throw new MalformedURLException("invalid port");
            }
            host = host.substring(0, index);
        }
    }
    name.append(url);
    if (host.length() == 0) {
        host = "localhost";
    }
    return LocateRegistry.getRegistry(host, port);
}
Example 13
Project: wso2-synapse-master  File: RMIRegistryController.java View source code
/**
     * Creates a RMI local registry with given port
     *
     * @param port The port of the RMI registry to be created
     */
public void createLocalRegistry(int port) {
    try {
        String key = toKey(port);
        synchronized (registriesCache) {
            if (registriesCache.containsKey(key)) {
                if (log.isDebugEnabled()) {
                    log.debug("There is an RMI registry bound to given port :" + port);
                }
                return;
            }
            Registry locateRegistry = LocateRegistry.createRegistry(port);
            if (locateRegistry == null) {
                handleException("Unable to create a RMI registry with port : " + port);
            }
            registriesCache.put(key, locateRegistry);
        }
    } catch (RemoteException e) {
        String msg = "Couldn't create a local registry(RMI) : port " + port + " already in use.";
        handleException(msg, e);
    }
}
Example 14
Project: classlib6-master  File: Main.java View source code
private void run(String[] args) {
    Parser p = initializeParser();
    p.parse(args);
    try {
        if (!stop) {
            // Start the system.
            File dataDirectory = new File(directory);
            if (!dataDirectory.exists())
                dataDirectory.mkdirs();
            ActivationSystem system;
            if (!persistent)
                system = ActivationSystemTransient.getInstance();
            else
                system = ActivationSystemImpl.getInstance(dataDirectory, cold);
            // We must export with the specific activation id that is only
            // possible when going into the gnu.java.rmi.activation.
            UnicastServerRef sref = new UnicastServerRef(new ObjID(ObjID.ACTIVATOR_ID), ACTIVATION_REGISTRY_PORT, ACTIVATION_REGISTY_SOCKET_FACTORY);
            Remote systemStub = sref.exportObject(system);
            // Start the naming system on the activation system port
            // (if not already running).
            Registry r;
            try {
                // Expect the naming service running first.
                // The local host may want to use the shared registry
                r = LocateRegistry.getRegistry(ACTIVATION_REGISTRY_PORT);
                r.rebind(ACTIVATION_SYSTEM_NAME, systemStub);
            } catch (Exception ex) {
                r = LocateRegistry.createRegistry(ACTIVATION_REGISTRY_PORT);
                r.rebind(ACTIVATION_SYSTEM_NAME, systemStub);
            }
            String host = InetAddress.getLocalHost().getCanonicalHostName();
            System.out.println("The RMI daemon is listening on " + host + " (port " + ACTIVATION_REGISTRY_PORT + ")");
        } else {
            // Stop the activation system.
            Registry r;
            try {
                System.out.print("Stopping RMI daemon at " + ACTIVATION_REGISTRY_PORT + " ... ");
                // Expect the naming service running first.
                // The local host may want to use the shared registry
                r = LocateRegistry.getRegistry(ACTIVATION_REGISTRY_PORT);
                ActivationSystem asys = (ActivationSystem) r.lookup(ACTIVATION_SYSTEM_NAME);
                asys.shutdown();
                System.out.println("OK.");
            } catch (Exception ex) {
                System.out.println("The RMI daemon seems not running at " + ACTIVATION_REGISTRY_PORT);
                if (ActivationSystemTransient.debug)
                    ex.printStackTrace();
            }
        }
    } catch (Exception e) {
        System.out.println("Failed to start the RMI daemon.");
        if (ActivationSystemTransient.debug)
            e.printStackTrace();
    }
}
Example 15
Project: Payara-master  File: EventListenerProxy.java View source code
public static synchronized EventListenerProxy getEventListenerProxy() {
    if (eventProxy == null) {
        EventListenerProxy newProxy = null;
        try {
            newProxy = new EventListenerProxy();
            Naming.rebind(newProxy.proxyAddress, newProxy);
            eventProxy = newProxy;
            if (debug)
                System.out.println(eventProxy.rmiName + " bound to existing registry at port " + portnum);
        } catch (RemoteException re) {
            if (debug)
                System.out.println("Naming.rebind(" + (newProxy != null ? newProxy.proxyAddress : "null") + ", eventProxy): " + re);
            try {
                newProxy = new EventListenerProxy();
                Registry r = LocateRegistry.createRegistry(portnum);
                r.bind(newProxy.rmiName, newProxy);
                eventProxy = newProxy;
                if (debug)
                    System.out.println(newProxy.rmiName + " bound to newly created registry at port " + portnum);
            } catch (Exception e) {
                eventProxy = null;
                if (debug)
                    e.printStackTrace();
            }
        } catch (Exception e) {
            if (debug)
                e.printStackTrace();
        }
    }
    return eventProxy;
}
Example 16
Project: glassfish-main-master  File: EventListenerProxy.java View source code
public static EventListenerProxy getEventListenerProxy() {
    if (eventProxy == null) {
        try {
            eventProxy = new EventListenerProxy();
            Naming.rebind(proxyAddress, eventProxy);
            if (debug)
                System.out.println(rmiName + " bound to existing registry at port " + portnum);
        } catch (RemoteException re) {
            if (debug)
                System.out.println("Naming.rebind(" + proxyAddress + ", eventProxy): " + re);
            try {
                eventProxy = new EventListenerProxy();
                Registry r = LocateRegistry.createRegistry(portnum);
                r.bind(rmiName, eventProxy);
                if (debug)
                    System.out.println(rmiName + " bound to newly created registry at port " + portnum);
            } catch (Exception e) {
                eventProxy = null;
                if (debug)
                    e.printStackTrace();
            }
        } catch (Exception e) {
            if (debug)
                e.printStackTrace();
        }
    }
    return eventProxy;
}
Example 17
Project: resin-master  File: RmiRegistry.java View source code
/**
   * Start the RMI registry in the local JVM, if it has not been started
   * already.
   */
private void startRegistry() throws ResourceAdapterInternalException {
    /**
     * Some tricks are required here, the RMI Registry needs to be
     * started from the system classloader.
     */
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();
    try {
        thread.setContextClassLoader(ClassLoader.getSystemClassLoader());
        try {
            Registry reg = LocateRegistry.getRegistry(_port);
            // Verify it's alive and well
            reg.list();
            if (log.isLoggable(Level.CONFIG))
                log.config(L.l("found RMI Registry on port `{0}'", _port));
        } catch (Exception e) {
            if (log.isLoggable(Level.CONFIG))
                log.config(L.l("creating RMI Registry on port `{0}'", _port));
            LocateRegistry.createRegistry(_port);
        }
    } catch (Exception ex) {
        throw new ResourceAdapterInternalException(ex);
    } finally {
        thread.setContextClassLoader(oldLoader);
    }
}
Example 18
Project: ikvm-openjdk-master  File: Jstatd.java View source code
static void bind(String name, RemoteHostImpl remoteHost) throws RemoteException, MalformedURLException, Exception {
    try {
        Naming.rebind(name, remoteHost);
    } catch (java.rmi.ConnectException e) {
        if (startRegistry && registry == null) {
            int localport = (port < 0) ? Registry.REGISTRY_PORT : port;
            registry = LocateRegistry.createRegistry(localport);
            bind(name, remoteHost);
        } else {
            System.out.println("Could not contact registry\n" + e.getMessage());
            e.printStackTrace();
        }
    } catch (RemoteException e) {
        System.err.println("Could not bind " + name + " to RMI Registry");
        e.printStackTrace();
    }
}
Example 19
Project: lucene-solr-master  File: TestJmxMonitoredMap.java View source code
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    String oldHost = System.getProperty("java.rmi.server.hostname");
    try {
        // this stupid sysprop thing is needed, because remote stubs use an
        // arbitrary local ip to connect
        // See: http://weblogs.java.net/blog/emcmanus/archive/2006/12/multihomed_comp.html
        System.setProperty("java.rmi.server.hostname", "127.0.0.1");
        class LocalhostRMIServerSocketFactory implements RMIServerSocketFactory {

            ServerSocket socket;

            @Override
            public ServerSocket createServerSocket(int port) throws IOException {
                return socket = new ServerSocket(port);
            }
        }
        ;
        LocalhostRMIServerSocketFactory factory = new LocalhostRMIServerSocketFactory();
        LocateRegistry.createRegistry(0, null, factory);
        port = factory.socket.getLocalPort();
        log.info("Using port: " + port);
        String url = "service:jmx:rmi:///jndi/rmi://127.0.0.1:" + port + "/solrjmx";
        JmxConfiguration config = new JmxConfiguration(true, null, url, null);
        monitoredMap = new JmxMonitoredMap<>("", "", config);
        JMXServiceURL u = new JMXServiceURL(url);
        connector = JMXConnectorFactory.connect(u);
        mbeanServer = connector.getMBeanServerConnection();
    } finally {
        if (oldHost == null) {
            System.clearProperty("java.rmi.server.hostname");
        } else {
            System.setProperty("java.rmi.server.hostname", oldHost);
        }
    }
}
Example 20
Project: Rio-master  File: ServiceBeanExecutorImpl.java View source code
private void bootstrap(final String[] configArgs) throws Exception {
    ClassLoader cCL = Thread.currentThread().getContextClassLoader();
    Configuration config = new GroovyConfig(configArgs, cCL);
    logger.debug("Loaded config");
    container = new ServiceBeanContainerImpl(config);
    computeResource = new ComputeResource(config);
    /* Setup persistent provisioning attributes */
    boolean provisionEnabled = (Boolean) config.getEntry("org.rioproject.cybernode", "provisionEnabled", Boolean.class, true);
    computeResource.setPersistentProvisioning(provisionEnabled);
    String provisionRoot = Environment.setupProvisionRoot(provisionEnabled, config);
    computeResource.setPersistentProvisioningRoot(provisionRoot);
    MeasurableCapability[] mCaps = loadMeasurables(config);
    for (MeasurableCapability mCap : mCaps) {
        computeResource.addMeasurableCapability(mCap);
        mCap.start();
    }
    container.setComputeResource(computeResource);
    container.addListener(this);
    context = ServiceBeanActivation.getServiceBeanContext(CONFIG_COMPONENT, "Cybernode", configArgs, config, getClass().getClassLoader());
    registry = LocateRegistry.getRegistry(cybernodeRegistryPort);
    exporter = ExporterConfig.getExporter(config, "org.rioproject.cybernode", "exporter");
    int createdRegistryPort = RegistryUtil.getRegistry();
    if (createdRegistryPort > 0) {
        System.setProperty(Constants.REGISTRY_PORT, Integer.toString(createdRegistryPort));
    } else {
        throw new RuntimeException("Unable to create RMI Registry");
    }
    Remote proxy = exporter.export(this);
    registry.bind(execBindName, proxy);
    new Thread(new CreateFDH(config, this)).start();
}
Example 21
Project: google-web-toolkit-svnmirror-master  File: BrowserManagerServerLauncher.java View source code
/**
   * This method should be invoked after argument parsing completes.
   */
public void run() {
    Registry rmiRegistry = null;
    try {
        // Create an RMI registry so we don't need an external process.
        // Uses the default RMI port if no port is specified with the -port arg.
        rmiRegistry = LocateRegistry.createRegistry(portArg);
    } catch (RemoteException e) {
        logger.log(Level.SEVERE, "Couldn't bind RMI Registry to port " + portArg, e);
        System.exit(1);
    }
    logger.log(Level.ALL, "RMI registry ready on port " + portArg + ".");
    // Startup each of the registered servers on this machine.
    for (BMSEntry entry : bmsList) {
        BrowserManagerServer server = null;
        try {
            server = new BrowserManagerServer(entry.browserPath, serializeArg);
        } catch (RemoteException re) {
            logger.log(Level.SEVERE, entry.registrationKey + ": Error starting new BrowserManagerServer.", re);
            System.exit(2);
        }
        try {
            rmiRegistry.rebind(entry.registrationKey, server);
        } catch (RemoteException re) {
            logger.log(Level.SEVERE, entry.registrationKey + " server: " + server + " port: " + portArg + " Error on rebind to " + entry.registrationKey, re);
            System.exit(3);
        }
        logger.log(Level.INFO, "Server: " + entry.registrationKey + " started and awaiting connections.");
    }
    logger.log(Level.INFO, "All servers started.");
}
Example 22
Project: sqlpower-library-master  File: DBConnectionSpecServerImpl.java View source code
/**
	 * Basic server main.  This class is executable with a command line
	 * something like this:
	 * 
	 * java -Djava.rmi.server.codebase="base.of.classpath" \
	 *      -cp ".;../../../../common/lib/xerces.jar" \
	 *      -Djava.security.policy=rmi.policy \
	 *      -DdatabasesFile=../databases.xml \
	 *      ca.sqlpower.sql.DBConnectionSpecServerImpl
	 */
public static void main(String args[]) throws RemoteException {
    // Create and install a security manager
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new RMISecurityManager());
    }
    DBConnectionSpecServerImpl obj = new DBConnectionSpecServerImpl();
    obj.xmlFileName = System.getProperty("databasesFile");
    if (obj.xmlFileName == null) {
        System.out.println("no databases file specified.  Please add -DdatabaseFile=filename to the command line.");
    } else {
        try {
            java.rmi.registry.LocateRegistry.createRegistry(1099);
            Naming.rebind("///DBConnectionSpecServer", obj);
            System.out.println("DBConnectionSpecServer bound in registry");
        } catch (Exception e) {
            System.out.println("DBConnectionSpecImpl err: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
Example 23
Project: oliot-fc-master  File: ALESettings.java View source code
private void initJConsole() {
    LOG.debug("initializing JConsole");
    try {
        // Ensure cryptographically strong random number generator used
        // to choose the object number - see java.rmi.server.ObjID
        //
        System.setProperty("java.rmi.server.randomIDs", "true");
        // Start an RMI registry on port 5001.
        //
        LOG.debug("Create RMI registry on port 5001");
        //LocateRegistry.createRegistry(5001);
        //int registryPort = org.fosstrak.llrp.adaptor.Constants.registryPort;
        // Retrieve the PlatformMBeanServer.
        //
        LOG.debug("Get the platform's MBean server");
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        // Environment map.
        //
        LOG.debug("Initialize the environment map");
        HashMap<String, Object> env = new HashMap<String, Object>();
        // Provide SSL-based RMI socket factories.
        //
        // The protocol and cipher suites to be enabled will be the ones
        // defined by the default JSSE implementation and only server
        // authentication will be required.
        //
        /*
	        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);
	*/
        // Provide the password file used by the connector server to
        // perform user authentication. The password file is a properties
        // based text file specifying username/password pairs.
        //
        //env.put("jmx.remote.x.password.file", "password.properties");
        // Provide the access level file used by the connector server to
        // perform user authorization. The access level file is a properties
        // based text file specifying username/access level pairs where
        // access level is either "readonly" or "readwrite" access to the
        // MBeanServer operations.
        //
        //env.put("jmx.remote.x.access.file", "access.properties");
        // 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 3000 with the name "jmxrmi". This is the same name the
        // out-of-the-box management agent uses to register the RMIServer
        // stub too.
        //
        //-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=5000
        env.put("com.sun.management.jmxremote.authenticate", "false");
        env.put("com.sun.management.jmxremote.ssl", "false");
        LOG.debug("Create an RMI connector server where RmiConnPort=5002, RmiRegistryPort=5001");
        //JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + 5002  + "/jndi/rmi://localhost:" + 5001 + "/jmxrmi");
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + 5002 + "/jndi/rmi://localhost:" + 5556 + "/jmxrmi");
        JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
        // Start the RMI connector server.
        //
        LOG.debug("Start the RMI connector server");
        cs.start();
    } catch (RemoteException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 24
Project: gluu-opendj-master  File: RmiConnector.java View source code
/**
   * Starts the common RMI registry. In order to provide RMI stub for
   * remote client, the JMX RMI connector should be register into an RMI
   * registry. Each server will maintain its own private one.
   *
   * @throws Exception
   *             if the registry cannot be started
   */
private void startCommonRegistry() throws Exception {
    int registryPort = jmxConnectionHandler.getListenPort();
    // create our local RMI registry if it does not exist already
    if (debugEnabled()) {
        TRACER.debugVerbose("start or reach an RMI registry on port %d", registryPort);
    }
    try {
        // TODO Not yet implemented: If the host has several interfaces
        if (registry == null) {
            rmiSsf = new OpendsRmiServerSocketFactory();
            registry = LocateRegistry.createRegistry(registryPort, null, rmiSsf);
        }
    } catch (RemoteException re) {
        if (debugEnabled()) {
            TRACER.debugWarning("cannot create the RMI registry -> already done ?");
        }
        try {
            Registry reg = LocateRegistry.getRegistry(registryPort);
            reg.list();
            registry = reg;
        } catch (Exception e) {
            if (debugEnabled()) {
                TRACER.debugError("exception thrown while pinging the RMI registry");
                TRACER.debugCaught(DebugLogLevel.ERROR, re);
            }
            throw re;
        }
        if (debugEnabled()) {
            TRACER.debugWarning("RMI was registry already started");
        }
    }
}
Example 25
Project: cids-server-master  File: StartProxy.java View source code
/**
     * DOCUMENT ME!
     *
     * @param   port  DOCUMENT ME!
     *
     * @return  DOCUMENT ME!
     *
     * @throws  ServerExitError  DOCUMENT ME!
     */
private Registry initRegistry(final int port) throws ServerExitError {
    try {
        if (LOG.isDebugEnabled()) {
            // NOI18N
            LOG.debug("<CS> DEBUG: getRMIRegistry on port " + port);
        }
        return LocateRegistry.getRegistry(port);
    } catch (final RemoteException e) {
        final String info = "<CS> INFO: no RMIRegistry on port " + port + " available";
        final String message = "<CS> INFO: create RMIRegistry on port " + port;
        System.out.println(e.getMessage() + " \n" + info);
        System.out.println(message);
        if (LOG.isInfoEnabled()) {
            LOG.info(info, e);
            LOG.info(message);
        }
        try {
            return LocateRegistry.createRegistry(port);
        } catch (final RemoteException ex) {
            final String fatal = "SEVERE: cannot create registry on port: " + port;
            LOG.fatal(fatal, ex);
            throw new ServerExitError(fatal, ex);
        }
    }
}