javatips.net counter

Java Examples for java.rmi.registry.LocateRegistry

The following java examples will help you to understand the usage of java.rmi.registry.LocateRegistry. These source code samples are taken from different open source projects.

Example 1
Project: jdk7u-jdk-master  File: CheckLeaseLeak.java View source code
public static void main(String[] args) {
    CheckLeaseLeak leakServer = null;
    int numLeft = 0;
    /*
         * we want DGC to collect leases *quickly*
         * decrease the lease check interval
         */
    TestLibrary.setInteger("sun.rmi.dgc.checkInterval", CHECK_INTERVAL);
    TestLibrary.setInteger("java.rmi.dgc.leaseValue", LEASE_VALUE);
    try {
        Registry registry = java.rmi.registry.LocateRegistry.createRegistry(TestLibrary.REGISTRY_PORT);
        leakServer = new CheckLeaseLeak();
        registry.rebind("/LeaseLeak", leakServer);
        /* create a bunch of clients in a *different* vm */
        for (int i = 0; i < ITERATIONS; i++) {
            System.err.println("Created client: " + i);
            JavaVM jvm = new JavaVM("LeaseLeakClient", " -Djava.security.policy=" + TestParams.defaultPolicy, "");
            jvm.start();
            if (jvm.getVM().waitFor() == 1) {
                TestLibrary.bomb("Client process failed");
            }
        }
        numLeft = getDGCLeaseTableSize();
        Thread.sleep(3000);
    } catch (Exception e) {
        TestLibrary.bomb("CheckLeaseLeak Error: ", e);
    } finally {
        if (leakServer != null) {
            TestLibrary.unexport(leakServer);
            leakServer = null;
        }
    }
    /* numLeft should be 2 - if 11 there is a problem. */
    if (numLeft > 2) {
        TestLibrary.bomb("Too many objects in DGCImpl.leaseTable: " + numLeft);
    } else {
        System.err.println("Check leaseInfo leak passed with " + numLeft + " object(s) in the leaseTable");
    }
}
Example 2
Project: openjdk8-jdk-master  File: MapNullValuesTest.java View source code
public static void main(String[] args) throws Exception {
    int errorCount = 0;
    MapNullValuesTest test = new MapNullValuesTest();
    // Create an RMI registry
    //
    echo("");
    echo(dashedMessage("Start RMI registry"));
    Registry reg = null;
    port = 7500;
    while (port++ < 7550) {
        try {
            reg = LocateRegistry.createRegistry(port);
            echo("\nRMI registry running on port " + port);
            break;
        } catch (RemoteException e) {
            echo("\nFailed to create RMI registry on port " + port);
            e.printStackTrace(System.out);
        }
    }
    if (reg == null) {
        System.exit(1);
    }
    // Run tests
    //
    errorCount += test.mapToHashtableTests();
    errorCount += test.jmxConnectorServerFactoryTests();
    errorCount += test.jmxConnectorFactoryTests();
    errorCount += test.nullKeyFactoryTests();
    if (errorCount == 0) {
        echo("\nNull values for key/value pairs in Map Tests PASSED!");
    } else {
        echo("\nNull values for key/value pairs in Map Tests FAILED!");
        System.exit(1);
    }
}
Example 3
Project: btpka3.github.com-master  File: MyServer.java View source code
public static void main(String[] args) throws Exception {
    // start RMI server
    // or CMD/> rmiregistry 9999
    LocateRegistry.createRegistry(9999);
    // setup MBeanServer
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    MyServer s = new MyServer();
    ObjectName objName = new ObjectName("MyServer:type=Hello");
    mbs.registerMBean(s, objName);
    // start JMXConnectorServer
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/jmxrmi");
    JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);
    cs.start();
    System.out.println("MBeanServer start");
}
Example 4
Project: interface_sdk-master  File: ModuleRMIHelper.java View source code
@Override
protected ModuleManagerRemote getManager() throws ModuleManagerCommunicationException {
    Registry registry;
    try {
        registry = LocateRegistry.getRegistry("localhost", ModuleManagerRunner.RMI_REGISTRY_PORT);
        ModuleManagerRemote obj = (ModuleManagerRemote) registry.lookup(ModuleManagerRunner.RMI_SERVER_NAME);
        log.debug("Got an instance of ModuleManager via RMI?");
        return obj;
    } catch (RemoteException e) {
        throw new ModuleManagerCommunicationException();
    } catch (NotBoundException e) {
        throw new ModuleManagerCommunicationException();
    }
}
Example 5
Project: eclipselink.runtime-master  File: EntityManagerSetupImpl.java View source code
/**
     * Checks for partitioning properties.
     */
