Example usage for java.rmi.registry LocateRegistry getRegistry

List of usage examples for java.rmi.registry LocateRegistry getRegistry

Introduction

In this page you can find the example usage for java.rmi.registry LocateRegistry getRegistry.

Prototype

public static Registry getRegistry(String host) throws RemoteException 

Source Link

Document

Returns a reference to the remote object Registry on the specified host on the default registry port of 1099.

Usage

From source file:org.apache.hadoop.distributedloadsimulator.sls.SLSRunner.java

public static void main(String args[]) throws Exception {
    Options options = new Options();
    options.addOption("inputsls", true, "input sls files");
    options.addOption("nodes", true, "input topology");
    options.addOption("output", true, "output directory");
    options.addOption("trackjobs", true, "jobs to be tracked during simulating");
    options.addOption("printsimulation", false, "print out simulation information");
    options.addOption("yarnnode", false, "taking boolean to enable rt mode");
    options.addOption("distributedmode", false, "taking boolean to enable scheduler mode");
    options.addOption("loadsimulatormode", false, "taking boolean to enable load simulator mode");
    options.addOption("rtaddress", true, "Resourcetracker address");
    options.addOption("rmaddress", true, "Resourcemanager  address for appmaster");
    options.addOption("parallelsimulator", false,
            "this is a boolean value to check whether to enable parallel simulator or not");
    options.addOption("rmiaddress", true, "Run a simulator on distributed mode, so we need rmi address");
    options.addOption("stopappsimulation", false, "we can stop the application simulation");
    options.addOption("isLeader", false, "leading slsRunner for the measurer");
    options.addOption("simulationDuration", true, "duration of the simulation only needed by the leader");
    options.addOption("rmiport", true, "port for the rmi server");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);

    String inputSLS = cmd.getOptionValue("inputsls");
    String output = cmd.getOptionValue("output");
    String rtAddress = cmd.getOptionValue("rtaddress"); // we are expecting the multiple rt, so input should be comma seperated
    String rmAddress = cmd.getOptionValue("rmaddress");
    String rmiAddress = "127.0.0.1";
    boolean isLeader = cmd.hasOption("isLeader");
    System.out.println(isLeader);
    long simulationDuration = 0;
    int rmiPort = 0;

    if (isLeader) {
        System.out.println(cmd.getOptionValue("simulationDuration"));
        simulationDuration = Long.parseLong(cmd.getOptionValue("simulationDuration")) * 1000;
    }//from  w  ww .  j a  v a 2 s.  co m
    if ((inputSLS == null) || output == null) {
        System.err.println();
        System.err.println("ERROR: Missing input or output file");
        System.err.println();
        System.err.println(
                "Options: -inputsls FILE,FILE... " + "-output FILE [-nodes FILE] [-trackjobs JobId,JobId...] "
                        + "[-printsimulation]" + "[-distributedrt]");
        System.err.println();
        System.exit(1);
    }

    File outputFile = new File(output);
    if (!outputFile.exists() && !outputFile.mkdirs()) {
        System.err.println("ERROR: Cannot create output directory " + outputFile.getAbsolutePath());
        System.exit(1);
    }

    Set<String> trackedJobSet = new HashSet<String>();
    if (cmd.hasOption("trackjobs")) {
        String trackjobs = cmd.getOptionValue("trackjobs");
        String jobIds[] = trackjobs.split(",");
        trackedJobSet.addAll(Arrays.asList(jobIds));
    }

    String nodeFile = cmd.hasOption("nodes") ? cmd.getOptionValue("nodes") : "";

    String inputFiles[] = inputSLS.split(",");
    if (cmd.hasOption("stopappsimulation")) {
        stopAppSimulation = true;
        LOG.warn("Application simulation is disabled!!!!!!");
    }
    if (cmd.hasOption("parallelsimulator")) {
        //  then we need rmi address
        rmiAddress = cmd.getOptionValue("rmiaddress"); // currently we support only two simulator in parallel
    }
    if (cmd.hasOption("rmiport")) {
        rmiPort = Integer.parseInt(cmd.getOptionValue("rmiport"));
    }
    SLSRunner sls = new SLSRunner(inputFiles, nodeFile, output, trackedJobSet, cmd.hasOption("printsimulation"),
            cmd.hasOption("yarnnode"), cmd.hasOption("distributedmode"), cmd.hasOption("loadsimulatormode"),
            rtAddress, rmAddress, rmiAddress, rmiPort, isLeader, simulationDuration);
    if (!cmd.hasOption("distributedmode")) {
        try {
            AMNMCommonObject stub = (AMNMCommonObject) UnicastRemoteObject.exportObject(sls, 0);
            // Bind the remote object's stub in the registry
            Registry registry = LocateRegistry.getRegistry(rmiPort);
            registry.bind("AMNMCommonObject", stub);
            LOG.info("HOP ::  SLS RMI Server ready on port " + rmiPort);
            sls.start();
        } catch (Exception e) {
            System.err.println("Server exception: " + e.toString());
            e.printStackTrace();
        }
    } else {
        sls.start();
    }
}

