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  
34      // TODO(minwoox): Add more prefixes such as classpath, url, etc.
35      private static final List<String> SUPPORTED_PREFIXES = ImmutableList.of(PLAINTEXT, FILE, BASE64);
36  
37      @Override
38      public List<String> supportedPrefixes() {
39          return SUPPORTED_PREFIXES;
40      }
41  
42      @Override
43      public String convert(String prefix, String value) {
44          switch (prefix) {
45              case PLAINTEXT:
46                  return value;
47              case FILE:
48                  try {
49                      return new String(Files.readAllBytes(Paths.get(value)), StandardCharsets.UTF_8);
50                  } catch (IOException e) {
51                      throw new RuntimeException("failed to read a file: " + value, e);
52                  }
53              case BASE64:
54                  return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8).trim();
55              default:
56                  // Should never reach here.
57                  throw new Error();
58          }
59      }
60  }