1   /*
2    * Copyright 2023 LINE Corporation
3    *
4    * LINE Corporation licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package com.linecorp.centraldogma.server;
17  
18  import java.io.IOException;
19  import java.nio.charset.StandardCharsets;
20  import java.nio.file.Files;
21  import java.nio.file.Paths;
22  import java.util.Base64;
23  import java.util.List;
24  
25  import com.google.common.collect.ImmutableList;
26  
27  enum DefaultConfigValueConverter implements ConfigValueConverter {
28      INSTANCE;
29  
30      private static final String PLAINTEXT = "plaintext";
31      private static final String FILE = "file";
32      private static final String BASE64 = "base64";
33      private static final String ENV = "env";
34  
35      // TODO(minwoox): Add more prefixes such as classpath, url, etc.
36      private static final List<String> SUPPORTED_PREFIXES = ImmutableList.of(PLAINTEXT, FILE, BASE64, ENV);
37  
38      @Override
39      public List<String> supportedPrefixes() {
40          return SUPPORTED_PREFIXES;
41      }
42  
43      @Override
44      public String convert(String prefix, String value) {
45          switch (prefix) {
46              case PLAINTEXT:
47                  return value;
48              case FILE:
49                  try {
50                      return new String(Files.readAllBytes(Paths.get(value)), StandardCharsets.UTF_8);
51                  } catch (IOException e) {
52                      throw new RuntimeException("failed to read a file: " + value, e);
53                  }
54              case BASE64:
55                  return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8).trim();
56              case ENV:
57                  return System.getenv(value);
58              default:
59                  // Should never reach here.
60                  throw new Error();
61          }
62      }
63  }