Example usage for org.springframework.jdbc.datasource DataSourceUtils getConnection

List of usage examples for org.springframework.jdbc.datasource DataSourceUtils getConnection

Introduction

In this page you can find the example usage for org.springframework.jdbc.datasource DataSourceUtils getConnection.

Prototype

public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException 

Source Link

Document

Obtain a Connection from the given DataSource.

Usage

From source file:org.syncope.core.init.ContentLoader.java

@Transactional
public void load() {
    // 0. DB connection, to be used below
    Connection conn = DataSourceUtils.getConnection(dataSource);

    // 1. Check wether we are allowed to load default content into the DB
    Statement statement = null;/*w w  w  .j  a v  a 2  s . c  o  m*/
    ResultSet resultSet = null;
    boolean existingData = false;
    try {
        statement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

        resultSet = statement.executeQuery("SELECT * FROM " + SyncopeConf.class.getSimpleName());
        resultSet.last();

        existingData = resultSet.getRow() > 0;
    } catch (SQLException e) {
        LOG.error("Could not access to table " + SyncopeConf.class.getSimpleName(), e);

        // Setting this to true make nothing to be done below
        existingData = true;
    } finally {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            LOG.error("While closing SQL result set", e);
        }
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            LOG.error("While closing SQL statement", e);
        }
    }

    if (existingData) {
        LOG.info("Data found in the database, leaving untouched");
        return;
    }

    LOG.info("Empty database found, loading default content");

    // 2. Create views
    LOG.debug("Creating views");
    try {
        InputStream viewsStream = getClass().getResourceAsStream("/views.xml");
        Properties views = new Properties();
        views.loadFromXML(viewsStream);

        for (String idx : views.stringPropertyNames()) {
            LOG.debug("Creating view {}", views.get(idx).toString());

            try {
                statement = conn.createStatement();
                statement.executeUpdate(views.get(idx).toString().replaceAll("\\n", " "));
                statement.close();
            } catch (SQLException e) {
                LOG.error("Could not create view ", e);
            }
        }

        LOG.debug("Views created, go for indexes");
    } catch (Throwable t) {
        LOG.error("While creating views", t);
    }

    // 3. Create indexes
    LOG.debug("Creating indexes");
    try {
        InputStream indexesStream = getClass().getResourceAsStream("/indexes.xml");
        Properties indexes = new Properties();
        indexes.loadFromXML(indexesStream);

        for (String idx : indexes.stringPropertyNames()) {
            LOG.debug("Creating index {}", indexes.get(idx).toString());

            try {
                statement = conn.createStatement();
                statement.executeUpdate(indexes.get(idx).toString());
                statement.close();
            } catch (SQLException e) {
                LOG.error("Could not create index ", e);
            }
        }

        LOG.debug("Indexes created, go for default content");
    } catch (Throwable t) {
        LOG.error("While creating indexes", t);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    try {
        conn.close();
    } catch (SQLException e) {
        LOG.error("While closing SQL connection", e);
    }

    // 4. Load default content
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        parser.parse(getClass().getResourceAsStream("/content.xml"), importExport);
        LOG.debug("Default content successfully loaded");
    } catch (Throwable t) {
        LOG.error("While loading default content", t);
    }
}

From source file:xyz.vopen.passport.commons.jdbc.JdbcTemplate.java

/**
 * ????Spring??
 *
 * @return
 */
private Connection getConnection() {
    return DataSourceUtils.getConnection(this.getDataSource());
}

From source file:org.gallery.persist.ImageDaoTest.java

@Before
public void setUp() throws DatabaseUnitException, SQLException, IOException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL url = loader.getResource(jsonfilename);
    file = new File(url.getFile());

    ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:applicationContext-test.xml");
    Connection connection = DataSourceUtils.getConnection((DataSource) ctx.getBean("dataSource"));
    DatabaseConnection dbunitConnection = new DatabaseConnection(connection, null);
    IDataSet expectedDataSet = getDataSet("data-test/full-database.xml");
    DatabaseOperation.CLEAN_INSERT.execute(dbunitConnection, expectedDataSet);
    imageDao = ctx.getBean(ImageDao.class);
}

From source file:org.dalesbred.integration.spring.SpringConfigurationTest.java

@Test
public void dalesbredUsesConnectionBoundToSpringTransactions() {
    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SimpleConfiguration.class);
    DataSource dataSource = ctx.getBean(DataSource.class);
    Database db = ctx.getBean(Database.class);

    new TransactionTemplate(new DataSourceTransactionManager(dataSource))
            .execute(status -> db.withTransaction(Propagation.MANDATORY, tx -> {
                assertThat(tx.getConnection(), is(DataSourceUtils.getConnection(dataSource)));
                return "ok";
            }));//from  ww  w  .ja  v  a  2 s . com
}

From source file:com.br.helpdesk.repository.MenuRepositoryTest.java

@Before
public void setupDB() throws Exception {
    FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
    builder.setColumnSensing(true);//from   w ww .ja  va2  s  .com
    Connection con = DataSourceUtils.getConnection(dataSource);
    IDatabaseConnection dbUnitCon = new DatabaseConnection(con);
    IDataSet dataSet = builder.build(new File("src/main/resources/com/br/helpdesk/repository/MenuData.xml"));
    ReplacementDataSet replacementDataSet = new ReplacementDataSet(dataSet);
    replacementDataSet.addReplacementObject("[NULL]", null);
    DatabaseOperation.CLEAN_INSERT.execute(dbUnitCon, replacementDataSet);
    DataSourceUtils.releaseConnection(con, dataSource);
}

From source file:fi.hsl.parkandride.config.JdbcConfiguration.java

