下面列出了org.springframework.data.domain.Sort#Direction ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private List<TxEvent> searchTxList(int pageIndex, int pageSize, String orderName, String direction, String searchText) {
// TODO 检测是否有非数字,如果有非数字则过滤掉数字类型字段
// TODO 检测如果是字符“-”,则视为无searchText处理,因为每一行的日期都含有“-”,或者是当已完成的查询
try {
pageIndex = pageIndex < 1 ? 0 : pageIndex;
pageSize = pageSize < 1 ? 100 : pageSize;
Sort.Direction sd = Sort.Direction.DESC;
if (orderName == null || orderName.length() == 0) {
orderName = "creationTime";
}
if ("asc".equalsIgnoreCase(direction)) {
sd = Sort.Direction.ASC;
}
PageRequest pageRequest = new PageRequest(pageIndex, pageSize, sd, orderName);
if (searchText == null || searchText.length() == 0) {
return eventRepo.findTxList(pageRequest);
}
return eventRepo.findTxList(pageRequest, searchText);
} catch (Exception e) {
LOG.error("Failed to find the list of Global Transaction. params {pageIndex: [{}], pageSize: [{}], orderName: [{}], direction: [{}], searchText: [{}]}.", pageIndex, pageSize, orderName, direction, searchText, e);
}
return null;
}
protected Pageable createPageRequest(int startPage, int itemsPerPage, String sortColumn, String direction) {
PageRequest pageRequest;
if (sortColumn == null || sortColumn.length() == 0) {
pageRequest = new PageRequest(startPage, itemsPerPage);
} else {
Sort.Direction sortDirection;
if (direction == null) {
sortDirection = Sort.Direction.ASC;
} else {
sortDirection = Sort.Direction.fromStringOrNull(direction.toUpperCase(Locale.US));
if (sortDirection == null) {
sortDirection = Sort.Direction.ASC;
}
}
pageRequest = new PageRequest(startPage, itemsPerPage, new Sort(sortDirection, sortColumn));
}
return pageRequest;
}
@GetMapping("/reports/harvest")
@PreAuthorize("hasPermission(#bodyId, 'ACCESS')")
@Activity(bodies = "#bodyId")
public String reportsHarvest(@RequestParam(name = "body") long bodyId,
@RequestParam(required = false, defaultValue = "AT") HarvestReportSortOrderDto order,
@RequestParam(required = false, defaultValue = "DESC") Sort.Direction direction,
@RequestParam(required = false, defaultValue = "1") @Min(1) int page,
@RequestParam(required = false, defaultValue = "50") @Min(1) int size,
Model model) {
PageRequest pageRequest = PageRequest.of(page - 1, size);
List<HarvestReportDto> reports = reportService.getHarvestReports(bodyId, order, direction, pageRequest);
model.addAttribute("bodyId", bodyId);
model.addAttribute("summary", reportService.getSummary(bodyId));
model.addAttribute("order", order.toString());
model.addAttribute("direction", direction.toString());
model.addAttribute("page", page);
model.addAttribute("size", size);
model.addAttribute("reports", reports);
return "reports-harvest";
}
/**
* Creates a 'LIMIT .. OFFSET .. ORDER BY ..' clause for the given {@link DataTablesInput}.
*
* @return a {@link Pageable}, must not be {@literal null}.
*/
public Pageable createPageable() {
List<Sort.Order> orders = new ArrayList<>();
for (org.springframework.data.jpa.datatables.mapping.Order order : input.getOrder()) {
Column column = input.getColumns().get(order.getColumn());
if (column.getOrderable()) {
String sortColumn = column.getData();
Sort.Direction sortDirection = Sort.Direction.fromString(order.getDir());
orders.add(new Sort.Order(sortDirection, sortColumn));
}
}
Sort sort = orders.isEmpty() ? Sort.unsorted() : Sort.by(orders);
if (input.getLength() == -1) {
input.setStart(0);
input.setLength(Integer.MAX_VALUE);
}
return new DataTablesPageRequest(input.getStart(), input.getLength(), sort);
}
public static Pageable initPage(PageVo page) {
Pageable pageable;
int pageNumber = page.getPageNumber();
int pageSize = page.getPageSize();
String sort = page.getSort();
String order = page.getOrder();
if (pageNumber < 1) {
pageNumber = 1;
}
if (pageSize < 1) {
pageSize = 10;
}
if (StrUtil.isNotBlank(sort)) {
Sort.Direction d;
if (StrUtil.isBlank(order)) {
d = Sort.Direction.DESC;
} else {
d = Sort.Direction.valueOf(order.toUpperCase());
}
Sort s = new Sort(d, sort);
pageable = PageRequest.of(pageNumber - 1, pageSize, s);
} else {
pageable = PageRequest.of(pageNumber - 1, pageSize);
}
return pageable;
}
public UserSettingsDto(String language, String skin, int numProbes, BodiesSortOrderDto bodiesSortOrder,
Sort.Direction bodiesSortDirection, boolean numberInputScrollingEnabled,
boolean showNewMessagesInOverviewEnabled, boolean showNewReportsInOverviewEnabled,
boolean stickyMoonsEnabled) {
this.language = language;
this.skin = skin;
this.numProbes = numProbes;
this.bodiesSortOrder = bodiesSortOrder;
this.bodiesSortDirection = bodiesSortDirection;
this.numberInputScrollingEnabled = numberInputScrollingEnabled;
this.showNewMessagesInOverviewEnabled = showNewMessagesInOverviewEnabled;
this.showNewReportsInOverviewEnabled = showNewReportsInOverviewEnabled;
this.stickyMoonsEnabled = stickyMoonsEnabled;
}
@RequiresPermissions("exchange:exchange-coin:page-query")
@PostMapping("page-query")
@AccessLog(module = AdminModule.EXCHANGE, operation = "分页查找币币交易手续费exchangeCoin")
public MessageResult ExchangeCoinList(PageModel pageModel) {
if (pageModel.getProperty() == null) {
List<String> list = new ArrayList<>();
list.add("symbol");
List<Sort.Direction> directions = new ArrayList<>();
directions.add(Sort.Direction.DESC);
pageModel.setProperty(list);
pageModel.setDirection(directions);
}
Page<ExchangeCoin> all = exchangeCoinService.findAll(null, pageModel.getPageable());
return success(all);
}
@Bean
@Qualifier("repositoryItemReaderWithParams")
public RepositoryItemReader<User> repositoryItemReaderWithParams() {
Map<String, Sort.Direction> map = new HashMap<>();
map.put("id", Sort.Direction.DESC);
List<String> params = new ArrayList();
params.add("i%");
RepositoryItemReader<User> repositoryItemReader = new RepositoryItemReader<>();
repositoryItemReader.setRepository(userReaderRepository);
repositoryItemReader.setPageSize(5);
repositoryItemReader.setMethodName("findAllByFirstNameLike");
repositoryItemReader.setArguments(params);
repositoryItemReader.setSort(map);
return repositoryItemReader;
}
private List<AuditLog> findAuditLogs(UUID tenantId, EntityId entityId, CustomerId customerId, UserId userId, TimePageLink pageLink){
Specification<AuditLogEntity> timeSearchSpec = JpaAbstractSearchTimeDao.getTimeSearchPageSpec(pageLink, "id");
Specification<AuditLogEntity> fieldsSpec = getEntityFieldsSpec(tenantId, entityId, customerId, userId);
Sort.Direction sortDirection = pageLink.isAscOrder() ? Sort.Direction.ASC : Sort.Direction.DESC;
Pageable pageable = new PageRequest(0, pageLink.getLimit(), sortDirection, ID_PROPERTY);
return DaoUtil.convertDataList(auditLogRepository.findAll(where(timeSearchSpec).and(fieldsSpec), pageable).getContent());
}
@Override
public List<Event> findEvents(UUID tenantId, EntityId entityId, String eventType, TimePageLink pageLink) {
Specification<EventEntity> timeSearchSpec = JpaAbstractSearchTimeDao.<EventEntity>getTimeSearchPageSpec(pageLink, "id");
Specification<EventEntity> fieldsSpec = getEntityFieldsSpec(tenantId, entityId, eventType);
Sort.Direction sortDirection = pageLink.isAscOrder() ? Sort.Direction.ASC : Sort.Direction.DESC;
Pageable pageable = new PageRequest(0, pageLink.getLimit(), sortDirection, ID_PROPERTY);
return DaoUtil.convertDataList(eventRepository.findAll(where(timeSearchSpec).and(fieldsSpec), pageable).getContent());
}
private Sort getSort(String sortNamePrefix, Map<String, String[]> sortMap, Pageable defaultPageRequest, NativeWebRequest webRequest) {
Sort sort = null;
List<OrderedSort> orderedSortList = Lists.newArrayList();
for (String name : sortMap.keySet()) {
//sort1.abc
int propertyIndex = name.indexOf(".") + 1;
int order = 0;
String orderStr = name.substring(sortNamePrefix.length(), propertyIndex - 1);
try {
if (!StringUtils.isEmpty(orderStr)) {
order = Integer.valueOf(orderStr);
}
} catch (Exception e) {
}
String property = name.substring(propertyIndex);
assertSortProperty(property);
Sort.Direction direction = Sort.Direction.fromString(sortMap.get(name)[0]);
orderedSortList.add(new OrderedSort(property, direction, order));
}
Collections.sort(orderedSortList);
for (OrderedSort orderedSort : orderedSortList) {
Sort newSort = new Sort(orderedSort.direction, orderedSort.property);
if (sort == null) {
sort = newSort;
} else {
sort = sort.and(newSort);
}
}
if (sort == null) {
return defaultPageRequest.getSort();
}
return sort;
}
SortAssert hasSort(String field, Sort.Direction direction) {
Sort.Order actualOrder = actual.getOrderFor(field);
if (actualOrder == null) {
failWithMessage("expected sort for field <%s> to be <%s> but was null", field, direction);
} else if (actualOrder.getDirection() != direction) {
failWithMessage("expected sort for field <%s> to be <%s> but was <%s>", field, direction, actualOrder.getDirection());
}
return this;
}
@Override
public List<TransportReport> findReports(User user, TransportReportSortOrder order, Sort.Direction direction,
Pageable pageable) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<TransportReport> criteriaQuery = criteriaBuilder.createQuery(TransportReport.class);
Root<TransportReport> root = criteriaQuery.from(TransportReport.class);
criteriaQuery.where(criteriaBuilder.and(
criteriaBuilder.equal(root.get("user"), user),
criteriaBuilder.equal(root.get("deleted"), false)));
Function<Expression<?>, Order> dirFunc =
direction == Sort.Direction.ASC ? criteriaBuilder::asc : criteriaBuilder::desc;
switch (order) {
case AT: {
criteriaQuery.orderBy(dirFunc.apply(root.get("at")));
break;
}
case KIND: {
criteriaQuery.orderBy(dirFunc.apply(root.get("kind")));
break;
}
case PARTNER_NAME: {
criteriaQuery.orderBy(dirFunc.apply(root.get("partnerName")));
break;
}
case START_COORDINATES: {
// galaxy, system, position, kind
criteriaQuery.orderBy(
dirFunc.apply(root.get("startCoordinates").get("galaxy")),
dirFunc.apply(root.get("startCoordinates").get("system")),
dirFunc.apply(root.get("startCoordinates").get("position")),
dirFunc.apply(root.get("startCoordinates").get("kind")));
break;
}
case TARGET_COORDINATES: {
// galaxy, system, position, kind
criteriaQuery.orderBy(
dirFunc.apply(root.get("targetCoordinates").get("galaxy")),
dirFunc.apply(root.get("targetCoordinates").get("system")),
dirFunc.apply(root.get("targetCoordinates").get("position")),
dirFunc.apply(root.get("targetCoordinates").get("kind")));
break;
}
case RESOURCES: {
// (metal + crystal) + deuterium
criteriaQuery.orderBy(dirFunc.apply(
criteriaBuilder.sum(
criteriaBuilder.sum(
root.get("resources").get("metal"),
root.get("resources").get("crystal")),
root.get("resources").get("deuterium"))));
break;
}
}
TypedQuery<TransportReport> typedQuery = entityManager.createQuery(criteriaQuery);
typedQuery.setFirstResult((int) pageable.getOffset());
typedQuery.setMaxResults(pageable.getPageSize());
return typedQuery.getResultList();
}
public void setBodiesSortDirection(Sort.Direction bodiesSortDirection) {
this.bodiesSortDirection = bodiesSortDirection;
}
public void setBodiesSortDirection(Sort.Direction bodiesSortDirection) {
this.bodiesSortDirection = bodiesSortDirection;
}
@Override
public List<EspionageReport> findReports(User user, EspionageReportSortOrder order, Sort.Direction direction,
Pageable pageable) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<EspionageReport> criteriaQuery = criteriaBuilder.createQuery(EspionageReport.class);
Root<EspionageReport> root = criteriaQuery.from(EspionageReport.class);
criteriaQuery.where(criteriaBuilder.and(
criteriaBuilder.equal(root.get("user"), user),
criteriaBuilder.equal(root.get("deleted"), false)));
Function<Expression<?>, Order> dirFunc =
direction == Sort.Direction.ASC ? criteriaBuilder::asc : criteriaBuilder::desc;
switch (order) {
case AT: {
criteriaQuery.orderBy(dirFunc.apply(root.get("at")));
break;
}
case ENEMY_NAME: {
criteriaQuery.orderBy(dirFunc.apply(root.get("enemyName")));
break;
}
case COORDINATES: {
// galaxy, system, position, kind
criteriaQuery.orderBy(
dirFunc.apply(root.get("coordinates").get("galaxy")),
dirFunc.apply(root.get("coordinates").get("system")),
dirFunc.apply(root.get("coordinates").get("position")),
dirFunc.apply(root.get("coordinates").get("kind")));
break;
}
case ACTIVITY: {
criteriaQuery.orderBy(dirFunc.apply(root.get("activity")));
break;
}
case RESOURCES: {
// (metal + crystal) + deuterium
criteriaQuery.orderBy(dirFunc.apply(
criteriaBuilder.sum(
criteriaBuilder.sum(
root.get("resources").get("metal"),
root.get("resources").get("crystal")),
root.get("resources").get("deuterium"))));
break;
}
case FLEET: {
criteriaQuery.orderBy(dirFunc.apply(root.get("fleet")));
break;
}
case DEFENSE: {
criteriaQuery.orderBy(dirFunc.apply(root.get("defense")));
break;
}
}
TypedQuery<EspionageReport> typedQuery = entityManager.createQuery(criteriaQuery);
typedQuery.setFirstResult((int) pageable.getOffset());
typedQuery.setMaxResults(pageable.getPageSize());
return typedQuery.getResultList();
}
/**
* Get {@link Sort}
*
* @param param sort param
* @param direction {@link Sort.Direction}
* @return {@link Sort}
*/
public static Sort getSort(String param, Sort.Direction direction) {
return Sort.by(direction, param);
}
/**
* Creates a new {@link OffsetBasedPageRequest} with sort parameters applied.
*
* @param offset zero-based offset.
* @param limit the size of the elements to be returned.
* @param direction the direction of the {@link Sort} to be specified, can be {@literal null}.
* @param properties the properties to sort by, must not be {@literal null} or empty.
*/
public OffsetBasedPageRequest(int offset, int limit, Sort.Direction direction, String... properties) {
this(offset, limit, new Sort(direction, properties));
}
public abstract Searchable addSort(final Sort.Direction direction, String property);
List<HarvestReport> findReports(User user, HarvestReportSortOrder order, Sort.Direction direction, Pageable pageable);