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:BatchUpdate.java

public static void main(String args[]) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*from  ww w  .  j a va  2  s .co  m*/
    Statement stmt;

    try {
        Class.forName("myDriver.ClassName");
    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        con.setAutoCommit(false);
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)");
        int[] updateCounts = stmt.executeBatch();
        ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");
        System.out.println("Table COFFEES after insertion:");

        while (uprs.next()) {
            String name = uprs.getString("COF_NAME");
            int id = uprs.getInt("SUP_ID");
            float price = uprs.getFloat("PRICE");
            int sales = uprs.getInt("SALES");
            int total = uprs.getInt("TOTAL");
            System.out.print(name + " " + id + " " + price);
            System.out.println(" " + sales + " " + total);
        }
        uprs.close();
        stmt.close();
        con.close();

    } catch (BatchUpdateException b) {
        System.err.println("SQLException: " + b.getMessage());
        System.err.println("SQLState: " + b.getSQLState());
        System.err.println("Message: " + b.getMessage());
        System.err.println("Vendor: " + b.getErrorCode());
        System.err.print("Update counts: ");
        int[] updateCounts = b.getUpdateCounts();
        for (int i = 0; i < updateCounts.length; i++) {
            System.err.print(updateCounts[i] + " ");
        }

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
        System.err.println("SQLState: " + ex.getSQLState());
        System.err.println("Message: " + ex.getMessage());
        System.err.println("Vendor: " + ex.getErrorCode());
    }
}

From source file:ImageStringToBlob.java