From source file:org.apache.ode.jca.server.rmi.RmiTransportServerImpl.java

public synchronized void start() throws RemoteException {
    if (_id == null)
        throw new IllegalStateException("Must set id!");
    if (_connProvider == null)
        throw new IllegalStateException("Must set connection provider.");

    _remote = UnicastRemoteObject.exportObject(this, 0);

    // Bind the RMI-server to the registry, creating one if necessary
    try {/*  w  w  w .java 2  s.  co  m*/
        _registry = LocateRegistry.createRegistry(_port);
        __log.debug("Created registry on port " + _port);
    } catch (Exception ex) {
        __log.debug("Could not create registry on port " + _port + " (perhaps it's already there)");
        /* ignore */
    }

    Registry registry = LocateRegistry.getRegistry(_port);

    registry.rebind(_id, _remote);

    __log.debug("Bound JCA server as \"" + _id + "\" on registry port " + _port);
}

From source file:org.jboss.tools.windup.runtime.WindupRmiClient.java

private static ExecutionBuilder getExecutionBuilder(int rmiPort) {
    logInfo("Attempting to retrieve ExecutionBuilder from registry."); //$NON-NLS-1$
    try {/*from ww  w  .j  a  v a 2s.  co  m*/
        Registry registry = LocateRegistry.getRegistry(rmiPort);
        ExecutionBuilder executionBuilder = (ExecutionBuilder) registry.lookup(ExecutionBuilder.LOOKUP_NAME);
        executionBuilder.clear();
        logInfo("ExecutionBuilder retrieved from registry."); //$NON-NLS-1$
        return executionBuilder;
    } catch (ConnectException e) {
    } catch (RemoteException e) {
        // TODO: We are polluting the log with this. Is there a better way?
        // Since onProcessFailed will be called when/if the process fails, can we rely on the logs sent from the rhamt-cli script? 
        // logError("Error while attempting to retrieve the ExecutionBuilder from RMI registry.", e); //$NON-NLS-1$
        logInfo("Unable to find ExecutionBuilder RMI registry."); //$NON-NLS-1$
    } catch (NotBoundException e) {
        logError("ExecutionBuilder not yet bound.", e); //$NON-NLS-1$
    }
    return null;
}

From source file:org.jgentleframework.integration.remoting.rmi.support.RmiExecutor.java

/**
 * Gets the registry.//from  ww w.ja v a2s  .  c om
 * 
 * @param registryPort
 *            the registry port
 * @param autoCreateRegistry
 *            the auto create registry
 * @return Registry
 * @throws RemoteException
 *             the remote exception
 */
public static Registry getRegistry(boolean autoCreateRegistry, int registryPort) throws RemoteException {

    if (autoCreateRegistry) {
        return LocateRegistry.createRegistry(registryPort);
    }
    try {
        Registry reg = LocateRegistry.getRegistry(registryPort);
        // Kim tra Registry.
        testRegistry(reg);
        return reg;
    } catch (RemoteException ex) {
        return LocateRegistry.createRegistry(registryPort);
    }
}

From source file:org.lnicholls.galleon.server.Server.java

