Example usage for org.apache.commons.dbcp BasicDataSource setUsername

List of usage examples for org.apache.commons.dbcp BasicDataSource setUsername

Introduction

In this page you can find the example usage for org.apache.commons.dbcp BasicDataSource setUsername.

Prototype

public synchronized void setUsername(String username) 

Source Link

Document

Sets the #username .

Note: this method currently has no effect once the pool has been initialized.

Usage

From source file:org.wso2.carbon.identity.oauth2.dao.util.DAOUtils.java

public static void initializeDataSource(String databaseName, String scriptPath) throws Exception {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUsername("username");
    dataSource.setPassword("password");
    dataSource.setUrl("jdbc:h2:mem:" + databaseName);

    try (Connection connection = dataSource.getConnection()) {
        connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'");
    }// w w w .  j  ava  2  s  . c o  m
    dataSourceMap.put(databaseName, dataSource);
}

From source file:org.wso2.carbon.identity.openidconnect.DefaultOIDCClaimsCallbackHandlerTest.java

@BeforeClass
public void setUp() throws Exception {

    System.setProperty(CarbonBaseConstants.CARBON_HOME, CARBON_HOME);
    BasicDataSource dataSource1 = new BasicDataSource();
    dataSource1.setDriverClassName("org.h2.Driver");
    dataSource1.setUsername("username");
    dataSource1.setPassword("password");
    dataSource1.setUrl("jdbc:h2:mem:test" + DB_NAME);
    connection = dataSource1.getConnection();
    connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + getFilePath(H2_SCRIPT_NAME) + "'");

    mockStatic(FrameworkUtils.class);
    when(FrameworkUtils.getMultiAttributeSeparator()).thenReturn(MULTI_ATTRIBUTE_SEPARATOR_DEFAULT);

    RequestObjectService requestObjectService = Mockito.mock(RequestObjectService.class);
    List<RequestedClaim> requestedClaims = Collections.emptyList();
    when(requestObjectService.getRequestedClaimsForIDToken(anyString())).thenReturn(requestedClaims);
    when(requestObjectService.getRequestedClaimsForUserInfo(anyString())).thenReturn(requestedClaims);

    // Skipping filtering with user consent.
    // TODO: Remove mocking claims filtering based on consent when fixing https://github.com/wso2/product-is/issues/2676
    OpenIDConnectClaimFilterImpl openIDConnectClaimFilter = spy(new OpenIDConnectClaimFilterImpl());
    when(openIDConnectClaimFilter.getClaimsFilteredByUserConsent(anyMap(), any(AuthenticatedUser.class),
            anyString(), anyString())).thenAnswer(invocation -> invocation.getArguments()[0]);
    OpenIDConnectServiceComponentHolder.getInstance().getOpenIDConnectClaimFilters()
            .add(openIDConnectClaimFilter);

    OpenIDConnectServiceComponentHolder.setRequestObjectService(requestObjectService);
    defaultOIDCClaimsCallbackHandler = new DefaultOIDCClaimsCallbackHandler();

}

From source file:org.wso2.carbon.identity.openidconnect.DefaultOIDCClaimsCallbackHandlerTest.java

private JWTClaimsSet getJwtClaimSet(JWTClaimsSet.Builder jwtClaimsSetBuilder,
        OAuthTokenReqMessageContext requestMsgCtx) {

    OAuthServerConfiguration mockOAuthServerConfiguration = PowerMockito.mock(OAuthServerConfiguration.class);
    DataSource dataSource = mock(DataSource.class);
    mockStatic(JDBCPersistenceManager.class);
    JDBCPersistenceManager jdbcPersistenceManager = mock(JDBCPersistenceManager.class);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(mockOAuthServerConfiguration);
    when(mockOAuthServerConfiguration.isConvertOriginalClaimsFromAssertionsToOIDCDialect()).thenReturn(true);
    JWTClaimsSet jwtClaimsSet = null;//from   ww  w .j  a va 2 s.  c o m

    try {
        if (connection.isClosed()) {

            BasicDataSource dataSource1 = new BasicDataSource();
            dataSource1.setDriverClassName("org.h2.Driver");
            dataSource1.setUsername("username");
            dataSource1.setPassword("password");
            dataSource1.setUrl("jdbc:h2:mem:test" + DB_NAME);
            Connection connection1 = null;
            connection1 = dataSource1.getConnection();
            Mockito.when(dataSource.getConnection()).thenReturn(connection1);

        } else {
            Mockito.when(dataSource.getConnection()).thenReturn(connection);
        }
    } catch (Exception e) {
        log.error("Error while obtaining the datasource. ");
    }

    Mockito.when(jdbcPersistenceManager.getInstance()).thenReturn(jdbcPersistenceManager);
    Mockito.when(jdbcPersistenceManager.getDataSource()).thenReturn(dataSource);
    jwtClaimsSet = defaultOIDCClaimsCallbackHandler.handleCustomClaims(jwtClaimsSetBuilder, requestMsgCtx);

    //return jwtClaimsSet;

    return jwtClaimsSet;
}

