Example usage for java.lang Class forName

List of usage examples for java.lang Class forName

Introduction

In this page you can find the example usage for java.lang Class forName.

Prototype

@CallerSensitive
public static Class<?> forName(String className) throws ClassNotFoundException 

Source Link

Document

Returns the Class object associated with the class or interface with the given string name.

Usage

From source file:jfutbol.com.jfutbol.GcmSender.java

public static void main(String[] args) {
    log.info("GCM - Sender running");
    do {//from   w ww .j a va 2s  .  co m

        Connection conn = null;
        Connection conn2 = null;
        Statement stmt = null;
        Statement stmt2 = null;

        try {
            // STEP 2: Register JDBC driver
            Class.forName(JDBC_DRIVER);
            // STEP 3: Open a connection
            // System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            conn2 = DriverManager.getConnection(DB_URL, USER, PASS);
            // STEP 4: Execute a query
            // System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT userId FROM notifications WHERE sentByGCM=0 GROUP BY userId";
            ResultSet rs = stmt.executeQuery(sql);
            // STEP 5: Extract data from result set
            while (rs.next()) {
                log.info("Notification found");
                int userId = rs.getInt("userId");

                stmt2 = conn2.createStatement();
                String sql2;
                sql2 = "SELECT COUNT(id) notificationCounter FROM notifications WHERE status=0 AND userId="
                        + userId;
                ResultSet rs2 = stmt2.executeQuery(sql2);
                int notificationCounter = rs2.getInt("notificationCounter");
                rs2.close();
                stmt2.close();
                // Retrieve by column name

                // Display values
                // System.out.print("userId: " + userId);
                // System.out.print(", notificationCounter: " +
                // notificationCounter);
                SendNotification(userId, notificationCounter);
            }
            // STEP 6: Clean-up environment
            rs.close();
            stmt.close();
            conn.close();
            conn2.close();
        } catch (SQLException se) {
            // Handle errors for JDBC
            log.error(se.getMessage());
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException se2) {
                log.error(se2.getMessage());
            } // nothing we can do
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                log.error(se.getMessage());
                se.printStackTrace();
            } // end finally try
        } // end try
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    } while (1 != 0);
}

From source file:LoadDriver.java

public static void main(String[] av) {
    try {//from   ww  w .  java  2s.  c om
        // Try to load the jdbc-odbc bridge driver
        // Should be present on Sun JDK implementations.
        Class c = Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        System.out.println("Loaded " + c.getName());
        // Try to load an Oracle driver.
        Class d = Class.forName("oracle.jdbc.driver.OracleDriver");
        System.out.println("Loaded " + d.getName());
    } catch (ClassNotFoundException ex) {
        System.err.println(ex);
    }
}

From source file:com.konakart.ApiExample.java

/**
 * @param args/*from   w  ww  . j  a  v  a 2 s. c  o m*/
 */
