Java Code Examples for com.mysql.cj.conf.ConnectionUrl#getConnectionUrlInstance()

The following examples show how to use com.mysql.cj.conf.ConnectionUrl#getConnectionUrlInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConnectionUrlTest.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Tests fix for BUG#28150662, CONNECTOR/J 8 MALFORMED DATABASE URL EXCEPTION WHIT CORRECT URL STRING.
 */
@Test
public void testBug28150662() {
    List<String> connStr = new ArrayList<>();
    connStr.add(
            "jdbc:mysql://localhost:3306/db1?connectionCollation=utf8mb4_unicode_ci&user=user1&sessionVariables=sql_mode='IGNORE_SPACE,ANSI',FOREIGN_KEY_CHECKS=0");
    connStr.add(
            "jdbc:mysql://localhost:3306/db1?connectionCollation=utf8mb4_unicode_ci&sessionVariables=sql_mode='IGNORE_SPACE,ANSI',FOREIGN_KEY_CHECKS=0&user=user1");
    connStr.add(
            "jdbc:mysql://address=(host=localhost)(port=3306)(connectionCollation=utf8mb4_unicode_ci)(sessionVariables=sql_mode='IGNORE_SPACE,ANSI',FOREIGN_KEY_CHECKS=0)(user=user1)/db1");
    connStr.add(
            "jdbc:mysql://(host=localhost,port=3306,connectionCollation=utf8mb4_unicode_ci,sessionVariables=sql_mode='IGNORE_SPACE%2CANSI'%2CFOREIGN_KEY_CHECKS=0,user=user1)/db1");

    for (String cs : connStr) {
        ConnectionUrl url = ConnectionUrl.getConnectionUrlInstance(cs, null);
        HostInfo hi = url.getMainHost();
        assertEquals("utf8mb4_unicode_ci", hi.getHostProperties().get("connectionCollation"));
        assertEquals("user1", hi.getUser());
        assertEquals("sql_mode='IGNORE_SPACE,ANSI',FOREIGN_KEY_CHECKS=0", hi.getHostProperties().get("sessionVariables"));
    }
}
 
Example 2
Source File: ConnectionUrlTest.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testReplaceLegacyPropertyValues() throws Exception {
    /* Test zeroDateTimeBehavior convertToNull-> CONVERT_TO_NULL replacement (BUG#91421) */
    List<String> connStr = new ArrayList<>();
    connStr.add("jdbc:mysql://somehost:1234/db");
    connStr.add("jdbc:mysql://somehost:1234/db?key=value&zeroDateTimeBehavior=convertToNull");
    connStr.add("jdbc:mysql://127.0.0.1:1234/db");
    connStr.add("jdbc:mysql://127.0.0.1:1234/db?key=value&zeroDateTimeBehavior=convertToNull");
    connStr.add("jdbc:mysql://(port=3306,user=root,password=pwd,zeroDateTimeBehavior=convertToNull)/test");
    connStr.add("jdbc:mysql://address=(port=3306)(user=root)(password=pwd)(zeroDateTimeBehavior=convertToNull)/test");

    Properties props = new Properties();
    props.setProperty(PropertyKey.zeroDateTimeBehavior.getKeyName(), "convertToNull");

    for (String cs : connStr) {
        ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(cs, props);
        assertEquals(ZeroDatetimeBehavior.CONVERT_TO_NULL.name(), connUrl.getMainHost().getProperty(PropertyKey.zeroDateTimeBehavior.getKeyName()));
    }
}
 
Example 3
Source File: MysqlDataSource.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a connection using the specified properties.
 * 
 * @param props
 *            the properties to connect with
 * 
 * @return a connection to the database
 * 
 * @throws SQLException
 *             if an error occurs
 */
protected java.sql.Connection getConnection(Properties props) throws SQLException {
    String jdbcUrlToUse = this.explicitUrl ? this.url : getUrl();

    //
    // URL should take precedence over properties
    //
    ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(jdbcUrlToUse, null);
    Properties urlProps = connUrl.getConnectionArgumentsAsProperties();
    urlProps.remove(PropertyKey.HOST.getKeyName());
    urlProps.remove(PropertyKey.PORT.getKeyName());
    urlProps.remove(PropertyKey.DBNAME.getKeyName());
    urlProps.stringPropertyNames().stream().forEach(k -> props.setProperty(k, urlProps.getProperty(k)));

    return mysqlDriver.connect(jdbcUrlToUse, props);
}
 
