Example usage for java.sql Driver connect

List of usage examples for java.sql Driver connect

Introduction

In this page you can find the example usage for java.sql Driver connect.

Prototype

Connection connect(String url, java.util.Properties info) throws SQLException;

Source Link

Document

Attempts to make a database connection to the given URL.

Usage

From source file:com.tacitknowledge.util.migration.jdbc.util.SqlUtil.java

/**
 * Established and returns a connection based on the specified parameters.
 *
 * @param driver the JDBC driver to use//from w  ww.  j a  va 2 s.  c o  m
 * @param url    the database URL
 * @param user   the username
 * @param pass   the password
 * @return a JDBC connection
 * @throws ClassNotFoundException if the driver could not be loaded
 * @throws SQLException           if a connnection could not be made to the database
 */
public static Connection getConnection(String driver, String url, String user, String pass)
        throws ClassNotFoundException, SQLException {
    Connection conn = null;
    try {
        Class.forName(driver);
        log.debug("Getting Connection to " + url);
        conn = DriverManager.getConnection(url, user, pass);
    } catch (Exception e) {
        /* work around for DriverManager 'feature'.  
         * In some cases, the jdbc driver jar is injected into a new 
         * child classloader (for example, maven provides different 
         * class loaders for different build lifecycle phases). 
         * 
         * Since DriverManager uses the calling class' loader instead 
         * of the current context's loader, it fails to find the driver.
         * 
         * Our work around is to give the current context's class loader 
         * a shot at finding the driver in cases where DriverManager fails.  
         * This 'may be' a security hole which is why DriverManager implements 
         * things in such a way that it doesn't use the current thread context class loader.
         */
        try {
            Class driverClass = Class.forName(driver, true, Thread.currentThread().getContextClassLoader());
            Driver driverImpl = (Driver) driverClass.newInstance();
            Properties props = new Properties();
            props.put("user", user);
            props.put("password", pass);
            conn = driverImpl.connect(url, props);
        } catch (InstantiationException ie) {
            log.debug(ie);
            throw new SQLException(ie.getMessage());
        } catch (IllegalAccessException iae) {
            log.debug(iae);
            throw new SQLException(iae.getMessage());
        }
    }

    return conn;
}

From source file:cz.lbenda.dataman.db.DatamanDataSource.java

private Connection createConnection(String username, String password) throws SQLException {
    DatamanConnection connection = connections.get(dbConfig);
    if (connection != null && !connection.isClosed()) {
        scheduleUnconnect(connection);// w  w w. j  ava 2 s.  c o m
        return connection;
    }
    Properties connectionProps = new Properties();
    if (!StringUtils.isEmpty(username)) {
        connectionProps.put("user", username);
    }
    if (!StringUtils.isEmpty(password)) {
        connectionProps.put("password", password);
    }
    Driver driver = getDriver(dbConfig);
    try {
        connection = new DatamanConnection(
                driver.connect(dbConfig.getJdbcConfiguration().getUrl(), connectionProps));
        connection.setConnectionTimeout(dbConfig.getConnectionTimeout());
        connections.put(dbConfig, connection);
        scheduleUnconnect(connection);
        return connection;
    } catch (SQLException e) {
        getLogWriter().print("Filed to create connection");
        e.printStackTrace(getLogWriter());
        onException(e);
        throw e;
    }
}

From source file:com.dx.ss.plugins.ptree.db.JDBCConnectionFactory.java

public Connection getConnection() throws SQLException {
    Driver driver = getDriver();

    Properties props = new Properties();

    if (StringUtils.isNotBlank(user)) {
        props.setProperty("user", user);
    }/* w ww. j a  v  a2  s  .  co  m*/

    if (StringUtils.isNotBlank(password)) {
        props.setProperty("password", password);
    }

    Connection conn = driver.connect(connectionURL, props);

    if (conn == null) {
        throw new SQLException();
    }

    return conn;
}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Instantiates a new database connection with the given driver instance and server address.
 * /*from   ww w  .j a  va2 s  .c o m*/
 * @param address
 *            The server address to connect to.
 * @throws SQLException
 */
