Java Code Examples for java.util.Properties.remove()

The following are Jave code examples for showing how to use remove() of the java.util.Properties class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: monarch   File: TestBase.java   Source Code and License Vote up 6 votes
/**
 * Get the required cache for server and client.
 *
 * @param props the properties for creating the cache
 * @return the cache
 */
MCache getCache(final Properties props) {
  MCache c;
  if (isServer) {
    try {
      c = MCacheFactory.getAnyInstance();
      c.close();
    } catch (CacheClosedException cce) {
      c = new MCacheFactory(props).set("mcast-port", "0").create();
      CacheServer cs = c.addCacheServer();
      cs.setPort(AvailablePortHelper.getRandomAvailableTCPPort());
      try {
        cs.start();
      } catch (IOException e) {
        System.out.println("Unable to start Cache Server.");
      }
    }
  } else {
    props.remove(DistributionConfig.LOCATORS_NAME);
    c = (MCache) new MClientCacheFactory(props).addPoolLocator(SERVER_HOST, getDUnitLocatorPort()).create();
  }
  return c;
}
 
Example 2
Project: openjdk-jdk10   File: MimeTable.java   Source Code and License Vote up 6 votes
void parse(Properties entries) {
    // first, strip out the platform-specific temp file template
    String tempFileTemplate = (String)entries.get("temp.file.template");
    if (tempFileTemplate != null) {
        entries.remove("temp.file.template");
        MimeTable.tempFileTemplate = tempFileTemplate;
    }

    // now, parse the mime-type spec's
    Enumeration<?> types = entries.propertyNames();
    while (types.hasMoreElements()) {
        String type = (String)types.nextElement();
        String attrs = entries.getProperty(type);
        parse(type, attrs);
    }
}
 
Example 3
Project: OpenJSharp   File: MimeTable.java   Source Code and License Vote up 6 votes
void parse(Properties entries) {
    // first, strip out the platform-specific temp file template
    String tempFileTemplate = (String)entries.get("temp.file.template");
    if (tempFileTemplate != null) {
        entries.remove("temp.file.template");
        MimeTable.tempFileTemplate = tempFileTemplate;
    }

    // now, parse the mime-type spec's
    Enumeration<?> types = entries.propertyNames();
    while (types.hasMoreElements()) {
        String type = (String)types.nextElement();
        String attrs = entries.getProperty(type);
        parse(type, attrs);
    }
}
 
Example 4
Project: lams   File: ConnectionPropertiesImpl.java   Source Code and License Vote up 5 votes
/**
 * Initializes driver properties that come from URL or properties passed to
 * the driver manager.
 * 
 * @param info
 * @throws SQLException
 */
