Fix Id-searches endpoint performance degradation
[cps.git] / cps-service / src / main / java / org / onap / cps / spi / FetchDescendantsOption.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Pantheon.tech
4  *  Copyright (C) 2022 Nordix Foundation
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        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.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.spi;
22
23 import lombok.RequiredArgsConstructor;
24
25 @RequiredArgsConstructor
26 public class FetchDescendantsOption {
27
28     public static final FetchDescendantsOption FETCH_DIRECT_CHILDREN_ONLY = new FetchDescendantsOption(1);
29     public static final FetchDescendantsOption OMIT_DESCENDANTS = new FetchDescendantsOption(0);
30     public static final FetchDescendantsOption INCLUDE_ALL_DESCENDANTS = new FetchDescendantsOption(-1);
31
32     private final int depth;
33
34     /**
35      * Has next depth.
36      *
37      * @return true if next level of depth is available
38      * @throws IllegalArgumentException when depth less than -1
39      */
40     public boolean hasNext() {
41         validateDepth(depth);
42         return depth > 0 || this.depth == INCLUDE_ALL_DESCENDANTS.depth;
43     }
44
45     /**
46      * Next fetch descendants option.
47      *
48      * @return the next fetch descendants option
49      * @throws IllegalArgumentException when depth less than -1 or 0
50      */
51     public FetchDescendantsOption next() {
52         if (depth == 0) {
53             throw new IllegalArgumentException("Do not use next() method with zero depth");
54         }
55         final FetchDescendantsOption nextDescendantsOption = this.depth == INCLUDE_ALL_DESCENDANTS.depth
56                 ? INCLUDE_ALL_DESCENDANTS : new FetchDescendantsOption(depth - 1);
57         validateDepth(nextDescendantsOption.depth);
58         return nextDescendantsOption;
59     }
60
61     private static void validateDepth(final int depth) {
62         if (depth < -1) {
63             throw new IllegalArgumentException("A depth of less than minus one is not allowed");
64         }
65     }
66
67 }