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

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: DependencySimilarityCalculator.java    From scava with Eclipse Public License 2.0 7 votes vote down vote up
@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 #2
Source File: PageUtils.java    From thymeleaf-spring-data-dialect with 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 #3
Source File: OrganController.java    From youkefu with 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 #4
Source File: PostController.java    From angularjs-springmvc-sample-boot with Apache License 2.0 6 votes vote down vote up
@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 q@" + keyword + ", status @" + status + ", page@" + page);

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

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

    return new ResponseEntity<>(posts, HttpStatus.OK);
}
 
Example #5
Source File: TaskController.java    From spring4-sandbox with 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 #6
Source File: SortParametersParserTest.java    From springlets with 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 #7
Source File: PageReq.java    From ElementVueSpringbootCodeTemplate with 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
Source File: CheckResultService.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 File: ZipsAggregationLiveTest.java    From tutorials with 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
Source File: PortfolioResponseServiceImpl.java    From ExecDashboard with Apache License 2.0 6 votes vote down vote up
/**
 * (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
Source File: PortfolioResponseServiceImpl.java    From ExecDashboard with Apache License 2.0 6 votes vote down vote up
/**
 * (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 File: UserRoleServiceImpl.java    From hermes with 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 #13
Source File: CmsController.java    From hermes with 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 #14
Source File: RedissonReactiveZSetCommands.java    From redisson with 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 #15
Source File: DictionaryTypeServiceImpl.java    From hermes with 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 #16
Source File: SysDicNameService.java    From danyuan-application with 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 #17
Source File: TaskController.java    From spring4-sandbox with 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 #18
Source File: ApiconfigServiceImpl.java    From hermes with 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 #19
Source File: ActionStatusBeanQuery.java    From hawkbit with 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 #20
Source File: PostController.java    From spring-microservice-sample with GNU General Public License v3.0 6 votes vote down vote up
@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 q@" + keyword + ", status @" + status + ", page@" + page);

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

        return ok(posts);
    }
 
Example #21
Source File: AbstractPaginateList.java    From plumdo-work with 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 #22
Source File: TargetResourceDocumentationTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private Action generateActionForTarget(final String knownControllerId, final boolean inSync,
        final boolean timeforced, final String maintenanceWindowSchedule, final String maintenanceWindowDuration,
        final String maintenanceWindowTimeZone) throws Exception {
    final PageRequest pageRequest = PageRequest.of(0, 1, Direction.ASC, ActionStatusFields.ID.getFieldName());

    createTargetByGivenNameWithAttributes(knownControllerId, inSync, timeforced, createDistributionSet(),
            maintenanceWindowSchedule, maintenanceWindowDuration, maintenanceWindowTimeZone);

    final List<Action> actions = deploymentManagement.findActionsAll(pageRequest).getContent();

    assertThat(actions).hasSize(1);
    return actions.get(0);
}
 
Example #23
Source File: UserPagingAndSortingRepositoryTest.java    From springbootexamples with Apache License 2.0 5 votes vote down vote up
/**
 * 单个字段排序
 */
@Test
public void findAllBySort() {
	Iterable<User> findAll = userPagingAndSortingRepository.findAll(new Sort(Sort.Direction.ASC,"age"));
	findAll.forEach((user)->{
		 System.out.println(user.getName()+"#"+user.getAge());
	 });
}
 
Example #24
Source File: MongoAccessor.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> K minimumIdentity(Class<T> clazz, K from, K to) {
	MongoMetadata metadata = metadatas.get(clazz);
	Query query = Query.query(Criteria.where(MongoMetadata.mongoId).gte(from).lte(to));
	query.fields().include(MongoMetadata.mongoId);
	query.with(Sort.by(Direction.ASC, MongoMetadata.mongoId));
	T instance = template.findOne(query, clazz, metadata.getOrmName());
	return instance.getId();
}
 
Example #25
Source File: MongoAccessor.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public <K extends Comparable, T extends IdentityObject<K>> K maximumIdentity(Class<T> clazz, K from, K to) {
	MongoMetadata metadata = metadatas.get(clazz);
	Query query = Query.query(Criteria.where(MongoMetadata.mongoId).gte(from).lte(to));
	query.fields().include(MongoMetadata.mongoId);
	query.with(Sort.by(Direction.DESC, MongoMetadata.mongoId));
	T instance = template.findOne(query, clazz, metadata.getOrmName());
	return instance.getId();
}
 
Example #26
Source File: PagingUtility.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
static Sort sanitizeSoftwareModuleMetadataSortParam(final String sortParam) {
    if (sortParam == null) {
        // default
        return new Sort(Direction.ASC, SoftwareModuleMetadataFields.KEY.getFieldName());
    }
    return new Sort(SortUtility.parse(SoftwareModuleMetadataFields.class, sortParam));
}
 
Example #27
Source File: MarketController.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
@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 #28
Source File: SysDicController.java    From youkefu with 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 #29
Source File: AgentIndexInitializer.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void createIndexOnName() {
    mongoOps.indexOps(Agent.class)
        .ensureIndex(new Index().on("name", Direction.ASC).unique());
}
 
Example #30
Source File: RolloutManagementTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Verifying that a finish condition of a group is hit the next group of the rollout is also started")
public void checkRunningRolloutsDoesNotStartNextGroupIfFinishConditionIsNotHit() {
    final int amountTargetsForRollout = 10;
    final int amountOtherTargets = 15;
    final int amountGroups = 5;
    final String successCondition = "50";
    final String errorCondition = "80";
    final Rollout createdRollout = createAndStartRollout(amountTargetsForRollout, amountOtherTargets, amountGroups,
            successCondition, errorCondition);

    final List<Action> runningActions = findActionsByRolloutAndStatus(createdRollout, Status.RUNNING);
    // finish one action should be sufficient due the finish condition is at
    // 50%
    final JpaAction action = (JpaAction) runningActions.get(0);
    controllerManagement
            .addUpdateActionStatus(entityFactory.actionStatus().create(action.getId()).status(Status.FINISHED));

    // check running rollouts again, now the finish condition should be hit
    // and should start the next group
    rolloutManagement.handleRollouts();

    // verify that now the first and the second group are in running state
    final List<RolloutGroup> runningRolloutGroups = rolloutGroupManagement
            .findByRollout(new OffsetBasedPageRequest(0, 2, new Sort(Direction.ASC, "id")), createdRollout.getId())
            .getContent();
    runningRolloutGroups.forEach(group -> assertThat(group.getStatus()).isEqualTo(RolloutGroupStatus.RUNNING)
            .as("group should be in running state because it should be started but it is in " + group.getStatus()
                    + " state"));

    // verify that the other groups are still in schedule state
    final List<RolloutGroup> scheduledRolloutGroups = rolloutGroupManagement
            .findByRollout(new OffsetBasedPageRequest(2, 10, new Sort(Direction.ASC, "id")), createdRollout.getId())
            .getContent();
    scheduledRolloutGroups.forEach(group -> assertThat(group.getStatus()).isEqualTo(RolloutGroupStatus.SCHEDULED)
            .as("group should be in scheduled state because it should not be started but it is in "
                    + group.getStatus() + " state"));
}