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:org.apache.juddi.api.impl.API_091_RMISubscriptionListenerIntegrationTest.java

@BeforeClass
public static void startManager() throws ConfigurationException {
    org.apache.juddi.Registry.start();
    try {//  ww w.  ja  v  a2 s .co m
        //random port
        randomPort = 19800 + new Random().nextInt(99);
        System.out.println("RMI Random port=" + randomPort);
        //bring up the RMISubscriptionListener
        URI rmiEndPoint = new URI("rmi://localhost:" + randomPort + "/tck/rmisubscriptionlistener");
        registry = LocateRegistry.createRegistry(rmiEndPoint.getPort());
        path = rmiEndPoint.getPath();

        //starting the service
        rmiSubscriptionListenerService = new UDDISubscriptionListenerImpl(0);
        //binding to the RMI Registry
        registry.bind(path, rmiSubscriptionListenerService);

        //double check that the service is bound in the local Registry
        Registry registry2 = LocateRegistry.getRegistry(rmiEndPoint.getHost(), rmiEndPoint.getPort());
        registry2.lookup(rmiEndPoint.getPath());

    } catch (Exception e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
        Assert.fail();
    }

    //manager  = new UDDIClient();
    //manager.start();

    logger.debug("Getting auth tokens..");
    try {

        api010.saveJoePublisher();
        UDDISecurityPortType security = new UDDISecurityImpl();
        authInfoJoe = TckSecurity.getAuthToken(security, TckPublisher.getJoePublisherId(),
                TckPublisher.getJoePassword());
        Assert.assertNotNull(authInfoJoe);

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        Assert.fail("Could not obtain authInfo token.");
    }
}

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.ja  va 2  s .c  o  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:dk.netarkivet.common.management.MBeanConnectorCreator.java

/**
 * Registers an RMI connector to the local mbean server in a private RMI
 * registry, under the name "jmxrmi". The port for the registry is read from
 * settings, and the RMI port used for exposing the connector is also read
 * from settings. Access to the mbean server is restricted by the rules set
 * in the password file, likewise read from settings.
 *
 * @throws IOFailure on trouble exposing the server.
 *//*from  ww  w  .ja v  a  2  s  . c o m*/
public static synchronized void exposeJMXMBeanServer() {
    try {
        if (!isExposed) {
            int jmxPort = Settings.getInt(CommonSettings.JMX_PORT);
            int rmiPort = Settings.getInt(CommonSettings.JMX_RMI_PORT);
            String passwordFile = Settings.get(CommonSettings.JMX_PASSWORD_FILE);

            // Create a private registry for the exposing the JMX connector.
            LocateRegistry.createRegistry(jmxPort);
            // Create a URL that signifies that we wish to use the local
            // registry created above, and listen for rmi callbacks on the
            // RMI port of this machine, exposing the mbeanserver with the
            // name "jmxrmi".
            String canonicalHostName = SystemUtils.getLocalHostName();
            JMXServiceURL url = new JMXServiceURL(MessageFormat.format(SERVICE_JMX_RMI_URL, canonicalHostName,
                    Integer.toString(rmiPort), Integer.toString(jmxPort)));
            // Insert the password file into environment used when creating
            // the connector server.
            Map<String, Serializable> env = new HashMap<String, Serializable>();
            env.put(ENVIRONMENT_PASSWORD_FILE_PROPERTY, passwordFile);
            // Register the connector to the local mbean server in this
            // registry under that URL, using the created environment
            // settings.
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            // Start the connector server.
            cs.start();
            isExposed = true;
            // Register the JMX server at the registry.
            MonitorRegistryClientFactory.getInstance().register(canonicalHostName,
                    Settings.getInt(CommonSettings.JMX_PORT), Settings.getInt(CommonSettings.JMX_RMI_PORT));

            if (log.isInfoEnabled()) {
                log.info("Registered mbean server in registry on port " + jmxPort + " communicating on port "
                        + rmiPort + " using password file '" + passwordFile + "'." + "\nService URL is "
                        + url.toString());
            }
        }
    } catch (IOException e) {
        throw new IOFailure("Error creating and registering an" + " RMIConnector to the platform mbean server.",
                e);
    }
}