public static void main(String[] args) {
    try {
        /*
         * Instantiate a KonaKart Engine instance
         */
        Class<?> engineClass = Class.forName(ws_engine_implementation);
        eng = (KKEngIf) engineClass.newInstance();

        /*
         * Login with default credentials
         */
        //sessionId = eng.login(DEFAULT_USERNAME, DEFAULT_PASSWORD);
        //log.info(DEFAULT_USERNAME + " logged in successfully and got session " + sessionId);

        log.info("Manufacturers:\n");
        ManufacturerIf[] manus = eng.getAllManufacturers();
        for (int m = 0; m < manus.length; m++) {
            log.info("\t" + manus[m].getName());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:eu.riscoss.RemoteRiskAnalyserMain.java

public static void main(String[] args) throws Exception {
    loadJSmile();/*from ww  w . ja  v  a2  s .co m*/
    Class rra = Class.forName("eu.riscoss.RemoteRiskAnalyser");
    Method meth = rra.getMethod("main");
    meth.invoke(null);
}

From source file:com.kylinolap.query.QueryCli.java

public static void main(String[] args) throws Exception {

    Options options = new Options();
    options.addOption(OPTION_METADATA);/*from   w  w w  .j a v  a  2s .c om*/
    options.addOption(OPTION_SQL);

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = parser.parse(options, args);
    KylinConfig config = KylinConfig
            .createInstanceFromUri(commandLine.getOptionValue(OPTION_METADATA.getOpt()));
    String sql = commandLine.getOptionValue(OPTION_SQL.getOpt());

    Class.forName("net.hydromatic.optiq.jdbc.Driver");
    File olapTmp = OLAPSchemaFactory.createTempOLAPJson(null, config);

    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = DriverManager.getConnection("jdbc:optiq:model=" + olapTmp.getAbsolutePath());

        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);
        int n = 0;
        ResultSetMetaData meta = rs.getMetaData();
        while (rs.next()) {
            n++;
            for (int i = 1; i <= meta.getColumnCount(); i++) {
                System.out.println(n + " - " + meta.getColumnLabel(i) + ":\t" + rs.getObject(i));
            }
        }
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }

}

From source file:ConstructorTroubleAgain.java

public static void main(String... args) {
    String argType = (args.length == 0 ? "" : args[0]);
    try {/*w  ww  . ja  v a 2s  . c o m*/
        Class<?> c = Class.forName("ConstructorTroubleAgain");
        if ("".equals(argType)) {
            // IllegalArgumentException: wrong number of arguments
            Object o = c.getConstructor().newInstance("foo");
        } else if ("int".equals(argType)) {
            // NoSuchMethodException - looking for int, have Integer
            Object o = c.getConstructor(int.class);
        } else if ("Object".equals(argType)) {
            // newInstance() does not perform method resolution
            Object o = c.getConstructor(Object.class).newInstance("foo");
        } else {
            assert false;
        }

        // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    } catch (NoSuchMethodException x) {
        x.printStackTrace();
    } catch (InvocationTargetException x) {
        x.printStackTrace();
    } catch (InstantiationException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    }
}

From source file:ClassForName.java

public static void main(String[] av) {
    Class c = null;/*from   www  . ja  v  a2 s  .c  o m*/
    Object o = null;
    try {
        // Load the class, return a Class for it
        c = Class.forName("java.awt.Frame");
        // Construct an object, as if new Type()
        o = c.newInstance();
    } catch (Exception e) {
        System.err.println("That didn't work. " + " Try something else" + e);
    }
    if (o != null && o instanceof Frame) {
        Frame f = (Frame) o;
        f.setTitle("Testing");
        f.setVisible(true);
    } else
        throw new IllegalArgumentException("Huh? What gives?");
}

From source file:ListTables.java

public static void main(String[] args) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    // Enable logging
    // DriverManager.setLogStream(System.err);

    System.out.println("Getting Connection");
    Connection c = DriverManager.getConnection("jdbc:odbc:Companies", "ian", ""); // user, passwd
    DatabaseMetaData md = c.getMetaData();
    ResultSet rs = md.getTables(null, null, "%", null);
    while (rs.next()) {
        System.out.println(rs.getString(3));
    }//  w  w  w . j av  a2  s . c  om
}

From source file:com.miraclelinux.historygluon.HistoryGluon.java

public static void main(String[] args) throws Exception {
    m_log = LogFactory.getLog(HistoryGluon.class);
    m_log.info("HistoryGluon, MIRACLE LINUX Corp. 2012");

    if (!parseArgs(args))
        return;/*from   w  ww. ja v a 2  s  . c  o  m*/

    StorageDriver driver = null;
    String prefix = "com.miraclelinux.historygluon.";
    String driverName = prefix + m_storageName + "Driver";
    try {
        Class<?> c = Class.forName(driverName);
        Class[] argTypes = { String[].class };
        Constructor constructor = c.getConstructor(argTypes);
        Object[] driverArgs = { m_storageDriverArgs };
        driver = (StorageDriver) constructor.newInstance(driverArgs);
    } catch (ClassNotFoundException e) {
        m_log.error("Unknown Storage Type: " + m_storageName);
        printUsage();
        return;
    } catch (Exception e) {
        throw e;
    }

    if (!driver.init()) {
        m_log.fatal("Failed to initialize Storage Driver.");
        return;
    }
    m_log.info("StorageDriver: " + driver.getName());

    if (m_isDeleteDBMode) {
        m_log.info("try to deleted DB...");
        if (driver.deleteDB())
            m_log.info("Success: Deleted DB");
        else
            m_log.info("Failed: Deleted DB");
        driver.close();
        return;
    }

    ConnectionThread connectionThread = new ConnectionThread(DEFAULT_PORT, driver);
    connectionThread.start();
    driver.close();
}

From source file:example.ConfigurationsExample.java

public static void main(String[] args) {
    String jdbcPropToLoad = "prod.properties";
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption("d", "dev", false,
            "Dev tag to launch app in dev mode. Means that app will launch embedded mckoi db.");
    try {//w  w  w . j  av  a2s .  co m
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("d")) {
            System.err.println("App is in DEV mode");
            jdbcPropToLoad = "dev.properties";
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }
    Properties p = new Properties();
    try {
        p.load(ConfigurationsExample.class.getResourceAsStream("/" + jdbcPropToLoad));
    } catch (IOException e) {
        System.err.println("Properties loading failed.  Reason: " + e.getMessage());
    }
    try {
        String clazz = p.getProperty("driver.class");
        Class.forName(clazz);
        System.out.println(" Jdbc driver loaded :" + clazz);
    } catch (ClassNotFoundException e) {
        System.err.println("Jdbc Driver class loading failed.  Reason: " + e.getMessage());
        e.printStackTrace();
    }

}