1 // Copyright 2020 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 com.google.api.generator.engine.lexicon.Keyword;
18 import com.google.common.base.CaseFormat;
19 import com.google.common.base.Strings;
20 import java.util.stream.IntStream;
21 
22 public class JavaStyle {
23   private static final String UNDERSCORE = "_";
24 
toLowerCamelCase(String s)25   public static String toLowerCamelCase(String s) {
26     if (Strings.isNullOrEmpty(s)) {
27       return s;
28     }
29 
30     s = s.replace('-', '_');
31 
32     if (s.indexOf(UNDERSCORE) >= 0) {
33       s = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, s);
34     }
35 
36     String name =
37         capitalizeLettersAfterDigits(
38             String.format("%s%s", s.substring(0, 1).toLowerCase(), s.substring(1)));
39 
40     // Some APIs use legit java keywords as method names. Both protobuf and gGRPC add an underscore
41     // in generated stubs to resolve name conflict, so we need to do the same.
42     return Keyword.escapeKeyword(name);
43   }
44 
toUpperCamelCase(String s)45   public static String toUpperCamelCase(String s) {
46     if (Strings.isNullOrEmpty(s)) {
47       return s;
48     }
49 
50     s = s.replace('-', '_');
51 
52     if (s.indexOf(UNDERSCORE) >= 0) {
53       s = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, s);
54     }
55     return capitalizeLettersAfterDigits(
56         String.format("%s%s", s.substring(0, 1).toUpperCase(), s.substring(1)));
57   }
58 
toUpperSnakeCase(String s)59   public static String toUpperSnakeCase(String s) {
60     String result = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, toUpperCamelCase(s));
61     return result;
62   }
63 
capitalizeLettersAfterDigits(String s)64   private static String capitalizeLettersAfterDigits(String s) {
65     return IntStream.range(0, s.length())
66         .collect(
67             StringBuilder::new,
68             (sb, i) ->
69                 sb.append(
70                     i > 0 && Character.isDigit(s.charAt(i - 1))
71                         ? Character.toUpperCase(s.charAt(i))
72                         : s.charAt(i)),
73             StringBuilder::append)
74         .toString();
75   }
76 }
77