aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/main/java/org/onap/cli/main/utils/OnapCliArgsParser.java
blob: 123521bf9d499eca8f21c151d10ec353ae43ce6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
 * Copyright 2017 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.cli.main.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.onap.cli.fw.error.OnapCommandException;
import org.onap.cli.fw.error.OnapCommandInvalidParameterValue;
import org.onap.cli.fw.input.OnapCommandParameter;
import org.onap.cli.fw.input.OnapCommandParameterType;
import org.onap.cli.main.error.OnapCliArgumentValueMissing;
import org.onap.cli.main.error.OnapCliInvalidArgument;
import com.esotericsoftware.yamlbeans.YamlReader;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

import java.io.Reader;
import java.io.InputStreamReader;
import java.io.FileReader;

/**
 * Oclip CLI utilities.
 *
 */
public class OnapCliArgsParser {
    private static Gson gson = new GsonBuilder().serializeNulls().create();

    /**
     * private Constructor.
     */
    private OnapCliArgsParser() {

    }

    /**
     * It read thru the args and populate the given params for short optional, long option and postional args the idx of
     * positional args, is calculated based on the position at which it present in the params and args.
     *
     * @param params
     *            List of command paramters
     * @param args
     *            Array of arguments
     * @throws OnapCliArgumentValueMissing
     *             ArgumentValueMissing exception
     * @throws OnapCliInvalidArgument
     *             Invalid argument exception
     * @throws OnapCommandInvalidParameterValue
     *             exception
     */
    public static void populateParams(Set<OnapCommandParameter> params, List<String> args)
            throws OnapCommandException {
        Map<String, String> shortOptionMap = new HashMap<>();
        Map<String, String> longOptionMap = new HashMap<>();
        List<String> positionArgs = new ArrayList<>();
        Map<String, OnapCommandParameter> paramMap = new HashMap<>();

        for (OnapCommandParameter param : params) {
            boolean positional = true;
            if (param.getShortOption() != null) {
                shortOptionMap.put(OnapCommandParameter.printShortOption(param.getShortOption()), param.getName());
                positional = false;
            }
            if (param.getLongOption() != null) {
                longOptionMap.put(OnapCommandParameter.printLongOption(param.getLongOption()), param.getName());
                positional = false;
            }

            if (positional) {
                positionArgs.add(param.getName());
            }

            paramMap.put(param.getName(), param);
        }

        int positionalIdx = 0;
        for (int i = 0; i < args.size(); i++) {
            String paramName = null;
            if (shortOptionMap.containsKey(args.get(i))) {
                paramName = shortOptionMap.get(args.get(i));
            } else if (longOptionMap.containsKey(args.get(i))) {
                paramName = longOptionMap.get(args.get(i));
            }

            if (paramName != null) {
                // end of the list or if its option rather than a value
                if ((i + 1) == args.size() || args.get(i + 1).startsWith("-")) {
                    if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.BOOL)) {
                        paramMap.get(paramName).setValue(true);
                        continue;
                    }
                    throw new OnapCliArgumentValueMissing(args.get(i));
                }

                if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.JSON)) {
                    paramMap.get(paramName).setValue(readJsonStringFromUrl(args.get(i + 1),
                            paramMap.get(paramName).getName()));
                    i++;
                    continue;

                } else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.TEXT)) {
                    paramMap.get(paramName).setValue(readTextStringFromUrl(args.get(i + 1),
                            paramMap.get(paramName).getName()));
                    i++;
                    continue;

                } else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.YAML)) {
                    String value = readYamlStringFromUrl(args.get(i + 1),
                            paramMap.get(paramName).getName());
                    paramMap.get(paramName).setValue(value);
                    i++;
                    continue;

                } else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.BYTE)) {
                    paramMap.get(paramName).setValue(readBytesFromUrl(args.get(i + 1),
                            paramMap.get(paramName).getName()));
                    i++;
                    continue;

                } else if (paramMap.get(paramName).getParameterType()
                        .equals(OnapCommandParameterType.ARRAY)) {
                    Object value = paramMap.get(paramName).getValue();
                    List<String> list = (List<String>) value;

                    list.add(readTextStringFromUrl(args.get(i + 1), paramMap.get(paramName).getName()));
                    paramMap.get(paramName).setValue(list);
                    i++;
                    continue;

                } else if (paramMap.get(paramName).getParameterType()
                        .equals(OnapCommandParameterType.MAP)) {
                    Object value = paramMap.get(paramName).getValue();

                    Map<String, String> map = (Map<String, String>) value;

                    String arg = args.get(i + 1);
                    String[] argArr = arg.split("=", 2);

                    if (argArr.length != 2) {
                        throw new OnapCliInvalidArgument(
                                paramMap.get(paramName).getName(),
                                "it should be in the form of <key>=<value>");
                    }

                    map.put(argArr[0], argArr[1]);
                    paramMap.get(paramName).setValue(map);
                    i++;
                    continue;
                }

                paramMap.get(paramName).setValue(args.get(i + 1));

                i++;
                continue;
            }

            // it is positional option
            // Positional arg is missing from the params
            if (positionalIdx >= positionArgs.size()) {
                throw new OnapCliInvalidArgument(
                        args.get(i),
                        "No positional argument is defined for this one");
            }

            paramMap.get(positionArgs.get(positionalIdx)).setValue(args.get(i));
            positionalIdx++;
        }

        params.clear();
        params.addAll(paramMap.values());
    }

    public static String readJsonStringFromUrl(String input, String argName) throws OnapCliInvalidArgument {
        String jsonValue;
        try {
            File file = new File(input);
            if (file.isFile()) {
                try(Reader reader = new FileReader(file)){
                    jsonValue = gson.fromJson(reader, JsonElement.class).toString();
                }
                return jsonValue;
            } else if (input.startsWith("file:") || input.startsWith("http:") || input.startsWith("ftp:")) {
                URL jsonUrl = new URL(input);
                try(Reader reader = new InputStreamReader(jsonUrl.openStream())){
                    jsonValue = gson.fromJson(reader, JsonElement.class).toString();
                }
                return jsonValue;
            } else {
                return gson.fromJson(input, JsonElement.class).toString();
            }
        } catch (Exception e) { // NOSONAR
            throw new OnapCliInvalidArgument(argName, e);
        }
    }

    public static String readTextStringFromUrl(String input, String argName) throws OnapCliInvalidArgument {
        try {
            File file = new File(input);
            if (file.isFile()) {
                return FileUtils.readFileToString(file, (Charset) null);
            } else {
                return input;
            }

        } catch (IOException e) {
            throw new OnapCliInvalidArgument(argName, e);
        }
    }

    public static String readYamlStringFromUrl(String input, String argName) throws OnapCliInvalidArgument {
        try {
            File file = new File(input);
            if (file.isFile()) {
                String value = FileUtils.readFileToString(file, (Charset) null);
                YamlReader reader = new YamlReader(value);
                value = (String) reader.read();
                return value;
            } else {
                return input;
            }

        } catch (IOException e) {
            throw new OnapCliInvalidArgument(argName, e);
        }
    }

    public static String readBytesFromUrl(String input, String argName) throws OnapCliInvalidArgument {
        try {
            File file = new File(input);
            if (file.isFile()) {
                byte[] encodeBase64 = Base64.encodeBase64(FileUtils.readFileToByteArray(file));
                return new String(encodeBase64);
            } else {
                byte[] encodeBase64 = Base64.encodeBase64(input.getBytes());
                return new String(encodeBase64);
            }
        } catch (IOException e) {
            throw new OnapCliInvalidArgument(argName, e);
        }
    }

    public static List<String> convertJsonToListString(String arg, String json) throws OnapCliInvalidArgument {
        TypeToken<List<String>> mapType = new TypeToken<List<String>>() {
        };
        try {
            return gson.fromJson(json, mapType.getType());
        } catch (Exception e) { // NOSONAR
            throw new OnapCliInvalidArgument(arg, e);
        }
    }

    public static Map<String, String> convertJsonToMapString(String arg, String json) throws OnapCliInvalidArgument {
        TypeToken<Map<String, String>> mapType = new TypeToken<Map<String, String>>() {
        };
        try {
            return gson.fromJson(json, mapType.getType());
        } catch (Exception e) { // NOSONAR
            throw new OnapCliInvalidArgument(arg, e);
        }
    }
}