Example 4
Source File: ConnectionUrlTest.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Tests default values.
 */
@Test
public void testDefaultValues() {
    Map<String, Integer> connStr = new HashMap<>();
    connStr.put("jdbc:mysql:", 3306);
    connStr.put("jdbc:mysql://,", 3306);
    connStr.put("jdbc:mysql:loadbalance://,", 3306);
    connStr.put("jdbc:mysql:replication://,", 3306);
    connStr.put("mysqlx:", 33060);

    for (String cs : connStr.keySet()) {
        ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(cs, null);
        for (HostInfo hi : connUrl.getHostsList()) {
            assertEquals(cs + "#databaseUrl", cs, hi.getDatabaseUrl());
            assertEquals(cs + "#host", "localhost", hi.getHost());
            assertEquals(cs + "#port", connStr.get(cs).intValue(), hi.getPort());
            assertEquals(cs + "#hostPortPair", "localhost:" + connStr.get(cs), hi.getHostPortPair());
            assertEquals(cs + "#user", "", hi.getUser());
            assertEquals(cs + "#password", "", hi.getPassword());
            assertEquals(cs + "#database", "", hi.getDatabase());
        }
    }
}
 
Example 5
Source File: ConnectionUrlTest.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Tests the connection strings internal cache.
 */
@Test
public void testConnectionStringCache() {
    Properties props1 = new Properties();
    props1.setProperty("propKey", "propValue");
    Properties props2 = new Properties(props1);

    ConnectionUrl cu1 = ConnectionUrl.getConnectionUrlInstance("jdbc:mysql://localhost:3306/?param=value", null);
    ConnectionUrl cu2 = ConnectionUrl.getConnectionUrlInstance("jdbc:mysql://localhost:3306/?param=value", props1);
    ConnectionUrl cu3 = ConnectionUrl.getConnectionUrlInstance("jdbc:mysql://localhost:3306/?param=value", props1);
    ConnectionUrl cu4 = ConnectionUrl.getConnectionUrlInstance("jdbc:mysql://localhost:3306/?param=value", props2);
    ConnectionUrl cu5 = ConnectionUrl.getConnectionUrlInstance("jdbc:mysql://localhost:3306/?param=value&flag", props1);

    assertNotSame(cu1, cu2);
    assertSame(cu2, cu3);
    assertSame(cu3, cu4);
    assertNotSame(cu4, cu5);
    assertNotSame(cu5, cu1);
}
 
Example 6
Source File: BaseTestCase.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a new BaseTestCase object.
 * 
 * @param name
 *            The name of the JUnit test case
 */
public BaseTestCase(String name) {
    super(name);
    this.myInstanceNumber = instanceCount++;

    String newDbUrl = System.getProperty(PropertyDefinitions.SYSP_testsuite_url);

    if ((newDbUrl != null) && (newDbUrl.trim().length() != 0)) {
        dbUrl = newDbUrl;
    }
    mainConnectionUrl = ConnectionUrl.getConnectionUrlInstance(dbUrl, null);
    this.dbName = mainConnectionUrl.getDatabase();

    String defaultSha256Url = System.getProperty(PropertyDefinitions.SYSP_testsuite_url_openssl);

    if ((defaultSha256Url != null) && (defaultSha256Url.trim().length() != 0)) {
        sha256Url = defaultSha256Url;
        sha256ConnectionUrl = ConnectionUrl.getConnectionUrlInstance(sha256Url, null);
    }
}
 
Example 7
Source File: MysqlDataSource.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a connection using the specified properties.
 * 
 * @param props
 *            the properties to connect with
 * 
 * @return a connection to the database
 * 
 * @throws SQLException
 *             if an error occurs
 */
