Example usage for java.rmi Naming lookup

List of usage examples for java.rmi Naming lookup

Introduction

In this page you can find the example usage for java.rmi Naming lookup.

Prototype

public static Remote lookup(String name)
        throws NotBoundException, java.net.MalformedURLException, RemoteException 

Source Link

Document

Returns a reference, a stub, for the remote object associated with the specified name.

Usage

From source file:je3.rmi.MudClient.java

/**
 * The main program.  It expects two or three arguments:
 *   0) the name of the host on which the mud server is running
 *   1) the name of the MUD on that host
 *   2) the name of a place within that MUD to start at (optional).
 *
 * It uses the Naming.lookup() method to obtain a RemoteMudServer object
 * for the named MUD on the specified host.  Then it uses the getEntrance()
 * or getNamedPlace() method of RemoteMudServer to obtain the starting
 * RemoteMudPlace object.  It prompts the user for a their name and 
 * description, and creates a MudPerson object.  Finally, it passes
 * the person and the place to runMud() to begin interaction with the MUD.
 **///w ww . j  a  v  a  2 s  . co  m
public static void main(String[] args) {
    try {
        String hostname = args[0]; // Each MUD is uniquely identified by a 
        String mudname = args[1];  //   host and a MUD name.
        String placename = null;   // Each place in a MUD has a unique name
        if (args.length > 2) placename = args[2];
       
        // Look up the RemoteMudServer object for the named MUD using
        // the default registry on the specified host.  Note the use of
        // the Mud.mudPrefix constant to help prevent naming conflicts
        // in the registry.
        RemoteMudServer server = 
            (RemoteMudServer)Naming.lookup("rmi://" + hostname + "/" +
                  Mud.mudPrefix + mudname);

        // If the user did not specify a place in the mud, use
        // getEntrance() to get the initial place.  Otherwise, call
        // getNamedPlace() to find the initial place.
        RemoteMudPlace location = null;
        if (placename == null) location = server.getEntrance();
        else location = (RemoteMudPlace) server.getNamedPlace(placename);
       
        // Greet the user and ask for their name and description.
        // This relies on getLine() and getMultiLine() defined below.
        System.out.println("Welcome to " + mudname);
        String name = getLine("Enter your name: ");
        String description = getMultiLine("Please describe what " +
             "people see when they look at you:");

        // Define an output stream that the MudPerson object will use to
        // display messages sent to it to the user.  We'll use the console.
        PrintWriter myout = new PrintWriter(System.out);
       
        // Create a MudPerson object to represent the user in the MUD.
        // Use the specified name and description, and the output stream.
        MudPerson me = new MudPerson(name, description, myout);
       
        // Lower this thread's priority one notch so that broadcast
        // messages can appear even when we're blocking for I/O.  This is
        // necessary on the Linux platform, but may not be necessary on all
        // platforms.
        int pri = Thread.currentThread().getPriority();
        Thread.currentThread().setPriority(pri-1);
       
        // Finally, put the MudPerson into the RemoteMudPlace, and start
        // prompting the user for commands.
        runMud(location, me);
    }
    // If anything goes wrong, print a message and exit.
    catch (Exception e) {
        System.out.println(e);
        System.out.println("Usage: java MudClient <host> <mud> [<place>]");
        System.exit(1);
    }
}

From source file:org.apache.jcs.auxiliary.remote.server.RemoteCacheServerFactory.java

