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

The following are top voted examples for showing how to use org.springframework.jdbc.core.JdbcTemplate. 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: lemon   File: WithdrawTaskCmd.java   Source Code and License 13 votes vote down vote up
/**
 * 删除历史节点.
 */
public void deleteHistoryActivities(List<String> historyNodeIds) {
    JdbcTemplate jdbcTemplate = ApplicationContextHelper
            .getBean(JdbcTemplate.class);
    logger.info("historyNodeIds : {}", historyNodeIds);

    for (String id : historyNodeIds) {
        String taskId = jdbcTemplate.queryForObject(
                "select task_id_ from ACT_HI_ACTINST where id_=?",
                String.class, id);

        if (taskId != null) {
            Context.getCommandContext()
                    .getHistoricTaskInstanceEntityManager()
                    .deleteHistoricTaskInstanceById(taskId);
        }

        jdbcTemplate.update("delete from ACT_HI_ACTINST where id_=?", id);
    }
}
 
Example 2
Project: EasyTransaction   File: PointService.java   Source Code and License 7 votes vote down vote up
public void addPointForBuying(OrderMessage msg){

		BusinessIdentifer businessIdentifer = ReflectUtil.getBusinessIdentifer(msg.getClass());
		
		JdbcTemplate jdbcTemplate = util.getJdbcTemplate(applicationName,businessIdentifer.busCode(),msg);
		int update = jdbcTemplate.update("update `point` set point = point + ? where user_id = ?;", 
				msg.getAmount(),msg.getUserId());
		
		if(update != 1){
			throw new RuntimeException("can not find specific user id!");
		}
		
		//for unit test
		if(successErrorCount != null){
			currentErrorCount++;
			if(successErrorCount < currentErrorCount){
				currentErrorCount = 0;
			} else {
				throw new UtProgramedException("error in message consume time:" + currentErrorCount);
			}
		}
	}
 
Example 3
Project: otter-G   File: DataMediaServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<String> queryColumnByMedia(DataMedia dataMedia) {
    List<String> columnResult = new ArrayList<String>();
    if (dataMedia.getSource().getType().isNapoli()) {
        return columnResult;
    }

    DataSource dataSource = dataSourceCreator.createDataSource(dataMedia.getSource());
    // 针对multi表,直接获取第一个匹配的表结构
    String schemaName = dataMedia.getNamespaceMode().getSingleValue();
    String tableName = dataMedia.getNameMode().getSingleValue();
    try {
        Table table = DdlUtils.findTable(new JdbcTemplate(dataSource), schemaName, schemaName, tableName);
        for (Column column : table.getColumns()) {
            columnResult.add(column.getName());
        }
    } catch (Exception e) {
        logger.error("ERROR ## DdlUtils find table happen error!", e);
    }

    return columnResult;
}
 
Example 4
Project: odotCore   File: ItemDao.java   Source Code and License 6 votes vote down vote up
/**
 * Finds All Item records in the DB.
 * 
 * @return List<Item> - the List of item objects in the DB.
 *         Will be empty if none found.
 */
public List<Item> findAll() {
  List<Item> ret;
  String sql = "SELECT * FROM " + Item.TABLE_NAME;
  JdbcTemplate jdbc = new JdbcTemplate(getDataSource());
  ret = jdbc.query(sql, new ItemRowMapper());
  if (ret.size() > 1) {
    log.info("Found " + ret.size() + " rows from query");
  }
  return ret;
}
 
Example 5
Project: plugin-bt-jira   File: JiraUpdateDao.java   Source Code and License 6 votes vote down vote up
/**
 * Indicate the installation and activation of "script runner" plug-in.
 * 
 * @param dataSource
 *            The data source of JIRA database.
 * @param jira
 *            the JIRA project identifier.
 * @param issues
 *            The issues to add. The ID property of each inserted issue is
 *            also updated in these objects.
 * @param workflowStepMapping
 *            the {@link Map} linking type identifier to a {@link Map}
 *            linking status name to steps.
 */
public void addIssues(final DataSource dataSource, final int jira, final List<JiraIssueRow> issues,
		final Map<Integer, Workflow> workflowStepMapping) {
	final JdbcOperations jdbcTemplate = new JdbcTemplate(dataSource);
	int nextId = prepareForNextId(dataSource, ISSUE_NODE, issues.size());
	reserveProjectCounter(dataSource, jira, issues);
	int nextCurrentStepId = prepareForNextId(dataSource, "OSCurrentStep", issues.size());
	int nextWfEntryId = prepareForNextId(dataSource, "OSWorkflowEntry", issues.size());
	int counter = 0;
	for (final JiraIssueRow issueRow : issues) {
		issueRow.setId(nextId);
		log.info("Inserting issue {}-{}({}) {}/{}", issueRow.getPkey(), issueRow.getIssueNum(), issueRow.getId(),
				counter, issues.size());
		Workflow workflow = workflowStepMapping.get(issueRow.getType());
		if (workflow == null) {
			workflow = workflowStepMapping.get(0);
		}

		addIssue(jira, jdbcTemplate, nextId, nextCurrentStepId, nextWfEntryId, issueRow, workflow);
		nextId++;
		nextWfEntryId++;
		nextCurrentStepId++;
		counter++;
	}
}
 
