Example usage for java.rmi.server UnicastRemoteObject exportObject

List of usage examples for java.rmi.server UnicastRemoteObject exportObject

Introduction

In this page you can find the example usage for java.rmi.server UnicastRemoteObject exportObject.

Prototype

private static Remote exportObject(Remote obj, UnicastServerRef sref) throws RemoteException 

Source Link

Document

Exports the specified object using the specified server ref.

Usage

From source file:engine.ComputeEngine.java

public static void main(String[] args) {
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManager());
    }/*from  w w  w . j  a  va2  s.co m*/
    try {
        String name = "Compute";
        Compute engine = new ComputeEngine();
        Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
        Registry registry = LocateRegistry.getRegistry();
        registry.rebind(name, stub);
        System.out.println("ComputeEngine bound");
    } catch (Exception e) {
        System.err.println("ComputeEngine exception:");
        e.printStackTrace();
    }
}

From source file:edu.cornell.med.icb.R.RConfigurationServer.java

public static void main(final String[] args) throws RemoteException {
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManager());
    }/*www  .j  a va2 s  . co m*/

    final String name = "RConfiguration";
    final RConfiguration engine = new RConfigurationServer();
    final RConfiguration stub = (RConfiguration) UnicastRemoteObject.exportObject(engine, 0);
    final Registry registry = LocateRegistry.getRegistry();
    System.out.println(ArrayUtils.toString(registry.list()));
    registry.rebind(name, stub);
    System.out.println("RConfiguration bound");
}

From source file:puma.central.pdp.CentralPUMAPDP.java

