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

The following examples show how to use org.springframework.data.domain.Sort.Direction. These examples are extracted from open source projects. 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 Project: hermes   Source File: CmsController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping("help-center/{cid}")
public String helpCenterArticleCategory(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size, @PathVariable String cid, Model model) {
	List<Order> orders = new ArrayList<Order>();
	orders.add(new Order(Direction.ASC, "order"));
	orders.add(new Order(Direction.DESC, "updateTime"));
	Pageable pageable = new PageRequest(page, size, new Sort(orders));
	Page<Article> dataBox = articleService.find(cid, pageable);
	if (dataBox.getContent().size() == 1) {
		return "redirect:/help-center/" + cid + "/" + dataBox.getContent().get(0).getId();
	} else {
		List<ArticleCategory> articleCategorys = articleCategoryRepository.findByLevel("二级");
		for (ArticleCategory a : articleCategorys) {
			if (OTHER_KIND_LEVEL.equals(a.getCode())) {
				articleCategorys.remove(a);
				break;
			}
		}
		model.addAttribute("nav",HomeNav.HELP );
		model.addAttribute("second", articleCategorys);
		model.addAttribute("sel", articleCategoryRepository.findOne(cid));
		model.addAttribute("aeli", dataBox);
		return "cms/template_li";
	}
}
 
Example 2
Source Project: youkefu   Source File: OrganController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping("/auth")
@Menu(type = "admin" , subtype = "organ")
public ModelAndView auth(ModelMap map ,HttpServletRequest request , @Valid String id) {
	
	SysDic sysDic = sysDicRes.findByCode(UKDataContext.UKEFU_SYSTEM_AUTH_DIC) ;
	if(sysDic!=null){ 
		map.addAttribute("resourceList", sysDicRes.findByDicid(sysDic.getId(),new PageRequest(0,1000, Direction.ASC , "createtime")).getContent()) ; 
	 }
	
	map.addAttribute("sysDic", sysDic) ;
	Organ organData = organRepository.findByIdAndOrgi(id, super.getOrgiByTenantshare(request)) ;
	map.addAttribute("organData", organData) ;
	map.addAttribute("roleList", roleRepository.findByOrgiAndOrgid(super.getOrgiByTenantshare(request),super.getOrgid(request))) ;
	
	map.addAttribute("organRoleList", organRoleRes.findByOrgiAndOrgan(super.getOrgiByTenantshare(request), organData)) ;
	
    return request(super.createRequestPageTempletResponse("/admin/organ/auth"));
}
 
Example 3
@GetMapping()
@ApiOperation(nickname = "get-all-posts", value = "Get all posts")
@ApiResponses(
        value = {
            @ApiResponse(code = 200, message = "return all posts by page")
        }
)
public ResponseEntity<Page<PostDetails>> getAllPosts(
        @RequestParam(value = "q", required = false) String keyword, //
        @RequestParam(value = "status", required = false) Post.Status status, //
        @PageableDefault(page = 0, size = 10, sort = "createdDate", direction = Direction.DESC) Pageable page) {

    log.debug("get all posts of [email protected]" + keyword + ", status @" + status + ", [email protected]" + page);

    Page<PostDetails> posts = blogService.searchPostsByCriteria(keyword, status, page);

    log.debug("get posts size @" + posts.getTotalElements());

    return new ResponseEntity<>(posts, HttpStatus.OK);
}
 
Example 4
Source Project: spring4-sandbox   Source File: TaskController.java    License: Apache License 2.0 6 votes vote down vote up
private List<TaskDetails> findByStatus(Status status) {
	Sort sort = new Sort(Direction.DESC, "lastModifiedDate");

	List<TaskDetails> detailsList = new ArrayList<>();
	List<Task> tasks = taskRepository.findByStatus(status, sort);

	for (Task task : tasks) {
		TaskDetails details = new TaskDetails();
		details.setId(task.getId());
		details.setName(task.getName());
		details.setDescription(task.getDescription());
		details.setCreatedDate(task.getCreatedDate());
		details.setLastModifiedDate(task.getLastModifiedDate());
		detailsList.add(details);
	}
	return detailsList;
}
 