Example 6
Project: EasyTransaction   File: WalletService.java   Source Code and License 6 votes vote down vote up
public WalletPayTccMethodResult doTryPay(WalletPayCascadeTccMethodRequest param) {
	JdbcTemplate jdbcTemplate = util.getJdbcTemplate(Constant.APPID,WalletPayTccMethod.METHOD_NAME,param);
	int update = jdbcTemplate.update("update `wallet` set freeze_amount = freeze_amount + ? where user_id = ? and (total_amount - freeze_amount) >= ?;", 
			param.getPayAmount(),param.getUserId(),param.getPayAmount());
	
	if(update != 1){
		throw new RuntimeException("can not find specific user id or have not enought money");
	}
	
	//start cascading transaction
	transaction.startEasyTrans(WalletPayCascadeTccMethod.METHOD_NAME, String.valueOf(System.currentTimeMillis()));
	//publish point message with an consumer cascading this transaction 
	OrderMessageForCascadingTest msg = new OrderMessageForCascadingTest();
	msg.setUserId(param.getUserId());
	msg.setAmount(param.getPayAmount());
	transaction.execute(msg);
	
	/**
	 * 
	 */
	ExpressDeliverAfterTransMethodRequest expressDeliverAfterTransMethodRequest = new ExpressDeliverAfterTransMethodRequest();
	expressDeliverAfterTransMethodRequest.setUserId(param.getUserId());
	expressDeliverAfterTransMethodRequest.setPayAmount(param.getPayAmount());
	transaction.execute(expressDeliverAfterTransMethodRequest);
	
	checkUtProgramedException();
	
	
	WalletPayTccMethodResult walletPayTccMethodResult = new WalletPayTccMethodResult();
	walletPayTccMethodResult.setFreezeAmount(param.getPayAmount());
	return walletPayTccMethodResult;
}
 
Example 7
Project: plugin-bt-jira   File: JiraUpdateDao.java   Source Code and License 6 votes vote down vote up
/**
 * Add the given versions to the given project
 * 
 * @param dataSource
 *            The data source of JIRA database.
 * @param jira
 *            the JIRA project identifier.
 * @param versions
 *            the version names to add
 * @return the {@link Map} where value is the created version identifier.
 */
public Map<String, Integer> addVersions(final DataSource dataSource, final int jira,
		final Collection<String> versions) {
	final Map<String, Integer> result = new HashMap<>();
	final JdbcOperations jdbcTemplate = new JdbcTemplate(dataSource);
	int nextId = prepareForNextId(dataSource, VERSION_NODE, versions.size());
	int nextSequence = getNextVersionSequence(jira, jdbcTemplate);
	for (final String version : versions) {
		jdbcTemplate.update("INSERT INTO projectversion (ID,PROJECT,vname,SEQUENCE) values(?,?,?,?)", nextId, jira,
				version, nextSequence);
		result.put(version, nextId);
		nextId++;
		nextSequence++;
	}
	return result;
}
 
Example 8
Project: calcite-sql-rewriter   File: SqlRewriterConfiguration.java   Source Code and License 6 votes vote down vote up
@Bean
public JdbcTemplate postgresJdbcTemplate(
		@Value("${postgres.jdbcUrl}") String postgresJdbcUrl,
		@Value("${postgres.jdbcDriver}") String postgresJdbcDriver,
		@Value("${postgres.jdbcUser}") String postgresJdbcUser,
		@Value("${postgres.jdbcPassword}") String postgresJdbcPassword) {

	DataSource targetDataSource = DataSourceBuilder
			.create()
			.driverClassName(postgresJdbcDriver)
			.url(postgresJdbcUrl)
			.username(postgresJdbcUser)
			.password(postgresJdbcPassword)
			.build();

	return new JdbcTemplate(targetDataSource);
}
 
Example 9
Project: neo-java   File: BlockDbH2Impl.java   Source Code and License 6 votes vote down vote up
/**
 * return the block, with transactions added.
 *
 * @param block
 *            the block, to add transactions to.
 */
private void getTransactionsForBlock(final Block block) {
	final JdbcTemplate t = new JdbcTemplate(ds);
	final String sql = getSql("getTransactionsWithIndex");
	final byte[] blockIndexBa = block.index.toByteArray();
	final List<byte[]> dataList = t.queryForList(sql, byte[].class, blockIndexBa);

	for (final byte[] data : dataList) {
		final Transaction transaction = new Transaction(ByteBuffer.wrap(data));
		block.getTransactionList().add(transaction);
	}

	getTransactionOutputsWithIndex(block, t, blockIndexBa);

	getTransactionInputsWithIndex(block, t, blockIndexBa);

	getTransactionScriptsWithIndex(block, t, blockIndexBa);
}
 
Example 10
Project: jigsaw-payment   File: JdbcProtobufTemplate.java   Source Code and License 6 votes vote down vote up
public JdbcProtobufTemplate(JdbcTemplate jdbcTemplate,
		Class<M> messageClass, String tableName) {
	this.jdbcTemplate = jdbcTemplate;
	if (messageClass == null) {
		this.messageClass = this.parseMessageClass();
	} else {
		this.messageClass = messageClass;
	}
	this.descriptor = this.getDescriptor(messageClass);
	if (tableName == null) {
		this.tableName = this.parseTableName();
	} else {
		this.tableName = tableName;
	}

}
 
Example 11
Project: nh-micro   File: MicroMetaDao.java   Source Code and License 6 votes vote down vote up
public List<Map<String, Object>> queryObjByCondition(String tableName, String condition,String cols, String orders,Object[] paramArray) {

		/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
		.getDbSource(dbName);*/
		JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
		String sql = "select "+cols+" from " + tableName + " where "+condition+" order by "+orders;
		logger.debug(sql);
		logger.debug(Arrays.toString(paramArray));
		List<Map<String, Object>> retList = jdbcTemplate.queryForList(sql,paramArray);
		return retList;
	}
 
