import java.net.*;
import java.io.*;
import java.util.*;

/** 
 *   PlaceEngine API Sample    
 *   2006.11.19
 *   @author Jun Rekimoto
 */
public class PeTest {
    public static final String appk = "S7Rk0Bm3DXEG11uCRG2LHjCjNMwF55iE8BE7fc9Z3.dZXgOXZL8Q5rQQn7TUgY13yVDtIAKdZi3cAhoQFT4sUmdveq9k0TOaUfBR8-QtDXMdskouu4CZnm6.m2528z5U-KIy5LRxvnIUjoE3MvvRr1BMg86yFxWqI6GHNJU.Wysqf8YH78BUHJ8s5WQl6lYvMWj6cl2srvvNN5rc3btE21lJpgZR4Tu2FWW.DOQ7IzNy5o7mO3fr-kLbKEMy49Q.eVHRZQCpqQ4z5aLWyFdJLuyYu1OVqza.PIrUvtQU6ql-fgQ5wNaDYRGl5N8agB-pRgyWvCxJC.rJWmj1LZ67kQ__,amF2YQ__,UGxhY2VFbmdpbmUgVGVzdA__";

    public static String getURL(String urlstr) throws MalformedURLException, ProtocolException, IOException {
	URL url = new URL(urlstr);
	HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
	urlc.connect();
	BufferedReader reader = new BufferedReader(new InputStreamReader(urlc.getInputStream(), "UTF-8"));
	String s = "";
	for (String line = null; (line = reader.readLine()) != null; ) {
	    s += line;
	}
	reader.close();
	urlc.disconnect();
	return s;
    }

    public static void printInfo(String s) {
	s = s.substring(1,s.length()-1);
	String param[] = s.split(",");
	String param2[] = s.split("\\{");

	if (param.length >= 4 && param2.length >= 2) {
	    System.out.println("Lat\t" + param[1]);
	    System.out.println("Lon\t" + param[0]);

	    String info[] = param2[1].substring(0, param2[1].length()-1).split(",");
	    for (int i = 0; i < info.length; i++) {
		String tk[] = info[i].split(":");
		String name = tk[0].substring(1,tk[0].length()-1);
		String value = tk[1];
		System.out.println(name + "\t" + value);
	    }
	}
    }

    public static void main(String[] argv) throws MalformedURLException, ProtocolException, IOException {
	System.setProperty("http.proxyHost", "proxy.csl.sony.co.jp");
	System.setProperty("http.proxyPort", "8080");
	System.setProperty("http.nonProxyHosts", "localhost");

	long t = System.currentTimeMillis() / 1000;

        String req = "http://localhost:5448/rtagjs?t=" + t + "&appk=" + appk;
	System.out.println("-->PlaceEngineClient\n" + req + "\n");
	String res = getURL(req);
	System.out.println("PlaceEngineClient-->\n" + res + "\n");

	String v[] = res.substring(9, res.length()-1).split(", *");
	String rtag = v[0].substring(1, v[0].length()-1);
	int numap = Integer.parseInt(v[1]);

	if (numap > 0) {
	    String req2 = "http://www.placeengine.com/api/loc?t=" + t + "&rtag=" + rtag + "&appk=" + appk + "&fmt=json";
	    System.out.println("-->PlaceEngineServer\n" + req2 + "\n");
	    String res2 = getURL(req2);

	    System.out.println("PlaceEngineServer-->\n" + res2 + "\n");

	    printInfo(res2);
	} else {
	    System.out.println("Can't get Wifi information");
	}
    }
}

