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

The following are top voted examples for showing how to use org.springframework.jdbc.core.RowCallbackHandler. 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: hauth-java   File: DomainDaoImpl.java   Source Code and License 7 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 2
Project: Equella   File: ReplicatedUserPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, UserBean> getInformationForUsers(final Collection<String> userIds)
{
	String sql = config.getUserInfo();
	if( Check.isEmpty(sql) )
	{
		return null;
	}

	final Map<String, UserBean> users = new HashMap<String, UserBean>();
	handleIn(sql, userIds, new RowCallbackHandler()
	{
		@Override
		public void processRow(ResultSet set) throws SQLException
		{
			String id = set.getString(1);
			String username = set.getString(2);
			String fname = set.getString(3);
			String lname = set.getString(4);
			String email = set.getString(5);
			DefaultUserBean user = new DefaultUserBean(id, username, fname, lname, email);
			users.put(id, user);
		}
	});
	return users;
}
 
Example 3
Project: Equella   File: ReplicatedUserPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public Pair<ChainResult, Collection<RoleBean>> getRolesForUser(final String userID)
{
	String sql = config.getUserRoles();
	if( Check.isEmpty(sql) )
	{
		return null;
	}

	final Collection<RoleBean> roles = new ArrayList<RoleBean>();
	executeSql(sql, getParamValues(sql, userID), new RowCallbackHandler()
	{
		@Override
		public void processRow(ResultSet set) throws SQLException
		{
			String id = set.getString(1);
			String name = set.getString(2);
			roles.add(new DefaultRoleBean(id, name));
		}
	});
	return new Pair<ChainResult, Collection<RoleBean>>(ChainResult.CONTINUE, roles);
}
 
Example 4
Project: Equella   File: ReplicatedUserPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public Collection<RoleBean> searchRoles(final String query)
{
	String sql = config.getSearchRoles();
	if( Check.isEmpty(sql) )
	{
		return null;
	}

	final Collection<RoleBean> roles = new ArrayList<RoleBean>();
	executeSql(sql, getParamValues(sql, query.replace('*', '%')), new RowCallbackHandler()
	{
		@Override
		public void processRow(ResultSet set) throws SQLException
		{
			String id = set.getString(1);
			String name = set.getString(2);
			roles.add(new DefaultRoleBean(id, name));
		}
	});
	return roles;
}
 
Example 5
Project: Equella   File: ReplicatedUserPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, RoleBean> getInformationForRoles(final Collection<String> roleIds)
{
	String sql = config.getRoleInfo();
	if( Check.isEmpty(sql) )
	{
		return null;
	}

	final Map<String, RoleBean> roles = Maps.newHashMapWithExpectedSize(roleIds.size());
	handleIn(sql, roleIds, new RowCallbackHandler()
	{
		@Override
		public void processRow(ResultSet set) throws SQLException
		{
			String id = set.getString(1);
			String name = set.getString(2);
			roles.put(id, new DefaultRoleBean(id, name));
		}
	});
	return roles;
}
 
Example 6
Project: Equella   File: ReplicatedUserPlugin.java   Source Code and License 6 votes vote down vote up
private UserInfo authenticate(String username)
{
	String sql = config.getAuthenticate();

	final UserInfo user = new UserInfo();
	executeSql(sql, getParamValues(sql, username), new RowCallbackHandler()
	{
		@Override
		public void processRow(ResultSet set) throws SQLException
		{
			boolean suspended = set.getInt(3) > 0;
			if( suspended )
			{
				throw new DisabledException("User suspended");
			}
			String id = set.getString(1);
			String password = set.getString(2);

			user.setId(id);
			user.setPassword(password);
		}
	});
	return user;
}
 
Example 7
Project: Equella   File: ReplicatedUserPlugin.java   Source Code and License 6 votes vote down vote up
private Map<String, GroupBean> getGroupInfo(Collection<String> ids)
{
	final Map<String, GroupBean> groupMap = new HashMap<String, GroupBean>();
	String sql = config.getGroupInfo();
	if( Check.isEmpty(sql) || Check.isEmpty(ids) )
	{
		return groupMap;
	}

	handleIn(sql, ids, new RowCallbackHandler()
	{
		@Override
		public void processRow(ResultSet set) throws SQLException
		{
			String id = set.getString(1);
			String name = set.getString(2);
			GroupBean group = new DefaultGroupBean(id, name);
			groupMap.put(id, group);
		}
	});
	return groupMap;
}
 
Example 8
Project: lams   File: JdbcBeanDefinitionReader.java   Source Code and License 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
Project: batch-scheduler   File: GroupTaskDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<GroupTaskEntity> getJobList(String groupId) {
    List<GroupTaskEntity> list = new ArrayList<>();
    jdbcTemplate.query(batchSqlText.getSql("sys_rdbms_133"), new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            GroupTaskEntity one = new GroupTaskEntity();
            one.setCodeNumber(resultSet.getString("code_number"));
            one.setDomainId(resultSet.getString("domain_id"));
            one.setGroupId(resultSet.getString("group_id"));
            one.setJobKey(resultSet.getString("job_key"));
            one.setPosTop(resultSet.getInt("pos_top"));
            one.setTaskId(resultSet.getString("task_id"));
            one.setTaskType(resultSet.getString("task_type"));
            one.setTaskTypeDesc(resultSet.getString("task_type_desc"));
            one.setTaskDesc(resultSet.getString("task_type_desc"));
            one.setPosLeft(resultSet.getInt("pos_left"));
            list.add(one);
        }
    }, groupId);
    logger.debug("group id is:{},result is:{}", groupId, list);
    return list;
}
 
