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

The following examples show how to use org.springframework.data.domain.Sort.Order. 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: SysComnLogsService.java    From danyuan-application with Apache License 2.0 7 votes vote down vote up
/**
 * @param vo
 * 方法名: findAllError
 * 功 能: TODO(这里用一句话描述这个方法的作用)
 * 参 数: @return
 * 返 回: List<SysComnLogs>
 * 作 者 : Administrator
 * @throws
 */
public Page<SysComnLogs> findAllError(SysComnLogsVo vo) {
	// Example<SysComnLogs> example = Example.of(vo.getInfo());
	Sort sort = Sort.by(new Order(Direction.DESC, "createTime"));
	PageRequest request = PageRequest.of(vo.getPageNumber() - 1, vo.getPageSize(), sort);
	Page<SysComnLogs> sourceCodes = sysComnLoggersDao.findAll(new Specification<SysComnLogs>() {
		/**
		 * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
		 */
		private static final long serialVersionUID = 1L;
		
		@Override
		public Predicate toPredicate(Root<SysComnLogs> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
			List<Predicate> list = new ArrayList<>();
			list.add(cb.isNotNull(root.get("message").as(String.class)));
			return cb.and(list.toArray(new Predicate[list.size()]));
		}
	}, request);
	return sourceCodes;
}
 
Example #2
Source File: KeyValueQuerydslUtils.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link Expression} for the given {@link Order} property.
 *
 * @param order must not be {@literal null}.
 * @param builder must not be {@literal null}.
 * @return
 */
private static Expression<?> buildOrderPropertyPathFrom(Order order, PathBuilder<?> builder) {

	Assert.notNull(order, "Order must not be null!");
	Assert.notNull(builder, "Builder must not be null!");

	PropertyPath path = PropertyPath.from(order.getProperty(), builder.getType());
	Expression<?> sortPropertyExpression = builder;

	while (path != null) {

		if (!path.hasNext() && order.isIgnoreCase()) {
			// if order is ignore-case we have to treat the last path segment as a String.
			sortPropertyExpression = Expressions.stringPath((Path<?>) sortPropertyExpression, path.getSegment()).lower();
		} else {
			sortPropertyExpression = Expressions.path(path.getType(), (Path<?>) sortPropertyExpression, path.getSegment());
		}

		path = path.next();
	}

	return sortPropertyExpression;
}
 
Example #3
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#findAll()
 * @return
 * 
 */
public List<PortfolioResponse> findAll() {
	List<ExecutiveSummaryList> executiveSummaryList = (List<ExecutiveSummaryList>) executiveSummaryListRepository
			.findAll();
	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 null;
}
 
Example #4
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 #5
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 #6
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 #7
Source File: SysComnLogsService.java    From danyuan-application with Apache License 2.0 6 votes vote down vote up
/**
 * 方法名: findAllLongtime
 * 功 能: TODO(这里用一句话描述这个方法的作用)
 * 参 数: @param vo
 * 参 数: @return
 * 返 回: Page<SysComnLogs>
 * 作 者 : Administrator
 * @throws
 */
public Page<SysComnLogs> findAllLongtime(SysComnLogsVo vo) {
	Sort sort = Sort.by(new Order(Direction.DESC, "createTime"));
	PageRequest request = PageRequest.of(vo.getPageNumber() - 1, vo.getPageSize(), sort);
	Page<SysComnLogs> sourceCodes = sysComnLoggersDao.findAll(new Specification<SysComnLogs>() {
		/**
		 * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
		 */
		private static final long serialVersionUID = 1L;
		
		@Override
		public Predicate toPredicate(Root<SysComnLogs> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
			List<Predicate> list = new ArrayList<>();
			list.add(cb.gt((root.get("requestLong").as(Long.class)), 1000));
			// list.add(cb.equal((root.get("url").as(String.class)), "/zhcx/findAllTableRow"));
			// list.add(cb.equal((root.get("classMethod").as(String.class)), "findAllTableRow"));
			return cb.and(list.toArray(new Predicate[list.size()]));
		}
	}, request);
	return sourceCodes;
}
 
