Example usage for java.rmi.registry LocateRegistry createRegistry

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

Introduction

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

Prototype

public static Registry createRegistry(int port) throws RemoteException 

Source Link

Document

Creates and exports a Registry instance on the local host that accepts requests on the specified port.

Usage

From source file:net.sf.ehcache.management.ManagementServiceTest.java

/**
 * Creates an RMI JMXConnectorServer, connects to it and demonstrates what attributes are traversable.
 * The answer is not all.// w  w  w .  j ava 2s .  c om
 *
 * Note that this test creates a Registry which will keep running until the JVM Exists. There
 * is no way to stop it but it should do no harm.
 *
 *
 */
public void testJMXConnectorServer() throws Exception {

    ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true);

    LocateRegistry.createRegistry(55000);
    String serverUrl = "service:jmx:rmi:///jndi/rmi://localhost:55000/server";
    JMXServiceURL url = new JMXServiceURL(serverUrl);
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer);
    cs.start();
    JMXConnector connector = cs.toJMXConnector(null);
    connector.connect(null);
    MBeanServerConnection connection = connector.getMBeanServerConnection();
    assertEquals(OBJECTS_IN_TEST_EHCACHE,
            connection.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());

    Ehcache ehcache = manager.getCache("sampleCache1");

    ehcache.put(new Element("key1", "value1"));
    ehcache.put(new Element("key2", "value1"));
    assertNotNull(ehcache.get("key1"));
    assertNotNull(ehcache.get("key2"));

    //Test CacheManager
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "CacheManager");

    //Test Cache
    //not all attributes are accessible due to serializability constraints
    //traverseMBeanAttributes(connection, "Cache");

    //Test CacheStatistics
    traverseMBeanAttributes(connection, "CacheStatistics");

    //Test CacheConfiguration
    traverseMBeanAttributes(connection, "CacheConfiguration");

    cs.stop();
}

From source file:net.sf.ehcache.distribution.RMICacheManagerPeerListener.java

/**
 * Start the rmiregistry.//ww w .  j  ava 2 s. c o  m
 * <p/>
 * The alternative is to use the <code>rmiregistry</code> binary, in which case:
 * <ol/>
 * <li>rmiregistry running
 * <li>-Djava.rmi.server.codebase="file:///Users/gluck/work/ehcache/build/classes/ file:///Users/gluck/work/ehcache/lib/commons-logging-1.0.4.jar"
 * </ol>
 *
 * @throws RemoteException
 */
protected void startRegistry() throws RemoteException {
    try {
        registry = LocateRegistry.getRegistry(port.intValue());
        try {
            registry.list();
        } catch (RemoteException e) {
            //may not be created. Let's create it.
            registry = LocateRegistry.createRegistry(port.intValue());
            registryCreated = true;
        }
    } catch (ExportException exception) {
        LOG.fatal("Exception starting RMI registry. Error was " + exception.getMessage(), exception);
    }
}

From source file:se.trixon.jota.server.Server.java

private void startServer() {
    mRmiNameServer = JotaHelper.getRmiName(SystemHelper.getHostname(), mPort, JotaServer.class);

    try {//  w  w  w .  j  a  v a 2  s.c o m
        LocateRegistry.createRegistry(mPort);
        mServerVmid = new VMID();
        //mServerOptions = new ServerOptions();
        Naming.rebind(mRmiNameServer, this);
        String message = String.format("started: %s (%s)", mRmiNameServer, mServerVmid.toString());
        Xlog.timedOut(message);
        listJobs();
        listTasks();
        getStatus();
        if (mOptions.isCronActive()) {
            cronOn();
        }
    } catch (IllegalArgumentException e) {
        Xlog.timedErr(e.getLocalizedMessage());
        Jota.exit();
    } catch (RemoteException e) {
        //nvm - server was running
        Xlog.timedErr(e.getLocalizedMessage());
        Jota.exit();
    } catch (MalformedURLException ex) {
        Xlog.timedErr(ex.getLocalizedMessage());
        Jota.exit();
    }
}

From source file:se.trixon.jota.client.Client.java

private void initCallbackServer()
        throws RemoteException, MalformedURLException, java.rmi.server.ExportException {
    mRmiNameClient = JotaHelper.getRmiName(SystemHelper.getHostname(), mPortClient, JotaClient.class);
    LocateRegistry.createRegistry(mPortClient);
    Naming.rebind(mRmiNameClient, this);
}