Example 10
Project: spring4-understanding   File: JdbcBeanDefinitionReader.java   Source Code and License 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 11
Project: spring4-understanding   File: NamedParameterJdbcTemplateTests.java   Source Code and License 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 12
Project: reactive-data   File: ModelJdbcRepository.java   Source Code and License 6 votes vote down vote up
@Override
public RegressionModel findOne(String id) {
  final List<RegressionModel> models = new ArrayList<>();
  jdbcTemplate.query(SELECT_MODEL.replaceFirst("@", id), new RowCallbackHandler() {
    
    @Override
    public void processRow(ResultSet rs) throws SQLException {
      RegressionModel m = new RegressionModel();
      try {
        m.deserializeClassifierFromJson(rs.getString(1));
        //m.setLongId(rs.getLong(2));
        m.setStringId(rs.getString(2));
        m.setGeneratedOn(rs.getDate(3).getTime());
        models.add(m);
      } catch (IOException e) {
        throw new SQLException("Unable to deserialze model from string", e);
      }
      
    }
  });
  return models.isEmpty() ? null : models.get(0);
}
 
Example 13
Project: xqres   File: UserInfoDAOImpl.java   Source Code and License 6 votes vote down vote up
@Override
public UserInfo findUserByUserName(String userName) {
	// TODO Auto-generated method stub
	String sql = "select * from user_info where user_name = ?";
	final UserInfo user = new UserInfo();
	jdbcTemplate.query(sql, new Object[]{userName}, new RowCallbackHandler() {
		
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			// TODO Auto-generated method stub
			if (rs.next()) {
				user.setUserId(rs.getLong("user_id"));
				user.setUserName(rs.getString("user_name"));
			}
		}
	});
	
	if (user.getUserId() == 0) {
		return null;
	}
	
	return user;
}
 
Example 14
Project: xqres   File: OrderItemDAOImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<OrderItem> queryOrderItems() {
	// TODO Auto-generated method stub
	String sql = "SELECT * FROM ORDER_ITEM";
	final List<OrderItem> list = new ArrayList<OrderItem>();
	jdbcTemplate.query(sql, new RowCallbackHandler() {
		
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			// TODO Auto-generated method stub
			OrderItem item = new OrderItem();
			item.setItemId(rs.getLong("ITEM_ID"));
			item.setGroupId(rs.getLong("GROUP_ID"));
			item.setStatus(rs.getInt("STATUS"));
			item.setItemCode(rs.getString("ITEM_CODE"));
			item.setItemName(rs.getString("ITEM_NAME"));
			item.setItemPrice(rs.getFloat("ITEM_PRICE"));
			item.setCreateDate(rs.getTimestamp("CREATE_DATE"));
			item.setItemPicurl(rs.getString("ITEM_PICURL"));
			item.setItemDetails(rs.getString("ITEM_DETAILS"));
			list.add(item);
		}
	});
	
	return list;
}
 
Example 15
Project: xqres   File: OrderItemDAOImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<FoodInfo> selectFoods() {
	String sql = "select food_id, food_name, food_price from food_info";
	final List<FoodInfo> list = new ArrayList<FoodInfo>();
	jdbcTemplate.query(sql, new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			FoodInfo info = new FoodInfo();
			info.setFoodId(rs.getLong("food_id"));
			info.setFoodName(rs.getString("food_name"));
			info.setFoodPrice(rs.getFloat("food_price"));
			list.add(info);
		}
	});

	return list;
}
 
Example 16
Project: dhis2-core   File: HibernateOrganisationUnitStore.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, Set<String>> getOrganisationUnitDataSetAssocationMap()
{
    final String sql = "select ds.uid as ds_uid, ou.uid as ou_uid from datasetsource d " +
        "left join organisationunit ou on ou.organisationunitid=d.sourceid " +
        "left join dataset ds on ds.datasetid=d.datasetid";

    final SetMap<String, String> map = new SetMap<>();

    jdbcTemplate.query( sql, new RowCallbackHandler()
    {
        @Override
        public void processRow( ResultSet rs ) throws SQLException
        {
            String dataSetId = rs.getString( "ds_uid" );
            String organisationUnitId = rs.getString( "ou_uid" );
            map.putValue( organisationUnitId, dataSetId );
        }
    } );

    return map;
}
 
Example 17
Project: lypBook   File: UserDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public User getUserByLogin(String username, String password) {
    String sqlStr = "select * from tuser where username=? and password=?";
    final User user = new User();
    jdbc.query(sqlStr,new Object[]{username,password},new RowCallbackHandler(){
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {

                user.setUid(resultSet.getInt("uid"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));

        }
    });
    return user;
}
 