protected java.sql.Connection getConnection(Properties props) throws SQLException {
    String jdbcUrlToUse = null;

    if (!this.explicitUrl) {
        jdbcUrlToUse = getUrl();
    } else {
        jdbcUrlToUse = this.url;
    }

    //
    // URL should take precedence over properties
    //
    ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(jdbcUrlToUse, null);
    if (connUrl.getType() == null) {
        throw SQLError.createSQLException(Messages.getString("MysqlDataSource.BadUrl", new Object[] { jdbcUrlToUse }),
                MysqlErrorNumbers.SQL_STATE_CONNECTION_FAILURE, null);
    }
    Properties urlProps = connUrl.getConnectionArgumentsAsProperties();
    urlProps.remove(PropertyDefinitions.DBNAME_PROPERTY_KEY);
    urlProps.remove(PropertyDefinitions.HOST_PROPERTY_KEY);
    urlProps.remove(PropertyDefinitions.PORT_PROPERTY_KEY);
    urlProps.stringPropertyNames().stream().forEach(k -> props.setProperty(k, urlProps.getProperty(k)));

    return mysqlDriver.connect(jdbcUrlToUse, props);
}
 
Example 8
Source File: TestXDevAPIRequirements.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Session [11]
 * Session.Connect.Single [6]
 * Session.Connect.DataSource [7]
 * Session.Connect.Mysqls [8] [9] - not supported in first version
 * 
 * @throws Exception
 */
@Test
public void testSessionCreation() throws Exception {
    if (!this.isSetForXTests) {
        return;
    }
    Session sess;

    String url = this.baseUrl;
    sess = getSession(url);
    sess.close();

    // TODO test different URLs

    ConnectionUrl conUrl = ConnectionUrl.getConnectionUrlInstance(url, null);

    Properties props = conUrl.getMainHost().exposeAsProperties();
    sess = getSession(props);
    sess.close();

    // test connection without port specification
    props.remove(PropertyKey.PORT.getKeyName());
    sess = getSession(props);
    ConnectionUrl conUrl1 = ConnectionUrl.getConnectionUrlInstance(sess.getUri(), null);
    assertEquals("33060", conUrl1.getMainHost().exposeAsProperties().getProperty(PropertyKey.PORT.getKeyName()));
    sess.close();

    // TODO test different properties
}
 
Example 9
Source File: MySQLBackupProcessor.java    From gocd with Apache License 2.0 5 votes vote down vote up
private ProcessExecutor createProcessExecutor(File targetDir, DbProperties dbProperties) {
    ConnectionUrl connectionUrlInstance = ConnectionUrl.getConnectionUrlInstance(dbProperties.url(), dbProperties.connectionProperties());

    LinkedHashMap<String, String> env = new LinkedHashMap<>();
    if (isNotBlank(dbProperties.password())) {
        env.put("MYSQL_PWD", dbProperties.password());
    }
    // override with any user specified environment
    env.putAll(dbProperties.extraBackupEnv());

    ArrayList<String> argv = new ArrayList<>();
    argv.add("mysqldump");


    String dbName = connectionUrlInstance.getDatabase();
    HostInfo mainHost = connectionUrlInstance.getMainHost();

    if (mainHost != null) {
        argv.add("--host=" + mainHost.getHost());
        argv.add("--port=" + mainHost.getPort());
    }
    if (isNotBlank(dbProperties.user())) {
        argv.add("--user=" + dbProperties.user());
    }

    // append any user specified args for mysqldump
    if (isNotBlank(dbProperties.extraBackupCommandArgs())) {
        Collections.addAll(argv, Commandline.translateCommandline(dbProperties.extraBackupCommandArgs()));
    }

    argv.add("--result-file=" + new File(targetDir, "db." + dbName).toString());
    argv.add(connectionUrlInstance.getDatabase());

    ProcessExecutor processExecutor = new ProcessExecutor();
    processExecutor.redirectOutputAlsoTo(Slf4jStream.of(getClass()).asDebug());
    processExecutor.redirectErrorAlsoTo(Slf4jStream.of(getClass()).asDebug());
    processExecutor.environment(env);
    processExecutor.command(argv);
    return processExecutor;
}
 
