Example usage for org.springframework.data.domain Sort Sort

List of usage examples for org.springframework.data.domain Sort Sort

Introduction

In this page you can find the example usage for org.springframework.data.domain Sort Sort.

Prototype

private Sort(Direction direction, List<String> properties) 

Source Link

Document

Creates a new Sort instance.

Usage

From source file:cn.guoyukun.spring.jpa.web.bind.method.annotation.PageableMethodArgumentResolver.java

private Pageable defaultPageable(PageableDefaults pageableDefaults) {

    if (pageableDefaults == null) {
        return null;
    }/*from ww w. j  ava 2s. c o m*/

    int pageNumber = pageableDefaults.pageNumber();
    int pageSize = pageableDefaults.value();

    String[] sortStrArray = pageableDefaults.sort();
    Sort sort = null;

    for (String sortStr : sortStrArray) {
        String[] sortStrPair = sortStr.split("=");
        Sort newSort = new Sort(Sort.Direction.fromString(sortStrPair[1]), sortStrPair[0]);
        if (sort == null) {
            sort = newSort;
        } else {
            sort = sort.and(newSort);
        }
    }
    return new PageRequest(pageNumber, pageSize, sort);
}

From source file:me.adaptive.che.infrastructure.api.MetricsModule.java

/**
 * Returns the specified number of values for a specific metric on
 * a specific server//w  w w.  j av a  2 s .c  o  m
 *
 * @param server Hosname of the server to query
 * @param metric Metric to query
 * @param number Number of values
 * @return Metric's values
 * @throws ServerException   When some error is produced on the server
 * @throws ConflictException When there are issues with the parameters
 * @throws NotFoundException When the platform is not found
 */
@ApiOperation(value = "Server metric last values", notes = "Returns the specified values for a metric in a concrete server", response = Map.class, position = 3)
@ApiResponses({ @ApiResponse(code = 200, message = "Successful operation"),
        @ApiResponse(code = 401, message = "Invalid parameters"),
        @ApiResponse(code = 404, message = "Platform Not Found"),
        @ApiResponse(code = 500, message = "Internal Server Error") })
@GET
@Path("/server/{server}/{metric}/{number}")
@GenerateLink(rel = "server metric values")
@Produces(APPLICATION_JSON)
public Map<String, String> serverMetricValues(
        @ApiParam(value = "server", required = true) @PathParam("server") String server,
        @ApiParam(value = "metric", required = true) @PathParam("metric") String metric,
        @ApiParam(value = "number", required = false, defaultValue = "20") @PathParam("number") String number)
        throws ServerException, ConflictException, NotFoundException {

    Map<String, String> map = new TreeMap<>();

    Page<MetricServerEntity> values = metricServerRepository.findByHostnameAndAttributeKey(server, metric,
            new PageRequest(0, Integer.valueOf(number), new Sort(Sort.Direction.DESC, "createdAt")));

    for (MetricServerEntity ms : values) {

        map.put(ms.getCreatedAt().toString(), ms.getAttributes().get(metric));
    }

    return map;
}

From source file:com.restfiddle.controller.rest.NodeController.java

@RequestMapping(value = "/api/nodes/starred", method = RequestMethod.GET)
public @ResponseBody List<NodeDTO> findStarredNodes(
        @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "limit", required = false) Integer limit) {
    logger.debug("Finding starred nodes.");

    int pageNo = 0;
    if (page != null && page > 0) {
        pageNo = page;//from ww  w  .  j  av  a  2  s.com
    }

    int numberOfRecords = 10;
    if (limit != null && limit > 0) {
        numberOfRecords = limit;
    }
    Sort sort = new Sort(Direction.DESC, "lastModifiedDate");
    Pageable pageable = new PageRequest(pageNo, numberOfRecords, sort);

    Page<BaseNode> paginatedStarredNodes = nodeRepository.findStarredNodes(pageable);

    List<BaseNode> starredNodes = paginatedStarredNodes.getContent();
    long totalElements = paginatedStarredNodes.getTotalElements();

    List<NodeDTO> response = new ArrayList<NodeDTO>();
    for (BaseNode item : starredNodes) {
        response.add(EntityToDTO.toDTO(item));
    }

    System.out.println("totalElements : " + totalElements);
    return response;
}

