Java Code Examples for org.springframework.data.domain.Sort#Direction

The following examples show how to use org.springframework.data.domain.Sort#Direction . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractPredicateBuilder.java    From spring-data-jpa-datatables with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Source File: ReportsController.java    From retro-game with GNU Affero General Public License v3.0 6 votes vote down vote up
@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";
}
 
Example 3
Source File: AbstractPagingAndSortingService.java    From logging-log4j-audit with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: SpringTxEventRepository.java    From txle with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source File: SortAssert.java    From code-examples with MIT License 5 votes vote down vote up
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;
	}
 
Example 6
Source File: PageUtil.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
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;
    }
 
Example 7
Source File: PageableMethodArgumentResolver.java    From es with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: JpaBaseEventDao.java    From iotplatform with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 9
Source File: JpaAuditLogDao.java    From Groza with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 10
Source File: UserReader.java    From spring-cloud with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 11
Source File: ExchangeCoinController.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@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);
}
 
Example 12
Source File: UserSettingsDto.java    From retro-game with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 13
Source File: User.java    From retro-game with GNU Affero General Public License v3.0 4 votes vote down vote up
public void setBodiesSortDirection(Sort.Direction bodiesSortDirection) {
  this.bodiesSortDirection = bodiesSortDirection;
}
 
Example 14
Source File: SettingsForm.java    From retro-game with GNU Affero General Public License v3.0 4 votes vote down vote up
public void setBodiesSortDirection(Sort.Direction bodiesSortDirection) {
  this.bodiesSortDirection = bodiesSortDirection;
}
 
Example 15
Source File: TransportReportRepositoryImpl.java    From retro-game with GNU Affero General Public License v3.0 4 votes vote down vote up
@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();
}
 
Example 16
Source File: EspionageReportRepositoryImpl.java    From retro-game with GNU Affero General Public License v3.0 4 votes vote down vote up
@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();
}
 
Example 17
Source File: QueryHelper.java    From spring-microservice-boilerplate with MIT License 2 votes vote down vote up
/**
 * 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);
}
 
Example 18
Source File: OffsetBasedPageRequest.java    From crudui with Apache License 2.0 2 votes vote down vote up
/**
 * 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));
}
 
Example 19
Source File: HarvestReportRepositoryCustom.java    From retro-game with GNU Affero General Public License v3.0 votes vote down vote up
List<HarvestReport> findReports(User user, HarvestReportSortOrder order, Sort.Direction direction, Pageable pageable); 
Example 20
Source File: Searchable.java    From es with Apache License 2.0 votes vote down vote up
public abstract Searchable addSort(final Sort.Direction direction, String property);