1 package io.getunleash.repository;
2
3 import com.google.gson.JsonSyntaxException;
4 import io.getunleash.UnleashException;
5 import io.getunleash.event.EventDispatcher;
6 import io.getunleash.event.UnleashEvent;
7 import io.getunleash.event.UnleashSubscriber;
8 import io.getunleash.lang.Nullable;
9 import io.getunleash.util.UnleashConfig;
10 import java.io.StringReader;
11 import java.util.Collections;
12
13 public class FeatureBootstrapHandler {
14     private final EventDispatcher eventDispatcher;
15     private final ToggleBootstrapProvider toggleBootstrapProvider;
16
17     public FeatureBootstrapHandler(UnleashConfig unleashConfig) {
18         if (unleashConfig.getToggleBootstrapProvider() != null) {
19             this.toggleBootstrapProvider = unleashConfig.getToggleBootstrapProvider();
20         } else {
21             this.toggleBootstrapProvider = new ToggleBootstrapFileProvider();
22         }
23         this.eventDispatcher = new EventDispatcher(unleashConfig);
24     }
25
26     public FeatureCollection parse(@Nullable String jsonString) {
27         if (jsonString != null) {
28             try (StringReader stringReader = new StringReader(jsonString)) {
29                 FeatureCollection featureCollection = JsonFeatureParser.fromJson(stringReader);
30                 eventDispatcher.dispatch(new FeatureBootstrapRead(featureCollection));
31                 return featureCollection;
32             } catch (IllegalStateException | JsonSyntaxException ise) {
33                 eventDispatcher.dispatch(
34                         new UnleashException("Failed to read toggle bootstrap", ise));
35             }
36         }
37         return new FeatureCollection(
38                 new ToggleCollection(Collections.emptyList()),
39                 new SegmentCollection(Collections.emptyList()));
40     }
41
42     public FeatureCollection read() {
43         if (toggleBootstrapProvider != null) {
44             return parse(toggleBootstrapProvider.read());
45         }
46         return new FeatureCollection(
47                 new ToggleCollection(Collections.emptyList()),
48                 new SegmentCollection(Collections.emptyList()));
49     }
50
51     public static class FeatureBootstrapRead implements UnleashEvent {
52         private final FeatureCollection featureCollection;
53
54         public FeatureBootstrapRead(FeatureCollection featureCollection) {
55             this.featureCollection = featureCollection;
56         }
57
58         @Override
59         public void publishTo(UnleashSubscriber unleashSubscriber) {
60             unleashSubscriber.featuresBootstrapped(featureCollection);
61         }
62     }
63 }
64