From source file:com.espertech.esper.example.servershell.ServerShellMain.java

public ServerShellMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }// w w w  . j av a 2  s . co  m
    properties.load(propertiesIS);

    // Start RMI registry
    log.info("Starting RMI registry");
    int port = Integer.parseInt(properties.getProperty(ServerShellConstants.MGMT_RMI_PORT));
    LocateRegistry.createRegistry(port);

    // Obtain MBean servera
    log.info("Obtaining JMX server and connector");
    MBeanServer mbs = MBeanServerFactory.createMBeanServer();
    String jmxServiceURL = properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL);
    JMXServiceURL jmxURL = new JMXServiceURL(jmxServiceURL);
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(jmxURL, null, mbs);
    cs.start();

    // Initialize engine
    log.info("Getting Esper engine instance");
    Configuration configuration = new Configuration();
    configuration.addEventType("SampleEvent", SampleEvent.class.getName());
    EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider(configuration);

    // Initialize engine
    log.info("Creating sample statement");
    SampleStatement.createStatement(engine.getEPAdministrator());

    // Register MBean
    log.info("Registering MBean");
    ObjectName name = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMX mbean = new EPServiceProviderJMX(engine);
    mbs.registerMBean(mbean, name);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    int numListeners = Integer.parseInt(properties.getProperty(ServerShellConstants.JMS_NUM_LISTENERS));
    log.info("Creating " + numListeners + " listeners to destination '" + destination + "'");

    SampleJMSMessageListener listeners[] = new SampleJMSMessageListener[numListeners];
    for (int i = 0; i < numListeners; i++) {
        listeners[i] = new SampleJMSMessageListener(engine.getEPRuntime());
        MessageConsumer consumer = jmsCtx.getSession().createConsumer(jmsCtx.getDestination());
        consumer.setMessageListener(listeners[i]);
    }

    // Start processing
    log.info("Starting JMS connection");
    jmsCtx.getConnection().start();

    // Register shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            isShutdown = true;
        }
    });

    // Report statistics
    long startTime = System.currentTimeMillis();
    long currTime;
    double deltaSeconds;
    int lastTotalEvents = 0;
    AccumulatingStat avgLast5 = new AccumulatingStat(5);
    AccumulatingStat avgLast10 = new AccumulatingStat(10);
    AccumulatingStat avgLast20 = new AccumulatingStat(20);
    do {
        // sleep
        Thread.sleep(1000);
        currTime = System.currentTimeMillis();
        deltaSeconds = (currTime - startTime) / 1000.0;

        // compute stats
        int totalEvents = 0;
        for (int i = 0; i < listeners.length; i++) {
            totalEvents += listeners[i].getCount();
        }

        double totalLastBatch = totalEvents - lastTotalEvents;

        avgLast5.add(totalLastBatch);
        avgLast10.add(totalLastBatch);
        avgLast20.add(totalLastBatch);

        log.info("total=" + totalEvents + " last=" + totalLastBatch + " last5Avg=" + avgLast5.getAvg()
                + " last10Avg=" + avgLast10.getAvg() + " last20Avg=" + avgLast20.getAvg() + " time="
                + deltaSeconds);
        lastTotalEvents = totalEvents;
    } while (!isShutdown);

    log.info("Shutting down server");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}

From source file:com.symbian.driver.remoting.master.TestMaster.java

/**
 * Start master.//from www.j  av a2 s  .co m
 */
