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

The following are top voted examples for showing how to use org.springframework.jdbc.core.ResultSetExtractor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 7 votes vote down vote up
public String viewUserNames() {
	return jdbcTemplate
			.query(
					"select loginid from USERLOGIN where logintype='user' or logintype='owner' order by userid",
					new ResultSetExtractor<String>() {
						String s = "";

						public String extractData(ResultSet rs)
								throws SQLException, DataAccessException {
							while (rs.next()) {
								s = s + rs.getString(1) + ",";
							}
							return s;
						}
					});

}
 
Example 2
Project: diamond-v2.1.1   File: PaginationHelper.java   Source Code and License 7 votes vote down vote up
/**
    * 取分页
    * 
    * @param jt
    *            jdbcTemplate
    * @param sqlFetchRows
    *            查询数据的sql
    * @param args
    *            查询参数
    * @param size
    *            大小
    * @param rowMapper
    * @return
    */
   @SuppressWarnings({ "unchecked", "rawtypes" })
public List<E> fetchList(final JdbcTemplate jt, final String sqlFetchRows,
		final Object args[], final int size, final ParameterizedRowMapper<E> rowMapper) {
	if (size == 0) {
		return null;
	}
	final Page<E> page = new Page<E>();
	// TODO 在数据量很大时, limit效率很低
	final String selectSQL = sqlFetchRows + " limit " + size;
	jt.query(selectSQL, args, new ResultSetExtractor() {
		public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
			final List<E> pageItems = page.getPageItems();
			int currentRow = 0;
			while (rs.next()) {
				pageItems.add(rowMapper.mapRow(rs, currentRow++));
			}
			return pageItems;
		}
	});
	return page.getPageItems();
}
 
Example 3
Project: graphium   File: TestWayGraphReadDaoImpl.java   Source Code and License 6 votes vote down vote up
@Test
public void testResultSetExtractorPrototypeInstantiation() {
	Set<String> tableAliases = new HashSet<>();
	tableAliases.add("wayseg");
	tableAliases.add("xit");
	ResultSetExtractor<? extends IBaseSegment> rsExtractor1 = resultSetExtractorFactory.getResultSetExtractor(tableAliases);
	ResultSetExtractor<? extends IBaseSegment> rsExtractor2 = resultSetExtractorFactory.getResultSetExtractor(tableAliases);
	try {
		rsExtractor1.extractData(null);
		rsExtractor2.extractData(null);
	} catch (DataAccessException | SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	Assert.assertNotEquals(rsExtractor1, rsExtractor2);
}
 
Example 4
Project: Equella   File: SqlTaxonomyDataSource.java   Source Code and License 6 votes vote down vote up
private Object executeSingleResultQuery(String query, Map<?, ?> params)
{
	return jdbcTemplate.query(query, params, new ResultSetExtractor()
	{
		@Override
		public Object extractData(ResultSet rs) throws SQLException, DataAccessException
		{
			Object data = null;
			if( rs.next() )
			{
				data = rs.getObject(1);

				// Sanity check - ensure only a single result
				if( rs.next() )
				{
					throw new IncorrectResultSizeDataAccessException(1);
				}
			}
			return data;
		}
	});
}
 
Example 5
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public String viewFileName() {
	return jdbcTemplate.query(
			"select * from CLOUDFILEDATA order by FILEDATAID",
			new ResultSetExtractor<String>() {
				String s = "";

				public String extractData(ResultSet rs)
						throws SQLException, DataAccessException {
					while (rs.next()) {
						s = s + rs.getString(5) + ",";
					}
					return s;
				}
			});

}
 
Example 6
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public String viewFileName(int userid) {
	return jdbcTemplate
			.query(
					"select * from CLOUDFILEDATA where groupname=(select (select groupname from groups where groupid=groupusers.groupid) from groupusers where userid="
							+ userid + ") order by FILEDATAID",
					new ResultSetExtractor<String>() {
						String s = "";

						public String extractData(ResultSet rs)
								throws SQLException, DataAccessException {
							while (rs.next()) {
								s = s + rs.getString(5) + ",";
							}
							return s;
						}
					});

}
 
Example 7
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public String viewFileKey(String filename) {
	return jdbcTemplate.query(
			"select PUBLICKEY from CLOUDFILEDATA where filename='"
					+ filename.trim() + "'",
			new ResultSetExtractor<String>() {
				String s = "";

				public String extractData(ResultSet rs)
						throws SQLException, DataAccessException {
					while (rs.next()) {
						s = s + rs.getString(1) + ",";
					}
					return s;
				}
			});

}
 
Example 8
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public String viewFileSignature(String groupname) {
	return jdbcTemplate.query(
			"select GROUPSIGNATURE from GROUPS where GROUPNAME='"
					+ groupname.trim() + "'",
			new ResultSetExtractor<String>() {
				String s = "";

				public String extractData(ResultSet rs)
						throws SQLException, DataAccessException {
					while (rs.next()) {
						s = s + rs.getString(1) + ",";
					}
					return s;
				}
			});

}
 
Example 9
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public Users viewGroupname(final Users users) {
	return jdbcTemplate
			.query(
					"select userid,(select (select groupname from groups where groupid=GROUPUSERS.groupid) from GROUPUSERS where userid=userlogin.userid) from userlogin where loginid='"
							+ users.getLoginid() + "'",
					new ResultSetExtractor<Users>() {

						public Users extractData(ResultSet rs)
								throws SQLException, DataAccessException {
							if (rs.next()) {
								users.setGroupname(rs.getString(2));
								users.setUserid(rs.getInt(1));

							}
							return users;
						}
					});

}
 
Example 10
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public Users managerLoginCheck(Users users) {

		return jdbcTemplate.query("select * from userlogin where loginid='"
				+ users.getLoginid() + "' and password='" + users.getPassword()
				+ "' and logintype='manager'", new ResultSetExtractor<Users>() {

			public Users extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				Users user = new Users();
				if (rs.next()) {
					user.setUserid(rs.getInt(1));
					user.setLoginid(rs.getString(2));
					user.setLogintype(rs.getString(3));
				}
				return user;
			}
		});
	}
 
Example 11
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public Object[] viewUserLoginMetaData() {
	return jdbcTemplate.query("select * from userlogin",
			new ResultSetExtractor<Object[]>() {
				public Object[] extractData(ResultSet rs)
						throws SQLException, DataAccessException {
					ResultSetMetaData resultSetMetaData = rs.getMetaData();
					String tablemetadata[] = new String[] {
							resultSetMetaData.getColumnName(1),
							resultSetMetaData.getColumnName(2),
							resultSetMetaData.getColumnName(4),
							resultSetMetaData.getColumnName(5),
							resultSetMetaData.getColumnName(6),
							"GroupName", };

					return tablemetadata;
				}
			});
}
 