Example 5
Source Project: springlets   Source File: SortParametersParserTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void orderLoadedFromPosition() {
  // Prepare: ordering first with property3 and then with property1
  parser = createParser(
      new String[] {"order[0][column]", "order[1][column]", "order[0][dir]", "order[1][dir]",
          "columns[0][data]", "columns[1][data]", "columns[2][data]", "columns[3][data]"},
      new String[] {"3", "1", "asc", "desc", "property0", "property1", "property2", "property3"});

  // Exercise
  Order order0 = parser.getOrderInPosition(0);
  Order order1 = parser.getOrderInPosition(1);

  // Verify
  assertThat(order0.getProperty()).as("Nombre de propiedad ordenada correcta")
      .isEqualTo("property3");
  assertThat(order0.getDirection()).as("Dirección de ordenación de propiedad correcta")
      .isEqualTo(Direction.ASC);
  assertThat(order1.getProperty()).as("Nombre de propiedad ordenada correcta")
      .isEqualTo("property1");
  assertThat(order1.getDirection()).as("Dirección de ordenación de propiedad correcta")
      .isEqualTo(Direction.DESC);
}
 
Example 6
@Override
public Map<String, Integer> getMapDependencyAndNumOfProjectThatUseIt() {
	Map<String, Integer> result = new HashMap<>();
	Aggregation aggregation = newAggregation(
			unwind("dependencies"),
			group("dependencies").count().as("count"),
			project("count").and("dependencies").previousOperation(),
			sort(Direction.DESC,"count")
		);
	AggregationResults<DependencyCount> results = mongoOperations.aggregate(aggregation, "artifact", DependencyCount.class);
	List<DependencyCount> intermediateResult = results.getMappedResults();
	for (DependencyCount dependencyCount : intermediateResult) {
		result.put(dependencyCount.getDependencies(), dependencyCount.getCount());
	}
	return result;
}
 
Example 7
Source Project: ElementVueSpringbootCodeTemplate   Source File: PageReq.java    License: Apache License 2.0 6 votes vote down vote up
public Pageable toPageable() {
	// pageable里面是从第0页开始的。
	Pageable pageable = null;

	if (StringUtils.isEmpty(sortfield)) {
		pageable = new PageRequest(page - 1, pagesize);
	}
	else {
		pageable = new PageRequest(page - 1, pagesize,
				sort.toLowerCase().startsWith("desc") ? Direction.DESC
						: Direction.ASC,
				sortfield);
	}

	return pageable;
}
 
Example 8
public Map<Integer, CheckResultDto> getLastResults(List<Check> checks) {
	Map<Integer, CheckResultDto> map = new HashMap<>();
	for (Check check : checks) {
		// skip inactive checks
		if (!check.isActive()) {
			continue;
		}
		List<CheckResult> checkResultList = checkResultRepository.findByCheck(check, PageRequest.of(0, 1, Sort.by(Direction.DESC, "id")));
		CheckResultDto checkResultDto = new CheckResultDto();
		if (checkResultList.isEmpty()) {
			// first time, no results yet
		} else {
			checkResultDto = transformCheckToDto(checkResultList.get(0));
		}
		map.put(check.getId(), checkResultDto);
	}
	return map;
}
 
Example 9
Source Project: tutorials   Source File: ZipsAggregationLiveTest.java    License: MIT License 6 votes vote down vote up
@Test
public void whenMaxTXAndMinDC_theSuccess() {

    GroupOperation sumZips = group("state").count().as("zipCount");
    SortOperation sortByCount = sort(Direction.ASC, "zipCount");
    GroupOperation groupFirstAndLast = group().first("_id").as("minZipState")
      .first("zipCount").as("minZipCount").last("_id").as("maxZipState")
      .last("zipCount").as("maxZipCount");

    Aggregation aggregation = newAggregation(sumZips, sortByCount, groupFirstAndLast);

    AggregationResults<Document> result = mongoTemplate.aggregate(aggregation, "zips", Document.class);
    Document document = result.getUniqueMappedResult();

    assertEquals("DC", document.get("minZipState"));
    assertEquals(24, document.get("minZipCount"));
    assertEquals("TX", document.get("maxZipState"));
    assertEquals(1671, document.get("maxZipCount"));
}
 
