Reduced code complexity
[cli.git] / main / src / main / java / org / onap / cli / main / utils / OnapCliArgsParser.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.main.utils;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.net.URL;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Set;
27
28 import org.apache.commons.codec.binary.Base64;
29 import org.apache.commons.io.FileUtils;
30 import org.onap.cli.fw.error.OnapCommandException;
31 import org.onap.cli.fw.error.OnapCommandInvalidParameterValue;
32 import org.onap.cli.fw.input.OnapCommandParameter;
33 import org.onap.cli.fw.input.OnapCommandParameterType;
34 import org.onap.cli.main.error.OnapCliArgumentValueMissing;
35 import org.onap.cli.main.error.OnapCliInvalidArgument;
36 import com.esotericsoftware.yamlbeans.YamlReader;
37
38 import com.google.gson.Gson;
39 import com.google.gson.GsonBuilder;
40 import com.google.gson.JsonElement;
41 import com.google.gson.reflect.TypeToken;
42
43 import java.io.Reader;
44 import java.io.InputStreamReader;
45 import java.io.FileReader;
46
47 /**
48  * Oclip CLI utilities.
49  *
50  */
51 public class OnapCliArgsParser {
52     private static Gson gson = new GsonBuilder().serializeNulls().create();
53
54     /**
55      * private Constructor.
56      */
57     private OnapCliArgsParser() {
58
59     }
60
61     /**
62      * It read thru the args and populate the given params for short optional, long option and postional args the idx of
63      * positional args, is calculated based on the position at which it present in the params and args.
64      *
65      * @param params
66      *            List of command paramters
67      * @param args
68      *            Array of arguments
69      * @throws OnapCliArgumentValueMissing
70      *             ArgumentValueMissing exception
71      * @throws OnapCliInvalidArgument
72      *             Invalid argument exception
73      * @throws OnapCommandInvalidParameterValue
74      *             exception
75      */
76     public static void populateParams(Set<OnapCommandParameter> params, List<String> args)
77             throws OnapCommandException {
78         Map<String, String> shortOptionMap = new HashMap<>();
79         Map<String, String> longOptionMap = new HashMap<>();
80         List<String> positionArgs = new ArrayList<>();
81         Map<String, OnapCommandParameter> paramMap = new HashMap<>();
82
83         for (OnapCommandParameter param : params) {
84             boolean positional = true;
85             if (param.getShortOption() != null) {
86                 shortOptionMap.put(OnapCommandParameter.printShortOption(param.getShortOption()), param.getName());
87                 positional = false;
88             }
89             if (param.getLongOption() != null) {
90                 longOptionMap.put(OnapCommandParameter.printLongOption(param.getLongOption()), param.getName());
91                 positional = false;
92             }
93
94             if (positional) {
95                 positionArgs.add(param.getName());
96             }
97
98             paramMap.put(param.getName(), param);
99         }
100
101         int positionalIdx = 0;
102         for (int i = 0; i < args.size(); i++) {
103             String paramName = null;
104             if (shortOptionMap.containsKey(args.get(i))) {
105                 paramName = shortOptionMap.get(args.get(i));
106             } else if (longOptionMap.containsKey(args.get(i))) {
107                 paramName = longOptionMap.get(args.get(i));
108             }
109
110             if (paramName != null) {
111                 // end of the list or if its option rather than a value
112                 if ((i + 1) == args.size() || args.get(i + 1).startsWith("-")) {
113                     if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.BOOL)) {
114                         paramMap.get(paramName).setValue(true);
115                         continue;
116                     }
117                     throw new OnapCliArgumentValueMissing(args.get(i));
118                 }
119
120                 if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.JSON)) {
121                     paramMap.get(paramName).setValue(readJsonStringFromUrl(args.get(i + 1),
122                             paramMap.get(paramName).getName()));
123                     i++;
124                     continue;
125
126                 } else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.TEXT)) {
127                     paramMap.get(paramName).setValue(readTextStringFromUrl(args.get(i + 1),
128                             paramMap.get(paramName).getName()));
129                     i++;
130                     continue;
131
132                 } else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.YAML)) {
133                     String value = readYamlStringFromUrl(args.get(i + 1),
134                             paramMap.get(paramName).getName());
135                     paramMap.get(paramName).setValue(value);
136                     i++;
137                     continue;
138
139                 } else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.BYTE)) {
140                     paramMap.get(paramName).setValue(readBytesFromUrl(args.get(i + 1),
141                             paramMap.get(paramName).getName()));
142                     i++;
143                     continue;
144
145                 } else if (paramMap.get(paramName).getParameterType()
146                         .equals(OnapCommandParameterType.ARRAY)) {
147                     Object value = paramMap.get(paramName).getValue();
148                     List<String> list = (List<String>) value;
149
150                     list.add(readTextStringFromUrl(args.get(i + 1), paramMap.get(paramName).getName()));
151                     paramMap.get(paramName).setValue(list);
152                     i++;
153                     continue;
154
155                 } else if (paramMap.get(paramName).getParameterType()
156                         .equals(OnapCommandParameterType.MAP)) {
157                     Object value = paramMap.get(paramName).getValue();
158
159                     Map<String, String> map = (Map<String, String>) value;
160
161                     String arg = args.get(i + 1);
162                     String[] argArr = arg.split("=", 2);
163
164                     if (argArr.length != 2) {
165                         throw new OnapCliInvalidArgument(
166                                 paramMap.get(paramName).getName(),
167                                 "it should be in the form of <key>=<value>");
168                     }
169
170                     //Make sure to read values from file, in case file path is given.
171                     //map.put(argArr[0], readTextStringFromUrl(argArr[1], paramMap.get(paramName).getName()));
172                     map.put(argArr[0], argArr[1]);
173                     paramMap.get(paramName).setValue(map);
174                     i++;
175                     continue;
176                 }
177
178                 paramMap.get(paramName).setValue(args.get(i + 1));
179
180                 i++;
181                 continue;
182             }
183
184             // it is positional option
185             // Positional arg is missing from the params
186             if (positionalIdx >= positionArgs.size()) {
187                 throw new OnapCliInvalidArgument(
188                         args.get(i),
189                         "No positional argument is defined for this one");
190             }
191
192             paramMap.get(positionArgs.get(positionalIdx)).setValue(args.get(i));
193             positionalIdx++;
194         }
195
196         params.clear();
197         params.addAll(paramMap.values());
198     }
199
200     public static String readJsonStringFromUrl(String input, String argName) throws OnapCliInvalidArgument {
201         String jsonValue;
202         try {
203             File file = new File(input);
204             if (file.isFile()) {
205                 try(Reader reader = new FileReader(file)){
206                     jsonValue = gson.fromJson(reader, JsonElement.class).toString();
207                 }
208                 return jsonValue;
209             } else if (input.startsWith("file:") || input.startsWith("http:") || input.startsWith("ftp:")) {
210                 URL jsonUrl = new URL(input);
211                 try(Reader reader = new InputStreamReader(jsonUrl.openStream())){
212                     jsonValue = gson.fromJson(reader, JsonElement.class).toString();
213                 }
214                 return jsonValue;
215             } else {
216                 return gson.fromJson(input, JsonElement.class).toString();
217             }
218         } catch (Exception e) { // NOSONAR
219             throw new OnapCliInvalidArgument(argName, e);
220         }
221     }
222
223     public static String readTextStringFromUrl(String input, String argName) throws OnapCliInvalidArgument {
224         try {
225             File file = new File(input);
226             if (file.isFile()) {
227                 return FileUtils.readFileToString(file);
228             } else {
229                 return input;
230             }
231
232         } catch (IOException e) {
233             throw new OnapCliInvalidArgument(argName, e);
234         }
235     }
236
237     public static String readYamlStringFromUrl(String input, String argName) throws OnapCliInvalidArgument {
238         try {
239             File file = new File(input);
240             if (file.isFile()) {
241                 String value = FileUtils.readFileToString(file);
242                 YamlReader reader = new YamlReader(value);
243                 value = (String) reader.read();
244                 return value;
245             } else {
246                 return input;
247             }
248
249         } catch (IOException e) {
250             throw new OnapCliInvalidArgument(argName, e);
251         }
252     }
253
254     public static String readBytesFromUrl(String input, String argName) throws OnapCliInvalidArgument {
255         try {
256             File file = new File(input);
257             if (file.isFile()) {
258                 byte[] encodeBase64 = Base64.encodeBase64(FileUtils.readFileToByteArray(file));
259                 return new String(encodeBase64);
260             } else {
261                 byte[] encodeBase64 = Base64.encodeBase64(input.getBytes());
262                 return new String(encodeBase64);
263             }
264         } catch (IOException e) {
265             throw new OnapCliInvalidArgument(argName, e);
266         }
267     }
268
269     public static List<String> convertJsonToListString(String arg, String json) throws OnapCliInvalidArgument {
270         TypeToken<List<String>> mapType = new TypeToken<List<String>>() {
271         };
272         try {
273             return gson.fromJson(json, mapType.getType());
274         } catch (Exception e) { // NOSONAR
275             throw new OnapCliInvalidArgument(arg, e);
276         }
277     }
278
279     public static Map<String, String> convertJsonToMapString(String arg, String json) throws OnapCliInvalidArgument {
280         TypeToken<Map<String, String>> mapType = new TypeToken<Map<String, String>>() {
281         };
282         try {
283             return gson.fromJson(json, mapType.getType());
284         } catch (Exception e) { // NOSONAR
285             throw new OnapCliInvalidArgument(arg, e);
286         }
287     }
288 }