Example 12
Project: dbadvisor   File: ForeignKeyAnalayzer.java   Source Code and License 6 votes vote down vote up
@Override
protected void analyzeImpl(DatabaseContext ctx) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(ctx.getDataSource());
    String schemaName = ctx.getSchemaName();
    List<Map<String, Object>> foreignKeys = jdbcTemplate.queryForList(FOREIGN_KEY_QUERY, schemaName, schemaName);
    if (foreignKeys.size() > 0) {
        Issue issue = issueBuilder.builder()
            .type(getName())
            .weight(foreignKeys.size())
            .query(FOREIGN_KEY_QUERY)
            .dataSourceName(ctx.getDataSourceName())
            .weightUnit("idx")
            .description(buildDescription(foreignKeys))
            .build();
        issueRepository.addIssue(issue);
    }
}
 
Example 13
Project: plugin-bt-jira   File: JiraImportPluginResourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testUploadDefaultWorkflowScheme() throws Exception {
	final JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
	try {
		// Delete the default project/workflow mapping, where type = '0'
		jdbcTemplate.update(
				"update nodeassociation SET SOURCE_NODE_ID=? WHERE SOURCE_NODE_ID=? AND SOURCE_NODE_ENTITY=? AND SINK_NODE_ID=? AND SINK_NODE_ENTITY=? AND ASSOCIATION_TYPE=?",
				1, 10074, "Project", 10025, "WorkflowScheme", "ProjectScheme");
		resource.upload(new ClassPathResource("csv/upload/nominal-simple.csv").getInputStream(), ENCODING, subscription,
				UploadMode.PREVIEW);
	} finally {
		jdbcTemplate.update(
				"update nodeassociation SET SOURCE_NODE_ID=? WHERE SOURCE_NODE_ID=? AND SOURCE_NODE_ENTITY=? AND SINK_NODE_ID=? AND SINK_NODE_ENTITY=? AND ASSOCIATION_TYPE=?",
				10074, 1, "Project", 10025, "WorkflowScheme", "ProjectScheme");
	}

	final ImportStatus result = jiraResource.getTask(subscription);
	Assert.assertEquals(UploadMode.PREVIEW, result.getMode());
	Assert.assertFalse(result.isFailed());
	Assert.assertEquals(22, result.getStep());
}
 
Example 14
Project: org.ops4j.pax.transx   File: HsqlTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSpringLocalTx() throws Exception {
    DataSource ds = wrap(createHsqlDataSource());
    JdbcTemplate jdbc = new JdbcTemplate(ds);
    TransactionTemplate tx = new TransactionTemplate(new DataSourceTransactionManager(ds));

    jdbc.execute(DROP_USER);
    jdbc.execute(CREATE_TABLE_USER);

    tx.execute(ts -> jdbc.update(INSERT_INTO_USER, 1, "user1"));
    User user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
    assertEquals(new User(1, "user1"), user);
    tx.execute(ts -> jdbc.update(DELETE_FROM_USER_BY_ID, 1));

    tx.execute(ts -> {
        int nb = jdbc.update(INSERT_INTO_USER, 1, "user1");
        ts.setRollbackOnly();
        return nb;
    });
    try {
        user = tx.execute(ts -> jdbc.queryForObject(SELECT_FROM_USER_BY_ID, new BeanPropertyRowMapper<>(User.class), 1));
        fail("Expected a EmptyResultDataAccessException");
    } catch (EmptyResultDataAccessException e) {
        // expected
    }
}
 
Example 15
Project: lemon   File: ArticleExporter.java   Source Code and License 6 votes vote down vote up
public void doExport(File baseDir, JdbcTemplate jdbcTemplate,
        String articleId) throws Exception {
    try {
        String sql = "select id,code,title,content from CMS_ARTICLE where id=?";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, articleId);

        this.exportProperties(baseDir, map);
        this.exportContent(baseDir, map);
    } catch (Exception ex) {
        ex.printStackTrace();
        System.out.println("cannot find article : " + articleId);
    }
}
 
Example 16
Project: java-p6spy   File: SpringTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws SQLException {
  BasicDataSource dataSource = getDataSource("");

  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
  jdbcTemplate.execute("CREATE TABLE employee (id INTEGER)");

  dataSource.close();

  List<MockSpan> finishedSpans = mockTracer.finishedSpans();
  assertEquals(1, finishedSpans.size());
  checkTags(finishedSpans, "myservice", "jdbc:hsqldb:mem:spring");
  checkSameTrace(finishedSpans);

  assertNull(mockTracer.scopeManager().active());
}
 
Example 17
Project: plugin-bt-jira   File: JiraImportPluginResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testZUploadWithInsertWithFailAuth() throws Exception {
	httpServer.stubFor(get(urlPathEqualTo("/login.jsp")).willReturn(aResponse().withStatus(HttpStatus.SC_NOT_FOUND)));
	httpServer.start();

	this.subscription = getSubscription("gStack");
	resource.upload(new ClassPathResource("csv/upload/nominal-complete2.csv").getInputStream(), ENCODING, subscription,
			UploadMode.FULL);
	final ImportStatus result = jiraResource.getTask(subscription);
	Assert.assertEquals(1, result.getChanges().intValue());
	Assert.assertEquals(30, result.getStep());
	Assert.assertEquals(10000, result.getJira().intValue());
	Assert.assertTrue(result.getCanSynchronizeJira());
	Assert.assertTrue(result.getScriptRunner());
	Assert.assertFalse(result.getSynchronizedJira());

	// Greater than the maximal "pcounter"
	final JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
	Assert.assertEquals(5124,
			jdbcTemplate.queryForObject("SELECT pcounter FROM project WHERE ID = ?", Integer.class, 10000).intValue());
}
 
Example 18
Project: odotCore   File: CategoryDao.java   Source Code and License 5 votes vote down vote up
/**
 * Finds the single Category record having the specified Name,
 * and returns it.
 * 
 * @param name
 *          The Name column value of the record to find.
 * @return Category - the Category object whose Name matches
 *         the specified Name, or null if no match was found.
 */