From source file:com.luna.common.web.bind.method.annotation.SearchableMethodArgumentResolverTest.java

@Test
public void testParameterDefaultSearchableWithOverrideSearchParams() throws Exception {
    int pn = 1;//from   w  w w.j av a 2s .c  o  m
    int pageSize = 10;
    request.setParameter("page.pn", String.valueOf(pn));
    request.setParameter("page.size", String.valueOf(pageSize));

    request.setParameter("sort1.baseInfo.realname", "asc");
    request.setParameter("sort2.id", "desc");

    request.setParameter("search.baseInfo.realname_like", "zhang");
    request.setParameter("search.username_eq", "zhang");

    MethodParameter parameter = new MethodParameter(parameterDefaultSearchable, 0);
    NativeWebRequest webRequest = new ServletWebRequest(request);
    Searchable searchable = (Searchable) new SearchableMethodArgumentResolver().resolveArgument(parameter, null,
            webRequest, null);

    //-10
    assertEquals(pn - 1, searchable.getPage().getPageNumber());
    assertEquals(pageSize, searchable.getPage().getPageSize());

    Sort expectedSort = new Sort(Sort.Direction.ASC, "baseInfo.realname")
            .and(new Sort(Sort.Direction.DESC, "id"));
    assertEquals(expectedSort, searchable.getSort());

    assertContainsSearchFilter(
            SearchFilterHelper.newCondition("baseInfo.realname", SearchOperator.like, "zhang"), searchable);
    assertContainsSearchFilter(SearchFilterHelper.newCondition("username", SearchOperator.eq, "zhang"),
            searchable);
}

From source file:com.epam.ta.reportportal.database.dao.LaunchRepositoryCustomImpl.java

@Override
public Optional<Launch> findLastLaunch(String projectId, String mode) {
    Query query = query(where(PROJECT_ID_REFERENCE).is(projectId)).addCriteria(where(STATUS).ne(IN_PROGRESS))
            .addCriteria(where(MODE).is(mode)).limit(1).with(new Sort(Sort.Direction.DESC, START_TIME));
    List<Launch> launches = mongoTemplate.find(query, Launch.class);
    return !launches.isEmpty() ? Optional.of(launches.get(0)) : Optional.empty();
}

From source file:com.epam.ta.reportportal.database.dao.LaunchRepositoryCustomImpl.java

@Override
public Optional<Launch> findLastLaunch(String projectId, String launchName, String mode) {
    Query query = query(where(PROJECT_ID_REFERENCE).is(projectId)).addCriteria(where(NAME).is(launchName))
            .addCriteria(where(MODE).is(mode)).limit(1).with(new Sort(Sort.Direction.DESC, START_TIME));
    List<Launch> launches = mongoTemplate.find(query, Launch.class);
    return !launches.isEmpty() ? Optional.of(launches.get(0)) : Optional.empty();
}

From source file:org.openmhealth.shim.Application.java

/**
 * Endpoint for retrieving data from shims.
 *
 * @param username User ID record for which to retrieve data, if not approved this will throw ShimException.
 * todo: finish javadoc!//from   ww w .  j a v a  2  s .c  o m
 * @return The shim data response wrapper with data from the shim.
 */
@RequestMapping(value = "/data/{shim}/{dataType}", produces = APPLICATION_JSON_VALUE)
public ShimDataResponse data(@RequestParam(value = "username") String username,
        @PathVariable("shim") String shim, @PathVariable("dataType") String dataTypeKey,
        @RequestParam(value = "normalize", defaultValue = "") String normalize,
        @RequestParam(value = "dateStart", defaultValue = "") String dateStart,
        @RequestParam(value = "dateEnd", defaultValue = "") String dateEnd,
        @RequestParam(value = "numToReturn", defaultValue = "50") Long numToReturn) throws ShimException {

    setPassThroughAuthentication(username, shim);

    ShimDataRequest shimDataRequest = new ShimDataRequest();

    shimDataRequest.setDataTypeKey(dataTypeKey);

    if (!normalize.equals("")) {
        shimDataRequest.setNormalize(Boolean.parseBoolean(normalize));
    }

    if (!"".equals(dateStart)) {
        shimDataRequest.setStartDateTime(LocalDate.parse(dateStart).atStartOfDay().atOffset(UTC));
    }
    if (!"".equals(dateEnd)) {
        shimDataRequest.setEndDateTime(LocalDate.parse(dateEnd).atStartOfDay().atOffset(UTC));
    }
    shimDataRequest.setNumToReturn(numToReturn);

    AccessParameters accessParameters = accessParametersRepo.findByUsernameAndShimKey(username, shim,
            new Sort(Sort.Direction.DESC, "dateCreated"));

    if (accessParameters == null) {
        throw new ShimException("User '" + username + "' has not authorized shim: '" + shim + "'");
    }
    shimDataRequest.setAccessParameters(accessParameters);
    return shimRegistry.getShim(shim).getData(shimDataRequest);
}

