/**************************************************************************************************
* Copyright (c) 1997-2016, 2018 Flexera. All Rights Reserved.
**************************************************************************************************/
package alerter;

import lmadmin.LicenseServerPortType;
import lmadmin.LicenseServerLocator;

/**
 * Aleter is a web client of the web services offered by the License Manager.
 * Alerter periodically checks for any alerts and sends out notification email.
 */
public class Connection {
    /** Interval between connection retries on startup */
    private static final int RETRY_INTERVAL = 15*1000; // 15 seconds

    /** 
     * The Alerter is a sample lmadmin web service client 
     *
     * @param args Command line arguments
     */
    public Connection(String host, int port, String user, String password) {
        // format the web service URL
        String url = "http://"+host+":"+port+"/soap";
        
        // keep trying to connect in case the server isn't up yet
        while (!connect(url, user, password)) {
            try {
                Thread.sleep(RETRY_INTERVAL);
            }
            catch(java.lang.InterruptedException e) {}
        }
    }

    /** Get the currect alerts. */
    public String getAlerts(String lastID) {
        try {
            return port.getAlerts(session, lastID); 
        }
        catch (java.rmi.RemoteException e) {
            System.out.println("Couldn't get alerts: "+e);
            return "";
        }
    }

    /** Connect to the lmadmin web service. */
    private boolean connect(String url, String user, String password) {
        try {
	    LicenseServerLocator service = new LicenseServerLocator();
	    service.setLicenseServerEndpointAddress(url);
	    port = service.getLicenseServer();
	    session = port.getSessionId(user, password);
        }
        catch (Exception e) {
	    System.out.println(e+"; retrying connection to lmadmin");
            return false;
        }
        
        return true;
    }

    /** The lmadmin web service */
    private LicenseServerPortType port;

    /** The session ID from successful authentication */
    private String session;
}
