Java Code Examples for java.rmi.registry.LocateRegistry

The following are top voted examples for showing how to use java.rmi.registry.LocateRegistry. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: QuartzScheduler.java   View source code 7 votes vote down vote up
/**
 * <p>
 * Un-bind the scheduler from an RMI registry.
 * </p>
 */
private void unBind() throws RemoteException {
    String host = resources.getRMIRegistryHost();
    // don't un-export if we're not configured to do so...
    if (host == null || host.length() == 0) {
        return;
    }

    Registry registry = LocateRegistry.getRegistry(resources
            .getRMIRegistryHost(), resources.getRMIRegistryPort());

    String bindName = resources.getRMIBindName();
    
    try {
        registry.unbind(bindName);
        UnicastRemoteObject.unexportObject(this, true);
    } catch (java.rmi.NotBoundException nbe) {
    }

    getLog().info("Scheduler un-bound from name '" + bindName + "' in RMI registry");
}
 
Example 2
Project: Pogamut3   File: Test01_Jmx.java   View source code 6 votes vote down vote up
@BeforeClass
public static void setUpClass() throws RemoteException, MalformedURLException, IOException {
    Registry r = LocateRegistry.createRegistry(9999);
    mbs = MBeanServerFactory.createMBeanServer();

    person = new Test01_JavaIntrospection.Person("Alice Aho", 23);
    person.knows = new Test01_JavaIntrospection.Person("Bob", 30);
    
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
    cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    if (cs == null) {
    	throw new RuntimeException("Could not setUpClass() for test! JMXConnectorServerFactory.newJMXConnectorServer FAILED (Returned null...)! Url: " + url + ", mbs: " + mbs);
    }
    cs.start();
    System.out.println("Registry created / JMX connector started.");
}
 
Example 3
Project: Pogamut3   File: DefaultPogamutPlatform.java   View source code 6 votes vote down vote up
/**
 * Returns MBeans server for the Pogamut Platform. All MBeans connected from
 * the platform should be registered in this server. There is also default
 * RMI connector for this server running on service:jmx:rmi:///jndi/rmi://localhost:9999/server
 * @return
 * @throws cz.cuni.amis.utils.exception.PogamutException
 */
@Override
public synchronized MBeanServer getMBeanServer() throws PogamutException {
    try {
        if (!registryCreated) {
            if (log.isLoggable(Level.WARNING)) log.warning("Creating registry at " + getRMIPort() + " ...");
            LocateRegistry.createRegistry(getRMIPort());
            registryCreated = true;
        }
        if (mBeanServer == null) {
            if (log.isLoggable(Level.WARNING)) log.warning("Starting MBean server.");
            //start a RMI registry                
            mBeanServer = new PogamutMBeanServer();

            // also create connector for this server, server without connector
            // would be unreachable outside this JVM
            cs = JMXConnectorServerFactory.newJMXConnectorServer(getMBeanServerURL(), null, mBeanServer);
            cs.start();

        }
        return mBeanServer;
    } catch (Exception ex) {
        throw new PogamutException("Error during JMX initialization.", ex);
    }
}
 
Example 4
Project: JavaRushTasks   File: Solution.java   View source code 6 votes vote down vote up
@Override
public void run() {
    //напишите тут ваш код
    try {
        //создание объекта для удаленного доступа
        final Animal cat = new Cat("Barsik");
        final Animal dog = new Dog("Palkan");

        //создание реестра расшареных объетов
        registry = LocateRegistry.createRegistry(2099);

        //создание "заглушки" – приемника удаленных вызовов
        Remote stubCat = UnicastRemoteObject.exportObject(cat, 0);
        Remote stubDog = UnicastRemoteObject.exportObject(dog, 0);

        //регистрация "заглушки" в реесте
        registry.bind(BINDING_NAME1, stubCat);
        registry.bind(BINDING_NAME2, stubDog);

    } catch (RemoteException | AlreadyBoundException e) {
        e.printStackTrace();
    }
}
 