protected void updateRemote(Map m, ClassLoader loader) {
    String protocol = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.REMOTE_PROTOCOL, m, this.session);
    String serverName = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.REMOTE_SERVER_NAME, m, this.session);
    if (serverName == null) {
        // Configure as client.
        if (protocol != null) {
            RemoteConnection connection = null;
            if (protocol.equalsIgnoreCase(RemoteProtocol.RMI)) {
                String url = getConfigPropertyAsStringLogDebug(PersistenceUnitProperties.REMOTE_URL, m, this.session);
                if (url == null) {
                    throw EntityManagerSetupException.missingProperty(PersistenceUnitProperties.REMOTE_URL);
                }
                try {
                    connection = new RMIConnection(((RMIServerSessionManager) Naming.lookup(url)).createRemoteSessionController());
                } catch (Exception exception) {
                    throw ValidationException.invalidValueForProperty(url, PersistenceUnitProperties.REMOTE_URL, exception);
                }
            } else {
                Class cls = findClassForProperty(protocol, PersistenceUnitProperties.REMOTE_PROTOCOL, loader);
                try {
                    Constructor constructor = cls.getConstructor();
                    connection = (RemoteConnection) constructor.newInstance();
                } catch (Exception exception) {
                    throw ValidationException.invalidValueForProperty(protocol, PersistenceUnitProperties.REMOTE_PROTOCOL, exception);
                }
            }
            RemoteSession remoteSession = new RemoteSession();
            remoteSession.setIsMetadataRemote(false);
            remoteSession.setProject(this.session.getProject());
            remoteSession.setProfiler(this.session.getProfiler());
            remoteSession.setSessionLog(this.session.getSessionLog());
            remoteSession.setEventManager(this.session.getEventManager());
            remoteSession.setQueries(this.session.getQueries());
            remoteSession.setProperties(this.session.getProperties());
            remoteSession.setName(this.session.getName());
            remoteSession.setRemoteConnection(connection);
            this.session = remoteSession;
        }
    } else {
        // Configure as server.
        if (protocol.equalsIgnoreCase(RemoteProtocol.RMI)) {
            RMIServerSessionManager manager = null;
            // Make sure RMI registry is started.
            try {
                java.rmi.registry.LocateRegistry.createRegistry(1099);
            } catch (Exception exception) {
                System.out.println("Security violation " + exception.toString());
            }
            // Create local instance of the factory
            try {
                manager = new RMIServerSessionManagerDispatcher(session);
            } catch (RemoteException exception) {
                throw ValidationException.invalidValueForProperty(serverName, PersistenceUnitProperties.REMOTE_SERVER_NAME, exception);
            }
            // Put the local instance into the Registry
            try {
                Naming.unbind(serverName);
            } catch (Exception exception) {
            }
            // Put the local instance into the Registry
            try {
                Naming.rebind(serverName, manager);
            } catch (Exception exception) {
                throw ValidationException.invalidValueForProperty(serverName, PersistenceUnitProperties.REMOTE_SERVER_NAME, exception);
            }
        }
    }
}
Example 6
Project: org.ops4j.pax.swissbox-master  File: RemoteFrameworkImpl.java View source code
private void export() throws RemoteException, AccessException {
    String port = System.getProperty(RMI_PORT_KEY, "1099");
    name = System.getProperty(RMI_NAME_KEY);
    timeout = Long.parseLong(System.getProperty(TIMEOUT_KEY, "10000"));
    registry = LocateRegistry.getRegistry(Integer.parseInt(port));
    URL location1 = getClass().getProtectionDomain().getCodeSource().getLocation();
    URL location2 = Bundle.class.getProtectionDomain().getCodeSource().getLocation();
    URL location3 = ServiceLookup.class.getProtectionDomain().getCodeSource().getLocation();
    System.setProperty("java.rmi.server.codebase", location1 + " " + location2 + " " + location3);
    Remote remote = UnicastRemoteObject.exportObject(this, 0);
    registry.rebind(name, remote);
}
Example 7
Project: spring-framework-2.5.x-master  File: RmiServiceExporter.java View source code
/**
	 * 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 explictly 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 8
Project: openjdk-master  File: JstatdTest.java View source code
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 9
Project: JBossAS51-master  File: JMXConnectorServerService.java View source code
public void start() throws Exception {
    // the address to expose in the urls
    String host = System.getProperty("java.rmi.server.hostname");
    // check to see if registry already created
    rmiRegistry = LocateRegistry.getRegistry(host, registryPort);
    if (rmiRegistry != null) {
        try {
            rmiRegistry.list();
        } catch (RemoteException e) {
            log.debug("No registry running at host '" + host + "', port '" + registryPort + "'.  Will create one.");
            rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
        }
    } else {
        rmiRegistry = LocateRegistry.createRegistry(registryPort, null, new DefaultSocketFactory(bindAddress));
    }
    String serviceURL = "service:jmx:rmi://" + host + "/jndi/rmi://" + host + ":" + registryPort + jndiPath;
    JMXServiceURL url = new JMXServiceURL(serviceURL);
    // create new connector server and start it
    final Map<String, Object> environment = new HashMap<String, Object>();
    final DefaultSocketFactory clientSocketFactory = new DefaultSocketFactory();
    clientSocketFactory.setBindAddress(bindAddress.getHostAddress());
    environment.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, clientSocketFactory);
    connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, environment, mbeanServer);
    connectorServer.start();
    log.info("JMX Connector server: " + serviceURL);
}
Example 10
Project: wso2-synapse-master  File: RMIRegistryController.java View source code
/**
     * Creates a RMI local registry with given port
     *
     * @param port The port of the RMI registry to be created
     */
