// 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.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;

public class WebPerf extends Thread {
    public static final int N1 = 100;
    public static final int N2 = 500;
    public static final int N3 = 30;
    private static HttpConnectionManager cm = new MultiThreadedHttpConnectionManager();
    private int errs = 0;
    public void run() {
        HttpClient[] client = new HttpClient[N2];
        for(int j = 0; j < N2; j++) {
            client[j] = new HttpClient();
            client[j].setHttpConnectionManager(cm);
        }
        for(int i = 0; i < N3; i++) {
            for(int j = 0; j < N2; j++) {
                try {
                    GetMethod met = new GetMethod("http://localhost:8080/test/perfload.jsp");
                    client[j].executeMethod(met);
                    String resp = met.getResponseBodyAsString();
                    if(resp.indexOf("Du er") < 0) errs++;
                    met.releaseConnection();
                } catch (HttpException e) {
                    e.printStackTrace();
                    errs++;
                } catch (IOException e) {
                    e.printStackTrace();
                    errs++;
                }
            }
        }
    }
    public int getErrs() {
        return errs;
    }
    public static void main(String[] args) throws Exception {
        WebPerf[] t = new WebPerf[N1];
        for(int i = 0; i < N1; i++) {
            t[i] = new WebPerf();
        }
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < N1; i++) {
            t[i].start();
        }
        int toterrs = 0;
        for(int i = 0; i < N1; i++) {
            t[i].join();
            toterrs += t[i].getErrs();
        }
        long t2 = System.currentTimeMillis();
        System.out.println((N1 * N2) + " simulated users: " + ((N1 * N2 * N3) / ((t2 - t1) / 1000)) + " req/sec (" + (toterrs*100)/(N1*N2*N3) + "% errors)");
    }
}