Example 12
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public Object[] viewCloudMetaData() {
	return jdbcTemplate.query(
			"select * from CLOUDFILEDATA order by FILEDATAID",
			new ResultSetExtractor<Object[]>() {
				public Object[] extractData(ResultSet rs)
						throws SQLException, DataAccessException {

					ResultSetMetaData resultSetMetaData = rs.getMetaData();

					String tablemetadata[] = new String[] {
							resultSetMetaData.getColumnName(1),
							resultSetMetaData.getColumnName(2),
							resultSetMetaData.getColumnName(3),
							resultSetMetaData.getColumnName(4),
							resultSetMetaData.getColumnName(5),
							resultSetMetaData.getColumnName(6),
							resultSetMetaData.getColumnName(9),
							resultSetMetaData.getColumnName(10),
							resultSetMetaData.getColumnName(11), };

					return tablemetadata;
				}
			});
}
 
Example 13
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public Boolean viewGroupMembers() {
	return jdbcTemplate.query("select * from groups",
			new ResultSetExtractor<Boolean>() {
				public Boolean extractData(ResultSet rs)
						throws SQLException, DataAccessException {
					boolean b = new File(new File(".").getAbsolutePath()
							+ "\\" + "groups").mkdir();
					while (rs.next()) {
						boolean path = new File(new File("groups")
								.getAbsolutePath()
								+ "\\" + rs.getString(2)).mkdir();
						try {
							createUserFloders(rs.getInt(1), new File(
									"groups\\" + rs.getString(2))
									.getAbsolutePath());
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
					return true;
				}
			});

}
 
Example 14
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public Boolean usergroupcount(final Users users) {

		String countuserssql = "select GROUPMEMBERCOUNT from GROUPS where GROUPNAME='"
				+ users.getNewgroupname() + "'";
		final Boolean usercount = jdbcTemplate.query(countuserssql,
				new ResultSetExtractor<Boolean>() {
					boolean s;

					public Boolean extractData(ResultSet rs)
							throws SQLException, DataAccessException {
						int i = 0;
						if (rs.next()) {
							System.out.println(rs.getInt(1));
							try {
								s = userChangeGroup(rs.getInt(1),
										viewGroupname(users));
							} catch (Exception e) {
								System.out.println(e);
							}
						}
						return s;
					}

				});
		return usercount;
	}
 
Example 15
Project: Mona-Secure-Multi-Owner-Data-Sharing-for-Dynamic-Group-in-the-Cloud   File: RegistrationDAO.java   Source Code and License 6 votes vote down vote up
public Integer groupMemberCount(String groupname) {

		String countuserssql = "select GROUPMEMBERCOUNT from GROUPS where GROUPNAME='"
				+ groupname + "'";
		final Integer usercount = jdbcTemplate.query(countuserssql,
				new ResultSetExtractor<Integer>() {
					int i = 0;

					public Integer extractData(ResultSet rs)
							throws SQLException, DataAccessException {

						if (rs.next()) {
							i = rs.getInt(1);

						}
						return i;

					}

				});
		return usercount;
	}
 
Example 16
Project: Learning-Spring-5.0   File: BookDAO_JdbcTemplate.java   Source Code and License 6 votes vote down vote up
@Override
public List<Book> findAllBooks(String author) {
	// TODO Auto-generated method stub
	System.out.println(author);
	String FIND_ALL_Author="select * from book where author=?";
	return jdbcTemplate.query(FIND_ALL_Author,new String[]{author}, new ResultSetExtractor<List<Book>>() {

		List<Book>books=new ArrayList();
		@Override
		public List<Book> extractData(ResultSet set) throws SQLException, DataAccessException {
			// TODO Auto-generated method stub
			while(set.next())
			{
				Book book=new Book();
				book.setAuthor(set.getString("author"));
				book.setBookName(set.getString("bookName"));
				book.setISBN(set.getLong("ISBN"));
				book.setPublication(set.getString("publication"));
				book.setDescription(set.getString("description"));
				books.add(book);
			}
			return books;
		}
	});
}
 
Example 17
Project: Learning-Spring-5.0   File: BookDAO_JdbcTemplate.java   Source Code and License 6 votes vote down vote up
@Override
public List<Book> findAllBooks(String author) {
	// TODO Auto-generated method stub
	System.out.println(author);
	String FIND_ALL_Author = "select * from book where author=?";
	return jdbcTemplate.query(FIND_ALL_Author, new String[] { author }, new ResultSetExtractor<List<Book>>() {

		List<Book> books = new ArrayList();

		@Override
		public List<Book> extractData(ResultSet set) throws SQLException, DataAccessException {
			// TODO Auto-generated method stub
			while (set.next()) {
				Book book = new Book();
				book.setAuthor(set.getString("author"));
				book.setBookName(set.getString("bookName"));
				book.setISBN(set.getLong("ISBN"));
				book.setPublication(set.getString("publication"));
				book.setDescription(set.getString("description"));
				books.add(book);
			}
			return books;
		}
	});
}
 
Example 18
Project: Learning-Spring-5.0   File: BookDAO_JdbcTemplate.java   Source Code and License 6 votes vote down vote up
@Override
public List<Book> findAllBooks(String author) {
	// TODO Auto-generated method stub
	System.out.println(author);
	String FIND_ALL_Author="select * from book where author=?";
	return jdbcTemplate.query(FIND_ALL_Author,new String[]{author}, new ResultSetExtractor<List<Book>>() {

		List<Book>books=new ArrayList();
		@Override
		public List<Book> extractData(ResultSet set) throws SQLException, DataAccessException {
			// TODO Auto-generated method stub
			while(set.next())
			{
				Book book=new Book();
				book.setAuthor(set.getString("author"));
				book.setBookName(set.getString("bookName"));
				book.setISBN(set.getLong("ISBN"));
				book.setPublication(set.getString("publication"));
				book.setDescription(set.getString("description"));
				books.add(book);
			}
			return books;
		}
	});
}
 
Example 19
Project: Learning-Spring-5.0   File: BookDAO_JdbcTemplate.java   Source Code and License 6 votes vote down vote up
@Override
public List<Book> findAllBooks(String author) {
	// TODO Auto-generated method stub
	System.out.println(author);
	String FIND_ALL_Author="select * from book where author=?";
	return jdbcTemplate.query(FIND_ALL_Author,new String[]{author}, new ResultSetExtractor<List<Book>>() {

		List<Book>books=new ArrayList();
		@Override
		public List<Book> extractData(ResultSet set) throws SQLException, DataAccessException {
			// TODO Auto-generated method stub
			while(set.next())
			{
				Book book=new Book();
				book.setAuthor(set.getString("author"));
				book.setBookName(set.getString("bookName"));
				book.setISBN(set.getLong("ISBN"));
				book.setPublication(set.getString("publication"));
				book.setDescription(set.getString("description"));
				books.add(book);
			}
			return books;
		}
	});
}
 
Example 20
Project: metacat   File: DirectSqlGetPartition.java   Source Code and License 6 votes vote down vote up
private List<FieldSchema> getPartitionKeys(final String databaseName,
                                           final String tableName,
                                           final boolean forceDisableAudit) {
    final List<FieldSchema> result = Lists.newArrayList();
    final ResultSetExtractor<List<FieldSchema>> handler = rs -> {
        while (rs.next()) {
            final String name = rs.getString("pkey_name");
            final String type = rs.getString("pkey_type");
            result.add(new FieldSchema(name, type, null));
        }
        return result;
    };
    final Optional<QualifiedName> sourceTable = getSourceTableName(databaseName, tableName, forceDisableAudit);

    return sourceTable.map(qualifiedName -> jdbcTemplate
        .query(SQL.SQL_GET_AUDIT_TABLE_PARTITION_KEYS,
            new Object[]{databaseName, tableName, qualifiedName.getDatabaseName(), qualifiedName.getTableName()},
            new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR},
            handler))
        .orElseGet(() -> jdbcTemplate
            .query(SQL.SQL_GET_PARTITION_KEYS,
                new Object[]{databaseName, tableName},
                new int[]{Types.VARCHAR, Types.VARCHAR},
                handler));
}
 
Example 21
Project: metacat   File: DirectSqlGetPartition.java   Source Code and License 6 votes vote down vote up
private Map<Long, Map<String, String>> getParameters(final List<Long> ids, final String sql, final String idName) {
    // Create the sql
    final StringBuilder queryBuilder = new StringBuilder(sql);
    if (!ids.isEmpty()) {
        queryBuilder.append(" and ").append(idName)
            .append(" in ('").append(Joiner.on("','").skipNulls().join(ids)).append("')");
    }
    final ResultSetExtractor<Map<Long, Map<String, String>>> handler = rs -> {
        final Map<Long, Map<String, String>> result = Maps.newHashMap();
        while (rs.next()) {
            final Long id = rs.getLong(idName);
            final String key = rs.getString("param_key");
            final String value = rs.getString("param_value");
            final Map<String, String> parameters = result.computeIfAbsent(id, k -> Maps.newHashMap());
            parameters.put(key, value);
        }
        return result;
    };
    return jdbcTemplate.query(queryBuilder.toString(), handler);
}
 
Example 22
Project: leopard   File: DfsMysqlImpl.java   Source Code and License 6 votes vote down vote up
@Override
public byte[] read(String filename) throws IOException {
	String sql = "select data from " + TABLE + " where filename='" + filename + "';";
	byte[] data = this.jdbc.getJdbcTemplate().query(sql, new ResultSetExtractor<byte[]>() {
		@Override
		public byte[] extractData(ResultSet rs) throws SQLException, DataAccessException {
			if (rs.first()) {
				return rs.getBytes(1);
			}
			else {
				return null;
			}
		}
	});
	if (data == null) {
		throw new FileNotFoundException(filename);
	}
	return data;
}
 
Example 23
Project: yugong   File: YugongExampleJoinDataTranslator.java   Source Code and License 6 votes vote down vote up
public boolean translator(DataSource sourceDs, Record record) {
    ColumnValue idColum = record.getColumnByName("id");
    if (idColum != null) {
        // 需要根据test.id字段,和另一张表做join,提取到关联id记录的name字段,合并输出到一个目标表
        JdbcTemplate jdbcTemplate = new JdbcTemplate(sourceDs);
        String name_value = (String) jdbcTemplate.query("select NAME FROM JOIN_NAME WHERE JOIN_ID = "
                                                        + idColum.getValue().toString(), new ResultSetExtractor() {

            public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
                if (rs.next()) {
                    return rs.getString("NAME");
                }

                return null;
            }
        });

        ColumnMeta nameMeta = new ColumnMeta("name", Types.VARCHAR);
        ColumnValue nameColumn = new ColumnValue(nameMeta, name_value);
        record.addColumn(nameColumn);
    }
    return super.translator(record);
}
 
