package com.orbekk.same;

import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.jsonrpc4j.JsonRpcServer;
import com.orbekk.net.HttpUtil;

public class ClientApp {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private Server server;
    private static final int timeout = 1000;
    
    public void run(int port, String networkName, String masterUrl) {
        logger.info("Starting client with port:{}, networkName:{}, masterUrl:{}",
                new Object[]{port, networkName, masterUrl});
        ConnectionManagerImpl connections = new ConnectionManagerImpl(timeout,
                timeout);
        State state = new State(networkName);
        Broadcaster broadcaster =
                BroadcasterImpl.getDefaultBroadcastRunner();
        MasterServiceImpl master = new MasterServiceImpl(state, connections,
                broadcaster);
        ClientServiceImpl client = new ClientServiceImpl(state, connections);
        
        JsonRpcServer jsonServer = new JsonRpcServer(client, ClientService.class);
        server = new Server(port);
        RpcHandler rpcHandler = new RpcHandler(jsonServer, client);
        server.setHandler(rpcHandler);
        
        try {
            server.start();
        } catch (Exception e) {
            logger.error("Could not start jetty server: {}", e);
        }
        
        while (client.getUrl() == null) {
            HttpUtil.sendHttpRequest(masterUrl + "ping?port=" + port);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                // Ignore interrupt in wait loop.
            }
        }
        
        client.joinNetwork(masterUrl + "MasterService.json");
        
        try {
            server.join();
        } catch (InterruptedException e) {
            logger.info("Received exception. Exiting. {}", e);
        }
    }
    
    public static void main(String[] args) {
        if (args.length < 3) {
            System.err.println("Usage: port networkName masterUrl");
            System.exit(1);
        }
        int port = Integer.parseInt(args[0]);
        String networkName = args[1];
        String masterUrl = args[2];
        (new ClientApp()).run(port, networkName, masterUrl);
    }
}

@@ -379,16 +379,31 @@
 lic 
-void run
+ClientService getClient
 (int
@@ -428,16 +428,28 @@
 orkName,
+%0A           
  String 
@@ -1794,33 +1794,189 @@
 json%22);%0A        
+return client;%0A    %7D%0A    %0A    public void run(int port, String networkName,%0A            String masterUrl) %7B%0A        getClient(port, networkName, masterUrl);
 %0A
-
         try %7B%0A  
@@ -2066,45 +2066,26 @@
 ger.
-info(%22Received exception. Exiting. %7B%7D
+warn(%22Interrupted.
 %22, e
@@ -2468,20 +2468,29 @@
 masterUrl);%0A
+        %0A
     %7D%0A%7D%0A

Refactor client.