Example usage for java.sql DriverManager registerDriver

List of usage examples for java.sql DriverManager registerDriver

Introduction

In this page you can find the example usage for java.sql DriverManager registerDriver.

Prototype

public static void registerDriver(java.sql.Driver driver) throws SQLException 

Source Link

Document

Registers the given driver with the DriverManager .

Usage

From source file:org.sonar.server.platform.db.EmbeddedDatabase.java

private static void createDatabase(File dbHome, String user, String password) throws SQLException {
    String url = format("jdbc:h2:%s/sonar;USER=%s;PASSWORD=%s", dbHome.getAbsolutePath(), user, password);

    DriverManager.registerDriver(new Driver());
    DriverManager.getConnection(url).close();
}

From source file:mil.army.usace.data.nativequery.rdbms.NativeRdbmsQuery.java

public NativeRdbmsQuery(Driver driver, String url) {
    try {/*w  w  w.j  a  va2  s  .  co  m*/
        DriverManager.registerDriver(driver);
        DriverManager.setLoginTimeout(10);
        conn = DriverManager.getConnection(url);
        conn.setAutoCommit(true);
    } catch (Exception ex) {
        System.out.println("Error Making Connection");
        throw new RuntimeException(ex.getMessage());
    }
}

From source file:eu.optimis.tf.sp.service.SPOperation.java

public String getHistoricTrust(String providerId) {
    String historic = "";
    //      String historicHeader = "<trust xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">";
    String historicBody = "";
    //      try {
    //         TrecIPTrustDAO iptdao = new TrecIPTrustDAO();
    //         List<IpTrust> iptlst = iptdao.getIPTrusts(providerId);
    //         /*  w  ww. j av a  2 s.co m*/
    //         for (IpTrust ipt : iptlst){
    //            historicBody = historicBody + "<value>" + (ipt.getIpTrust() * rate)
    //                  + "</value>";
    //         }
    //         String historicEnd = "</trust>";
    //         historic = historicHeader + historicBody + historicEnd;
    //         return historic;
    //      } catch (Exception e) {
    ResourceBundle rb = ResourceBundle.getBundle("trustframework", Locale.getDefault());
    try {
        String url = rb.getString("db.sp.host");
        String user = rb.getString("db.user");
        String password = rb.getString("db.pass");
        Driver myDriver = new com.mysql.jdbc.Driver();
        DriverManager.registerDriver(myDriver);
        Connection conn = DriverManager.getConnection(url, user, password);
        // Get a statement from the connection
        Statement stmt = conn.createStatement();

        // Execute the query
        ResultSet rs = stmt.executeQuery(
                "SELECT  `ip_trust` FROM  `ip_trust` WHERE  `ip_id` =  '" + providerId + "' limit 100");

        // Loop through the result set
        while (rs.next()) {
            //               historicBody = historicBody + "<value>" + (Double.valueOf(rs.getString(1)) * rate)
            //                     + "</value>";
            historicBody = historicBody + (Double.valueOf(rs.getString(1)) * rate) + ",";
        }

        // Close the result set, statement and the connection
        rs.close();
        stmt.close();
        conn.close();
        return historicBody;
    } catch (SQLException e1) {
        System.out.println("Error: unable to load infrastructure provider trust");
        return "";
    }
    //      }
}

From source file:com.alibaba.wasp.jdbc.Driver.java

/**
 * INTERNAL/*from   w ww  .j a  va 2  s.c om*/
 */
public static synchronized Driver load() {
    try {
        if (!registered) {
            registered = true;
            DriverManager.registerDriver(INSTANCE);
        }
    } catch (SQLException e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    }
    return INSTANCE;
}

From source file:org.sonar.server.database.EmbeddedDatabase.java

private void createDatabase(File dbHome, String user, String password) throws SQLException {
    String url = String.format("jdbc:h2:%s/sonar;USER=%s;PASSWORD=%s", dbHome.getAbsolutePath(), user,
            password);/* w  ww  . j a  v a2  s. c om*/

    DriverManager.registerDriver(new Driver());
    DriverManager.getConnection(url).close();
}

