2 * ============LICENSE_START=======================================================
3 * Copyright (c) 2021 Bell Canada.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.temporal.controller.rest.model;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.stream.Collectors;
27 import javax.validation.ValidationException;
28 import javax.validation.constraints.NotEmpty;
29 import org.springframework.data.domain.Sort;
30 import org.springframework.data.domain.Sort.Direction;
31 import org.springframework.data.domain.Sort.Order;
32 import org.springframework.stereotype.Component;
35 public class SortMapper {
37 private static final String SORT_ORDER_SEPARATOR = ",";
38 private static final String FIELD_DIRECTION_SEPARATOR = ":";
41 * convert from Sort to String format "fieldname:direction,...,fieldname:direction".
46 public String sortAsString(final Sort sort) {
49 sortOrder.getProperty() + FIELD_DIRECTION_SEPARATOR
50 + sortOrder.getDirection().toString().toLowerCase(Locale.ENGLISH))
51 .collect(Collectors.joining(SORT_ORDER_SEPARATOR));
55 * Convert from "fieldname:direction,...,fieldname:direction" format to Sort. Example :
56 * "anchor:asc,observed_timestamp:desc"
58 * @param sortString sortString
61 public Sort toSort(@NotEmpty final String sortString) {
63 final String[] sortingOrderAsString = sortString.split(SORT_ORDER_SEPARATOR);
64 final List<Order> sortOrder = new ArrayList<>();
65 for (final String eachSortAsString : sortingOrderAsString) {
66 final String[] eachSortDetail = eachSortAsString.split(FIELD_DIRECTION_SEPARATOR);
67 final var direction = Direction.fromString(eachSortDetail[1]);
68 final var fieldName = eachSortDetail[0];
69 sortOrder.add(new Order(direction, fieldName));
71 return Sort.by(sortOrder);
72 } catch (final Exception exception) {
73 throw new ValidationException(
75 "Invalid sort format. sort '%s' is not in '<fieldname>:<direction>,...,<fieldname>:<direction>'"
76 + " format. Example: 'anchor:asc,observed_timestamp:desc'", sortString), exception