Merge "removed block of commented-out lines of code"
[cli.git] / framework / src / main / java / org / onap / cli / fw / store / OnapCommandProfileStore.java
1 /*
2  * Copyright 2017 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://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,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.cli.fw.store;
18
19 import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_PATH_PROFILE_JSON;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.nio.file.Files;
24 import java.nio.file.Paths;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30
31 import org.apache.commons.io.FileUtils;
32 import org.onap.cli.fw.conf.OnapCommandConfig;
33 import org.onap.cli.fw.conf.OnapCommandConstants;
34 import org.onap.cli.fw.error.OnapCommandException;
35 import org.onap.cli.fw.error.OnapCommandPersistProfileFailed;
36 import org.onap.cli.fw.error.OnapCommandProfileLoadFailed;
37 import org.onap.cli.fw.input.cache.OnapCommandParamEntity;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import com.google.gson.Gson;
42 import com.google.gson.GsonBuilder;
43 import java.io.FileWriter;
44 import java.io.FileReader;
45 import java.io.Writer;
46 import java.io.Reader;
47
48
49
50 public class OnapCommandProfileStore {
51     private static Logger log = LoggerFactory.getLogger(OnapCommandProfileStore.class);
52     private Gson gson = new GsonBuilder().setPrettyPrinting().create();
53
54     private Map<String, Map<String, String>> paramCache = new HashMap<>();
55
56     private static OnapCommandProfileStore single = null;
57
58     private String profileName = OnapCommandConstants.PARAM_CACHE_FILE_NAME;
59
60     static {
61         try {
62             FileUtils.forceMkdir(new File(getDataStorePath()));
63         } catch (IOException e) {
64             log.error("Failed to create the data store profile");
65         }
66     }
67     private OnapCommandProfileStore() {
68
69     }
70
71     public static OnapCommandProfileStore getInstance() {
72         if (single == null) {
73             single = new OnapCommandProfileStore();
74         }
75
76         return single;
77     }
78
79     public void includeProfile(String profile) throws OnapCommandException {
80         this.load(profile, true);
81     }
82
83     public void excludeProfile(String profile) throws OnapCommandException {
84         this.load(profile, false);
85     }
86
87     public void add(String productVersion, String paramName, String paramValue) {
88
89         if (!paramCache.containsKey(productVersion)) {
90             paramCache.put(productVersion, new HashMap<>());
91         }
92
93         paramCache.get(productVersion).put(paramName, paramValue);
94
95         this.persist();
96     }
97
98     public void remove(String productVersion, String paramName) {
99             if (paramCache.containsKey(productVersion) && paramCache.get(productVersion).containsKey(paramName)) {
100                 paramCache.get(productVersion).remove(paramName);
101             }
102
103         this.persist();
104     }
105
106     public Map<String, String> getParams(String productVersion) {
107         //default profile used across products, set in profile-set command
108         Map<String, String> map = new HashMap<>();
109
110         if (paramCache.containsKey(OnapCommandConstants.OCLIP_GLOBAL_PROFILE)) {
111             map = this.paramCache.get(OnapCommandConstants.OCLIP_GLOBAL_PROFILE);
112         }
113
114         if (paramCache.containsKey(productVersion)) {
115             map.putAll(this.paramCache.get(productVersion));
116         }
117
118         return map;
119     }
120
121     private void persist() {
122         List<OnapCommandParamEntity> params = new ArrayList<>();
123
124         for (Map.Entry<String, Map<String, String>> p: this.paramCache.entrySet()) {
125             for (Map.Entry<String, String> paramEntry: p.getValue().entrySet()) {
126
127                 OnapCommandParamEntity param = new OnapCommandParamEntity();
128                 param.setProduct(p.getKey());
129                 param.setName(paramEntry.getKey());
130                 param.setValue(paramEntry.getValue());
131
132                 params.add(param);
133              }
134         }
135
136         try {
137             this.persistProfile(params, this.profileName);
138         } catch (OnapCommandPersistProfileFailed e) {
139             throw new RuntimeException(e);   // NOSONAR
140         }
141     }
142
143     private void load() throws OnapCommandException {
144         this.load(this.profileName, true);
145     }
146
147     private void load(String profileName, boolean include) throws OnapCommandException {
148         List<OnapCommandParamEntity> params = this.loadParamFromCache(profileName);
149
150         for (OnapCommandParamEntity p : params) {
151             if (include) {
152                 this.add(p.getProduct(), p.getName(), p.getValue());
153             } else {
154                 this.remove(p.getProduct(), p.getName());
155             }
156         }
157     }
158
159     public void setProfile(String profileName) throws OnapCommandException {
160         this.profileName = profileName;
161         this.paramCache.clear();
162         this.load();
163     }
164
165     public static String getDataStorePath() {
166         return OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_DATA_DIR)
167                 + File.separator + "profiles";
168     }
169
170     public void persistProfile(List<OnapCommandParamEntity> params, String profileName) throws OnapCommandPersistProfileFailed {
171         if (params != null) {
172             String dataDir = getDataStorePath();
173                 File file = new File(dataDir + File.separator + profileName + DATA_PATH_PROFILE_JSON);
174                 try (Writer writer = new FileWriter(file)){
175                     gson.toJson(params, writer);
176                 } catch (Exception e1) { // NOSONAR
177                 throw new OnapCommandPersistProfileFailed(e1);
178             }
179         }
180     }
181
182     public List<OnapCommandParamEntity> loadParamFromCache(String profileName) throws OnapCommandException {
183         List<OnapCommandParamEntity> params = new ArrayList<>();
184         String dataDir = getDataStorePath();
185         File file = new File(dataDir + File.separator + profileName + DATA_PATH_PROFILE_JSON);
186         if (file.exists()) {
187             try (Reader jsonReader = new FileReader(file)){
188
189                 OnapCommandParamEntity[] list = gson.fromJson(jsonReader,
190                         OnapCommandParamEntity[].class);
191                 params.addAll(Arrays.asList(list));
192             } catch (Exception e) { // NOSONAR
193                 throw new OnapCommandProfileLoadFailed(e);
194             }
195         }
196
197         return params;
198     }
199
200     public void removeProfile(String profile) {
201          String dataDir = getDataStorePath();
202          File file = new File(dataDir + File.separator + profile + DATA_PATH_PROFILE_JSON);
203         try {
204             Files.delete(Paths.get(dataDir + File.separator + profile + DATA_PATH_PROFILE_JSON));
205         } catch (IOException e) {
206             String fileAbsPath = file.getAbsolutePath();
207             log.error("Failed to delete profile {}", fileAbsPath);
208         }
209     }
210
211     public List<String> getProfiles() {
212         List<String> profiles = new ArrayList<>();
213
214         String dataDir = getDataStorePath();
215         for (File file: new File(dataDir).listFiles((dir, name) -> name.endsWith(DATA_PATH_PROFILE_JSON))) {
216             String profile = file.getName().substring(0, file.getName().indexOf(DATA_PATH_PROFILE_JSON));
217             profiles.add(profile);
218         }
219
220         return profiles;
221     }
222 }