From source file:org.wso2.carbon.identity.openidconnect.util.TestUtils.java

public static void initiateH2Base() throws SQLException {

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUsername("username");
    dataSource.setPassword("password");
    dataSource.setUrl("jdbc:h2:mem:test" + DB_NAME);
    Connection connection = dataSource.getConnection();
    connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + getFilePath(H2_SCRIPT_NAME) + "'");

    dataSourceMap.put(DB_NAME, dataSource);
}

From source file:org.wso2.carbon.registry.core.jdbc.utils.RegistryDataSource.java

public RegistryDataSource(DataBaseConfiguration config) {

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setUrl(config.getDbUrl());
    basicDataSource.setDriverClassName(config.getDriverName());
    basicDataSource.setUsername(config.getUserName());
    basicDataSource.setPassword(config.getResolvedPassword());

    if (config.getMaxActive() != null) {
        basicDataSource.setMaxActive(Integer.parseInt(config.getMaxActive()));
    } else {//from  w w w. j a  v a2 s.  c  o m
        basicDataSource.setMaxActive(DEFAULT_MAX_ACTIVE);
    }

    if (config.getMaxWait() != null) {
        basicDataSource.setMaxWait(Integer.parseInt(config.getMaxWait()));
    } else {
        basicDataSource.setMaxWait(DEFAULT_MAX_WAIT);
    }

    if (config.getMaxIdle() != null) {
        basicDataSource.setMaxIdle(Integer.parseInt(config.getMaxIdle()));
    }

    if (config.getMinIdle() != null) {
        basicDataSource.setMinIdle(Integer.parseInt(config.getMinIdle()));
    } else {
        basicDataSource.setMinIdle(DEFAULT_MIN_IDLE);
    }

    this.dataSource = basicDataSource;
}

From source file:org.wso2.carbon.registry.core.test.performance.BasicPerformanceTest.java

public void setUp() {
    //String connURL = "jdbc:log4jdbc:derby:target/REG1_DB";
    //String connURL = "jdbc:derby:target/REG1_DB";
    String connURL = "jdbc:mysql://localhost:3306/registry1";
    BasicDataSource ds = new BasicDataSource();
    //ds.setUrl(connURL + ";");
    //ds.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl(connURL);//from w w  w .j ava 2 s.  c o m
    ds.setUsername("root");
    ds.setPassword("password");

    //        ds.setMaxWait(1000*60*2);

    ds.setMaxActive(150);
    ds.setMaxIdle(1000 * 60 * 2);
    ds.setMinIdle(5);
    //ds.setDriverClassName("net.sf.log4jdbc.DriverSpy");

    //DerbyDatabaseCreator creator = new DerbyDatabaseCreator(ds);
    DatabaseCreator creator = new DatabaseCreator(ds);
    try {
        creator.createRegistryDatabase();
    } catch (Exception e) {
        fail("Failed to create database. Caused by: " + e.getMessage());
    }
    //String fileName = "target/db/registry";
    //File file = new File(fileName);

    //if (! file.exists()) {
    //creator.createDefaultDatabaseTables();
    //}

    //        UserRealm realm = new DefaultRealm();
    //        DefaultRealmConfig config = (DefaultRealmConfig) realm.getBootstrapRealmConfiguration();
    //        config.setConnectionURL(connURL);
    //        realm.init(config);
    //        UserRealm registryRealm = new UserRealm(realm);
    //
    //        InputStream configStream =
    //            Thread.currentThread().getContextClassLoader().getResourceAsStream("registry.xml");
    //        RegistryContext regContext = new RegistryContext(configStream, registryRealm);
    //        embeddedRegistryService = new EmbeddedRegistryService(regContext);
    //        adminRegistry = embeddedRegistryService.getUserRegistry(
    //            RegistryConstants.ADMIN_USER, RegistryConstants.ADMIN_PASSWORD);
    System.out.println("~~~~~setup method done~~~~~");
}

