Merge changes I60285973,I612ecfe2
[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.io.FileUtils;
29 import org.onap.cli.fw.error.OnapCommandException;
30 import org.onap.cli.fw.error.OnapCommandInvalidParameterValue;
31 import org.onap.cli.fw.input.OnapCommandParameter;
32 import org.onap.cli.fw.input.OnapCommandParameterType;
33 import org.onap.cli.main.error.OnapCliArgumentValueMissing;
34 import org.onap.cli.main.error.OnapCliInvalidArgument;
35
36 import com.fasterxml.jackson.core.type.TypeReference;
37 import com.fasterxml.jackson.databind.ObjectMapper;
38
39 import net.minidev.json.JSONObject;
40
41 /**
42  * Oclip CLI utilities.
43  *
44  */
45 public class OnapCliArgsParser {
46
47     /**
48      * private Constructor.
49      */
50     private OnapCliArgsParser() {
51
52     }
53
54     /**
55      * It read thru the args and populate the given params for short optional, long option and postional args the idx of
56      * positional args, is calculated based on the position at which it present in the params and args.
57      *
58      * @param params
59      *            List of command paramters
60      * @param args
61      *            Array of arguments
62      * @throws OnapCliArgumentValueMissing
63      *             ArgumentValueMissing exception
64      * @throws OnapCliInvalidArgument
65      *             Invalid argument exception
66      * @throws OnapCommandInvalidParameterValue
67      *             exception
68      */
69     public static void populateParams(Set<OnapCommandParameter> params, List<String> args)
70             throws OnapCommandException {
71         Map<String, String> shortOptionMap = new HashMap<>();
72         Map<String, String> longOptionMap = new HashMap<>();
73         List<String> positionArgs = new ArrayList<>();
74         Map<String, OnapCommandParameter> paramMap = new HashMap<>();
75
76         for (OnapCommandParameter param : params) {
77             boolean positional = true;
78             if (param.getShortOption() != null) {
79                 shortOptionMap.put(OnapCommandParameter.printShortOption(param.getShortOption()), param.getName());
80                 positional = false;
81             }
82             if (param.getLongOption() != null) {
83                 longOptionMap.put(OnapCommandParameter.printLongOption(param.getLongOption()), param.getName());
84                 positional = false;
85             }
86
87             if (positional) {
88                 positionArgs.add(param.getName());
89             }
90
91             paramMap.put(param.getName(), param);
92         }
93
94         int positionalIdx = 0;
95         for (int i = 0; i < args.size(); i++) {
96             String paramName = null;
97             if (shortOptionMap.containsKey(args.get(i))) {
98                 paramName = shortOptionMap.get(args.get(i));
99             } else if (longOptionMap.containsKey(args.get(i))) {
100                 paramName = longOptionMap.get(args.get(i));
101             }
102
103             if (paramName != null) {
104                 // end of the list or if its option rather than a value
105                 if ((i + 1) == args.size() || args.get(i + 1).startsWith("-")) {
106                     if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.BOOL)) {
107                         paramMap.get(paramName).setValue(true);
108                         continue;
109                     }
110                     throw new OnapCliArgumentValueMissing(args.get(i));
111                 }
112
113                 if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.JSON)) {
114                     paramMap.get(paramName).setValue(readJsonStringFromUrl(args.get(i + 1),
115                             paramMap.get(paramName).getName()));
116                     i++;
117                     continue;
118
119                 } if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.TEXT)) {
120                     paramMap.get(paramName).setValue(readTextStringFromUrl(args.get(i + 1),
121                             paramMap.get(paramName).getName()));
122                     i++;
123                     continue;
124
125                 } else if (paramMap.get(paramName).getParameterType()
126                         .equals(OnapCommandParameterType.ARRAY)) {
127                     Object value = paramMap.get(paramName).getValue();
128                     List<String> list = (List<String>) value;
129
130                     list.add(readTextStringFromUrl(args.get(i + 1), paramMap.get(paramName).getName()));
131                     paramMap.get(paramName).setValue(list);
132                     i++;
133                     continue;
134
135                 } else if (paramMap.get(paramName).getParameterType()
136                         .equals(OnapCommandParameterType.MAP)) {
137                     Object value = paramMap.get(paramName).getValue();
138
139                     Map<String, String> map = (Map<String, String>) value;
140
141                     String arg = args.get(i + 1);
142                     String[] argArr = arg.split("=", 2);
143
144                     if (argArr.length != 2) {
145                         throw new OnapCliInvalidArgument(
146                                 paramMap.get(paramName).getName(),
147                                 "it should be in the form of <key>=<value>");
148                     }
149
150                     //Make sure to read values from file, in case file path is given.
151                     //map.put(argArr[0], readTextStringFromUrl(argArr[1], paramMap.get(paramName).getName()));
152                     map.put(argArr[0], argArr[1]);
153                     paramMap.get(paramName).setValue(map);
154                     i++;
155                     continue;
156                 }
157
158                 paramMap.get(paramName).setValue(args.get(i + 1));
159
160                 i++;
161                 continue;
162             }
163
164             // it is positional option
165             // Positional arg is missing from the params
166             if (positionalIdx >= positionArgs.size()) {
167                 throw new OnapCliInvalidArgument(
168                         args.get(i),
169                         "No positional argument is defined for this one");
170             }
171
172             paramMap.get(positionArgs.get(positionalIdx)).setValue(args.get(i));
173             positionalIdx++;
174         }
175
176         params.clear();
177         params.addAll(paramMap.values());
178     }
179
180     private static String readJsonStringFromUrl(String input, String argName) throws OnapCliInvalidArgument {
181         ObjectMapper mapper = new ObjectMapper();
182         try {
183             File file = new File(input);
184             if (file.isFile()) {
185                 return mapper.readValue(file, JSONObject.class).toJSONString();
186             } else if (input.startsWith("file:") || input.startsWith("http:") || input.startsWith("ftp:")) {
187                 URL jsonUrl = new URL(input);
188                 return mapper.readValue(jsonUrl, JSONObject.class).toJSONString();
189             } else {
190                 return mapper.readValue(input, JSONObject.class).toJSONString();
191             }
192         } catch (IOException e) {
193             throw new OnapCliInvalidArgument(argName, e);
194         }
195     }
196
197     private static String readTextStringFromUrl(String input, String argName) throws OnapCliInvalidArgument {
198         try {
199             File file = new File(input);
200             if (file.isFile()) {
201                 return FileUtils.readFileToString(file);
202             } else {
203                 return input;
204             }
205
206         } catch (IOException e) {
207             throw new OnapCliInvalidArgument(argName, e);
208         }
209     }
210
211     private static List<String> convertJsonToListString(String arg, String json) throws OnapCliInvalidArgument {
212         TypeReference<List<String>> mapType = new TypeReference<List<String>>() {
213         };
214         try {
215             return new ObjectMapper().readValue(json, mapType);
216         } catch (IOException e) {
217             throw new OnapCliInvalidArgument(arg, e);
218         }
219     }
220
221     private static Map<String, String> convertJsonToMapString(String arg, String json) throws OnapCliInvalidArgument {
222         TypeReference<Map<String, String>> mapType = new TypeReference<Map<String, String>>() {
223         };
224         try {
225             return new ObjectMapper().readValue(json, mapType);
226         } catch (IOException e) {
227             throw new OnapCliInvalidArgument(arg, e);
228         }
229     }
230 }