Example 18
Project: AgileAlligators   File: HibernateOrganisationUnitStore.java   Source Code and License 6 votes vote down vote up
@Override
public Map<String, Set<String>> getOrganisationUnitDataSetAssocationMap()
{
    final String sql = "select ds.uid as ds_uid, ou.uid as ou_uid from datasetsource d " +
        "left join organisationunit ou on ou.organisationunitid=d.sourceid " +
        "left join dataset ds on ds.datasetid=d.datasetid";

    final SetMap<String, String> map = new SetMap<>();

    jdbcTemplate.query( sql, new RowCallbackHandler()
    {
        @Override
        public void processRow( ResultSet rs ) throws SQLException
        {
            String dataSetId = rs.getString( "ds_uid" );
            String organisationUnitId = rs.getString( "ou_uid" );
            map.putValue( organisationUnitId, dataSetId );
        }
    } );

    return map;
}
 
Example 19
Project: ignite   File: CacheSpringPersonStore.java   Source Code and License 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 20
Project: service   File: OrderServiceImpl.java   Source Code and License 6 votes vote down vote up
private Map<Long, Long> queryBookedBookablePackageIds(Collection<Long> userIds) {
    final Map<Long, Long> packageIdsMap = new HashMap<Long, Long>();
    String sql = "SELECT A.UserId, A.Id AS PackageId " +
            "FROM SG_SubjectOrderPackage A " +
            "INNER JOIN SG_SubjectSku B ON A.SkuId=B.Id " +
            "INNER JOIN SG_BookedCourse C ON A.Id=C.PackageId " +
            "INNER JOIN SG_CourseSku D ON C.CourseSkuId=D.Id " +
            "WHERE A.UserId IN (" + StringUtils.join(userIds, ",") + ") AND A.BookableCount>0 AND A.Status=1 AND B.Status<>0 AND C.Status<>0 AND D.Status<>0 " +
            "ORDER BY D.StartTime ASC";
    query(sql, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
            long userId = rs.getLong("userId");
            long packageId = rs.getLong("packageId");
            if (!packageIdsMap.containsKey(userId)) packageIdsMap.put(userId, packageId);
        }
    });

    return packageIdsMap;
}
 
Example 21
Project: service   File: OrderServiceImpl.java   Source Code and License 6 votes vote down vote up
private Map<Long, Long> queryNotBookedBookablePackageIds(Collection<Long> userIds) {
    final Map<Long, Long> packageIdsMap = new HashMap<Long, Long>();
    String sql = "SELECT A.UserId, A.Id AS PackageId " +
            "FROM SG_SubjectOrderPackage A " +
            "INNER JOIN SG_SubjectSku B ON A.SkuId=B.Id " +
            "LEFT JOIN SG_BookedCourse C ON A.Id=C.PackageId AND C.Status<>0 " +
            "WHERE A.UserId IN (" + StringUtils.join(userIds, ",") + ") AND A.BookableCount>0 AND A.Status=1 AND B.Status<>0 AND C.Id IS NULL";
    query(sql, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
            long userId = rs.getLong("userId");
            long packageId = rs.getLong("packageId");
            if (!packageIdsMap.containsKey(userId)) packageIdsMap.put(userId, packageId);
        }
    });

    return packageIdsMap;
}
 
Example 22
Project: service   File: OrderServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Set<Integer> getOrderPackageTypes(long orderId) {
    final Set<Integer> packageTypes = new HashSet<Integer>();
    String sql = "SELECT B.CourseId, C.Type FROM SG_SubjectOrderPackage A INNER JOIN SG_SubjectSku B ON A.SkuId=B.Id INNER JOIN SG_Subject C ON B.SubjectId=C.Id WHERE A.OrderId=? AND A.Status<>0 AND B.Status<>0 AND C.Status<>0";
    query(sql, new Object[] { orderId }, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
            long courseId = rs.getLong("CourseId");
            int type = rs.getInt("Type");
            if (type == Subject.Type.TRIAL) {
                packageTypes.add(OrderPackage.Type.TRIAL);
            } else if (courseId > 0) {
                packageTypes.add(OrderPackage.Type.SINGLE_COURSE);
            } else {
                packageTypes.add(OrderPackage.Type.PACKAGE);
            }
        }
    });

    return packageTypes;
}
 
Example 23
Project: service   File: ChildServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ChildRecord getRecord(long teacherUerId, long childId, long courseId, long courseSkuId) {
    final List<ChildRecord> records = new ArrayList<ChildRecord>();
    String sql = "SELECT Tags, Content FROM SG_ChildRecord WHERE TeacherUserId=? AND ChildId=? AND CourseId=? AND CourseSkuId=? AND Status=1 LIMIT 1";
    query(sql, new Object[] { teacherUerId, childId, courseId, courseSkuId }, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
            ChildRecord record = new ChildRecord();
            List<Integer> tags = new ArrayList<Integer>();
            for (String tagId : Splitter.on(",").trimResults().omitEmptyStrings().split(rs.getString("Tags"))) {
                tags.add(Integer.valueOf(tagId));
            }
            record.setTags(tags);
            record.setContent(rs.getString("Content"));

            records.add(record);
        }
    });

    return records.isEmpty() ? ChildRecord.EMPTY_RECORD : records.get(0);
}
 