Example 10
/**
 * (non-Javadoc)
 *
 * @see com.capitalone.dashboard.executive.service.PortfolioResponseService#findByBusinessUnit(String)
 * @param businessUnit
 * @return
 */
@Override
public List<PortfolioResponse> findByBusinessUnit(String businessUnit) {
	List<ExecutiveSummaryList> executiveSummaryList = executiveSummaryListRepository
			.findByBusinessUnits(businessUnit);
	List<String> eids = new ArrayList<>();
	if (executiveSummaryList != null && !executiveSummaryList.isEmpty()) {
		for (ExecutiveSummaryList executiveSummary : executiveSummaryList) {
			eids.add(executiveSummary.getEid());
		}
		if (!eids.isEmpty()) {
			Sort sort = new Sort(new Order(Direction.ASC, "order"),
					new Order(Direction.ASC, "executive.firstName"));
			return portfolioResponseRepository.getByEidsWithSort(eids, sort);
		}
	}

	return new ArrayList();
}
 
Example 11
/**
 * (non-Javadoc)
 *
 * @see com.capitalone.dashboard.executive.service.PortfolioResponseService#findByExecutivesHierarchy(String,
 *      String)
 * @param businessUnit
 * @return
 */
@Override
public List<PortfolioResponse> findByExecutivesHierarchy(String eid, String businessUnit) {

	List<String> reportingEids = new ArrayList<>();
	ExecutiveHierarchy executivesHierarchy = executiveHierarchyRepository.findByEid(eid);
	if (executivesHierarchy != null) {
		Map<String, List<String>> reportees = executivesHierarchy.getReportees();
		if (reportees != null && !reportees.isEmpty()) {
			if (!ALL.equalsIgnoreCase(businessUnit)) {
				reportingEids.addAll(reportees.get(businessUnit));
			} else {
				for (Map.Entry<String, List<String>> entry : reportees.entrySet()) {
					reportingEids.addAll(entry.getValue());
				}
			}
		}
	}
	if (!reportingEids.isEmpty()) {
		Sort sort = new Sort(new Order(Direction.ASC, "order"), new Order(Direction.ASC, "executive.firstName"));
		return portfolioResponseRepository.getByEidsWithSort(reportingEids, sort);
	}
	return new ArrayList();
}
 
Example 12
Source Project: plumdo-work   Source File: AbstractPaginateList.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private void setQueryOrder(Sort sort, Query query, Map<String, QueryProperty> properties) {
    if (sort == null || properties.isEmpty()) {
        return;
    }
    for (Order order : sort) {
        QueryProperty qp = properties.get(order.getProperty());
        if (qp == null) {
            throw new FlowableIllegalArgumentException("Value for param 'sort' is not valid, '" + sort + "' is not a valid property");
        }
        query.orderBy(qp);
        if (order.getDirection() == Direction.ASC) {
            query.asc();
        } else {
            query.desc();
        }
    }
}
 
Example 13
Source Project: hermes   Source File: UserRoleServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 角色列表
 */
@Override
public Page<Role> queryRoleListByCondition(final UserRoleVo userRoleVo, String page, String size) throws Exception {
	 Pageable pageable = new PageRequest(Integer.valueOf(Strings.empty(page, "0")), Integer.valueOf(Strings.empty(size, "10")), new Sort(Direction.DESC,  "createTime"));
	 return roleRepository.findAll(new Specification<Role>() {
		@Override
		public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
			List<Predicate> list = new ArrayList<Predicate>();
			if (StringUtils.isNotEmpty(userRoleVo.getRoleName())) {
				list.add(cb.like(root.<String>get("name"), "%"+userRoleVo.getRoleName().trim()+"%"));
			}
			User currentUser = userService.loadById(App.current().getUser().getId());
			//超级管理员获取所有角色,否则获取自己创建的角色
			if(!HermesConstants.PLAT_MANAGER.equals(currentUser.getAccount())){
				list.add(cb.equal(root.<String>get("creator"),  currentUser.getId()));
			}
			list.add(cb.equal(root.<String>get("type"),  Role.Type.SYS_AUTH));
			list.add(cb.equal(root.<String>get("status"), Role.Status.ENABLED));
			return cb.and(list.toArray(new Predicate[list.size()]));
		}
	},pageable);
}
 
