Java Code Examples for org.springframework.jdbc.core.PreparedStatementCallback

The following are top voted examples for showing how to use org.springframework.jdbc.core.PreparedStatementCallback. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 11 votes vote down vote up
public Boolean deleteFile(final String filename, final String key)
		throws FileNotFoundException, IOException {
	String cloudfilesql = "delete CLOUDFILEDATA where FILENAME=?";

	return jdbcTemplate.execute(cloudfilesql,
			new PreparedStatementCallback<Boolean>() {

				@Override
				public Boolean doInPreparedStatement(PreparedStatement ps)
						throws SQLException, DataAccessException {
					ps.setString(1, filename.trim());
					return ps.execute();
				}

			});
}
 
Example 2
Project: class-guard   File: NamedParameterJdbcTemplateTests.java   Source Code and License 8 votes vote down vote up
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 3
Project: bdf2   File: LobStoreServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 从删除一条代表二进制数据的记录
 * 
 * @param id
 *            主键
 * @throws SQLException
 */
protected void deleteFromBlob(final String id) throws SQLException {
	final String sql = "DELETE FROM BDF2_BLOB_STORE WHERE ID_=?";
	int updatedRowCount = super.getJdbcTemplate().execute(sql,
			new PreparedStatementCallback<Integer>() {
				public Integer doInPreparedStatement(
						PreparedStatement preparedstatement)
						throws SQLException, DataAccessException {
					preparedstatement.setString(1, id);
					return preparedstatement.executeUpdate();
				}
			});
	if (0 == updatedRowCount) {
		throw new SQLException(String.format("未能成功删除大二进制对象[id=%s],请检查其是否存在", id));
	}
}
 
Example 4
Project: bdf2   File: LobStoreServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * 删除一条代表文本的记录。
 * 
 * @param id
 *            主键
 * @throws SQLException
 */
protected void deleteFromClob(final String id) throws SQLException {
	final String sql = "DELETE FROM BDF2_CLOB_STORE WHERE ID_=?";
	int updatedRowCount = super.getJdbcTemplate().execute(sql,
			new PreparedStatementCallback<Integer>() {
				public Integer doInPreparedStatement(
						PreparedStatement preparedstatement)
						throws SQLException, DataAccessException {
					preparedstatement.setString(1, id);
					return preparedstatement.executeUpdate();
				}

			});
	if (0 == updatedRowCount) {
		throw new SQLException(String.format("未能成功删除大字符对象[id=%s],请检查其是否存在",
				id));
	}
}
 
Example 5
Project: sjk   File: AppRankDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<App> getAppCategoryRank(final int parentId, final int subCatalog, final int top) {
    PreparedStatementCallback<List<App>> cb = new PreparedStatementCallback<List<App>>() {
        @Override
        public List<App> doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.setInt(1, parentId);
            ps.setInt(2, subCatalog);
            ps.setInt(3, top);
            ResultSet rs = null;
            try {
                rs = ps.executeQuery();
                if (rs.last()) {
                    int count = rs.getRow();
                    List<App> list = new ArrayList<App>(count);
                    rs.beforeFirst();
                    App app = null;
                    while (rs.next()) {
                        app = appRowMapper.mapRow(rs, rs.getRow());
                        changeOutputImpl.setUrls(app);
                        list.add(app);
                    }
                    return list;
                }

            } catch (Exception e) {
                logger.error("SQL data error:", e);
                return null;
            } finally {
                if (null != rs)
                    rs.close();
            }
            return null;
        }
    };
    return jdbcTemplate.execute(QUERY_APP_CATEGORY_TOP_SQL, cb);
}
 
Example 6
Project: sjk   File: AppRankDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<App> getAppDefultRank(final int typeId, final int top) {
    PreparedStatementCallback<List<App>> cb = new PreparedStatementCallback<List<App>>() {
        @Override
        public List<App> doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.setInt(1, typeId);
            ps.setInt(2, top);
            ResultSet rs = null;
            try {
                rs = ps.executeQuery();
                if (rs.last()) {
                    int count = rs.getRow();
                    List<App> list = new ArrayList<App>(count);
                    rs.beforeFirst();
                    App app = null;
                    while (rs.next()) {
                        app = appRowMapper.mapRow(rs, rs.getRow());
                        changeOutputImpl.setUrls(app);
                        list.add(app);
                    }
                    return list;
                }

            } catch (Exception e) {
                logger.error("SQL data error:", e);
                return null;
            } finally {
                if (null != rs)
                    rs.close();
            }
            return null;
        }
    };
    return jdbcTemplate.execute(QUERY_APP_DEFAULT_TOP_SQL, cb);
}
 
Example 7
Project: sjk   File: AppsDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<AppType> getAppTypes(final int parentId) {
    PreparedStatementCallback<List<AppType>> cb = new PreparedStatementCallback<List<AppType>>() {
        @Override
        public List<AppType> doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ResultSet rs = null;
            try {
                ps.setInt(1, parentId);
                ps.setInt(2, parentId);
                rs = ps.executeQuery();
                // predicate count.
                if (rs.last()) {
                    int count = rs.getRow();
                    List<AppType> list = new ArrayList<AppType>(count);
                    rs.beforeFirst();
                    AppType appType = null;
                    while (rs.next()) {
                        appType = appTypeRowMapper.mapRow(rs, rs.getRow());
                        list.add(appType);
                    }
                    return list;
                } else {
                    return null;
                }
            } finally {
                if (null != rs) {
                    rs.close();
                }
            }
        }
    };
    return this.jdbcTemplate.execute(appTypes, cb);
}
 
Example 8
Project: sjk   File: AppsDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Topic getPowerTuiJianTopic(final int topicid) {
    PreparedStatementCallback<Topic> cb = new PreparedStatementCallback<Topic>() {
        @Override
        public Topic doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ResultSet rs = null;
            try {
                ps.setInt(1, topicid);
                rs = ps.executeQuery();
                if (!rs.next()) {
                    return null;
                }
                Topic topic = topicRowMapper.mapRow(rs, 1);
                changeOutputImpl.setUrls(topic);
                return topic;
            } finally {
                if (null != rs)
                    rs.close();
            }
        }
    };
    return jdbcTemplate.execute(topicPowerTuiJian, cb);
}
 
Example 9
Project: sjk   File: AppsDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Topic getPowerChannelTuiJianTopic(final int topicid) {
    PreparedStatementCallback<Topic> cb = new PreparedStatementCallback<Topic>() {
        @Override
        public Topic doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ResultSet rs = null;
            try {
                ps.setInt(1, topicid);
                rs = ps.executeQuery();
                if (!rs.next()) {
                    return null;
                }
                Topic topic = topicRowMapper.mapRow(rs, 1);
                changeOutputImpl.setUrls(topic);
                return topic;
            } finally {
                if (null != rs)
                    rs.close();
            }
        }
    };
    return jdbcTemplate.execute(topicPowerChannelTuiJian, cb);
}
 