Example 24
Project: WebAPI   File: VocabularyService.java   Source Code and License 6 votes vote down vote up
@POST
@Path("{sourceKey}/resolveConceptSetExpression")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Collection<Long> resolveConceptSetExpression(@PathParam("sourceKey") String sourceKey, ConceptSetExpression conceptSetExpression) {
  Source source = getSourceRepository().findBySourceKey(sourceKey);
  String tqName = "cdm_database_schema";
  String tqValue = source.getTableQualifier(SourceDaimon.DaimonType.Vocabulary);
  ConceptSetExpressionQueryBuilder builder = new ConceptSetExpressionQueryBuilder();
  String query = builder.buildExpressionQuery(conceptSetExpression);
  PreparedStatementRenderer psr = new PreparedStatementRenderer(source, query, tqName, tqValue);
  final ArrayList<Long> identifiers = new ArrayList<>();
  getSourceJdbcTemplate(source).query(psr.getSql(), psr.getSetter(), new RowCallbackHandler() {
    @Override
    public void processRow(ResultSet rs) throws SQLException {
      identifiers.add(rs.getLong("CONCEPT_ID"));
    }
  });

  return identifiers;
}
 
Example 25
Project: TemporalDB   File: JdbcOrderDAO.java   Source Code and License 6 votes vote down vote up
@Override
public void findAll(Timestamp modifiedAfter, final Consumer consumer)
{
    String sql = "SELECT * FROM ORDERS where orders.update_time >= ?";

    
    getJdbcTemplate().query(sql, new Object[] { modifiedAfter }, new RowCallbackHandler() {

        @Override
        public void processRow(ResultSet row) throws SQLException
        {
            
            Order order = new Order();
            order.setOrderId(row.getLong("order_id"));
            order.setNote(row.getString("note"));
            order.setSaleCode(row.getInt("sale_code"));

            Date createTime = new java.util.Date(row.getTimestamp("create_time").getTime());
            order.setCreateTime(createTime);
            Date updateTime = new java.util.Date(row.getTimestamp("update_time").getTime());
            order.setUpdateTime(updateTime);

            consumer.consume(order);
        }
    });
}
 
Example 26
Project: lavagna   File: CardLabelRepository.java   Source Code and License 6 votes vote down vote up
/**
 * Return a mapping
 *
 * {labelListValue : {labelId : labelListValueId}}
 *
 * @param labelListValues
 * @return
 */
public Map<String, Map<Integer, Integer>> findLabelListValueMapping(List<String> labelListValues) {

    if (labelListValues.isEmpty()) {
        return Collections.emptyMap();
    }

    final Map<String, Map<Integer, Integer>> res = new HashMap<>();
    jdbc.query(queries.findLabelListValueMapping(), new MapSqlParameterSource("values", labelListValues),
        new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                String name = rs.getString("CARD_LABEL_LIST_VALUE");
                if (!res.containsKey(name)) {
                    res.put(name, new HashMap<Integer, Integer>());
                }
                res.get(name).put(rs.getInt("CARD_LABEL_ID_FK"), rs.getInt("CARD_LABEL_LIST_VALUE_ID"));
            }
        });
    return res;
}
 
Example 27
Project: NewReportServlet4H5   File: DBTool.java   Source Code and License 6 votes vote down vote up
/**
 * 
 * @param tcKey
 * @return
 */
public String getTcValueBytcKey(String tcKey) {
	String sql = " select tc_value from t_uitest_cases where tc_key=? ";
	Object params[] = new Object[] { tcKey };
	final String[] tcValue = { "" };
	System.out.println(jdbcTemplate);
	jdbcTemplate.query(sql, params, new RowCallbackHandler() {

		@Override
		public void processRow(ResultSet rs) throws SQLException {

			tcValue[0] = rs.getString("tc_value");
		}
	});

	return tcValue[0];

}
 
Example 28
Project: class-guard   File: NamedParameterJdbcTemplateTests.java   Source Code and License 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 29
Project: score   File: ExecutionQueueRepositoryImpl.java   Source Code and License 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 30
Project: opennmszh   File: JdbcWebAlarmRepository.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public int[] countMatchingAlarmsBySeverity(AlarmCriteria criteria) {
    String selectClause = "SELECT SEVERITY, COUNT(ALARMID) AS ALARMCOUNT FROM ALARMS LEFT OUTER JOIN NODE USING (NODEID) LEFT OUTER JOIN SERVICE USING (SERVICEID) ";
    String sql = getSql(selectClause, criteria);
    sql = sql + " GROUP BY SEVERITY";

    final int[] alarmCounts = new int[8];
    jdbc().query(sql, paramSetter(criteria), new RowCallbackHandler() {

        public void processRow(ResultSet rs) throws SQLException {
            int severity = rs.getInt("SEVERITY");
            int alarmCount = rs.getInt("ALARMCOUNT");

            alarmCounts[severity] = alarmCount;

        }

    });

    return alarmCounts;
}
 
