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 Sort getSort(String sortNamePrefix, Map<String, String[]> sortMap, Pageable defaultPageRequest,
        NativeWebRequest webRequest) {//from w w w  . j av a 2s .c om
    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;
}

From source file:com.contact.ContactController.java

@ResponseBody
@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json")
public ContactGrid listGrid(@RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "rows", required = false) Integer rows,
        @RequestParam(value = "sidx", required = false) String sortBy,
        @RequestParam(value = "sord", required = false) String order) {

    logger.info("Listing contacts for grid with page: {}, rows: {}", page, rows);
    logger.info("Listing contacts for grid with sort: {}, order: {}", sortBy, order);

    // Process order by
    Sort sort = null;//from   w ww .j av  a 2 s. c o m
    String orderBy = sortBy;
    if (orderBy != null && orderBy.equals("birthDateString"))
        orderBy = "birthDate";

    if (orderBy != null && order != null) {
        if (order.equals("desc")) {
            sort = new Sort(Sort.Direction.DESC, orderBy);
        } else
            sort = new Sort(Sort.Direction.ASC, orderBy);
    }

    // Constructs page request for current page
    // Note: page number for Spring Data JPA starts with 0, while jqGrid starts with 1
    PageRequest pageRequest = null;

    if (sort != null) {
        pageRequest = new PageRequest(page - 1, rows, sort);
    } else {
        pageRequest = new PageRequest(page - 1, rows);
    }

    Page<Contact> contactPage = contactService.findAllByPage(pageRequest);

    // Construct the grid data that will return as JSON data
    ContactGrid contactGrid = new ContactGrid();

    contactGrid.setCurrentPage(contactPage.getNumber() + 1);
    contactGrid.setTotalPages(contactPage.getTotalPages());
    contactGrid.setTotalRecords(contactPage.getTotalElements());

    contactGrid.setContactData(Lists.newArrayList(contactPage.iterator()));

    return contactGrid;
}

From source file:org.ng200.openolympus.controller.user.SolutionListController.java

@RequestMapping(value = "/user/solutions", method = RequestMethod.GET)
public String showUserSolutions(@RequestParam(value = "page", defaultValue = "1") final Integer pageNumber,
        final Model model, final Principal principal) {
    final User user = this.userRepository.findByUsername(principal.getName());

    final List<SolutionDTO> lst = new ArrayList<SolutionDTO>();
    final Sort sort = new Sort(Direction.DESC, "timeAdded");
    final PageRequest pageRequest = new PageRequest(pageNumber - 1, 10, sort);
    final List<Solution> solutions = new ArrayList<>();
    if (this.contestService.getRunningContest() != null) {
        this.contestService.getRunningContest().getTasks().forEach((task) -> solutions.addAll(Optional
                .fromNullable(/*from  w  w w .jav a2 s .  co  m*/
                        this.solutionRepository.findByUserAndTaskOrderByTimeAddedDesc(user, task, pageRequest))
                .or(new ArrayList<>())));
    } else {
        solutions.addAll(this.solutionRepository.findByUserOrderByTimeAddedDesc(user, pageRequest));
    }
    for (final Solution solution : solutions) {
        lst.add(new SolutionDTO(MessageFormat.format("/solution?id={0}", Long.toString(solution.getId())),
                solution.getUser().getUsername(), this.solutionService.getSolutionScore(solution),
                this.solutionService.getSolutionMaximumScore(solution), solution.getTask().getName(),
                MessageFormat.format("/task/{0}", Long.toString(solution.getTask().getId())),
                solution.getTimeAdded()));
    }
    SolutionListController.logger.info("Page view: {}", solutions);
    model.addAttribute("solutions", lst);
    model.addAttribute("numberOfPages", Math.max((this.getSolutionCountForUser(user) + 9) / 10, 1));
    model.addAttribute("currentPage", pageNumber);
    model.addAttribute("pagePrefix", "/user/solutions?page=");

    return "tasks/solutions";
}

From source file:com.simphony.managedbeans.PopulationBean.java

private Sort sortByDescription() {
    return new Sort(Sort.Direction.ASC, "Description");
}

From source file:org.ngrinder.user.service.UserService.java

/**
 * Get the users by the given role.//from w  ww.  ja v  a  2s. c  om
 *
 * @param role role
 * @return found user list
 */
public List<User> getAll(Role role) {
    return getAll(role, new Sort(Direction.ASC, "userName"));
}

From source file:fi.vm.sade.eperusteet.ylops.service.dokumentti.impl.DokumenttiServiceImpl.java