Example 24
Project: caom2db   File: BaseSQLGenerator.java   Source Code and License 6 votes vote down vote up
public ResultSetExtractor getSkeletonExtractor(Class<? extends Skeleton> c) {
    if (c.equals(ObservationSkeleton.class)) {
        return new ObservationSkeletonExtractor();
    }

    if (c.equals(ObservationMetaReadAccessSkeleton.class)) {
        return new ReadAccessSkeletonExtractor(ObservationMetaReadAccessSkeleton.class);
    }

    if (c.equals(PlaneMetaReadAccessSkeleton.class)) {
        return new ReadAccessSkeletonExtractor(PlaneMetaReadAccessSkeleton.class);
    }

    if (c.equals(PlaneDataReadAccessSkeleton.class)) {
        return new ReadAccessSkeletonExtractor(PlaneDataReadAccessSkeleton.class);
    }

    throw new UnsupportedOperationException("getSkeletonExtractor: " + c.getName());
}
 
Example 25
Project: Rapture   File: JDBCStructuredStore.java   Source Code and License 6 votes vote down vote up
private ResultSetExtractor<List<Map<String, Object>>> createResultSetExtractor() {
    return new ResultSetExtractor<List<Map<String, Object>>>() {
        @Override
        public List<Map<String, Object>> extractData(ResultSet rs) throws SQLException, DataAccessException {
            List<Map<String, Object>> ret = new ArrayList<>();
            ResultSetMetaData rsmd = rs.getMetaData();
            int numColumns = rsmd.getColumnCount();
            while (rs.next()) {
                Map<String, Object> m = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
                for (int i = 1; i <= numColumns; i++) {
                    m.put(rsmd.getColumnLabel(i), rs.getObject(i));
                }
                ret.add(m);
            }
            return ret;
        }
    };
}
 
Example 26
Project: CatalogAutoExportKits_Huiwen   File: HuiwenMarcDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String getSingleMarcData(String marcId) {
	String sql = " SELECT marc01,marc02,marc03 FROM " + dbUserPrefix + "marc_data WHERE marc_rec_no=? ORDER BY data_serial";
	String marcStr = (String)getJdbcTemplate().query(sql, new Object[]{marcId},new ResultSetExtractor() {
		@Override
		public Object extractData(ResultSet rs) throws SQLException,
				DataAccessException {
			StringBuffer sb = new StringBuffer();
			while(rs.next()){
				if(StringUtils.isNoneBlank(rs.getString(1)))
					sb.append(rs.getString(1));
				if(StringUtils.isNoneBlank(rs.getString(2)))
					sb.append(rs.getString(2));
				if(StringUtils.isNoneBlank(rs.getString(3)))
					sb.append(rs.getString(3));
			}
			return sb.toString();
		}
	});
	logger.debug(marcStr);
	return marcStr;
}
 