public static void main(String[] args) {
    Connection conn = null;/* w  ww  . ja  va 2  s.  co m*/

    if (args.length != 1) {
        System.out.println("Missing argument: full path to <oscar.properties>");
        return;
    }

    try {

        FileInputStream fin = new FileInputStream(args[0]);
        Properties prop = new Properties();
        prop.load(fin);

        String driver = prop.getProperty("db_driver");
        String uri = prop.getProperty("db_uri");
        String db = prop.getProperty("db_name");
        String username = prop.getProperty("db_username");
        String password = prop.getProperty("db_password");

        Class.forName(driver);
        conn = DriverManager.getConnection(uri + db, username, password);
        conn.setAutoCommit(true); // no transactions

        /*
         * select all records ids with image_data not null and contents is null
         * for each id fetch record
         * migrate data from image_data to contents
         */
        String sql = "select image_id from client_image where image_data is not null and contents is null";
        PreparedStatement pst = conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();
        List<Long> ids = new ArrayList<Long>();

        while (rs.next()) {
            ids.add(rs.getLong("image_id"));
        }

        rs.close();

        sql = "select image_data from client_image where image_id = ?";
        pst = conn.prepareStatement(sql);

        System.out.println("Migrating image data for " + ids.size() + " images...");
        for (Long id : ids) {
            pst.setLong(1, id);
            ResultSet imagesRS = pst.executeQuery();
            while (imagesRS.next()) {
                String dataString = imagesRS.getString("image_data");
                Blob dataBlob = fromStringToBlob(dataString);
                if (writeBlobToDb(conn, id, dataBlob) == 1) {
                    System.out.println("Image data migrated for image_id: " + id);
                }
            }
            imagesRS.close();
        }
        System.out.println("Migration completed.");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.jetbrains.webdemo.executors.JavaExecutor.java

public static void main(String[] args) {
    PrintStream defaultOutputStream = System.out;
    try {/*from   w ww  . j av  a 2  s .  c  o  m*/
        System.setOut(new PrintStream(standardOutputStream));
        System.setErr(new PrintStream(errorOutputStream));

        RunOutput outputObj = new RunOutput();
        String className;
        if (args.length > 0) {
            className = args[0];
            try {
                Method mainMethod = Class.forName(className).getMethod("main", String[].class);
                mainMethod.invoke(null, (Object) Arrays.copyOfRange(args, 1, args.length));
            } catch (InvocationTargetException e) {
                outputObj.exception = e.getCause();
            } catch (NoSuchMethodException e) {
                System.err.println("No main method found in project.");
            } catch (ClassNotFoundException e) {
                System.err.println("No main method found in project.");
            }
        } else {
            System.err.println("No main method found in project.");
        }

        System.out.flush();
        System.err.flush();
        System.setOut(defaultOutputStream);
        outputObj.text = outputStream.toString().replaceAll("</errStream><errStream>", "")
                .replaceAll("</outStream><outStream>", "");
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(Throwable.class, new ThrowableSerializer());
        objectMapper.registerModule(module);
        System.out.print(objectMapper.writeValueAsString(outputObj));
    } catch (Throwable e) {
        System.setOut(defaultOutputStream);
        System.out.println("{\"text\":\"<errStream>" + e.getClass().getName() + ": " + e.getMessage());
        System.out.print("</errStream>\"}");
    }

}

From source file:CreateCoffees.java

public static void main(String args[]) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*  w  ww  .  j  av a2s.  c o  m*/
    String createString;
    createString = "create table COFFEES " + "(COF_NAME VARCHAR(32), " + "SUP_ID INTEGER, " + "PRICE FLOAT, "
            + "SALES INTEGER, " + "TOTAL INTEGER)";
    Statement stmt;

    try {
        Class.forName("myDriver.ClassName");
    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");
        stmt = con.createStatement();
        stmt.executeUpdate(createString);
        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:ExecuteSQL.java

public static void main(String[] args) {
    Connection conn = null; // Our JDBC connection to the database server
    try {//w  w  w . j  ava 2s.  c  o m
        String driver = null, url = null, user = "", password = "";

        // Parse all the command-line arguments
        for (int n = 0; n < args.length; n++) {
            if (args[n].equals("-d"))
                driver = args[++n];
            else if (args[n].equals("-u"))
                user = args[++n];
            else if (args[n].equals("-p"))
                password = args[++n];
            else if (url == null)
                url = args[n];
            else
                throw new IllegalArgumentException("Unknown argument.");
        }

        // The only required argument is the database URL.
        if (url == null)
            throw new IllegalArgumentException("No database specified");

        // If the user specified the classname for the DB driver, load
        // that class dynamically. This gives the driver the opportunity
        // to register itself with the DriverManager.
        if (driver != null)
            Class.forName(driver);

        // Now open a connection the specified database, using the
        // user-specified username and password, if any. The driver
        // manager will try all of the DB drivers it knows about to try to
        // parse the URL and connect to the DB server.
        conn = DriverManager.getConnection(url, user, password);

        // Now create the statement object we'll use to talk to the DB
        Statement s = conn.createStatement();

        // Get a stream to read from the console
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        // Loop forever, reading the user's queries and executing them
        while (true) {
            System.out.print("sql> "); // prompt the user
            System.out.flush(); // make the prompt appear now.
            String sql = in.readLine(); // get a line of input from user

            // Quit when the user types "quit".
            if ((sql == null) || sql.equals("quit"))
                break;

            // Ignore blank lines
            if (sql.length() == 0)
                continue;

            // Now, execute the user's line of SQL and display results.
            try {
                // We don't know if this is a query or some kind of
                // update, so we use execute() instead of executeQuery()
                // or executeUpdate() If the return value is true, it was
                // a query, else an update.
                boolean status = s.execute(sql);

                // Some complex SQL queries can return more than one set
                // of results, so loop until there are no more results
                do {
                    if (status) { // it was a query and returns a ResultSet
                        ResultSet rs = s.getResultSet(); // Get results
                        printResultsTable(rs, System.out); // Display them
                    } else {
                        // If the SQL command that was executed was some
                        // kind of update rather than a query, then it
                        // doesn't return a ResultSet. Instead, we just
                        // print the number of rows that were affected.
                        int numUpdates = s.getUpdateCount();
                        System.out.println("Ok. " + numUpdates + " rows affected.");
                    }

                    // Now go see if there are even more results, and
                    // continue the results display loop if there are.
                    status = s.getMoreResults();
                } while (status || s.getUpdateCount() != -1);
            }
            // If a SQLException is thrown, display an error message.
            // Note that SQLExceptions can have a general message and a
            // DB-specific message returned by getSQLState()
            catch (SQLException e) {
                System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
            }
            // Each time through this loop, check to see if there were any
            // warnings. Note that there can be a whole chain of warnings.
            finally { // print out any warnings that occurred
                SQLWarning w;
                for (w = conn.getWarnings(); w != null; w = w.getNextWarning())
                    System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
            }
        }
    }
    // Handle exceptions that occur during argument parsing, database
    // connection setup, etc. For SQLExceptions, print the details.
    catch (Exception e) {
        System.err.println(e);
        if (e instanceof SQLException)
            System.err.println("SQL State: " + ((SQLException) e).getSQLState());
        System.err.println(
                "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>");
    }

    // Be sure to always close the database connection when we exit,
    // whether we exit because the user types 'quit' or because of an
    // exception thrown while setting things up. Closing this connection
    // also implicitly closes any open statements and result sets
    // associated with it.
    finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:JDBCMeta.java

public static void main(String[] av) {
    int i;/*  w  ww.j av  a2 s .com*/
    try {
        // Load the driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

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

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection("jdbc:odbc:Companies", "ian", ""); // user, passwd

        // Get a Database MetaData as a way of interrogating
        // the names of the tables in this database.
        DatabaseMetaData meta = conn.getMetaData();

        System.out.println("We are using " + meta.getDatabaseProductName());
        System.out.println("Version is " + meta.getDatabaseProductVersion());

        int txisolation = meta.getDefaultTransactionIsolation();
        System.out.println("Database default transaction isolation is " + txisolation + " ("
                + transactionIsolationToString(txisolation) + ").");

        conn.close();

        System.out.println("All done!");

    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException ex) {
        System.out.println("Database access failed:");
        System.out.println(ex);
    }
}

From source file:TableTypes.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*from   w w  w  .j  a v  a2s  .c  om*/

    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {
        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        DatabaseMetaData dbmd = con.getMetaData();
        String dbmsName = dbmd.getDatabaseProductName();
        ResultSet rs = dbmd.getTableTypes();
        System.out.print("The following types of tables are ");
        System.out.println("available in " + dbmsName + ":  ");

        while (rs.next()) {
            String tableType = rs.getString("TABLE_TYPE");
            System.out.println("    " + tableType);
        }

        rs.close();
        con.close();

    } catch (SQLException ex) {
        System.err.print("SQLException: ");
        System.err.println(ex.getMessage());
    }
}

From source file:ArrayCreator.java

public static void main(String... args) {
    Matcher m = p.matcher(s);// www. j a v  a2 s .  c  om

    if (m.find()) {
        String cName = m.group(1);
        String[] cVals = m.group(2).split("[\\s,]+");
        int n = cVals.length;

        try {
            Class<?> c = Class.forName(cName);
            Object o = Array.newInstance(c, n);
            for (int i = 0; i < n; i++) {
                String v = cVals[i];
                Constructor ctor = c.getConstructor(String.class);
                Object val = ctor.newInstance(v);
                Array.set(o, i, val);
            }

            Object[] oo = (Object[]) o;
            out.format("%s[] = %s%n", cName, Arrays.toString(oo));

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

From source file:io.anserini.util.SearchTimeUtil.java

public static void main(String[] args) throws IOException, ParseException, ClassNotFoundException,
        NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {

    if (args.length != 1) {
        System.err.println("Usage: SearchTimeUtil <indexDir>");
        System.err.println("indexDir: index directory");
        System.exit(1);/*from   w  ww  .  j ava 2s . co  m*/
    }

    String[] topics = { "topics.web.1-50.txt", "topics.web.51-100.txt", "topics.web.101-150.txt",
            "topics.web.151-200.txt", "topics.web.201-250.txt", "topics.web.251-300.txt" };

    SearchWebCollection searcher = new SearchWebCollection(args[0]);

    for (String topicFile : topics) {
        Path topicsFile = Paths.get("src/resources/topics-and-qrels/", topicFile);
        TopicReader tr = (TopicReader) Class.forName("io.anserini.search.query." + "Webxml" + "TopicReader")
                .getConstructor(Path.class).newInstance(topicsFile);
        SortedMap<Integer, String> queries = tr.read();
        for (int i = 1; i <= 3; i++) {
            final long start = System.nanoTime();
            String submissionFile = File.createTempFile(topicFile + "_" + i, ".tmp").getAbsolutePath();
            RerankerCascade cascade = new RerankerCascade();
            cascade.add(new IdentityReranker());
            searcher.search(queries, submissionFile, new BM25Similarity(0.9f, 0.4f), 1000, cascade);
            final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start,
                    TimeUnit.NANOSECONDS);
            System.out.println(topicFile + "_" + i + " search completed in "
                    + DurationFormatUtils.formatDuration(durationMillis, "mm:ss:SSS"));
        }
    }

    searcher.close();
}

From source file:com.github.zerkseez.codegen.wrappergenerator.Main.java

public static void main(final String[] args) throws Exception {
    final Options options = new Options();
    options.addOption(Option.builder().longOpt("outputDirectory").hasArg().required().build());
    options.addOption(Option.builder().longOpt("classMappings").hasArgs().required().build());

    final CommandLineParser parser = new DefaultParser();

    try {//from w  ww  . j av a 2s  . c o  m
        final CommandLine line = parser.parse(options, args);
        final String outputDirectory = line.getOptionValue("outputDirectory");
        final String[] classMappings = line.getOptionValues("classMappings");
        for (String classMapping : classMappings) {
            final String[] tokens = classMapping.split(":");
            if (tokens.length != 2) {
                throw new IllegalArgumentException(
                        String.format("Invalid class mapping format \"%s\"", classMapping));
            }
            final Class<?> wrappeeClass = Class.forName(tokens[0]);
            final String fullWrapperClassName = tokens[1];
            final int indexOfLastDot = fullWrapperClassName.lastIndexOf('.');
            final String wrapperPackageName = (indexOfLastDot == -1) ? ""
                    : fullWrapperClassName.substring(0, indexOfLastDot);
            final String simpleWrapperClassName = (indexOfLastDot == -1) ? fullWrapperClassName
                    : fullWrapperClassName.substring(indexOfLastDot + 1);

            System.out.println(String.format("Generating wrapper class for %s...", wrappeeClass));
            final WrapperGenerator generator = new WrapperGenerator(wrappeeClass, wrapperPackageName,
                    simpleWrapperClassName);
            generator.writeTo(outputDirectory, true);
        }
        System.out.println("Done");
    } catch (MissingOptionException e) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(String.format("java -cp CLASSPATH %s", Main.class.getName()), options);
    }
}