Example usage for javax.sql DataSource getConnection

List of usage examples for javax.sql DataSource getConnection

Introduction

In this page you can find the example usage for javax.sql DataSource getConnection.

Prototype

Connection getConnection() throws SQLException;

Source Link

Document

Attempts to establish a connection with the data source that this DataSource object represents.

Usage

From source file:org.akhikhl.examples.gretty.hellogretty.MainConfig.java

@Bean
public DataSource dataSource() {
    /* final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
    dsLookup.setResourceRef(true);//from   w ww.java  2s . c o  m
    return dsLookup.getDataSource("jdbc/devcore"); */

    DataSource dataSource = null;
    try {
        InitialContext init = new InitialContext();
        Context env = (Context) init.lookup("java:comp/env");
        dataSource = (DataSource) env.lookup("jdbc/devcore");
        Connection con = dataSource.getConnection();
    } catch (Exception e) {
        logger.error("Exception in dataSource", e);
        throw new RuntimeException(e);
    }
    return dataSource;
}

From source file:com.p6spy.engine.spy.MultipleDataSourceTest.java

private void validateNotSpyEnabled(DataSource ds) throws SQLException {
    assertNotNull("JNDI data source not found", ds);

    // get the connection
    Connection con = ds.getConnection();

    if (ProxyFactory.isProxy(con.getClass())) {
        assertTrue("p6spy proxy is enabled!",
                !(Proxy.getInvocationHandler(con) instanceof P6LogConnectionInvocationHandler));
    }/*from w w  w  .j av a  2 s  .co  m*/

    if (con.getMetaData().getDatabaseProductName().contains("HSQL")) {
        con.createStatement().execute("set database sql syntax ora true");
    }
    con.createStatement().execute("select current_date from dual");
    assertNull(((P6TestLogger) P6LogQuery.getLogger()).getLastEntry());
}

From source file:com.sf.ddao.conn.DataSourceHandler.java

@Override
public Connection createConnection(Context context) throws SQLException {
    DataSource dataSource = dataSourceMap.get(dsName);
    if (dataSource == null) {
        throw new NullPointerException(
                "DataSource with name " + dsName + " should be regstered at " + DataSourceHandler.class);
    }/*from  w ww  .j a  va  2 s . co m*/
    return dataSource.getConnection();
}

From source file:com.thoughtworks.go.server.database.H2Database.java

public void startDatabase() {
    if (systemEnvironment.inDbDebugMode()) {
        if (tcpServer != null) {
            return;
        }/*from   www .  j  a v  a 2 s  . c om*/
        try {
            DataSource ds = createDataSource();
            Connection con = ds.getConnection();
            ResultSet set = con.getMetaData().getTables(null, null, null, null);
            set.next();
            set.close();
            con.close();
            LOG.info("Database is already running.");
            return;
        } catch (Exception e) {
            LOG.info("Database is not running - starting a new one.");
        }
        try {
            LOG.info("Starting h2 server in debug mode : " + "port=" + configuration.getPort() + " baseDir="
                    + systemEnvironment.getDbPath().getCanonicalPath());
            String[] args = { "-tcp", "-tcpAllowOthers", "-tcpPort", String.valueOf(configuration.getPort()),
                    "-baseDir", systemEnvironment.getDbPath().getCanonicalPath() };
            tcpServer = Server.createTcpServer(args);
            tcpServer.start();
        } catch (Exception e) {
            bomb("Could not create database server.", e);
        }
    }
}

From source file:fll.web.admin.CreateUser.java

@Override
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    PreparedStatement addUser = null;
    PreparedStatement checkUser = null;
    ResultSet rs = null;/*from   ww w. j a v  a2 s . c  o m*/
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    try {
        connection = datasource.getConnection();

        final String user = request.getParameter("user");
        final String pass = request.getParameter("pass");
        final String passCheck = request.getParameter("pass_check");
        if (null == pass || null == passCheck || null == user || user.isEmpty() || pass.isEmpty()
                || passCheck.isEmpty()) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>You must enter all information in the form.</p>");
            response.sendRedirect(response.encodeRedirectURL("createUsername.jsp"));
            return;
        }

        if (!pass.equals(passCheck)) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>Password and password check do not match.</p>");
            response.sendRedirect(response.encodeRedirectURL("createUsername.jsp"));
            return;
        }

        checkUser = connection.prepareStatement("SELECT fll_user FROM fll_authentication WHERE fll_user = ?");
        checkUser.setString(1, user);
        rs = checkUser.executeQuery();
        if (rs.next()) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>Username '" + user + "' already exists.</p>");
            response.sendRedirect(response.encodeRedirectURL("createUsername.jsp"));
            return;
        }

        final String hashedPass = DigestUtils.md5Hex(pass);
        addUser = connection
                .prepareStatement("INSERT INTO fll_authentication (fll_user, fll_pass) VALUES(?, ?)");
        addUser.setString(1, user);
        addUser.setString(2, hashedPass);
        addUser.executeUpdate();

        session.setAttribute(SessionAttributes.MESSAGE,
                "<p class='success' id='success-create-user'>Successfully created user '" + user + "'</p>");

        // do a login if not already logged in
        final Collection<String> loginKeys = CookieUtils.findLoginKey(request);
        final String authenticatedUser = Queries.checkValidLogin(connection, loginKeys);
        if (null == authenticatedUser) {
            DoLogin.doLogin(request, response, application, session);
        } else {
            response.sendRedirect(response.encodeRedirectURL("index.jsp"));
        }

    } catch (final SQLException e) {
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(checkUser);
        SQLFunctions.close(addUser);
        SQLFunctions.close(connection);
    }

}

