1 package io.getunleash.repository;
2
3 import io.getunleash.lang.Nullable;
4 import java.io.File;
5 import java.io.FileNotFoundException;
6 import java.io.IOException;
7 import java.net.URISyntaxException;
8 import java.net.URL;
9 import java.nio.charset.StandardCharsets;
10 import java.nio.file.Files;
11 import java.nio.file.Paths;
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14
15 public class ToggleBootstrapFileProvider implements ToggleBootstrapProvider {
16     private static final Logger LOG = LoggerFactory.getLogger(ToggleBootstrapFileProvider.class);
17     final String path;
18
19     public ToggleBootstrapFileProvider() {
20         this.path = getBootstrapFile();
21     }
22
23     /**
24      * Accepts path to file to read either as constructor parameter or as environment variable in
25      * "UNLEASH_BOOTSTRAP_FILE"
26      *
27      * @param path - path to toggles file
28      */

29     public ToggleBootstrapFileProvider(String path) {
30         this.path = path;
31     }
32
33     @Override
34     @Nullable
35     public String read() {
36         LOG.info("Trying to read feature toggles from bootstrap file found at {}", path);
37         try {
38             File file = getFile(path);
39             if (file != null) {
40                 return fileAsString(file);
41             }
42         } catch (FileNotFoundException ioEx) {
43             LOG.warn("Could not find file {}", path, ioEx);
44         } catch (IOException ioEx) {
45             LOG.warn("Generic IOException when trying to read file at {}", path, ioEx);
46         }
47         return null;
48     }
49
50     @Nullable
51     private String getBootstrapFile() {
52         String path = System.getenv("UNLEASH_BOOTSTRAP_FILE");
53         if (path == null) {
54             path = System.getProperty("UNLEASH_BOOTSTRAP_FILE");
55         }
56         return path;
57     }
58
59     private String fileAsString(File file) throws IOException {
60         return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
61     }
62
63     @Nullable
64     private File getFile(@Nullable String path) {
65         if (path != null) {
66             if (path.startsWith("classpath:")) {
67                 try {
68                     URL resource =
69                             getClass()
70                                     .getClassLoader()
71                                     .getResource(path.substring("classpath:".length()));
72                     if (resource != null) {
73                         return Paths.get(resource.toURI()).toFile();
74                     }
75                     return null;
76                 } catch (URISyntaxException e) {
77                     return null;
78                 }
79             } else {
80                 return Paths.get(path).toFile();
81             }
82         } else {
83             return null;
84         }
85     }
86 }
87