Example 31
Project: opennmszh   File: JdbcWebEventRepository.java   Source Code and License 6 votes vote down vote up
/** {@inheritDoc} */
public int[] countMatchingEventsBySeverity(EventCriteria criteria) {
    String selectClause = "SELECT EVENTSEVERITY, COUNT(*) AS EVENTCOUNT FROM EVENTS LEFT OUTER JOIN NODE USING (NODEID) LEFT OUTER JOIN SERVICE USING (SERVICEID) ";
    String sql = getSql(selectClause, criteria);
    //sql = sql + " AND EVENTDISPLAY='Y'";
    sql = sql + " GROUP BY EVENTSEVERITY";
    
    final int[] alarmCounts = new int[8];
    jdbc().query(sql, paramSetter(criteria), new RowCallbackHandler(){

        public void processRow(ResultSet rs) throws SQLException {
            int severity = rs.getInt("EVENTSEVERITY");
            int alarmCount = rs.getInt("EVENTCOUNT");
            
            alarmCounts[severity] = alarmCount;
            
        }
        
    });
    return alarmCounts;
}
 
Example 32
Project: whois   File: ResourceDataDao.java   Source Code and License 6 votes vote down vote up
public AuthoritativeResource load(final String source) {
    final SortedRangeSet<Asn, AsnRange> autNums = new SortedRangeSet<>();
    final SortedRangeSet<Ipv4, Ipv4Range> inetnums = new SortedRangeSet<>();
    final SortedRangeSet<Ipv6, Ipv6Range> inet6nums = new SortedRangeSet<>();

    jdbcTemplate.query("SELECT resource FROM authoritative_resource WHERE source = ?", new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
            String resource = rs.getString(1);
            if (resource.startsWith("AS")) {
                autNums.add(resource.contains("-") ? AsnRange.parse(resource) : Asn.parse(resource).asRange());
            } else if (resource.indexOf(':') >= 0) {
                inet6nums.add(Ipv6Range.parse(resource));
            } else {
                inetnums.add(Ipv4Range.parse(resource));
            }
        }

    }, source);
    return new AuthoritativeResource(autNums, inetnums, inet6nums);
}
 
Example 33
Project: OpenNMS   File: JdbcWebEventRepository.java   Source Code and License 6 votes vote down vote up
/** {@inheritDoc} */
public int[] countMatchingEventsBySeverity(EventCriteria criteria) {
    String selectClause = "SELECT EVENTSEVERITY, COUNT(*) AS EVENTCOUNT FROM EVENTS LEFT OUTER JOIN NODE USING (NODEID) LEFT OUTER JOIN SERVICE USING (SERVICEID) ";
    String sql = getSql(selectClause, criteria);
    //sql = sql + " AND EVENTDISPLAY='Y'";
    sql = sql + " GROUP BY EVENTSEVERITY";
    
    final int[] alarmCounts = new int[8];
    jdbc().query(sql, paramSetter(criteria), new RowCallbackHandler(){

        public void processRow(ResultSet rs) throws SQLException {
            int severity = rs.getInt("EVENTSEVERITY");
            int alarmCount = rs.getInt("EVENTCOUNT");
            
            alarmCounts[severity] = alarmCount;
            
        }
        
    });
    return alarmCounts;
}
 
Example 34
Project: hauth-java   File: RoleResourceDaoImpl.java   Source Code and License 5 votes vote down vote up
private Set<String> getAll(String roleId) {
    Set<String> set = new HashSet<>();
    jdbcTemplate.query(SqlDefine.sys_rdbms_100, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            set.add(resultSet.getString("res_id"));
        }
    }, roleId);
    return set;
}
 
Example 35
Project: hauth-java   File: UserResourceDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Set<String> findAll(String userId) {
    Set<String> set = new HashSet<>();
    jdbcTemplate.query(SqlDefine.sys_rdbms_115, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            set.add(resultSet.getString("res_id"));
        }
    }, userId);
    return set;
}
 
Example 36
Project: hauth-java   File: RoleDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public RoleEntity getDetails(String roleId) {
    RoleEntity roleEntity = new RoleEntity();
    jdbcTemplate.query(SqlDefine.sys_rdbms_208, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            roleEntity.setDomain_id(resultSet.getString("domain_id"));
            roleEntity.setRole_id(resultSet.getString("role_id"));
            roleEntity.setCode_number(resultSet.getString("code_number"));
            roleEntity.setRole_name(resultSet.getString("role_name"));
            roleEntity.setDomain_desc(resultSet.getString("domain_desc"));
        }
    }, roleId);
    return roleEntity;
}
 
Example 37
Project: Equella   File: ReplicatedUserPlugin.java   Source Code and License 5 votes vote down vote up
@Override
public GroupBean getParentGroupForGroup(final String groupID)
{
	String sql = config.getParentGroup();
	if( Check.isEmpty(sql) )
	{
		return null;
	}

	final UserInfo groupInfo = new UserInfo();
	final Object[] ids = getParamValues(sql, groupID);
	executeSql(sql, ids, new RowCallbackHandler()
	{
		@Override
		public void processRow(ResultSet set) throws SQLException
		{
			String groupId = set.getString(1);
			String groupName = set.getString(2);
			groupInfo.setId(groupId);
			groupInfo.setPassword(groupName);
		}
	});

	if( groupInfo.getId() == null )
	{
		return null;
	}

	return new DefaultGroupBean(groupInfo.getId(), groupInfo.getPassword());
}
 
