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         //single.load();
77         return single;
78     }
79
80     public void includeProfile(String profile) throws OnapCommandException {
81         this.load(profile, true);
82     }
83
84     public void excludeProfile(String profile) throws OnapCommandException {
85         this.load(profile, false);
86     }
87
88     public void add(String productVersion, String paramName, String paramValue) {
89
90         if (!paramCache.containsKey(productVersion)) {
91             paramCache.put(productVersion, new HashMap<>());
92         }
93
94         paramCache.get(productVersion).put(paramName, paramValue);
95
96         this.persist();
97     }
98
99     public void remove(String productVersion, String paramName) {
100             if (paramCache.containsKey(productVersion) && paramCache.get(productVersion).containsKey(paramName)) {
101                 paramCache.get(productVersion).remove(paramName);
102             }
103
104         this.persist();
105     }
106
107     public Map<String, String> getParams(String productVersion) {
108         //default profile used across products, set in profile-set command
109         Map<String, String> map = new HashMap<>();
110
111         if (paramCache.containsKey(OnapCommandConstants.OCLIP_GLOBAL_PROFILE)) {
112             map = this.paramCache.get(OnapCommandConstants.OCLIP_GLOBAL_PROFILE);
113         }
114
115         if (paramCache.containsKey(productVersion)) {
116             map.putAll(this.paramCache.get(productVersion));
117         }
118
119         return map;
120     }
121
122     private void persist() {
123         List<OnapCommandParamEntity> params = new ArrayList<>();
124
125         for (Map.Entry<String, Map<String, String>> p: this.paramCache.entrySet()) {
126             for (Map.Entry<String, String> paramEntry: p.getValue().entrySet()) {
127
128                 OnapCommandParamEntity param = new OnapCommandParamEntity();
129                 param.setProduct(p.getKey());
130                 param.setName(paramEntry.getKey());
131                 param.setValue(paramEntry.getValue());
132
133                 params.add(param);
134              }
135         }
136
137         try {
138             this.persistProfile(params, this.profileName);
139         } catch (OnapCommandPersistProfileFailed e) {
140             throw new RuntimeException(e);   // NOSONAR
141         }
142     }
143
144     private void load() throws OnapCommandException {
145         this.load(this.profileName, true);
146     }
147
148     private void load(String profileName, boolean include) throws OnapCommandException {
149         List<OnapCommandParamEntity> params = this.loadParamFromCache(profileName);
150
151         for (OnapCommandParamEntity p : params) {
152             if (include) {
153                 this.add(p.getProduct(), p.getName(), p.getValue());
154             } else {
155                 this.remove(p.getProduct(), p.getName());
156             }
157         }
158     }
159
160     public void setProfile(String profileName) throws OnapCommandException {
161         this.profileName = profileName;
162         this.paramCache.clear();
163         this.load();
164     }
165
166     public static String getDataStorePath() {
167         return OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_DATA_DIR)
168                 + File.separator + "profiles";
169     }
170
171     public void persistProfile(List<OnapCommandParamEntity> params, String profileName) throws OnapCommandPersistProfileFailed {
172         if (params != null) {
173             String dataDir = getDataStorePath();
174                 File file = new File(dataDir + File.separator + profileName + DATA_PATH_PROFILE_JSON);
175                 try (Writer writer = new FileWriter(file)){
176                     gson.toJson(params, writer);
177                 } catch (Exception e1) { // NOSONAR
178                 throw new OnapCommandPersistProfileFailed(e1);
179             }
180         }
181     }
182
183     public List<OnapCommandParamEntity> loadParamFromCache(String profileName) throws OnapCommandException {
184         List<OnapCommandParamEntity> params = new ArrayList<>();
185         String dataDir = getDataStorePath();
186         File file = new File(dataDir + File.separator + profileName + DATA_PATH_PROFILE_JSON);
187         if (file.exists()) {
188             try (Reader jsonReader = new FileReader(file)){
189
190                 OnapCommandParamEntity[] list = gson.fromJson(jsonReader,
191                         OnapCommandParamEntity[].class);
192                 params.addAll(Arrays.asList(list));
193 //            } else {
194 //                throw new OnapCommandProfileNotFound(profileName);
195             } catch (Exception e) { // NOSONAR
196                 throw new OnapCommandProfileLoadFailed(e);
197             }
198         }
199
200         return params;
201     }
202
203     public void removeProfile(String profile) {
204          String dataDir = getDataStorePath();
205          File file = new File(dataDir + File.separator + profile + DATA_PATH_PROFILE_JSON);
206         try {
207             Files.delete(Paths.get(dataDir + File.separator + profile + DATA_PATH_PROFILE_JSON));
208         } catch (IOException e) {
209             String fileAbsPath = file.getAbsolutePath();
210             log.error("Failed to delete profile {}", fileAbsPath);
211         }
212     }
213
214     public List<String> getProfiles() {
215         List<String> profiles = new ArrayList<>();
216
217         String dataDir = getDataStorePath();
218         for (File file: new File(dataDir).listFiles((dir, name) -> name.endsWith(DATA_PATH_PROFILE_JSON))) {
219             String profile = file.getName().substring(0, file.getName().indexOf(DATA_PATH_PROFILE_JSON));
220             profiles.add(profile);
221         }
222
223         return profiles;
224     }
225 }