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 java.util.Set;
import org.json.*;

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

public class Main {
    
    public Main() {
    }
    
    public static void main(String[] args) {
        String data, url_string;
        String base_url = "http://localhost/auth/run.cgi/";
        String method = "wordlist";
        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);
        
        // creating query string
        attrs = new HashMap();
        attrs.put("corpname", "bnc");
        attrs.put("wlattr", "word");
        attrs.put("wlpat", "test.*");
        attrs.put("format", "json");
        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(json.toString(3));
        } 
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    
}