Example #8
Source File: IssueServiceTests.java    From mirrorgate with Apache License 2.0 6 votes vote down vote up
@Test
public void getActiveUserStoriesByProjectNameTest() {

    final DashboardDTO dashboard = TestObjectFactory.createDashboard();

    final Issue story1 = TestObjectFactory.createActiveStory();
    final Issue story2 = TestObjectFactory.createActiveStory();

    final List<Issue> stories = Arrays.asList(story1, story2);

    when(issueRepository.findActiveUserStoriesByBoards(
        Collections.singletonList(dashboard.getName()),
        Sort.by(Order.by("status")))
    ).thenReturn(stories);

    final List<Issue> activeStoriesByDashboardName
        = issueService.getActiveUserStoriesByBoards(Collections.singletonList(dashboard.getName()));

    verify(issueRepository, times(1)).findActiveUserStoriesByBoards(
        Collections.singletonList(dashboard.getName()), Sort.by(Order.by("status"))
    );

    assertThat(activeStoriesByDashboardName.get(0)).isEqualTo(story1);
    assertThat(activeStoriesByDashboardName.get(1)).isEqualTo(story2);
}
 
Example #9
Source File: PageableDataProvider.java    From spring-data-provider with Apache License 2.0 6 votes vote down vote up
private <T, F> Sort createSpringSort(Query<T, F> q) {
    List<QuerySortOrder> sortOrders;
    if (q.getSortOrders().isEmpty()) {
        sortOrders = getDefaultSortOrders();
    } else {
        sortOrders = q.getSortOrders();
    }
    List<Order> orders = sortOrders.stream()
            .map(PageableDataProvider::queryOrderToSpringOrder)
            .collect(Collectors.toList());
    if (orders.isEmpty()) {
        return Sort.unsorted();
    } else {
        return Sort.by(orders);
    }
}
 
Example #10
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 #11
Source File: DatatablesSortHandlerMethodArgumentResolver.java    From springlets with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a full ordering criteria from the datatables parameters.
 * @return the ordering criteria
 */
public DatatablesSort getSort() {
  int columnCount = getColumnCount();

  if (columnCount <= 0) {
    return null;
  }

  List<Order> orderList = new ArrayList<Order>(columnCount);

  for (int i = 0; i < columnCount; i++) {
    Order order = getOrderInPosition(i);
    if (order != null) {
      orderList.add(order);
    }
  }

  if (orderList.isEmpty()) {
    return null;
  }

  return new DatatablesSort(orderList);
}
 