/**
 * Creates an local RMI registry on the default port, starts up the remote cache server, and
 * binds it to the registry.//from www  .  jav a2  s . co  m
 * A remote cache is either a local cache or a cluster cache
 * @param args The command line arguments
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    Properties prop = args.length > 0 ? RemoteUtils.loadProps(args[args.length - 1]) : new Properties();

    int port;
    try {
        port = Integer.parseInt(prop.getProperty("registry.port"));
    } catch (NumberFormatException ex) {
        port = Registry.REGISTRY_PORT;
    }

    // shutdown
    if (args.length > 0 && args[0].toLowerCase().indexOf("-shutdown") != -1) {
        String serviceName = prop.getProperty(REMOTE_CACHE_SERVICE_NAME, REMOTE_CACHE_SERVICE_VAL).trim();
        String registry = "//:" + port + "/" + serviceName;

        if (log.isDebugEnabled()) {
            log.debug("looking up server " + registry);
        }
        Object obj = Naming.lookup(registry);
        if (log.isDebugEnabled()) {
            log.debug("server found");
        }
        IRemoteCacheServiceAdmin admin = (IRemoteCacheServiceAdmin) obj;
        try {
            admin.shutdown();
        } catch (Exception ex) {
            log.error("Problem calling shutdown.", ex);
        }
        log.debug("done.");
        System.exit(0);
    }

    // STATS
    if (args.length > 0 && args[0].toLowerCase().indexOf("-stats") != -1) {

        log.debug("getting cache stats");

        try {
            String serviceName = prop.getProperty(REMOTE_CACHE_SERVICE_NAME, REMOTE_CACHE_SERVICE_VAL).trim();
            String registry = "//:" + port + "/" + serviceName;
            log.debug("looking up server " + registry);
            Object obj = Naming.lookup(registry);
            log.debug("server found");

            log.debug("obj = " + obj);
            IRemoteCacheServiceAdmin admin = (IRemoteCacheServiceAdmin) obj;

            try {
                System.out.println(admin.getStats().toString());
                log.debug(admin.getStats());
            } catch (Exception es) {
                log.error(es);
            }

        } catch (Exception ex) {
            log.error("Problem getting stats.", ex);
        }
        log.debug("done.");
        System.exit(0);
    }

    // startup.
    String host = prop.getProperty("registry.host");

    if (host == null || host.trim().equals("") || host.trim().equals("localhost")) {
        log.debug("main> creating registry on the localhost");
        port = RemoteUtils.createRegistry(port);
    }
    log.debug("main> starting up RemoteCacheServer");
    RemoteCacheServerFactory.startup(host, port, args.length > 0 ? args[0] : null);
    log.debug("main> done");
}

From source file:org.tinygroup.rpc.RMIFactory.java

public Object makeObject() throws Exception {
    String url = RMIRemoteUtil.getURL(node);
    CEPCoreRMI rmi = null;//from w ww. j ava2  s .c o m
    try {
        rmi = (CEPCoreRMI) Naming.lookup(url);
    } catch (Exception e) {
        logger.logMessage(LogLevel.ERROR, "?,{0}:{1}:{2},{3}", node.getIp(),
                node.getPort(), node.getNodeName(), e.getMessage());
        throw new CEPConnectException(e, node);
    }
    return rmi;
}

From source file:org.speechforge.cairo.server.resource.TransmitterResource.java

public static void main(String[] args) throws Exception {

    CommandLineParser parser = new GnuParser();
    Options options = getOptions();//  w  ww. j  a va2  s. com
    CommandLine line = parser.parse(options, args, true);
    args = line.getArgs();

    if (args.length != 2 || line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("TransmitterResource [options] <cairo-config-URL> <resource-name>", options);
        return;
    }

    URL configURL = CairoUtil.argToURL(args[0]);
    String resourceName = args[1];

    CairoConfig config = new CairoConfig(configURL);
    TransmitterConfig resourceConfig = config.getTransmitterConfig(resourceName);

    StringBuilder rmiUrl = new StringBuilder("rmi://");
    if (line.hasOption(RSERVERHOST_OPTION)) {
        rmiUrl.append(line.getOptionValue(RSERVERHOST_OPTION));
    } else {
        rmiUrl.append(CairoUtil.getLocalHost().getHostName());
    }
    rmiUrl.append('/').append(ResourceRegistry.NAME);

    _logger.info("looking up: " + rmiUrl);
    ResourceRegistry resourceRegistry = (ResourceRegistry) Naming.lookup(rmiUrl.toString());

    TransmitterResource impl = new TransmitterResource(resourceConfig);

    _logger.info("binding transmitter resource...");
    resourceRegistry.register(impl, RESOURCE_TYPE);

    _logger.info("Resource bound and waiting...");

}

From source file:org.apache.axis.providers.java.RMIProvider.java

/**
 * Return a object which implements the service.
 * //from w ww.  j a v a 2s .  c o  m
 * @param msgContext the message context
 * @param clsName The JNDI name of the EJB home class
 * @return an object that implements the service
 */