Example 14
Source Project: hawkbit   Source File: ActionStatusBeanQuery.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parametric Constructor.
 *
 * @param definition
 *            QueryDefinition contains the query properties.
 * @param queryConfig
 *            Implementation specific configuration.
 * @param sortPropertyIds
 *            The properties participating in sort.
 * @param sortStates
 *            The ascending or descending state of sort properties.
 */
public ActionStatusBeanQuery(final QueryDefinition definition, final Map<String, Object> queryConfig,
        final Object[] sortPropertyIds, final boolean[] sortStates) {
    super(definition, queryConfig, sortPropertyIds, sortStates);

    if (isNotNullOrEmpty(queryConfig)) {
        currentSelectedActionId = (Long) queryConfig.get(SPUIDefinitions.ACTIONSTATES_BY_ACTION);
    }

    if (sortStates != null && sortStates.length > 0) {
        // Initialize sort
        sort = new Sort(sortStates[0] ? Direction.ASC : Direction.DESC, (String) sortPropertyIds[0]);
        // Add sort
        for (int distId = 1; distId < sortPropertyIds.length; distId++) {
            sort.and(new Sort(sortStates[distId] ? Direction.ASC : Direction.DESC,
                    (String) sortPropertyIds[distId]));
        }
    }
}
 
Example 15
Source Project: hermes   Source File: ApiconfigServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Page<ApiConfig> queryByCondition(final ApiConfigVo apiConfigVo, String page, String size) throws Exception {
	 Pageable pageable = new PageRequest(Integer.valueOf(Strings.empty(page, "0")), Integer.valueOf(Strings.empty(size, "10")), new Sort(Direction.DESC,  "createTime"));
	 return  apiConfigRepository.findAll(new Specification<ApiConfig>() {
		@Override
		public Predicate toPredicate(Root<ApiConfig> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
			List<Predicate> list = new ArrayList<Predicate>();
			if (StringUtils.isNotEmpty(apiConfigVo.getPlatCode())) {
				list.add(cb.like(root.<String>get("platCode"), "%"+apiConfigVo.getPlatCode().trim()+"%"));
			}
			if (StringUtils.isNotEmpty(apiConfigVo.getClientStoreName())) {
				list.add(cb.like(root.<String>get("clientStoreName"), "%"+apiConfigVo.getClientStoreName().trim()+"%"));
			}
			if(StringUtils.isNotEmpty(apiConfigVo.getTruestStoreName())){
				list.add(cb.like(root.<String>get("truestStoreName"), "%"+apiConfigVo.getTruestStoreName().trim()+"%"));
			}
			return cb.and(list.toArray(new Predicate[list.size()]));
		}
	},pageable);
}
 
Example 16
Source Project: spring4-sandbox   Source File: TaskController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "", method = RequestMethod.GET)
public ResponseEntity<List<TaskDetails>> allTask() {

	List<TaskDetails> detailsList = new ArrayList<>();

	Sort sort = new Sort(Direction.DESC, "lastModifiedDate");
	List<Task> tasks = taskRepository.findAll(sort);

	for (Task task : tasks) {
		TaskDetails details = new TaskDetails();
		details.setName(task.getName());
		details.setDescription(task.getDescription());
		details.setCreatedDate(task.getCreatedDate());
		details.setLastModifiedDate(task.getLastModifiedDate());
		detailsList.add(details);
	}

	return new ResponseEntity<>(detailsList, HttpStatus.OK);
}
 
Example 17
Source Project: danyuan-application   Source File: SysDicNameService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 方法名: findkeyList
 * 功 能: TODO(这里用一句话描述这个方法的作用)
 * 参 数: @param code
 * 参 数: @return
 * 返 回: boolean
 * 作 者 : Administrator
 * @throws
 */
public List<SysDicKeyList> findkeyList(SysDicName info) {
	Example<SysDicName> example = Example.of(info);
	Optional<SysDicName> reinfo = sysDicNameDao.findOne(example);
	if (reinfo.isPresent()) {
		info = reinfo.get();
		SysDicKeyList key = new SysDicKeyList();
		key.setNameUuid(info.getUuid());

		Example<SysDicKeyList> ke = Example.of(key);
		Order[] order = { new Order(Direction.ASC, "keyOrder"), new Order(Direction.ASC, "createTime") };
		Sort sort = Sort.by(order);
		return sysDicKeyListDao.findAll(ke, sort);
	} else {
		return null;
	}
}
 
