import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;

public class TestDriverFailoverNoMaster {
    public static void main(String[] args) {


        try {
            // The newInstance() call is a work around for some
            // broken Java implementations

            Class.forName("org.mariadb.jdbc.Driver").newInstance();

        } catch (Exception ex) {
            System.out.println("Exception: " + ex.getMessage());
        } 	
		
		for (int i = 0; i < 20; i++) {
			Connection conn = null;
			Statement stmt = null;
			ResultSet rs = null;
			Boolean setReadOnly = true;
			
			try {
				conn = DriverManager.getConnection("jdbc:mariadb:replication://address=(host=nonexistent)(type=master),address=(host=127.0.0.1)(type=slave)/?autoReconnect=true",
					"failover_test", "password");
				
				if (setReadOnly) {
					System.out.println("Setting connection to read-only.");
					conn.setReadOnly(true);
				}
				
				stmt = conn.createStatement();
				rs = stmt.executeQuery("SELECT @@global.hostname AS this_node;");

				while (rs.next()) {
					String this_node = rs.getString("this_node");
				
					System.out.println("Iteration = " + Integer.toString(i) + ", Node = " + this_node);
				}
			} catch (SQLException ex) {
				// handle any errors
				System.out.println("SQLException: " + ex.getMessage());
				System.out.println("SQLState: " + ex.getSQLState());
				System.out.println("VendorError: " + ex.getErrorCode());
			} finally {
				if (rs != null) {
					try {
						rs.close();
					} catch (SQLException sqlEx) { } // ignore

					rs = null;
				}

				if (stmt != null) {
					try {
						stmt.close();
					} catch (SQLException sqlEx) { } // ignore

					stmt = null;
				}
				
				if (conn != null) {
					try {
						conn.close();
					} catch (SQLException sqlEx) { } // ignore

					conn = null;
				}
			}	
		}
    }
}