Example 10
Source File: ConnectionUrlTest.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Tests the {@link ConnectionUrl} with close to one million of different connection string variations.
 */
@Test
public void testConnectionUrl() {
    Properties props = new Properties();
    props.setProperty("propKey", "propValue");

    for (ConnectionStringGenerator.UrlMode urlMode : ConnectionStringGenerator.UrlMode.values()) {
        ConnectionStringGenerator csg = new ConnectionStringGenerator(urlMode);
        for (String cs : csg) {
            try {
                ConnectionUrl.getConnectionUrlInstance(cs, props);
            } catch (WrongArgumentException e) {
                // X plugin connections ("mysqlx:") don't allow different credentials in different hosts and the generator doesn't account for that.
                assertEquals(cs, ConnectionUrl.Type.XDEVAPI_SESSION.getScheme(), csg.getProtocol());
                boolean first = true;
                boolean ok = false;
                String lastUi = "";
                for (int hostIndex = 0; hostIndex < urlMode.getHostsCount() && !ok; hostIndex++) {
                    if (first) {
                        first = false;
                        lastUi = csg.getUserInfo(hostIndex);
                    } else if (!lastUi.equals(csg.getUserInfo(hostIndex))) {
                        ok = true;
                    }
                }
                if (!ok) {
                    fail(cs + ": unexpected " + e.getClass().getName() + " thrown with message: " + e.getMessage());
                }
            }
        }
    }
}
 
Example 11
Source File: SessionFactory.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parses the connection string URL.
 * 
 * @param url
 *            the connection string URL.
 * @return a {@link ConnectionUrl} instance containing the URL components.
 */
protected ConnectionUrl parseUrl(String url) {
    ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(url, null);
    if (connUrl == null || connUrl.getType() != ConnectionUrl.Type.XDEVAPI_SESSION) {
        throw ExceptionFactory.createException(InvalidConnectionAttributeException.class, "Initialization via URL failed for \"" + url + "\"");
    }
    return connUrl;
}
 
Example 12
Source File: SessionFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses the connection string URL.
 * 
 * @param url
 *            the connection string URL.
 * @return a {@link ConnectionUrl} instance containing the URL components.
 */
private ConnectionUrl parseUrl(String url) {
    ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(url, null);
    if (connUrl.getType() != ConnectionUrl.Type.XDEVAPI_SESSION) {
        throw ExceptionFactory.createException(InvalidConnectionAttributeException.class, "Initialization via URL failed for \"" + url + "\"");
    }
    return connUrl;
}
 
Example 13
Source File: NonRegisteringDriver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Try to make a database connection to the given URL. The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given
 * URL. This will be common, as when the JDBC driverManager is asked to connect to a given URL, it passes the URL to each loaded driver in turn.
 * 
 * <p>
 * The driver should raise an SQLException if the URL is null or if it is the right driver to connect to the given URL, but has trouble connecting to the
 * database.
 * </p>
 * 
 * <p>
 * The java.util.Properties argument can be used to pass arbitrary string tag/value pairs as connection arguments. These properties take precedence over any
 * properties sent in the URL.
 * </p>
 * 
 * <p>
 * MySQL protocol takes the form:
 * 
 * <PRE>
 * jdbc:mysql://host:port/database
 * </PRE>
 * 
 * </p>
 * 
 * @param url
 *            the URL of the database to connect to
 * @param info
 *            a list of arbitrary tag/value pairs as connection arguments
 * 
 * @return a connection to the URL or null if it isn't us
 * 
 * @exception SQLException
 *                if a database access error occurs or the url is {@code null}
 * 
 * @see java.sql.Driver#connect
 */