public static void main(String[] args) {
    // initialize log4j
    BasicConfigurator.configure();//from w  ww .ja va 2  s.  co m

    CommandLineParser parser = new BasicParser();
    Options options = new Options();
    options.addOption("ph", "policy-home", true,
            "The folder where to find the policy file given with the given policy id. "
                    + "For default operation, this folder should contain the central PUMA policy (called "
                    + CENTRAL_PUMA_POLICY_FILENAME + ")");
    options.addOption("pid", "policy-id", true,
            "The id of the policy to be evaluated on decision requests. Default value: " + GLOBAL_PUMA_POLICY_ID
                    + ")");
    options.addOption("s", "log-disabled", true, "Verbose mode (true/false)");
    String policyHome = "";
    String policyId = "";

    // read command line
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Simple PDP Test", options);
            return;
        }
        if (line.hasOption("policy-home")) {
            policyHome = line.getOptionValue("policy-home");
        } else {
            logger.log(Level.WARNING, "Incorrect arguments given.");
            return;
        }
        if (line.hasOption("log-disabled") && Boolean.parseBoolean(line.getOptionValue("log-disabled"))) {
            logger.log(Level.INFO, "Now switching to silent mode");
            LogManager.getLogManager().getLogger("").setLevel(Level.WARNING);
            //LogManager.getLogManager().reset();
        }
        if (line.hasOption("policy-id")) {
            policyId = line.getOptionValue("policy-id");
        } else {
            logger.log(Level.INFO, "Using default policy id: " + GLOBAL_PUMA_POLICY_ID);
            policyId = GLOBAL_PUMA_POLICY_ID;
        }
    } catch (ParseException e) {
        logger.log(Level.WARNING, "Incorrect arguments given.", e);
        return;
    }

    //
    // STARTUP THE RMI SERVER
    //      
    // if (System.getSecurityManager() == null) {
    // System.setSecurityManager(new SecurityManager());
    // }
    final CentralPUMAPDP pdp;
    try {
        pdp = new CentralPUMAPDP(policyHome, policyId);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "FAILED to set up the CentralPUMAPDP. Quitting.", e);
        return;
    }

    try {
        Registry registry;
        try {
            registry = LocateRegistry.createRegistry(RMI_REGISITRY_PORT);
            logger.info("Created new RMI registry");
        } catch (RemoteException e) {
            // MDC: I hope this means the registry already existed.
            registry = LocateRegistry.getRegistry(RMI_REGISITRY_PORT);
            logger.info("Reusing existing RMI registry");
        }
        CentralPUMAPDPRemote stub = (CentralPUMAPDPRemote) UnicastRemoteObject.exportObject(pdp, 0);
        registry.bind(CENTRAL_PUMA_PDP_RMI_NAME, stub);
        logger.info(
                "Central PUMA PDP up and running (available using RMI with name \"central-puma-pdp\" on RMI registry port "
                        + RMI_REGISITRY_PORT + ")");
        Thread.sleep(100); // MDC: vroeger eindigde de Thread om n of andere reden, dit lijkt te werken...
    } catch (Exception e) {
        logger.log(Level.SEVERE, "FAILED to set up PDP as RMI server", e);
    }

    //
    // STARTUP THE THRIFT PEP SERVER
    //
    //logger.log(Level.INFO, "Not setting up the Thrift server");

    // set up server
    //      PEPServer handler = new PEPServer(new CentralPUMAPEP(pdp));
    //      RemotePEPService.Processor<PEPServer> processor = new RemotePEPService.Processor<PEPServer>(handler);
    //      TServerTransport serverTransport;
    //      try {
    //         serverTransport = new TServerSocket(THRIFT_PEP_PORT);
    //      } catch (TTransportException e) {
    //         e.printStackTrace();
    //         return;
    //      }
    //      TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor));
    //      System.out.println("Setting up the Thrift PEP server on port " + THRIFT_PEP_PORT);
    //      server.serve();
    //
    // STARTUP THE THRIFT PEP SERVER
    //
    //logger.log(Level.INFO, "Not setting up the Thrift server");

    // set up server
    // do this in another thread not to block the main thread
    new Thread(new Runnable() {
        @Override
        public void run() {
            RemotePDPService.Processor<CentralPUMAPDP> pdpProcessor = new RemotePDPService.Processor<CentralPUMAPDP>(
                    pdp);
            TServerTransport pdpServerTransport;
            try {
                pdpServerTransport = new TServerSocket(THRIFT_PDP_PORT);
            } catch (TTransportException e) {
                e.printStackTrace();
                return;
            }
            TServer pdpServer = new TThreadPoolServer(
                    new TThreadPoolServer.Args(pdpServerTransport).processor(pdpProcessor));
            logger.info("Setting up the Thrift PDP server on port " + THRIFT_PDP_PORT);
            pdpServer.serve();
        }
    }).start();
}

From source file:engine.Pi.java

public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }//from w  ww  . j  av a2s  . c  o m
        try {
            String name = "Compute";
            Compute engine = new ComputeEngine();
            Compute stub = (Compute) UnicastRemoteObject.exportObject(engine, 0);
            Registry registry = LocateRegistry.getRegistry();
            registry.rebind(name, stub);
            System.out.println("ComputeEngine bound");
        } catch (Exception e) {
            System.err.println("ComputeEngine exception:");
            e.printStackTrace();
        }
    }

From source file:com.feedzai.fos.server.FosServer.java

/**
 * Binds the Manager and Scorer to the RMI Registry.
 * <p/> Also registers a shutdown hook for closing and removing the items from the registry.
 *
 * @throws RemoteException when binding was not possible.
 *///from   w ww  .ja v  a  2 s .  co  m
public void bind() throws RemoteException {
    registry = LocateRegistry.getRegistry(parameters.getRegistryPort());
    registry.rebind(IRemoteManager.class.getSimpleName(),
            UnicastRemoteObject.exportObject(remoteManager, parameters.getRegistryPort()));
    registry.rebind(RemoteScorer.class.getSimpleName(),
            UnicastRemoteObject.exportObject(remoteManager.getScorer(), parameters.getRegistryPort()));

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            unbind();
        }
    });
}

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.healthmarketscience.rmiio.RemoteIteratorTest.java