public Category findByName(String name) {
  Category ret = null;
  String sql = "SELECT * FROM " + Category.TABLE_NAME + " WHERE name = ?";
  Object[] paramValues = { name };
  JdbcTemplate jdbc = new JdbcTemplate(getDataSource());
  List<Category> categories = jdbc.query(sql, paramValues, new CategoryRowMapper());
  if (categories.size() > 1) {
    throw new RuntimeException("Expected 1 result from findByName(), instead found " + categories.size()
        + " (DB configuration error, maybe?)");
  }
  if (!categories.isEmpty()) {
    ret = categories.get(0);
  }
  return ret;
}
 
Example 19
Project: OperatieBRP   File: AfnemerindicatieBatchStrategy.java   Source Code and License 5 votes vote down vote up
@Override
public void dumpHisAfnemerindicatieTabel(final File outputFile) {
    LOGGER.info("Genereer hisafnemerindicatie rijen naar {}", outputFile.getAbsolutePath());
    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
        final SqlRowSet sqlRowSet = new JdbcTemplate(masterDataSource).queryForRowSet("select hpa.* from autaut.his_persafnemerindicatie hpa\n"
                + "inner join (select pa.id as afnemerindid \n"
                + "from autaut.persafnemerindicatie pa, autaut.levsautorisatie la where pa.levsautorisatie = la.id and la.dateinde is null) \n"
                + "as x on hpa.persafnemerindicatie = x.afnemerindid");
        while (sqlRowSet.next()) {
            IOUtils.write(String.format("%s,%s,%s,%s,%s,%s,%s,%s%n",
                    sqlRowSet.getString(INDEX_HIS_ID),
                    sqlRowSet.getString(INDEX_HIS_PERSAFNEMERINDICATIE),
                    sqlRowSet.getString(INDEX_HIS_TSREG),
                    StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_TSVERVAL), AfnemerindicatieConversie.NULL_VALUE),
                    StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_DIENSTINHOUD), AfnemerindicatieConversie.NULL_VALUE),
                    StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_DIENSTVERVAL), AfnemerindicatieConversie.NULL_VALUE),
                    StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_DATAANVANGMATERIELEPERIODE), AfnemerindicatieConversie.NULL_VALUE),
                    StringUtils.defaultIfBlank(sqlRowSet.getString(INDEX_HIS_DATEINDEVOLGEN), AfnemerindicatieConversie.NULL_VALUE)
            ), fos, StandardCharsets.UTF_8);
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 20
Project: nh-micro   File: MicroMetaDao.java   Source Code and License 5 votes vote down vote up
public List<Map<String, Object>> queryObjDataPageByCondition(String tableName, String condition,String cols,String orders, int start,int end ) {
	/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
	.getDbSource(dbName);*/
	JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
	String sql = "";
	String tempType=calcuDbType();
	if(tempType!=null && tempType.equals("mysql")){
	//if(dbType!=null && dbType.equals("mysql")){
		int pageRows=end-start;
		String limit=start+","+pageRows;
		sql="select "+cols+" from " + tableName + " where "+condition+" order by "+orders+ " limit "+limit;
	}else{
		String startLimit=" WHERE NHPAGE_RN >= "+start;
		String endLimit=" WHERE ROWNUM < "+end;
		String innerSql="select "+cols+" from " + tableName + " where "+condition+" order by "+orders;
		sql="SELECT * FROM ( SELECT NHPAGE_TEMP.*, ROWNUM NHPAGE_RN FROM ("+ innerSql +" ) NHPAGE_TEMP "+endLimit+" ) "+ startLimit;
	}
	logger.debug(sql);
	
	List<Map<String, Object>> retList = jdbcTemplate.queryForList(sql);
	return retList;
}
 
Example 21
Project: plugin-bt-jira   File: JiraDao.java   Source Code and License 5 votes vote down vote up
/**
 * Return all status changes of issues of given project.
 * 
 * @param dataSource
 *            The data source of JIRA database.
 * @param jira
 *            the JIRA project identifier.
 * @param pkey
 *            the project 'pkey'.
 * @param resultType
 *            the bean type to build in result list.
 * @param timing
 *            When <code>true</code> time spent data is fetched.
 * @param summary
 *            When <code>true</code> Summary is fetched.
 * @return status changes of all issues of given project.
 */
public <T> List<T> getChanges(final DataSource dataSource, final int jira, final String pkey, final Class<T> resultType, final boolean timing,
		final boolean summary) {
	final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	final RowMapper<T> rowMapper = new BeanPropertyRowMapper<>(resultType);

	// First, get all created issues (first change)
	final List<T> issues;
	final String sqlPart = ", RESOLUTION AS resolution, PRIORITY AS priority, issuestatus AS status, ASSIGNEE AS assignee,"
			+ " REPORTER AS reporter, issuetype AS type, ? AS toStatus, DUEDATE AS dueDate, created"
			+ (timing ? ", TIMESPENT AS timeSpent, TIMEESTIMATE AS timeEstimate, TIMEORIGINALESTIMATE AS timeEstimateInit" : "")
			+ (summary ? ", SUMMARY AS summary" : "") + "  FROM jiraissue WHERE PROJECT = ?";
	if (getJiraVersion(dataSource).compareTo("6.0.0") < 0) {
		// JIRA 4-5 implementation, use "pkey"
		issues = jdbcTemplate.query("SELECT ID AS id, pkey AS pkey" + sqlPart, rowMapper, STATUS_OPEN, jira);
	} else {
		// JIRA 6+, "pkey" is no more available in the 'jiraissue' table
		issues = jdbcTemplate.query("SELECT ID AS id, CONCAT(?, issuenum) AS pkey" + sqlPart, rowMapper, pkey + "-", STATUS_OPEN, jira);
	}
	return issues;
}
 