public void createLocalRegistry(int port) {
    try {
        String key = toKey(port);
        synchronized (registriesCache) {
            if (registriesCache.containsKey(key)) {
                if (log.isDebugEnabled()) {
                    log.debug("There is an RMI registry bound to given port :" + port);
                }
                return;
            }
            Registry locateRegistry = LocateRegistry.createRegistry(port);
            if (locateRegistry == null) {
                handleException("Unable to create a RMI registry with port : " + port);
            }
            registriesCache.put(key, locateRegistry);
        }
    } catch (RemoteException e) {
        String msg = "Couldn't create a local registry(RMI) : port " + port + " already in use.";
        handleException(msg, e);
    }
}
Example 11
Project: classlib6-master  File: Main.java View source code
private void run(String[] args) {
    Parser p = initializeParser();
    p.parse(args, new FileArgumentCallback() {

        public void notifyFile(String portArgument) {
            port = Integer.parseInt(portArgument);
        }
    });
    if (!stop) {
        Map table;
        if (!persistent)
            table = new Hashtable();
        else {
            // Start the system.
            File dataDirectory = new File(directory);
            if (!dataDirectory.exists())
                dataDirectory.mkdirs();
            table = PersistentHashTable.createInstance(new File(dataDirectory, "rmiregistry.data"), cold);
        }
        RegistryImpl system = new RegistryImpl(table);
        // possible when going into the gnu.java.rmi
        try {
            UnicastServerRef sref = new UnicastServerRef(new ObjID(ObjID.REGISTRY_ID), port, ssf);
            sref.exportObject(system);
            System.out.println("The RMI naming service is listening at " + port);
        } catch (Exception ex) {
            System.out.println("Failed to start RMI naming service at " + port);
        }
    } else {
        // Stop the naming service.
        try {
            Registry r = LocateRegistry.getRegistry(port);
            // Search for this specific line will command to stop the registry.
            // Our service returns null, but any other service will thrown
            // NotBoundException.
            r.unbind(STOP);
        } catch (RemoteException e) {
            System.out.println("Failed to stop RMI naming service at " + port);
        } catch (NotBoundException e) {
            System.out.println("The naming service at port " + port + " is not a " + Main.class.getName());
        }
    }
}
Example 12
Project: Payara-master  File: RMIConnectorStarter.java View source code
/**
     * Delegate method to start the registry based on security is enabled or not.
     *
     * @param port
     * @return Registry
     */