Example 5
Project: ats-framework   File: AbstractRMIDriver.java   View source code 6 votes vote down vote up
@Override
public void start() {

    try {
        JavaSecurityUtils.unlockJavaSecurity();

        if( System.getSecurityManager() == null ) {
            System.setSecurityManager( new SecurityManager() );
        }

        log.info( "Connecting to " + connectionDescription );
        this.registry = LocateRegistry.getRegistry( this.ip, this.rmiPort );
        log.info( "Successfully connected to " + connectionDescription );
    } catch( Exception e ) {
        throw new RmiException( "Error connecting to " + connectionDescription, e );
    }
}
 
Example 6
Project: lams   File: RmiServiceExporter.java   View source code 6 votes vote down vote up
/**
 * Locate or create the RMI registry for this exporter.
 * @param registryHost the registry host to use (if this is specified,
 * no implicit creation of a RMI registry will happen)
 * @param registryPort the registry port to use
 * @param clientSocketFactory the RMI client socket factory for the registry (if any)
 * @param serverSocketFactory the RMI server socket factory for the registry (if any)
 * @return the RMI registry
 * @throws RemoteException if the registry couldn't be located or created
 */
protected Registry getRegistry(String registryHost, int registryPort,
		RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory)
		throws RemoteException {

	if (registryHost != null) {
		// Host explicitly specified: only lookup possible.
		if (logger.isInfoEnabled()) {
			logger.info("Looking for RMI registry at port '" + registryPort + "' of host [" + registryHost + "]");
		}
		Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory);
		testRegistry(reg);
		return reg;
	}

	else {
		return getRegistry(registryPort, clientSocketFactory, serverSocketFactory);
	}
}
 
Example 7
Project: lams   File: RmiServiceExporter.java   View source code 6 votes vote down vote up
/**
 * Locate or create the RMI registry for this exporter.
 * @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.alwaysCreateRegistry) {
		logger.info("Creating new RMI registry");
		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.
			return LocateRegistry.createRegistry(registryPort);
		}
	}
}
 
Example 8
Project: lams   File: RmiRegistryFactoryBean.java   View source code 6 votes vote down vote up
/**
 * Locate or create the RMI registry.
 * @param registryHost the registry host to use (if this is specified,
 * no implicit creation of a RMI registry will happen)
 * @param registryPort the registry port to use
 * @param clientSocketFactory the RMI client socket factory for the registry (if any)
 * @param serverSocketFactory the RMI server socket factory for the registry (if any)
 * @return the RMI registry
 * @throws java.rmi.RemoteException if the registry couldn't be located or created
 */
protected Registry getRegistry(String registryHost, int registryPort,
		RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory)
		throws RemoteException {

	if (registryHost != null) {
		// Host explicitly specified: only lookup possible.
		if (logger.isInfoEnabled()) {
			logger.info("Looking for RMI registry at port '" + registryPort + "' of host [" + registryHost + "]");
		}
		Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory);
		testRegistry(reg);
		return reg;
	}

	else {
		return getRegistry(registryPort, clientSocketFactory, serverSocketFactory);
	}
}
 