@Bean
public Provider<Connection> connectionProvider() {
    return () -> {
        Connection conn = DataSourceUtils.getConnection(dataSource);
        if (!DataSourceUtils.isConnectionTransactional(conn, dataSource)) {
            throw new RuntimeException("Connection should be transactional");
        }/* w  w w.  j  a  v  a2  s . co m*/
        return conn;
    };
}

From source file:com.chillenious.common.db.jooq.SpringConnectionProvider.java

@Override
public Connection acquire() throws DataAccessException {
    return DataSourceUtils.getConnection(dataSource);
}

From source file:com.glaf.base.test.service.MxMixFeatureTestService.java

@Transactional
public void run() {
    log.debug("-------------------start run-------------------");
    for (int i = 0; i < 2; i++) {
        SysLog bean = new SysLog();
        bean.setAccount("test");
        bean.setIp("127.0.0.1");
        bean.setOperate("add");
        sysLogService.create(bean);//from   w ww  .  j  a v a2 s .  c  o  m
    }

    String sql = "insert into SYS_LOG(ID, ACCOUNT, IP, CREATETIME, MODULEID, OPERATE, FLAG, TIMEMS) values (?, ?, ?, ?, ?, ?, ?, ?) ";
    Connection connection = null;
    PreparedStatement psmt = null;
    try {
        connection = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
        System.out.println("connection:" + connection.toString());
        psmt = connection.prepareStatement(sql);
        for (int i = 0; i < 2; i++) {
            psmt.setLong(1, idGenerator.nextId());
            psmt.setString(2, "test2");
            psmt.setString(3, "192.168.0.100");
            psmt.setTimestamp(4, DateUtils.toTimestamp(new Date()));
            psmt.setString(5, "xx");
            psmt.setString(6, "Y");
            psmt.setInt(7, 1);
            psmt.setLong(8, i * i);
            psmt.addBatch();
        }
        psmt.executeBatch();
        psmt.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error(ex);
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
    }
    log.debug("-------------------end run-------------------");
}

From source file:org.syncope.buildtools.H2StartStopListener.java

@Override
public void contextInitialized(final ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();

    File workDir = (File) sce.getServletContext().getAttribute("javax.servlet.context.tempdir");
    try {//ww w .  j  a  v a  2 s.  c om
        Server h2TestDb = new Server();
        h2TestDb.runTool("-baseDir", workDir.getAbsolutePath(), "-tcp", "-tcpDaemon", "-web", "-webDaemon",
                "-webPort", sce.getServletContext().getInitParameter("testdb.webport"));

        context.setAttribute(H2_TESTDB, h2TestDb);
    } catch (SQLException e) {
        LOG.error("Could not start H2 test db", e);
    }

    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
    DataSource datasource = ctx.getBean(DataSource.class);

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DataSourceUtils.getConnection(datasource);
        stmt = conn.createStatement();
        stmt.executeUpdate("RUNSCRIPT FROM 'classpath:/testdb.sql'");
    } catch (Exception e) {
        LOG.error("While loading data into testdb", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
        DataSourceUtils.releaseConnection(conn, datasource);
    }
}

From source file:net.tirasa.connid.bundles.soap.wssample.DefaultContentLoader.java

@Override
public void contextInitialized(final ServletContextEvent sce) {
    final WebApplicationContext springContext = WebApplicationContextUtils
            .getWebApplicationContext(sce.getServletContext());

    if (springContext == null) {
        LOG.error("Invalid Spring context");
        return;//  ww  w.  jav  a  2  s  .  co  m
    }

    final DataSource dataSource = springContext.getBean(DataSource.class);
    localDataSource = dataSource;

    final DefaultDataTypeFactory dbUnitDataTypeFactory = (DefaultDataTypeFactory) springContext
            .getBean("dbUnitDataTypeFactory");

    final Connection conn = DataSourceUtils.getConnection(dataSource);

    // create schema
    final StringBuilder statement = new StringBuilder();

    final InputStream dbschema = DefaultContentLoader.class.getResourceAsStream(DBSCHEMA);

    final BufferedReader buff = new BufferedReader(new InputStreamReader(dbschema));

    String line = null;
    try {
        while ((line = buff.readLine()) != null) {
            if (!line.isEmpty() && !line.startsWith("--")) {
                statement.append(line);
            }
        }
    } catch (IOException e) {
        LOG.error("Error reading file " + DBSCHEMA, e);
        return;
    }

    Statement st = null;
    try {
        st = conn.createStatement();
        st.execute(statement.toString());
    } catch (SQLException e) {
        LOG.error("Error creating schema:\n" + statement.toString(), e);
        return;
    } finally {
        try {
            st.close();
        } catch (Throwable t) {
            // ignore exception
        }
    }

    try {
        IDatabaseConnection dbUnitConn = new DatabaseConnection(conn);

        final DatabaseConfig config = dbUnitConn.getConfig();
        config.setProperty("http://www.dbunit.org/properties/datatypeFactory", dbUnitDataTypeFactory);

        boolean existingData = false;
        final IDataSet existingDataSet = dbUnitConn.createDataSet();
        for (final ITableIterator itor = existingDataSet.iterator(); itor.next() && !existingData;) {
            existingData = (itor.getTable().getRowCount() > 0);
        }

        final FlatXmlDataSetBuilder dataSetBuilder = new FlatXmlDataSetBuilder();
        dataSetBuilder.setColumnSensing(true);
        final IDataSet dataSet = dataSetBuilder.build(getClass().getResourceAsStream("/content.xml"));
        DatabaseOperation.REFRESH.execute(dbUnitConn, dataSet);
    } catch (Throwable t) {
        LOG.error("Error loding default content", t);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }
}