private Registry _startRegistry(final int port) {
    // Ensure cryptographically strong random number generator used
    // to choose the object number - see java.rmi.server.ObjID
    System.setProperty("java.rmi.server.randomIDs", "true");
    try {
        if (isSecurityEnabled()) {
            return LocateRegistry.createRegistry(port, sslCsf, sslServerSocketFactory);
        } else {
            return LocateRegistry.createRegistry(port, null, mServerSocketFactory);
        }
    } catch (final Exception e) {
        throw new RuntimeException("Port " + port + " is not available for the internal rmi registry. " + "This means that a call was made with the same port, without closing earlier " + "registry instance. This has to do with the system jmx connector configuration " + "in admin-service element of the configuration associated with this instance");
    }
}
Example 13
Project: resin-master  File: RmiRegistry.java View source code
/**
   * Start the RMI registry in the local JVM, if it has not been started
   * already.
   */
private void startRegistry() throws ResourceAdapterInternalException {
    /**
     * Some tricks are required here, the RMI Registry needs to be
     * started from the system classloader.
     */
    Thread thread = Thread.currentThread();
    ClassLoader oldLoader = thread.getContextClassLoader();
    try {
        thread.setContextClassLoader(ClassLoader.getSystemClassLoader());
        try {
            Registry reg = LocateRegistry.getRegistry(_port);
            // Verify it's alive and well
            reg.list();
            if (log.isLoggable(Level.CONFIG))
                log.config(L.l("found RMI Registry on port `{0}'", _port));
        } catch (Exception e) {
            if (log.isLoggable(Level.CONFIG))
                log.config(L.l("creating RMI Registry on port `{0}'", _port));
            LocateRegistry.createRegistry(_port);
        }
    } catch (Exception ex) {
        throw new ResourceAdapterInternalException(ex);
    } finally {
        thread.setContextClassLoader(oldLoader);
    }
}
Example 14
Project: lucene-solr-master  File: TestJmxMonitoredMap.java View source code
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    String oldHost = System.getProperty("java.rmi.server.hostname");
    try {
        // this stupid sysprop thing is needed, because remote stubs use an
        // arbitrary local ip to connect
        // See: http://weblogs.java.net/blog/emcmanus/archive/2006/12/multihomed_comp.html
        System.setProperty("java.rmi.server.hostname", "127.0.0.1");
        class LocalhostRMIServerSocketFactory implements RMIServerSocketFactory {

            ServerSocket socket;

            @Override
            public ServerSocket createServerSocket(int port) throws IOException {
                return socket = new ServerSocket(port);
            }
        }
        ;
        LocalhostRMIServerSocketFactory factory = new LocalhostRMIServerSocketFactory();
        LocateRegistry.createRegistry(0, null, factory);
        port = factory.socket.getLocalPort();
        log.info("Using port: " + port);
        String url = "service:jmx:rmi:///jndi/rmi://127.0.0.1:" + port + "/solrjmx";
        JmxConfiguration config = new JmxConfiguration(true, null, url, null);
        monitoredMap = new JmxMonitoredMap<>("", "", config);
        JMXServiceURL u = new JMXServiceURL(url);
        connector = JMXConnectorFactory.connect(u);
        mbeanServer = connector.getMBeanServerConnection();
    } finally {
        if (oldHost == null) {
            System.clearProperty("java.rmi.server.hostname");
        } else {
            System.setProperty("java.rmi.server.hostname", oldHost);
        }
    }
}
Example 15
Project: Rio-master  File: CybernodeImpl.java View source code
/**
     * Override ServiceBeanAdapter createProxy to return a Cybernode Proxy
     */