Example 9
Project: lams   File: RmiRegistryFactoryBean.java   View source code 6 votes vote down vote up
/**
 * Locate or create the RMI registry.
 * @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);
		}
	}
}
 
Example 10
Project: lams   File: RemoteScheduler.java   View source code 6 votes vote down vote up
protected RemotableQuartzScheduler getRemoteScheduler()
    throws SchedulerException {
    if (rsched != null) {
        return rsched;
    }

    try {
        Registry registry = LocateRegistry.getRegistry(rmiHost, rmiPort);

        rsched = (RemotableQuartzScheduler) registry.lookup(schedId);

    } catch (Exception e) {
        SchedulerException initException = new SchedulerException(
                "Could not get handle to remote scheduler: "
                        + e.getMessage(), e);
        throw initException;
    }

    return rsched;
}
 
Example 11
Project: otter-G   File: JmxConnectorServerFactoryBean.java   View source code 6 votes vote down vote up
private Registry getRegistry(int registryPort) throws RemoteException {
    if (this.alwaysCreateRegistry) {
        logger.info("Creating new RMI registry");
        return LocateRegistry.createRegistry(registryPort);
    }
    if (logger.isInfoEnabled()) {
        logger.info("Looking for RMI registry at port '" + registryPort + "'");
    }
    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.
        return LocateRegistry.createRegistry(registryPort);
    }
}
 
Example 12
Project: openjdk-jdk10   File: RMIConnectorLogAttributesTest.java   View source code 6 votes vote down vote up
private JMXConnectorServer startServer(int rmiPort) throws Exception {
    System.out.println("DEBUG: Create RMI registry on port " + rmiPort);
    LocateRegistry.createRegistry(rmiPort);

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    HashMap<String,Object> env = new HashMap<String,Object>();

    JMXServiceURL url =
            new JMXServiceURL("service:jmx:rmi:///jndi/rmi://127.0.0.1:" + rmiPort + "/jmxrmi");
    JMXConnectorServer cs =
            JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);

    cs.start();
    System.out.println("DEBUG: Started the RMI connector server");
    return cs;
}
 
Example 13
Project: Proyecto-DASI   File: AdaptadorRegRMI.java   View source code 6 votes vote down vote up
public static Registry getRegistroRMInodoRemoto (String identHost){

   // Si no existe se crea el registro en el nodo local y en el puerto por defecto
//       if (registroRMILocalCreado ) return registroRMILocal ;

         try {
//             hostRMI =  getIPLocal();
//             hostRMI = InetAddress.getLocalHost().getHostName();
////             hostRMI = InetAddress.getByName("SERTORIUS").toString();
//             puertoRMIOrganizacionconfigurado = configuracionOrganizacion.getPropiedadesGlobales().getProperty("PuertoRMI");
//             if (puertoRMIOrganizacionconfigurado != null)puertoRMI = Integer.parseInt (puertoRMIOrganizacionconfigurado);
//             registroRMILocal = LocateRegistry.createRegistry(puertoRMI);
//             registroRMILocalCreado = true;
            return LocateRegistry.getRegistry(identHost);

            } catch (Exception e) {

                logger.error("Error al localizar el registro de la organizacion  en el nodo--: "+ hostRMI + " Es posible que no se haya creado: Revisar la descripcion de la organizacion" );
                trazas.aceptaNuevaTraza(new InfoTraza("AdaptadorRegRMI",
						"La direccion IP del registro RMI es NULA  "+ hostRMI + "-- Es posible que no se haya creado: Revisar la descripcion de la organizacion" ,
						InfoTraza.NivelTraza.error));
//
                return null;
            }

    }
 
Example 14
Project: Proyecto-DASI   File: AdaptadorRegRMI.java   View source code 6 votes vote down vote up
public static Remote getRemoteEntityFromHost(String host, int puerto, String identEntity) throws java.rmi.RemoteException {
        Registry regCliente = LocateRegistry.getRegistry(host, puerto);
        Object remoteEntity = null;
//        ItfUsoRecursoTrazas trazas = Directorio.getRecursoTrazas();
        try {
            if (regCliente == null) {
//                System.err.println("buscarAgenteRemoto regCliente == null");
//                if (trazas != null)
                trazas.aceptaNuevaTraza(new InfoTraza("AdaptadorRegRMI", " No se puede obtener la entidad : "+
                        identEntity + " No se consigue encontrar el  registro RMI del Host :" + host + " puerto:" + puerto, NivelTraza.debug));
            }
            return  regCliente.lookup(identEntity);

        } catch (Exception ex) {
            System.err.println("Fallo buscaAgenteRemoto\n"+ ex.getMessage());
            trazas.aceptaNuevaTraza(new InfoTraza("AdaptadorRegRMI", " No se puede obtener la entidad : "+
                      identEntity + " No se consigue encontrar el  registro RMI del Host :" + host + " puerto:"+ puerto , NivelTraza.debug));
//            Logger.getLogger(ComunicacionAgentes.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
 
Example 15
Project: Proyecto-DASI   File: ControlRMI.java   View source code 6 votes vote down vote up
public static boolean startRMI() {
    try {
        registroRMI = LocateRegistry.createRegistry(puertoRMI);
        System.err.println("Registro listo en " + puertoRMI);
  
        return true;
    } catch (Exception e) {
        System.err.println("No se ha podido crear el registro RMI");
        try {
            registroRMI = LocateRegistry.getRegistry(puertoRMI);
            System.err.println ("El registro ya existia (RMI listo)");
 
            return true;
        }
        catch (Exception ex) {
            System.err.println ("RMI no disponible!!\n" + ex.getMessage());
            return false;
        }
    }
}
 
Example 16
Project: Proyecto-DASI   File: ControlRMI.java   View source code 6 votes vote down vote up
public static ItfUsoAgenteReactivo buscarAgenteRemoto(String ip, int puerto, String nombreAgente) throws java.rmi.RemoteException {
        Registry regCliente = LocateRegistry.getRegistry(ip, puerto);
        ItfUsoAgenteReactivo agenteRemoto = null;
//        ItfUsoRecursoTrazas trazas = Directorio.getRecursoTrazas();
        try {            
            if (regCliente == null) {
                System.err.println("buscarAgenteRemoto regCliente == null");
                if (trazas != null)
                trazas.aceptaNuevaTraza(new InfoTraza("ControlRMI (null)", "No consigo encontrar al agente: "+
                        nombreAgente + " en ip:" + ip + " puerto:" + puerto, NivelTraza.error));
            }
            agenteRemoto = (ItfUsoAgenteReactivo) regCliente.lookup(nombreAgente);
            return agenteRemoto;
        } catch (Exception ex) {
            System.err.println("Fallo buscaAgenteRemoto\n"+ ex.getMessage());
            if (trazas != null)
            trazas.aceptaNuevaTraza(new InfoTraza("ControlRMI (Excepcion)", "No consigo encontrar al agente: "+
                        nombreAgente + " en ip:" + ip + " puerto:" + puerto, NivelTraza.error));
//            Logger.getLogger(ComunicacionAgentes.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
 
Example 17
Project: asura   File: RemoteScheduler.java   View source code 6 votes vote down vote up
protected RemotableQuartzScheduler getRemoteScheduler()
    throws SchedulerException {
    if (rsched != null) {
        return rsched;
    }

    try {
        Registry registry = LocateRegistry.getRegistry(rmiHost, rmiPort);

        rsched = (RemotableQuartzScheduler) registry.lookup(schedId);

    } catch (Exception e) {
        SchedulerException initException = new SchedulerException(
                "Could not get handle to remote scheduler: "
                        + e.getMessage(), e);
        initException
                .setErrorCode(SchedulerException.ERR_COMMUNICATION_FAILURE);
        throw initException;
    }

    return rsched;
}
 
Example 18
Project: asura   File: QuartzScheduler.java   View source code 6 votes vote down vote up
/**
 * <p>
 * Un-bind the scheduler from an RMI registry.
 * </p>
 */
