com.mysql.cj.conf.ConnectionUrl Java Examples

The following examples show how to use com.mysql.cj.conf.ConnectionUrl. 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: SessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public String getUri() {
    PropertySet pset = this.session.getPropertySet();

    StringBuilder sb = new StringBuilder(ConnectionUrl.Type.XDEVAPI_SESSION.getProtocol());
    sb.append("//").append(this.session.getProcessHost()).append(":").append(this.session.getPort()).append("/").append(this.defaultSchemaName).append("?");

    for (String propName : PropertyDefinitions.PROPERTY_NAME_TO_PROPERTY_DEFINITION.keySet()) {
        ReadableProperty<?> propToGet = pset.getReadableProperty(propName);

        String propValue = propToGet.getStringValue();

        if (propValue != null && !propValue.equals(propToGet.getPropertyDefinition().getDefaultValue().toString())) {
            sb.append(",");
            sb.append(propName);
            sb.append("=");
            sb.append(propValue);
        }
    }

    // TODO modify for multi-host connections

    return sb.toString();

}
 
Example #2
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 #3
Source File: FailoverConnectionProxy.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Instantiates a new FailoverConnectionProxy for the given list of hosts and connection properties.
 * 
 * @param connectionUrl
 *            {@link ConnectionUrl} instance containing the lists of hosts available to switch on.
 * @throws SQLException
 *             if an error occurs
 */
private FailoverConnectionProxy(ConnectionUrl connectionUrl) throws SQLException {
    super(connectionUrl);

    JdbcPropertySetImpl connProps = new JdbcPropertySetImpl();
    connProps.initializeProperties(connectionUrl.getConnectionArgumentsAsProperties());

    this.secondsBeforeRetryPrimaryHost = connProps.getIntegerProperty(PropertyKey.secondsBeforeRetryMaster).getValue();
    this.queriesBeforeRetryPrimaryHost = connProps.getIntegerProperty(PropertyKey.queriesBeforeRetryMaster).getValue();
    this.failoverReadOnly = connProps.getBooleanProperty(PropertyKey.failOverReadOnly).getValue();
    this.retriesAllDown = connProps.getIntegerProperty(PropertyKey.retriesAllDown).getValue();

    this.enableFallBackToPrimaryHost = this.secondsBeforeRetryPrimaryHost > 0 || this.queriesBeforeRetryPrimaryHost > 0;

    pickNewConnection();

    this.explicitlyAutoCommit = this.currentConnection.getAutoCommit();
}
 
Example #4
Source File: BaseTestCase.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
protected String getNoDbUrl(String url) throws SQLException {
    Properties props = getPropertiesFromUrl(ConnectionUrl.getConnectionUrlInstance(url, null));
    final String host = props.getProperty(PropertyKey.HOST.getKeyName(), "localhost");
    final String port = props.getProperty(PropertyKey.PORT.getKeyName(), "3306");
    props.remove(PropertyKey.DBNAME.getKeyName());
    removeHostRelatedProps(props);

    final StringBuilder urlBuilder = new StringBuilder("jdbc:mysql://").append(host).append(":").append(port).append("/?");

    Enumeration<Object> keyEnum = props.keys();
    while (keyEnum.hasMoreElements()) {
        String key = (String) keyEnum.nextElement();
        urlBuilder.append(key);
        urlBuilder.append("=");
        urlBuilder.append(props.get(key));
        if (keyEnum.hasMoreElements()) {
            urlBuilder.append("&");
        }
    }
    return urlBuilder.toString();
}
 
Example #5
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 #6
Source File: ConnectionTest.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public void testCannedConfigs() throws Exception {

        Properties cannedProps = ConnectionUrl.getConnectionUrlInstance("jdbc:mysql:///?useConfigs=clusterBase", null).getConnectionArgumentsAsProperties();

        assertTrue("true".equals(cannedProps.getProperty(PropertyKey.autoReconnect.getKeyName())));
        assertTrue("false".equals(cannedProps.getProperty(PropertyKey.failOverReadOnly.getKeyName())));

        // this will fail, but we test that too
        assertThrows(InvalidConnectionAttributeException.class, "Can't find configuration template named 'clusterBase2'", new Callable<Void>() {
            public Void call() throws Exception {
                try {
                    ConnectionUrl.getConnectionUrlInstance("jdbc:mysql:///?useConfigs=clusterBase,clusterBase2", null);
                    return null;
                } catch (Throwable t) {
                    t.printStackTrace();
                    throw t;
                }
            }
        });
    }
 
