2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.auth.cmd;
24 import java.io.BufferedReader;
26 import java.io.FileReader;
27 import java.io.InputStreamReader;
28 import java.io.OutputStreamWriter;
29 import java.io.PrintWriter;
30 import java.io.Reader;
31 import java.io.Writer;
32 import java.net.HttpURLConnection;
33 import java.util.ArrayList;
34 import java.util.List;
36 import org.onap.aaf.auth.cmd.mgmt.Mgmt;
37 import org.onap.aaf.auth.cmd.ns.NS;
38 import org.onap.aaf.auth.cmd.perm.Perm;
39 import org.onap.aaf.auth.cmd.role.Role;
40 import org.onap.aaf.auth.cmd.user.User;
41 import org.onap.aaf.auth.common.Define;
42 import org.onap.aaf.auth.env.AuthzEnv;
43 import org.onap.aaf.cadi.Access;
44 import org.onap.aaf.cadi.Access.Level;
45 import org.onap.aaf.cadi.CadiException;
46 import org.onap.aaf.cadi.PropAccess;
47 import org.onap.aaf.cadi.SecuritySetter;
48 import org.onap.aaf.cadi.aaf.v2_0.AAFConHttp;
49 import org.onap.aaf.cadi.client.Retryable;
50 import org.onap.aaf.cadi.config.Config;
51 import org.onap.aaf.cadi.config.SecurityInfoC;
52 import org.onap.aaf.cadi.http.HBasicAuthSS;
53 import org.onap.aaf.cadi.http.HMangr;
54 import org.onap.aaf.cadi.sso.AAFSSO;
55 import org.onap.aaf.misc.env.APIException;
57 import jline.console.ConsoleReader;
60 protected static PrintWriter pw;
61 protected HMangr hman;
62 // Storage for last reused client. We can do this
63 // because we're technically "single" threaded calls.
64 public Retryable<?> prevCall;
66 protected SecuritySetter<HttpURLConnection> ss;
67 // protected AuthzEnv env;
68 private boolean close;
69 private List<Cmd> cmds;
72 private ArrayList<Integer> expect = new ArrayList<>();
73 private boolean verbose = true;
75 private SecurityInfoC<HttpURLConnection> si;
76 private boolean request = false;
77 private String force = null;
78 private boolean gui = false;
83 private static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF);
84 private static boolean isConsole = false;
85 private static boolean isTest = false;
86 private static boolean showDetails = false;
87 private static boolean ignoreDelay = false;
88 private static int globalDelay=0;
90 public static int timeout() {
94 // Create when only have Access
95 public AAFcli(Access access, Writer wtr, HMangr hman, SecurityInfoC<HttpURLConnection> si, SecuritySetter<HttpURLConnection> ss) throws APIException, CadiException {
96 this(access,new AuthzEnv(access.getProperties()),wtr,hman, si,ss);
99 public AAFcli(Access access, AuthzEnv env, Writer wtr, HMangr hman, SecurityInfoC<HttpURLConnection> si, SecuritySetter<HttpURLConnection> ss) throws APIException, CadiException {
101 this.access = access;
105 if (wtr instanceof PrintWriter) {
106 pw = (PrintWriter) wtr;
109 pw = new PrintWriter(wtr);
116 cmds = new ArrayList<>();
118 Role role = new Role(this);
119 cmds.add(new Help(this, cmds));
120 cmds.add(new Version(this));
121 cmds.add(new Perm(role));
123 cmds.add(new User(this));
124 cmds.add(new NS(this));
125 cmds.add(new Mgmt(this));
128 public void verbose(boolean v) {
132 public void close() {
133 // if (hman != null) {
142 public boolean eval(String line) throws Exception {
143 if (line.length() == 0) {
145 } else if (line.startsWith("#")) {
150 String[] largs = argEval(line);
153 // Variable replacement
154 StringBuilder sb = null;
155 while (idx < largs.length) {
157 for (int v = largs[idx].indexOf("@["); v >= 0; v = largs[idx].indexOf("@[", v + 1)) {
159 sb = new StringBuilder();
161 sb.append(largs[idx], e, v);
162 if ((e = largs[idx].indexOf(']', v)) >= 0) {
163 String p = access.getProperty(largs[idx].substring(v + 2, e),null);
165 p = System.getProperty(largs[idx].substring(v+2,e));
173 if (sb != null && sb.length() > 0) {
174 sb.append(largs[idx], e, largs[idx].length());
175 largs[idx] = sb.toString();
183 while (rv && idx < largs.length) {
184 // Allow Script to change Credential
186 if ("as".equalsIgnoreCase(largs[idx])) {
187 if (largs.length > ++idx) {
188 // get Password from Props with ID as Key
189 String user = largs[idx++];
190 int colon = user.indexOf(':');
193 pass = user.substring(colon + 1);
194 user = user.substring(0, colon);
196 pass = access.getProperty(user, null);
199 pass = access.decrypt(pass, false);
200 access.getProperties().put(user, pass);
201 ss=new HBasicAuthSS(si, user, pass);
202 pw.println("as " + user);
203 } else { // get Pass from System Properties, under name of
205 pw.println("ERROR: No password set for " + user);
210 } else if ("expect".equalsIgnoreCase(largs[idx])) {
212 if (largs.length > idx++) {
213 if (!"nothing".equals(largs[idx])) {
214 for (String str : largs[idx].split(",")) {
216 if ("Exception".equalsIgnoreCase(str)) {
219 expect.add(Integer.parseInt(str));
221 } catch (NumberFormatException e) {
222 throw new CadiException("\"expect\" should be followed by Number");
229 // Sleep, typically for reports, to allow DB to update
232 } else if ("sleep".equalsIgnoreCase(largs[idx])) {
233 Integer t = Integer.parseInt(largs[++idx]);
234 pw.println("sleep " + t);
238 } else if ("delay".equalsIgnoreCase(largs[idx])) {
239 delay = Integer.parseInt(largs[++idx]);
240 pw.println("delay " + delay);
243 } else if ("pause".equalsIgnoreCase(largs[idx])) {
244 pw.println("Press <Return> to continue...");
246 // Sonar insists we do something with the string, though it's only a pause. Not very helpful...
247 String sonar = new BufferedReader(new InputStreamReader(System.in)).readLine();
248 sonar=""; // this useless code brought to you by Sonar.
251 } else if ("exit".equalsIgnoreCase(largs[idx])) {
252 pw.println("Exiting...");
254 } else if ("set".equalsIgnoreCase(largs[idx])) {
255 while (largs.length > ++idx) {
256 int equals = largs[idx].indexOf('=');
260 value = access.getProperty(Config.AAF_APPPASS,null);
264 value = access.decrypt(value, false);
268 access.getProperties().put(tag, value);
269 pw.println("set " + tag + " <encrypted>");
272 tag = largs[idx].substring(0, equals);
273 value = largs[idx].substring(++equals);
274 pw.println("set " + tag + ' ' + value);
276 boolean isTrue = "TRUE".equalsIgnoreCase(value);
277 if ("FORCE".equalsIgnoreCase(tag)) {
279 } else if ("REQUEST".equalsIgnoreCase(tag)) {
281 } else if ("DETAILS".equalsIgnoreCase(tag)) {
282 showDetails = isTrue;
284 access.getProperties().put(tag, value);
288 // Allow Script to indicate if Failure is what is expected
293 if ("REQUEST".equalsIgnoreCase(largs[idx])) {
296 } else if ("FORCE".equalsIgnoreCase(largs[idx])) {
299 } else if ("DETAILS".equalsIgnoreCase(largs[idx])) {
306 if (largs[idx].equalsIgnoreCase(c.getName())) {
309 if (expect.size() > 0) {
310 pw.print("** Expect ");
311 boolean first = true;
312 for (Integer i : expect) {
324 ret = c.exec(++idx, largs);
325 if (delay+globalDelay > 0) {
326 Thread.sleep((long)(delay+globalDelay));
328 } catch (Exception e) {
329 if (expect.contains(-1)) {
330 pw.println(e.getMessage());
336 clearSingleLineProperties();
338 rv = expect.isEmpty() ? true : expect.contains(ret);
343 pw.print("!!! Unexpected Return Code: ");
345 pw.println(", VALIDATE OUTPUT!!!");
351 pw.write("Unknown Instruction \"");
352 pw.write(largs[idx]);
354 idx = largs.length;// always end after one command
359 private String[] argEval(String line) {
360 StringBuilder sb = new StringBuilder();
361 ArrayList<String> arr = new ArrayList<>();
362 boolean start = true;
365 for (int i = 0; i < line.length(); ++i) {
367 if (Character.isWhitespace(ch = line.charAt(i))) {
368 if (start || last==',') {
370 } else if (quote != 0) {
373 arr.add(sb.toString());
377 } else if (ch == '\'' || ch == '"') { // toggle
383 } else if (ch=='|' && quote==0) {
384 arr.add(sb.toString());
393 if (sb.length() > 0) {
394 arr.add(sb.toString());
397 String[] rv = new String[arr.size()];
402 public static void keyboardHelp() {
403 System.out.println("'C-' means hold the ctrl key down while pressing the next key.");
404 System.out.println("'M-' means hold the alt key down while pressing the next key.");
405 System.out.println("For instance, C-b means hold ctrl key and press b, M-b means hold alt and press b\n");
407 System.out.println("Basic Keybindings:");
408 System.out.println("\tC-l - clear screen");
409 System.out.println("\tC-a - beginning of line");
410 System.out.println("\tC-e - end of line");
411 System.out.println("\tC-b - backward character (left arrow also works)");
412 System.out.println("\tM-b - backward word");
413 System.out.println("\tC-f - forward character (right arrow also works)");
414 System.out.println("\tM-f - forward word");
415 System.out.println("\tC-d - delete character under cursor");
416 System.out.println("\tM-d - delete word forward");
417 System.out.println("\tM-backspace - delete word backward");
418 System.out.println("\tC-k - delete from cursor to end of line");
419 System.out.println("\tC-u - delete entire line, regardless of cursor position\n");
421 System.out.println("Command History:");
422 System.out.println("\tC-r - search backward in history (repeating C-r continues the search)");
423 System.out.println("\tC-p - move backwards through history (up arrow also works)");
424 System.out.println("\tC-n - move forwards through history (down arrow also works)\n");
431 public static void main(String[] args) {
435 AAFSSO aafsso = new AAFSSO(args);
436 String noexit = aafsso.access().getProperty("no_exit");
438 PropAccess access = aafsso.access();
442 AuthzEnv env = new AuthzEnv(access);
445 boolean exitOnFailure = true;
447 * Check for "-" options anywhere in command line
449 StringBuilder sb = new StringBuilder();
450 for (int i = 0; i < args.length; ++i) {
451 if ("-i".equalsIgnoreCase(args[i])) {
452 rdr = new InputStreamReader(System.in);
453 // } else if ("-o".equalsIgnoreCase(args[i])) {
454 // // shall we do something different? Output stream is
456 } else if ("-f".equalsIgnoreCase(args[i])) {
457 if (args.length > i + 1) {
458 rdr = new FileReader(args[++i]);
460 } else if ("-a".equalsIgnoreCase(args[i])) {
461 exitOnFailure = false;
462 } else if ("-c".equalsIgnoreCase(args[i])) {
464 } else if ("-s".equalsIgnoreCase(args[i]) && args.length > i + 1) {
465 access.setProperty(Cmd.STARTDATE, args[++i]);
466 } else if ("-e".equalsIgnoreCase(args[i]) && args.length > i + 1) {
467 access.setProperty(Cmd.ENDDATE, args[++i]);
468 } else if ("-t".equalsIgnoreCase(args[i])) {
470 } else if ("-d".equalsIgnoreCase(args[i])) {
472 } else if ("-n".equalsIgnoreCase(args[i])) {
475 if (sb.length() > 0) {
482 AAFConHttp aafcon = new AAFConHttp(access);
484 // SecurityInfoC<?> si = aafcon.securityInfo();
487 aafsso.setLogDefault();
488 aafsso.setStdErrDefault();
490 // Note, with AAF Locator, this may not longer be necessary 3/2018 Jonathan
491 if (!aafsso.loginOnly()) {
493 // loc = new AAFLocator(si,new URI(access.getProperty(Config.AAF_URL)));
494 // } catch (Throwable t) {
495 // aafsso.setStdErrDefault();
498 // // Other Access is done writing to StdOut and StdErr, reset Std out
499 // aafsso.setLogDefault();
502 TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF));
503 // HMangr hman = new HMangr(access, loc).readTimeout(TIMEOUT).apiVersion(Config.AAF_DEFAULT_API_VERSION);
505 if (access.getProperty(Config.AAF_DEFAULT_REALM)==null) {
506 access.setProperty(Config.AAF_DEFAULT_REALM, "people.osaaf.org");
507 aafsso.addProp(Config.AAF_DEFAULT_REALM, "people.osaaf.org");
510 AAFcli aafcli = new AAFcli(access,env, new OutputStreamWriter(System.out),
511 aafcon.hman(), aafcon.securityInfo(), aafcon.securityInfo().defSS);
512 // new HBasicAuthSS(si,aafsso.user(), access.decrypt(aafsso.enc_pass(),false)));
515 File delay = new File("aafcli.delay");
516 if (delay.exists()) {
517 BufferedReader br = new BufferedReader(new FileReader(delay));
519 globalDelay = Integer.parseInt(br.readLine());
520 } catch (Exception e) {
521 access.log(Level.DEBUG,e);
529 System.out.println("Type 'help' for short help or 'help -d' for detailed help with aafcli commands");
530 System.out.println("Type '?' for help with command line editing");
531 System.out.println("Type 'q', 'quit', or 'exit' to quit aafcli\n");
533 ConsoleReader reader = new ConsoleReader();
535 reader.setPrompt("aafcli > ");
538 while ((line = reader.readLine()) != null) {
539 showDetails = (line.contains("-d"))?true:false;
541 if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("q") || line.equalsIgnoreCase("exit")) {
543 } else if (line.equalsIgnoreCase("--help -d") || line.equalsIgnoreCase("help -d")
544 || line.equalsIgnoreCase("help")) {
546 } else if (line.equalsIgnoreCase("cls")) {
547 reader.clearScreen();
549 } else if (line.equalsIgnoreCase("?")) {
556 } catch (Exception e) {
557 pw.println(e.getMessage());
564 } else if (rdr != null) {
565 BufferedReader br = new BufferedReader(rdr);
567 while ((line = br.readLine()) != null) {
568 if (!aafcli.eval(line) && exitOnFailure) {
573 } else { // just run the command line
574 aafcli.verbose(false);
575 if (sb.length() == 0) {
578 rv = aafcli.eval(sb.toString()) ? 0 : 1;
584 // Don't close if No Reader, or it's a Reader of Standard In
585 if (rdr != null && !(rdr instanceof InputStreamReader)) {
593 StringBuilder err = aafsso.err();
595 err.append("to continue...");
596 System.err.println(err);
604 } catch (MessageException e) {
605 System.out.println("MessageException caught");
607 System.err.println(e.getMessage());
608 } catch (Exception e) {
609 e.printStackTrace(System.err);
614 public boolean isTest() {
615 return AAFcli.isTest;
618 public boolean isDetailed() {
619 return AAFcli.showDetails;
622 public String typeString(Class<?> cls, boolean json) {
623 return "application/" + cls.getSimpleName() + "+" + (json ? "json" : "xml");//+ ";version=" + hman.apiVersion();
626 public String forceString() {
630 public boolean addRequest() {
634 public void clearSingleLineProperties() {
640 public void gui(boolean b) {