Example 27
Project: CatalogAutoExportKits_Huiwen   File: HuiwenMarcDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public String getItemLocationByMarcId(String marcId) {
	String sql = " SELECT distinct location from " + dbUserPrefix + "item WHERE book_stat_code>'40' and marc_rec_no=? ";
	String locaStr = (String)getJdbcTemplate().query(sql, new Object[]{marcId},new ResultSetExtractor() {
		@Override
		public Object extractData(ResultSet rs) throws SQLException,
				DataAccessException {
			List<String> locaList = new ArrayList<String>();
			while(rs.next()){
				locaList.add(StringUtils.trim(rs.getString(1)));
			}
			return StringUtils.join(locaList,",");
		}
	});
	logger.debug("marcId:{}=>loca:{}",marcId,locaStr);
	return locaStr;
}
 
Example 28
Project: FinanceAnalytics   File: AbstractDocumentDbMaster.java   Source Code and License 6 votes vote down vote up
/**
 * Performs a standard get by object identifier at instants.
 *
 * @param objectId  the object identifier, not null
 * @param versionCorrection  the version-correction locator, not null
 * @param extractor  the extractor to use, not null
 * @param masterName  a name describing the contents of the master for an error message, not null
 * @return the document, null if not found
 */
protected D doGetByOidInstants(
  final ObjectIdentifiable objectId, final VersionCorrection versionCorrection,
  final ResultSetExtractor<List<D>> extractor, final String masterName) {
  ArgumentChecker.notNull(objectId, "oid");
  ArgumentChecker.notNull(versionCorrection, "versionCorrection");
  ArgumentChecker.notNull(extractor, "extractor");
  s_logger.debug("getByOidInstants {}", objectId);

  Timer.Context context = _getByOidInstantsTimer.time();
  try {
    final VersionCorrection vc = (versionCorrection.containsLatest() ? versionCorrection.withLatestFixed(now()) : versionCorrection);
    final DbMapSqlParameterSource args = argsGetByOidInstants(objectId, vc);
    final NamedParameterJdbcOperations namedJdbc = getDbConnector().getJdbcTemplate();
    final String sql = getElSqlBundle().getSql("GetByOidInstants", args);
    final List<D> docs = namedJdbc.query(sql, args, extractor);
    if (docs.isEmpty()) {
      throw new DataNotFoundException(masterName + " not found: " + objectId);
    }
    return docs.get(0);
  } finally {
    context.stop();
  }
}
 
Example 29
Project: FinanceAnalytics   File: AbstractDocumentDbMaster.java   Source Code and License 6 votes vote down vote up
/**
 * Performs a standard get by versioned unique identifier.
 *
 * @param uniqueId  the versioned unique identifier, not null
 * @param extractor  the extractor to use, not null
 * @param masterName  a name describing the contents of the master for an error message, not null
 * @return the document, null if not found
 */
protected D doGetById(final UniqueId uniqueId, final ResultSetExtractor<List<D>> extractor, final String masterName) {
  ArgumentChecker.notNull(uniqueId, "uniqueId");
  ArgumentChecker.notNull(extractor, "extractor");
  s_logger.debug("getById {}", uniqueId);

  Timer.Context context = _getByIdTimer.time();
  try {
    final DbMapSqlParameterSource args = argsGetById(uniqueId);
    final NamedParameterJdbcOperations namedJdbc = getDbConnector().getJdbcTemplate();
    final String sql = getElSqlBundle().getSql("GetById", args);
    final List<D> docs = namedJdbc.query(sql, args, extractor);
    if (docs.isEmpty()) {
      throw new DataNotFoundException(masterName + " not found: " + uniqueId);
    }
    return docs.get(0);
  } finally {
    context.stop();
  }
}
 
Example 30
Project: FinanceAnalytics   File: AbstractDocumentDbMaster.java   Source Code and License 6 votes vote down vote up
/**
 * Performs a standard history search.
 *
 * @param <R>  the document result type
 * @param request  the request, not null
 * @param result  the result to populate, not null
 * @param extractor  the extractor to use, not null
 * @return the populated result, not null
 */
protected <R extends AbstractHistoryResult<D>> R doHistory(
  final AbstractHistoryRequest request, final R result,
  final ResultSetExtractor<List<D>> extractor) {
  ArgumentChecker.notNull(request, "request");
  ArgumentChecker.notNull(result, "result");
  ArgumentChecker.notNull(extractor, "extractor");
  ArgumentChecker.notNull(request.getObjectId(), "request.objectId");
  checkScheme(request.getObjectId());
  s_logger.debug("history {}", request);
  
  Timer.Context context = _historyTimer.time();
  try {
    final DbMapSqlParameterSource args = argsHistory(request);
    final String[] sql = {getElSqlBundle().getSql("History", args), getElSqlBundle().getSql("HistoryCount", args)};
    searchWithPaging(request.getPagingRequest(), sql, args, extractor, result);
    return result;
  } finally {
    context.stop();
  }
}
 
Example 31
Project: FinanceAnalytics   File: AbstractDocumentDbMaster.java   Source Code and License 6 votes vote down vote up
/**
 * Searches for documents with paging.
 *
 * @param <T>  the type of the document
 * @param pagingRequest  the paging request, not null
 * @param sql  the array of SQL, query and count, not null
 * @param args  the query arguments, not null
 * @param extractor  the extractor of results, not null
 * @param result  the object to populate, not null
 */
protected <T extends AbstractDocument> void searchWithPaging(
    final PagingRequest pagingRequest, final String[] sql, final DbMapSqlParameterSource args,
    final ResultSetExtractor<List<T>> extractor, final AbstractDocumentsResult<T> result) {
  s_logger.debug("with args {}", args);
  
  final NamedParameterJdbcOperations namedJdbc = getJdbcTemplate();
  if (pagingRequest.equals(PagingRequest.ALL)) {
    result.getDocuments().addAll(namedJdbc.query(sql[0], args, extractor));
    result.setPaging(Paging.of(pagingRequest, result.getDocuments()));
  } else {
    s_logger.debug("executing sql {}", sql[1]);
    final int count = namedJdbc.queryForObject(sql[1], args, Integer.class);
    result.setPaging(Paging.of(pagingRequest, count));
    if (count > 0 && pagingRequest.equals(PagingRequest.NONE) == false) {
      s_logger.debug("executing sql {}", sql[0]);
      result.getDocuments().addAll(namedJdbc.query(sql[0], args, extractor));
    }
  }
}
 
Example 32
Project: diamond-v2.1.1   File: PaginationHelper.java   Source Code and License 6 votes vote down vote up
/**
    * 取分页
    * 
    * @param jt
    *            jdbcTemplate
    * @param sqlFetchRows
    *            查询数据的sql
    * @param args
    *            查询参数
    * @param size
    *            大小
    * @param rowMapper
    * @return
    */
   @SuppressWarnings({ "unchecked", "rawtypes" })