Example #7
Source File: SessionFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates {@link Session} by given URL.
 * 
 * @param url
 *            the session URL.
 * @return a {@link Session} instance.
 */
public Session getSession(String url) {
    CJCommunicationsException latestException = null;
    ConnectionUrl connUrl = parseUrl(url);
    for (HostInfo hi : connUrl.getHostsList()) {
        try {
            return new SessionImpl(hi);
        } catch (CJCommunicationsException e) {
            latestException = e;
        }
    }
    if (latestException != null) {
        throw latestException;
    }
    return null;
}
 
Example #8
Source File: ConnectionUrlTest.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Tests the {@link ConnectionUrl} with a few wrong connection strings.
 */
@Test
public void testConnectionUrlWithWrongConnectionString() {
    List<String> connStr = new ArrayList<>();
    connStr.add("jdbc:mysql://johndoe:secret@janedoe:secret@myhost:1234/db?key=value");
    connStr.add("jdbc:mysql://johndoe:secret@@myhost:1234/db?key=value");
    connStr.add("jdbc:mysql://johndoe:secret@myhost:abcd/db?key=value");
    connStr.add("jdbc:mysql://johndoe:secret@myhost:1234//db?key=value");
    connStr.add("jdbc:mysql://johndoe:secret@myhost:1234/db??key=value");
    connStr.add("jdbc:mysql://johndoe:secret@myhost:1234/db?=value");

    for (String cs : connStr) {
        try {
            System.out.println(ConnectionUrl.getConnectionUrlInstance(cs, null));
            fail(cs + ": expected to throw a " + WrongArgumentException.class.getName());
        } catch (Exception e) {
            assertTrue(cs + ": expected to throw a " + WrongArgumentException.class.getName(), WrongArgumentException.class.isAssignableFrom(e.getClass()));
        }
    }
}
 
Example #9
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 #10
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 #11
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 #12
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 #13
Source File: FailoverConnectionProxy.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Instantiates a new FailoverConnectionProxy for the given list of hosts and connection properties.
 * 
 * @param hosts
 *            The lists of hosts available to switch on.
 * @param props
 *            The properties to be used in new internal connections.
 */
private FailoverConnectionProxy(ConnectionUrl connectionUrl) throws SQLException {
    super(connectionUrl);

    JdbcPropertySetImpl connProps = new JdbcPropertySetImpl();
    connProps.initializeProperties(connectionUrl.getConnectionArgumentsAsProperties());

    this.secondsBeforeRetryPrimaryHost = connProps.getIntegerReadableProperty(PropertyDefinitions.PNAME_secondsBeforeRetryMaster).getValue();
    this.queriesBeforeRetryPrimaryHost = connProps.getIntegerReadableProperty(PropertyDefinitions.PNAME_queriesBeforeRetryMaster).getValue();
    this.failoverReadOnly = connProps.getBooleanReadableProperty(PropertyDefinitions.PNAME_failOverReadOnly).getValue();
    this.retriesAllDown = connProps.getIntegerReadableProperty(PropertyDefinitions.PNAME_retriesAllDown).getValue();

    this.enableFallBackToPrimaryHost = this.secondsBeforeRetryPrimaryHost > 0 || this.queriesBeforeRetryPrimaryHost > 0;

    pickNewConnection();

    this.explicitlyAutoCommit = this.currentConnection.getAutoCommit();
}
 
