// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package rmi.client;

import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.stream.IntStream;

import rmi.common.Data;
import rmi.common.Test;

public class Client {
    private static final String REGISTRY = "localhost";
    private static final int REGISTRY_PORT = 1099; 
    private static final String NAME = "Test";
    private static void testFunctional() throws AccessException, RemoteException, NotBoundException {
        Test tst = (Test)LocateRegistry.getRegistry(REGISTRY, REGISTRY_PORT).lookup(NAME);
        int a = 123;
        int b = 456;
        int c = tst.add(a,  b);
        System.out.println(c);;
        String s = "ABC";
        String s2 = tst.dup(s);
        System.out.println(s2);
        Data d = new Data(123, "ABC");
        Data d2 = tst.process(d);
        System.out.printf("%d %s\n", d2.getIv(), d2.getSv());
    }
    private static void testInstantiation() throws AccessException, RemoteException, NotBoundException {
        Test tst1 = (Test)LocateRegistry.getRegistry(REGISTRY, REGISTRY_PORT).lookup(NAME);
        for(int i = 0; i < 2; i++) {
            int n = tst1.getCounter();
            System.out.println(n);
        }
        Test tst2 = (Test)LocateRegistry.getRegistry(REGISTRY, REGISTRY_PORT).lookup(NAME);
        for(int i = 0; i < 2; i++) {
            int n = tst2.getCounter();
            System.out.println(n);
        }
    }
    private static final int REP = 100000;
    private static void testPerformance() throws AccessException, RemoteException, NotBoundException {
        Test tst = (Test)LocateRegistry.getRegistry(REGISTRY, REGISTRY_PORT).lookup(NAME);
        long t1 = System.currentTimeMillis();
        IntStream.range(0, REP).parallel().forEach(i -> { try { tst.noop(); } catch(RemoteException re) { } });
        long t2 = System.currentTimeMillis();
        System.out.printf("%d requests per second\n", REP * 1000 / (t2 - t1));
    }
    public static void main(String[] args) throws AccessException, RemoteException, NotBoundException {
        testFunctional();
        testInstantiation();
        testPerformance();
    }
}