private void unBind() throws RemoteException {
    String host = resources.getRMIRegistryHost();
    // don't un-export if we're not configured to do so...
    if (host == null || host.length() == 0) {
        return;
    }

    Registry registry = LocateRegistry.getRegistry(resources
            .getRMIRegistryHost(), resources.getRMIRegistryPort());

    String bindName = resources.getRMIBindName();
    
    try {
        registry.unbind(bindName);
        UnicastRemoteObject.unexportObject(this, true);
    } catch (java.rmi.NotBoundException nbe) {
    }

    getLog().info("Scheduler un-bound from name '" + bindName + "' in RMI registry");
}
 
Example 19
Project: OpenJSharp   File: RegistryContext.java   View source code 6 votes vote down vote up
/**
 * Returns the registry at a given host, port and socket factory.
 * If "host" is null, uses default host.
 * If "port" is non-positive, uses default port.
 * If "socketFactory" is null, uses the default socket.
 */
private static Registry getRegistry(String host, int port,
            RMIClientSocketFactory socketFactory)
        throws NamingException
{
    // %%% We could cache registry connections here.  The transport layer
    // may already reuse connections.
    try {
        if (socketFactory == null) {
            return LocateRegistry.getRegistry(host, port);
        } else {
            return LocateRegistry.getRegistry(host, port, socketFactory);
        }
    } catch (RemoteException e) {
        throw (NamingException)wrapRemoteException(e).fillInStackTrace();
    }
}
 