protected Object makeNewServiceObject(MessageContext msgContext, String clsName) throws Exception {
    // Read deployment descriptor options
    String namingLookup = getStrOption(OPTION_NAMING_LOOKUP, msgContext.getService());
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new RMISecurityManager());
    }
    Object targetObject = Naming.lookup(namingLookup);
    return targetObject;
}

From source file:Peer.java

/**
 * The peer constructor./*from  w ww.j  a  va  2  s. c o m*/
 */
public Peer(String sp) throws Exception {
    try {
        // Initialize of various members
        pred = null;
        succ = null;
        lock = false;

        // Find the SuperPeer
        superpeer = (SuperPeerInterface) Naming.lookup("//" + sp + "/SuperPeer");

        // Initialize the node cache
        peercache = new HashMap<Key, PeerInterface>();

        // Initialize word map
        dict = new HashMap<String, String>();

        ////////////////////////////////////////////////
        // BEGIN CRITICAL SECTION
        // only one peer will be in this code at a time.
        superpeer.lock();
        // Get this Peer's NodeID
        nodeid = superpeer.join();
        //Start logger
        lg = new Logger("Peer:" + nodeid.toString());
        lg.log(Level.FINER, "Peer started.");

        // Register with the RMI Registry.
        lg.log(Level.FINER, "Binding to local RMI registry with name " + nodeid.toString());
        Naming.rebind(nodeid.toString(), this);

        // Get Successor
        succ = superpeer.getSuccessor(nodeid);

        // Get hasher
        lg.log(Level.FINER, "Retrieving Hash object");
        hasher = superpeer.getHasher();
        // Set mbits
        int mbits = hasher.getBitSize();
        // Initialize finger table
        ft = new FingerTable(nodeid.succ(), nodeid);
        // Update finger table
        constructFingerTable(mbits);
        lock = true;
        // If we have a successor, start the notify cycle
        if (succ != null) {
            lg.log(Level.FINER, "Calling " + succ.toString());
            getPeer(succ).notify(nodeid);
        }
        lock = false;
        superpeer.unlock();
        // END CRITICAL SECTION
        ////////////////////////////////////////////////
        lg.log(Level.FINER, "Exit Critical Section");

        lg.log(Level.INFO, "!!!! Peer " + nodeid + " at " + superpeer.getAddress(nodeid) + " started !!!!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ComputeNode.java

public ComputeNode(String servername, Double _underLoadThreshold, Double _overLoadThreshold,
        Double _failProbability, Double _loadConstant, Pair<Double, Double> _loadGaussian, String configFile)
        throws Exception {

    server = (ServerInterface) Naming.lookup("//" + servername + "/Server");

    id = server.registerNode();//from  w  w  w .  j  a  va2  s.  c o  m

    lg = new Logger("Compute Node:" + id);
    lg.log(Level.INFO, "ComputeNode " + id + " started.");

    // If a config file was specified
    if (configFile == null) {
        configFile = defaultconf;
    }

    try {
        // TODO: Only load if we need to.
        Properties properties = new Properties();
        properties.load(new FileInputStream(configFile));

        if (_overLoadThreshold == null)
            _overLoadThreshold = new Double(properties.getProperty("computenode.overload_threshhold"));
        overLoadThreshold = _overLoadThreshold;

        if (_underLoadThreshold == null)
            _underLoadThreshold = new Double(properties.getProperty("computenode.underload_threshhold"));
        underLoadThreshold = _underLoadThreshold;

        if (_failProbability == null)
            _failProbability = new Double(properties.getProperty("computenode.fail_probability"));
        failProbability = _failProbability;

        lg.log(Level.FINER, "ComputeNode " + id + ": under load threshhold = " + underLoadThreshold);
        lg.log(Level.FINER, "ComputeNode " + id + ": over load threshhold = " + overLoadThreshold);
        lg.log(Level.FINER, "ComputeNode " + id + ": fail probability = " + failProbability);

        loadConstant = _loadConstant;
        if (loadConstant != null)
            lg.log(Level.FINER, "ComputeNode " + id + ": load constant = " + loadConstant);

        loadGaussian = _loadGaussian;
        if (loadGaussian != null)
            lg.log(Level.FINER,
                    "ComputeNode " + id + ": load gaussian = " + loadGaussian.fst() + "," + loadGaussian.snd());

    } catch (Exception e) {
        lg.log(Level.SEVERE, "ComputeNode " + id + ": Constructor failure! " + underLoadThreshold);
        e.printStackTrace();
        System.exit(1);
    }

    myNodeStats = new NodeStats();
    myNodeStats.setCurrentLoad(getCurrentLoad());
}

From source file:assign3.client.WaypointClient.java

public WaypointClient(String base, String hostId, String port) throws RemoteException {
    super(base);//from w w w.j a  va2 s .co m
    this.hostId = hostId;
    this.port = port;
    removeWPButt.addActionListener(this);
    addWPButt.addActionListener(this);
    modWPButt.addActionListener(this);
    exportToJSON.addActionListener(this);
    distBearButt.addActionListener(this);
    frWps.addItemListener(this);
    toWps.addItemListener(this);

    try {
        server = (WaypointServer) Naming.lookup("rmi://" + hostId + ":" + port + "/WaypointServer");
        System.out.println("Client obtained remote object reference to" + " the WaypointServer at:\n" + "rmi://"
                + hostId + ":" + port + "/WaypointServer");
    } catch (Exception e) {
        System.out.println("Could not find server.");
    }
    System.out.println("Getting Waypoints From Server.");
    String[] names = server.getNames();
    for (int i = 0; i < names.length; i++) {
        Waypoint aWp = server.get(names[i]);
        frWps.addItem(names[i]);
        toWps.addItem(names[i]);
        System.out.println(names[i]);
    }

    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            debug("you clicked X");
            System.exit(0);
        }
    });

    setVisible(true);
}

