org.springframework.jdbc.core.RowCallbackHandler Java Examples

The following examples show how to use org.springframework.jdbc.core.RowCallbackHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NamedParameterJdbcTemplateTests.java    From effectivejava with Apache License 2.0 7 votes vote down vote up
@Test
public void testQueryWithRowCallbackHandlerNoParameters() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	final List<Customer> customers = new LinkedList<Customer>();
	namedParameterTemplate.query(SELECT_NO_PARAMETERS, new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			Customer cust = new Customer();
			cust.setId(rs.getInt(COLUMN_NAMES[0]));
			cust.setForename(rs.getString(COLUMN_NAMES[1]));
			customers.add(cust);
		}
	});

	assertEquals(1, customers.size());
	assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
	assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NO_PARAMETERS);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #2
Source File: LendDao.java    From Books-Management-System with Apache License 2.0 7 votes vote down vote up
public ArrayList<Lend> lendList(){
    final ArrayList<Lend> list=new ArrayList<Lend>();

    jdbcTemplate.query(LEND_LIST_SQL, new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            resultSet.beforeFirst();
            while (resultSet.next()){
                Lend lend=new Lend();
                lend.setBackDate(resultSet.getDate("back_date"));
                lend.setBookId(resultSet.getLong("book_id"));
                lend.setLendDate(resultSet.getDate("lend_date"));
                lend.setReaderId(resultSet.getInt("reader_id"));
                lend.setSernum(resultSet.getLong("sernum"));
                list.add(lend);
            }
        }
    });
    return list;
}
 
Example #3
Source File: WorkerNodeRegistory.java    From super-cloudops with Apache License 2.0 7 votes vote down vote up
/**
 * Get {@link WorkerNode} by node host
 * 
 * @param host
 * @param port
 * @return
 */
public WorkerNode getWorkerNodeByHostPort(String host, String port) {
	final WorkerNode workerNode = new WorkerNode();
	String querySql = "select * from WORKER_NODE where HOST_NAME = ? AND PORT = ? ";
	jdbcTemplate.query(querySql, new String[] { host, port }, new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			workerNode.setId(rs.getLong("ID"));
			workerNode.setHostName(rs.getString("HOST_NAME"));
			workerNode.setPort(rs.getString("PORT"));
			workerNode.setType(rs.getInt("TYPE"));
			workerNode.setLaunchDateDate(rs.getDate("LAUNCH_DATE"));
			workerNode.setModified(rs.getDate("MODIFIED"));
			workerNode.setCreated(rs.getDate("CREATED"));
		}
	});
	return workerNode;
}
 
Example #4
Source File: JdbcBeanDefinitionReader.java    From spring4-understanding with Apache License 2.0 7 votes vote down vote up
/**
 * Load bean definitions from the database via the given SQL string.
 * @param sql SQL query to use for loading bean definitions.
 * The first three columns must be bean name, property name and value.
 * Any join and any other columns are permitted: e.g.
 * {@code SELECT BEAN_NAME, PROPERTY, VALUE FROM CONFIG WHERE CONFIG.APP_ID = 1}
 * It's also possible to perform a join. Column names are not significant --
 * only the ordering of these first three columns.
 */
public void loadBeanDefinitions(String sql) {
	Assert.notNull(this.jdbcTemplate, "Not fully configured - specify DataSource or JdbcTemplate");
	final Properties props = new Properties();
	this.jdbcTemplate.query(sql, new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			String beanName = rs.getString(1);
			String property = rs.getString(2);
			String value = rs.getString(3);
			// Make a properties entry by combining bean name and property.
			props.setProperty(beanName + "." + property, value);
		}
	});
	this.propReader.registerBeanDefinitions(props);
}
 
Example #5
Source File: WorkerNodeDAO.java    From ecp-uid with Apache License 2.0 7 votes vote down vote up
/**
 * Get {@link WorkerNode} by node host
 * 
 * @param host
 * @param port
 * @return
 */