public static List<List<TestObject>> mainTest(final boolean sendEmptyList, final boolean doAbort,
        final boolean noDelayAbort, final List<Throwable> clientExceptions,
        final List<AccumulateRemoteStreamMonitor<?>> monitors) throws Exception {

    ObjectServer server = new ObjectServer();
    final RemoteObjectServer stub = (RemoteObjectServer) RemoteStreamServerTest
            .simulateRemote(UnicastRemoteObject.exportObject(server, 0));
    LOG.debug("Server ready");

    LOG.debug("Sleeping 3000 ms...");
    Thread.sleep(3000);//from ww w. j  a  va 2s. co m

    LOG.debug("Running tests");
    Thread clientThread = new Thread(new Runnable() {
        public void run() {
            clientExceptions.addAll(ObjectClient.main(stub, sendEmptyList, doAbort, noDelayAbort, monitors));
        }
    });
    clientThread.start();
    clientThread.join();

    LOG.debug("Unexporting server");
    UnicastRemoteObject.unexportObject(server, true);

    return server._recvdObjectLists;
}

From source file:com.okidokiteam.gouken.macosx.MacOSBoot.java

private void bind() {
    try {//from   w  w  w.  ja va2s.  c o  m
        // try to find port from property
        int port = getPort();
        LOG.debug("Starting up RMI registry on port [" + port + "]");
        m_registry = LocateRegistry.createRegistry(port);
        LOG.debug("Binding " + m_vault.getClass() + " to RMI registry");
        m_registry.bind(Vault.class.getName(), UnicastRemoteObject.exportObject(this, port));
        LOG.info("RMI registry started on port [" + port + "]");
    } catch (Exception e) {
        throw new RuntimeException("Cannot setup RMI registry", e);
    }
}

From source file:com.web.server.EJBDeployer.java