From source file:org.wso2.carbon.registry.migration.utils.DBUtils.java

public static void initializeDB()
        throws APIManagementException, ClassNotFoundException, IllegalAccessException, InstantiationException {

    String dbUrl = CommandHandler.getDBUrl();
    String driver = CommandHandler.getDBDriver();
    String username = CommandHandler.getDBUsername();
    String password = CommandHandler.getDBPassword();
    if (dbUrl == null || driver == null || username == null || password == null) {
        System.out.println("Required DB configuration parameters unspecified. So API Store and API Publisher "
                + "will not work as expected.");
    }/*from  w w w  .j a  v  a2 s  .c o m*/

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(driver);
    basicDataSource.setUrl(dbUrl);
    basicDataSource.setUsername(username);
    basicDataSource.setPassword(password);
    dataSource = basicDataSource;

}

From source file:org.wso2.carbon.user.core.jdbc.JDBCRealmTest.java

public void testAuthorizationClearence() throws Exception {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(UserCoreTestConstants.DB_DRIVER);
    ds.setUrl("jdbc:h2:target/clear-resources/WSO2CARBON_DB_CLEAR");
    ds.setUsername("wso2carbon");
    ds.setPassword("wso2carbon");

    realm = new DefaultRealm();

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(UserCoreConstants.DATA_SOURCE, ds);

    RealmConfigXMLProcessor xmlProcessor = new RealmConfigXMLProcessor();
    InputStream stream = new FileInputStream("target/clear-resources/user-mgt-clear.xml");
    RealmConfiguration configuration = xmlProcessor.buildRealmConfiguration(stream);

    JDBCAuthorizationManager jdbcAuthnManager = new JDBCAuthorizationManager(configuration, properties, null,
            null, realm, 0);//from w  w w  .j a  v  a 2s .c o  m

    String[] roles = jdbcAuthnManager.getAllowedRolesForResource("/permission/admin", "ui.execute");
    assertEquals(roles.length, 1);

    jdbcAuthnManager.clearPermissionTree();

    //the tree should automatically be loaded on next call
    roles = jdbcAuthnManager.getAllowedRolesForResource("/permission/admin", "ui.execute");
    assertEquals(roles.length, 1);
}

From source file:org.wso2.throttle.core.Throttler.java

/**
 * Copies physical ThrottleTable to this instance's in-memory ThrottleTable.
 *//*  w w  w.  j av a  2  s. c  om*/
private void populateThrottleTable() {
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
    basicDataSource.setUrl("jdbc:mysql://localhost/org_wso2_throttle_DataSource");
    basicDataSource.setUsername("root");
    basicDataSource.setPassword("root");

    Connection connection = null;
    try {
        connection = basicDataSource.getConnection();
        DatabaseMetaData dbm = connection.getMetaData();
        // check if "ThrottleTable" table is there
        ResultSet tables = dbm.getTables(null, null, RDBMS_THROTTLE_TABLE_NAME, null);
        if (tables.next()) { // Table exists
            PreparedStatement stmt = connection.prepareStatement("SELECT * FROM " + RDBMS_THROTTLE_TABLE_NAME);
            ResultSet resultSet = stmt.executeQuery();
            while (resultSet.next()) {
                String key = resultSet.getString(RDBMS_THROTTLE_TABLE_COLUMN_KEY);
                Boolean isThrottled = resultSet.getBoolean(RDBMS_THROTTLE_TABLE_COLUMN_ISTHROTTLED);
                try {
                    getGlobalThrottleStreamInputHandler().send(new Object[] { key, isThrottled });
                } catch (InterruptedException e) {
                    log.error("Error occurred while sending an event.", e);
                }
            }
        } else { // Table does not exist
            log.warn("RDBMS ThrottleTable does not exist. Make sure global throttler server is started.");
        }
    } catch (SQLException e) {
        log.error("Error occurred while copying throttle data from global throttler server.", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                log.error("Error occurred while closing database connection.", e);
            }
        }
    }
}