public WorkerNode getWorkerNodeByHostPort(String host, String port) {
    final WorkerNode workerNode = new WorkerNode();
    String querySql = "select * from WORKER_NODE where HOST_NAME = ? AND PORT = ? ";
    this.jdbcTemplate.query(querySql, new String[] {host, port}, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs)
            throws SQLException {
            workerNode.setId(rs.getLong("ID"));
            workerNode.setHostName(rs.getString("HOST_NAME"));
            workerNode.setPort(rs.getString("PORT"));
            workerNode.setType(rs.getInt("TYPE"));
            workerNode.setLaunchDateDate(rs.getDate("LAUNCH_DATE"));
            workerNode.setModified(rs.getDate("MODIFIED"));
            workerNode.setCreated(rs.getDate("CREATED"));
        }
    });
    return workerNode;
}
 
Example #6
Source File: MessageDaoImpl.java    From ecp-uid with Apache License 2.0 7 votes vote down vote up
@Override
public List<Message> select(String[] ids) {
    List<Message> list = new ArrayList<Message>(ids.length);
    jdbcTemplate.query(String.format(SQL_SELECT, String.join(",", ids)), new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs)
            throws SQLException {
            Message queue = new Message();
            queue.setId(rs.getString("id"));
            queue.setSubject(rs.getString("subject"));
            queue.setPublishTime(rs.getLong("publish_time"));
            queue.setContent(rs.getString("content"));
            list.add(queue);
        }
    });
    return list;
}
 
Example #7
Source File: ExecutionQueueRepositoryImpl.java    From score with Apache License 2.0 6 votes vote down vote up
@Override
public Map<Long, Payload> findPayloadByExecutionIds(Long... ids) {
    String qMarks = StringUtils.repeat("?", ",", ids.length);
    String sqlStat = QUERY_PAYLOAD_BY_EXECUTION_IDS.replace(":IDS", qMarks);

    final Map<Long, Payload> result = new HashMap<>();
    findPayloadByExecutionIdsJdbcTemplate.query(sqlStat, ids, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            result.put(
                    resultSet.getLong(1),
                    new Payload(resultSet.getBytes("payload"))
            );
        }
    });

    return result;
}
 
Example #8
Source File: JdbcBeanDefinitionReader.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
/**
 * Load bean definitions from the database via the given SQL string.
 * @param sql SQL query to use for loading bean definitions.
 * The first three columns must be bean name, property name and value.
 * Any join and any other columns are permitted: e.g.
 * {@code SELECT BEAN_NAME, PROPERTY, VALUE FROM CONFIG WHERE CONFIG.APP_ID = 1}
 * It's also possible to perform a join. Column names are not significant --
 * only the ordering of these first three columns.
 */
public void loadBeanDefinitions(String sql) {
	Assert.notNull(this.jdbcTemplate, "Not fully configured - specify DataSource or JdbcTemplate");
	final Properties props = new Properties();
	this.jdbcTemplate.query(sql, new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			String beanName = rs.getString(1);
			String property = rs.getString(2);
			String value = rs.getString(3);
			// Make a properties entry by combining bean name and property.
			props.setProperty(beanName + "." + property, value);
		}
	});
	this.propReader.registerBeanDefinitions(props);
}
 
Example #9
Source File: NamedParameterJdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryWithRowCallbackHandlerNoParameters() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	final List<Customer> customers = new LinkedList<Customer>();
	namedParameterTemplate.query(SELECT_NO_PARAMETERS, new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			Customer cust = new Customer();
			cust.setId(rs.getInt(COLUMN_NAMES[0]));
			cust.setForename(rs.getString(COLUMN_NAMES[1]));
			customers.add(cust);
		}
	});

	assertEquals(1, customers.size());
	assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
	assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NO_PARAMETERS);
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #10
Source File: DomainDaoImpl.java    From hauth-java with MIT License 6 votes vote down vote up
@Override
public DomainEntity getDomainDetails(String domainId) {
    DomainEntity domainEntity = new DomainEntity();
    jdbcTemplate.query(SqlDefine.sys_rdbms_084, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            domainEntity.setDomain_id(domainId);
            domainEntity.setDomain_desc(resultSet.getString("domain_desc"));
            domainEntity.setDomain_status_desc(resultSet.getString("domain_status_desc"));
            domainEntity.setMaintance_date(resultSet.getString("maintance_date"));
            domainEntity.setCreate_user_id(resultSet.getString("create_user_id"));
            domainEntity.setDomain_modify_user(resultSet.getString("domain_modify_user"));
            domainEntity.setDomain_modify_date(resultSet.getString("domain_modify_date"));
        }
    }, domainId);
    return domainEntity;
}
 
