1 // Copyright 2021 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 package com.google.api.generator.gapic.utils;
16 
17 import java.util.Arrays;
18 import java.util.Optional;
19 
20 public final class ResourceReferenceUtils {
21 
22   private static final String SLASH = "/";
23 
ResourceReferenceUtils()24   private ResourceReferenceUtils() {}
25 
parseParentPattern(String pattern)26   public static Optional<String> parseParentPattern(String pattern) {
27     String[] tokens = pattern.split(SLASH);
28     String lastToken = tokens[tokens.length - 1];
29     if (lastToken.equals(ResourceNameConstants.DELETED_TOPIC_LITERAL)
30         || lastToken.equals(ResourceNameConstants.WILDCARD_PATTERN)) {
31       return Optional.empty();
32     }
33 
34     int lastTokenIndex = tokens.length - 2;
35     int minLengthWithParent = 4;
36     // Singleton patterns, e.g. projects/{project}/agent.
37     if (!lastToken.contains("{")) {
38       minLengthWithParent = 3;
39       lastTokenIndex = tokens.length - 1;
40     }
41 
42     // No fully-formed parent. Expected: ancestors/{ancestor}/childNodes/{child_node}.
43     if (tokens.length < minLengthWithParent) {
44       return Optional.empty();
45     }
46 
47     return Optional.of(String.join(SLASH, Arrays.asList(tokens).subList(0, lastTokenIndex)));
48   }
49 }
50