Example 20
Project: jdk8u-jdk   File: RegistryContext.java   View source code 6 votes vote down vote up
/**
 * Returns the registry at a given host, port and socket factory.
 * If "host" is null, uses default host.
 * If "port" is non-positive, uses default port.
 * If "socketFactory" is null, uses the default socket.
 */
private static Registry getRegistry(String host, int port,
            RMIClientSocketFactory socketFactory)
        throws NamingException
{
    // %%% We could cache registry connections here.  The transport layer
    // may already reuse connections.
    try {
        if (socketFactory == null) {
            return LocateRegistry.getRegistry(host, port);
        } else {
            return LocateRegistry.getRegistry(host, port, socketFactory);
        }
    } catch (RemoteException e) {
        throw (NamingException)wrapRemoteException(e).fillInStackTrace();
    }
}
 
Example 21
Project: jdk8u-jdk   File: InheritedChannelNotServerSocket.java   View source code 6 votes vote down vote up
public synchronized Channel inheritedChannel() throws IOException {
    System.err.println("SP.inheritedChannel");
    if (channel == null) {
        channel = SocketChannel.open();
        Socket socket = channel.socket();
        System.err.println("socket = " + socket);

        /*
         * Notify test that inherited channel was created.
         */
        try {
            System.err.println("notify test...");
            Registry registry =
                LocateRegistry.getRegistry(TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_REGISTRY_PORT);
            Callback obj = (Callback) registry.lookup("Callback");
            obj.notifyTest();
        } catch (NotBoundException nbe) {
            throw (IOException)
                new IOException("callback object not bound").
                    initCause(nbe);
        }
    }
    return channel;
}
 
Example 22
Project: jdk8u-jdk   File: ShutdownImpl.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    try {
        int registryPort = Integer.parseInt(System.getProperty("rmi.registry.port"));
        Registry registry =
            LocateRegistry.getRegistry("", registryPort);
        ShutdownMonitor monitor = (ShutdownMonitor)
            registry.lookup(KeepAliveDuringCall.BINDING);
        System.err.println("(ShutdownImpl) retrieved shutdown monitor");

        impl = new ShutdownImpl(monitor);
        Shutdown stub = (Shutdown) UnicastRemoteObject.exportObject(impl);
        System.err.println("(ShutdownImpl) exported shutdown object");

        monitor.submitShutdown(stub);
        System.err.println("(ShutdownImpl) submitted shutdown object");

    } catch (Exception e) {
        System.err.println("(ShutdownImpl) TEST SUBPROCESS FAILURE:");
        e.printStackTrace();
    }
}
 
Example 23
Project: jdk8u-jdk   File: AddrInUse.java   View source code 6 votes vote down vote up
public void run() {

        /*
         * Attempt to create (i.e. export) a registry on the port that
         * has already been bound, and record the result.
         */
        try {
            LocateRegistry.createRegistry(port);
            synchronized (this) {
                exportSucceeded = true;
                notifyAll();
            }
        } catch (Throwable t) {
            synchronized (this) {
                exportException = t;
                notifyAll();
            }
        }
    }
 
Example 24
Project: jdk8u-jdk   File: TestLibrary.java   View source code 6 votes vote down vote up
/**
 * Helper method to determine if registry has started
 *
 * @param port The port number to check
 * @param msTimeout The amount of milliseconds to spend checking
 */

public static boolean checkIfRegistryRunning(int port, int msTimeout) {
    long stopTime = System.currentTimeMillis() + msTimeout;
    do {
        try {
            Registry r = LocateRegistry.getRegistry(port);
            String[] s = r.list();
            // no exception. We're now happy that registry is running
            return true;
        } catch (RemoteException e) {
            // problem - not ready ? Try again
            try {
                Thread.sleep(500);
            } catch (InterruptedException ie) {
                // not expected
            }
        }
    } while (stopTime > System.currentTimeMillis());
    return false;
}
 