public java.sql.Connection connect(String url, Properties info) throws SQLException {

    try {
        ConnectionUrl conStr = ConnectionUrl.getConnectionUrlInstance(url, info);
        if (conStr.getType() == null) {
            /*
             * According to JDBC spec:
             * The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL. This will be common, as when the
             * JDBC driver manager is asked to connect to a given URL it passes the URL to each loaded driver in turn.
             */
            return null;
        }

        switch (conStr.getType()) {
            case LOADBALANCE_CONNECTION:
                return LoadBalancedConnectionProxy.createProxyInstance((LoadbalanceConnectionUrl) conStr);

            case FAILOVER_CONNECTION:
                return FailoverConnectionProxy.createProxyInstance(conStr);

            case REPLICATION_CONNECTION:
                return ReplicationConnectionProxy.createProxyInstance((ReplicationConnectionUrl) conStr);

            case XDEVAPI_SESSION:
                // TODO test it
                //return new XJdbcConnection(conStr.getProperties());

            default:
                return com.mysql.cj.jdbc.ConnectionImpl.getInstance(conStr.getMainHost());

        }

    } catch (CJException ex) {
        throw ExceptionFactory.createException(UnableToConnectException.class,
                Messages.getString("NonRegisteringDriver.17", new Object[] { ex.toString() }), ex);
    }
}
 
Example 14
Source File: NonRegisteringDriver.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
    String host = "";
    String port = "";
    String database = "";
    String user = "";
    String password = "";

    if (!isNullOrEmpty(url)) {
        ConnectionUrl connStr = ConnectionUrl.getConnectionUrlInstance(url, info);
        if (connStr.getType() == Type.SINGLE_CONNECTION) {
            HostInfo hostInfo = connStr.getMainHost();
            info = hostInfo.exposeAsProperties();
        }
    }

    if (info != null) {
        host = info.getProperty(PropertyKey.HOST.getKeyName());
        port = info.getProperty(PropertyKey.PORT.getKeyName());
        database = info.getProperty(PropertyKey.DBNAME.getKeyName());
        user = info.getProperty(PropertyKey.USER.getKeyName());
        password = info.getProperty(PropertyKey.PASSWORD.getKeyName());
    }

    DriverPropertyInfo hostProp = new DriverPropertyInfo(PropertyKey.HOST.getKeyName(), host);
    hostProp.required = true;
    hostProp.description = Messages.getString("NonRegisteringDriver.3");

    DriverPropertyInfo portProp = new DriverPropertyInfo(PropertyKey.PORT.getKeyName(), port);
    portProp.required = false;
    portProp.description = Messages.getString("NonRegisteringDriver.7");

    DriverPropertyInfo dbProp = new DriverPropertyInfo(PropertyKey.DBNAME.getKeyName(), database);
    dbProp.required = false;
    dbProp.description = Messages.getString("NonRegisteringDriver.10");

    DriverPropertyInfo userProp = new DriverPropertyInfo(PropertyKey.USER.getKeyName(), user);
    userProp.required = true;
    userProp.description = Messages.getString("NonRegisteringDriver.13");

    DriverPropertyInfo passwordProp = new DriverPropertyInfo(PropertyKey.PASSWORD.getKeyName(), password);
    passwordProp.required = true;
    passwordProp.description = Messages.getString("NonRegisteringDriver.16");

    DriverPropertyInfo[] dpi;
    dpi = new JdbcPropertySetImpl().exposeAsDriverPropertyInfo(info, 5);

    dpi[0] = hostProp;
    dpi[1] = portProp;
    dpi[2] = dbProp;
    dpi[3] = userProp;
    dpi[4] = passwordProp;

    return dpi;
}
 
Example 15
Source File: NonRegisteringDriver.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Try to make a database connection to the given URL. The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given
 * URL. This will be common, as when the JDBC driverManager is asked to connect to a given URL, it passes the URL to each loaded driver in turn.
 * 
 * <p>
 * The driver should raise an SQLException if the URL is null or if it is the right driver to connect to the given URL, but has trouble connecting to the
 * database.
 * </p>
 * 
 * <p>
 * The java.util.Properties argument can be used to pass arbitrary string tag/value pairs as connection arguments. These properties take precedence over any
 * properties sent in the URL.
 * </p>
 * 
 * <p>
 * MySQL protocol takes the form: jdbc:mysql://host:port/database
 * </p>
 * 
 * @param url
 *            the URL of the database to connect to
 * @param info
 *            a list of arbitrary tag/value pairs as connection arguments
 * 
 * @return a connection to the URL or null if it isn't us
 * 
 * @exception SQLException
 *                if a database access error occurs or the url is {@code null}
 */