public Integer start() {
    if (log.isDebugEnabled())
        log.debug("start()");
    try {//from   ww  w .  jav a  2  s  .c om
        // Start the database
        NetworkServerManager.initialize();

        HibernateUtil.initialize();
        if (NetworkServerManager.findSchema())
            HibernateUtil.updateSchema();
        else
            HibernateUtil.createSchema();

        // Start time task for period operations such as internet downloads
        mLongTermTimer = new Timer();
        mShortTermTimer = new Timer();
        mDataTimer = new Timer();

        mDownloadManager = new DownloadManager();

        // Load apps
        mAppManager = new AppManager(mAppClassLoader);

        // Read the conf/configure.xml file
        mConfigurator = new Configurator();
        mConfigurator.load(mAppManager);

        setDebugLogging(mServerConfiguration.isDebug());

        mTiVoListener = new TiVoListener();

        mAppManager.loadApps();

        // mAppManager.startPlugins();

        // Start the Media Manager refresh thread
        // scheduleLongTerm(new MediaManager.RefreshTask(), 3); //60*24);
        // MediaManager.addPath(new
        // MediaRefreshThread.PathInfo("d:/download/mp3",FileFilters.audioFilter));

        try {
            mToGoThread = new ToGoThread(this);
            mToGoThread.start();
            mDownloadThread = new DownloadThread(this);
            mDownloadThread.start();
        } catch (Exception ex) {
            Tools.logException(Server.class, ex);

            mToGoThread = null;
            mDownloadThread = null;
        }

        try {
            // Is there already a RMI server?
            mRegistry = LocateRegistry.getRegistry(1099);
            String[] names = mRegistry.list();
            log.info("Using RMI port " + 1099);
        } catch (Exception ex) {
            int port = Tools.findAvailablePort(1099);
            if (port != 1099) {
                log.info("Changed RMI port to " + port);
            } else
                log.info("Using RMI port " + 1099);

            mRegistry = LocateRegistry.createRegistry(port);
        }

        mRegistry.bind("serverControl", new ServerControlImpl());

        mTCMs = new LinkedList();
        int port = mServerConfiguration.getHttpPort();
        mHMOPort = Tools.findAvailablePort(port);
        if (mHMOPort != port) {
            log.info("Changed PC publishing port to " + mHMOPort);
        } else
            log.info("Using PC publishing port " + mHMOPort);

        Config config = new Config();
        config.put("http.ports", String.valueOf(mHMOPort));
        config.put("http.interfaces", mServerConfiguration.getIPAddress());
        mVideoServer = new VideoServer(config);

        if (System.getProperty("disableBeacon") != null && System.getProperty("disableBeacon").equals("true")) {
            log.debug("Beacon disabled");
        } else {
            // TiVo Beacon API
            publishTiVoBeacon();

            if (!mPublished) {
                mBeaconPort = Constants.TIVO_PORT;
                // TODO
                int counter = 0;
                while (counter++ < 100) {
                    try {
                        if (log.isDebugEnabled())
                            log.debug("Using beacon port=" + mBeaconPort);
                        mBroadcastThread = new BroadcastThread(this, mBeaconPort);
                        mBroadcastThread.start();
                        break;
                    } catch (Throwable ex) {
                        Tools.logException(Server.class, ex);

                        if (mBroadcastThread != null)
                            mBroadcastThread.interrupt();

                        mBroadcastThread = null;
                        mBeaconPort = mBeaconPort + 1;
                    }
                }

                if (mBroadcastThread != null) {
                    log.info("Broadcast port=" + mBeaconPort);

                    mListenThread = new ListenThread(this);
                    mListenThread.start();
                } else
                    log.error("Cannot broadcast");

                mConnectionThread = new ConnectionThread(this);
                mConnectionThread.start();
            }
        }

        //mDataUpdateThread = new DataUpdateThread();
        //mDataUpdateThread.start();

        System.out.println("Galleon is ready.");
        mReady = true;

        Iterator iterator = mShortTermTasks.iterator();
        while (iterator.hasNext()) {
            TaskInfo taskInfo = (TaskInfo) iterator.next();
            scheduleShortTerm(taskInfo.task, 0, taskInfo.time);
        }
        mShortTermTasks.clear();
        iterator = mLongTermTasks.iterator();
        while (iterator.hasNext()) {
            TaskInfo taskInfo = (TaskInfo) iterator.next();
            scheduleLongTerm(taskInfo.task, 30, taskInfo.time);
        }
        mLongTermTasks.clear();
        iterator = mDataTasks.iterator();
        while (iterator.hasNext()) {
            TaskInfo taskInfo = (TaskInfo) iterator.next();
            scheduleData(taskInfo.task, 0, taskInfo.time);
        }
        mDataTasks.clear();

        iterator = mPublishedVideos.iterator();
        while (iterator.hasNext()) {
            publishVideo((NameValue) iterator.next());
        }
        mPublishedVideos.clear();
    } catch (Exception ex) {
        Tools.logException(Server.class, ex);
        return new Integer(1);
    }
    return null;
}

From source file:org.ops4j.pax.exam.rbc.client.RemoteBundleContextClient.java

/**
 * Looks up the {@link RemoteBundleContext} via RMI. The lookup will timeout in the specified number of millis.
 *
 * @return remote bundle context/*from  www. j  av a2 s  .c  o m*/
 */