From source file:org.apache.jcs.auxiliary.remote.RemoteCacheRestore.java

/**
 * Returns true if the connection to the remote host for the corresponding cache manager can be
 * successfully re-established./*from w ww  . j  av a2s .co  m*/
 * <p>
 * @return true if we found a failover server
 */
public boolean canFix() {
    if (!canFix) {
        return canFix;
    }
    String registry = "//" + rcm.host + ":" + rcm.port + "/" + rcm.service;
    if (log.isInfoEnabled()) {
        log.info("looking up server " + registry);
    }
    try {
        remoteObj = Naming.lookup(registry);
        if (log.isInfoEnabled()) {
            log.info("looking up server " + registry);
        }
    } catch (Exception ex) {
        log.error("host=" + rcm.host + "; port" + rcm.port + "; service=" + rcm.service);
        canFix = false;
    }
    return canFix;
}

From source file:net.sqs2.omr.task.broker.RemoteTaskExecutorManager.java

private TaskBroker createRemoteTaskBroker(String uriString, long remoteKey, long sessionID) {
    try {/*from  ww  w  . ja  v a 2 s  . c o m*/
        URI uri = new URI(uriString);

        if (NetworkUtil.isMyAddress(InetAddress.getAllByName(uri.getHost()))) {
            return null;
        }

        RemoteSessionService sessionService = (RemoteSessionService) Naming.lookup(uri.toString()); // connect to remote SessionService
        long result = sessionService.ping(remoteKey); // authentication
        if (DEBUG) {
            Logger.getLogger("executor").info("RemoteSessionService.URI=" + uri);
            Logger.getLogger("executor").info("Hello=" + result);
        }
        TaskBroker remoteTaskBroker = new TaskBroker("Remote", this.manager,
                new TaskExecutorEnv(null, sessionService, remoteKey, sessionID));
        return remoteTaskBroker;
    } catch (UnknownHostException ex) {
        Logger.getLogger("executor").severe("UnknownHostException:" + ex.getMessage());
    } catch (SocketException ex) {
        Logger.getLogger("executor").severe("SocketException:" + ex.getMessage());
    } catch (URISyntaxException ex) {
        Logger.getLogger("executor").severe("URISyntaxException:" + ex.getMessage());
    } catch (ConnectException ex) {
        Logger.getLogger("executor").severe("ConnectException:" + ex.getMessage());
    } catch (RemoteException ex) {
        Logger.getLogger("executor").severe("RemoteException:" + ex.getMessage());
    } catch (MalformedURLException ex) {
        Logger.getLogger("executor").severe("MalformedURLException:" + ex.getMessage());
    } catch (NotBoundException ex) {
        Logger.getLogger("executor").severe("NotBoundException:" + ex.getMessage());
    }
    return null;
}