Example 25
Project: jdk8u-jdk   File: JstatdTest.java   View source code 6 votes vote down vote up
private Registry startRegistry()
        throws InterruptedException, RemoteException {
    Registry registry = null;
    try {
        System.out.println("Start rmiregistry on port " + port);
        registry = LocateRegistry
                .createRegistry(Integer.parseInt(port));
    } catch (RemoteException e) {
        if (e.getMessage().contains("Port already in use")) {
            System.out.println("Port already in use. Trying to restart with a new one...");
            Thread.sleep(100);
            return null;
        } else {
            throw e;
        }
    }
    return registry;
}
 
Example 26
Project: jdk8u-jdk   File: RMIConnectorLogAttributesTest.java   View source code 6 votes vote down vote up
private JMXConnectorServer startServer(int rmiPort) throws Exception {
    System.out.println("DEBUG: Create RMI registry on port " + rmiPort);
    LocateRegistry.createRegistry(rmiPort);

    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    HashMap<String,Object> env = new HashMap<String,Object>();

    JMXServiceURL url =
            new JMXServiceURL("service:jmx:rmi:///jndi/rmi://127.0.0.1:" + rmiPort + "/jmxrmi");
    JMXConnectorServer cs =
            JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);

    cs.start();
    System.out.println("DEBUG: Started the RMI connector server");
    return cs;
}
 
Example 27
Project: openjdk-jdk10   File: RegistryContext.java   View source code 6 votes vote down vote up
/**
 * Returns the registry at a given host, port and socket factory.
 * If "host" is null, uses default host.
 * If "port" is non-positive, uses default port.
 * If "socketFactory" is null, uses the default socket.
 */
private static Registry getRegistry(String host, int port,
            RMIClientSocketFactory socketFactory)
        throws NamingException
{
    // %%% We could cache registry connections here.  The transport layer
    // may already reuse connections.
    try {
        if (socketFactory == null) {
            return LocateRegistry.getRegistry(host, port);
        } else {
            return LocateRegistry.getRegistry(host, port, socketFactory);
        }
    } catch (RemoteException e) {
        throw (NamingException)wrapRemoteException(e).fillInStackTrace();
    }
}
 
Example 28
Project: openjdk-jdk10   File: InheritedChannelNotServerSocket.java   View source code 6 votes vote down vote up
public synchronized Channel inheritedChannel() throws IOException {
    System.err.println("SP.inheritedChannel");
    if (channel == null) {
        channel = SocketChannel.open();
        Socket socket = channel.socket();
        System.err.println("socket = " + socket);

        /*
         * Notify test that inherited channel was created.
         */
        try {
            System.err.println("notify test...");
            int registryPort = Integer.getInteger(
                    "test.java.rmi.rmidViaInheritedChannel.registry.port", 0);
            Registry registry = LocateRegistry.getRegistry(registryPort);
            Callback obj = (Callback) registry.lookup("Callback");
            obj.notifyTest();
        } catch (NotBoundException nbe) {
            throw (IOException)
                new IOException("callback object not bound").
                    initCause(nbe);
        }
    }
    return channel;
}
 
Example 29
Project: openjdk-jdk10   File: ShutdownImpl.java   View source code 6 votes vote down vote up
public static void main(String[] args) {
    try {
        int registryPort = Integer.parseInt(System.getProperty("rmi.registry.port"));
        Registry registry =
            LocateRegistry.getRegistry("", registryPort);
        ShutdownMonitor monitor = (ShutdownMonitor)
            registry.lookup(KeepAliveDuringCall.BINDING);
        System.err.println("(ShutdownImpl) retrieved shutdown monitor");

        impl = new ShutdownImpl(monitor);
        Shutdown stub = (Shutdown) UnicastRemoteObject.exportObject(impl);
        System.err.println("(ShutdownImpl) exported shutdown object");

        monitor.submitShutdown(stub);
        System.err.println("(ShutdownImpl) submitted shutdown object");

    } catch (Exception e) {
        System.err.println("(ShutdownImpl) TEST SUBPROCESS FAILURE:");
        e.printStackTrace();
    }
}
 