Example 10
Project: spring4-understanding   File: NamedParameterJdbcTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecute() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", 1);
	params.put("priceId", 1);
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1);
	verify(preparedStatement).setObject(2, 1);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 11
Project: spring4-understanding   File: NamedParameterJdbcTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecuteWithTypedParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("priceId", new SqlParameterValue(Types.INTEGER, 1));
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setObject(2, 1, Types.INTEGER);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 12
Project: spring4-understanding   File: NamedParameterJdbcTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecuteNoParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeQuery();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(SELECT_NO_PARAMETERS);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 13
Project: yugong   File: OracleMaterializedIncRecordExtractor.java   Source Code and License 6 votes vote down vote up
public Position ack(final List<Record> records) throws YuGongException {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getSourceDs());
    jdbcTemplate.execute(mlogCleanSql, new PreparedStatementCallback() {

        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            for (Record record : records) {
                OracleIncrementRecord incRecord = (OracleIncrementRecord) record;
                ps.setObject(1, incRecord.getRowId().getValue(), incRecord.getRowId().getColumn().getType());
                ps.addBatch();
            }

            ps.executeBatch();
            return null;
        }
    });

    return null;
}
 
Example 14
Project: yugong   File: TableMetaGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * <pre>
 * 常见的物化视图创建语句:
 * 1. CREATE MATERIALIZED VIEW LOG ON test_all_target with primary key; 
 * 
 * 本方法,主要提取生成物化视图的表名
 * </pre>
 * 
 * @param dataSource
 * @param schemaName
 * @param tableName
 * @return
 */
public static String getMLogTableName(final DataSource dataSource, final String schemaName, final String tableName) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    String sql = StringUtils.isNotEmpty(schemaName) ? mlogSchemaQuerySql : mlogQuerySql;
    return (String) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            DatabaseMetaData metaData = ps.getConnection().getMetaData();
            String sName = getIdentifierName(schemaName, metaData);
            String tName = getIdentifierName(tableName, metaData);
            ps.setString(1, tName);
            if (StringUtils.isNotEmpty(schemaName)) {
                ps.setString(2, sName);
            }
            ResultSet rs = ps.executeQuery();
            String log = null;
            if (rs.next()) {
                log = rs.getString("log_table");
            }

            rs.close();
            return log;
        }
    });
}
 
Example 15
Project: cango   File: KafkaIncRecordExtractor.java   Source Code and License 6 votes vote down vote up
@Override
public void clearMlog(final List<ColumnValue> records, String mlogCleanSql) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getSourceDs());
    jdbcTemplate.execute(mlogCleanSql, new PreparedStatementCallback() {

        @Override
        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            for (ColumnValue record : records) {
                ps.setObject(1, record.getValue(), record.getColumn().getType());
                ps.addBatch();
            }
            ps.executeBatch();
            return null;
        }
    });
}
 
Example 16
Project: cango   File: KafkaIncRecordExtractor.java   Source Code and License 6 votes vote down vote up
/**
 * 根据mlog物化日志表的SEQUENCE$$字段单独查询
 *
 * @param sequence
 * @param context
 * @param columns
 * @return
 */
private List<ColumnValue> getSingleMlogRecord(final String singleMlogExtractSql, final int sequence, final YuGongContext context, final List<ColumnMeta> mlogCols, final List<ColumnMeta> columns, final List<ColumnValue> rowIds) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getSourceDs());
    final List<ColumnValue> columnValues = new ArrayList<ColumnValue>();
    return (List<ColumnValue>) jdbcTemplate.execute(singleMlogExtractSql, new PreparedStatementCallback() {
        @Override
        public List<ColumnValue> doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.setInt(1, sequence);
            ResultSet rs = ps.executeQuery();
            try {
                while (rs.next()) {
                    rowIds.add(new ColumnValue(rowidColumn, rs.getObject("rowid")));
                    columnValues.addAll(buildColumnValue(rs, context.getSourceEncoding(), mlogCols, columns));
                }
            } finally {
                JdbcUtils.closeResultSet(rs);
            }
            return columnValues;
        }
    });
}
 
Example 17
Project: cango   File: TableMetaGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * 获取DRDS下表的拆分字段, 返回格式为 id,name
 *
 * @param dataSource
 * @param schemaName
 * @param tableName
 * @return
 */
public static String getShardKeyByDRDS(final DataSource dataSource, final String schemaName, final String tableName) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    return (String) jdbcTemplate.execute(queryShardKey, new PreparedStatementCallback() {

        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            DatabaseMetaData metaData = ps.getConnection().getMetaData();
            // String sName = getIdentifierName(schemaName, metaData);
            String tName = getIdentifierName(tableName, metaData);

            ps.setString(1, tName);
            ResultSet rs = null;
            try {
                rs = ps.executeQuery();
                String log = null;
                if (rs.next()) {
                    log = rs.getString("KEYS");
                }

                return log;
            } finally {
                JdbcUtils.closeResultSet(rs);
            }
        }
    });
}
 
Example 18
Project: spring-content   File: JpaContentTemplate.java   Source Code and License 6 votes vote down vote up
public <T> void unsetContent(T metadata) {
	String sql = "DELETE FROM BLOBS WHERE id=" + BeanUtils.getFieldWithAnnotation(metadata, ContentId.class);
       this.template.execute(sql, new PreparedStatementCallback<Integer>() {
           @Override
           public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
               int rc = 0;
               try {
                   rc = ps.executeUpdate();
                   BeanUtils.setFieldWithAnnotation(metadata, ContentId.class, null);
                   BeanUtils.setFieldWithAnnotation(metadata, ContentLength.class, 0);
               } catch (SQLException sqle) {
                   logger.error(String.format("Error deleting content %s", BeanUtils.getFieldWithAnnotation(metadata, ContentId.class)), sqle);
               }
               return rc;
           }
       });
}
 
Example 19
Project: Camel   File: ElsqlSqlProcessingStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public int commit(DefaultSqlEndpoint defaultSqlEndpoint, Exchange exchange, Object data, NamedParameterJdbcTemplate jdbcTemplate,
                  SqlParameterSource parameterSource, String query) throws Exception {

    final SqlParameterSource param = new ElsqlSqlMapSource(exchange, data);
    final String sql = elSql.getSql(query, new SpringSqlParams(param));
    LOG.debug("commit @{} using sql: {}", query, sql);

    return jdbcTemplate.execute(sql, param, new PreparedStatementCallback<Integer>() {
        @Override
        public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.execute();

            int updateCount = ps.getUpdateCount();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Update count {}", updateCount);
            }
            return updateCount;
        }
    });
}
 