From source file:com.luna.common.web.bind.method.annotation.SearchableMethodArgumentResolverTest.java

@Test
public void testCustomNamePrefixSearchableAndPageableAndSort() throws Exception {
    int pn = 1;//from   w  ww. j av a  2s  .  c  om
    int pageSize = 10;
    request.setParameter("foo_page.pn", String.valueOf(pn));
    request.setParameter("foo_page.size", String.valueOf(pageSize));

    request.setParameter("foo_sort1.baseInfo.realname", "asc");
    request.setParameter("foo_sort2.id", "desc");

    request.setParameter("foo_search.baseInfo.realname_like", "zhang");
    request.setParameter("foo_search.username_eq", "zhang");

    MethodParameter parameter = new MethodParameter(customNamePrefixSearchableAndPageableAndSort, 0);
    NativeWebRequest webRequest = new ServletWebRequest(request);
    Searchable searchable = (Searchable) new SearchableMethodArgumentResolver().resolveArgument(parameter, null,
            webRequest, null);

    //-10
    assertEquals(pn - 1, searchable.getPage().getPageNumber());
    assertEquals(pageSize, searchable.getPage().getPageSize());

    Sort expectedSort = new Sort(Sort.Direction.ASC, "baseInfo.realname")
            .and(new Sort(Sort.Direction.DESC, "id"));
    assertEquals(expectedSort, searchable.getSort());

    assertContainsSearchFilter(
            SearchFilterHelper.newCondition("baseInfo.realname", SearchOperator.like, "zhang"), searchable);
    assertContainsSearchFilter(SearchFilterHelper.newCondition("username", SearchOperator.eq, "zhang"),
            searchable);
}

From source file:org.ngrinder.user.controller.UserController.java

/**
 * Search user list on the given keyword.
 *
 * @param pageable page info/*from  ww w  .j  a  v a2  s . co  m*/
 * @param keywords search keyword.
 * @return json message
 */
@RestAPI
@RequestMapping(value = "/api/search", method = RequestMethod.GET)
public HttpEntity<String> search(User user, @PageableDefaults Pageable pageable,
        @RequestParam(required = true) String keywords) {
    pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(),
            defaultIfNull(pageable.getSort(), new Sort(Direction.ASC, "userName")));
    Page<User> pagedUser = userService.getPagedAll(keywords, pageable);
    List<UserSearchResult> result = newArrayList();
    for (User each : pagedUser) {
        result.add(new UserSearchResult(each));
    }

    final String currentUserId = user.getUserId();
    CollectionUtils.filter(result, new Predicate() {
        @Override
        public boolean evaluate(Object object) {
            UserSearchResult each = (UserSearchResult) object;
            return !(each.getId().equals(currentUserId)
                    || each.getId().equals(ControllerConstants.NGRINDER_INITIAL_ADMIN_USERID));
        }
    });

    return toJsonHttpEntity(result);
}

From source file:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogService.java

private Sort createArrivalOrderSort(Filter filter) {
    Sort.Direction arrivalOrderDirection = Sort.Direction.ASC;

    if ("descending".equalsIgnoreCase(filter.getArrivalOrder())) {
        arrivalOrderDirection = Sort.Direction.DESC;
    }//from  ww  w.  ja  va 2  s .com

    return new Sort(arrivalOrderDirection, "arrivalTimeStamp");
}