Example #11
Source File: BookDao.java    From Books-Management-System with Apache License 2.0 6 votes vote down vote up
public Book getBook(Long bookId){
    final Book book =new Book();
    jdbcTemplate.query(GET_BOOK_SQL, new Object[]{bookId}, new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
                book.setAuthor(resultSet.getString("author"));
                book.setBookId(resultSet.getLong("book_id"));
                book.setClassId(resultSet.getInt("class_id"));
                book.setIntroduction(resultSet.getString("introduction"));
                book.setIsbn(resultSet.getString("isbn"));
                book.setLanguage(resultSet.getString("language"));
                book.setName(resultSet.getString("name"));
                book.setPressmark(resultSet.getInt("pressmark"));
                book.setPubdate(resultSet.getDate("pubdate"));
                book.setPrice(resultSet.getBigDecimal("price"));
                book.setState(resultSet.getInt("state"));
                book.setPublish(resultSet.getString("publish"));
        }

    });
    return book;
}
 
Example #12
Source File: LendDao.java    From Books-Management-System with Apache License 2.0 6 votes vote down vote up
public ArrayList<Lend> myLendList(int readerId){
    final ArrayList<Lend> list=new ArrayList<Lend>();

    jdbcTemplate.query(MY_LEND_LIST_SQL, new Object[]{readerId},new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            resultSet.beforeFirst();
            while (resultSet.next()){
                Lend lend=new Lend();
                lend.setBackDate(resultSet.getDate("back_date"));
                lend.setBookId(resultSet.getLong("book_id"));
                lend.setLendDate(resultSet.getDate("lend_date"));
                lend.setReaderId(resultSet.getInt("reader_id"));
                lend.setSernum(resultSet.getLong("sernum"));
                list.add(lend);
            }
        }
    });
    return list;

}
 
Example #13
Source File: CacheSpringPersonStore.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void loadCache(final IgniteBiInClosure<Long, Person> clo, Object... args) {
    if (args == null || args.length == 0 || args[0] == null)
        throw new CacheLoaderException("Expected entry count parameter is not provided.");

    int entryCnt = (Integer)args[0];

    final AtomicInteger cnt = new AtomicInteger();

    jdbcTemplate.query("select * from PERSON limit ?", new RowCallbackHandler() {
        @Override public void processRow(ResultSet rs) throws SQLException {
            Person person = new Person(rs.getLong(1), rs.getString(2), rs.getString(3));

            clo.apply(person.id, person);

            cnt.incrementAndGet();
        }
    }, entryCnt);

    System.out.println(">>> Loaded " + cnt + " values into cache.");
}
 