From source file:org.datacleaner.database.UserDatabaseDriver.java

public UserDatabaseDriver loadDriver() throws IllegalStateException {
    if (!_loaded) {
        ClassLoader driverClassLoader = ClassLoaderUtils.createClassLoader(_files);

        final Class<?> loadedClass;
        try {//from   www.j  av  a  2  s.  c o m
            loadedClass = Class.forName(_driverClassName, true, driverClassLoader);
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            }
            throw new IllegalStateException("Could not load driver class", e);
        }
        logger.info("Loaded class: {}", loadedClass.getName());

        if (ReflectionUtils.is(loadedClass, Driver.class)) {
            _driverInstance = (Driver) ReflectionUtils.newInstance(loadedClass);
            _registeredDriver = new DriverWrapper(_driverInstance);
            try {
                DriverManager.registerDriver(_registeredDriver);
            } catch (SQLException e) {
                throw new IllegalStateException("Could not register driver", e);
            }
        } else {
            throw new IllegalStateException("Class is not a Driver class: " + _driverClassName);
        }
        _loaded = true;
    }
    return this;
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

public RdbmsDataQuery(Driver driver, String url, DB db) {
    try {/*from w w  w  .j  a  v a 2s . com*/
        DriverManager.registerDriver(driver);
        DriverManager.setLoginTimeout(10);
        conn = DriverManager.getConnection(url);
        conn.setAutoCommit(true);
        this.db = db;
        switch (db) {
        case ORACLE:
            this.converter = new OracleConverter(conn);
            break;
        default:
            this.converter = new DefaultConverter();
        }
    } catch (Exception ex) {
        System.out.println("Error Making Connection");
        throw new RuntimeException(ex.getMessage());
    }
}

From source file:net.fender.sql.DriverConnectionFactory.java

/**
 * @throws Exception/*from   w  w  w.java2  s  .  c o  m*/
 */
public void init() throws Exception {
    try {
        driver = DriverManager.getDriver(url);
    } catch (SQLException e) {
        // no suitable driver
    }
    if (driver == null) {
        driver = (Driver) Class.forName(driverClassName).newInstance();
        log.debug(driver);
        DriverManager.registerDriver(driver);
    }
    String encryptedUser = properties.getProperty("encryptedUser");
    if (encryptedUser != null) {
        String user = null;
        if (cryptoUtil == null) {
            user = CryptoUtil.decryptUsingSystemPropertyKey(systemPropertyKeyName, encryptedUser);
        } else {
            user = cryptoUtil.decrypt(key, encryptedUser);
        }
        properties.setProperty("user", user);
        properties.remove("encryptedUser");
    }
    String encryptedPassword = properties.getProperty("encryptedPassword");
    if (encryptedPassword != null) {
        String password = null;
        if (cryptoUtil == null) {
            password = CryptoUtil.decryptUsingSystemPropertyKey(systemPropertyKeyName, encryptedPassword);
        } else {
            password = cryptoUtil.decrypt(key, encryptedPassword);
        }
        properties.setProperty("password", password);
        properties.remove("encryptedPassword");
    }
    if (testOnCreate) {
        Connection connection = getConnection();
        JdbcUtils.close(connection);
    }
}

From source file:com.mg.jet.birt.report.data.oda.ejbql.HibernateUtil.java