Example 20
Project: Camel   File: ElsqlSqlProcessingStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public int commitBatchComplete(DefaultSqlEndpoint endpoint, NamedParameterJdbcTemplate namedJdbcTemplate,
                        SqlParameterSource parameterSource, String query) throws Exception {

    final SqlParameterSource param = new EmptySqlParameterSource();
    final String sql = elSql.getSql(query, new SpringSqlParams(param));
    LOG.debug("commitBatchComplete @{} using sql: {}", query, sql);

    return namedJdbcTemplate.execute(sql, param, new PreparedStatementCallback<Integer>() {
        @Override
        public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ps.execute();

            int updateCount = ps.getUpdateCount();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Update count {}", updateCount);
            }
            return updateCount;
        }
    });
}
 
Example 21
Project: Camel   File: DefaultSqlProcessingStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public int commit(final DefaultSqlEndpoint endpoint, final Exchange exchange, final Object data, final JdbcTemplate jdbcTemplate, final String query) throws Exception {

    final String preparedQuery = sqlPrepareStatementStrategy.prepareQuery(query, endpoint.isAllowNamedParameters(), exchange);

    return jdbcTemplate.execute(preparedQuery, new PreparedStatementCallback<Integer>() {
        public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException {
            int expected = ps.getParameterMetaData().getParameterCount();

            Iterator<?> iterator = sqlPrepareStatementStrategy.createPopulateIterator(query, preparedQuery, expected, exchange, data);
            if (iterator != null) {
                sqlPrepareStatementStrategy.populateStatement(ps, iterator, expected);
                LOG.trace("Execute query {}", query);
                ps.execute();

                int updateCount = ps.getUpdateCount();
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Update count {}", updateCount);
                }
                return updateCount;
            }

            return 0;
        };
    });
}
 
Example 22
Project: Camel   File: DefaultSqlProcessingStrategy.java   Source Code and License 6 votes vote down vote up
@Override
public int commitBatchComplete(final DefaultSqlEndpoint endpoint, final JdbcTemplate jdbcTemplate, final String query) throws Exception {
    final String preparedQuery = sqlPrepareStatementStrategy.prepareQuery(query, endpoint.isAllowNamedParameters(), null);

    return jdbcTemplate.execute(preparedQuery, new PreparedStatementCallback<Integer>() {
        public Integer doInPreparedStatement(PreparedStatement ps) throws SQLException {
            int expected = ps.getParameterMetaData().getParameterCount();
            if (expected != 0) {
                throw new IllegalArgumentException("Query onConsumeBatchComplete " + query + " cannot have parameters, was " + expected);
            }

            LOG.trace("Execute query {}", query);
            ps.execute();

            int updateCount = ps.getUpdateCount();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Update count {}", updateCount);
            }
            return updateCount;
        };
    });
}
 
Example 23
Project: xap-openspaces   File: DbcpJdbcTests.java   Source Code and License 6 votes vote down vote up
@Test public void testSimpleOperation() {
    jdbcTemplate.execute("create table Person(FirstName varchar2 INDEX, LastName varchar2)");
    jdbcTemplate.execute("insert into Person values(?,?)", new PreparedStatementCallback() {
        public Object doInPreparedStatement(PreparedStatement preparedStatement) throws SQLException, DataAccessException {
            for (int i = 0; i < 10; i++) {
                preparedStatement.setString(1, "FirstName" + i);
                preparedStatement.setString(2, "LastName" + i);
                preparedStatement.executeUpdate();
            }
            return null;
        }
    });
    long count = jdbcTemplate.queryForLong("select count(*) from Person");
    assertEquals(10, count);
}
 
Example 24
Project: STLCourts-api   File: ViolationDAO.java   Source Code and License 6 votes vote down vote up
public boolean insertViolations(List<Violation> violations){
	try{
		for(int i = 0; i < violations.size(); i++){
			Violation v = violations.get(i);
			String sql = "INSERT INTO violations (citation_number,violation_number,violation_description,warrant_status,warrant_number,status,fine_amount,court_cost) VALUES ('"+v.citation_number+"','"+v.violation_number+"','"+v.violation_description+"',"+v.warrant_status+",'"+v.warrant_number+"','"+v.status.name()+"',"+v.fine_amount.toString()+","+v.court_cost.toString()+")";
			jdbcTemplate.execute(sql, new PreparedStatementCallback<Boolean>(){
				@Override
				public Boolean doInPreparedStatement(java.sql.PreparedStatement ps)
						throws SQLException, DataAccessException {
					return ps.execute();
				}
			});
		}	
	}catch(Exception e){
		LogSystem.LogDBException(e);
		return false;
	}
	return true;
}
 
Example 25
Project: STLCourts-api   File: ViolationDAO.java   Source Code and License 6 votes vote down vote up
public boolean removeViolations(List<Violation> violations){
	try{
		for(int i = 0; i < violations.size(); i++){
			Violation v = violations.get(i);
			String sql = "DELETE FROM violations WHERE citation_number = '"+v.citation_number+"'";
			jdbcTemplate.execute(sql, new PreparedStatementCallback<Boolean>(){
				@Override
				public Boolean doInPreparedStatement(java.sql.PreparedStatement ps)
						throws SQLException, DataAccessException {
					return ps.execute();
				}
			});
		}
	}catch(Exception e){
		LogSystem.LogDBException(e);
		return false;
	}
	return true;
}
 
Example 26
Project: STLCourts-api   File: ViolationDAOTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Ignore
@Test
public void insertsViolations(){
	//This code is not working yet, to Ignored.
	final Violation VIOLATION = new Violation();
       VIOLATION.id = 4;
       final List<Violation> VIOLATIONS = Lists.newArrayList(VIOLATION);
       
       //when(jdbcTemplate.execute(Matchers.anyString(), Mockito.any(PreparedStatementCallback.class))).thenReturn(true);
       when(jdbcTemplate.execute(Matchers.anyString(), Mockito.any(PreparedStatementCallback.class)))
       .thenAnswer(new Answer<Boolean>(){

		@Override
		public Boolean answer(InvocationOnMock invocation) throws Throwable {
			// TODO Auto-generated method stub
			//http://stackoverflow.com/questions/28633173/increasing-code-coverage-for-jdbctemplate-mocking
			return true;
		}
       	
       });
       
       Boolean returnValue = mockViolationDAO.insertViolations(VIOLATIONS);
       assertThat(returnValue, is(true));
}
 