Example #14
Source File: SegmentServiceImpl.java    From ecp-uid with Apache License 2.0 5 votes vote down vote up
private IdSegment updateId(String bizTag)
    throws Exception {
    String querySql = "select step, max_id, last_update_time, current_update_time from id_segment where biz_tag=?";
    String updateSql = "update id_segment set max_id=?, last_update_time=?, current_update_time=now() where biz_tag=? and max_id=?";
    final IdSegment currentSegment = new IdSegment();
    this.jdbcTemplate.query(querySql, new String[] {bizTag}, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs)
            throws SQLException {
            Long step = null;
            Long currentMaxId = null;
            step = rs.getLong("step");
            currentMaxId = rs.getLong("max_id");
            Date lastUpdateTime = new Date();
            if (rs.getTimestamp("last_update_time") != null) {
                lastUpdateTime = (java.util.Date)rs.getTimestamp("last_update_time");
            }
            Date currentUpdateTime = new Date();
            if (rs.getTimestamp("current_update_time") != null) {
                currentUpdateTime = (java.util.Date)rs.getTimestamp("current_update_time");
            }
            currentSegment.setStep(step);
            currentSegment.setMaxId(currentMaxId);
            currentSegment.setLastUpdateTime(lastUpdateTime);
            currentSegment.setCurrentUpdateTime(currentUpdateTime);
        }
    });
    Long newMaxId = currentSegment.getMaxId() + currentSegment.getStep();
    int row = this.jdbcTemplate.update(updateSql, new Object[] {newMaxId, currentSegment.getCurrentUpdateTime(), bizTag, currentSegment.getMaxId()});
    if (row == 1) {
        IdSegment newSegment = new IdSegment();
        newSegment.setStep(currentSegment.getStep());
        newSegment.setMaxId(newMaxId);
        return newSegment;
    } else {
        // 递归,直至更新成功
        return updateId(bizTag);
    }
}
 
Example #15
Source File: BookDao.java    From Books-Management-System with Apache License 2.0 5 votes vote down vote up
public ArrayList<Book> queryBook(String sw){
    String swcx="%"+sw+"%";
    final ArrayList<Book> books=new ArrayList<Book>();
    jdbcTemplate.query(QUERY_BOOK_SQL, new Object[]{swcx,swcx}, new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            resultSet.beforeFirst();
            while (resultSet.next()){
                Book book =new Book();
                book.setAuthor(resultSet.getString("author"));
                book.setBookId(resultSet.getLong("book_id"));
                book.setClassId(resultSet.getInt("class_id"));
                book.setIntroduction(resultSet.getString("introduction"));
                book.setIsbn(resultSet.getString("isbn"));
                book.setLanguage(resultSet.getString("language"));
                book.setName(resultSet.getString("name"));
                book.setPressmark(resultSet.getInt("pressmark"));
                book.setPubdate(resultSet.getDate("pubdate"));
                book.setPrice(resultSet.getBigDecimal("price"));
                book.setState(resultSet.getInt("state"));
                book.setPublish(resultSet.getString("publish"));
                books.add(book);
            }

        }
    });
    return books;
}
 
Example #16
Source File: HibernateLockExceptionStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public List<LockException> getCombinations()
{
    final String sql = "select distinct datasetid, periodid from lockexception";

    final List<LockException> lockExceptions = new ArrayList<>();

    jdbcTemplate.query( sql, new RowCallbackHandler()
    {
        @Override
        public void processRow( ResultSet rs ) throws SQLException
        {
            int dataSetId = rs.getInt( 1 );
            int periodId = rs.getInt( 2 );

            LockException lockException = new LockException();
            Period period = periodService.getPeriod( periodId );
            DataSet dataSet = dataSetStore.get( dataSetId );

            lockException.setDataSet( dataSet );
            lockException.setPeriod( period );

            lockExceptions.add( lockException );
        }
    } );

    return lockExceptions;
}
 
Example #17
Source File: BookDao.java    From Books-Management-System with Apache License 2.0 5 votes vote down vote up
public ArrayList<Book> getAllBooks(){
    final ArrayList<Book> books=new ArrayList<Book>();

    jdbcTemplate.query(QUERY_ALL_BOOKS_SQL, new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            resultSet.beforeFirst();
                while (resultSet.next()){
                    Book book =new Book();
                    book.setPrice(resultSet.getBigDecimal("price"));
                    book.setState(resultSet.getInt("state"));
                    book.setPublish(resultSet.getString("publish"));
                    book.setPubdate(resultSet.getDate("pubdate"));
                    book.setName(resultSet.getString("name"));
                    book.setIsbn(resultSet.getString("isbn"));
                    book.setClassId(resultSet.getInt("class_id"));
                    book.setBookId(resultSet.getLong("book_id"));
                    book.setAuthor(resultSet.getString("author"));
                    book.setIntroduction(resultSet.getString("introduction"));
                    book.setPressmark(resultSet.getInt("pressmark"));
                    book.setLanguage(resultSet.getString("language"));
                    books.add(book);
                }
        }
    });
    return books;

}
 
