package jsonexample;

import java.util.HashMap;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import org.json.*;

/**
 * @author Vojtech Kovar, xkovar3@fi.muni.cz
 */

public class Main {
    
    public Main() {
    }
    
    public static void main(String[] args) {
        int qlist_size = 4;
        String data, url_string;
        String base_url = "http://localhost/auth/run.cgi/";
        String method = "view";
        String query_list[] = new String[qlist_size];
        Map attrs;
        JSONObject json_query;
        
        final String usr = "<username>";
        final String passwd = "<password>";
        
            // authentication issues
        Authenticator auth = new Authenticator() {
            protected PasswordAuthentication  getPasswordAuthentication () {
                return new PasswordAuthentication(usr, passwd.toCharArray());
            }
        };
        Authenticator.setDefault(auth);
        
        // specifying attributes
        attrs = new HashMap();
        attrs.put("corpname", "bnc2");
        attrs.put("pagesize", "1");
        attrs.put("format", "json");
        // query list can be loaded from a file, ...
        query_list[0] = "[lemma=\"test\"]";
        query_list[1] = "[lemma=\"drug\"][lemma=\"test\"]";
        query_list[2] = "[lemma=\"blood\"][lemma=\"test\"]";
        query_list[3] = "[lemma=\"test\"][lemma=\"result\"]";
        
        for (int i = 0; i < qlist_size; i++) {
            attrs.put("q", "q" + query_list[i]);
            json_query = new JSONObject(attrs);
            url_string = base_url + method + "?json=" + json_query.toString();
        
            try {
                    // connecting the SketchEngine Server
                URL url = new URL(url_string);
                InputStream stream = url.openStream();
                InputStreamReader isr = new InputStreamReader(stream);
                BufferedReader reader = new BufferedReader(isr);
            
                    // json data receiving
                data = reader.readLine(); // json data are on the first line
            
                    // now, in the 'data' variable, there is a json string
                    // that can be parsed for json syntax
                JSONObject json = new JSONObject(data);
                System.out.println(query_list[i] + "\t" + json.get("concsize").toString());
            } 
            catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    
}