@Override
protected Object createProxy() {
    Cybernode cybernode = (Cybernode) getExportedProxy();
    if (cybernode == null) {
        logger.error("Could not get the exported proxy for the Cybernode, " + "returning null. The Cybernode will not be able to " + "accept remote inbound communications");
        return null;
    }
    Object proxy = CybernodeProxy.getInstance(cybernode, getUuid());
    logger.trace("Proxy created {}", proxy);
    /* Get the registry port */
    String sPort = System.getProperty(Constants.REGISTRY_PORT, "0");
    registryPort = Integer.parseInt(sPort);
    String name = context.getServiceBeanConfig().getName();
    if (registryPort != 0) {
        try {
            String address = HostUtil.getHostAddressFromProperty(Constants.RMI_HOST_ADDRESS);
            Registry registry = LocateRegistry.getRegistry(address, registryPort);
            try {
                registry.bind(name, (Remote) proxy);
                logger.debug("Bound to RMI Registry on port={}", registryPort);
            } catch (AlreadyBoundException e) {
            }
        } catch (AccessException e) {
            logger.warn("Binding " + name + " to RMI Registry", e);
        } catch (RemoteException e) {
            logger.warn("Binding " + name + " to RMI Registry", e);
        } catch (java.net.UnknownHostException e) {
            logger.warn("Unknown host address locating RMI Registry", e);
        }
    } else {
        logger.debug("RMI Registry property not set, unable to bind {}", name);
    }
    /*
         * Set the MarshalledInstance into the ServiceBeanManager
         */
    try {
        MarshalledInstance mi = new MarshalledInstance(proxy);
        ((DefaultServiceBeanManager) context.getServiceBeanManager()).setMarshalledInstance(mi);
    } catch (IOException e) {
        logger.warn("Unable to create MarshalledInstance for Cybernode proxy, non-fatal error, continuing ...", e);
    }
    return (proxy);
}
Example 16
Project: google-web-toolkit-svnmirror-master  File: BrowserManagerServerLauncher.java View source code
/**
   * This method should be invoked after argument parsing completes.
   */
public void run() {
    Registry rmiRegistry = null;
    try {
        // Create an RMI registry so we don't need an external process.
        // Uses the default RMI port if no port is specified with the -port arg.
        rmiRegistry = LocateRegistry.createRegistry(portArg);
    } catch (RemoteException e) {
        logger.log(Level.SEVERE, "Couldn't bind RMI Registry to port " + portArg, e);
        System.exit(1);
    }
    logger.log(Level.ALL, "RMI registry ready on port " + portArg + ".");
    // Startup each of the registered servers on this machine.
    for (BMSEntry entry : bmsList) {
        BrowserManagerServer server = null;
        try {
            server = new BrowserManagerServer(entry.browserPath, serializeArg);
        } catch (RemoteException re) {
            logger.log(Level.SEVERE, entry.registrationKey + ": Error starting new BrowserManagerServer.", re);
            System.exit(2);
        }
        try {
            rmiRegistry.rebind(entry.registrationKey, server);
        } catch (RemoteException re) {
            logger.log(Level.SEVERE, entry.registrationKey + " server: " + server + " port: " + portArg + " Error on rebind to " + entry.registrationKey, re);
            System.exit(3);
        }
        logger.log(Level.INFO, "Server: " + entry.registrationKey + " started and awaiting connections.");
    }
    logger.log(Level.INFO, "All servers started.");
}
Example 17
Project: sqlpower-library-master  File: DBConnectionSpecServerImpl.java View source code
/**
	 * Basic server main.  This class is executable with a command line
	 * something like this:
	 * 
	 * java -Djava.rmi.server.codebase="base.of.classpath" \
	 *      -cp ".;../../../../common/lib/xerces.jar" \
	 *      -Djava.security.policy=rmi.policy \
	 *      -DdatabasesFile=../databases.xml \
	 *      ca.sqlpower.sql.DBConnectionSpecServerImpl
	 */