Example 22
Project: nh-micro   File: MicroMetaDao.java   Source Code and License 5 votes vote down vote up
public int updateObjByCondition(String tableName, String condition,String setStr) {
	//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
	JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
	String timeName=getTimeName();
	if(autoOperTime){
		setStr="update_time="+timeName+","+setStr;
	}
	
	String sql = "update " + tableName +" set "+setStr+ " where "+condition;
	logger.debug(sql);
	Integer retStatus=jdbcTemplate.update(sql);
	return retStatus;
}
 
Example 23
Project: EasyTransaction   File: ExpressService.java   Source Code and License 5 votes vote down vote up
public int getUserExpressCount(int userId){
	
	JdbcTemplate jdbcTemplate = util.getJdbcTemplate(Constant.APPID,ExpressDeliverAfterTransMethod.BUSINESS_CODE,(ExpressDeliverAfterTransMethodRequest)null);
	Integer queryForObject = jdbcTemplate.queryForObject("select count(1) from express where user_id = ?", Integer.class,userId);
	if(queryForObject == null){
		queryForObject = 0;
	}
	return queryForObject;
}
 
Example 24
Project: cas-server-4.2.1   File: InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapterTests.java   Source Code and License 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    new JdbcTemplate(dataSource).execute("CREATE TABLE COM_AUDIT_TRAIL ( "
            + "AUD_USER      VARCHAR(100)  NOT NULL, "
            + "AUD_CLIENT_IP VARCHAR(15)    NOT NULL, "
            + "AUD_SERVER_IP VARCHAR(15)    NOT NULL, "
            + "AUD_RESOURCE  VARCHAR(100)  NOT NULL, "
            + "AUD_ACTION    VARCHAR(100)  NOT NULL, "
            + "APPLIC_CD     VARCHAR(5)    NOT NULL, "
            + "AUD_DATE      TIMESTAMP      NOT NULL)");
}
 
Example 25
Project: EasyTransaction   File: WalletService.java   Source Code and License 5 votes vote down vote up
public void doConfirmPay(WalletPayCascadeTccMethodRequest param) {
	JdbcTemplate jdbcTemplate = util.getJdbcTemplate(Constant.APPID,WalletPayTccMethod.METHOD_NAME,param);
	int update = jdbcTemplate.update("update `wallet` set freeze_amount = freeze_amount - ?, total_amount = total_amount - ? where user_id = ?;", 
			param.getPayAmount(),param.getPayAmount(),param.getUserId());
	
	if(update != 1){
		throw new RuntimeException("unknow Exception!");
	}
}
 
Example 26
Project: cas-server-4.2.1   File: JpaLockingStrategyTests.java   Source Code and License 5 votes vote down vote up
private String getOwner(final String appId) {
    final JdbcTemplate simpleJdbcTemplate = new JdbcTemplate(dataSource);
    final List<Map<String, Object>> results = simpleJdbcTemplate.queryForList(
            "SELECT unique_id FROM locks WHERE application_id=?", appId);
    if (results.isEmpty()) {
        return null;
    }
    return (String) results.get(0).get("unique_id");
}
 
Example 27
Project: graphouse   File: ClickHouseRetentionProvider.java   Source Code and License 5 votes vote down vote up
private static List<MetricRetention> loadRetentions(JdbcTemplate jdbcTemplate, String configName) {

        log.info("Loading retentions from ClickHouse, config: " + configName);

        List<MetricRetention> retentions = jdbcTemplate.query(
            "SELECT priority, is_default, regexp, function, " +
                "groupArray(age) AS ages, groupArray(precision) AS precisions FROM (" +
                "   SELECT * FROM system.graphite_retentions WHERE config_name = ? ORDER BY priority, age" +
                ") GROUP BY regexp, function, priority, is_default ORDER BY priority",
            (rs, rowNum) -> {
                String pattern = rs.getString("regexp") + ".*";
                String function = rs.getString("function");
                MetricRetention.MetricDataRetentionBuilder builder = MetricRetention.newBuilder(pattern, function);
                int[] ages = getIntArray(rs.getString("ages"));
                int[] precisions = getIntArray(rs.getString("precisions"));
                for (int i = 0; i < ages.length; i++) {
                    builder.addRetention(ages[i], precisions[i]);
                }
                return builder.build();
            },
            configName
        );
        if (retentions.isEmpty()) {
            throw new IllegalStateException("No retentions found in ClickHouse for config: " + configName);
        }
        log.info("Loaded " + retentions.size() + " retentions");
        return retentions;
    }
 
Example 28
Project: lemon   File: RollbackTaskCmd.java   Source Code and License 5 votes vote down vote up
/**
 * 查找离当前节点最近的上一个userTask.
 */
public String findNearestUserTask(CommandContext commandContext) {
    TaskEntity taskEntity = commandContext.getTaskEntityManager()
            .findTaskById(taskId);

    if (taskEntity == null) {
        logger.debug("cannot find task : {}", taskId);

        return null;
    }

    Graph graph = new ActivitiHistoryGraphBuilder(
            taskEntity.getProcessInstanceId()).build();
    JdbcTemplate jdbcTemplate = ApplicationContextHelper
            .getBean(JdbcTemplate.class);
    String historicActivityInstanceId = jdbcTemplate.queryForObject(
            "SELECT ID_ FROM ACT_HI_ACTINST WHERE TASK_ID_=?",
            String.class, taskId);
    Node node = graph.findById(historicActivityInstanceId);

    String previousHistoricActivityInstanceId = this.findIncomingNode(
            graph, node);

    if (previousHistoricActivityInstanceId == null) {
        logger.debug(
                "cannot find previous historic activity instance : {}",
                taskEntity);

        return null;
    }

    return jdbcTemplate.queryForObject(
            "SELECT TASK_ID_ FROM ACT_HI_ACTINST WHERE ID_=?",
            String.class, previousHistoricActivityInstanceId);
}
 