Example 18
Source Project: hermes   Source File: DictionaryTypeServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Page<DictionaryType> queryByCondition(final DictionaryType dictionaryType, String page, String size) throws Exception {
	 Pageable pageable = new PageRequest(Integer.valueOf(Strings.empty(page, "0")), Integer.valueOf(Strings.empty(size, "10")), new Sort(Direction.DESC,  "createTime"));
	 return  dictionaryTypeRepository.findAll(new Specification<DictionaryType>() {
		@Override
		public Predicate toPredicate(Root<DictionaryType> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
			List<Predicate> list = new ArrayList<Predicate>();
			if (StringUtils.isNotEmpty(dictionaryType.getCode())) {
				list.add(cb.like(root.<String>get("code"), "%"+dictionaryType.getCode().trim()+"%"));
			}
			if (StringUtils.isNotEmpty(dictionaryType.getName())) {
				list.add(cb.like(root.<String>get("name"), "%"+dictionaryType.getName().trim()+"%"));
			}
			return cb.and(list.toArray(new Predicate[list.size()]));
		}
	},pageable);
}
 
Example 19
Source Project: redisson   Source File: RedissonReactiveZSetCommands.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Flux<NumericResponse<ZRankCommand, Long>> zRank(Publisher<ZRankCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKey(), "Key must not be null!");
        Assert.notNull(command.getValue(), "Member must not be null!");

        byte[] keyBuf = toByteArray(command.getKey());
        byte[] valueBuf = toByteArray(command.getValue());
        RedisCommand<Long> cmd = RedisCommands.ZRANK;
        if (command.getDirection() == Direction.DESC) {
            cmd = RedisCommands.ZREVRANK;
        }
        Mono<Long> m = read(keyBuf, DoubleCodec.INSTANCE, cmd, keyBuf, valueBuf);
        return m.map(v -> new NumericResponse<>(command, v));
    });
}
 
Example 20
Source Project: thymeleaf-spring-data-dialect   Source File: PageUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an url to sort data by fieldName
 * 
 * @param context execution context
 * @param fieldName field name to sort
 * @param forcedDir optional, if specified then only this sort direction will be allowed
 * @return sort URL
 */
public static String createSortUrl(final ITemplateContext context, final String fieldName, final Direction forcedDir) {
    // Params can be prefixed to manage multiple pagination on the same page
    final String prefix = getParamPrefix(context);
    final Collection<String> excludedParams = Arrays
            .asList(new String[] { prefix.concat(SORT), prefix.concat(PAGE) });
    final String baseUrl = buildBaseUrl(context, excludedParams);

    final StringBuilder sortParam = new StringBuilder();
    final Page<?> page = findPage(context);
    final Sort sort = page.getSort();
    final boolean hasPreviousOrder = sort != null && sort.getOrderFor(fieldName) != null;
    if (forcedDir != null) {
        sortParam.append(fieldName).append(COMMA).append(forcedDir.toString().toLowerCase());
    } else if (hasPreviousOrder) {
        // Sort parameters exists for this field, modify direction
        Order previousOrder = sort.getOrderFor(fieldName);
        Direction dir = previousOrder.isAscending() ? Direction.DESC : Direction.ASC;
        sortParam.append(fieldName).append(COMMA).append(dir.toString().toLowerCase());
    } else {
        sortParam.append(fieldName);
    }

    return buildUrl(baseUrl, context).append(SORT).append(EQ).append(sortParam).toString();
}
 
Example 21
@GetMapping()
//    @ApiOperation(nickname = "get-all-posts", value = "Get all posts")
//    @ApiResponses(
//        value = {
//            @ApiResponse(code = 200, message = "return all posts by page")
//        }
//    )
    @JsonView(View.Summary.class)
    public ResponseEntity<Page<Post>> getAllPosts(
        @RequestParam(value = "q", required = false) String keyword, //
        @RequestParam(value = "status", required = false) Post.Status status, //
        @PageableDefault(page = 0, size = 10, sort = "createdDate", direction = Direction.DESC) Pageable page) {

        log.debug("get all posts of [email protected]" + keyword + ", status @" + status + ", [email protected]" + page);

        Page<Post> posts = this.postRepository.findAll(PostSpecifications.filterByKeywordAndStatus(keyword, status), page);

        return ok(posts);
    }
 