public static void main(String args[]) throws RemoteException {
    // Create and install a security manager
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new RMISecurityManager());
    }
    DBConnectionSpecServerImpl obj = new DBConnectionSpecServerImpl();
    obj.xmlFileName = System.getProperty("databasesFile");
    if (obj.xmlFileName == null) {
        System.out.println("no databases file specified.  Please add -DdatabaseFile=filename to the command line.");
    } else {
        try {
            java.rmi.registry.LocateRegistry.createRegistry(1099);
            Naming.rebind("///DBConnectionSpecServer", obj);
            System.out.println("DBConnectionSpecServer bound in registry");
        } catch (Exception e) {
            System.out.println("DBConnectionSpecImpl err: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
Example 18
Project: oliot-fc-master  File: AdaptorManagement.java View source code
/**
	 * adds a new adaptor to the adaptor list.
	 * @param adaptorName the name of the new adaptor.
	 * @param address if you are using a client adaptor you have to provide the address of the server stub.
	 * @throws LLRPRuntimeException when either name already exists or when there occurs an error in adaptor creation.
	 * @throws RemoteException when there is an error during transmition.
	 * @throws NotBoundException when there is no registry available.
	 */
public synchronized String define(String adaptorName, String address) throws LLRPRuntimeException, RemoteException, NotBoundException {
    checkStatus();
    synchronized (workers) {
        synchronized (localWorkers) {
            synchronized (remoteWorkers) {
                Adaptor adaptor = null;
                if (address != null) {
                    // try to get the instance from the remote 
                    // adaptor.
                    int registryPort = 5001;
                    Registry registry = LocateRegistry.getRegistry(address, Constants.registryPort);
                    //Registry registry = LocateRegistry.getRegistry(address, registryPort);
                    adaptor = (Adaptor) registry.lookup(Constants.adaptorNameInRegistry);
                    // server adaptor always keeps its name. therefore 
                    // we rename the adaptor
                    log.debug(String.format("adaptor is remote. therefore renaming %s to %s.", adaptorName, adaptor.getAdaptorName()));
                    adaptorName = adaptor.getAdaptorName();
                }
                // tests whether there exists already a adaptor of this name
                if (containsAdaptor(adaptorName)) {
                    log.error("Adaptor '" + adaptorName + "' already exists!");
                    LLRPDuplicateNameException e = new LLRPDuplicateNameException(adaptorName, "Adaptor '" + adaptorName + "' already exists!");
                    postException(e, LLRPExceptionHandlerTypeMap.EXCEPTION_ADAPTOR_ALREADY_EXISTS, adaptorName, "");
                    throw e;
                }
                AdaptorCallback cb = null;
                AdaptorWorker worker = null;
                if (address == null) {
                    // determine the special hopefully unique server adaptor name
                    if (export) {
                        // change the name of the adaptor to the ip of the current machine.
                        String HOST_NAME_PREFIX = "server adaptor - ";
                        String HOST_ADDRESS = String.format("unknown ip %d", System.currentTimeMillis());
                        try {
                            java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
                            HOST_ADDRESS = localMachine.getHostAddress();
                        } catch (java.net.UnknownHostException uhe) {
                            log.debug("hmmm, what happened? " + "This should not occur here :-).");
                        }
                        adaptorName = HOST_NAME_PREFIX + HOST_ADDRESS;
                    }
                    // local case
                    adaptor = new AdaptorImpl(adaptorName);
                    ((AdaptorImpl) adaptor).setAdaptorManagement(this);
                    cb = new AdaptorCallback(false);
                    worker = new AdaptorWorker(cb, adaptor);
                    worker.setAdaptorIpAddress(null);
                    localWorkers.put(adaptorName, worker);
                    log.debug("created a new local adaptor '" + adaptorName + "'.");
                } else {
                    // remote case
                    cb = new AdaptorCallback(true);
                    worker = new AdaptorWorker(cb, adaptor);
                    // store the ip address of the remote adaptor.
                    worker.setAdaptorIpAddress(address);
                    remoteWorkers.put(adaptorName, worker);
                    log.debug("created a new client adaptor '" + adaptorName + "' with url '" + address + "'.");
                }
                // register the callback.
                try {
                    adaptor.registerForAsynchronous(cb);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                // register the thread.
                workers.put(adaptorName, worker);
                // start the thread
                new Thread(worker).start();
                // the adaptor HAS to be local!
                if ((export) && (address == null)) {
                    // now export the adaptor
                    // create the new registry
                    log.debug("create a registry for the export of the local adaptor.");
                    LocateRegistry.createRegistry(Constants.registryPort);
                    Registry registry = LocateRegistry.getRegistry(Constants.registryPort);
                    //int registryPort = 5001;
                    //LocateRegistry.createRegistry(registryPort);
                    //Registry registry = LocateRegistry.getRegistry(registryPort);
                    log.debug("bind the adaptor to the registry");
                    try {
                        registry.bind(Constants.adaptorNameInRegistry, adaptor);
                    } catch (AlreadyBoundException e) {
                        log.error("THERE WAS A SEVERE ERROR THAT SHOULD NEVER OCCUR!!!");
                        e.printStackTrace();
                    }
                }
            }
        }
        commit();
    }
    return adaptorName;
}
Example 19
Project: gluu-opendj-master  File: RmiConnector.java View source code
/**
   * Starts the common RMI registry. In order to provide RMI stub for
   * remote client, the JMX RMI connector should be register into an RMI
   * registry. Each server will maintain its own private one.
   *
   * @throws Exception
   *             if the registry cannot be started
   */
private void startCommonRegistry() throws Exception {
    int registryPort = jmxConnectionHandler.getListenPort();
    // create our local RMI registry if it does not exist already
    if (debugEnabled()) {
        TRACER.debugVerbose("start or reach an RMI registry on port %d", registryPort);
    }
    try {
        // TODO Not yet implemented: If the host has several interfaces
        if (registry == null) {
            rmiSsf = new OpendsRmiServerSocketFactory();
            registry = LocateRegistry.createRegistry(registryPort, null, rmiSsf);
        }
    } catch (RemoteException re) {
        if (debugEnabled()) {
            TRACER.debugWarning("cannot create the RMI registry -> already done ?");
        }
        try {
            Registry reg = LocateRegistry.getRegistry(registryPort);
            reg.list();
            registry = reg;
        } catch (Exception e) {
            if (debugEnabled()) {
                TRACER.debugError("exception thrown while pinging the RMI registry");
                TRACER.debugCaught(DebugLogLevel.ERROR, re);
            }
            throw re;
        }
        if (debugEnabled()) {
            TRACER.debugWarning("RMI was registry already started");
        }
    }
}
Example 20
Project: cids-server-master  File: DomainServerImpl.java View source code
/**
     * DOCUMENT ME!
     *
     * @param   args  DOCUMENT ME!
     *
     * @throws  Throwable              DOCUMENT ME!
     * @throws  ServerExitError        DOCUMENT ME!
     * @throws  IllegalStateException  DOCUMENT ME!
     */
public static void main(final String[] args) throws Throwable {
    // first of all register the default exception handler for all threads
    Thread.setDefaultUncaughtExceptionHandler(new DefaultServerExceptionHandler());
    ServerProperties properties = null;
    int rmiPort;
    if (args == null) {
        // NOI18N
        throw new ServerExitError("args == null no commandline parameter given (Configfile / port)");
    } else if (args.length < 1) {
        // NOI18N
        throw new ServerExitError("insufficient arguments given");
    }
    if (instance != null) {
        // NOI18N
        throw new IllegalStateException("an instance was already created");
    }
    try {
        try {
            properties = new ServerProperties(args[0]);
            rmiPort = new Integer(properties.getRMIRegistryPort()).intValue();
        } catch (MissingResourceException mre) {
            System.err.println("Info :: <LS> Key  rmiRegistryPort  in ConfigFile +" + args[0] + " is Missing!");
            System.err.println("Info :: <LS> Set Default to 1099");
            rmiPort = 1099;
        }
        try {
            initLog4J(properties);
        } catch (final Exception e) {
            System.err.println("WARN :: <LS> Could not init log4j_: " + e);
        }
        // NOI18N
        System.out.println("<LS> ConfigFile: " + args[0]);
        // abfragen, ob schon eine  RMI Registry exitiert.
        try {
            LocateRegistry.getRegistry(rmiPort);
        // wenn keine Registry vorhanden, wird an dieser Stelle Exception ausgeloest
        } catch (Exception e) {
            LocateRegistry.createRegistry(rmiPort);
        }
        if (properties.getStartMode().equalsIgnoreCase("simple")) {
            // NOI18N
            Sirius.server.registry.Registry.getServerInstance(rmiPort);
            StartProxy.getInstance(args[0]);
        }
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new ServerSecurityManager());
        }
        instance = new DomainServerImpl(new ServerProperties(args[0]));
        // NOI18N
        System.out.println("Info :: <LS>  !!!LocalSERVER started!!!!");
    } catch (Exception e) {
        System.err.println("Error while starting domainserver :: " + e.getMessage());
        if (instance != null) {
            instance.shutdown();
        }
        throw new ServerExitError(e);
    }
}