Example #12
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 #13
Source File: SortParametersParserTest.java    From springlets with Apache License 2.0 6 votes vote down vote up
@Test
public void validSortParsed() {
  // 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
  Sort sort = parser.getSort();
  Order order0 = sort.getOrderFor("property3");
  Order order1 = sort.getOrderFor("property1");

  // 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 #14
Source File: SortUtils.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
public static Sort covertSortDto(SortDto sortDto) {

		if (sortDto == null || sortDto.getOrders() == null
				|| sortDto.getOrders().isEmpty()) {
			return null;
		}
		List<Order> orders = new ArrayList<>();

		for (OrderDto orderdto : sortDto.getOrders()) {
			Order order = new Order(Sort.Direction.fromString(orderdto
					.getDirection().name()), orderdto.getProperty());
			if (orderdto.isIgnoreCase()) {
				order = order.ignoreCase();
			}
			orders.add(order);
		}

		return new Sort(orders);
	}
 
Example #15
Source File: SortUtility.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parses the sort string e.g. given in a REST call based on the definition
 * of sorting: http://localhost/entity?s=field1:ASC, field2:DESC The fields
 * will be split into the keys of the returned map. The direction of the
 * sorting will be mapped into the {@link Direction} enum.
 * 
 * @param enumType
 *            the class of the enum which the fields in the sort string
 *            should be related to.
 * @param <T>
 *            the type of the enumeration which must be derived from
 *            {@link FieldNameProvider}
 * @param sortString
 *            the string representation of the query parameters. Might be
 *            {@code null} or an empty string.
 * @return a list which holds the {@link FieldNameProvider} and the specific
 *         {@link Direction} for them as a tuple. Never {@code null}. In
 *         case of no sorting parameters an empty map will be returned.
 * @throws SortParameterSyntaxErrorException
 *             if the sorting query parameter is not well-formed
 * @throws SortParameterUnsupportedFieldException
 *             if a field name cannot be mapped to the enum type
 * @throws SortParameterUnsupportedDirectionException
 *             if the given direction is not "ASC" or "DESC"
 */
public static <T extends Enum<T> & FieldNameProvider> List<Order> parse(final Class<T> enumType,
        final String sortString) throws SortParameterSyntaxErrorException {
    final List<Order> parsedSortings = new ArrayList<>();
    // scan the sort tuples e.g. field:direction
    if (sortString != null) {
        final StringTokenizer tupleTokenizer = new StringTokenizer(sortString, DELIMITER_SORT_TUPLE);
        while (tupleTokenizer.hasMoreTokens()) {
            final String sortTuple = tupleTokenizer.nextToken().trim();
            final StringTokenizer fieldDirectionTokenizer = new StringTokenizer(sortTuple,
                    DELIMITER_FIELD_DIRECTION);
            if (fieldDirectionTokenizer.countTokens() == 2) {
                final String fieldName = fieldDirectionTokenizer.nextToken().trim().toUpperCase();
                final String sortDirectionStr = fieldDirectionTokenizer.nextToken().trim();

                final T identifier = getAttributeIdentifierByName(enumType, fieldName);

                final Direction sortDirection = getDirection(sortDirectionStr);
                parsedSortings.add(new Order(sortDirection, identifier.getFieldName()));
            } else {
                throw new SortParameterSyntaxErrorException();
            }
        }
    }
    return parsedSortings;
}
 
Example #16
Source File: DataInitializer.java    From POC with Apache License 2.0 6 votes vote down vote up
@EventListener(ContextRefreshedEvent.class)
public void init() {
	log.info("start data initialization  ...");
	List<String> statements = Arrays.asList(//
			"DROP TABLE IF EXISTS reactive_posts;",
			"CREATE TABLE reactive_posts ( id SERIAL PRIMARY KEY, title VARCHAR(100) NOT NULL, content VARCHAR(100) NOT NULL);");

	statements.forEach(query -> this.databaseClient.execute(query).then().block());

	this.databaseClient.delete().from("reactive_posts").then()
			.and(this.databaseClient.insert().into("reactive_posts").value("title", "First post title")
					.value("content", "Content of my first post").map((r, m) -> r.get("id", Integer.class)).all()
					.log())
			.thenMany(this.databaseClient.select().from("reactive_posts").orderBy(Sort.by(Order.desc("id")))
					.as(ReactivePost.class).fetch().all().log())
			.subscribe(post -> log.info("saving {}", post.toString()), e -> log.error(e.getMessage(), e),
					() -> log.info("initialization is done..."));
}
 
Example #17
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 #18
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 #19
Source File: KeyValueQuerydslUtils.java    From spring-data-keyvalue with Apache License 2.0 6 votes vote down vote up
/**
 * Transforms a plain {@link Order} into a QueryDsl specific {@link OrderSpecifier}.
 *
 * @param sort must not be {@literal null}.
 * @param builder must not be {@literal null}.
 * @return empty {@code OrderSpecifier<?>[]} when sort is {@literal null}.
 */
static OrderSpecifier<?>[] toOrderSpecifier(Sort sort, PathBuilder<?> builder) {

	Assert.notNull(sort, "Sort must not be null.");
	Assert.notNull(builder, "Builder must not be null.");

	List<OrderSpecifier<?>> specifiers = null;

	if (sort instanceof QSort) {
		specifiers = ((QSort) sort).getOrderSpecifiers();
	} else {

		specifiers = new ArrayList<>();
		for (Order order : sort) {
			specifiers.add(toOrderSpecifier(order, builder));
		}
	}

	return specifiers.toArray(new OrderSpecifier<?>[specifiers.size()]);
}
 
Example #20
Source File: R2dbcAppDetailRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<AppDetail> findAll() {
	return client
			.select()
			.from(AppDetail.tableName())
			.project(AppDetail.columnNames())
			.orderBy(Order.asc("organization"), Order.asc("space"), Order.asc("app_name"))
			.map((row, metadata) -> fromRow(row))
			.all();
}
 
Example #21
Source File: R2dbcAppDetailRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<AppDetail> findByDateRange(LocalDate start, LocalDate end) {
	return client
			.select()
				.from(AppDetail.tableName())
				.project(AppDetail.columnNames())
				.matching(Criteria.where("last_pushed").lessThanOrEquals(LocalDateTime.of(end, LocalTime.MAX)).and("last_pushed").greaterThan(LocalDateTime.of(start, LocalTime.MIDNIGHT)))
				.orderBy(Order.desc("last_pushed"))
			.map((row, metadata) -> fromRow(row))
			.all();
}
 
Example #22
Source File: R2dbcAppDetailRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
private Flux<Tuple2<AppDetail, ApplicationPolicy>> findApplicationsThatMayHaveServiceBindings(ApplicationPolicy policy) {
	LocalDateTime fromDateTime = policy.getOption("from-datetime", LocalDateTime.class);
	String fromDuration = policy.getOption("from-duration", String.class);
	LocalDateTime temporal = null;
	Criteria criteria = null;
	if (fromDateTime != null) {
		temporal = fromDateTime;
	}
	if (fromDuration != null) {
		temporal = LocalDateTime.now().minus(Duration.parse(fromDuration));;
	}
	if (temporal != null) {
		criteria = Criteria.where("requested_state").is(policy.getState()).and("last_event_time").lessThanOrEquals(temporal);
	} else {
		criteria = Criteria.where("requested_state").is(policy.getState());
	}
	return
		client
			.select()
				.from(AppDetail.tableName())
				.project(AppDetail.columnNames())
				.matching(criteria)
				.orderBy(Order.asc("organization"), Order.asc("space"), Order.asc("app_name"))
			.map((row, metadata) -> fromRow(row))
					.all()
					.map(r -> toTuple(r, policy));
}
 
Example #23
Source File: R2dbcAppDetailRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
private Flux<Tuple2<AppDetail, ApplicationPolicy>> findApplicationsThatDoNotHaveServiceBindings(ApplicationPolicy policy) {
	LocalDateTime fromDateTime = policy.getOption("from-datetime", LocalDateTime.class);
	String fromDuration = policy.getOption("from-duration", String.class);
	LocalDateTime temporal = null;
	Criteria criteria = null;
	if (fromDateTime != null) {
		temporal = fromDateTime;
	}
	if (fromDuration != null) {
		temporal = LocalDateTime.now().minus(Duration.parse(fromDuration));;
	}
	if (temporal != null) {
		criteria = Criteria.where("requested_state").is(policy.getState()).and("service_instance_id").isNull().and("last_event_time").lessThanOrEquals(temporal);
	} else {
		criteria = Criteria.where("requested_state").is(policy.getState()).and("service_instance_id").isNull();
	}
	return
		client
			.select()
				.from("service_bindings")
				.project(AppDetail.columnNames())
				.matching(criteria)
				.orderBy(Order.asc("organization"), Order.asc("space"), Order.asc("app_name"))
			.map((row, metadata) -> fromRow(row))
					.all()
					.map(r -> toTuple(r, policy));
}
 
Example #24
Source File: R2dbcHistoricalRecordRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<HistoricalRecord> findAll() {
	return client
			.select()
			.from(HistoricalRecord.tableName())
			.project(HistoricalRecord.columnNames())
			.orderBy(Order.desc("transaction_date_time"))
			.as(HistoricalRecord.class)
			.fetch()
			.all();
}
 
Example #25
Source File: R2dbcHistoricalRecordRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<HistoricalRecord> findByDateRange(LocalDate start, LocalDate end) {
	return client
			.select()
			.from(HistoricalRecord.tableName())
			.project(HistoricalRecord.columnNames())
			.matching(Criteria.where("transaction_date_time").lessThanOrEquals(LocalDateTime.of(end, LocalTime.MAX)).and("transaction_date_time").greaterThan(LocalDateTime.of(start, LocalTime.MIDNIGHT)))
			.orderBy(Order.desc("transaction_date_time"))
			.as(HistoricalRecord.class)
			.fetch()
			.all();
}
 
Example #26
Source File: R2dbcServiceInstanceDetailRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<ServiceInstanceDetail> findAll() {
	return client
			.select()
			.from(ServiceInstanceDetail.tableName())
			.project(ServiceInstanceDetail.columnNames())
			.orderBy(Order.asc("organization"), Order.asc("space"), Order.asc("service"), Order.asc("service_name"))
			.map((row, metadata) -> fromRow(row))
			.all();
}
 
Example #27
Source File: R2dbcServiceInstanceDetailRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<Tuple2<ServiceInstanceDetail, ServiceInstancePolicy>> findByServiceInstancePolicy(ServiceInstancePolicy policy) {
	LocalDateTime fromDateTime = policy.getOption("from-datetime", LocalDateTime.class);
	String fromDuration = policy.getOption("from-duration", String.class);
	LocalDateTime temporal = null;
	Criteria criteria = null;
	if (fromDateTime != null) {
		temporal = fromDateTime;
	}
	if (fromDuration != null) {
		temporal = LocalDateTime.now().minus(Duration.parse(fromDuration));;
	}
	if (temporal != null) {
		criteria = Criteria.where("bound_applications").isNull().and("last_updated").lessThanOrEquals(temporal);
	} else {
		criteria = Criteria.where("bound_applications").isNull();
	}
	return
		client
			.select()
				.from(ServiceInstanceDetail.tableName())
				.project(ServiceInstanceDetail.columnNames())
				.matching(criteria)
				.orderBy(Order.asc("organization"), Order.asc("space"), Order.asc("service_name"))
			.map((row, metadata) -> fromRow(row))
					.all()
					.map(r -> toTuple(r, policy));
}
 
Example #28
Source File: R2dbcSpaceRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<Space> findAll() {
	return client
			.select()
			.from(Space.tableName())
			.project(Space.columnNames())
			.orderBy(Order.asc("org_name"), Order.asc("space_name"))
			.map((row, metadata) -> fromRow(row))
			.all();
}
 
Example #29
Source File: R2dbcAppRelationshipRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<AppRelationship> findAll() {
	return client
			.select()
			.from(AppRelationship.tableName())
			.project(AppRelationship.columnNames())
			.orderBy(Order.asc("organization"), Order.asc("space"), Order.asc("app_name"))
			.as(AppRelationship.class)
			.fetch()
			.all();
}
 
Example #30
Source File: R2dbcAppRelationshipRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<AppRelationship> findByApplicationId(String applicationId) {
	return client
			.select()
				.from(AppRelationship.tableName())
				.project(AppRelationship.columnNames())
				.matching(Criteria.where("app_id").is(applicationId))
			.orderBy((Order.asc("organization")), Order.asc("space"), Order.asc("service_name"))
			.as(AppRelationship.class)
			.fetch()
			.all();
}