public void start() {

    String bindingName = null;
    String jobsFolder = null;
    String lHostName = null;
    String lServiceName = null;

    // start rmi registry
    /*
     * The user can specify the ip@ or the host name at config --server
     */
    try {

        TDConfig CONFIG = TDConfig.getInstance();
        lHostName = CONFIG.getPreference(TDConfig.SERVER_NAME);
        lServiceName = CONFIG.getPreference(TDConfig.SERVICE);

        LOGGER.fine("Host: " + lHostName + " RMI Service: " + lServiceName);

        jobsFolder = CONFIG.getPreferenceFile(TDConfig.JOBS_FOLDER).getAbsolutePath();
        if (lHostName.matches("^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")) {
            LOGGER.fine("Using host ip address for RMI from the config : " + lHostName);
            lHostName = InetAddress.getByName(lHostName).getHostName();
        }

        if (lHostName == null) {
            LOGGER.log(Level.SEVERE, "Could not determine the Host Name. Please check your config.");
            System.exit(-1);
        }

        System.getProperties().setProperty("java.rmi.server.hostname", lHostName);
        Registry lRegistry = LocateRegistry.createRegistry(1099);
        LOGGER.fine("Master: RMI registry ready. " + lRegistry);

    } catch (ParseException lE) {
        LOGGER.log(Level.SEVERE, "Master: Can not parse configuration.", lE);
        System.exit(-1);
    } catch (UnknownHostException lUHE) {
        LOGGER.log(Level.SEVERE, "Invalid host name " + lHostName, lUHE);
        System.exit(-1);
    } catch (RemoteException lRemoteException) {
        LOGGER.log(Level.SEVERE, "Master: RMI registry failed to start " + lRemoteException.getMessage(),
                lRemoteException);
        System.exit(-1);
    }

    File storeFolder = new File(SERIALIZE_FOLDER);
    if (!(storeFolder.isDirectory())) {
        if (!(storeFolder.mkdirs())) {
            LOGGER.log(Level.SEVERE,
                    "Master: Unable to create the store folder." + "Please ensure that the " + SERIALIZE_FOLDER
                            + " folder exists. It is needed by Master for placing system restore files.");
            System.exit(-1);
        }
    }

    try {
        if (ClientRegister.getInstance().needRestore()) {
            LOGGER.info("Restoring Client register.");
            ClientRegister.getInstance().restoreSnapshot();
        }
        if (JobTracker.getInstance().needRestore()) {
            LOGGER.info("Restoring Job tracker.");
            JobTracker.getInstance().restoreSnapshot();
        }
        JobCounter jobCounter = new JobCounter();
        if (jobCounter.needRestore()) {
            LOGGER.info("Restoring Job counter.");
            jobCounter.restoreSnapshot();
        }
        QueuedExecutor queuedExecutor = new QueuedExecutor();
        if (queuedExecutor.needRestore()) {
            LOGGER.info("Restoring execution queue.");
            queuedExecutor.restoreSnapshot();
        }
        bindingName = "//" + lHostName + "/" + lServiceName;
        MasterRemote master = new MasterRemoteImpl(jobsFolder, jobCounter, queuedExecutor);
        Naming.rebind(bindingName, master);
        LOGGER.info("Remote Service Name : " + bindingName);
    } catch (RemoteException lRE) {
        LOGGER.log(Level.SEVERE, "Master: Problem with contacting the RMI Registry: ", lRE);
        System.exit(-1);
    } catch (IOException lE) {
        LOGGER.log(Level.SEVERE, "Master: Problem with starting up TestMaster: ", lE);
        System.exit(-1);
    }
}

From source file:com.taobao.tddl.common.util.TDDLMBeanServer.java

