/*
 * HelloMaxDB example file
 *
 * use: 'javac HelloMaxDB.java' to compile
 *
 * and: 'java -cp /usr/share/java/sapdbc.jar:. HelloMaxDB' (and 
 *      connect options) to run
 */

import java.util.Properties;
import java.sql.*;

public class HelloMaxDB {
    public static void main (String [] args)
            throws ClassNotFoundException, SQLException
    {
        String user;
        String password;
        String host = "localhost";
        String dbname;

        /*
         * parse arguments
         */
        Properties options = parseOptions (args);
        host = options.getProperty ("host", "localhost");
        dbname = options.getProperty ("dbname");
        user = options.getProperty ("user");
        password = options.getProperty ("password");
        String url = "jdbc:sapdb://" + host + "/" + dbname;
        /*
         * load driver and connect
         */
        Class.forName ("com.sap.dbtech.jdbc.DriverSapDB");
        Connection connection = DriverManager.getConnection (url, user, password);

        /*
         * execute query
         */
        Statement stmt = connection.createStatement ();
        ResultSet resultSet = stmt.executeQuery ("Select 'hello world' from dual");
        resultSet.next ();
        String hello = resultSet.getString (1);
        System.out.println (hello);
    }

    public static void usage (boolean error) {
        System.out.println ("Usage: java ... HelloMaxDB -u name,pwd -d dbname [-n node]");
        if (error) {
            System.exit (2);
        }
        else {
            System.exit (0);
        }
    }

    public static Properties parseOptions (String[] args) {
        Properties result = new Properties ();
        boolean hasUser = false;
        boolean hasDb = false;

        for (int i = 0; i < args.length; ++i) {
            String currentArg = args [i];
            if (currentArg.charAt (0) != '-') {
                break;
            }
            char currentOpt = currentArg.charAt (1);
            switch (currentOpt) {
            case 'h':
                usage (false);
                break;
            case 'u':
                ++i;
                currentArg = args [i];
                int pos = currentArg.indexOf (',');
                result.put ("user", currentArg.substring (0, pos));
                result.put ("password", currentArg.substring (pos + 1));
                hasUser = true;
                break;
            case 'd':
                ++i;
                result.put ("dbname", args [i]);
                hasDb = true;
                break;
            case 'n':
                ++i;
                result.put ("host", args [i]);
                break;
            default:
                System.err.println ("invalid option " + currentOpt);
                usage (true);
                break;
            }
        }
        if (!hasUser || !hasDb) {
            usage (true);
        }
        return result;
    }

}