private static synchronized void initSessionFactory(String hibfile, String mapdir, String jndiName)
        throws HibernateException {
    //ClassLoader cl1;

    if (sessionFactory == null) {

        if (jndiName == null || jndiName.trim().length() == 0)
            jndiName = CommonConstant.DEFAULT_JNDI_URL;
        Context initCtx = null;/*  ww w .j a v  a2  s .  c  o  m*/
        try {
            initCtx = new InitialContext();
            sessionFactory = (SessionFactory) initCtx.lookup(jndiName);
            return;
        } catch (Exception e) {
            logger.log(Level.INFO, "Unable to get JNDI data source connection", e);
        } finally {
            if (initCtx != null)
                try {
                    initCtx.close();
                } catch (NamingException e) {
                    //ignore
                }
        }

        Thread thread = Thread.currentThread();
        try {
            //Class.forName("org.hibernate.Configuration");
            //Configuration ffff = new Configuration();
            //Class.forName("org.apache.commons.logging.LogFactory");

            oldloader = thread.getContextClassLoader();
            //Class thwy = oldloader.loadClass("org.hibernate.cfg.Configuration");
            //Class thwy2 = oldloader.loadClass("org.apache.commons.logging.LogFactory");
            //refreshURLs();
            //ClassLoader changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]),HibernateUtil.class.getClassLoader());
            ClassLoader testLoader = new URLClassLoader((URL[]) URLList.toArray(new URL[0]), pluginLoader);
            //changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]));

            thread.setContextClassLoader(testLoader);
            //Class thwy2 = changeLoader.loadClass("org.hibernate.cfg.Configuration");
            //Class.forName("org.apache.commons.logging.LogFactory", true, changeLoader);
            //Class cls = Class.forName("org.hibernate.cfg.Configuration", true, changeLoader);
            //Configuration cfg=null;
            //cfg = new Configuration();
            //Object oo = cls.newInstance();
            //Configuration cfg = (Configuration)oo;
            Configuration cfg = new Configuration();
            buildConfig(hibfile, mapdir, cfg);

            Class<? extends Driver> driverClass = testLoader
                    .loadClass(cfg.getProperty("connection.driver_class")).asSubclass(Driver.class);
            Driver driver = driverClass.newInstance();
            WrappedDriver wd = new WrappedDriver(driver, cfg.getProperty("connection.driver_class"));

            boolean foundDriver = false;
            Enumeration<Driver> drivers = DriverManager.getDrivers();
            while (drivers.hasMoreElements()) {
                Driver nextDriver = (Driver) drivers.nextElement();
                if (nextDriver.getClass() == wd.getClass()) {
                    if (nextDriver.toString().equals(wd.toString())) {
                        foundDriver = true;
                        break;
                    }
                }
            }
            if (!foundDriver) {

                DriverManager.registerDriver(wd);
            }

            sessionFactory = cfg.buildSessionFactory();
            //configuration = cfg;
            HibernateMapDirectory = mapdir;
            HibernateConfigFile = hibfile;
        } catch (Throwable e) {
            e.printStackTrace();
            throw new HibernateException("No Session Factory Created " + e.getLocalizedMessage(), e);
        } finally {
            thread.setContextClassLoader(oldloader);
        }
    }
}

From source file:com.toolsverse.etl.sql.connection.PooledAliasConnectionProvider.java

@Override
protected Connection createConnection(Alias alias) throws Exception {
    java.sql.Driver driver = (java.sql.Driver) Class.forName(alias.getJdbcDriverClass()).newInstance();

    DriverManager.registerDriver(driver);

    org.apache.commons.dbcp.ConnectionFactory connectionFactory = null;

    Properties props = Utils.getProperties(alias.getParams());

    String userId = alias.getUserId();
    String password = alias.getPassword();

    String url = alias.getUrl();//from w  w  w  . j  a va  2s . c o m

    if (props.size() > 0) {
        if (!Utils.isNothing(userId)) {
            props.put("user", userId);
            if (!Utils.isNothing(password))
                props.put("password", password);
        }

        connectionFactory = new DriverManagerConnectionFactory(url, props);
    } else
        connectionFactory = new DriverManagerConnectionFactory(url, userId, password);

    ObjectPool connectionPool = new GenericObjectPool(null, _config);

    @SuppressWarnings("unused")
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);

    PoolingDataSource poolingDataSource = new PoolingDataSource(connectionPool);

    return poolingDataSource.getConnection();
}