Example #14
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 #15
Source File: ConnectionUrlTest.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if the values returned from {@link ConnectionUrl.Type#fromValue(String, int)} are correct.
 */
@Test
public void testTypeEnumCorrectValues() {
    assertEquals(ConnectionUrl.Type.SINGLE_CONNECTION, ConnectionUrl.Type.fromValue("jdbc:mysql:", 1));
    assertEquals(ConnectionUrl.Type.FAILOVER_CONNECTION, ConnectionUrl.Type.fromValue("jdbc:mysql:", 2));
    assertEquals(ConnectionUrl.Type.FAILOVER_CONNECTION, ConnectionUrl.Type.fromValue("jdbc:mysql:", 3));
    assertEquals(ConnectionUrl.Type.LOADBALANCE_CONNECTION, ConnectionUrl.Type.fromValue("jdbc:mysql:loadbalance:", 1));
    assertEquals(ConnectionUrl.Type.LOADBALANCE_CONNECTION, ConnectionUrl.Type.fromValue("jdbc:mysql:loadbalance:", 2));
    assertEquals(ConnectionUrl.Type.REPLICATION_CONNECTION, ConnectionUrl.Type.fromValue("jdbc:mysql:replication:", 1));
    assertEquals(ConnectionUrl.Type.REPLICATION_CONNECTION, ConnectionUrl.Type.fromValue("jdbc:mysql:replication:", 2));
    assertEquals(ConnectionUrl.Type.XDEVAPI_SESSION, ConnectionUrl.Type.fromValue("mysqlx:", 1));
}
 
Example #16
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 #17
Source File: SessionFailoverTest.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Builds a connection string with the given hosts while setting priorities according to their positions.
 * 
 * @param hosts
 *            the hosts list, 1st has priority=100, 2nd has priority=99, and so on
 * @return a single host or a multi-host connection string
 */
private String buildConnectionString(String... hosts) {
    StringBuilder url = new StringBuilder(ConnectionUrl.Type.XDEVAPI_SESSION.getScheme()).append("//");
    url.append(getTestUser()).append(":").append(getTestPassword()).append("@").append("[");
    String separator = "";
    int priority = 100;
    for (String h : hosts) {
        url.append(separator).append("(address=").append(h).append(",priority=").append(priority--).append(")");
        separator = ",";
    }
    url.append("]").append("/").append(getTestDatabase());
    return url.toString();
}
 
Example #18
Source File: SessionFailoverTest.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
private String buildConnectionStringNoUser(String... hosts) {
    StringBuilder url = new StringBuilder(ConnectionUrl.Type.XDEVAPI_SESSION.getScheme()).append("//");
    url.append("[");
    String separator = "";
    int priority = 100;
    for (String h : hosts) {
        url.append(separator).append("(address=").append(h).append(",priority=").append(priority--).append(")");
        separator = ",";
    }
    url.append("]").append("/").append(getTestDatabase());
    return url.toString();
}
 
Example #19
Source File: SessionFactory.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates {@link Session} by given URL.
 * 
 * @param connUrl
 *            the session {@link ConnectionUrl}.
 * @return a {@link Session} instance.
 */
protected Session getSession(ConnectionUrl connUrl) {
    CJCommunicationsException latestException = null;
    for (HostInfo hi : connUrl.getHostsList()) {
        try {
            return new SessionImpl(hi);
        } catch (CJCommunicationsException e) {
            latestException = e;
        }
    }
    if (latestException != null) {
        throw latestException;
    }
    return null;
}
 
Example #20
Source File: BaseTestCase.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
protected Connection getLoadBalancedConnection(int customHostLocation, String customHost, Properties props) throws SQLException {
    if (customHostLocation > 3) {
        throw new IllegalArgumentException();
    }
    Properties urlProps = getHostFreePropertiesFromTestsuiteUrl();
    if (props != null) {
        urlProps.putAll(props);
    }

    /*
     * 1: customHost,defaultHost
     * 2: defaultHost,customHost,defaultHost
     * 3: defaultHost,customHost
     */
    StringJoiner hostsString = new StringJoiner(",");
    if (customHostLocation > 1) {
        hostsString.add(getEncodedHostPortPairFromTestsuiteUrl());
    }
    if (!isNullOrEmpty(customHost)) {
        hostsString.add(customHost);
    }
    if (customHostLocation < 3) {
        hostsString.add(getEncodedHostPortPairFromTestsuiteUrl());
    }

    Connection lbConn = DriverManager.getConnection(ConnectionUrl.Type.LOADBALANCE_CONNECTION.getScheme() + "//" + hostsString, urlProps);
    return lbConn;
}
 
Example #21
Source File: BaseTestCase.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
protected Connection getUnreliableMultiHostConnection(String haMode, String[] hostNames, Properties props, Set<String> downedHosts) throws Exception {
    if (downedHosts == null) {
        downedHosts = new HashSet<>();
    }

    props = getHostFreePropertiesFromTestsuiteUrl(props);
    props.setProperty(PropertyKey.socketFactory.getKeyName(), "testsuite.UnreliableSocketFactory");

    HostInfo defaultHost = mainConnectionUrl.getMainHost();
    String db = defaultHost.getDatabase();
    String port = String.valueOf(defaultHost.getPort());
    String host = defaultHost.getHost();

    UnreliableSocketFactory.flushAllStaticData();

    StringBuilder hostString = new StringBuilder();
    String delimiter = "";
    for (String hostName : hostNames) {
        UnreliableSocketFactory.mapHost(hostName, host);
        hostString.append(delimiter);
        delimiter = ",";
        hostString.append(hostName + ":" + port);

        if (downedHosts.contains(hostName)) {
            UnreliableSocketFactory.downHost(hostName);
        }
    }

    if (haMode == null) {
        haMode = "";
    } else if (haMode.length() > 0) {
        haMode += ":";
    }

    return getConnectionWithProps(ConnectionUrl.Type.FAILOVER_CONNECTION.getScheme() + haMode + "//" + hostString.toString() + "/" + db, props);
}
 
Example #22
Source File: BaseTestCase.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
protected ReplicationConnection getUnreliableReplicationConnection(Set<MockConnectionConfiguration> configs, Properties props) throws Exception {
    props = getHostFreePropertiesFromTestsuiteUrl(props);
    props.setProperty(PropertyKey.socketFactory.getKeyName(), "testsuite.UnreliableSocketFactory");

    HostInfo defaultHost = mainConnectionUrl.getMainHost();
    String db = defaultHost.getDatabase();
    String port = String.valueOf(defaultHost.getPort());
    String host = defaultHost.getHost();

    UnreliableSocketFactory.flushAllStaticData();

    StringBuilder hostString = new StringBuilder();
    String glue = "";
    for (MockConnectionConfiguration config : configs) {
        UnreliableSocketFactory.mapHost(config.hostName, host);
        hostString.append(glue);
        glue = ",";
        if (config.port == null) {
            config.port = (port == null ? "3306" : port);
        }
        hostString.append(config.getAddress());
        if (config.isDowned) {
            UnreliableSocketFactory.downHost(config.hostName);
        }
    }

    return (ReplicationConnection) getConnectionWithProps(ConnectionUrl.Type.REPLICATION_CONNECTION.getScheme() + "//" + hostString.toString() + "/" + db,
            props);
}
 
Example #23
Source File: MultiHostConnectionProxy.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initializes the hosts lists and makes a "clean" local copy of the given connection properties so that it can be later used to create standard
 * connections.
 * 
 * @param connUrl
 *            The connection URL that initialized this multi-host connection.
 * @param hosts
 *            The list of hosts for this multi-host connection.
 * @return
 *         The number of hosts found in the hosts list.
 */
int initializeHostsSpecs(ConnectionUrl connUrl, List<HostInfo> hosts) {
    this.connectionUrl = connUrl;

    Properties props = connUrl.getConnectionArgumentsAsProperties();

    this.autoReconnect = "true".equalsIgnoreCase(props.getProperty(PropertyDefinitions.PNAME_autoReconnect))
            || "true".equalsIgnoreCase(props.getProperty(PropertyDefinitions.PNAME_autoReconnectForPools));

    this.hostsList = new ArrayList<>(hosts);
    int numHosts = this.hostsList.size();
    return numHosts;
}
 
Example #24
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 #25
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 #26
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 #27
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 #28
Source File: SessionImpl.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public String getUri() {
    PropertySet pset = this.session.getPropertySet();

    StringBuilder sb = new StringBuilder(ConnectionUrl.Type.XDEVAPI_SESSION.getScheme());
    sb.append("//").append(this.session.getProcessHost()).append(":").append(this.session.getPort()).append("/").append(this.defaultSchemaName).append("?");

    boolean isFirstParam = true;

    for (PropertyKey propKey : PropertyDefinitions.PROPERTY_KEY_TO_PROPERTY_DEFINITION.keySet()) {
        RuntimeProperty<?> propToGet = pset.getProperty(propKey);
        if (propToGet.isExplicitlySet()) {
            String propValue = propToGet.getStringValue();
            Object defaultValue = propToGet.getPropertyDefinition().getDefaultValue();
            if (defaultValue == null && !StringUtils.isNullOrEmpty(propValue) || defaultValue != null && propValue == null
                    || defaultValue != null && propValue != null && !propValue.equals(defaultValue.toString())) {
                if (isFirstParam) {
                    isFirstParam = false;
                } else {
                    sb.append("&");
                }
                sb.append(propKey.getKeyName());
                sb.append("=");
                sb.append(propValue);
            }

            // TODO custom properties?
        }
    }

    // TODO modify for multi-host connections

    return sb.toString();

}
 
Example #29
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 #30
Source File: MysqlDataSource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the JDBC URL that will be used to create the database connection.
 * 
 * @return the URL for this connection
 */
public String getUrl() {
    if (!this.explicitUrl) {
        StringBuilder sbUrl = new StringBuilder(ConnectionUrl.Type.SINGLE_CONNECTION.getProtocol());
        sbUrl.append("//").append(getServerName()).append(":").append(getPort()).append("/").append(getDatabaseName());
        return sbUrl.toString();
    }
    return this.url;
}