Example 29
Project: keti   File: V2_0_1__InitializeIdentityZones.java   Source Code and License 5 votes vote down vote up
@Override
public void migrate(final JdbcTemplate jdbcTemplate) throws Exception {
    Long acsAuthorizationZoneId = createDefaultAuthzZone(jdbcTemplate);
    /*
     * Let's find all the possible OAuth issuer_id and client_id combinations that exist in the old database
     * schema.
     */
    Set<ZoneClientEntity> existingOAuthClients = findExistingOAuthClients(jdbcTemplate);
    addOAuthClientsToDefaultAuthzZone(jdbcTemplate, acsAuthorizationZoneId, existingOAuthClients);
    dropConstraintsAndColumns(jdbcTemplate);
    removeDuplicateRows(jdbcTemplate, acsAuthorizationZoneId);
}
 
Example 30
Project: nh-micro   File: MicroMetaDao.java   Source Code and License 5 votes vote down vote up
public int insertObj(String tableName, String cols,String values,final Object[] paramArray, KeyHolder keyHolder, final String idCol) {
	//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
	JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
	String timeName=getTimeName();
	if(autoOperTime){
		cols="create_time,update_time,"+cols;
		values=timeName+","+timeName+","+values;
	}
	final String sql = "insert into " + tableName + " ("+cols+") values ("+values+")";
	logger.debug(sql);
	logger.debug(Arrays.toString(paramArray));

	//Integer retStatus=jdbcTemplate.update(sql,paramArray);
	Integer retStatus=jdbcTemplate.update(new PreparedStatementCreator() { 

		public PreparedStatement createPreparedStatement(Connection con) 
		throws SQLException { 
				String[] keyColNames=new String[1];
				keyColNames[0]=idCol;
				PreparedStatement ps=con.prepareStatement(sql,keyColNames); 
				if(paramArray!=null){
					int size=paramArray.length;
					for(int i=0;i<size;i++){
						ps.setObject(i+1, paramArray[i]);
					}
				}
	
				return ps; 
			} 
		}, keyHolder);		
	
	return retStatus;
}
 
Example 31
Project: alfresco-repository   File: ScriptBundleExecutorImplIntegrationTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    bundleExecutor = ctx.getBean("bundleExecutor", ScriptBundleExecutorImpl.class);
    dataSource = ctx.getBean("dataSource", DataSource.class);
    jdbcTmpl = new JdbcTemplate(dataSource);
}
 
Example 32
Project: nh-micro   File: MicroMetaDao.java   Source Code and License 5 votes vote down vote up
public List<Map<String, Object>> queryObjJoinByCondition(String sql,Object[] paramArray) {

		/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
		.getDbSource(dbName);*/
		JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
		logger.debug(sql);
		logger.debug(Arrays.toString(paramArray));
		List<Map<String, Object>> retList = jdbcTemplate.queryForList(sql,paramArray);
		return retList;
	}
 
Example 33
Project: lemon   File: RollbackCmd.java   Source Code and License 5 votes vote down vote up
/**
 * 判断跳过节点.
 */
public boolean isSkipActivity(String historyActivityId) {
    JdbcTemplate jdbcTemplate = ApplicationContextHelper
            .getBean(JdbcTemplate.class);
    String historyTaskId = jdbcTemplate.queryForObject(
            "select task_id_ from ACT_HI_ACTINST where id_=?",
            String.class, historyActivityId);

    HistoricTaskInstanceEntity historicTaskInstanceEntity = Context
            .getCommandContext().getHistoricTaskInstanceEntityManager()
            .findHistoricTaskInstanceById(historyTaskId);
    String deleteReason = historicTaskInstanceEntity.getDeleteReason();

    return "跳过".equals(deleteReason);
}
 
Example 34
Project: plugin-bt-jira   File: JiraImportPluginResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUploadInvalidVersion() throws Exception {
	thrown.expect(ValidationJsonException.class);
	thrown.expect(MatcherUtil.validationMatcher("jira", "Required JIRA version is 6.0.0, and the current version is 4.4.2"));
	final JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
	try {
		jdbcTemplate.update("update pluginversion SET pluginversion=? WHERE ID = ?", "4.4.2", 10075);
		resource.upload(new ClassPathResource("csv/upload/nominal-simple.csv").getInputStream(), ENCODING, subscription,
				UploadMode.PREVIEW);
	} finally {
		jdbcTemplate.update("update pluginversion SET pluginversion=? WHERE ID = ?", "6.0.1", 10075);
	}
}
 
Example 35
Project: nh-micro   File: MicroMetaDao.java   Source Code and License 5 votes vote down vote up
public int delObjByCondition(String tableName, String condition,Object[] paramArray,int[] typeArray) {
	//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
	JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
	String sql = "delete from " + tableName + " where "+condition;
	logger.debug(sql);
	logger.debug(Arrays.toString(paramArray));
	Integer retStatus=jdbcTemplate.update(sql,paramArray,typeArray);
	return retStatus;
}
 
Example 36
Project: otter-G   File: DdlUtils.java   Source Code and License 5 votes vote down vote up
/**
 * !!! Only supports MySQL
 */
public static List<String> findSchemas(JdbcTemplate jdbcTemplate, final String schemaPattern,
                                       final DdlSchemaFilter ddlSchemaFilter) {
    List<String> schemas = findSchemas(jdbcTemplate, schemaPattern);
    if (ddlSchemaFilter == null) {
        return schemas;
    }
    List<String> filterSchemas = new ArrayList<String>();
    for (String schema : schemas) {
        if (ddlSchemaFilter.accept(schema)) {
            filterSchemas.add(schema);
        }
    }
    return filterSchemas;
}
 