Example 22
Source Project: youkefu   Source File: RoleController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/auth")
@Menu(type = "admin" , subtype = "role")
public ModelAndView auth(ModelMap map , HttpServletRequest request , @Valid String id) {
	SysDic sysDic = sysDicRes.findByCode(UKDataContext.UKEFU_SYSTEM_AUTH_DIC) ;
	if(sysDic!=null){
		map.addAttribute("resourceList", sysDicRes.findByDicid(sysDic.getId(),new PageRequest(0,1000, Direction.ASC , "createtime")).getContent()) ;
	}
	map.addAttribute("sysDic", sysDic) ;
	Role role = roleRepository.findByIdAndOrgi(id, super.getOrgiByTenantshare(request)) ;
	map.addAttribute("role", role) ;
	map.addAttribute("roleAuthList", roleAuthRes.findByRoleidAndOrgi(role.getId(), super.getOrgiByTenantshare(request))) ;
    return request(super.createRequestPageTempletResponse("/admin/role/auth"));
}
 
Example 23
Source Project: youkefu   Source File: OrganController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/index")
@Menu(type = "admin" , subtype = "organ")
public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid String organ, @Valid String msg) {
	List<Organ> organList = organRepository.findByOrgiAndOrgid(super.getOrgiByTenantshare(request),super.getOrgid(request)) ;
	map.addAttribute("organList", organList);
	if(organList.size() > 0){
		Organ organData = null ;
		if(!StringUtils.isBlank(organ) && !"null".equals(organ)){
			for(Organ data : organList){
				if(data.getId().equals(organ)){
					map.addAttribute("organData", data);
					organData = data;
				}
			}
		}else{
			map.addAttribute("organData", organData = organList.get(0));
		}
		if(organData!=null){
			map.addAttribute("userList", userRepository.findByDatastatusAndOrganAndOrgi(false,organData.getId() ,super.getOrgi(request), new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC, new String[] { "createtime" })));
		}
	}
	map.addAttribute("areaList", areaRepository.findByOrgi(super.getOrgiByTenantshare(request))) ;
	map.addAttribute("roleList", roleRepository.findByOrgiAndOrgid(super.getOrgiByTenantshare(request),super.getOrgid(request)));
    map.put("msg", msg);
    map.put("pagetemp", request.getParameter("pagetemp"));
	return request(super.createAdminTempletResponse("/admin/organ/index"));
}
 
Example 24
Source Project: youkefu   Source File: SysDicController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/dicitem")
  @Menu(type = "admin" , subtype = "sysdic")
  public ModelAndView dicitem(ModelMap map , HttpServletRequest request , @Valid String id , @Valid String msg) {
  	if (!StringUtils.isBlank(msg)) {
  		map.addAttribute("msg", msg) ;
}
  	map.addAttribute("sysDic", sysDicRes.findById(id)) ;
  	map.addAttribute("sysDicList", sysDicRes.findByParentid( id , new PageRequest(super.getP(request), super.getPs(request) , Direction.DESC , "createtime")));
      return request(super.createAdminTempletResponse("/admin/system/sysdic/dicitem"));
  }
 
Example 25
@RequestMapping(value="/{market}", method=GET)
@ApiOperation(value = "Get one markets", notes = "Return a market")
public MarketResource get(
		@ApiParam(value="Market code: EUROPE") @PathVariable(value="market") MarketId marketId,
		@ApiIgnore @PageableDefault(size=10, page=0, sort={"name"}, direction=Direction.ASC) Pageable pageable){
	return assembler.toResource(marketService.get(marketId));
}
 
Example 26
@Override
public Sort deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    final ArrayNode node = jsonParser.getCodec().readTree(jsonParser);
    final Order[] orders = new Order[node.size()];

    int i = 0;
    for (JsonNode jsonNode : node) {
        orders[i] = new Order(Direction.valueOf(jsonNode.get("direction").asText()), jsonNode.get("property").asText());
        i++;
    }

    return new Sort(orders);
}
 