Example 27
Project: egd-web   File: ReportDB.java   Source Code and License 6 votes vote down vote up
public List<Map<String, ?>> getCountGlossToSumFreqRatio() {
    String sql = "SELECT count_gloss, sum_freq, freq_ratio FROM public.v_count_gloss_to_sum_freq";
    CustomPreparedStatementCreator sc = new CustomPreparedStatementCreator(sql) {};

    PreparedStatementCallback<List<Map<String, ?>>> cb = s -> {
        ResultSet rs = s.executeQuery();

        List<Map<String, ?>> result = new ArrayList<>();
        Map<String, Object> item;
        while (rs.next()) {
            item = new LinkedHashMap<>();

            item.put("countGloss", rs.getInt(1));
            item.put("sumFreq", rs.getInt(2));
            item.put("freqRatio", rs.getFloat(3));

            result.add(item);
        }

        return result;
    };
    return execute(sc, cb);
}
 
Example 28
Project: pulsar-reporting-api   File: RDBMS.java   Source Code and License 6 votes vote down vote up
public Boolean execute(final String sql,final Map<String,?> parameters) {
        return this.namedParameterJdbcTemplate.execute(sql,parameters, new PreparedStatementCallback<Boolean>() {
            @Override
            public Boolean doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
//            	if(ps.getParameterMetaData()!=null){
//            		int count=ps.getParameterMetaData().getParameterCount();
//            		for(int i=0;i<count;i++){
//            			String name=ps.getParameterMetaData().getParameterTypeName(i);
//            			System.out.println(i+":"+name);
//            			if(name.equalsIgnoreCase("properties") || "config".equalsIgnoreCase(name)){
//            				Blob bv=ps.getConnection().createBlob();
//            				bv.setBytes(0, ((String)parameters.get(name)).getBytes());
//            				ps.setBlob(i, bv);
//            			}
//            		}
//            		return ps.execute();
//            	}else{
//            		return ps.execute();
//            	}
            	return ps.execute();
            }
        });
    }
 
Example 29
Project: SimpleFlatMapper   File: PreparedStatementCallbackImpl.java   Source Code and License 6 votes vote down vote up
public <H extends CheckedConsumer<T>> PreparedStatementCallback<H> newPreparedStatementCallback(final H handler) {
	return new PreparedStatementCallback<H>() {
		@Override
		public H doInPreparedStatement(
				PreparedStatement ps)
				throws SQLException, DataAccessException {
			ResultSet rs = ps.executeQuery();
			ResultSetExtractor<H> extractor = resultSetExtractor.newResultSetExtractor(handler);
			try {
				return extractor.extractData(rs);
			} finally {
				rs.close();
			}
		}
	};
}
 
Example 30
Project: class-guard   File: NamedParameterJdbcTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecute() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	params.put("perfId", 1);
	params.put("priceId", 1);
	Object result = namedParameterTemplate.execute(UPDATE_NAMED_PARAMETERS, params,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeUpdate();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1);
	verify(preparedStatement).setObject(2, 1);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 31
Project: class-guard   File: NamedParameterJdbcTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecuteNoParameters() throws SQLException {
	given(preparedStatement.executeUpdate()).willReturn(1);

	Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS,
			new PreparedStatementCallback<Object>() {
				@Override
				public Object doInPreparedStatement(PreparedStatement ps)
						throws SQLException {
					assertEquals(preparedStatement, ps);
					ps.executeQuery();
					return "result";
				}
			});

	assertEquals("result", result);
	verify(connection).prepareStatement(SELECT_NO_PARAMETERS);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 32
Project: Sql4D   File: MysqlAccessor.java   Source Code and License 6 votes vote down vote up
/**
 * Suitable for CRUD operations where no result set is expected.
 * @param params
 * @param query 
 * @return  
 */
public boolean execute(Map<String, String> params, String query) {
    final AtomicBoolean result = new AtomicBoolean(false);
    Tuple2<DataSource, Connection> conn = null;
    try {
        conn = getConnection();
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1());
        jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() {
            @Override
            public Void doInPreparedStatement(PreparedStatement ps) {
                try {
                    result.set(ps.execute());
                } catch(SQLException e) {
                    result.set(false);
                }
                return null;
            }
        });
    } catch (Exception ex) {
        Logger.getLogger(MysqlAccessor.class.getName()).log(Level.SEVERE, null, ex);
        result.set(false);
    } finally {
        returnConnection(conn);
    }
    return result.get();
}
 
Example 33
Project: Equella   File: JdbcQueryDelegate.java   Source Code and License 5 votes vote down vote up
@Override
public MetadataBean getParameterMetadata(String query, final List<Object> params)
{
	try
	{
		query = processQuery(query);

		return (MetadataBean) new JdbcTemplate(getDataSourceHolder().getDataSource()).execute(query,
			new PreparedStatementCallback()
			{
				@Override
				public Object doInPreparedStatement(PreparedStatement statement) throws SQLException,
					DataAccessException
				{
					addParamsToStatement(statement, params);
					try
					{
						ParameterMetaData parameterMetaData = statement.getParameterMetaData();
						return new MetadataBean(parameterMetaData);
					}
					catch( SQLException sqle )
					{
						return null;
					}
				}
			});
	}
	catch( Exception e )
	{
		String msg = CurrentLocale.get("com.tle.core.reporting.error.parameter.metadata") + query;
		LOGGER.error(msg, e);
		throw new RuntimeException(msg, e);
	}
}
 
Example 34
Project: factcast   File: PGCatchUpPrepare.java   Source Code and License 5 votes vote down vote up
public long prepareCatchup(AtomicLong serial) {
    PGQueryBuilder b = new PGQueryBuilder(req);
    long clientId = jdbc.queryForObject(PGConstants.NEXT_FROM_CATCHUP_SEQ, Long.class);
    String catchupSQL = b.catchupSQL(clientId);
    return jdbc.execute(catchupSQL, new PreparedStatementCallback<Long>() {

        @Override
        public Long doInPreparedStatement(PreparedStatement ps) throws SQLException,
                DataAccessException {

            log.debug("{} preparing paging for matches after {}", req, serial.get());
            try {
                Stopwatch sw = Stopwatch.createStarted();
                b.createStatementSetter(serial).setValues(ps);
                int numberOfFactsToCatchup = ps.executeUpdate();
                sw.stop();
                if (numberOfFactsToCatchup > 0) {
                    log.debug("{} prepared {} facts for cid={} in {}ms", req,
                            numberOfFactsToCatchup, clientId, sw.elapsed(
                                    TimeUnit.MILLISECONDS));
                    return clientId;
                } else {
                    log.debug("{} nothing to catch up", req);
                    return 0L;
                }
            } catch (SQLException ex) {
                log.error("While trying to prepare catchup", ex);
                throw ex;
            }
        }
    });

}
 
Example 35
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 5 votes vote down vote up
public boolean updateRevocation(String filename) {
	String newusersql = "update CLOUDFILEDATA set REVOCATION='yes' where filename='"
			+ filename.trim() + "'";

	return jdbcTemplate.execute(newusersql,
			new PreparedStatementCallback<Boolean>() {

				@Override
				public Boolean doInPreparedStatement(PreparedStatement ps)
						throws SQLException, DataAccessException {

					return ps.execute();
				}

			});

}
 