public DatabaseConnection(Driver driver, String address) throws SQLException {
    logger.debug("creating new database connection: address=" + address);
    this.address = address;
    connection = driver.connect(address, new Properties());
}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Instantiates a new database connection with the given driver instance, server address, and
 * connection arguments./*from   w  w w  .j  a  v  a 2s .  c o m*/
 * 
 * @param driver
 *            The explicit driver instance to connect with.
 * @param address
 *            The server address to connect to.
 * @param info
 *            A Properties object containing all applicable connection arguments.
 * @throws SQLException
 */
public DatabaseConnection(Driver driver, String address, Properties info) throws SQLException {
    logger.debug("creating new database connection: address=" + address + ", " + info);
    this.address = address;
    connection = driver.connect(address, info);
}

From source file:de.erdesignerng.dialect.Dialect.java

/**
 * Create a connection to a database.//from   w w w  .  j  a v a 2 s. c o  m
 *
 * @param aClassLoader      the classloader
 * @param aDriver         the name of the driver
 * @param aUrl            the url
 * @param aUser           the user
 * @param aPassword        the password
 * @param aPromptForPassword shall be prompted for the password
 * @return the connection
 * @throws ClassNotFoundException is thrown in case of an error
 * @throws InstantiationException is thrown in case of an error
 * @throws IllegalAccessException is thrown in case of an error
 * @throws SQLException         is thrown in case of an error
 */
public Connection createConnection(ClassLoader aClassLoader, String aDriver, String aUrl, String aUser,
        String aPassword, boolean aPromptForPassword)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
    Class<Driver> theDriverClass = (Class<Driver>) aClassLoader.loadClass(aDriver);
    Driver theDriver = theDriverClass.newInstance();

    if (aPromptForPassword) {
        aPassword = DialogUtils.promptForPassword();
        if (aPassword == null) {
            return null;
        }
    }

    Properties theProperties = new Properties();
    theProperties.put("user", aUser);
    theProperties.put("password", aPassword);

    return theDriver.connect(aUrl, theProperties);
}

From source file:net.big_oh.common.jdbc.JdbcDriverProxy.java

public Connection connect(String url, Properties connectionProperties) throws SQLException {
    Driver delegateDriver = lookupDelegateDriver(url);

    if (delegateDriver == null) {
        // return null per the API guidelines
        return null;
    }/*from   ww w . j a  v  a  2s.co m*/

    url = stripJdbcObserverPrefixFromUrl(url);

    ConnectionInstantiationEvent connectionInstantiationEvent = new ConnectionInstantiationEvent(this,
            delegateDriver, url, connectionProperties);

    for (JDBCEventListener listener : listeners) {
        try {
            listener.connectionRequested(connectionInstantiationEvent);
        } catch (RuntimeException rte) {
            logger.error(rte);
        }
    }

    Connection newConnection = delegateDriver.connect(url, connectionProperties);

    if (newConnection == null) {
        throw new SQLException("Failed to connect to url '" + url + "' using delegate driver "
                + delegateDriver.getClass().getName());
    }

    // Create a proxy for the returned connection
    boolean newConnectionInterfacesContainsConnection = Arrays.asList(newConnection.getClass().getInterfaces())
            .contains(Connection.class);
    Class<?>[] interfaces = new Class<?>[(newConnection.getClass().getInterfaces().length
            + ((newConnectionInterfacesContainsConnection) ? 0 : 1))];
    System.arraycopy(newConnection.getClass().getInterfaces(), 0, interfaces, 0,
            newConnection.getClass().getInterfaces().length);
    if (!newConnectionInterfacesContainsConnection) {
        interfaces[newConnection.getClass().getInterfaces().length] = Connection.class;
    }
    Connection connectionProxy = (Connection) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            interfaces, new JdbcObserverProxyConnectionInvocationHandler(newConnection, listeners));

    for (JDBCEventListener listener : listeners) {
        try {
            listener.connectionInstantiated(connectionInstantiationEvent, connectionProxy);
        } catch (RuntimeException rte) {
            logger.error(rte);
        }
    }

    return connectionProxy;
}