Example #18
Source File: TrackedEntityProgramAttributeEncryptionTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testTrackedEntityProgramAttributeEncryptedValue() throws IOException
{
    TrackerBundle trackerBundle = renderService.fromJson( new ClassPathResource( "tracker/te_program_with_tea_encryption_data.json" ).getInputStream(),
        TrackerBundleParams.class ).toTrackerBundle();

    List<TrackerBundle> trackerBundles = trackerBundleService.create( TrackerBundleParams.builder()
        .trackedEntities( trackerBundle.getTrackedEntities() )
        .enrollments( trackerBundle.getEnrollments() )
        .events( trackerBundle.getEvents() )
        .build() );

    assertEquals( 1, trackerBundles.size() );

    trackerBundleService.commit( trackerBundles.get( 0 ) );

    List<TrackedEntityInstance> trackedEntityInstances = manager.getAll( TrackedEntityInstance.class );
    assertEquals( 1, trackedEntityInstances.size() );

    TrackedEntityInstance trackedEntityInstance = trackedEntityInstances.get( 0 );

    List<TrackedEntityAttributeValue> attributeValues = trackedEntityAttributeValueService.getTrackedEntityAttributeValues(
        trackedEntityInstance );

    assertEquals( 5, attributeValues.size() );

    // not really a great test, but we are using a random seed for salt, so it changes on every run... we might want to
    // add another EncryptionConfig test profile
    RowCallbackHandler handler = resultSet -> assertNotNull( resultSet.getString( "encryptedvalue" ) );
    jdbcTemplate.query( "select * from trackedentityattributevalue where encryptedvalue is not null ", handler );
}
 
Example #19
Source File: MigrateForm.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
 * 以流方式获得blog,image等大数据
 * 
 * @param id
 *            字段主键
 * @param tableName
 *            表名
 * @param ColumnName
 *            字段名
 * @param jdbcTemplate
 */
public static String getBlob(String id, String tableName, final String columnName, JdbcTemplate jdbcTemplate) {
	String ls_sql = "select " + columnName + " from " + tableName + " where id='" + id + "'";

	// 查询并获得输入流
	jdbcTemplate.query(ls_sql, new RowCallbackHandler() {
		
		public void processRow(ResultSet rs) throws SQLException {
			inStream = rs.getBinaryStream(columnName);
		}
	});

	// 读取流数据并转换成16进制字符串
	if (inStream != null) {
		StringBuffer readInBuffer = new StringBuffer();
		readInBuffer.append("0x");
		byte[] b = new byte[4096];
		try {

			for (; (inStream.read(b)) != -1;) {
				readInBuffer.append(byte2HexStr(b));
			}
		} catch (IOException e) {

			e.printStackTrace();
		}
		String ls_return = readInBuffer.toString().trim();
		if ("0x".equals(ls_return)) {
			ls_return = ls_return + "00";
		}
		return ls_return;
	} else {
		return "0x00";
	}
}
 
Example #20
Source File: ReaderCardDao.java    From Books-Management-System with Apache License 2.0 5 votes vote down vote up
public ReaderCard findReaderByReaderId(int userId){
    final ReaderCard readerCard=new ReaderCard();
    jdbcTemplate.query(FIND_READER_BY_USERID, new Object[]{userId},
            //匿名类实现的回调函数
            new RowCallbackHandler() {
                public void processRow(ResultSet resultSet) throws SQLException {
                    readerCard.setReaderId(resultSet.getInt("reader_id"));
                    readerCard.setPasswd(resultSet.getString("passwd"));
                    readerCard.setName(resultSet.getString("name"));
                    readerCard.setCardState(resultSet.getInt("card_state"));
                }
            });
    return readerCard;
}
 
Example #21
Source File: NamedParameterJdbcTemplateTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryWithRowCallbackHandler() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	final List<Customer> customers = new LinkedList<Customer>();
	namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params, new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			Customer cust = new Customer();
			cust.setId(rs.getInt(COLUMN_NAMES[0]));
			cust.setForename(rs.getString(COLUMN_NAMES[1]));
			customers.add(cust);
		}
	});

	assertEquals(1, customers.size());
	assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
	assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example #22
