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.apimgt.impl.dao.test.APIMgtDAOTest.java

private void initializeDatabase(String configFilePath) {

    InputStream in = null;/*from   w  w w .  j  ava  2 s . co m*/
    try {
        in = FileUtils.openInputStream(new File(configFilePath));
        StAXOMBuilder builder = new StAXOMBuilder(in);
        String dataSource = builder.getDocumentElement().getFirstChildWithName(new QName("DataSourceName"))
                .getText();
        OMElement databaseElement = builder.getDocumentElement().getFirstChildWithName(new QName("Database"));
        String databaseURL = databaseElement.getFirstChildWithName(new QName("URL")).getText();
        String databaseUser = databaseElement.getFirstChildWithName(new QName("Username")).getText();
        String databasePass = databaseElement.getFirstChildWithName(new QName("Password")).getText();
        String databaseDriver = databaseElement.getFirstChildWithName(new QName("Driver")).getText();

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(databaseDriver);
        basicDataSource.setUrl(databaseURL);
        basicDataSource.setUsername(databaseUser);
        basicDataSource.setPassword(databasePass);

        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
        try {
            InitialContext.doLookup("java:/comp/env/jdbc/WSO2AM_DB");
        } catch (NamingException e) {
            InitialContext ic = new InitialContext();
            ic.createSubcontext("java:");
            ic.createSubcontext("java:/comp");
            ic.createSubcontext("java:/comp/env");
            ic.createSubcontext("java:/comp/env/jdbc");

            ic.bind("java:/comp/env/jdbc/WSO2AM_DB", basicDataSource);
        }
    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.apimgt.impl.dao.test.CertificateMgtDaoTest.java

private static void initializeDatabase(String configFilePath)
        throws IOException, XMLStreamException, NamingException {

    InputStream in;/*from w  w  w.ja va2 s  . co  m*/
    in = FileUtils.openInputStream(new File(configFilePath));
    StAXOMBuilder builder = new StAXOMBuilder(in);
    String dataSource = builder.getDocumentElement().getFirstChildWithName(new QName("DataSourceName"))
            .getText();
    OMElement databaseElement = builder.getDocumentElement().getFirstChildWithName(new QName("Database"));
    String databaseURL = databaseElement.getFirstChildWithName(new QName("URL")).getText();
    String databaseUser = databaseElement.getFirstChildWithName(new QName("Username")).getText();
    String databasePass = databaseElement.getFirstChildWithName(new QName("Password")).getText();
    String databaseDriver = databaseElement.getFirstChildWithName(new QName("Driver")).getText();

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(databaseDriver);
    basicDataSource.setUrl(databaseURL);
    basicDataSource.setUsername(databaseUser);
    basicDataSource.setPassword(databasePass);

    // Create initial context
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
    try {
        InitialContext.doLookup("java:/comp/env/jdbc/WSO2AM_DB");
    } catch (NamingException e) {
        InitialContext ic = new InitialContext();
        ic.createSubcontext("java:");
        ic.createSubcontext("java:/comp");
        ic.createSubcontext("java:/comp/env");
        ic.createSubcontext("java:/comp/env/jdbc");

        ic.bind("java:/comp/env/jdbc/WSO2AM_DB", basicDataSource);
    }
}

From source file:org.wso2.carbon.appfactory.core.util.AppFactoryDBUtil.java

public static void initializeDatasource() throws AppFactoryException {
    AppFactoryConfiguration configuration = ServiceHolder.getAppFactoryConfiguration();
    String datasourceName = configuration.getFirstProperty(AppFactoryConstants.DATASOURCE_NAME);
    if (datasourceName != null) {
        InitialContext context;/* www. j  a va  2s  . c o m*/
        try {
            context = new InitialContext();
        } catch (NamingException e) {
            String msg = "Could get JNDI initial context.Unable to get datasource for appfactory";
            log.error(msg, e);
            throw new AppFactoryException(msg, e);
        }
        try {
            AppFactoryDBUtil.dataSource = (DataSource) context.lookup(datasourceName);
        } catch (NamingException e) {
            String msg = "Could not found data source " + datasourceName + ".Please make sure the "
                    + "datasource is configured in appfactory.xml";
            log.error(msg, e);
            throw new AppFactoryException(msg, e);
        }
    } else {
        //This is only needed for unit test .
        DBConfiguration dbConfiguration;
        dbConfiguration = getDBConfig(configuration);
        String dbUrl = dbConfiguration.getDbUrl();
        String driver = dbConfiguration.getDriverName();
        String username = dbConfiguration.getUserName();
        String password = dbConfiguration.getPassword();
        if (dbUrl == null || driver == null || username == null || password == null) {
            log.warn("Required DB configuration parameters unspecified. So App Factory "
                    + "will not work as expected.");
        }

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

From source file:org.wso2.carbon.appmgt.impl.utils.APIMgtDBUtil.java

/**
 * Initializes the data source/*from  www  .ja  v  a  2  s .  com*/
 *
 * @throws org.wso2.carbon.appmgt.api.AppManagementException if an error occurs while loading DB configuration
 */
public static void initialize() throws Exception {
    if (dataSource != null) {
        return;
    }
    AppManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration();

    synchronized (APIMgtDBUtil.class) {
        if (dataSource == null) {
            if (log.isDebugEnabled()) {
                log.debug("Initializing data source");
            }
            String dataSourceName = config.getFirstProperty(DATA_SOURCE_NAME);

            if (dataSourceName != null) {
                dataSource = initializeDataSource(dataSourceName);
            } else {
                DBConfiguration configuration = getDBConfig(config);
                String dbUrl = configuration.getDbUrl();
                String driver = configuration.getDriverName();
                String username = configuration.getUserName();
                String password = configuration.getPassword();
                if (dbUrl == null || driver == null || username == null || password == null) {
                    log.warn(
                            "Required DB configuration parameters unspecified. So WebApp Store and WebApp Publisher "
                                    + "will not work as expected.");
                }

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

        // initializing the UI Activity Publish specific data source
        if (uiActivityPublishDataSource == null) {
            if (log.isDebugEnabled()) {
                log.debug("Initializing UI-Activity-Publish data source");
            }
            String dataSourceName = config.getFirstProperty(UI_ACTIVITY_PUBLISH_DATA_SOURCE_NAME);

            if (dataSourceName != null) {
                uiActivityPublishDataSource = initializeDataSource(dataSourceName);
            }
        }
        setupAPIManagerDatabase();
    }
}

From source file:org.wso2.carbon.appmgt.impl.utils.AppMgtDataSourceProvider.java

public static void initialize() throws Exception {
    if (dataSource != null) {
        return;/*from   w w w .j  a  v a2  s .com*/
    }
    AppManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration();

    synchronized (AppMgtDataSourceProvider.class) {
        if (dataSource == null) {
            if (log.isDebugEnabled()) {
                log.debug("Initializing data source");
            }
            String dataSourceName = config.getFirstProperty(AppMConstants.APPM_DATA_SOURCES_STORAGE);

            if (dataSourceName != null) {
                dataSource = initializeDataSource(dataSourceName);
            } else {
                DBConfiguration configuration = getDBConfig(config);
                String dbUrl = configuration.getDbUrl();
                String driver = configuration.getDriverName();
                String username = configuration.getUserName();
                String password = configuration.getPassword();
                if (dbUrl == null || driver == null || username == null || password == null) {
                    log.warn(
                            "Required DB configuration parameters unspecified. So WebApp Store and WebApp Publisher "
                                    + "will not work as expected.");
                }

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

From source file:org.wso2.carbon.core.util.PasswordUpdater.java

private void run(String[] args) {
    String wso2wsasHome = System.getProperty(ServerConstants.CARBON_HOME);
    if (wso2wsasHome == null) {
        wso2wsasHome = new File(".").getAbsolutePath();
        System.setProperty(ServerConstants.CARBON_HOME, wso2wsasHome);
    }/* ww w  . j av a2s . c  o  m*/

    if (args.length == 0) {
        printUsage();
        System.exit(0);
    }

    String dbURL = getParam(DB_URL, args);

    if (dbURL == null || dbURL.indexOf("jdbc:") != 0) {
        System.err.println(" Invalid database DB_URL : " + dbURL);
        printUsage();
        System.exit(0);
    }

    // ------- DB Connection params
    String dbDriver = getParam(DB_DRIVER, args);
    if (dbDriver == null) {
        dbDriver = "org.h2.Driver";
    }
    String dbUsername = getParam(DB_USERNAME, args);
    if (dbUsername == null) {
        dbUsername = "wso2carbon";
    }
    String dbPassword = getParam(DB_PASSWORD, args);
    if (dbPassword == null) {
        dbPassword = "wso2carbon";
    }

    // ------------ Load the DB Driver
    try {
        Class.forName(dbDriver);
    } catch (ClassNotFoundException e) {
        System.err.println(" Database driver [" + dbDriver + "] not found in classpath.");
        System.exit(1);
    }

    // Connect to the database
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(dbURL, dbUsername, dbPassword);
    } catch (Exception e) {
        System.err.println("Cannot connect to database. \n"
                + "Please make sure that the JDBC URL is correct and that you have \n"
                + "stopped WSO2 Carbon before running this script. Root cause is : \n" + e);
        System.exit(1);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // --------- Capture the service username and password
    String username = getParam(USERNAME, args);
    while (username == null || username.trim().length() == 0) {
        System.out.print("Username: ");
        try {
            username = InputReader.readInput();
        } catch (IOException e) {
            System.err.println(" Could not read username : " + e);
            System.exit(1);
        }
    }

    String password = getParam(NEW_PASSWORD, args);
    if (password == null || password.trim().length() == 0) {
        String passwordRepeat = null;
        while (password == null || password.trim().length() == 0) {
            try {
                password = InputReader.readPassword("New password: ");
            } catch (IOException e) {
                System.err.println("Unable to read password : " + e);
                System.exit(1);
            }
        }
        while (passwordRepeat == null || passwordRepeat.trim().length() == 0) {
            try {
                passwordRepeat = InputReader.readPassword("Re-enter new password: ");
            } catch (IOException e) {
                System.err.println("Unable to read re-entered password : " + e);
                System.exit(1);
            }
        }
        if (!password.equals(passwordRepeat)) {
            System.err.println(" Password and re-entered password do not match");
            System.exit(1);
        }
    }

    // DataSource is created to connect to user store DB using input parameters given by user

    BasicDataSource ds = new BasicDataSource();
    ds.setUrl(dbURL);
    ds.setDriverClassName(dbDriver);
    ds.setUsername(dbUsername);
    ds.setPassword(dbPassword);

    try {
        RealmConfiguration realmConfig = new RealmConfigXMLProcessor().buildRealmConfigurationFromFile();
        JDBCUserStoreManager userStore = new JDBCUserStoreManager(ds, realmConfig);
        userStore.doUpdateCredentialByAdmin(username, password);
        System.out.println("Password updated successfully.");
    } catch (UserStoreException ex) {
        System.err.println("Error updating credentials for user " + username + " : " + ex);
    }
}

From source file:org.wso2.carbon.identity.common.testng.MockInitialContextFactory.java

private static BasicDataSource createDb(String dbName, Class clazz, String[] files)
        throws TestCreationException {

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUsername("username");
    dataSource.setPassword("password");
    dataSource.setUrl("jdbc:h2:mem:test" + dbName);
    try (Connection connection = dataSource.getConnection()) {
        for (String f : files) {
            File fileFromClasspathResource = getClasspathAccessibleFile(f, clazz);
            String scriptPath = null;
            File tempFile = null;
            if (fileFromClasspathResource != null && fileFromClasspathResource.exists()) {
                scriptPath = fileFromClasspathResource.getAbsolutePath();
            } else {
                //This may be from jar.
                tempFile = copyTempFile(f, clazz);
                scriptPath = tempFile.getAbsolutePath();
            }/*from  w w  w .j  av a  2  s.c om*/
            if (scriptPath != null) {
                try (Statement statement = connection.createStatement()) {
                    statement.executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'"); //NOSONAR
                } catch (SQLException e) {
                    throw new TestCreationException(
                            "Error while loading data to the in-memory H2 Database located from resource : "
                                    + fileFromClasspathResource + "\nabsolute path : " + scriptPath,
                            e);
                }
            }
            if (tempFile != null) {
                tempFile.delete();
            }
        }
        return dataSource;
    } catch (SQLException e) {
        throw new TestCreationException("Error while creating the in-memory H2 Database : ", e);
    }
}

From source file:org.wso2.carbon.identity.oauth.dao.TestOAuthDAOBase.java

protected void initiateH2Base(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:test" + databaseName);
    try (Connection connection = dataSource.getConnection()) {
        connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'");
    }//from  w  ww  .  jav a 2 s  .  c o  m
    dataSourceMap.put(databaseName, dataSource);
}

From source file:org.wso2.carbon.identity.oauth.endpoint.user.impl.TestUtils.java

public static void initiateH2Base() throws Exception {

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUsername("username");
    dataSource.setPassword("password");
    dataSource.setUrl("jdbc:h2:mem:test" + DB_NAME);
    try (Connection connection = dataSource.getConnection()) {
        connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + getFilePath(H2_SCRIPT_NAME) + "'");
    }/*from   ww  w  .  j  a  va2 s  . c om*/
    dataSourceMap.put(DB_NAME, dataSource);
}

From source file:org.wso2.carbon.identity.oauth.endpoint.util.TestOAthEndpointBase.java

protected void initiateInMemoryH2() throws Exception {
    BasicDataSource dataSource = new BasicDataSource();

    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUsername("username");
    dataSource.setPassword("password");
    dataSource.setUrl("jdbc:h2:mem:test");

    connection = dataSource.getConnection();
    connection.createStatement().executeUpdate("RUNSCRIPT FROM 'src/test/resources/dbscripts/h2.sql'");
}