public List<E> fetchList(final JdbcTemplate jt, final String sqlFetchRows,
		final Object args[], final int size, final ParameterizedRowMapper<E> rowMapper) {
	if (size == 0) {
		return null;
	}
	final Page<E> page = new Page<E>();
	// TODO 在数据量很大时, limit效率很低
	final String selectSQL = sqlFetchRows + " limit " + size;
	jt.query(selectSQL, args, new ResultSetExtractor() {
		public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
			final List<E> pageItems = page.getPageItems();
			int currentRow = 0;
			while (rs.next()) {
				pageItems.add(rowMapper.mapRow(rs, currentRow++));
			}
			return pageItems;
		}
	});
	return page.getPageItems();
}
 
Example 33
Project: compass   File: ShardJdbcTemplate.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private ShardOperationProcessor<List> getNonAggregationProcessor(final RowMapper rowMapper) {
       final List<QueryCallable<List>> callableList = new ArrayList<ShardJdbcTemplate.QueryCallable<List>>();

       ShardOperationProcessor<List> processor = new ShardOperationProcessor<List>() {
           @SuppressWarnings("unchecked")
		@Override
           public void addOperation(Shard shard, String sql, Object[] args) {
               ResultSetExtractor extractor = new RowMapperResultSetExtractor(rowMapper);
               QueryCallable<List> callable = new QueryCallable<List>(shard, sql, args, extractor);

               callableList.add(callable);
           }

		@Override
           public List processOperations() {
               List<List> rawResultList = ShardJdbcTemplate.this.executeQuery(callableList);
               return AggregationUtil.aggregateObjectList(rawResultList);
           }
       };

       return processor;
   }
 
Example 34
Project: herd   File: JdbcDaoImpl.java   Source Code and License 6 votes vote down vote up
/**
 * Delegates to {@link JdbcOperations#query(JdbcTemplate, String, ResultSetExtractor)} where the {@link ResultSetExtractor} converts the {@link ResultSet}
 * into {@link JdbcStatementResultSet}.
 */
@Override
public JdbcStatementResultSet query(JdbcTemplate jdbcTemplate, String sql, final Integer maxResult)
{
    return jdbcOperations.query(jdbcTemplate, sql, new ResultSetExtractor<JdbcStatementResultSet>()
    {
        @Override
        public JdbcStatementResultSet extractData(ResultSet resultSet) throws SQLException, DataAccessException
        {
            JdbcStatementResultSet jdbcStatementResultSet = new JdbcStatementResultSet();

            List<String> columnNames = getColumnNames(resultSet.getMetaData());
            jdbcStatementResultSet.setColumnNames(columnNames);

            List<JdbcStatementResultSetRow> rows = getRows(resultSet, maxResult);
            jdbcStatementResultSet.setRows(rows);

            return jdbcStatementResultSet;
        }
    });
}
 
Example 35
Project: jeecms6   File: CmsDb2DataBackDaoImpl.java   Source Code and License 6 votes vote down vote up
public List<Object[]> getTableReferences(String tablename){
	List<Object[]> results = new ArrayList<Object[]>();
	String sql = " SELECT TABNAME,CONSTNAME,FK_COLNAMES  ,PK_COLNAMES   FROM SYSCAT.REFERENCES   where  REFTABNAME ='"+tablename+"' " ;
	results=getJdbcTemplate().query(sql, new ResultSetExtractor<List<Object[]>>(){
		public List<Object[]> extractData(ResultSet rs) throws SQLException,
				DataAccessException {
			List<Object[]>result=new ArrayList<Object[]>();
			while(rs.next()){
				Object[] oneResult = new Object[4];
				for (int i = 1; i <= 4; i++) {
					oneResult[i - 1] = rs.getObject(i);
				}
				result.add(oneResult);
			}
			return result;
		}
	});
	return results;
}
 
Example 36
Project: jeecms6   File: CmsDb2DataBackDaoImpl.java   Source Code and License 6 votes vote down vote up
public List<Object[]> createTableData(String tablename) {
	final int filedNum = getTableFieldNums(tablename);
	List<Object[]> results = new ArrayList<Object[]>();
	String sql = " select * from   " + tablename;
	results=getJdbcTemplate().query(sql, new ResultSetExtractor<List<Object[]>>(){
		public List<Object[]> extractData(ResultSet rs) throws SQLException,
				DataAccessException {
			List<Object[]>result=new ArrayList<Object[]>();
			while(rs.next()){
				Object[] oneResult = new Object[filedNum];
				for (int i = 1; i <= filedNum; i++) {
					oneResult[i - 1] = rs.getObject(i);
					if(rs.getObject(i)instanceof Clob){
						oneResult[i - 1]=lobHandler.getClobAsString(rs, i);
					}
				}
				result.add(oneResult);
			}
			return result;
		}
	});
	return results;
}
 
Example 37
Project: jeecms6   File: CmsOracleDataBackDaoImpl.java   Source Code and License 6 votes vote down vote up
public List<String> createIndexDDL(String tablename){
	List<String>results;
	String sql = " SELECT DBMS_METADATA.GET_DDL('INDEX',u.index_name)FROM USER_INDEXES u WHERE table_name='"
			+ tablename + "'";
	results=getJdbcTemplate().query(sql, new ResultSetExtractor<List<String>>(){
		public List<String> extractData(ResultSet rs) throws SQLException,
				DataAccessException {
			List<String>result=new ArrayList<String>();
			while(rs.next()){
				result.add(lobHandler.getClobAsString(rs, 1)) ;
			}
			return result;
		}
	});
	return results;
}
 
Example 38
Project: pulsar-reporting-api   File: RDBMS.java   Source Code and License 6 votes vote down vote up
public <T> List<T> queryForList(String sql,Map<String,?> parameters, final int maxrows){
 	final RowMapper<T> mapper=new SingleColumnRowMapper<T>();
 	return this.namedParameterJdbcTemplate.query(sql, parameters, new ResultSetExtractor<List<T>>(){
@Override
public List<T> extractData(ResultSet rs) throws SQLException,
		DataAccessException {
	List<T> data = new ArrayList<T>();
       if(rs==null) return data;
       int rowNum = 0;
       while((maxrows>0 && rowNum<maxrows || maxrows<0) && rs.next()){
       	data.add(mapper.mapRow(rs, rowNum++));
       }
       return data;
}
 	});
 }
 
Example 39
Project: leopard-data   File: DfsMysqlImpl.java   Source Code and License 6 votes vote down vote up
@Override
public byte[] read(String filename) throws IOException {
	String sql = "select data from " + TABLE + " where filename='" + filename + "';";
	byte[] data = this.jdbc.getJdbcTemplate().query(sql, new ResultSetExtractor<byte[]>() {
		@Override
		public byte[] extractData(ResultSet rs) throws SQLException, DataAccessException {
			if (rs.first()) {
				return rs.getBytes(1);
			}
			else {
				return null;
			}
		}
	});
	if (data == null) {
		throw new FileNotFoundException(filename);
	}
	return data;
}
 