@Override
@Transactional/*from w  ww.j  ava  2s  .c  o m*/
public Long getDokumenttiId(Long opsId, Kieli kieli) {
    Sort sort = new Sort(Sort.Direction.DESC, "valmistumisaika");
    List<Dokumentti> documents = dokumenttiRepository.findByOpsIdAndKieliAndTila(opsId, kieli,
            DokumenttiTila.VALMIS, sort);

    if (!documents.isEmpty()) {
        return documents.get(0).getId();
    } else {
        return null;
    }
}

From source file:com.pkrete.locationservice.endpoint.solr.service.impl.LocationIndexServiceImpl.java

/**
 * Returns a Sort object that sorts the results in ascending order by call
 * number./*from  w w  w. j av  a 2s .  c om*/
 *
 * @return Sort object that sorts the results in ascending order by call
 * number
 */
private Sort sortByCallNumberAsc() {
    return new Sort(Sort.Direction.ASC, RepositoryConstants.FIELD_CALL_NUMBER);
}

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

@Override
public AuthorizationResponse handleAuthorizationResponse(HttpServletRequest servletRequest)
        throws ShimException {

    String state = servletRequest.getParameter("state");
    String code = servletRequest.getParameter("code");

    AuthorizationRequestParameters authorizationRequestParameters = authorizationRequestParametersRepo
            .findByStateKey(state);//from w w  w .j  av a2s .c o  m

    if (authorizationRequestParameters == null) {
        throw new IllegalStateException(
                "Could not find corresponding authorization " + "request parameters, cannot continue.");
    }

    OAuth2RestOperations restTemplate = restTemplate(state, code);
    try {
        /**
         * Create a persistable access parameters entity so that
         * spring oauth2's client token services can relate
         * the serialized OAuth2AccessToken to it.
         */
        AccessParameters accessParameters = new AccessParameters();
        accessParameters.setUsername(authorizationRequestParameters.getUsername());
        accessParameters.setShimKey(getShimKey());
        accessParameters.setStateKey(state);
        accessParametersRepo.save(accessParameters);

        trigger(restTemplate, getTriggerDataRequest());

        /**
         * By this line we will have an approved access token or
         * not, if we do not then we delete the access parameters entity.
         */
        if (restTemplate.getAccessToken() == null) {
            accessParametersRepo.delete(accessParameters);
            return AuthorizationResponse.error("Did not receive approval");
        } else {
            accessParameters = accessParametersRepo.findByUsernameAndShimKey(
                    authorizationRequestParameters.getUsername(), getShimKey(),
                    new Sort(Sort.Direction.DESC, "dateCreated"));
        }
        return AuthorizationResponse.authorized(accessParameters);
    } catch (OAuth2Exception e) {
        //TODO: OAuth2Exception may include other stuff
        System.out.println("Problem trying out the token!");
        e.printStackTrace();
        return AuthorizationResponse.error(e.getMessage());
    }
}

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

@Test
public void testCustomNamePrefixPageableAndSort() throws Exception {
    int pn = 1;/*from  w w w. j a  va  2 s.c om*/
    int pageSize = 10;
    request.setParameter("foo_page.pn", String.valueOf(pn));
    request.setParameter("foo_page.size", String.valueOf(pageSize));
    request.setParameter("foo_sort2.id", "desc");
    request.setParameter("foo_sort1.baseInfo.realname", "asc");

    MethodParameter parameter = new MethodParameter(customNamePrefixPageableAndSort, 0);
    NativeWebRequest webRequest = new ServletWebRequest(request);
    Pageable pageable = (Pageable) new PageableMethodArgumentResolver().resolveArgument(parameter, null,
            webRequest, null);

    //-10
    assertEquals(pn - 1, pageable.getPageNumber());
    assertEquals(pageSize, pageable.getPageSize());
    Sort expectedSort = new Sort(Sort.Direction.ASC, "baseInfo.realname")
            .and(new Sort(Sort.Direction.DESC, "id"));
    assertEquals(expectedSort, pageable.getSort());
}

From source file:com.pkrete.locationservice.endpoint.solr.service.impl.LocationIndexServiceImpl.java

/**
 * Returns a Sort object that sorts the results in descending order by call
 * number./*w  ww  .ja v a  2 s  .  com*/
 *
 * @return Sort object that sorts the results in descending order by call
 * number
 */
private Sort sortByCallNumberDesc() {
    return new Sort(Sort.Direction.DESC, RepositoryConstants.FIELD_CALL_NUMBER);
}