Source File: TestExample.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
    template.query("select name, status from virt.Pet", new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
            assertEquals("doggie", rs.getString(1));
        }
    });
}
 
Example #23
Source File: WebController.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/count")
public String count() {
    StringBuilder sb = new StringBuilder();
    JdbcTemplate template = new JdbcTemplate(dataSource);
    template.query("select count(*) from customer", new Object[] {}, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
            //System.out.println(rs.getInt(1) + ":" + rs.getString(2));
            sb.append(rs.getObject(1));
        }
    });
    return sb.toString();
}
 
Example #24
Source File: JdbcTaskExecutionDao.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
private List<String> getTaskArguments(long taskExecutionId) {
	final List<String> params = new ArrayList<>();
	RowCallbackHandler handler = new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			params.add(rs.getString(2));
		}
	};
	this.jdbcTemplate.query(getQuery(FIND_ARGUMENT_FROM_ID),
			new MapSqlParameterSource("taskExecutionId", taskExecutionId), handler);
	return params;
}
 
Example #25
Source File: StorageConverter.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Transfer the resources from the source file system handler to the
 * destination.
 */
public void convertStorage() {
    log.info("Start converting storage....");
    setupDataSource();
    if (sourceFileSystemHandler == null) {
        throw new IllegalStateException("The source FileSystemHandler must be set!");
    }
    if (destinationFileSystemHandler == null) {
        throw new IllegalStateException("The destination FileSystemHandler must be set!");
    }
    final AtomicInteger counter = new AtomicInteger(0);
    // read content_resource records that have null file path
    JdbcTemplate template = new JdbcTemplate(dataSource);
    template.query(contentSql, new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            counter.incrementAndGet();
            String id = resultSet.getString(1);
            String path = resultSet.getString(2);
            try {
                InputStream input = sourceFileSystemHandler.getInputStream(id, sourceBodyPath, path);
                if (input != null) {
                    destinationFileSystemHandler.saveInputStream(id, destinationBodyPath, path, input);
                }
                if (deleteFromSource) {
                    sourceFileSystemHandler.delete(id, sourceBodyPath, path);
                }
            } catch (IOException e) {
                if (ignoreMissing) {
                    log.info("Missing file: " + id);
                } else {
                    log.error("Failed to read or write resources from or to the FileSystemHandlers", e);
                    throw new SQLException("Failed to read or write resources from or to the FileSystemHandlers", e);
                }
            }
        }
    });
    log.info("Converted " + counter.get() + " records....");
    log.info("Finished converting storage....");
}
 
Example #26
Source File: FileConverter.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Selects all the encrypted xml documents from krns_maint_doc_t, decrypts them, runs the rules to upgrade them,
 * encrypt them and update krns_maint_doc_t with the upgraded xml.
 *
 * @param settingsMap - the settings
 * @throws Exception
 */
public void runFileConversion(HashMap settingsMap, final String runMode, final String fromRange,
        final String toRange, final boolean hasRangeParameters) throws Exception {

    final EncryptionService encryptService = new EncryptionService((String) settingsMap.get("encryption.key"));

    String docSQL = "SELECT DOC_HDR_ID, DOC_CNTNT FROM krns_maint_doc_t ";

    // If user entered range add the sql parameters and filter results because DOC_HDR_ID is a varchar field.
    if (hasRangeParameters) {
        docSQL = docSQL.concat(" WHERE DOC_HDR_ID >= '" + fromRange + "' AND DOC_HDR_ID <= '" + toRange + "'");
    }
    System.out.println("SQL to run:"  + docSQL);

    jdbcTemplate = new JdbcTemplate(getDataSource(settingsMap));
    jdbcTemplate.query(docSQL, new RowCallbackHandler() {

        public void processRow(ResultSet rs) throws SQLException {
            // Check that all docId's is in range
            if (hasRangeParameters) {
                int docId = Integer.parseInt(rs.getString(1));
                if (docId >= Integer.parseInt(fromRange) && docId <= Integer.parseInt(toRange)) {
                    processDocumentRow(rs.getString(1), rs.getString(2), encryptService, runMode);
                }
            } else {
                processDocumentRow(rs.getString(1), rs.getString(2), encryptService, runMode);
            }
        }
    });

    System.out.println(totalDocs + " maintenance documents upgraded.");

}
 