From source file:com.jaspersoft.jasperserver.war.action.DataSourceAction.java

public Event testJdbcDataSource(RequestContext context) throws Exception {
    TestJdbcConnectionResponseBuilder response = new TestJdbcConnectionResponseBuilder().failed();
    ReportDataSourceWrapper wrapper = (ReportDataSourceWrapper) getFormObject(context);
    JdbcReportDataSource ds = (JdbcReportDataSource) wrapper.getReportDataSource();

    Connection conn = null;//w  w w.  ja v  a 2 s. c om
    try {
        jdbcDriverService.register(ds.getDriverClass());

        // On edit datasource we set the passwordSubstitution to the passwords form fields
        // If we get the substitution from UI then set the password from original datasource (if it exists)
        if (ds.getPassword().equals(passwordSubstitution)) {
            JdbcReportDataSource existingDs = (JdbcReportDataSource) repository.getResource(null,
                    ds.getURIString());
            if (existingDs != null) {
                ds.setPassword(existingDs.getPassword());
            }
        }
        Properties properties = new Properties();
        properties.put("user", ds.getUsername());
        properties.put("password", ds.getPassword());
        Driver driver = DriverManager.getDriver(ds.getConnectionUrl());
        conn = driver.connect(ds.getConnectionUrl(), properties);
        if (conn != null) {
            response.passed();
        }
    } catch (Exception e) {
        logger.error("exception testing jdbc data source", e);
        response.failed(e);
    } finally {
        if (conn != null)
            conn.close();
    }

    context.getRequestScope().put(AJAX_RESPONSE_MODEL, response.buildJson());
    return success();
}

From source file:net.sf.jasperreports.data.jdbc.JdbcDataAdapterService.java

public Connection getConnection() throws SQLException {
    JdbcDataAdapter jdbcDataAdapter = getJdbcDataAdapter();
    if (jdbcDataAdapter != null) {
        ClassLoader oldThreadClassLoader = Thread.currentThread().getContextClassLoader();

        try {//from  w w w.  j  a va  2s  .c om
            Thread.currentThread().setContextClassLoader(getClassLoader(oldThreadClassLoader));

            Class<?> clazz = JRClassLoader.loadClassForRealName(jdbcDataAdapter.getDriver());
            Driver driver = (Driver) clazz.getDeclaredConstructor().newInstance();

            //            Driver driver = (Driver) (Class.forName(
            //                  jdbcDataAdapter.getDriver(), true, getClassLoader()))
            //                  .getDeclaredConstructor().newInstance();

            Properties connectProps = new Properties();
            Map<String, String> map = jdbcDataAdapter.getProperties();
            if (map != null)
                for (String key : map.keySet())
                    connectProps.setProperty(key, map.get(key));

            String password = jdbcDataAdapter.getPassword();
            SecretsUtil secretService = SecretsUtil.getInstance(getJasperReportsContext());
            if (secretService != null)
                password = secretService.getSecret(SECRETS_CATEGORY, password);

            connectProps.setProperty("user", jdbcDataAdapter.getUsername());
            connectProps.setProperty("password", password);

            connection = driver.connect(jdbcDataAdapter.getUrl(), connectProps);
            if (connection == null) {
                boolean urlValid = driver.acceptsURL(jdbcDataAdapter.getUrl());
                if (!urlValid) {
                    throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_INVALID_URL,
                            new Object[] { jdbcDataAdapter.getUrl(), jdbcDataAdapter.getDriver() });
                }

                throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_CONNECTION_NOT_CREATED,
                        new Object[] { jdbcDataAdapter.getUrl() });
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | NoSuchMethodException | InvocationTargetException e) {
            throw new JRRuntimeException(e);
        } finally {
            Thread.currentThread().setContextClassLoader(oldThreadClassLoader);
        }
        return connection;
    }
    return null;
}