Example 36
Project: sjk   File: AppsDaoImpl.java   Source Code and License 5 votes vote down vote up
/**
 * 根据软件编号获取截图数据
 * 
 * @param softid
 *            软件编号
 * @return
 */
private List<ScreenImage> getAppScreenImages(final int softid) {
    PreparedStatementCallback<List<ScreenImage>> cb = new PreparedStatementCallback<List<ScreenImage>>() {
        @Override
        public List<ScreenImage> doInPreparedStatement(PreparedStatement ps) throws SQLException,
                DataAccessException {
            ResultSet rs = null;
            try {
                ps.setInt(1, softid);
                rs = ps.executeQuery();
                if (rs.last()) {
                    int count = rs.getRow();
                    List<ScreenImage> list = new ArrayList<ScreenImage>(count);
                    rs.beforeFirst();
                    ScreenImage appScreenImage = null;
                    while (rs.next()) {
                        appScreenImage = screenImageRowMapper.mapRow(rs, rs.getRow());
                        changeOutputImpl.setAppScreenUrl(appScreenImage);
                        list.add(appScreenImage);
                    }
                    return list;
                } else {
                    return null;
                }
            } finally {
                if (null != rs)
                    rs.close();
            }
        }
    };
    return this.jdbcTemplate.execute(appScreenImage, cb);
}
 
Example 37
Project: sjk   File: AppsDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<App> findByIds(List<Integer> ids) {
    // Session session = sessions.getCurrentSession();
    // Query query = null;
    // query =
    // session.createQuery("select a.id, a.name, a.downLoadLink, a.logo from App a where id in (:ids)").setParameterList("ids",
    // ids);
    // List<App> list = HibernateHelper.list(query);
    // for (App app : list) {
    // changeOutputImpl.setUrls(app);
    // }
    StringBuilder tmp = new StringBuilder(ids.size() * 6);
    for (Integer id : ids) {
        tmp.append(id).append(',');
    }
    tmp.deleteCharAt(tmp.length() - 1);
    String sql = appsByIds.replace("?", tmp.toString());

    PreparedStatementCallback<List<App>> cb = new PreparedStatementCallback<List<App>>() {
        @Override
        public List<App> doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            ResultSet rs = null;
            try {
                rs = ps.executeQuery();
                if (rs.last()) {
                    int count = rs.getRow();
                    List<App> list = new ArrayList<App>(count);
                    rs.beforeFirst();
                    App app = null;
                    while (rs.next()) {
                        app = appsRowMapper.mapRow(rs, rs.getRow());
                        changeOutputImpl.setUrls(app);
                        list.add(app);
                    }
                    return list;
                } else {
                    return null;
                }
            } finally {
                if (null != rs) {
                    rs.close();
                }
            }
        }

    };
    return this.jdbcTemplate.execute(sql, cb);
}
 
Example 38
Project: yugong   File: OracleFullRecordExtractor.java   Source Code and License 5 votes vote down vote up
private Object getMinId() {
    if (jdbcTemplate != null && StringUtils.isNotBlank(getMinPkSql)) {
        Object min = jdbcTemplate.execute(getMinPkSql, new PreparedStatementCallback() {

            @Override
            public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                ResultSet rs = ps.executeQuery();
                Object re = null;
                while (rs.next()) {
                    re = rs.getObject(1);
                    break;
                }
                return re;
            }
        });

        if (min != null) {
            if (min instanceof Number) {
                min = Long.valueOf(String.valueOf(min)) - 1;
            } else {
                min = "";
            }
        } else {
            if (min instanceof Number) {
                min = 0;
            } else {
                min = "";
            }
        }

        return min;
    } else {
        throw new YuGongException("jdbcTemplate or getMinPkSql is null while getMinId");
    }
}
 
Example 39
Project: yugong   File: TableMetaGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * 获取DRDS下表的拆分字段, 返回格式为 id,name
 * 
 * @param dataSource
 * @param schemaName
 * @param tableName
 * @return
 */
public static String getShardKeyByDRDS(final DataSource dataSource, final String schemaName, final String tableName) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    try {
        return (String) jdbcTemplate.execute(queryShardKey, new PreparedStatementCallback() {

            public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                DatabaseMetaData metaData = ps.getConnection().getMetaData();
                // String sName = getIdentifierName(schemaName, metaData);
                String tName = getIdentifierName(tableName, metaData);

                ps.setString(1, tName);
                ResultSet rs = ps.executeQuery();
                String log = null;
                if (rs.next()) {
                    log = rs.getString("KEYS");
                }

                rs.close();
                return log;
            }
        });
    } catch (DataAccessException e) {
        // 兼容下oracle源库和目标库DRDS表名不一致的情况,识别一下表名不存在
        Throwable cause = e.getRootCause();
        if (cause instanceof SQLException) {
            // ER_NO_SUCH_TABLE
            if (((SQLException) cause).getErrorCode() == 1146) {
                return null;
            }
        }

        throw e;
    }
}
 
Example 40
Project: cango   File: TableMetaGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * <pre>
 * 常见的物化视图创建语句:
 * 1. CREATE MATERIALIZED VIEW LOG ON test_all_target with primary key;
 *
 * 本方法,主要提取生成物化视图的表名
 * </pre>
 *
 * @param dataSource
 * @param schemaName
 * @param tableName
 * @return
 */
public static String getMLogTableName(final DataSource dataSource, final String schemaName, final String tableName) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    String querySql = StringUtils.isEmpty(schemaName) ? mlogQuerySql : mlogSchemaQuerySql;

    return (String) jdbcTemplate.execute(querySql, new PreparedStatementCallback() {

        public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
            DatabaseMetaData metaData = ps.getConnection().getMetaData();
            String sName = getIdentifierName(schemaName, metaData);
            String tName = getIdentifierName(tableName, metaData);

            ps.setString(1, tName);
            if (StringUtils.isNotEmpty(schemaName)) {
                ps.setString(2, sName);
            }

            ResultSet rs = null;
            String log;
            try {
                rs = ps.executeQuery();
                log = null;
                if (rs.next()) {
                    log = rs.getString("log_table");
                }
            } finally {
                JdbcUtils.closeResultSet(rs);
            }
            return log;
        }
    });
}
 