Example #27
Source File: StorageConverter.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Transfer the resources from the source file system handler to the
 * destination.
 */
public void convertStorage() {
    log.info("Start converting storage....");
    setupDataSource();
    if (sourceFileSystemHandler == null) {
        throw new IllegalStateException("The source FileSystemHandler must be set!");
    }
    if (destinationFileSystemHandler == null) {
        throw new IllegalStateException("The destination FileSystemHandler must be set!");
    }
    final AtomicInteger counter = new AtomicInteger(0);
    // read content_resource records that have null file path
    JdbcTemplate template = new JdbcTemplate(dataSource);
    template.query(contentSql, new RowCallbackHandler() {
        public void processRow(ResultSet resultSet) throws SQLException {
            counter.incrementAndGet();
            String id = resultSet.getString(1);
            String path = resultSet.getString(2);
            try {
                InputStream input = sourceFileSystemHandler.getInputStream(id, sourceBodyPath, path);
                if (input != null) {
                    destinationFileSystemHandler.saveInputStream(id, destinationBodyPath, path, input);
                }
                if (deleteFromSource) {
                    sourceFileSystemHandler.delete(id, sourceBodyPath, path);
                }
            } catch (IOException e) {
                if (ignoreMissing) {
                    log.info("Missing file: " + id);
                } else {
                    log.error("Failed to read or write resources from or to the FileSystemHandlers", e);
                    throw new SQLException("Failed to read or write resources from or to the FileSystemHandlers", e);
                }
            }
        }
    });
    log.info("Converted " + counter.get() + " records....");
    log.info("Finished converting storage....");
}
 
Example #28
Source File: JobExecutionListener.java    From messaging with Apache License 2.0 5 votes vote down vote up
@EventListener(JobExecutionEvent.class)
public void job(JobExecutionEvent executionEvent) {
 log.info("jobExecutionEvent: "
  + executionEvent.getJobExecution().toString());
 jdbcTemplate.query("select * from CONTACT", (RowCallbackHandler) rs -> log
  .info(String.format("id=%s, full_name=%s, email=%s, valid_email=%s",
   rs.getLong("id"), rs.getString("full_name"), rs.getString("email"),
   rs.getBoolean("valid_email"))));
}
 
Example #29
Source File: RoleResourceDaoImpl.java    From batch-scheduler with MIT License 5 votes vote down vote up
private Set<String> getAll(String roleId) {
    Set<String> set = new HashSet<>();
    jdbcTemplate.query(sqlText.getSql("sys100"), new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            set.add(resultSet.getString("res_id"));
        }
    }, roleId);
    return set;
}
 
Example #30
Source File: NamedParameterJdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testQueryWithRowCallbackHandler() throws SQLException {
	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getInt("id")).willReturn(1);
	given(resultSet.getString("forename")).willReturn("rod");

	params.put("id", new SqlParameterValue(Types.DECIMAL, 1));
	params.put("country", "UK");
	final List<Customer> customers = new LinkedList<Customer>();
	namedParameterTemplate.query(SELECT_NAMED_PARAMETERS, params, new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			Customer cust = new Customer();
			cust.setId(rs.getInt(COLUMN_NAMES[0]));
			cust.setForename(rs.getString(COLUMN_NAMES[1]));
			customers.add(cust);
		}
	});

	assertEquals(1, customers.size());
	assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1);
	assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod"));
	verify(connection).prepareStatement(SELECT_NAMED_PARAMETERS_PARSED);
	verify(preparedStatement).setObject(1, 1, Types.DECIMAL);
	verify(preparedStatement).setString(2, "UK");
	verify(preparedStatement).close();
	verify(connection).close();
}