Example 40
Project: spring-cloud-task   File: JdbcTaskExecutionDao.java   Source Code and License 6 votes vote down vote up
@Override
public Set<Long> getJobExecutionIdsByTaskExecutionId(long taskExecutionId) {
	try {
		return jdbcTemplate.query(
				getQuery(FIND_JOB_EXECUTION_BY_TASK_EXECUTION_ID),
				new Object[] {taskExecutionId},
				new ResultSetExtractor<Set<Long>>() {
					@Override
					public Set<Long> extractData(ResultSet resultSet) throws SQLException, DataAccessException {
						Set<Long> jobExecutionIds = new TreeSet<>();

						while(resultSet.next()) {
							jobExecutionIds.add(resultSet.getLong("JOB_EXECUTION_ID"));
						}

						return jobExecutionIds;
					}
				});
	}
	catch (DataAccessException e) {
		return Collections.emptySet();
	}
}
 
Example 41
Project: WebAPI   File: CohortResultsService.java   Source Code and License 6 votes vote down vote up
@GET
@Path("{sourceKey}/{id}/distinctPersonCount/")
@Produces(MediaType.APPLICATION_JSON)
public Integer getRawDistinctPersonCount(@PathParam("sourceKey") String sourceKey,
        @PathParam("id") String id,
        @DefaultValue("false") @QueryParam("refresh") boolean refresh) {
  Source source = getSourceRepository().findBySourceKey(sourceKey);
  PreparedStatementRenderer psr = prepareGetRawDistinctPersonCount(id, source);
  Integer result = getSourceJdbcTemplate(source).query(psr.getSql(), psr.getSetter(), new ResultSetExtractor<Integer>() {
    @Override
    public Integer extractData(ResultSet rs) throws SQLException {

      while (rs.next()) {
        return rs.getInt(1);
      }
      return null;
    }
  });
  return result;
}
 
Example 42
Project: WebAPI   File: CDMResultsCacheTasklet.java   Source Code and License 6 votes vote down vote up
private HashMap<Long,Long[]> warmCache() {
    String resultTableQualifier = source.getTableQualifier(SourceDaimon.DaimonType.Results);
    String vocabularyTableQualifier = source.getTableQualifier(SourceDaimon.DaimonType.Vocabulary);

    String sql_statement = ResourceHelper.GetResourceAsString("/resources/cdmresults/sql/loadConceptRecordCountCache.sql");
    String[] tables = {"resultTableQualifier", "vocabularyTableQualifier"};
    String[] tableValues = {resultTableQualifier, vocabularyTableQualifier};

    PreparedStatementRenderer psr = new PreparedStatementRenderer(source, sql_statement, tables, tableValues,
      SessionUtils.sessionId());

    return jdbcTemplate.query(psr.getSql(), psr.getSetter(), new ResultSetExtractor<HashMap<Long,Long[]>>() {
        @Override
        public HashMap<Long,Long[]> extractData(ResultSet rs) throws SQLException, DataAccessException {
            HashMap<Long, Long[]> newCache = new HashMap<>();
            while (rs.next()) {
                long id = rs.getLong("concept_id");
                long record_count = rs.getLong("record_count");
                long descendant_record_count = rs.getLong("descendant_record_count");

                newCache.put(id, new Long[] { record_count, descendant_record_count });
            }
            return newCache;
        }
    });        
}
 
Example 43
Project: SimpleFlatMapper   File: PreparedStatementCallbackImpl.java   Source Code and License 6 votes vote down vote up
public <H extends CheckedConsumer<T>> PreparedStatementCallback<H> newPreparedStatementCallback(final H handler) {
	return new PreparedStatementCallback<H>() {
		@Override
		public H doInPreparedStatement(
				PreparedStatement ps)
				throws SQLException, DataAccessException {
			ResultSet rs = ps.executeQuery();
			ResultSetExtractor<H> extractor = resultSetExtractor.newResultSetExtractor(handler);
			try {
				return extractor.extractData(rs);
			} finally {
				rs.close();
			}
		}
	};
}
 
Example 44
Project: sqlapp   File: QueryDslSupportImpl.java   Source Code and License 6 votes vote down vote up
private long downloadMain(QueryConfigurer commonClause, QueryConfigurer orderByClause, Consumer consumer,
		Limiter limiter, Expression<?>... expressions) throws LimiterException, IOException {

	ResultSetExtractor<Long> extractor = new ExtractorResultSetExtractor(consumer, limiter);

	limiter.start();
	try {

		SQLQuery query = queryDslJdbcOperations.newSqlQuery();
		query = commonClause.configure(query);
		query = orderByClause.configure(query);

		return queryDslJdbcOperations.queryForObject(query, extractor, expressions);
	} catch (IllegalStateException ex) {
		throw (IOException) ex.getCause();
	} finally {
		limiter.stop();
	}
}
 
Example 45
Project: sqlapp   File: ExtractorImpl.java   Source Code and License 6 votes vote down vote up
/**
 * データを抽出する。
 * 
 * @param dataSource データソース。
 * @param sql SQL。
 * @param paramMap データ抽出時のパラメタ。
 * @param consumer データの格納先。
 * @param limiter データ抽出制限。
 * @return 格納したデータの件数。
 * @throws LimiterException データ抽出制限超過。
 * @throws IOException データ格納エラー。
 */
@Override
public long extract(DataSource dataSource, String sql, Map<String, ?> paramMap, Consumer consumer, Limiter limiter)
		throws LimiterException, IOException {

	NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource);
	ResultSetExtractor<Long> extractor = new ExtractorResultSetExtractor(consumer, limiter);

	limiter.start();
	try {
		return template.query(sql, paramMap, extractor);
	} catch (IllegalStateException ex) {
		throw (IOException) ex.getCause();
	} finally {
		limiter.stop();
	}
}
 
Example 46
Project: spring-session   File: JdbcOperationsSessionRepositoryTests.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getSessionNotFound() {
	String sessionId = "testSessionId";
	given(this.jdbcOperations.query(isA(String.class),
			isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)))
			.willReturn(Collections.emptyList());

	JdbcOperationsSessionRepository.JdbcSession session = this.repository
			.findById(sessionId);

	assertThat(session).isNull();
	assertPropagationRequiresNew();
	verify(this.jdbcOperations, times(1)).query(isA(String.class),
			isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class));
}
 