From source file:org.apache.camel.management.DefaultManagementAgent.java

protected void createJmxConnector(String host) throws IOException {
    ObjectHelper.notEmpty(serviceUrlPath, "serviceUrlPath");
    ObjectHelper.notNull(registryPort, "registryPort");

    try {//from  www  .  java2  s.  c  o m
        LocateRegistry.createRegistry(registryPort);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Created JMXConnector RMI registry on port " + registryPort);
        }
    } catch (RemoteException ex) {
        // The registry may had been created, we could get the registry instead
    }

    // must start with leading slash
    String path = serviceUrlPath.startsWith("/") ? serviceUrlPath : "/" + serviceUrlPath;
    // Create an RMI connector and start it
    final JMXServiceURL url;
    if (connectorPort > 0) {
        url = new JMXServiceURL("service:jmx:rmi://" + host + ":" + connectorPort + "/jndi/rmi://" + host + ":"
                + registryPort + path);
    } else {
        url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + registryPort + path);
    }

    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);

    if (executorService == null) {
        // we only need a single for the JMX connector
        executorService = camelContext.getExecutorServiceStrategy().newSingleThreadExecutor(this,
                "JMXConnector: " + url);
    }

    // execute the JMX connector
    executorService.execute(new Runnable() {
        public void run() {
            try {
                cs.start();
            } catch (IOException ioe) {
                LOG.warn("Could not start JMXConnector thread.", ioe);
            }
        }
    });

    LOG.info("JMX Connector thread started and listening at: " + url);
}

From source file:org.red5.server.war.RootContextLoaderServlet.java

