// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MultiThreadedClient extends Thread {
    private static boolean dohttp() {
        try {
            URL url = new URL("http://localhost:8080/test/TestServlet");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.connect();
            if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String line = br.readLine();
                br.close();
                con.disconnect();
                if(line.equals("OK")) {
                    return true;
                } else {
                    return false;
                }
            } else {
                System.out.println(con.getResponseCode() + " " + con.getResponseMessage());
                return false;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    private final static int NREQ = 100;
    public void run() {
        for(int i = 0; i < NREQ; i++) {
            if(!dohttp()) {
                System.out.println("Ooops");
                System.exit(0);
            }
        }
    }
    private static void test(int nthr) throws InterruptedException {
          Client[] t = new Client[nthr];
          for(int i = 0; i < nthr; i++) {
             t[i] = new Client();
          }
          long t1 = System.currentTimeMillis();
          for(int i = 0; i < nthr; i++) {
             t[i].start();
          }
          for(int i = 0; i < nthr; i++) {
             t[i].join();
          }
          long t2 = System.currentTimeMillis();
          System.out.println(nthr + " : " + (nthr*NREQ*60000L)/(t2 - t1) + " TPM");
    }
    public static void main(String[] args) throws Exception {
        test(10);
        test(50);
        test(100);
        test(500);
        test(1000);
    }
}