From source file:name.marcelomorales.siqisiqi.bonecp.DataSourceProviderTest.java

@Test
public void testWithDependencyInjector() throws Exception {
    Injector injector = Guice.createInjector(new AbstractModule() {

        @Override//from  www .  j  av  a 2s . c om
        protected void configure() {
            bind(Config.class).toInstance(ConfigFactory.load());
            bind(DataSourceProvider.class).in(Scopes.SINGLETON);
            bind(DataSource.class).toProvider(DataSourceProvider.class).in(Scopes.SINGLETON);
        }
    });

    DataSource dataSource = injector.getInstance(DataSource.class);

    Connection connection = dataSource.getConnection();

    DatabaseMetaData metaData = connection.getMetaData();

    assertEquals("Apache Derby", metaData.getDatabaseProductName());

    connection.close();

    injector.getInstance(DataSourceProvider.class).close();
}

From source file:de.iritgo.aktario.jdbc.StoreUser.java

/**
 * Perform the command.//ww w  .  ja v  a 2 s .  c o  m
 */
public void perform() {
    if (properties.get("id") == null) {
        Log.logError("persist", "StoreUser", "Missing unique id for the user to store");

        return;
    }

    UserRegistry userRegistry = Server.instance().getUserRegistry();
    long userId = ((Long) properties.get("id")).longValue();
    User user = userRegistry.getUser(userId);

    if (user == null) {
        Log.logError("persist", "StoreUser", "Unable to find user with id " + userId);

        return;
    }

    JDBCManager jdbcManager = (JDBCManager) Engine.instance().getManager("persist.JDBCManager");
    DataSource dataSource = jdbcManager.getDefaultDataSource();

    Connection connection = null;
    PreparedStatement stmt = null;

    try {
        connection = dataSource.getConnection();

        stmt = connection.prepareStatement("delete from IritgoUser where id=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        String userSql = "insert into IritgoUser (id, name, password, email) " + " values (?, ?, ?, ?)";

        stmt = connection.prepareStatement(userSql);
        stmt.setLong(1, userId);
        stmt.setString(2, user.getName());
        stmt.setString(3, user.getPassword());
        stmt.setString(4, user.getEmail());
        stmt.execute();
        stmt.close();

        stmt = connection.prepareStatement("delete from IritgoNamedObjects where userId=?");
        stmt.setLong(1, userId);
        stmt.execute();
        stmt.close();

        Log.logVerbose("persist", "StoreUser", "INSERT USER " + userId + " |" + userSql + "|");
    } catch (SQLException x) {
        Log.logError("persist", "StoreUser", "Error while storing user with id " + userId + ": " + x);
    } finally {
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:net.metanotion.multitenant.adminapp.Manager.java

/** This method generates the appropriate predicate to be used by a
{@link net.metanotion.web.concrete.ObjectPrefixDispatcher} to verify whether an HTTP request against a tenant
instance by the currently authenticated user is allowed based on the user's status as either a tenant admin or
tenant owner. This predicated does NOT verify specific ooperations permitted only to owners or verify that the user
has provided their password for operations that require a password to initiate.
   @param adminDS the data source for the administrative web application database.
   @return The predicate to use with the {@link net.metanotion.web.concrete.ObjectPrefixDispatcher}
*///from  w  w w  . j a  v a 2 s. c  om
public static Predicate<Map.Entry<Object, RequestObject>, Exception> tenantUserPermissionPredicate(
        final DataSource adminDS) {
    return new Predicate<Map.Entry<Object, RequestObject>, Exception>() {
        @Override
        public void eval(final Map.Entry<Object, RequestObject> requestInfo) throws Exception {
            logger.debug("auth check on tid {} for uid {}", requestInfo.getKey(), requestInfo.getValue());
            final long tid = Long.parseLong(requestInfo.getValue().get(Constants.TENANT_ID).toString());
            final UserToken user = ((Unknown) requestInfo.getKey()).lookupInterface(UserToken.class);
            try (final Connection conn = adminDS.getConnection()) {
                if (tenantQueries.checkAuth(conn, user.getID(), tid).size() == 0) {
                    throw new SecurityException("Invalid tenant for user.");
                }
            }
        }
    };
}

From source file:no.polaric.aprsdb.DBSession.java

/**
 * Constructor. /*from   w  w w  .j  ava2  s.  c  o  m*/
 * @param dsrc JDBC DataSource object. 
 */
public DBSession(DataSource dsrc, boolean autocommit, Logfile log) {
    try {
        if (_con == null) {
            _log = log;
            _con = dsrc.getConnection();
            _con.setAutoCommit(autocommit);

            /* PostGIS extensions */
            Connection dconn = ((DelegatingConnection) _con).getInnermostDelegate();
            ((org.postgresql.PGConnection) dconn).addDataType("geometry", "org.postgis.PGgeometry");
            ((org.postgresql.PGConnection) dconn).addDataType("box3d", "org.postgis.PGbox3d");
        }
    } catch (Exception e) {
        // FIXME: Re-throw exception here. 
        _log.warn("DbSession", "Cannot open db connection: " + e);
    }
}