@Override
public java.sql.Connection connect(String url, Properties info) throws SQLException {

    try {
        if (!ConnectionUrl.acceptsUrl(url)) {
            /*
             * According to JDBC spec:
             * The driver should return "null" if it realizes it is the wrong kind of driver to connect to the given URL. This will be common, as when the
             * JDBC driver manager is asked to connect to a given URL it passes the URL to each loaded driver in turn.
             */
            return null;
        }

        ConnectionUrl conStr = ConnectionUrl.getConnectionUrlInstance(url, info);
        switch (conStr.getType()) {
            case SINGLE_CONNECTION:
                return com.mysql.cj.jdbc.ConnectionImpl.getInstance(conStr.getMainHost());

            case LOADBALANCE_CONNECTION:
                return LoadBalancedConnectionProxy.createProxyInstance((LoadbalanceConnectionUrl) conStr);

            case FAILOVER_CONNECTION:
                return FailoverConnectionProxy.createProxyInstance(conStr);

            case REPLICATION_CONNECTION:
                return ReplicationConnectionProxy.createProxyInstance((ReplicationConnectionUrl) conStr);

            default:
                return null;
        }

    } catch (UnsupportedConnectionStringException e) {
        // when Connector/J can't handle this connection string the Driver must return null
        return null;

    } catch (CJException ex) {
        throw ExceptionFactory.createException(UnableToConnectException.class,
                Messages.getString("NonRegisteringDriver.17", new Object[] { ex.toString() }), ex);
    }
}
 
Example 16
Source File: ConnectionUrlTest.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Tests the usage of a properties transformer.
 */
@Test
public void testPropertiesTransformer() {
    String propsTransClassName = ConnectionPropertiesTest.class.getName();
    List<String> connStr = new ArrayList<>();
    connStr.add("jdbc:mysql://johndoe:secret@mysql:1234/sakila");
    connStr.add("jdbc:mysql://johndoe:secret@mysql:1234/sakila?stars=*");
    connStr.add("jdbc:mysql://johndoe:secret@address=(host=mysql)(port=1234)/sakila");
    connStr.add("jdbc:mysql://johndoe:secret@address=(host=mysql)(port=1234)(stars=*)/sakila");
    connStr.add("jdbc:mysql://johndoe:secret@address=(host=mysql)(port=1234)/sakila?stars=*");
    connStr.add("jdbc:mysql://johndoe:secret@mysql:1234/sakila?propertiesTransform=" + propsTransClassName);
    connStr.add("jdbc:mysql://johndoe:secret@mysql:1234/sakila?stars=*&propertiesTransform=" + propsTransClassName);
    connStr.add("jdbc:mysql://johndoe:secret@address=(host=mysql)(port=1234)(propertiesTransform=" + propsTransClassName + ")/sakila");
    connStr.add("jdbc:mysql://johndoe:secret@address=(host=mysql)(port=1234)(propertiesTransform=" + propsTransClassName + ")(stars=*)/sakila");
    connStr.add("jdbc:mysql://johndoe:secret@address=(host=mysql)(port=1234)(propertiesTransform=" + propsTransClassName + ")/sakila?stars=*");

    for (String cs : connStr) {
        Properties props = new Properties();
        if (cs.indexOf(PropertyKey.propertiesTransform.getKeyName()) == -1) {
            // Send "propertiesTransform" parameter through external properties.
            props.setProperty(PropertyKey.propertiesTransform.getKeyName(), propsTransClassName);
        }
        if (cs.indexOf("stars") == -1) {
            // Send "stars" parameter through external properties.
            props.setProperty("stars", "*");

        }
        ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(cs, props);

        // "propertiesTransform" doesn't apply when set through host internal properties.
        boolean transforms = cs.indexOf("(propertiesTransform") == -1;

        assertEquals(cs + "#hostProps", transforms ? "**" : "*", connUrl.getMainHost().getProperty("stars"));
        if (cs.indexOf("(stars") == -1) {
            assertEquals(cs + "#originalProps", "*", connUrl.getOriginalProperties().get("stars"));
            assertEquals(cs + "#connProps", transforms ? "**" : "*", connUrl.getConnectionArgumentsAsProperties().getProperty("stars"));
        } else {
            assertNull(cs + "#originalProps", connUrl.getOriginalProperties().get("stars"));
            assertNull(cs + "#connProps", connUrl.getConnectionArgumentsAsProperties().getProperty("stars"));
        }
    }
}
 