Example 41
Project: RLCMS   File: CrateSecurityUser.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Base64DecodingException {
	AesCipherService aesCipherService = new AesCipherService();
	aesCipherService.setKeySize(128); 
	FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("src/main/resources/applicationContext.xml");
	JdbcTemplate template = (JdbcTemplate) context.getBean("jdbcTemplate");
	Key key = aesCipherService.generateNewKey();
	final byte[] bytes = key.getEncoded();
	final String password = aesCipherService.encrypt(ByteSource.Util.bytes("123456").getBytes(), bytes).toBase64();
	
	System.out.println(password);
	System.out.println(new String(Base64.decode(aesCipherService.decrypt(Base64.decode(password), bytes).toBase64())));
	for(byte b : bytes){
		System.out.print(b+",");
	}
	template.execute("insert into security_user(password,username,password_key) values(?,?,?)", new PreparedStatementCallback(){

		@Override
		public Object doInPreparedStatement(PreparedStatement ps)
				throws SQLException, DataAccessException {
			ps.setString(1, password);
			ps.setString(2, "admin");
			ps.setBytes(3, bytes);
			ps.execute();
			return null;
		}
		
	});
}
 
Example 42
Project: xap-openspaces   File: SimpleJdbcTests.java   Source Code and License 5 votes vote down vote up
@Test public void testSimpleOperation() {
    jdbcTemplate.execute("create table Person(FirstName varchar2 INDEX, LastName varchar2)");
    jdbcTemplate.execute("insert into Person values(?,?)", new PreparedStatementCallback() {
        public Object doInPreparedStatement(PreparedStatement preparedStatement) throws SQLException, DataAccessException {
            for (int i = 0; i < 10; i++) {
                preparedStatement.setString(1, "FirstName" + i);
                preparedStatement.setString(2, "LastName" + i);
                preparedStatement.executeUpdate();
            }
            return null;
        }
    });
    long count = jdbcTemplate.queryForLong("select count(*) from Person");
    assertEquals(10, count);
}
 
Example 43
Project: kc-rice   File: RouteNodeDAOJpa.java   Source Code and License 5 votes vote down vote up
@Override
public List<String> getCurrentRouteNodeNames(final String documentId) {
    final DataSource dataSource = KEWServiceLocator.getDataSource();
    JdbcTemplate template = new JdbcTemplate(dataSource);
    List<String> names = template.execute(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    return connection.prepareStatement(CURRENT_ROUTE_NODE_NAMES_SQL);
                }
            }, new PreparedStatementCallback<List<String>>() {
                public List<String> doInPreparedStatement(
                        PreparedStatement statement) throws SQLException, DataAccessException {
                    List<String> routeNodeNames = new ArrayList<String>();
                    statement.setString(1, documentId);
                    ResultSet rs = statement.executeQuery();
                    try {
                        while (rs.next()) {
                            String name = rs.getString("nm");
                            routeNodeNames.add(name);
                        }
                    } finally {
                        if (rs != null) {
                            rs.close();
                        }
                    }
                    return routeNodeNames;
                }
            }
    );
    return names;
}
 
Example 44
Project: owsi-core-parent   File: V1_2__ImportExcel.java   Source Code and License 5 votes vote down vote up
@Override
public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
	final Integer id = new Integer(jdbcTemplate.queryForObject("SELECT NEXTVAL('" + Parameter.class.getSimpleName() + "_id_seq');", Integer.class));
	jdbcTemplate.execute("INSERT INTO parameter (id,datevalue,name,stringvalue) VALUES (?,?,'" + DATA_UPGRADE_AUTOPERFOM_PREFIX + "." + DATA_UPGRADE_NAME + "." + DATA_UPGRADE_AUTOPERFOM_SUFFIX + "',true);"
			, new PreparedStatementCallback<Boolean>() {
				@Override
				public Boolean doInPreparedStatement(PreparedStatement ps)
						throws SQLException, DataAccessException {
					ps.setInt(1, id);
					ps.setDate(2, new Date(new java.util.Date().getTime()));

					return ps.execute();
				}
			});
}
 
Example 45
Project: cernunnos   File: StatementTask.java   Source Code and License 5 votes vote down vote up
public void perform(TaskRequest req, TaskResponse res) {
    final DataSource dataSource = DataSourceRetrievalUtil.getDataSource(dataSourcePhrase, connectionPhrase, req, res);
	
       final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

       //Setup the callback class to do the PreparedStatement parameter binding and statement execution
	final PreparedStatementCallback preparedStatementCallback = new PhraseParameterPreparedStatementCallback(this.parameters, req, res);
       
	//Get the SQL and execute it in a PreparedStatement
	final String fSql = (String) sql.evaluate(req, res);
	jdbcTemplate.execute(fSql, preparedStatementCallback);
}
 
Example 46
Project: egd-web   File: SHADBRepository.java   Source Code and License 5 votes vote down vote up
public void save(SHAFile shafile) {

        String sql = "insert into public.sha_file(file, sha256sum, length, mime, file_name, file_extension," +
            " created_by, created_date, last_modified_by, last_modified_date)" +
            " values(FILE_READ(?),?,?,?,?, ?,?,?,?,?)";

        CustomPreparedStatementCreator sc = new CustomPreparedStatementCreator(sql) {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                PreparedStatement s = con.prepareStatement(this.sql);
                int i = 1;

                setString(s, i++, shafile.getFile().getAbsolutePath());
                setString(s, i++, shafile.getSha256sum());
                setLong(s, i++, shafile.getLength());
                setString(s, i++, shafile.getMime());
                setString(s, i++, shafile.getFileName());

                setString(s, i++, shafile.getFileExtension());
                setString(s, i++, shafile.getCreatedBy());
                setTimestamp(s, i++, Timestamp.from(shafile.getCreatedDate().toInstant()));
                setString(s, i++, shafile.getLastModifiedBy());
                setTimestamp(s, i, shafile.getLastModifiedDate() != null ? Timestamp.from(shafile.getLastModifiedDate().toInstant()) : null);

                return s;
            }
        };

        PreparedStatementCallback cb = PreparedStatement::execute;

        execute(sc, cb);
    }
 
Example 47
Project: egd-web   File: ReportDB.java   Source Code and License 5 votes vote down vote up
public List<Map<String, ?>> findAllVKanji() {

        String sql = "select kanji, stroke_count, on_yomis, kun_yomis, primitives," +
            " jinmei_seq, jouyou_radical, jouyou_year_added, jouyou_old_kanji," +
            " jouyou_meaning_en, jouyou_grade, jouyou_grade_seq from v_kanji";

        CustomPreparedStatementCreator sc = new CustomPreparedStatementCreator(sql) {};

        PreparedStatementCallback<List<Map<String, ?>>> cb = s -> {
            ResultSet rs = s.executeQuery();

            List<Map<String, ?>> result = new ArrayList<>();
            Map<String, Object> item;
            while (rs.next()) {
                item = new HashMap<>();
                int i = 1;

                item.put("kanji", rs.getString(i++));//kanji
                item.put("strokeCount", rs.getInt(i++));//stroke_count
                item.put("onYomis", rs.getString(i++));//on_yomis
                item.put("kunYomis", rs.getString(i++));//kun_yomis
                item.put("primitives", rs.getString(i++));//primitives

                item.put("jinmeiSeq", rs.getInt(i++));//jinmei_seq
                item.put("jouyouRadical", rs.getString(i++));//jouyou_radical
                item.put("jouyouYearAdded", rs.getInt(i++));//jouyou_year_added
                item.put("jouyouOldKanji", rs.getString(i++));//jouyou_old_kanji
                item.put("jouyouMeaningEn", rs.getString(i++));//jouyou_meaning_en

                item.put("jouyouGrade", rs.getInt(i++));//jouyou_grade
                item.put("jouyouGradeSeq", rs.getInt(i));//jouyou_grade_seq

                result.add(item);
            }

            return result;
        };
        return execute(sc, cb);
    }
 