protected void initializeProperties(Properties info) throws SQLException {
    if (info != null) {
        // For backwards-compatibility
        String profileSqlLc = info.getProperty("profileSql");

        if (profileSqlLc != null) {
            info.put("profileSQL", profileSqlLc);
        }

        Properties infoCopy = (Properties) info.clone();

        infoCopy.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
        infoCopy.remove(NonRegisteringDriver.USER_PROPERTY_KEY);
        infoCopy.remove(NonRegisteringDriver.PASSWORD_PROPERTY_KEY);
        infoCopy.remove(NonRegisteringDriver.DBNAME_PROPERTY_KEY);
        infoCopy.remove(NonRegisteringDriver.PORT_PROPERTY_KEY);
        infoCopy.remove("profileSql");

        int numPropertiesToSet = PROPERTY_LIST.size();

        for (int i = 0; i < numPropertiesToSet; i++) {
            java.lang.reflect.Field propertyField = PROPERTY_LIST.get(i);

            try {
                ConnectionProperty propToSet = (ConnectionProperty) propertyField.get(this);

                propToSet.initializeFrom(infoCopy, getExceptionInterceptor());
            } catch (IllegalAccessException iae) {
                throw SQLError.createSQLException(Messages.getString("ConnectionProperties.unableToInitDriverProperties") + iae.toString(),
                        SQLError.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
            }
        }

        postInitialization();
    }
}
 
Example 5
Project: crawler-jsoup-maven   File: PropertyReader.java   Source Code and License Vote up 5 votes
/**
 * 
 * 方法用途和描述: 删除属性文件中的Key数组所对应的键值对
 * 
 * @param propertyFilePath
 *            属性文件路径(包括类路径及文件系统路径)
 * @param key
 *            key数组
 * @return 属性文件对象
 * @author bluetata / [email protected] 2017/03/04
 * @author Name Date(YYYY/MM/dd)
 * @since datasnatch(crawler) version(1.0)
 */
public final static Properties removeValue(String propertyFilePath, String[] key) {
    if (key == null) {
        Log4jUtil.error("key[] is null!");
        return null;
    }
    Properties ppts = _getProperties(propertyFilePath);
    if (ppts == null) {
        return null;
    }
    for (String strKey : key) {
        ppts.remove(strKey);
    }
    return ppts;
}
 
Example 6
Project: monarch   File: SecurityTestUtils.java   Source Code and License Vote up 5 votes
private static void removeJavaProperties(final Properties javaProps) {
  if (javaProps != null) {
    Properties props = System.getProperties();

    for (Iterator iter = javaProps.keySet().iterator(); iter.hasNext();) {
      props.remove(iter.next());
    }

    System.setProperties(props);
  }
}
 
Example 7
Project: dble   File: CacheService.java   Source Code and License Vote up 5 votes
private void createRootLayedCachePool(Properties props) throws Exception {
    String layedCacheType = props.getProperty("layedpool.TableID2DataNodeCacheType");
    String cacheDefault = props.getProperty("layedpool.TableID2DataNodeCache");
    if (cacheDefault != null && layedCacheType != null) {
        throw new java.lang.IllegalArgumentException(
                "invalid cache config, layedpool.TableID2DataNodeCacheType and " +
                        "layedpool.TableID2DataNodeCache don't coexist");
    } else if (cacheDefault == null && layedCacheType == null) {
        return;
    }

    final String rootlayedCacheName = "TableID2DataNodeCache";
    int size = 0;
    int timeOut = 0;
    if (layedCacheType != null) {
        props.remove("layedpool.TableID2DataNodeCacheType");
    } else {
        String value = (String) props.get("layedpool.TableID2DataNodeCache");
        props.remove("layedpool.TableID2DataNodeCache");

        String[] valueItems = value.split(",");
        layedCacheType = valueItems[0];
        size = Integer.parseInt(valueItems[1]);
        timeOut = Integer.parseInt(valueItems[2]);
    }
    createLayeredPool(rootlayedCacheName, layedCacheType, size, timeOut);
}
 
Example 8
Project: oscm   File: UserNotificationIT.java   Source Code and License Vote up 5 votes
/**
 * Execute with a missing body text in the default locale.
 */
@Test(expected = RuntimeException.class)
public void testPrepareMessageText_nullBodyDef() throws Exception {
    Properties unProperties = getProperties(
            getProperiesForComputerName(unPropertiesFilePath));
    unProperties.remove(HandlerUtils.MAIL_BODY + setLocale(Locale.ENGLISH));
    userNotification.prepareMessageText(unProperties);
}
 
Example 9
Project: the-vigilantes   File: CharsetRegressionTest.java   Source Code and License Vote up 5 votes
/**
 * Tests fix for Bug#72630 (18758686), NullPointerException during handshake in some situations
 * 
 * @throws Exception
 */
public void testBug72630() throws Exception {
    // bug is related to authentication plugins, available only in 5.5.7+ 
    if (versionMeetsMinimum(5, 5, 7)) {
        try {
            createUser("'Bug72630User'@'%'", "IDENTIFIED WITH mysql_native_password AS 'pwd'");
            this.stmt.execute("GRANT ALL ON *.* TO 'Bug72630User'@'%'");

            final Properties props = new Properties();
            props.setProperty("user", "Bug72630User");
            props.setProperty("password", "pwd");
            props.setProperty("characterEncoding", "NonexistentEncoding");

            assertThrows(SQLException.class, "Unsupported character encoding 'NonexistentEncoding'.", new Callable<Void>() {
                public Void call() throws Exception {
                    getConnectionWithProps(props);
                    return null;
                }
            });

            props.remove("characterEncoding");
            props.setProperty("passwordCharacterEncoding", "NonexistentEncoding");
            assertThrows(SQLException.class, "Unsupported character encoding 'NonexistentEncoding' for 'passwordCharacterEncoding' or 'characterEncoding'.",
                    new Callable<Void>() {
                        public Void call() throws Exception {
                            getConnectionWithProps(props);
                            return null;
                        }
                    });
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
 
Example 10
Project: BibliotecaPS   File: BaseTestCase.java   Source Code and License Vote up 5 votes
protected void removeHostRelatedProps(Properties props) {
    props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
    props.remove(NonRegisteringDriver.PORT_PROPERTY_KEY);

    int numHosts = Integer.parseInt(props.getProperty(NonRegisteringDriver.NUM_HOSTS_PROPERTY_KEY));

    for (int i = 1; i <= numHosts; i++) {
        props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY + "." + i);
        props.remove(NonRegisteringDriver.PORT_PROPERTY_KEY + "." + i);
    }

    props.remove(NonRegisteringDriver.NUM_HOSTS_PROPERTY_KEY);
}
 
Example 11
Project: monarch   File: DistributionConfigImpl.java   Source Code and License Vote up 5 votes
public void close() {
  // Clear the extra stuff from System properties
  Properties props = System.getProperties();
  props.remove(SECURITY_SYSTEM_PREFIX + SECURITY_PEER_AUTH_INIT);
  props.remove(SECURITY_SYSTEM_PREFIX + SECURITY_PEER_AUTHENTICATOR);

  Iterator iter = security.keySet().iterator();
  while (iter.hasNext()) {
    props.remove(SECURITY_SYSTEM_PREFIX + (String) iter.next());
  }
  System.setProperties(props);
}
 
Example 12
Project: BibliotecaPS   File: NonRegisteringDriver.java   Source Code and License Vote up 4 votes
protected java.sql.Connection connectReplicationConnection(String url, Properties info) throws SQLException {
    Properties parsedProps = parseURL(url, info);

    if (parsedProps == null) {
        return null;
    }

    Properties masterProps = (Properties) parsedProps.clone();
    Properties slavesProps = (Properties) parsedProps.clone();

    // Marker used for further testing later on, also when
    // debugging
    slavesProps.setProperty("com.mysql.jdbc.ReplicationConnection.isSlave", "true");

    int numHosts = Integer.parseInt(parsedProps.getProperty(NUM_HOSTS_PROPERTY_KEY));

    if (numHosts < 2) {
        throw SQLError.createSQLException("Must specify at least one slave host to connect to for master/slave replication load-balancing functionality",
                SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, null);
    }
    List<String> slaveHostList = new ArrayList<String>();
    List<String> masterHostList = new ArrayList<String>();

    String firstHost = masterProps.getProperty(HOST_PROPERTY_KEY + ".1") + ":" + masterProps.getProperty(PORT_PROPERTY_KEY + ".1");

    boolean usesExplicitServerType = NonRegisteringDriver.isHostPropertiesList(firstHost);

    for (int i = 0; i < numHosts; i++) {
        int index = i + 1;

        masterProps.remove(HOST_PROPERTY_KEY + "." + index);
        masterProps.remove(PORT_PROPERTY_KEY + "." + index);
        slavesProps.remove(HOST_PROPERTY_KEY + "." + index);
        slavesProps.remove(PORT_PROPERTY_KEY + "." + index);

        String host = parsedProps.getProperty(HOST_PROPERTY_KEY + "." + index);
        String port = parsedProps.getProperty(PORT_PROPERTY_KEY + "." + index);
        if (usesExplicitServerType) {
            if (isHostMaster(host)) {
                masterHostList.add(host);
            } else {
                slaveHostList.add(host);
            }
        } else {
            if (i == 0) {
                masterHostList.add(host + ":" + port);
            } else {
                slaveHostList.add(host + ":" + port);
            }
        }
    }

    slavesProps.remove(NUM_HOSTS_PROPERTY_KEY);
    masterProps.remove(NUM_HOSTS_PROPERTY_KEY);
    masterProps.remove(HOST_PROPERTY_KEY);
    masterProps.remove(PORT_PROPERTY_KEY);
    slavesProps.remove(HOST_PROPERTY_KEY);
    slavesProps.remove(PORT_PROPERTY_KEY);

    return ReplicationConnectionProxy.createProxyInstance(masterHostList, masterProps, slaveHostList, slavesProps);
}
 
Example 13
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   Source Code and License Vote up 4 votes
/**
 * Tests fix for BUG#61150 - First call to SP
 * fails with "No Database Selected"
 * The workaround introduced in DatabaseMetaData.getCallStmtParameterTypes
 * to fix the bug in server where SHOW CREATE PROCEDURE was not respecting
 * lower-case table names is misbehaving when connection is not attached to
 * database and on non-casesensitive OS.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug61150() throws Exception {
    NonRegisteringDriver driver = new NonRegisteringDriver();
    Properties oldProps = driver.parseURL(BaseTestCase.dbUrl, null);

    String host = driver.host(oldProps);
    int port = driver.port(oldProps);
    StringBuilder newUrlToTestNoDB = new StringBuilder("jdbc:mysql://");
    if (host != null) {
        newUrlToTestNoDB.append(host);
    }
    newUrlToTestNoDB.append(":").append(port).append("/");

    Statement savedSt = this.stmt;

    Properties props = getHostFreePropertiesFromTestsuiteUrl();
    props.remove(NonRegisteringDriver.DBNAME_PROPERTY_KEY);
    Connection conn1 = DriverManager.getConnection(newUrlToTestNoDB.toString(), props);

    this.stmt = conn1.createStatement();
    createDatabase("TST1");
    createProcedure("TST1.PROC", "(x int, out y int)\nbegin\ndeclare z int;\nset z = x+1, y = z;\nend\n");

    CallableStatement cStmt = null;
    cStmt = conn1.prepareCall("{call `TST1`.`PROC`(?, ?)}");
    cStmt.setInt(1, 5);
    cStmt.registerOutParameter(2, Types.INTEGER);

    cStmt.execute();
    assertEquals(6, cStmt.getInt(2));
    cStmt.clearParameters();
    cStmt.close();

    conn1.setCatalog("TST1");
    cStmt = null;
    cStmt = conn1.prepareCall("{call TST1.PROC(?, ?)}");
    cStmt.setInt(1, 5);
    cStmt.registerOutParameter(2, Types.INTEGER);

    cStmt.execute();
    assertEquals(6, cStmt.getInt(2));
    cStmt.clearParameters();
    cStmt.close();

    conn1.setCatalog("mysql");
    cStmt = null;
    cStmt = conn1.prepareCall("{call `TST1`.`PROC`(?, ?)}");
    cStmt.setInt(1, 5);
    cStmt.registerOutParameter(2, Types.INTEGER);

    cStmt.execute();
    assertEquals(6, cStmt.getInt(2));
    cStmt.clearParameters();
    cStmt.close();

    this.stmt = savedSt;
}
 
Example 14
Project: the-vigilantes   File: ConnectionRegressionTest.java   Source Code and License Vote up 4 votes
public void testAutoCommitLB() throws Exception {
    Properties props = new Properties();
    props.setProperty("loadBalanceStrategy", CountingReBalanceStrategy.class.getName());
    props.setProperty("loadBalanceAutoCommitStatementThreshold", "3");

    String portNumber = new NonRegisteringDriver().parseURL(dbUrl, null).getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);

    if (portNumber == null) {
        portNumber = "3306";
    }

    Connection conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(true);
    CountingReBalanceStrategy.resetTimesRebalanced();
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 3");
    assertEquals(1, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.setAutoCommit(false);
    CountingReBalanceStrategy.resetTimesRebalanced();
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.close();

    props.remove("loadBalanceAutoCommitStatementThreshold");
    conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(true);
    CountingReBalanceStrategy.resetTimesRebalanced();
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.setAutoCommit(false);
    CountingReBalanceStrategy.resetTimesRebalanced();
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.close();

    props.setProperty("loadBalanceAutoCommitStatementThreshold", "3");
    props.setProperty("loadBalanceAutoCommitStatementRegex", ".*2.*");
    conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(true);
    CountingReBalanceStrategy.resetTimesRebalanced();
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    conn2.createStatement().execute("SELECT 2");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 2");
    assertEquals(1, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.close();

}
 
Example 15
Project: BibliotecaPS   File: ConnectionRegressionTest.java   Source Code and License Vote up 4 votes
/**
 * Tests fix for BUG#6966, connections starting up failed-over (due to down
 * master) never retry master.
 * 
 * @throws Exception
 *             if the test fails...Note, test is timing-dependent, but
 *             should work in most cases.
 */
public void testBug6966() throws Exception {
    Properties props = new Driver().parseURL(BaseTestCase.dbUrl, null);
    props.setProperty("autoReconnect", "true");
    props.setProperty("socketFactory", "testsuite.UnreliableSocketFactory");

    Properties urlProps = new NonRegisteringDriver().parseURL(dbUrl, null);

    String host = urlProps.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
    String port = urlProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);

    props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
    props.remove(NonRegisteringDriver.NUM_HOSTS_PROPERTY_KEY);
    props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY + ".1");
    props.remove(NonRegisteringDriver.PORT_PROPERTY_KEY + ".1");

    props.setProperty("queriesBeforeRetryMaster", "50");
    props.setProperty("maxReconnects", "1");

    UnreliableSocketFactory.mapHost("master", host);
    UnreliableSocketFactory.mapHost("slave", host);
    UnreliableSocketFactory.downHost("master");

    Connection failoverConnection = null;

    try {
        failoverConnection = getConnectionWithProps("jdbc:mysql://master:" + port + ",slave:" + port + "/", props);
        failoverConnection.setAutoCommit(false);

        String originalConnectionId = getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()").toString();

        for (int i = 0; i < 50; i++) {
            this.rs = failoverConnection.createStatement().executeQuery("SELECT 1");
        }

        UnreliableSocketFactory.dontDownHost("master");

        failoverConnection.setAutoCommit(true);

        String newConnectionId = getSingleIndexedValueWithQuery(failoverConnection, 1, "SELECT CONNECTION_ID()").toString();

        assertEquals("/master", UnreliableSocketFactory.getHostFromLastConnection());
        assertFalse(newConnectionId.equals(originalConnectionId));

        this.rs = failoverConnection.createStatement().executeQuery("SELECT 1");
    } finally {
        UnreliableSocketFactory.flushAllStaticData();

        if (failoverConnection != null) {
            failoverConnection.close();
        }
    }
}
 
Example 16
Project: BibliotecaPS   File: ConnectionRegressionTest.java   Source Code and License Vote up 4 votes
public void testAutoCommitLB() throws Exception {
    Properties props = new Properties();
    props.setProperty("loadBalanceStrategy", CountingReBalanceStrategy.class.getName());
    props.setProperty("loadBalanceAutoCommitStatementThreshold", "3");

    String portNumber = new NonRegisteringDriver().parseURL(dbUrl, null).getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);

    if (portNumber == null) {
        portNumber = "3306";
    }

    Connection conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(true);
    CountingReBalanceStrategy.resetTimesRebalanced();
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 3");
    assertEquals(1, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.setAutoCommit(false);
    CountingReBalanceStrategy.resetTimesRebalanced();
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.close();

    props.remove("loadBalanceAutoCommitStatementThreshold");
    conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(true);
    CountingReBalanceStrategy.resetTimesRebalanced();
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.setAutoCommit(false);
    CountingReBalanceStrategy.resetTimesRebalanced();
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.close();

    props.setProperty("loadBalanceAutoCommitStatementThreshold", "3");
    props.setProperty("loadBalanceAutoCommitStatementRegex", ".*2.*");
    conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(true);
    CountingReBalanceStrategy.resetTimesRebalanced();
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    conn2.createStatement().execute("SELECT 2");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 2");
    assertEquals(1, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.close();

}
 
Example 17
Project: OpenVertretung   File: ConnectionRegressionTest.java   Source Code and License Vote up 4 votes
public void testAutoCommitLB() throws Exception {
    Properties props = new Properties();
    props.setProperty("loadBalanceStrategy", CountingReBalanceStrategy.class.getName());
    props.setProperty("loadBalanceAutoCommitStatementThreshold", "3");

    String portNumber = new NonRegisteringDriver().parseURL(dbUrl, null).getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);

    if (portNumber == null) {
        portNumber = "3306";
    }

    Connection conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(true);
    CountingReBalanceStrategy.resetTimesRebalanced();
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 3");
    assertEquals(1, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.setAutoCommit(false);
    CountingReBalanceStrategy.resetTimesRebalanced();
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.close();

    props.remove("loadBalanceAutoCommitStatementThreshold");
    conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(true);
    CountingReBalanceStrategy.resetTimesRebalanced();
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.setAutoCommit(false);
    CountingReBalanceStrategy.resetTimesRebalanced();
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.close();

    props.setProperty("loadBalanceAutoCommitStatementThreshold", "3");
    props.setProperty("loadBalanceAutoCommitStatementRegex", ".*2.*");
    conn2 = this.getUnreliableLoadBalancedConnection(new String[] { "first", "second" }, props);
    conn2.setAutoCommit(true);
    CountingReBalanceStrategy.resetTimesRebalanced();
    conn2.createStatement().execute("SELECT 1");
    conn2.createStatement().execute("SELECT 2");
    conn2.createStatement().execute("SELECT 3");
    conn2.createStatement().execute("SELECT 2");
    assertEquals(0, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.createStatement().execute("SELECT 2");
    assertEquals(1, CountingReBalanceStrategy.getTimesRebalanced());
    conn2.close();

}
 
Example 18
Project: jdk8u-jdk   File: LoadAndStoreXMLWithDefaults.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws IOException {
    Properties p1 = new Properties();
    p1.setProperty("p1.prop", "prop1-p1");
    p1.setProperty("p1.and.p2.prop", "prop2-p1");
    p1.setProperty("p1.and.p2.and.p3.prop", "prop3-p1");
    Properties p2 = new Properties(p1);
    p2.setProperty("p2.prop", "prop4-p2");
    p2.setProperty("p1.and.p2.prop", "prop5-p2");
    p2.setProperty("p1.and.p2.and.p3.prop", "prop6-p2");
    p2.setProperty("p2.and.p3.prop", "prop7-p2");
    Properties p3 = new Properties(p2);
    p3.setProperty("p3.prop", "prop8-p3");
    p3.setProperty("p1.and.p2.and.p3.prop", "prop9-p3");
    p3.setProperty("p2.and.p3.prop", "prop10-p3");

    for (StoreMethod m : StoreMethod.values()) {
        System.out.println("Testing with " + m.displayName());
        Properties P1 = m.loadFromXML(m.writeToXML(p1), null);
        Properties P2 = m.loadFromXML(m.writeToXML(p2), P1);
        Properties P3 = m.loadFromXML(m.writeToXML(p3), P2);

        testResults(m, p1, P1, p2, P2, p3, P3);

        // Now check that properties whose keys or values are objects
        // are skipped.

        System.out.println("Testing with " + m.displayName() + " and Objects");
        P1.put("p1.object.prop", Objects.OBJ1);
        P1.put(Objects.OBJ1, "p1.object.prop");
        P1.put("p2.object.prop", "p2.object.prop");
        P2.put("p2.object.prop", Objects.OBJ2);
        P2.put(Objects.OBJ2, "p2.object.prop");
        P3.put("p3.object.prop", Objects.OBJ3);
        P3.put(Objects.OBJ3, "p3.object.prop");

        Properties PP1 = m.loadFromXML(m.writeToXML(P1), null);
        Properties PP2 = m.loadFromXML(m.writeToXML(P2), PP1);
        Properties PP3 = m.loadFromXML(m.writeToXML(P3), PP2);

        p1.setProperty("p2.object.prop", "p2.object.prop");
        try {
            testResults(m, p1, PP1, p2, PP2, p3, PP3);
        } finally {
            p1.remove("p2.object.prop");
        }
    }
}
 
Example 19
Project: lams   File: MysqlDataSource.java   Source Code and License Vote up 4 votes
/**
 * 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) {
        StringBuilder jdbcUrl = new StringBuilder("jdbc:mysql://");

        if (this.hostName != null) {
            jdbcUrl.append(this.hostName);
        }

        jdbcUrl.append(":");
        jdbcUrl.append(this.port);
        jdbcUrl.append("/");

        if (this.databaseName != null) {
            jdbcUrl.append(this.databaseName);
        }

        jdbcUrlToUse = jdbcUrl.toString();
    } else {
        jdbcUrlToUse = this.url;
    }

    //
    // URL should take precedence over properties
    //

    Properties urlProps = mysqlDriver.parseURL(jdbcUrlToUse, null);
    urlProps.remove(NonRegisteringDriver.DBNAME_PROPERTY_KEY);
    urlProps.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
    urlProps.remove(NonRegisteringDriver.PORT_PROPERTY_KEY);

    Iterator<Object> keys = urlProps.keySet().iterator();

    while (keys.hasNext()) {
        String key = (String) keys.next();

        props.setProperty(key, urlProps.getProperty(key));
    }

    return mysqlDriver.connect(jdbcUrlToUse, props);
}
 
Example 20
Project: ats-framework   File: SkipPropertyMatcher.java   Source Code and License Vote up 4 votes
private void processKeys( String snapshot, Properties props ) {

        List<String> keysToRemove = new ArrayList<>();

        // cycle all property keys
        // it is possible to match more than one key from the file
        for (String keyFromFile : props.stringPropertyNames()) {

            // cycle all match conditions
            for (Entry<String, MATCH_TYPE> matcherEntry : keysMap.entrySet()) {
                if (matcherEntry.getValue().isRegex()) {
                    // regular expression
                    if (keyFromFile.matches(matcherEntry.getKey())) {
                        if (log.isDebugEnabled()) {
                            log.debug("[" + snapshot + "] File " + filePath + ": Removing property '"
                                      + keyFromFile + "=" + props.getProperty(keyFromFile)
                                      + "' as its key matches the '" + matcherEntry.getKey()
                                      + "' regular expression");
                        }

                        keysToRemove.add(keyFromFile);
                        break;
                    }
                } else if (matcherEntry.getValue().isPlainText()) {
                    // just text
                    if (keyFromFile.trim().equalsIgnoreCase(matcherEntry.getKey().trim())) {
                        if (log.isDebugEnabled()) {
                            log.debug("[" + snapshot + "] File " + filePath + ": Removing property '"
                                      + keyFromFile + "=" + props.getProperty(keyFromFile)
                                      + "' as its key equals ignoring case the '" + matcherEntry.getKey()
                                      + "' text");
                        }

                        keysToRemove.add(keyFromFile);
                        break;
                    }

                }
                // if( entry.getValue().isContainingText() )
                else {
                    if (keyFromFile.trim()
                                   .toLowerCase()
                                   .contains(matcherEntry.getKey().trim().toLowerCase())) {
                        if (log.isDebugEnabled()) {
                            log.debug("[" + snapshot + "] File " + filePath + ": Removing property '"
                                      + keyFromFile + "=" + props.getProperty(keyFromFile)
                                      + "' as its key contains ignoring case the '" + matcherEntry.getKey()
                                      + "' text");
                        }

                        keysToRemove.add(keyFromFile);
                        break;
                    }
                }
            }
        }

        // now remove all matched properties
        for (String keyToRemove : keysToRemove) {
            props.remove(keyToRemove);
        }
    }