Example 37
Project: plugin-bt-jira   File: JiraDao.java   Source Code and License 5 votes vote down vote up
/**
 * Reset the login failed to bypass CAPTCHA guard.
 * 
 * @param dataSource
 *            The data source of JIRA database.
 * @param login
 *            The user login to reset.
 */
public void clearLoginFailed(final DataSource dataSource, final String login) {
	// Reset the CAPTCHA only for Jira 6+
	if (getJiraVersion(dataSource).compareTo("6.0.0") >= 0) {
		final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		final List<Integer> ids = jdbcTemplate.query("SELECT ID FROM cwd_user WHERE lower_user_name = ?", (rs, n) -> rs.getInt("ID"),
				login.toLowerCase(Locale.ENGLISH));
		if (!ids.isEmpty()) {
			jdbcTemplate.update("UPDATE cwd_user_attributes SET attribute_value=0, lower_attribute_value=0 WHERE attribute_name=? AND user_id=?",
					"login.currentFailedCount", ids.get(0));
		}
	}
}
 
Example 38
Project: otter-G   File: AbstractOperationInterceptor.java   Source Code and License 5 votes vote down vote up
private void init(final JdbcTemplate jdbcTemplate, final String markTableName, final String markTableColumn) {
    int count = jdbcTemplate.queryForInt(MessageFormat.format(checkDataSql, markTableName, GLOBAL_THREAD_COUNT - 1));
    if (count != GLOBAL_THREAD_COUNT) {
        if (logger.isInfoEnabled()) {
            logger.info("Interceptor: init " + markTableName + "'s data.");
        }
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
        transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);// 注意这里强制使用非事务,保证多线程的可见性
        transactionTemplate.execute(new TransactionCallback() {

            public Object doInTransaction(TransactionStatus status) {
                jdbcTemplate.execute(MessageFormat.format(deleteDataSql, markTableName));
                String batchSql = MessageFormat.format(updateSql, new Object[] { markTableName, markTableColumn });
                jdbcTemplate.batchUpdate(batchSql, new BatchPreparedStatementSetter() {

                    public void setValues(PreparedStatement ps, int idx) throws SQLException {
                        ps.setInt(1, idx);
                        ps.setInt(2, 0);
                        // ps.setNull(3, Types.VARCHAR);
                    }

                    public int getBatchSize() {
                        return GLOBAL_THREAD_COUNT;
                    }
                });
                return null;
            }
        });

        if (logger.isInfoEnabled()) {
            logger.info("Interceptor: Init EROSA Client Data: " + updateSql);
        }
    }

}
 
Example 39
Project: otter-G   File: AbstractDbDialect.java   Source Code and License 5 votes vote down vote up
public AbstractDbDialect(JdbcTemplate jdbcTemplate, LobHandler lobHandler, String name, int majorVersion,
                         int minorVersion){
    this.jdbcTemplate = jdbcTemplate;
    this.lobHandler = lobHandler;
    // 初始化transction
    this.transactionTemplate = new TransactionTemplate();
    transactionTemplate.setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource()));
    transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

    this.databaseName = name;
    this.databaseMajorVersion = majorVersion;
    this.databaseMinorVersion = minorVersion;

    initTables(jdbcTemplate);
}
 
Example 40
Project: neo-java   File: BlockDbH2Impl.java   Source Code and License 5 votes vote down vote up
@Override
public Transaction getTransactionWithHash(final UInt256 hash) {
	final JdbcTemplate t = new JdbcTemplate(ds);
	final String sql = getSql("getTransactionWithHash");
	final List<Map<String, Object>> dataList = t.queryForList(sql, hash.toByteArray());

	if (dataList.isEmpty()) {
		return null;
	}

	final Map<String, Object> data = dataList.get(0);

	final byte[] blockIndexBa = (byte[]) data.get("block_index");
	final byte[] transactionIndexBa = (byte[]) data.get(TRANSACTION_INDEX);
	final byte[] transactionBa = (byte[]) data.get("transaction");
	final int transactionIndex = getTransactionIndex(transactionIndexBa);

	final Transaction transaction = new Transaction(ByteBuffer.wrap(transactionBa));

	final Map<Integer, List<TransactionOutput>> outputsMap = getMapList(t,
			"getTransactionOutputsWithBlockAndTransactionIndex", new TransactionOutputMapToObject(), blockIndexBa,
			transactionIndexBa);
	transaction.outputs.addAll(outputsMap.get(transactionIndex));

	final Map<Integer, List<CoinReference>> inputsMap = getMapList(t,
			"getTransactionInputsWithBlockAndTransactionIndex", new CoinReferenceMapToObject(), blockIndexBa,
			transactionIndexBa);
	transaction.inputs.addAll(inputsMap.get(transactionIndex));

	final Map<Integer, List<Witness>> scriptsMap = getMapList(t,
			"getTransactionScriptsWithBlockAndTransactionIndex", new WitnessMapToObject(), blockIndexBa,
			transactionIndexBa);
	transaction.scripts.addAll(scriptsMap.get(transactionIndex));

	return transaction;
}
 
Example 41
Project: plugin-bt-jira   File: JiraDao.java   Source Code and License 5 votes vote down vote up
/**
 * Query JIRA database to collect activities of given users. For now, only the last success connection is
 * registered.
 * 
 * @param dataSource The JIRA datasource to query the user activities.
 * @param users
 *            the users to query.
 * @return activities.
 */
public Map<String, Activity> getActivities(final DataSource dataSource, final Collection<String> users) {
	final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	final Map<String, Activity> result = new HashMap<>();
	if (!users.isEmpty()) {
		jdbcTemplate.query("SELECT u.lower_user_name AS login, attribute_value AS value FROM cwd_user AS u"
				+ " INNER JOIN cwd_user_attributes AS ua ON ua.user_id = u.ID WHERE u.lower_user_name IN (" + newIn(users)
				+ ") AND attribute_name=?;", rs -> {
					final Activity activity = new Activity();
					activity.setLastConnection(new Date(Long.valueOf(rs.getString("value"))));
					result.put(rs.getString("login"), activity);
				}, ArrayUtils.add(users.toArray(), "lastAuthenticated"));
	}
	return result;
}
 