Example 38
Project: Equella   File: ReplicatedUserPlugin.java   Source Code and License 5 votes vote down vote up
private List<String> getIds(String sql, Object[] values)
{
	final List<String> ids = new ArrayList<String>();
	executeSql(sql, values, new RowCallbackHandler()
	{
		@Override
		public void processRow(ResultSet set) throws SQLException
		{
			ids.add(set.getString(1));
		}
	});
	return ids;
}
 
Example 39
Project: batch-scheduler   File: RoleResourceDaoImpl.java   Source Code and 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 40
Project: batch-scheduler   File: UserResourceDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Set<String> findAll(String userId) {
    Set<String> set = new HashSet<>();
    jdbcTemplate.query(sqlText.getSql("sys115"), new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet resultSet) throws SQLException {
            set.add(resultSet.getString("res_id"));
        }
    }, userId);
    return set;
}
 
Example 41
Project: factcast   File: PGSynchronizedQuery.java   Source Code and License 5 votes vote down vote up
PGSynchronizedQuery(@NonNull JdbcTemplate jdbcTemplate, @NonNull String sql,
        @NonNull PreparedStatementSetter setter, @NonNull RowCallbackHandler rowHandler,
        AtomicLong serialToContinueFrom, PGLatestSerialFetcher fetcher) {
    this.serialToContinueFrom = serialToContinueFrom;
    latestFetcher = fetcher;
    this.jdbcTemplate = jdbcTemplate;
    this.sql = sql;
    this.setter = setter;
    this.rowHandler = rowHandler;

    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(
            jdbcTemplate.getDataSource());
    transactionTemplate = new TransactionTemplate(transactionManager);
}
 
Example 42
Project: plugin-bt-jira   File: JiraDao.java   Source Code and License 5 votes vote down vote up
/**
 * Return all components attached to an issue of a project.
 * 
 * @param dataSource
 *            The data source of JIRA database.
 * @param jira
 *            the JIRA project identifier.
 * @return all custom fields attached to an issue of a project ordered by issue. Key is the issue.
 */
public Map<Integer, Collection<Integer>> getComponentsAssociation(final DataSource dataSource, final int jira) {
	final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	final Map<Integer, Collection<Integer>> result = new HashMap<>();

	jdbcTemplate.query(
			"SELECT n.SOURCE_NODE_ID AS issue, n.SINK_NODE_ID AS c"
					+ " FROM nodeassociation AS n INNER JOIN jiraissue AS i ON (i.ID = n.SOURCE_NODE_ID AND i.PROJECT = ?)"
					+ " WHERE n.SOURCE_NODE_ENTITY=? AND n.SINK_NODE_ENTITY=? AND n.ASSOCIATION_TYPE=?",
			(RowCallbackHandler) rs -> result.computeIfAbsent(rs.getInt("issue"), k -> new ArrayList<>()).add(rs.getInt("c")), jira, "Issue",
			"Component", "IssueComponent");
	return result;
}
 
Example 43
Project: plugin-bt-jira   File: JiraDao.java   Source Code and License 5 votes vote down vote up
/**
 * Return all parent relationships of tickets of given project.
 * 
 * @param dataSource
 *            The data source of JIRA database.
 * @param project
 *            Jira project identifier. Required to filter custom field against contexts.
 * @return all parent relationships of tickets of given project. Key is the subtask, value is the parent issue.
 */
public Map<Integer, Integer> getSubTasks(final DataSource dataSource, final int project) {
	final JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	final Map<Integer, Integer> result = new HashMap<>();
	jdbcTemplate.query(
			"SELECT l.SOURCE AS parent,l.DESTINATION AS subTask FROM issuelink AS l"
					+ " INNER JOIN issuelinktype AS t ON (l.LINKTYPE = t.ID AND t.LINKNAME=?)"
					+ " INNER JOIN jiraissue AS i ON (i.ID = l.SOURCE AND i.PROJECT = ?);",
			(RowCallbackHandler) rs -> result.put(rs.getInt("subTask"), rs.getInt("parent")), "jira_subtask_link", project);
	return result;
}
 
Example 44
Project: spring4-understanding   File: NamedParameterJdbcTemplateTests.java   Source Code and License 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 45
Project: Rapture   File: PostgresDocHandler.java   Source Code and License 5 votes vote down vote up
public void visitKeys(String prefix, final StoreKeyVisitor iStoreKeyVisitor) {
    String sql = String.format("SELECT key, content\n"
            + "FROM %s\n"
            + "WHERE key LIKE :like_prefix;", tableName);
    RowCallbackHandler callback = new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
            String key = rs.getString(1);
            String content = rs.getString(2);
            log.debug("Found key " + key);
            iStoreKeyVisitor.visit(key, content);
        }
    };
    namedJdbcTemplate.query(sql, new MapSqlParameterSource("like_prefix", prefix + "%"), callback);
}
 