Example 47
Project: spring-session   File: JdbcOperationsSessionRepositoryTests.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getSessionExpired() {
	Session expired = this.repository.new JdbcSession();
	expired.setLastAccessedTime(Instant.now().minusSeconds(
			MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS + 1));
	given(this.jdbcOperations.query(isA(String.class),
			isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)))
			.willReturn(Collections.singletonList(expired));

	JdbcOperationsSessionRepository.JdbcSession session = this.repository
			.findById(expired.getId());

	assertThat(session).isNull();
	assertPropagationRequiresNew();
	verify(this.jdbcOperations, times(1)).query(isA(String.class),
			isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class));
	verify(this.jdbcOperations, times(1)).update(startsWith("DELETE"),
			eq(expired.getId()));
}
 
Example 48
Project: spring-session   File: JdbcOperationsSessionRepositoryTests.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getSessionFound() {
	Session saved = this.repository.new JdbcSession("primaryKey", new MapSession());
	saved.setAttribute("savedName", "savedValue");
	given(this.jdbcOperations.query(isA(String.class),
			isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)))
			.willReturn(Collections.singletonList(saved));

	JdbcOperationsSessionRepository.JdbcSession session = this.repository
			.findById(saved.getId());

	assertThat(session.getId()).isEqualTo(saved.getId());
	assertThat(session.isNew()).isFalse();
	assertThat(session.<String>getAttribute("savedName")).isEqualTo("savedValue");
	assertPropagationRequiresNew();
	verify(this.jdbcOperations, times(1)).query(isA(String.class),
			isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class));
}
 
Example 49
Project: spring-session   File: JdbcOperationsSessionRepositoryTests.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void findByIndexNameAndIndexValuePrincipalIndexNameNotFound() {
	String principal = "username";
	given(this.jdbcOperations.query(isA(String.class),
			isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class)))
			.willReturn(Collections.emptyList());

	Map<String, JdbcOperationsSessionRepository.JdbcSession> sessions = this.repository
			.findByIndexNameAndIndexValue(
					FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
					principal);

	assertThat(sessions).isEmpty();
	assertPropagationRequiresNew();
	verify(this.jdbcOperations, times(1)).query(isA(String.class),
			isA(PreparedStatementSetter.class), isA(ResultSetExtractor.class));
}
 
Example 50
Project: iBase   File: JdbcUserInfoDAO.java   Source Code and License 6 votes vote down vote up
public UserInfo findById(String userId) {
	String sql = "SELECT * FROM userInfo WHERE userId = "+"\""+userId+"\"";
	logger.info("Running query: " + sql);
	return jdbcTemplate.query(sql, new ResultSetExtractor<UserInfo>(){
		public UserInfo extractData(ResultSet rs) throws SQLException,
				DataAccessException {
			if(rs.next()){
				UserInfo userInfo = new UserInfo(rs.getString("userId")
						, rs.getString("password")
						, rs.getString("firstName")
						, rs.getString("lastName")
						, rs.getString("friendList"), rs.getString("imagesList")
						, rs.getInt("imageCount"), rs.getString("profilePic"));
				return userInfo;
			}
			return null;
		}
	});	
}
 
Example 51
Project: kfs   File: IcrEncumbranceDaoJdbc.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the object type code for the object code associated with the ICR Rate
 *
 * @param icrArgs a list of query arguments
 * @return the object type code if found, null otherwise
 */
protected String getICRObjectTypeCode(Object[] icrArgs) {
    final String icrSql = "select fin_obj_typ_cd "
            + "from ca_object_code_t where univ_fiscal_yr = ? and fin_coa_cd = ? and fin_object_cd = ?";

    String objectTypeCode = (String) getJdbcTemplate().query(icrSql, icrArgs, new ResultSetExtractor() {
        @Override
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
            try {
                if (rs.next()) {
                    return rs.getString("fin_obj_typ_cd");
                }

                return null;
            }
            catch (SQLException e) {
                throw new RuntimeException(e);
            }
            catch (DataAccessException ed) {
                throw new RuntimeException(ed);
            }
        }
    });

    return objectTypeCode;
}
 
Example 52
Project: kfs   File: DepreciationBatchDaoJdbc.java   Source Code and License 6 votes vote down vote up
/**
 * @see org.kuali.kfs.module.cam.document.dataaccess.DepreciationBatchDao#getAssetAndPaymentCount(java.lang.Integer,
 *      java.lang.Integer, java.util.Calendar, boolean, java.util.List)
 */
@Override
public Object[] getAssetAndPaymentCount(Integer fiscalYear, Integer fiscalMonth, final Calendar depreciationDate, boolean includePending) {
    final Object[] data = new Object[2];
    List<String> depreciationMethodList = new ArrayList<String>();
    Collection<String> notAcceptedAssetStatus = parameterService.getParameterValuesAsString(KfsParameterConstants.CAPITAL_ASSETS_BATCH.class, CamsConstants.Parameters.NON_DEPRECIABLE_NON_CAPITAL_ASSETS_STATUS_CODES);
    depreciationMethodList.add(CamsConstants.Asset.DEPRECIATION_METHOD_SALVAGE_VALUE_CODE);
    depreciationMethodList.add(CamsConstants.Asset.DEPRECIATION_METHOD_STRAIGHT_LINE_CODE);
    Collection<String> federallyOwnedObjectSubTypes = getFederallyOwnedObjectSubTypes();
    String sql = "SELECT COUNT(DISTINCT A0.CPTLAST_NBR), COUNT(1) " + buildCriteria(fiscalYear, fiscalMonth, depreciationMethodList, notAcceptedAssetStatus, federallyOwnedObjectSubTypes, false, includePending);
    getJdbcTemplate().query(sql, preparedStatementSetter(depreciationDate), new ResultSetExtractor() {

        @Override
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
            if (rs != null && rs.next()) {
                data[0] = rs.getInt(1);
                data[1] = rs.getInt(2);
            }
            return data;
        }

    });
    return data;
}
 
Example 53
Project: kfs   File: DepreciationBatchDaoJdbc.java   Source Code and License 6 votes vote down vote up
/**
 * @see org.kuali.kfs.module.cam.document.dataaccess.DepreciationBatchDao#getFederallyOwnedAssetAndPaymentCount(java.lang.Integer,
 *      java.lang.Integer, java.util.Calendar)
 */
