package jsonexample;

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.*;

public class Main {
    
    public Main() {
    }
    
    public static void main(String[] args) {
        String data;
            
            // url with the query
        String url_string = "http://localhost/auth/run.cgi/wordlist?corpname=bnc;wlattr=word;wlminfreq=5;wlmaxitems=100;wlpat=test.*;format=json";

        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);
        
        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();
        }
    } 
}

