/*
 * THE SOFTWARE PRODUCT IS PROVIDED “AS IS” WITHOUT REPRESENTATIONS OR WARRANTIES OF ANY KIND. TO THE
 * FULLEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW, LRI SPECIFICALLY DISCLAIMS ALL WARRANTIES, CONDITIONS,
 * AND REPRESENTATIONS REGARDING THE SOFTWARE PRODUCT, INCLUDING WITHOUT LIMITATION ANY WARRANTY OF
 * FITNESS FOR ANY PARTICULAR PURPOSE, MERCHANTABILITY, TITLE, QUIET ENJOYMENT, OR NON-INFRINGEMENT.
 * 
 * Copyright 2016 Liquid Robotics
 */
package logintest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Base64;

/*
 * Always connect to https to secure user authentication credentials.
 */
public class LoginTest {
    /**
     * @param args the command line arguments
     *
     */
    public static void main(String[] args) {
        final String defaultURL = "https://mds.liquidr.net/firehose/?start=now&kinds=Waveglider"; // Stream from current date/time
        final String defaultUser = "YourUser";
        final String defaultPassword = "YourUserPassword";
        String url;
        String user;
        String password; 
        
        if (args.length != 0 && args.length != 3) {
            System.err.println("Usage: LoginTest [URL User Password]");
            System.exit(1);
        }
        if (args.length == 3) {
            url = args[0];
            user = args[1];
            password = args[2];
        } else {
            url = defaultURL;
            user = defaultUser;
            password = defaultPassword;
        }
        try {           
            byte c[] = new byte[1];
            int readCount;
            
            // Attempt to connect
            InputStream is = openAuthenticatedConnection(url, user, password);
            
            // Connection established, start reading stream
            while ((readCount=is.read(c)) >= 0) {
                if (readCount > 0) {
                    System.out.print(new String(c, Charset.forName("ISO-8859-1"))); System.out.flush();
                } else {
                    // Should the read return 0 bytes read
                    System.out.println("sleeping...");
                    Thread.sleep(1000);
                }
            }
            System.err.println("EOF on input stream");
        } catch(Exception e) {
            System.err.println("Login exception: " + e);
        }
        System.exit(0);
    }
    public static InputStream openAuthenticatedConnection(String urlStr, String username, String password) throws IOException {
       URL url = new URL(urlStr);
       System.err.println("BasicAuthClient: Attempt to authenticate on " + url + " for user " + username);

       String authString = username + ":" + password;
       byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
       String authStringEnc = new String(authEncBytes);
       HttpURLConnection connection = (HttpURLConnection) url.openConnection();
       connection.setUseCaches(false);
       connection.setReadTimeout(0);
       //connection.setConnectTimeout(1000*60*15);
       connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
       if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
           System.err.println("User: " + username + " authenticated");
           return connection.getInputStream();
       } else {
           throw new IOException("Connection or authentication exception: Http Status code (" + connection.getResponseCode() + ")");
       }
   }  
}