@Override
public Object[] getFederallyOwnedAssetAndPaymentCount(Integer fiscalYear, Integer fiscalMonth, final Calendar depreciationDate) {
    final Object[] data = new Object[2];
    List<String> depreciationMethodList = new ArrayList<String>();
    Collection<String> notAcceptedAssetStatus = parameterService.getParameterValuesAsString(KfsParameterConstants.CAPITAL_ASSETS_BATCH.class, CamsConstants.Parameters.NON_DEPRECIABLE_NON_CAPITAL_ASSETS_STATUS_CODES);
    depreciationMethodList.add(CamsConstants.Asset.DEPRECIATION_METHOD_SALVAGE_VALUE_CODE);
    depreciationMethodList.add(CamsConstants.Asset.DEPRECIATION_METHOD_STRAIGHT_LINE_CODE);
    Collection<String> federallyOwnedObjectSubTypes = getFederallyOwnedObjectSubTypes();
    String sql = "SELECT COUNT(DISTINCT A0.CPTLAST_NBR), COUNT(1) " + buildCriteria(fiscalYear, fiscalMonth, depreciationMethodList, notAcceptedAssetStatus, federallyOwnedObjectSubTypes, true, true);
    getJdbcTemplate().query(sql, preparedStatementSetter(depreciationDate), new ResultSetExtractor() {

        @Override
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
            if (rs != null && rs.next()) {
                data[0] = rs.getInt(1);
                data[1] = rs.getInt(2);
            }
            return data;
        }

    });
    return data;
}
 
Example 54
Project: kfs   File: DepreciationBatchDaoJdbc.java   Source Code and License 6 votes vote down vote up
/**
 * @see org.kuali.kfs.module.cam.document.dataaccess.DepreciationBatchDao#getPrimaryDepreciationBaseAmountForSV()
 */
@Override
public Map<Long, KualiDecimal> getPrimaryDepreciationBaseAmountForSV() {
    final Map<Long, KualiDecimal> amountMap = new HashMap<Long, KualiDecimal>();
    getJdbcTemplate().query("SELECT PMT.CPTLAST_NBR, SUM(PMT.AST_DEPR1_BASE_AMT) FROM CM_CPTLAST_T AST, CM_AST_PAYMENT_T PMT WHERE AST.CPTLAST_NBR = PMT.CPTLAST_NBR AND AST.AST_DEPR_MTHD1_CD = '" + CamsConstants.Asset.DEPRECIATION_METHOD_SALVAGE_VALUE_CODE + "' GROUP BY PMT.CPTLAST_NBR", new ResultSetExtractor() {

        @Override
        public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
            while (rs != null && rs.next()) {
                amountMap.put(rs.getLong(1), new KualiDecimal(rs.getBigDecimal(2)));
            }
            return amountMap;
        }

    });
    return amountMap;
}
 
Example 55
Project: springapp   File: QueryDslSupportImpl.java   Source Code and License 6 votes vote down vote up
private long downloadMain(QueryConfigurer commonClause, QueryConfigurer orderByClause, Consumer consumer,
		Limiter limiter, Expression<?>... expressions) throws LimiterException, IOException {

	limiter.start();
	try {

		SQLQuery query = commonClause.configure(queryFactory.query());
		query = orderByClause.configure(query);

		ResultSetExtractor<Long> extractor = new ExtractorResultSetExtractor(consumer, limiter);
		return getResults("download", query, extractor, expressions);

	} catch (IllegalStateException ex) {
		throw (IOException) ex.getCause();
	} finally {
		limiter.stop();
	}
}
 
Example 56
Project: springapp   File: ExtractorImpl.java   Source Code and License 6 votes vote down vote up
/**
 * データを抽出する。
 * 
 * @param dataSource データソース。
 * @param sql SQL。
 * @param paramMap データ抽出時のパラメタ。
 * @param consumer データの格納先。
 * @param limiter データ抽出制限。
 * @return 格納したデータの件数。
 * @throws LimiterException データ抽出制限超過。
 * @throws IOException データ格納エラー。
 */
@Override
public long extract(DataSource dataSource, String sql, Map<String, ?> paramMap, Consumer consumer, Limiter limiter)
		throws LimiterException, IOException {

	NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource);
	ResultSetExtractor<Long> extractor = new ExtractorResultSetExtractor(consumer, limiter);

	limiter.start();
	try {
		return template.query(sql, paramMap, extractor);
	} catch (IllegalStateException ex) {
		throw (IOException) ex.getCause();
	} finally {
		limiter.stop();
	}
}
 
Example 57
Project: maven-framework-project   File: ContactDAOImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Contact get(int contactId) {
	String sql = "SELECT * FROM contact WHERE contact_id=" + contactId;
    return jdbcTemplate.query(sql, new ResultSetExtractor<Contact>() {
 
        @Override
        public Contact extractData(ResultSet rs) throws SQLException,
                DataAccessException {
            if (rs.next()) {
                Contact contact = new Contact();
                contact.setId(rs.getInt("contact_id"));
                contact.setName(rs.getString("name"));
                contact.setEmail(rs.getString("email"));
                contact.setAddress(rs.getString("address"));
                contact.setTelephone(rs.getString("telephone"));
                return contact;
            }
 
            return null;
        }
 
    });
}
 
Example 58
Project: hibernate-postgresql   File: HstoreTypeTest.java   Source Code and License 6 votes vote down vote up
@Test
   @Sql
   public void testSetWithNewMap() throws Exception {
    HstoreTypeEntity fromDb = em.find(HstoreTypeEntity.class, 37);
       Map<String, String> map = fromDb.getMap();
       map.remove("name");
       map.put("power", "ball");
       em.flush();

       String newMapValue = this.jdbcTemplate.query("select map from HstoreTypeEntity where id = 37", new ResultSetExtractor<String>(){

           @Override
           public String extractData(ResultSet rs) throws SQLException, DataAccessException {
               rs.next();
               return rs.getString(1);
           }});
       assertNotNull(newMapValue);
       /*
        * postgres puts a space around the '=>' operator, which I wanna ignore
        */
       assertThat(newMapValue.replace(" => ", "=>"), is(equalTo("\"power\"=>\"ball\"")));
}
 
Example 59
Project: corpus-utils   File: NFCrawlerDocumentSet.java   Source Code and License 6 votes vote down vote up
private SortedSet<Long> getFeedArticleIds(int feedId) {
	Map<String, Object> paramMap = prepareParamMap();
	paramMap.put("feedId", feedId);
	return getNamedParameterJdbcTemplate().query(SELECT_FEED_ARTICLE_IDS, paramMap,
			new ResultSetExtractor<SortedSet<Long>>() {
				@Override
				public SortedSet<Long> extractData(ResultSet rs) throws SQLException,
						DataAccessException {
					SortedSet<Long> resultSet = Sets.newTreeSet();
					while (rs.next()) {
						resultSet.add(rs.getLong(1));
					}
					return resultSet;
				}
			});
}
 
Example 60
Project: spring4-sandbox   File: JdbcConferenceDaoImpl.java   Source Code and License 6 votes vote down vote up
public Conference findBySlug1(String slug) {
	List<Conference> confs = getJdbcTemplate().query(
			"select * from conference where slug=?", new Object[] { slug },
			new ResultSetExtractor<List<Conference>>() {

				@Override
				public List<Conference> extractData(ResultSet rs)
						throws SQLException, DataAccessException {
					// TODO Auto-generated method stub
					return null;
				}
			});
	if (!confs.isEmpty()) {
		return confs.get(0);
	}
	return null;
}