Example 42
Project: lemon   File: RollbackTaskCmd.java   Source Code and License 5 votes vote down vote up
/**
 * 判断跳过节点.
 */
public boolean isSkipActivity(String historyActivityId) {
    JdbcTemplate jdbcTemplate = ApplicationContextHelper
            .getBean(JdbcTemplate.class);
    String historyTaskId = jdbcTemplate.queryForObject(
            "SELECT TASK_ID_ FROM ACT_HI_ACTINST WHERE ID_=?",
            String.class, historyActivityId);

    HistoricTaskInstanceEntity historicTaskInstanceEntity = Context
            .getCommandContext().getHistoricTaskInstanceEntityManager()
            .findHistoricTaskInstanceById(historyTaskId);
    String deleteReason = historicTaskInstanceEntity.getDeleteReason();

    return "跳过".equals(deleteReason);
}
 
Example 43
Project: cas-5.1.0   File: JdbcDataSourceMonitor.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new instance that monitors the given data source.
 *
 * @param executorService the executor service
 * @param maxWait         the max wait
 * @param dataSource      Data source to monitor.
 * @param validationQuery validation query used to monitor the data source. The validation query
 *                        should return at least one result; otherwise results are ignored.
 */
public JdbcDataSourceMonitor(final ExecutorService executorService, final int maxWait,
                             final DataSource dataSource, final String validationQuery) {
    super(JdbcDataSourceMonitor.class.getSimpleName(), executorService, maxWait);
    if (dataSource != null) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    } else {
        LOGGER.debug("No data source is defined to monitor");
    }
    this.validationQuery = validationQuery;
}
 
Example 44
Project: buffer-slayer   File: JdbcTemplateSender.java   Source Code and License 4 votes vote down vote up
JdbcTemplateSender(JdbcTemplate underlying) {
  this.underlying = underlying;
}
 
Example 45
Project: lemon   File: DatabaseUserAuthConnector.java   Source Code and License 4 votes vote down vote up
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}
 
Example 46
Project: spring-test-examples   File: FooRepositoryImpl.java   Source Code and License 4 votes vote down vote up
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  this.jdbcTemplate = jdbcTemplate;
}
 
Example 47
Project: graphouse   File: MetricDataService.java   Source Code and License 4 votes vote down vote up
public MetricDataService(MetricSearch metricSearch, JdbcTemplate clickHouseJdbcTemplate, String graphiteTable) {
    this.metricSearch = metricSearch;
    this.clickHouseJdbcTemplate = clickHouseJdbcTemplate;
    this.graphiteTable = graphiteTable;
}
 
Example 48
Project: idea-forge   File: SecurityConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
public JdbcTemplate JdbcTemplate() {
	return new JdbcTemplate(dataSource);
}
 
Example 49
Project: Learning-Spring-5.0   File: BookDAO_JdbcTemplateSupport.java   Source Code and License 4 votes vote down vote up
@Autowired
public BookDAO_JdbcTemplateSupport(JdbcTemplate jdbcTemplate) {
	// TODO Auto-generated constructor stub
	setJdbcTemplate(jdbcTemplate);
}
 
Example 50
Project: EasyTransaction   File: EasyTransTestConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
public JdbcTemplate wholeJdbcTemplate(DataSource whole){
	return new JdbcTemplate(whole);
}
 
Example 51
Project: BackOffice   File: Database.java   Source Code and License 4 votes vote down vote up
public JdbcTemplate getJdbcTemplate(){
    return this.jdbcTemplate;
}
 
Example 52
Project: otter-G   File: MysqlDialect.java   Source Code and License 4 votes vote down vote up
public MysqlDialect(JdbcTemplate jdbcTemplate, LobHandler lobHandler){
    super(jdbcTemplate, lobHandler);
    sqlTemplate = new MysqlSqlTemplate();
}
 
Example 53
Project: graphouse   File: MetricCacher.java   Source Code and License 4 votes vote down vote up
public MetricCacher(JdbcTemplate clickHouseJdbcTemplate, Monitoring monitoring) {
    this.clickHouseJdbcTemplate = clickHouseJdbcTemplate;
    this.monitoring = monitoring;
}
 
Example 54
Project: pub-service   File: JdbcDaoSupport.java   Source Code and License 4 votes vote down vote up
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
	this.jdbcTemplate = jdbcTemplate;
}
 
Example 55
Project: artemis-disruptor-miaosha   File: ItemDataStartupLoader.java   Source Code and License 4 votes vote down vote up
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  this.jdbcTemplate = jdbcTemplate;
}
 
Example 56
Project: esup-sgc   File: SqlUserInfoService.java   Source Code and License 4 votes vote down vote up
public void setDataSource(DataSource datesource) {
	this.jdbcTemplate = new JdbcTemplate(datesource);
}
 
Example 57
Project: Spring-Security-Third-Edition   File: DataSourceConfig.java   Source Code and License 4 votes vote down vote up
@Bean
@Autowired
public JdbcTemplate jdbcOperations(final DataSource dataSource){
    return new JdbcTemplate(dataSource);
}
 
Example 58
Project: lemon   File: DatabaseUserRepoConnector.java   Source Code and License 4 votes vote down vote up
@Resource
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}
 
Example 59
Project: lemon   File: DatabaseUserStatusUpdater.java   Source Code and License 4 votes vote down vote up
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}
 
Example 60
Project: lemon   File: DatabaseUserFetcher.java   Source Code and License 4 votes vote down vote up
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}