protected void initRegistry(ServletContext ctx) {
    Registry r = null;//from ww w  .jav  a2 s . c  om
    try {
        Object o = ctx.getInitParameter("rmiPort");
        if (o != null) {
            rmiPort = Integer.valueOf((String) o);
        }
        if (System.getSecurityManager() != null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        // lookup the registry
        r = LocateRegistry.getRegistry(rmiPort);
        // ensure we are not already registered with the registry
        for (String regName : r.list()) {
            logger.debug("Registry entry: " + regName);
        }
    } catch (RemoteException re) {
        logger.info("RMI Registry server was not found on port " + rmiPort);
        // if we didnt find the registry and the user wants it created
        try {
            logger.info("Starting an internal RMI registry");
            // create registry for rmi
            r = LocateRegistry.createRegistry(rmiPort);
        } catch (RemoteException e) {
            logger.info("RMI Registry server was not started on port " + rmiPort);
        }

    }
}

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

public Integer start() {
    if (log.isDebugEnabled())
        log.debug("start()");
    try {//from   w w w.ja  v  a 2  s  .  c o  m
        // 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:au.com.jwatmuff.genericp2p.rmi.RMIPeerManager.java

@Override
public void refreshServices() {
    try {//from  www .  j a  v  a2  s . c om
        // Restart RMI Registry
        UnicastRemoteObject.unexportObject(registry, true);
        registry = LocateRegistry.createRegistry(registryPort);

        // Re-export services to new RMI Registry
        for (PeerService service : peerServiceMap.values()) {
            refreshService(service);
        }

        addSelf();
    } catch (Exception e) {
        log.error("Failed to refresh services", e);
    }
}

From source file:org.ops4j.pax.exam.container.def.internal.PaxRunnerTestContainer.java

/**
 * Creates an RMI registry on the first free port found.
 *
 * @return RMI registry//from w w  w. j  av a  2  s.c om
 */
protected int createRegistry() {
    for (int port = Registry.REGISTRY_PORT; port <= Registry.REGISTRY_PORT + AMOUNT_OF_PORTS_TO_CHECK; port++) {
        try {
            m_registry = LocateRegistry.createRegistry(port);
            LOG.info("RMI registry started on port [" + port + "]");
            return port;
        } catch (Exception e) {
            // ignore and try next port number
        }
    }

    throw new RuntimeException("No free port in range " + Registry.REGISTRY_PORT + ":" + Registry.REGISTRY_PORT
            + AMOUNT_OF_PORTS_TO_CHECK);
}

From source file:com.redsqirl.auth.UserInfoBean.java

/**
 * createRegistry//from   w  w  w . j a  v  a  2 s. c  om
 * 
 * Method to create the connection to the server rmi. Retrieve objects and
 * places them in the context of the application.
 * 
 * @return
 * @author Igor.Souza
 */
public boolean createRegistry() {

    logger.warn("createRegistry");

    List<String> beans = new ArrayList<String>();
    beans.add("wfm");
    beans.add("ssharray");
    beans.add("jdbc");
    beans.add("hcat");
    beans.add("oozie");
    beans.add("hdfs");
    beans.add("prefs");
    beans.add("hdfsbrowser");
    beans.add("samanager");

    FacesContext fCtx = FacesContext.getCurrentInstance();
    ServletContext sc = (ServletContext) fCtx.getExternalContext().getContext();
    HttpSession session = (HttpSession) fCtx.getExternalContext().getSession(false);

    try {
        try {
            registry = LocateRegistry.getRegistry(port);
        } catch (Exception e) {
            registry = LocateRegistry.createRegistry(port);
        }

        Iterator<String> beanIt = beans.iterator();
        while (beanIt.hasNext()) {
            String bean = beanIt.next();
            try {
                registry.unbind(userName + "@" + beanIt.next());
            } catch (NotBoundException e) {
                logger.warn("Object " + bean + " unable to unbind: " + e.getMessage());
            } catch (Exception e) {
                logger.warn("Object " + bean + " unable to unbind: " + e.getMessage());
            }
        }

        if (th != null) {
            String pid = new WorkflowProcessesManager(userName).getPid();
            logger.warn("Kill the process " + pid);
            th.kill(pid);
        }

        th = new ServerProcess(port);
        logger.warn("Sys home is : " + WorkflowPrefManager.pathSysHome);
        th.run(userName, sessionSSH);
        logger.warn("Sys home is : " + WorkflowPrefManager.pathSysHome);

        if (sessionSSH != null) {
            sc.setAttribute("UserInfo", sessionSSH.getUserInfo());
        }

        logger.info("update progressbar");
        setValueProgressBar(10);

        session.setAttribute("serverThread", th);
        sc.setAttribute("registry", registry);
        Iterator<String> itBean = beans.iterator();
        while (itBean.hasNext() && !cancel) {
            String beanName = itBean.next();
            logger.warn("createRegistry - " + beanName);

            if (beanName.equalsIgnoreCase("wfm")) {
                boolean error = true;
                int tryNumb = 0;
                while (error && !cancel) {
                    ++tryNumb;
                    try {
                        DataFlowInterface dfi = (DataFlowInterface) registry.lookup(userName + "@" + beanName);
                        dfi.addWorkflow("test");
                        error = false;
                        dfi.removeWorkflow("test");

                        //FIXME size cluster aws
                        //                     if(!dfi.checkNumberCluster(getNumberCluster())){
                        //                        setErrorNumberCluster(getMessageResources("error_number_cluster"));
                        //                        return false;
                        //                     }

                        logger.warn("workflow is running ");
                    } catch (Exception e) {
                        logger.info("workflow not running ");
                        Thread.sleep(500);
                        if (tryNumb > 1 * 60 * 2000000) {
                            throw e;
                        }
                        if (getValueProgressBar() < 45) {
                            logger.info("update progressbar");
                            setValueProgressBar(Math.min(79, getValueProgressBar() + 3));
                        } else {
                            setValueProgressBar(Math.min(79, getValueProgressBar() + 2));
                        }
                    }
                }
                logger.info("update progressbar");
                setValueProgressBar(80);
            }

            boolean error = true;
            int cont = 0;

            while (error && !cancel) {
                cont++;
                try {
                    Remote remoteObject = registry.lookup(userName + "@" + beanName);
                    error = false;
                    session.setAttribute(beanName, remoteObject);
                } catch (Exception e) {
                    Thread.sleep(500);
                    logger.error(e.getMessage());
                    // Time out after 3 minutes
                    if (cont > 1 * 60 * 2000000) {
                        throw e;
                    }
                }
            }
        }

        return true;

    } catch (Exception e) {
        logger.error("Fail to initialise registry, Exception: " + e.getMessage(), e);
        return false;
    }

}