From source file:io.stallion.dataAccess.db.DB.java

/**
 * Intialize the database based on the passed in configuration object.
 * @param config/*from w  w w  . jav a  2  s .c o  m*/
 */
public void initialize(DbConfig config) {
    try {
        dbImplementation = (DbImplementation) StallionClassLoader.loadClass(config.getImplementationClass())
                .newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    // Test out the connection. We do this directly, because if we test via the ComboPooledDataSource
    // exceptions will make the driver hang while retrying, and will also bury the underlying cause

    try {
        Driver driver = (Driver) StallionClassLoader.loadClass(config.getDriverClass()).newInstance();
        Properties props = new Properties();
        props.setProperty("user", config.getUsername());
        props.setProperty("password", config.getPassword());
        try (Connection conn = driver.connect(config.getUrl(), props)) {
            Statement st = conn.createStatement();
            ResultSet results = st.executeQuery("SELECT 1 AS oneCol");
            results.next();
            Long i = results.getLong("oneCol");
            assert i == 1L;
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    ComboPooledDataSource cpds = new ComboPooledDataSource();
    /*
    try {
    try (Connection conn = cpds.getConnection()) {
        Statement st = conn.createStatement();
        ResultSet results = st.executeQuery("SELECT 1");
        Long i = results.getLong(0);
        assert i == 1L;
    }
    } catch (SQLException e) {
    throw new RuntimeException(e);
    }
            
    */
    try {
        cpds.setDriverClass(config.getDriverClass()); //loads the jdbc driver
    } catch (PropertyVetoException e) {
        throw new RuntimeException(e);
    }

    String url = config.getUrl();
    if (!url.contains("?")) {
        url += "?";
    }
    // Assume the database server is in UTC
    if (!url.contains("&useLegacyDatetimeCode=")) {
        url += "&useLegacyDatetimeCode=false";
    }
    if (!url.contains("&serverTimezone=")) {
        url += "&serverTimezone=UTC";
    }
    //&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC

    cpds.setJdbcUrl(url);
    cpds.setUser(config.getUsername());
    cpds.setPassword(config.getPassword());

    if (url.contains("utf8mb4_unicode_ci")) {
        cpds.setConnectionCustomizerClassName("io.stallion.dataAccess.db.mysql.Utf8InitCustomizer");
    }

    cpds.setAcquireRetryAttempts(10);
    cpds.setAcquireRetryDelay(200);
    //cpds.setCheckoutTimeout(1);
    // the settings below are optional -- c3p0 can work with defaults
    cpds.setMinPoolSize(5);
    cpds.setAcquireIncrement(5);
    cpds.setMaxPoolSize(20);
    cpds.setIdleConnectionTestPeriod(5000);
    cpds.setTestConnectionOnCheckin(true);

    this.dataSource = cpds;

    // Make sure the database server time is UTC and in sync with the local server time
    // or else stop execution to prevent nasty and insiduious errors.
    //Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    Timestamp date = this.queryScalar(dbImplementation.getCurrentTimeStampQuery());
    ZonedDateTime now = utcNow();
    ZonedDateTime dbTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.of("UTC"));

    //LocalDateTime now = utcNow().toLocalDateTime();
    ZonedDateTime max = now.plusMinutes(2);
    ZonedDateTime min = now.minusMinutes(2);

    //LocalDateTime dbTime = date.toLocalDateTime();
    if (dbTime.isAfter(max) || dbTime.isBefore(min)) {
        throw new ConfigException(
                "The database CURRENT_TIMESTAMP() is mismatched with the server time. Db time is " + dbTime
                        + ". Server time is " + now
                        + ". Make sure the database server is in UTC and that all your servers clocks are matched. ");
    }

    // Todo: why not lazy load converters???
    registerConverter(new JsonMapConverter());
    registerConverter(new JsonSetConverter());
    registerConverter(new JsonObjectConverter());
    registerConverter(new JsonListConverter());

    this.tickets = dbImplementation.initTicketsService(this);

}