Example 46
Project: dhis2-core   File: HibernateLockExceptionStore.java   Source Code and 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 47
Project: kc-rice   File: FileConverter.java   Source Code and License 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 48
Project: cloudfoundry-ftp-service-broker   File: Application.java   Source Code and License 5 votes vote down vote up
@Bean
CommandLineRunner runner(AnnotationConfigApplicationContext configApplicationContext, JdbcTemplate template) {
    return args -> {
        template.query("select USERNAME from FTP_USER",
                (RowCallbackHandler) resultSet -> log.info(String.format("ftp_user row: %s", resultSet.getString("USERNAME"))));
        configApplicationContext.destroy();
    };
}
 
Example 49
Project: AgileAlligators   File: HibernateLockExceptionStore.java   Source Code and 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 = dataSetService.getDataSet( dataSetId );

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

            lockExceptions.add( lockException );
        }
    } );

    return lockExceptions;
}
 
Example 50
Project: AgileAlligators   File: SpringDataValueSetStore.java   Source Code and License 5 votes vote down vote up
private void writeDataValueSet( String sql, DataExportParams params, Date completeDate, final DataValueSet dataValueSet )
{
    if ( params.isSingleDataValueSet() )
    {
        dataValueSet.setDataSet( params.getFirstDataSet().getUid() ); //TODO id scheme
        dataValueSet.setCompleteDate( getLongGmtDateString( completeDate ) );
        dataValueSet.setPeriod( params.getFirstPeriod().getIsoDate() );
        dataValueSet.setOrgUnit( params.getFirstOrganisationUnit().getUid() );
    }

    final Calendar calendar = PeriodType.getCalendar();

    jdbcTemplate.query( sql, new RowCallbackHandler()
    {
        @Override
        public void processRow( ResultSet rs ) throws SQLException
        {
            DataValue dataValue = dataValueSet.getDataValueInstance();
            PeriodType pt = PeriodType.getPeriodTypeByName( rs.getString( "ptname" ) );

            dataValue.setDataElement( rs.getString( "deid" ) );
            dataValue.setPeriod( pt.createPeriod( rs.getDate( "pestart" ), calendar ).getIsoDate() );
            dataValue.setOrgUnit( rs.getString( "ouid" ) );
            dataValue.setCategoryOptionCombo( rs.getString( "cocid" ) );
            dataValue.setAttributeOptionCombo( rs.getString( "aocid" ) );
            dataValue.setValue( rs.getString( "value" ) );
            dataValue.setStoredBy( rs.getString( "storedby" ) );
            dataValue.setCreated( getLongGmtDateString( rs.getTimestamp( "created" ) ) );
            dataValue.setLastUpdated( getLongGmtDateString( rs.getTimestamp( "lastupdated" ) ) );
            dataValue.setComment( rs.getString( "comment" ) );
            dataValue.setFollowup( rs.getBoolean( "followup" ) );
            dataValue.close();
        }
    } );

    dataValueSet.close();
}
 
Example 51
Project: STLCourts-api   File: MunicipalityDAOTest.java   Source Code and License 5 votes vote down vote up
@Test
public void returnsMunicipalitiesFromCourtId() throws IOException {
	final long COURTID = 123458L;

	Resource resource = mock(Resource.class);
	when(resource.getInputStream()).thenReturn(null);
	when(resourceLoader.getResource(CLASSPATH_URL_PREFIX + "sql/municipality/get-all.sql")).thenReturn(resource);

	municipalityDAO.getByCourtId(COURTID);

	verify(jdbcTemplate).query(sqlCaptor.capture(), paramMapCaptor.capture(), Matchers.<RowCallbackHandler> any());
	assertTrue(sqlCaptor.getValue().contains("WHERE mc.court_id = :courtId"));
	assertEquals(paramMapCaptor.getValue().get("courtId"), COURTID);
}
 
Example 52
Project: STLCourts-api   File: MunicipalityDAOTest.java   Source Code and License 5 votes vote down vote up
@Test
public void returnsMunicipalityFromMunicipalityId() throws IOException {
	final Long MUNICIPALITYID = 123458L;

	Resource resource = mock(Resource.class);
	when(resource.getInputStream()).thenReturn(null);
	when(resourceLoader.getResource(CLASSPATH_URL_PREFIX + "sql/municipality/get-all.sql")).thenReturn(resource);

	municipalityDAO.getByMunicipalityId(MUNICIPALITYID);

	verify(jdbcTemplate).query(sqlCaptor.capture(), paramMapCaptor.capture(), Matchers.<RowCallbackHandler> any());
	assertTrue(sqlCaptor.getValue().contains("WHERE m.municipality_id = :municipalityId"));
	assertEquals(paramMapCaptor.getValue().get("municipalityId"), MUNICIPALITYID);
}
 
Example 53
Project: STLCourts-api   File: MunicipalityDAOTest.java   Source Code and License 5 votes vote down vote up
@Test
public void returnsAllMunicipalities() throws IOException {
	Resource resource = mock(Resource.class);
	when(resource.getInputStream()).thenReturn(null);
	when(resourceLoader.getResource(CLASSPATH_URL_PREFIX + "sql/municipality/get-all.sql")).thenReturn(resource);

	municipalityDAO.getAllMunicipalities(null);

	verify(jdbcTemplate).query(Matchers.anyString(), Matchers.any(RowCallbackHandler.class));
}
 
