import java.sql.*;

public class IReportJDBCConnector
{
	public static void main(String[] args)
	{
		boolean test = false;

		String query     = "";
		String jdbDriver = "";
		String jdbcUser  ="";
		String jdbcPassword ="";
		String jdbcUrl   ="";
		String error_msg = "";
		Exception exx = null;
		
		System.setErr(System.out);
		try 
		{
			
			//long start = System.currentTimeMillis();
			if(args.length == 0)
			{
				usage();
				System.out.println("CODE 1");
				System.exit(1);
			}
	
			for (int i=0; i<args.length; ++i)
			{
				if (args[i].startsWith("-jdriver"))
					jdbDriver = args[i].substring(8);
				else if (args[i].startsWith("-juser"))
					jdbcUser = args[i].substring(6);
				else if (args[i].startsWith("-jpasswd"))
					jdbcPassword = args[i].substring(8);
				else if (args[i].startsWith("-jurl"))
					jdbcUrl = args[i].substring(5);
				else if (args[i].equals("-test"))
				{
					test = true;
				}
				else if (args[i].equals("-query"))
				{
					if (i+1 < args.length) i++;
					query = args[i].replace('\"',' ');
				}
				else if (i+1 != args.length)
				{
						//System.out.println("No more params expected!");
						usage();
						System.out.println("CODE 2");
						System.exit(1);
				}
			}

			//System.out.println("Opening connection....");
			//System.out.flush();
			Class.forName( jdbDriver );
			Connection conn = DriverManager.getConnection(jdbcUrl,
			jdbcUser,
			jdbcPassword); 
			
			Statement stmt = null;
			
			
			stmt = conn.createStatement();
			if (test)
			{
				System.out.println("SUCCESS");
				System.out.println("***XXX***");
				System.out.flush();
				//conn.close();
				System.exit(0); 
			}
				
			if (query.length()>0)
			{	
				//System.out.println("Executing  query " + query);
				//System.out.flush();
				String output = "SUCCESS\n";
				ResultSet rs = stmt.executeQuery(query);
				ResultSetMetaData rsmd = rs.getMetaData();
				
				for (int i=1; i <=rsmd.getColumnCount(); ++i)
				{
					output += rsmd.getColumnName(i)+ "--" + getJdbcTypeClass(rsmd.getColumnType(i) )  + "\n";
				}
				
				System.out.println(output);
				System.out.flush();
				conn.close();
				System.exit(0); 
							
			}
					
		}catch (NoClassDefFoundError ex)
		{
			error_msg = "NoClassDefFoundError!!\nCheck your classpath!";
			System.out.println("ERROR");
			System.out.println(error_msg);
			System.out.println("CODE 3");
			System.out.flush();
			
			System.exit(1);		
		} 
		catch (ClassNotFoundException ex)
		{
			error_msg = "ClassNotFoundError:\n"+ ex.getMessage() +"\n\nCheck your classpath!";		
			exx = ex;
		} 
		catch (java.sql.SQLException ex)
		{
			error_msg = "SQL problems:\n"+ex.getMessage();			
			exx = ex;
		} 
		catch (Exception ex)
		{
			error_msg = "General problem:\n"+ex.getMessage()+"\n\nCheck username and password; is the DBMS active ?!";
			exx = ex;
		}
		
		java.io.StringWriter s = new java.io.StringWriter();
		exx.printStackTrace(new java.io.PrintWriter(s));
		System.out.println("ERROR");
		System.out.println(error_msg);
		System.out.println(s);
		System.out.flush();
		System.out.println("CODE 4");
		System.exit(1);
	}


	/**
	 *
	 */
	private static void usage()
	{
		System.out.println( "ERROR" );
		System.out.println("Syntax error of the command");
		System.out.println( "IReportJDBCConnector usage:" );
		System.out.println( "\tjava IReportJDBCConnector [options]\n" );
		System.out.println( "\t -test\tonly test the connection" );
		System.out.println( "\t -jdriver<jdbcdriver>\tuse this JDBC driver" );
		System.out.println( "\t -juser<jdbc user>\tdatabase user" );
		System.out.println( "\t -jpasswd<jdbc pass>\tdatabase password" );
		System.out.println( "\t -jurl<jdbc url>\tJDBC url" );
		System.out.println( "\t -query\"<query>\"\tQuery to execute" );
	}	
	
	
	/**
	 * Thanx to Jackie Manning j.m@programmer.net for this method!!
	 */
	 public static String getJdbcTypeClass( int t ) {
        String cls = "java.lang.String";
        switch( t ) {
            case java.sql.Types.TINYINT:
            case java.sql.Types.BIT:
                cls = "java.lang.Byte";
                break;
            case java.sql.Types.SMALLINT:
                cls = "java.lang.Short";
                break;
            case java.sql.Types.INTEGER:
                cls = "java.lang.Integer";
                break;
            case java.sql.Types.REAL:
            case java.sql.Types.DOUBLE:
            case java.sql.Types.NUMERIC:
            case java.sql.Types.DECIMAL:
                cls = "java.lang.Double";
                break;
            case java.sql.Types.CHAR:
            case java.sql.Types.VARCHAR:
                cls = "java.lang.String";
                break;

            case java.sql.Types.BIGINT:
                cls = "java.lang.Long";
                break;
            case java.sql.Types.DATE:
            case java.sql.Types.TIME:
                cls = "java.util.Date";
                break;
            case java.sql.Types.TIMESTAMP:
                cls = "java.sql.Timestamp";
                break;
        }
        return cls;
    }
}