Example 48
Project: egd-web   File: ReportDB.java   Source Code and License 5 votes vote down vote up
public VStats getStats() {

        String sql = "select * from v_stats";
        CustomPreparedStatementCreator sc = new CustomPreparedStatementCreator(sql) {};

        PreparedStatementCallback<VStats> cb = s -> {
            ResultSet rs = s.executeQuery();

            VStats result = null;
            if (rs.next()) {
                int i = 1;
                result = new VStats();

                result.countJpEntry = rs.getInt(i++);//countJpEntry
                result.countTranslatedEntries = rs.getInt(i++);//countTranslatedEntries
                result.countEtTranslations = rs.getInt(i++);//countEtTranslations
                result.countSentencePairs = rs.getInt(i++);//countSentencePairs
                result.countEstwnExamples = rs.getInt(i++);//countEstwnExamples

                result.countOriginJatik = rs.getInt(i++);//countOriginJatik
                result.countOriginIlo = rs.getInt(i++);//countOriginIlo
                result.countOriginEgd = rs.getInt(i++);//countOriginEgd

                result.countJpSearchWords = rs.getInt(i++);//countJpSearchWords
                result.countJpSearchWithResults = rs.getInt(i++);//countJpSearchWithResults
                result.countEtSearchWords = rs.getInt(i++);//countEtSearchWords
                result.countEtSearchWithResults = rs.getInt(i++);//countEtSearchWithResults

                result.countKanjiInDb = rs.getInt(i++);//countKanjiInDb
                result.countKanjisDescribedWithHeisig = rs.getInt(i++);//countKanjisDescribedWithHeisig
                result.countStrokeDiagrams = rs.getInt(i);//countStrokeDiagrams

            }

            return result;
        };
        return execute(sc, cb);
    }
 
Example 49
Project: gerbil   File: ExperimentDAOImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void close() throws IOException {
    this.template.execute(SHUTDOWN, new PreparedStatementCallback<Object>() {
        @Override
        public Object doInPreparedStatement(PreparedStatement arg0) throws SQLException, DataAccessException {
            // nothing to do
            return null;
        }
    });
}
 
Example 50
Project: rice   File: RouteNodeDAOJpa.java   Source Code and License 5 votes vote down vote up
@Override
public List<String> getCurrentRouteNodeNames(final String documentId) {
    final DataSource dataSource = KEWServiceLocator.getDataSource();
    JdbcTemplate template = new JdbcTemplate(dataSource);
    List<String> names = template.execute(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    return connection.prepareStatement(CURRENT_ROUTE_NODE_NAMES_SQL);
                }
            }, new PreparedStatementCallback<List<String>>() {
                public List<String> doInPreparedStatement(
                        PreparedStatement statement) throws SQLException, DataAccessException {
                    List<String> routeNodeNames = new ArrayList<String>();
                    statement.setString(1, documentId);
                    ResultSet rs = statement.executeQuery();
                    try {
                        while (rs.next()) {
                            String name = rs.getString("nm");
                            routeNodeNames.add(name);
                        }
                    } finally {
                        if (rs != null) {
                            rs.close();
                        }
                    }
                    return routeNodeNames;
                }
            }
    );
    return names;
}
 
Example 51
Project: kuali_rice   File: RouteNodeDAOOjbImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<String> getCurrentRouteNodeNames(final String documentId) {
    final DataSource dataSource = KEWServiceLocator.getDataSource();
    JdbcTemplate template = new JdbcTemplate(dataSource);
    List<String> names = template.execute(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    return connection.prepareStatement(CURRENT_ROUTE_NODE_NAMES_SQL);
                }
            }, new PreparedStatementCallback<List<String>>() {
                public List<String> doInPreparedStatement(
                        PreparedStatement statement) throws SQLException, DataAccessException {
                    List<String> routeNodeNames = new ArrayList<String>();
                    statement.setString(1, documentId);
                    ResultSet rs = statement.executeQuery();
                    try {
                        while (rs.next()) {
                            String name = rs.getString("nm");
                            routeNodeNames.add(name);
                        }
                    } finally {
                        if (rs != null) {
                            rs.close();
                        }
                    }
                    return routeNodeNames;
                }
            }
    );
    return names;
}
 
Example 52
Project: kuali_rice   File: RouteNodeDAOJpaImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<String> getCurrentRouteNodeNames(final String documentId) {
    final DataSource dataSource = KEWServiceLocator.getDataSource();
    JdbcTemplate template = new JdbcTemplate(dataSource);
    List<String> names = template.execute(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    return connection.prepareStatement(CURRENT_ROUTE_NODE_NAMES_SQL);
                }
            }, new PreparedStatementCallback<List<String>>() {
                public List<String> doInPreparedStatement(
                        PreparedStatement statement) throws SQLException, DataAccessException {
                    List<String> routeNodeNames = new ArrayList<String>();
                    statement.setString(1, documentId);
                    ResultSet rs = statement.executeQuery();
                    try {
                        while (rs.next()) {
                            String name = rs.getString("nm");
                            routeNodeNames.add(name);
                        }
                    } finally {
                        if (rs != null) {
                            rs.close();
                        }
                    }
                    return routeNodeNames;
                }
            }
    );
    return names;
}
 
Example 53
Project: buffer-slayer   File: BatchJdbcTemplate.java   Source Code and License 4 votes vote down vote up
public <T> T execute(PreparedStatementCreator psc,
    PreparedStatementCallback<T> action) throws DataAccessException {
  return delegate.execute(psc, action);
}
 
Example 54
Project: buffer-slayer   File: BatchJdbcTemplate.java   Source Code and License 4 votes vote down vote up
public <T> T execute(String sql, PreparedStatementCallback<T> action) throws DataAccessException {
  return delegate.execute(sql, action);
}
 