private RemoteBundleContext getRemoteBundleContext() {
    if (m_remoteBundleContext == null) {
        long startedTrying = System.currentTimeMillis();
        //!! Absolutely necesary for RMI class loading to work
        // TODO maybe use ContextClassLoaderUtils.doWithClassLoader
        Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        Throwable reason = null;
        try {
            final Registry registry = LocateRegistry.getRegistry(m_rmiPort);
            do {
                try {
                    m_remoteBundleContext = (RemoteBundleContext) registry
                            .lookup(RemoteBundleContext.class.getName());
                } catch (ConnectException e) {
                    reason = e;
                } catch (NotBoundException e) {
                    reason = e;
                }
            } while (m_remoteBundleContext == null && (m_rmiLookupTimeout == Constants.WAIT_FOREVER
                    || System.currentTimeMillis() < startedTrying + m_rmiLookupTimeout));
        } catch (RemoteException e) {
            reason = e;
        }
        if (m_remoteBundleContext == null) {
            throw new TestContainerException("Cannot get the remote bundle context", reason);
        }
        LOG.info("Remote bundle context found after " + (System.currentTimeMillis() - startedTrying)
                + " millis");
    }
    return m_remoteBundleContext;
}

From source file:org.ops4j.pax.exam.rbc.internal.Activator.java

/**
 * {@inheritDoc}//from  www  .ja  va  2s  .  c om
 */
public void start(final BundleContext bundleContext) throws Exception {
    //!! Absolutely necessary for RMIClassLoading to work
    ContextClassLoaderUtils.doWithClassLoader(null, // getClass().getClassLoader()
            new Callable<Object>() {
                public Object call() throws Exception {
                    try {
                        // try to find port from property
                        int port = getPort();
                        m_registry = LocateRegistry.getRegistry(port);
                        LOG.debug("Binding " + RemoteBundleContext.class.getSimpleName() + " to RMI registry");
                        m_registry.bind(RemoteBundleContext.class.getName(), UnicastRemoteObject.exportObject(
                                m_remoteBundleContext = new RemoteBundleContextImpl(bundleContext), 0));
                        LOG.info("Remote Bundle Context started");
                    } catch (Exception e) {
                        throw new BundleException("Cannot bind RBC to RMI registry", e);
                    }
                    return null;
                }
            });
}

From source file:org.quartz.core.QuartzScheduler.java

/**
 * <p>/*from  w w w  .java  2s  .com*/
 * Bind the scheduler to an RMI registry.
 * </p>
 */
private void bind() throws RemoteException {
    String host = resources.getRMIRegistryHost();
    // don't export if we're not configured to do so...
    if (host == null || host.length() == 0) {
        return;
    }

    RemotableQuartzScheduler exportable = null;

    if (resources.getRMIServerPort() > 0) {
        exportable = (RemotableQuartzScheduler) UnicastRemoteObject.exportObject(this,
                resources.getRMIServerPort());
    } else {
        exportable = (RemotableQuartzScheduler) UnicastRemoteObject.exportObject(this);
    }

    Registry registry = null;

    if (resources.getRMICreateRegistryStrategy().equals(QuartzSchedulerResources.CREATE_REGISTRY_AS_NEEDED)) {
        try {
            // First try to get an existing one, instead of creating it,
            // since if
            // we're in a web-app being 'hot' re-depoloyed, then the JVM
            // still
            // has the registry that we created above the first time...
            registry = LocateRegistry.getRegistry(resources.getRMIRegistryPort());
            registry.list();
        } catch (Exception e) {
            registry = LocateRegistry.createRegistry(resources.getRMIRegistryPort());
        }
    } else if (resources.getRMICreateRegistryStrategy()
            .equals(QuartzSchedulerResources.CREATE_REGISTRY_ALWAYS)) {
        try {
            registry = LocateRegistry.createRegistry(resources.getRMIRegistryPort());
        } catch (Exception e) {
            // Fall back to an existing one, instead of creating it, since
            // if
            // we're in a web-app being 'hot' re-depoloyed, then the JVM
            // still
            // has the registry that we created above the first time...
            registry = LocateRegistry.getRegistry(resources.getRMIRegistryPort());
        }
    } else {
        registry = LocateRegistry.getRegistry(resources.getRMIRegistryHost(), resources.getRMIRegistryPort());
    }

    String bindName = resources.getRMIBindName();

    registry.rebind(bindName, exportable);

    getLog().info("Scheduler bound to RMI registry under name '" + bindName + "'");
}