Example 17
Source File: NonRegisteringDriver.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * The getPropertyInfo method is intended to allow a generic GUI tool to
 * discover what properties it should prompt a human for in order to get
 * enough information to connect to a database.
 * 
 * <p>
 * Note that depending on the values the human has supplied so far, additional values may become necessary, so it may be necessary to iterate through
 * several calls to getPropertyInfo
 * </p>
 * 
 * @param url
 *            the Url of the database to connect to
 * @param info
 *            a proposed list of tag/value pairs that will be sent on
 *            connect open.
 * 
 * @return An array of DriverPropertyInfo objects describing possible
 *         properties. This array may be an empty array if no properties are
 *         required
 * 
 * @exception SQLException
 *                if a database-access error occurs
 * 
 * @see java.sql.Driver#getPropertyInfo
 */
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
    String host = "";
    String port = "";
    String database = "";
    String user = "";
    String password = "";

    if (!isNullOrEmpty(url)) {
        ConnectionUrl connStr = ConnectionUrl.getConnectionUrlInstance(url, info);
        if (connStr.getType() == Type.SINGLE_CONNECTION) {
            HostInfo hostInfo = connStr.getMainHost();
            info = hostInfo.exposeAsProperties();
        }
    }

    if (info != null) {
        host = info.getProperty(PropertyDefinitions.HOST_PROPERTY_KEY);
        port = info.getProperty(PropertyDefinitions.PORT_PROPERTY_KEY);
        database = info.getProperty(PropertyDefinitions.DBNAME_PROPERTY_KEY);
        user = info.getProperty(PropertyDefinitions.PNAME_user);
        password = info.getProperty(PropertyDefinitions.PNAME_password);
    }

    DriverPropertyInfo hostProp = new DriverPropertyInfo(PropertyDefinitions.HOST_PROPERTY_KEY, host);
    hostProp.required = true;
    hostProp.description = Messages.getString("NonRegisteringDriver.3");

    DriverPropertyInfo portProp = new DriverPropertyInfo(PropertyDefinitions.PORT_PROPERTY_KEY, port);
    portProp.required = false;
    portProp.description = Messages.getString("NonRegisteringDriver.7");

    DriverPropertyInfo dbProp = new DriverPropertyInfo(PropertyDefinitions.DBNAME_PROPERTY_KEY, database);
    dbProp.required = false;
    dbProp.description = Messages.getString("NonRegisteringDriver.10");

    DriverPropertyInfo userProp = new DriverPropertyInfo(PropertyDefinitions.PNAME_user, user);
    userProp.required = true;
    userProp.description = Messages.getString("NonRegisteringDriver.13");

    DriverPropertyInfo passwordProp = new DriverPropertyInfo(PropertyDefinitions.PNAME_password, password);
    passwordProp.required = true;
    passwordProp.description = Messages.getString("NonRegisteringDriver.16");

    DriverPropertyInfo[] dpi;
    dpi = new JdbcPropertySetImpl().exposeAsDriverPropertyInfo(info, 5);

    dpi[0] = hostProp;
    dpi[1] = portProp;
    dpi[2] = dbProp;
    dpi[3] = userProp;
    dpi[4] = passwordProp;

    return dpi;
}
 
Example 18
Source File: SessionFactory.java    From FoxTelem with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Creates a {@link Session} using the information contained in the given properties.
 * 
 * @param properties
 *            the {@link Properties} instance that contains the session components.
 * @return a {@link Session} instance.
 */
public Session getSession(Properties properties) {
    ConnectionUrl connUrl = ConnectionUrl.getConnectionUrlInstance(ConnectionUrl.Type.XDEVAPI_SESSION.getScheme(), properties);

    return new SessionImpl(connUrl.getMainHost());
}