Example 30
Project: openjdk-jdk10   File: AddrInUse.java   View source code 6 votes vote down vote up
public void run() {

        /*
         * Attempt to create (i.e. export) a registry on the port that
         * has already been bound, and record the result.
         */
        try {
            LocateRegistry.createRegistry(port);
            synchronized (this) {
                exportSucceeded = true;
                notifyAll();
            }
        } catch (Throwable t) {
            synchronized (this) {
                exportException = t;
                notifyAll();
            }
        }
    }
 
Example 31
Project: openjdk-jdk10   File: TestLibrary.java   View source code 6 votes vote down vote up
/**
 * Helper method to determine if registry has started
 *
 * @param port The port number to check
 * @param msTimeout The amount of milliseconds to spend checking
 */

public static boolean checkIfRegistryRunning(int port, int msTimeout) {
    final long POLLTIME_MS = 100L;
    long stopTime = computeDeadline(System.currentTimeMillis(), msTimeout);
    do {
        try {
            Registry r = LocateRegistry.getRegistry(port);
            String[] s = r.list();
            // no exception. We're now happy that registry is running
            return true;
        } catch (RemoteException e) {
            // problem - not ready ? Try again
            try {
                Thread.sleep(POLLTIME_MS);
            } catch (InterruptedException ie) {
                // not expected
            }
        }
    } while (System.currentTimeMillis() < stopTime);
    return false;
}
 
Example 32
Project: openjdk-jdk10   File: JstatdTest.java   View source code 6 votes vote down vote up
private Registry startRegistry()
        throws InterruptedException, RemoteException {
    Registry registry = null;
    try {
        System.out.println("Start rmiregistry on port " + port);
        registry = LocateRegistry
                .createRegistry(Integer.parseInt(port));
    } catch (RemoteException e) {
        if (e.getMessage().contains("Port already in use")) {
            System.out.println("Port already in use. Trying to restart with a new one...");
            Thread.sleep(100);
            return null;
        } else {
            throw e;
        }
    }
    return registry;
}
 
Example 33
Project: scratch-bench   File: Login.java   View source code 5 votes vote down vote up
public void connectServer() {
 try
    {
        Registry reg=LocateRegistry.getRegistry("localhost",5040);

        serverAddress = (ServerInterface) reg.lookup("LionKing");
        System.out.println("Connected to Server");
    
    }catch(Exception e)
    {
        System.out.println(e);
    }
}
 
Example 34
Project: DocIT   File: Server.java   View source code 5 votes vote down vote up
/**
 * Start the Server and wait for user termination by keyboard.
 * 
 * @param args
 *            This program does not accept command line parameters.
 */
public static void main(String args[]) {

	// Override the default security manager
	System.setSecurityManager(new SecurityManager());
	
	try {
		LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
	} catch (RemoteException remoteException) {
		remoteException.printStackTrace();
	}

	Server server = new Server();

	System.out.println("Server started.");
	System.out.println("Enter <CR> to end.");

	try {
		System.in.read(); // Wait for Enter ...
	} catch (IOException ioException) {
		ioException.printStackTrace();
	}

	try {
		Naming.unbind("//" + server.hostname + "/meganalysis");
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		System.exit(0);
	}
}
 
Example 35
Project: APacheSynapseSimplePOC   File: RMIRegistryExploit.java   View source code 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
	final String host = args[0];
	final int port = Integer.parseInt(args[1]);
	final String command = args[3];
	final Registry registry = LocateRegistry.getRegistry(host, port);
	final String className = CommonsCollections1.class.getPackage().getName() +  "." + args[2];
	final Class<? extends ObjectPayload> payloadClass = (Class<? extends ObjectPayload>) Class.forName(className);

	// ensure payload doesn't detonate during construction or deserialization
	exploit(registry, payloadClass, command);
}
 
Example 36
Project: ysoserial-plus   File: RMIRegistryExploit.java   View source code 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
	final String host = args[0];
	final int port = Integer.parseInt(args[1]);
	final String command = args[3];
	final Registry registry = LocateRegistry.getRegistry(host, port);
	final String className = CommonsCollections1.class.getPackage().getName() +  "." + args[2];
	final Class<? extends ObjectPayload> payloadClass = (Class<? extends ObjectPayload>) Class.forName(className);

	// ensure payload doesn't detonate during construction or deserialization
	exploit(registry, payloadClass, command);
}
 