Example 55
Project: lams   File: NamedParameterJdbcTemplate.java   Source Code and License 4 votes vote down vote up
@Override
public <T> T execute(String sql, SqlParameterSource paramSource, PreparedStatementCallback<T> action)
		throws DataAccessException {

	return getJdbcOperations().execute(getPreparedStatementCreator(sql, paramSource), action);
}
 
Example 56
Project: lams   File: NamedParameterJdbcTemplate.java   Source Code and License 4 votes vote down vote up
@Override
public <T> T execute(String sql, Map<String, ?> paramMap, PreparedStatementCallback<T> action)
		throws DataAccessException {

	return execute(sql, new MapSqlParameterSource(paramMap), action);
}
 
Example 57
Project: lams   File: NamedParameterJdbcTemplate.java   Source Code and License 4 votes vote down vote up
@Override
public <T> T execute(String sql, PreparedStatementCallback<T> action) throws DataAccessException {
	return execute(sql, EmptySqlParameterSource.INSTANCE, action);
}
 
Example 58
Project: otter-G   File: BitTableIntegration.java   Source Code and License 4 votes vote down vote up
@Test
public void test_mysql() throws UnsupportedEncodingException {
    DbMediaSource dbMediaSource = new DbMediaSource();
    dbMediaSource.setId(10L);
    dbMediaSource.setDriver("com.mysql.jdbc.Driver");
    dbMediaSource.setUsername("xxxxx");
    dbMediaSource.setPassword("xxxxx");
    dbMediaSource.setUrl("jdbc:mysql://127.0.0.1:3306");
    dbMediaSource.setEncode("UTF-8");
    dbMediaSource.setType(DataMediaType.MYSQL);

    final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, dbMediaSource);
    want.object(dbDialect).clazIs(MysqlDialect.class);

    Table table = dbDialect.findTable(SCHEMA_NAME, TABLE_NAME);
    System.out.println(table);

    final SqlTemplate sqlTemplate = dbDialect.getSqlTemplate();
    final JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate();
    final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();
    final int[] pkColumnTypes = { Types.INTEGER };
    final int[] columnTypes = { Types.BIT, Types.BIT };
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            int affect = 0;
            String sql = null;
            // 执行insert
            sql = sqlTemplate.getInsertSql(SCHEMA_NAME, TABLE_NAME, pkColumns, columns);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps,
                        dbDialect,
                        toTypes(columnTypes, pkColumnTypes),
                        toValues(columnValues, pkColumnValues));
                    return ps.executeUpdate();
                }

            });
            want.number(affect).isEqualTo(1);
            return null;
            // throw new RuntimeException("rollback");
        }
    });

}
 
Example 59
Project: otter-G   File: TimeTableIntegration.java   Source Code and License 4 votes vote down vote up
@Test
public void test_mysql() {
    DbMediaSource dbMediaSource = new DbMediaSource();
    dbMediaSource.setId(10L);
    dbMediaSource.setDriver("oracle.jdbc.OracleDriver");
    dbMediaSource.setUsername("otter1");
    dbMediaSource.setPassword("jonathan");
    dbMediaSource.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:ointest");
    dbMediaSource.setEncode("UTF-8");
    dbMediaSource.setType(DataMediaType.ORACLE);

    final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, dbMediaSource);
    // want.object(dbDialect).clazIs(MysqlDialect.class);

    Table table = dbDialect.findTable("otter2", "test_time");
    System.out.println(table);

    final SqlTemplate sqlTemplate = dbDialect.getSqlTemplate();
    final JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate();
    final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();
    final int[] pkColumnTypes = { Types.INTEGER };
    final int[] columnTypes = { Types.TIMESTAMP, Types.TIMESTAMP, Types.DATE, Types.TIME, Types.INTEGER,
            Types.INTEGER };
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            int affect = 0;
            String sql = null;
            // 执行insert
            sql = sqlTemplate.getInsertSql(SCHEMA_NAME, TABLE_NAME, pkColumns, columns);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps,
                        dbDialect,
                        toTypes(columnTypes, pkColumnTypes),
                        toValues(columnValues, pkColumnValues));
                    return ps.executeUpdate();
                }

            });
            want.number(affect).isEqualTo(1);
            return null;
            // throw new RuntimeException("rollback");
        }
    });

}
 
Example 60
Project: otter-G   File: DbDialectTest.java   Source Code and License 4 votes vote down vote up
@Test(expectedExceptions = RuntimeException.class)
public void test_mysql() {
    DbDataMedia media = getMysqlMedia();
    final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, media.getSource());
    want.object(dbDialect).clazIs(MysqlDialect.class);

    final SqlTemplate sqlTemplate = dbDialect.getSqlTemplate();
    final JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate();
    final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate();
    final int[] pkColumnTypes = { Types.INTEGER, Types.VARCHAR };
    final int[] columnTypes = { Types.CHAR, Types.DECIMAL, Types.BLOB, Types.CLOB, Types.DATE, Types.TIMESTAMP,
            Types.TIMESTAMP };
    transactionTemplate.execute(new TransactionCallback() {

        public Object doInTransaction(TransactionStatus status) {
            int affect = 0;
            String sql = null;
            // 执行insert
            sql = sqlTemplate.getInsertSql(MYSQL_SCHEMA_NAME, TABLE_NAME, pkColumns, columns);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps,
                        dbDialect,
                        toTypes(columnTypes, pkColumnTypes),
                        toValues(columnValues, pkColumnValues));
                    return ps.executeUpdate();
                }

            });
            want.number(affect).isEqualTo(1);
            // 执行update
            sql = sqlTemplate.getUpdateSql(MYSQL_SCHEMA_NAME, TABLE_NAME, pkColumns, columns);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps,
                        dbDialect,
                        toTypes(columnTypes, pkColumnTypes),
                        toValues(columnValues, pkColumnValues));
                    return ps.executeUpdate();
                }

            });
            want.number(affect).isEqualTo(1);
            // 执行deleate
            sql = sqlTemplate.getDeleteSql(MYSQL_SCHEMA_NAME, TABLE_NAME, pkColumns);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps, dbDialect, toTypes(pkColumnTypes), toValues(pkColumnValues));
                    return ps.executeUpdate();
                }

            });
            want.number(affect).isEqualTo(1);
            // 执行merge
            sql = sqlTemplate.getMergeSql(MYSQL_SCHEMA_NAME, TABLE_NAME, pkColumns, columns, null);
            System.out.println(sql);
            affect = (Integer) jdbcTemplate.execute(sql, new PreparedStatementCallback() {

                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    doPreparedStatement(ps,
                        dbDialect,
                        toTypes(columnTypes, pkColumnTypes),
                        toValues(columnValues, pkColumnValues));
                    return ps.executeUpdate();
                }

            });
            want.number(affect).isEqualTo(1);
            throw new RuntimeException("rollback");
        }
    });

}