@Override
public void run() {
    EJBJarFileListener jarFileListener = new EJBJarFileListener(registry, this.servicesRegistryPort, jarEJBMap,
            jarMDBMap, jms, connectionFactory);
    DefaultFileMonitor fm = new DefaultFileMonitor(jarFileListener);
    FileObject listendir = null;// www. j av a2  s  .co m
    StandardFileSystemManager fsManager = new StandardFileSystemManager();
    String[] dirsToScan = scanDirectory.split(";");
    EJBContext ejbContext;
    try {
        File scanDirFile = new File(dirsToScan[0]);
        File[] scanJarFiles = scanDirFile.listFiles();
        System.out.println("SCANDIRECTORY=" + scanDirectory);
        if (scanJarFiles != null) {
            for (File scanJarFile : scanJarFiles) {
                if (scanJarFile.isFile() && scanJarFile.getAbsolutePath().endsWith(".jar")) {
                    URLClassLoader classLoader = new URLClassLoader(
                            new URL[] { new URL("file:///" + scanJarFile.getAbsolutePath()) },
                            Thread.currentThread().getContextClassLoader());
                    ConfigurationBuilder config = new ConfigurationBuilder();
                    config.addUrls(ClasspathHelper.forClassLoader(classLoader));
                    config.addClassLoader(classLoader);
                    org.reflections.Reflections reflections = new org.reflections.Reflections(config);
                    EJBContainer container = EJBContainer
                            .getInstance("file:///" + scanJarFile.getAbsolutePath(), config);
                    container.inject();
                    Set<Class<?>> cls = reflections.getTypesAnnotatedWith(Stateless.class);
                    Set<Class<?>> clsMessageDriven = reflections.getTypesAnnotatedWith(MessageDriven.class);
                    Object obj;
                    System.gc();
                    if (cls.size() > 0) {
                        ejbContext = new EJBContext();
                        ejbContext.setJarPath(scanJarFile.getAbsolutePath());
                        ejbContext.setJarDeployed(scanJarFile.getName());
                        for (Class<?> ejbInterface : cls) {
                            //BeanPool.getInstance().create(ejbInterface);
                            obj = BeanPool.getInstance().get(ejbInterface);
                            System.out.println(obj);
                            ProxyFactory factory = new ProxyFactory();
                            obj = UnicastRemoteObject.exportObject((Remote) factory.createWithBean(obj),
                                    servicesRegistryPort);
                            String remoteBinding = container.getRemoteBinding(ejbInterface);
                            System.out.println(remoteBinding + " for EJB" + obj);
                            if (remoteBinding != null) {
                                //registry.unbind(remoteBinding);
                                registry.rebind(remoteBinding, (Remote) obj);
                                ejbContext.put(remoteBinding, obj.getClass());
                            }
                            //registry.rebind("name", (Remote) obj);
                        }
                        jarEJBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                ejbContext);
                    }
                    System.out.println("Class Message Driven" + clsMessageDriven);
                    if (clsMessageDriven.size() > 0) {
                        System.out.println("Class Message Driven");
                        MDBContext mdbContext;
                        ConcurrentHashMap<String, MDBContext> mdbContexts;
                        if (jarMDBMap.get(scanJarFile.getAbsolutePath()) != null) {
                            mdbContexts = jarMDBMap.get(scanJarFile.getAbsolutePath());
                        } else {
                            mdbContexts = new ConcurrentHashMap<String, MDBContext>();
                        }
                        jarMDBMap.put("file:///" + scanJarFile.getAbsolutePath().replace("\\", "/"),
                                mdbContexts);
                        MDBContext mdbContextOld;
                        for (Class<?> mdbBean : clsMessageDriven) {
                            String classwithpackage = mdbBean.getName();
                            System.out.println("class package" + classwithpackage);
                            classwithpackage = classwithpackage.replace("/", ".");
                            System.out.println("classList:" + classwithpackage.replace("/", "."));
                            try {
                                if (!classwithpackage.contains("$")) {
                                    //System.out.println("executor class in ExecutorServicesConstruct"+executorServiceClass);
                                    //System.out.println();
                                    if (!mdbBean.isInterface()) {
                                        Annotation[] classServicesAnnot = mdbBean.getDeclaredAnnotations();
                                        if (classServicesAnnot != null) {
                                            for (int annotcount = 0; annotcount < classServicesAnnot.length; annotcount++) {
                                                if (classServicesAnnot[annotcount] instanceof MessageDriven) {
                                                    MessageDriven messageDrivenAnnot = (MessageDriven) classServicesAnnot[annotcount];
                                                    ActivationConfigProperty[] activationConfigProperties = messageDrivenAnnot
                                                            .activationConfig();
                                                    mdbContext = new MDBContext();
                                                    mdbContext.setMdbName(messageDrivenAnnot.name());
                                                    for (ActivationConfigProperty activationConfigProperty : activationConfigProperties) {
                                                        if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATIONTYPE)) {
                                                            mdbContext.setDestinationType(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.DESTINATION)) {
                                                            mdbContext.setDestination(
                                                                    activationConfigProperty.propertyValue());
                                                        } else if (activationConfigProperty.propertyName()
                                                                .equals(MDBContext.ACKNOWLEDGEMODE)) {
                                                            mdbContext.setAcknowledgeMode(
                                                                    activationConfigProperty.propertyValue());
                                                        }
                                                    }
                                                    if (mdbContext.getDestinationType()
                                                            .equals(Queue.class.getName())) {
                                                        mdbContextOld = null;
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld != null
                                                                    && mdbContext.getDestination().equals(
                                                                            mdbContextOld.getDestination())) {
                                                                throw new Exception(
                                                                        "Only one MDB can listen to destination:"
                                                                                + mdbContextOld
                                                                                        .getDestination());
                                                            }
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Queue queue = (Queue) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(queue);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Queue=" + queue);
                                                    } else if (mdbContext.getDestinationType()
                                                            .equals(Topic.class.getName())) {
                                                        if (mdbContexts.get(mdbContext.getMdbName()) != null) {
                                                            mdbContextOld = mdbContexts
                                                                    .get(mdbContext.getMdbName());
                                                            if (mdbContextOld.getConsumer() != null)
                                                                mdbContextOld.getConsumer()
                                                                        .setMessageListener(null);
                                                            if (mdbContextOld.getSession() != null)
                                                                mdbContextOld.getSession().close();
                                                            if (mdbContextOld.getConnection() != null)
                                                                mdbContextOld.getConnection().close();
                                                        }
                                                        mdbContexts.put(mdbContext.getMdbName(), mdbContext);
                                                        Topic topic = (Topic) jms
                                                                .lookup(mdbContext.getDestination());
                                                        Connection connection = connectionFactory
                                                                .createConnection("guest", "guest");
                                                        connection.start();
                                                        Session session;
                                                        if (mdbContext.getAcknowledgeMode() != null
                                                                && mdbContext.getAcknowledgeMode()
                                                                        .equals("Auto-Acknowledge")) {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        } else {
                                                            session = connection.createSession(false,
                                                                    Session.AUTO_ACKNOWLEDGE);
                                                        }
                                                        MessageConsumer consumer = session
                                                                .createConsumer(topic);
                                                        consumer.setMessageListener(
                                                                (MessageListener) mdbBean.newInstance());
                                                        mdbContext.setConnection(connection);
                                                        mdbContext.setSession(session);
                                                        mdbContext.setConsumer(consumer);
                                                        System.out.println("Topic=" + topic);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                    classLoader.close();
                    System.out.println(scanJarFile.getAbsolutePath() + " Deployed");
                }
            }
        }
        FileSystemOptions opts = new FileSystemOptions();
        FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
        fsManager.init();
        for (String dir : dirsToScan) {
            if (dir.startsWith("ftp://")) {
                listendir = fsManager.resolveFile(dir, opts);
            } else {
                listendir = fsManager.resolveFile(dir);
            }
            fm.addFile(listendir);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    fm.setRecursive(true);
    fm.setDelay(1000);
    fm.start();
}

From source file:com.app.server.EJBDeployer.java

public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) {
    this.serviceList = serviceList;
    this.serverConfig = serverConfig;
    this.mbeanServer = mbeanServer;
    this.serviceRegistryPort = Integer.parseInt(serverConfig.getServicesregistryport());
    //System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    //System.setProperty(Context.PROVIDER_URL, "rmi://localhost:"+serverConfig.getServicesregistryport());;
    try {/*  www. ja va  2s  . c  o m*/
        fsManager = new StandardFileSystemManager();
        System.setProperty("java.io.tmpdir", serverConfig.getCachedir());
        /*DefaultFileReplicator replicator = new DefaultFileReplicator(new File(cacheDir));
        //fsManager.setReplicator(new PrivilegedFileReplicator(replicator));
        fsManager.setTemporaryFileStore(replicator);*/
        fsManager.init();
        registry = LocateRegistry.createRegistry(Integer.parseInt(serverConfig.getServicesregistryport()));
        try {
            ic = new InitialContext();
            Context subctx = null;
            try {
                subctx = (Context) ic.lookup("java:");
            } catch (Exception ex) {
                log.error("Error in getting the java context", ex);
                //ex.printStackTrace();
            }
            if (subctx == null) {
                ic.createSubcontext("java:");
            }
            remoteBindingInterface = new RemoteBindingObject(ic);
            Object jndilookupobj = UnicastRemoteObject.exportObject((Remote) remoteBindingInterface,
                    this.serviceRegistryPort);
            //registry.rebind("RemoteBindingObject", (Remote) jndilookupobj);
        } catch (Exception ex) {
            log.error("error in registring to the remote binding object", ex);
            //e1.printStackTrace();
        }
        this.jms = new EmbeddedJMS();
        this.jms.start();

    } catch (Exception e) {
        log.error("error in initialization", e);
        // TODO Auto-generated catch block
        //e.printStackTrace();
    }
    connectionFactory = (ConnectionFactory) jms.lookup("java:/ConnectionFactory");
    log.info("initialized");
}