Example 54
Project: STLCourts-api   File: MunicipalityDAOTest.java   Source Code and License 5 votes vote down vote up
@Test
public void returnsSupportedMunicipalities() throws IOException {
	Resource resource = mock(Resource.class);
	when(resource.getInputStream()).thenReturn(null);
	when(resourceLoader.getResource(CLASSPATH_URL_PREFIX + "sql/municipality/get-all.sql")).thenReturn(resource);

	municipalityDAO.getAllMunicipalities(true);

	verify(jdbcTemplate).query(sqlCaptor.capture(), Matchers.<RowCallbackHandler> any());
	assertTrue(sqlCaptor.getValue().contains(" WHERE cdm.citation_datasource_id IS NOT NULL"));
}
 
Example 55
Project: STLCourts-api   File: MunicipalityDAOTest.java   Source Code and License 5 votes vote down vote up
@Test
public void returnsNonSupportedMunicipalities() throws IOException {
	Resource resource = mock(Resource.class);
	when(resource.getInputStream()).thenReturn(null);
	when(resourceLoader.getResource(CLASSPATH_URL_PREFIX + "sql/municipality/get-all.sql")).thenReturn(resource);

	municipalityDAO.getAllMunicipalities(false);

	verify(jdbcTemplate).query(sqlCaptor.capture(), Matchers.<RowCallbackHandler> any());
	assertTrue(sqlCaptor.getValue().contains(" WHERE cdm.citation_datasource_id IS NULL"));
}
 
Example 56
Project: SupaCommons   File: SQLDatabaseTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConnection() throws Exception {
  database.getJdbcAgent().createJdbcTemplate().query(
      "SELECT 1", new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
          // do nothing, it works :D
        }
      });
}
 
Example 57
Project: sakai   File: StorageConverter.java   Source Code and License 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 58
Project: service   File: OrderServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Map<Long, Date> queryStartTimesOfPackages(Collection<Long> packageIds) {
    if (packageIds.isEmpty()) return new HashMap<Long, Date>();

    final Map<Long, Date> startTimesMap = new HashMap<Long, Date>();
    String sql = "SELECT A.PackageId, MIN(B.StartTime) AS StartTime FROM SG_BookedCourse A INNER JOIN SG_CourseSku B ON A.CourseSkuId=B.Id WHERE A.PackageId IN (" + StringUtils.join(packageIds, ",") + ") AND A.Status<>0 AND B.Status<>0 GROUP BY A.PackageId";
    query(sql, new RowCallbackHandler() {
        @Override
        public void processRow(ResultSet rs) throws SQLException {
            startTimesMap.put(rs.getLong("PackageId"), rs.getTimestamp("StartTime"));
        }
    });

    return startTimesMap;
}
 
Example 59
Project: jspresso-ce   File: JdbcPreferencesStore.java   Source Code and License 5 votes vote down vote up
private void initIfNecessary() {
  if (preferences == null) {
    preferences = new HashMap<>();

    StringBuilder sql = new StringBuilder("SELECT ").append(getKeyColumnName())
        .append(", ").append(getValueColumnName()).append(" FROM ")
        .append(getTableName()).append(" WHERE ").append(getPathColumnName())
        .append(" = ?");
    String[] restrictionsValues;
    int[] restrictionsTypes;
    if (defaultRestrictions != null && defaultRestrictions.size() > 0) {
      restrictionsValues = new String[defaultRestrictions.size() + 1];
      restrictionsTypes = new int[defaultRestrictions.size() + 1];
      int i = 1;
      for (Map.Entry<String, String> restriction : defaultRestrictions
          .entrySet()) {
        restrictionsValues[i] = restriction.getValue();
        restrictionsTypes[i] = Types.VARCHAR;
        if (i > 0) {
          sql.append(" AND ");
        }
        sql.append(restriction.getKey()).append(" = ?");
        i++;
      }
    } else {
      restrictionsValues = new String[1];
      restrictionsTypes = new int[1];
    }
    restrictionsValues[0] = storePath;
    restrictionsTypes[0] = Types.VARCHAR;
    jdbcTemplate.query(sql.toString(), restrictionsValues, restrictionsTypes,
        new RowCallbackHandler() {

          @Override
          public void processRow(ResultSet rs) throws SQLException {
            preferences.put(rs.getString(1), rs.getString(2));
          }
        });
  }
}
 
Example 60
Project: spring-cloud-task   File: JdbcTaskExecutionDao.java   Source Code and License 5 votes vote down vote up
private List<String> getTaskArguments(long executionId){
	final List<String> params= new ArrayList<>();
	RowCallbackHandler handler = new RowCallbackHandler() {
		@Override
		public void processRow(ResultSet rs) throws SQLException {
			params.add(rs.getString(2));
		}
	};

	jdbcTemplate.query(getQuery(FIND_ARGUMENT_FROM_ID), new Object[] { executionId },
			handler);
	return params;
}