Example 27
Source Project: hawkbit   Source File: PagingUtility.java    License: Eclipse Public License 1.0 5 votes vote down vote up
static Sort sanitizeActionSortParam(final String sortParam) {
    if (sortParam == null) {
        // default sort is DESC in case of action to match behavior
        // of management UI (last entry on top)
        return new Sort(Direction.DESC, ActionFields.ID.getFieldName());
    }
    return new Sort(SortUtility.parse(ActionFields.class, sortParam));
}
 
Example 28
Source Project: youkefu   Source File: SessionTypeController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/sessionitem")
@Menu(type = "apps" , subtype = "sessiontype")
public ModelAndView dicitem(ModelMap map , HttpServletRequest request , @Valid String id, @Valid String typeCode) {
	map.addAttribute("sessiontype", sessionTypeRes.findById(id)) ;
	//map.addAttribute("sysDicList", sysDicRes.findByParentid( id , new PageRequest(super.getP(request), super.getPs(request) , Direction.DESC , "createtime")));
	map.addAttribute("sessionTypeList", sessionTypeRes.findByOrgiAndParentid( super.getOrgi(request),id , new PageRequest(super.getP(request), super.getPs(request) , Direction.DESC , "createtime")));
	map.addAttribute("typeCode", typeCode);
    return request(super.createAppsTempletResponse("/apps/setting/sessiontype/sessionitem"));
}
 
Example 29
Source Project: tutorials   Source File: ZipsAggregationLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenStatesHavePopGrtrThan10MillionAndSorted_thenSuccess() {

    GroupOperation groupByStateAndSumPop = group("state").sum("pop").as("statePop");
    MatchOperation filterStates = match(new Criteria("statePop").gt(10000000));
    SortOperation sortByPopDesc = sort(new Sort(Direction.DESC, "statePop"));

    Aggregation aggregation = newAggregation(groupByStateAndSumPop, filterStates, sortByPopDesc);
    AggregationResults<StatePopulation> result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class);

    /*
     * Assert that all states have population
     * greater than 10000000
     */
    result.forEach(statePop -> {
        assertTrue(statePop.getStatePop() > 10000000);
    });

    /*
     * Assert that states fetched are in sorted by
     * decreasing population
     */
    List<StatePopulation> actualList = StreamSupport.stream(result.spliterator(), false)
      .collect(Collectors.toList());

    List<StatePopulation> expectedList = new ArrayList<>(actualList);
    Collections.sort(expectedList, (sp1, sp2) -> sp2.getStatePop() - sp1.getStatePop());

    assertEquals(expectedList, actualList);

}
 
Example 30
Source Project: hermes   Source File: ContentServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 内容管理查询结果
 * 
 * @author lishunfeng
 */
@Override
public Page<Article> find(final String levelOne, final String levelTwo, final String levelThree, final String inputName, int page, int size) {
	// 初始化
	List<Order> orders = new ArrayList<Order>();
	orders.add(new Order(Direction.ASC, "order"));
	orders.add(new Order(Direction.DESC, "updateTime"));
	Pageable pageable = new PageRequest(page, size, new Sort(orders));
	Page<Article> articleList = articleRepository.findAll(new Specification<Article>() {
		@Override
		public Predicate toPredicate(Root<Article> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
			List<Predicate> p = new ArrayList<Predicate>();
			if (StringUtils.isNotEmpty(levelOne) && StringUtils.isEmpty(levelTwo)) {
				p.add(cb.equal(root.<ArticleCategory> get("category").<String> get("id"), levelOne));
			}
			if (StringUtils.isNotEmpty(levelTwo) && StringUtils.isEmpty(levelThree)) {
				p.add(cb.equal(root.<ArticleCategory> get("category").<String> get("id"), levelTwo));
			}
			if (StringUtils.isNotEmpty(levelThree)) {
				p.add(cb.equal(root.<ArticleCategory> get("category").<String> get("id"), levelThree));
			}
			if (StringUtils.isNotEmpty(inputName)) {
				p.add(cb.like(root.<String> get("articleTitle"), "%" + inputName + "%"));
			}
			query.where(cb.and(p.toArray(new Predicate[p.size()])));
			return query.getRestriction();
		}
	}, pageable);
	return articleList;
}