Example 37
Project: OpenDA   File: Server.java   View source code 5 votes vote down vote up
public String getInstance(IStochModelFactory.OutputLevel outputLevel)  {
    String instanceID=null;

 try {
        nModels++;
        instanceID= FactoryBindingID+"_IRmiIStochModel_"+nModels;

        // Create a new model instance
        IStochModelInstance newStochModel = stochModelFactory.getInstance(outputLevel);
        // Create a new server instance and set the new model for this instance
        Server obj = new Server();
        obj.setModel(newStochModel);

        IRmiIStochModel stub = (IRmiIStochModel) UnicastRemoteObject.exportObject(obj, 0);

        // Register this insntance such that it will not be deleted.
        allStochModels.add(stub);

       // Bind the remote object's stub in the registry
     Registry registry = LocateRegistry.getRegistry();
     registry.bind(instanceID, stub);

     System.err.println("Server has created model "+instanceID);
 } catch (Exception e) {
     System.err.println("Server exception when creating new model: " + e.toString());
     e.printStackTrace();
 }
    return instanceID;
}
 
Example 38
Project: mage   File: MageServer.java   View source code 5 votes vote down vote up
private void init() {
    try {
        rmiRegistry = LocateRegistry.createRegistry(port);

        logger.info("mage server is running");

    } catch (RemoteException e) {

        logger.error("init mage server error");
        throw new RuntimeException(e);
    }
}
 
Example 39
Project: openNaEF   File: RealDeviceAccessFactory.java   View source code 5 votes vote down vote up
private RemoteSnmpAccessService getRemoteSnmpAccessService()
        throws IOException, RemoteException {
    try {
        Registry registry = LocateRegistry.getRegistry(remoteSnmpAccessServer, remoteSnmpAccessServerPort);
        return (RemoteSnmpAccessService) registry.lookup(RemoteSnmpAccessService.SERVICE_NAME);
    } catch (NotBoundException e) {
        throw new IOException("remote service not found on " + remoteSnmpAccessServer, e);
    }
}
 
Example 40
Project: BaRMIe   File: IllegalRegistryBind.java   View source code 5 votes vote down vote up
/*******************
 * Check if the given endpoint can be attacked.
 * 
 * This check is performed by executing a dummy attack against the
 * endpoint and observing the resulting exception.
 * 
 * @param ep An enumerated RMI endpoint.
 * @return True if we can attack it.
 ******************/
public boolean canAttackEndpoint(RMIEndpoint ep) {
	RMIBindExploitProxy proxy = null;
	Registry reg;
	
	//Execute a dummy attack
	try {
		//Start a bind exploit proxy
		proxy = new RMIBindExploitProxy(InetAddress.getByName(ep.getEndpoint().getHost()), ep.getEndpoint().getPort(), this._options, this._dummyPayload);
		proxy.startProxy();
		
		//Get a proxied RMI registry reference
		reg = LocateRegistry.getRegistry(proxy.getServerListenAddress().getHostAddress(), proxy.getServerListenPort());
		
		//Bind a dummy object in an attempt to trigger the vulnerability
		reg.bind(this.generateRandomString(), new BaRMIeBindExploit());
	} catch(BaRMIeException | UnknownHostException | RemoteException | AlreadyBoundException ex) {
		//An up to date RMI registry will, by default, reject the dummy object
		if(ex instanceof ServerException && ex.getCause() != null && ex.getCause() instanceof UnmarshalException && ex.getCause().getCause() != null && ex.getCause().getCause() instanceof InvalidClassException) {
			//Check for "filter status: REJECTED"
			if(ex.getCause().getCause().toString().contains("filter status: REJECTED")) {
				//Test payload was filtered, likely this attack isn't possible
				return false;
			}
		}
	} finally {
		//Stop the proxy
		if(proxy != null) {
			proxy.stopProxy(true);
		}
	}
	
	//In all other cases we should be able to attack the registry
	return true;
}