From source file:org.red5.server.jmx.JMXAgent.java

public void init() {
    //environmental var holder
    HashMap env = null;//  ww w  . j  a  va  2 s.c om
    if (enableHtmlAdapter) {
        // setup the adapter
        try {
            //instance an html adaptor
            int port = htmlAdapterPort == null ? 8082 : Integer.valueOf(htmlAdapterPort);
            html = new HtmlAdaptorServer(port);
            ObjectName htmlName = new ObjectName(
                    JMXFactory.getDefaultDomain() + ":type=HtmlAdaptorServer,port=" + port);
            log.debug("Created HTML adaptor on port: " + port);
            //add the adaptor to the server
            mbs.registerMBean(html, htmlName);
            //start the adaptor
            html.start();
            log.info("JMX HTML connector server successfully started");

        } catch (Exception e) {
            log.error("Error in setup of JMX subsystem (HTML adapter)", e);
        }
    } else {
        log.info("JMX HTML adapter was not enabled");
    }
    if (enableRmiAdapter) {
        // Create an RMI connector server
        log.debug("Create an RMI connector server");
        try {

            Registry r = null;
            try {
                //lookup the registry
                r = LocateRegistry.getRegistry(Integer.valueOf(rmiAdapterPort));
                //ensure we are not already registered with the registry
                for (String regName : r.list()) {
                    if (regName.equals("red5")) {
                        //unbind connector from rmi registry
                        r.unbind("red5");
                    }
                }
            } catch (RemoteException re) {
                log.info("RMI Registry server was not found on port " + rmiAdapterPort);
                //if we didnt find the registry and the user wants it created
                if (startRegistry) {
                    log.info("Starting an internal RMI registry");
                    // create registry for rmi port 9999
                    r = LocateRegistry.createRegistry(Integer.valueOf(rmiAdapterPort));
                }
            }
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + rmiAdapterPort + "/red5");
            //if SSL is requested to secure rmi connections
            if (enableSsl) {
                // Environment map
                log.debug("Initialize the environment map");
                env = new HashMap();
                // Provide SSL-based RMI socket factories
                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);
            }

            //if authentication is requested
            if (StringUtils.isNotBlank(remoteAccessProperties)) {
                //if ssl is not used this will be null
                if (null == env) {
                    env = new HashMap();
                }
                //check the existance of the files
                //in the war version the full path is needed
                File file = new File(remoteAccessProperties);
                if (!file.exists()) {
                    log.debug("Access file was not found on path, will prepend config_root");
                    //pre-pend the system property set in war startup
                    remoteAccessProperties = System.getProperty("red5.config_root") + '/'
                            + remoteAccessProperties;
                    remotePasswordProperties = System.getProperty("red5.config_root") + '/'
                            + remotePasswordProperties;
                }
                env.put("jmx.remote.x.access.file", remoteAccessProperties);
                env.put("jmx.remote.x.password.file", remotePasswordProperties);
            }

            // create the connector server
            cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            // add a listener for shutdown
            cs.addNotificationListener(this, null, null);
            // Start the RMI connector server
            log.debug("Start the RMI connector server");
            cs.start();
            log.info("JMX RMI connector server successfully started");
        } catch (ConnectException e) {
            log.warn("Could not establish RMI connection to port " + rmiAdapterPort
                    + ", please make sure \"rmiregistry\" is running and configured to listen on this port.");
        } catch (IOException e) {
            String errMsg = e.getMessage();
            if (errMsg.indexOf("NameAlreadyBoundException") != -1) {
                log.error("JMX connector (red5) already registered, you will need to restart your rmiregistry");
            } else {
                log.error("{}", e);
            }
        } catch (Exception e) {
            log.error("Error in setup of JMX subsystem (RMI connector)", e);
        }
    } else {
        log.info("JMX RMI adapter was not enabled");
    }
}

From source file:org.springframework.remoting.rmi.RmiRegistryFactoryBean.java

/**
 * Locate or create the RMI registry./*from  w  w w.ja  v  a 2  s  . co m*/
 * @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.info("Creating new RMI registry");
        this.created = true;
        return LocateRegistry.createRegistry(registryPort);
    }
    if (logger.isInfoEnabled()) {
        logger.info("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.debug("RMI registry access threw exception", ex);
            logger.info("Could not detect RMI registry - creating new one");
            // Assume no registry found -> create new one.
            this.created = true;
            return LocateRegistry.createRegistry(registryPort);
        }
    }
}