// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.lang.reflect.Type;

import javax.xml.bind.annotation.XmlRootElement;

import com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;

public class Client {
    @XmlRootElement
    public static class Message {
        private String text;
        public Message() {
            this("");
        }
        public Message(String text) {
            this.text = text;
        }
        public String getText() {
            return text;
        }
        public void setText(String text) {
            this.text = text;
        }
    }
    private static String interact(String method, String urlstr, String typ, String body) {
        try {
            HttpURLConnection con = (HttpURLConnection)(new URL(urlstr)).openConnection();
            con.setRequestMethod(method);
            con.addRequestProperty("accept",  typ);
            if(body != null) {
                con.addRequestProperty("content-type", typ);
                con.setDoOutput(true);
                con.getOutputStream().write(body.getBytes());
            }
            StringBuilder sb = new StringBuilder();
            con.connect();
            if(con.getResponseCode() / 100 == 2) {
                InputStream is = con.getInputStream();
                byte[] b = new byte[1000];
                int n;
                while((n = is.read(b)) >= 0) {
                    sb.append(new String(b,0,n));
                }
                is.close();
            } else {
                System.out.printf("Error: %d %s\n", con.getResponseCode(), con.getResponseMessage());
            }
            con.disconnect();
            return sb.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void main(String[] args) {
        Gson gson = new Gson();
        String request1 = gson.toJson(new Message("Hi from Java!"));
        String response1 = interact("POST", "http://localhost:8001/msgs", "application/json", request1);
        String response2 = interact("GET", "http://localhost:8001/msgs", "application/json", null);
        Type t = new TypeToken<TreeMap<String,ArrayList<Message>>>(){}.getType();
        Map<String,List<Message>> msgs = gson.fromJson(response2, t);
        for(Message msg : msgs.get("message")) {
            System.out.println(msg.getText());
        }
    }
}
