CounterApp.java Source code

Java tutorial

Introduction

Here is the source code for CounterApp.java

Source

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

public class CounterApp {
    String servletURL;

    String sessionCookie = null;

    public static void main(String args[]) {
        if (args.length == 0) {
            System.out.println("\nServlet URL must be specified");
            return;
        }

        try {
            CounterApp app = new CounterApp(args[0]);
            for (int i = 1; i <= 5; i++) {
                int count = app.getCount();
                System.out.println("Pass " + i + " count=" + count);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    public CounterApp(String url) {
        servletURL = url;
    }

    public int getCount() throws Exception {
        java.net.URL url = new java.net.URL(servletURL);
        java.net.URLConnection con = url.openConnection();
        if (sessionCookie != null) {
            con.setRequestProperty("cookie", sessionCookie);
        }
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setDoInput(true);
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(byteOut);
        out.flush();
        byte buf[] = byteOut.toByteArray();
        con.setRequestProperty("Content-type", "application/octet-stream");
        con.setRequestProperty("Content-length", "" + buf.length);
        DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
        dataOut.write(buf);
        dataOut.flush();
        dataOut.close();
        DataInputStream in = new DataInputStream(con.getInputStream());
        int count = in.readInt();
        in.close();
        if (sessionCookie == null) {
            String cookie = con.getHeaderField("set-cookie");
            if (cookie != null) {
                sessionCookie = parseCookie(cookie);
                System.out.println("Setting session ID=" + sessionCookie);
            }
        }

        return count;
    }

    public String parseCookie(String raw) {
        String c = raw;

        if (raw != null) {
            int endIndex = raw.indexOf(";");
            if (endIndex >= 0) {
                c = raw.substring(0, endIndex);
            }
        }

        return c;
    }
}