private TDDLMBeanServer() {
    // MBServer/* www .  j  ava  2s .  c  o  m*/
    String hostName = null;
    try {
        InetAddress addr = InetAddress.getLocalHost();

        hostName = addr.getHostName();
    } catch (IOException e) {
        log.error(LogPrefix + "Get HostName Error", e);
        hostName = "localhost";
    }
    String host = System.getProperty("hostName", hostName);
    try {
        boolean useJmx = Boolean.parseBoolean(System.getProperty("tddl.useJMX", "true"));
        if (useJmx) {
            mbs = ManagementFactory.getPlatformMBeanServer();
            int port = Integer.parseInt(System.getProperty("tddl.rmi.port", "6679"));
            String rmiName = System.getProperty("tddl.rmi.name", "tddlJmxServer");
            Registry reg = null;
            try {
                reg = LocateRegistry.getRegistry(port);
                reg.list();
            } catch (Exception e) {
                reg = null;
            }
            if (null == reg) {
                reg = LocateRegistry.createRegistry(port);
            }
            reg.list();
            String serverURL = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/" + rmiName;
            JMXServiceURL url = new JMXServiceURL(serverURL);
            final JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url,
                    null, mbs);
            connectorServer.start();
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    try {
                        System.err.println("JMXConnector stop");
                        connectorServer.stop();
                    } catch (IOException e) {
                        log.error(LogPrefix + e);
                    }
                }
            });
            log.warn(LogPrefix + "jmx url: " + serverURL);
        }
    } catch (Exception e) {
        log.error(LogPrefix + "create MBServer error", e);
    }
}

From source file:org.apache.juddi.rmi.RMIRegistration.java

private RMIRegistration(int port) throws NamingException, RemoteException {
    super();
    registry = LocateRegistry.createRegistry(port);
}

From source file:com.cisco.oss.foundation.monitoring.RMIRegistryManager.java

/**
 * Starts in-process rmiregistry on the specified port.
 *
 * @param port on which the rmiregistry needs to be started
 * @return true if successful, false otherwise
 */// w ww .j  a  v  a2s.  com
public static boolean startInProcRMIRegistry(final int port) {
    LOGGER.info("Starting In-Process rmiregistry on port " + port);
    boolean result = true;
    try {
        LocateRegistry.createRegistry(port);
        LOGGER.info("In-Process rmiregistry started on port " + port);
    } catch (RemoteException e) {
        LOGGER.error("Failed to start In-Process rmiregistry on port " + port);
        result = false;
    }
    return result;
}

From source file:edu.mines.acmX.exhibit.runner.ModuleManagerRunner.java

private static void publicizeRmiInterface(ModuleManager m, int registry_port) throws RemoteException {
    ModuleManagerRemote remote = (ModuleManagerRemote) UnicastRemoteObject.exportObject(m, 0);
    Registry reg = LocateRegistry.createRegistry(registry_port);
    logger.info("java RMI registry created.");
    reg.rebind(RMI_SERVER_NAME, remote);
}

From source file:com.mindquarry.jcr.jackrabbit.JCRTestBaseStandalone.java

@Override
protected void setUp() throws Exception {

    this.logger = new ConsoleLogger(ConsoleLogger.LEVEL_WARN);

    // remove old repository
    File repoFolder = new File("target/repository"); //$NON-NLS-1$
    removeRepository(repoFolder);//from   w  ww  .ja  va  2 s.  c  o  m

    InputStream repoConfigIn = getClass().getResourceAsStream(REPO_CONFIG_FILE);

    File tempRepoConfigFile = File.createTempFile("repository", "xml"); //$NON-NLS-1$ //$NON-NLS-2$
    tempRepoConfigFile.deleteOnExit();

    OutputStream tempRepoConfigOut = new FileOutputStream(tempRepoConfigFile);

    try {
        IOUtils.copy(repoConfigIn, tempRepoConfigOut);
    } finally {
        repoConfigIn.close();
        tempRepoConfigOut.close();
    }

    Repository repo = new TransientRepository(tempRepoConfigFile.getAbsolutePath(), "target/repository"); //$NON-NLS-1$

    ServerAdapterFactory factory = new ServerAdapterFactory();
    RemoteRepository remoteRepo = factory.getRemoteRepository(repo);

    reg = LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
    reg.rebind(REMOTE_REPO_NAME, remoteRepo);

    session = repo.login(new SimpleCredentials(LOGIN, PWD.toCharArray()), WORKSPACE);

    InputStream nodeTypeDefIn = getClass().getResourceAsStream(MQ_JCR_XML_NODETYPES_FILE);

    JackrabbitInitializerHelper.setupRepository(session, new InputStreamReader(nodeTypeDefIn), ""); //$NON-NLS-1$
}