From source file:org.xbib.io.jdbc.SQLConnectionFactory.java

/**
 * Get connection/*www .j a va2  s.com*/
 *
 * @param uri
 *
 * @return an SQL connection
 *
 * @throws java.io.IOException
 */
@Override
public Connection<SQLSession> getConnection(final URI uri) throws IOException {
    this.properties = URIUtil.getPropertiesFromURI(uri);
    Context context = null;
    DataSource ds = null;
    for (String name : new String[] { "jdbc/" + properties.getProperty("host"),
            "java:comp/env/" + properties.getProperty("scheme") + ":" + properties.getProperty("host") + ":"
                    + properties.getProperty("port") }) {
        this.jndiName = name;
        try {
            context = new InitialContext();
            Object o = context.lookup(jndiName);
            if (o instanceof DataSource) {
                logger.info("DataSource ''{}'' found in naming context", jndiName);
                ds = (DataSource) o;
                break;
            } else {
                logger.warn("JNDI object {} not a DataSource class: {} - ignored", jndiName, o.getClass());
            }
        } catch (NameNotFoundException e) {
            logger.warn("DataSource ''{}'' not found in context", jndiName);
        } catch (NamingException e) {
            logger.warn(e.getMessage(), e);
        }
    }
    try {
        if (ds == null) {
            BasicDataSource bsource = new BasicDataSource();
            bsource.setDriverClassName(properties.getProperty("driverClassName"));
            String url = properties.getProperty("jdbcScheme") + properties.getProperty("host") + ":"
                    + properties.getProperty("port")
                    + ("jdbc:oracle:thin:@".equals(properties.getProperty("jdbcScheme")) ? ":" : "/")
                    + properties.getProperty("cluster");
            bsource.setUrl(url);
            if (properties.containsKey("username")) {
                bsource.setUsername(properties.getProperty("username"));
            }
            if (properties.containsKey("password")) {
                bsource.setPassword(properties.getProperty("password"));
            }
            if (properties.containsKey("n")) {
                bsource.setInitialSize(Integer.parseInt(properties.getProperty("n")));
                bsource.setMaxActive(Integer.parseInt(properties.getProperty("n")));
            }
            // Other BasicDataSource settings, not used yet:
            //  setAccessToUnderlyingConnectionAllowed(boolean allow)
            //  setDefaultAutoCommit(boolean defaultAutoCommit)
            //  setDefaultCatalog(String defaultCatalog)
            //  setDefaultReadOnly(boolean defaultReadOnly)
            //  setDefaultTransactionIsolation(int defaultTransactionIsolation)
            //  setLogAbandoned(boolean logAbandoned)
            //  setLoginTimeout(int loginTimeout)
            //  setLogWriter(PrintWriter logWriter)
            //  setMaxIdle(int maxIdle)
            //  setMaxOpenPreparedStatements(int maxOpenStatements)
            //  setMaxWait(long maxWait)
            //  setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis)
            //  setMinIdle(int minIdle)
            //  setNumTestsPerEvictionRun(int numTestsPerEvictionRun)
            //  setPoolPreparedStatements(boolean poolingStatements)
            //  setTestOnBorrow(boolean testOnBorrow)
            //  setTestOnReturn(boolean testOnReturn)
            //  setTestWhileIdle(boolean testWhileIdle)
            //  setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis)
            //  setValidationQuery(String validationQuery)
            context.bind(jndiName, bsource);
            ds = (DataSource) bsource;
        }
    } catch (NamingException e) {
        throw new IOException(e.getMessage());
    }
    try {
        ds.getConnection().setAutoCommit("false".equals(properties.getProperty("autoCommit")) ? false : true);
    } catch (SQLException e) {
        throw new IOException(e.getMessage());
    }
    return new SQLConnection(ds);
}