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;
34 import java.util.ArrayList;
35 import java.util.List;
37 import org.onap.aaf.auth.cmd.mgmt.Mgmt;
38 import org.onap.aaf.auth.cmd.ns.NS;
39 import org.onap.aaf.auth.cmd.perm.Perm;
40 import org.onap.aaf.auth.cmd.role.Role;
41 import org.onap.aaf.auth.cmd.user.User;
42 import org.onap.aaf.auth.common.Define;
43 import org.onap.aaf.auth.env.AuthzEnv;
44 import org.onap.aaf.cadi.Access;
45 import org.onap.aaf.cadi.Access.Level;
46 import org.onap.aaf.cadi.CadiException;
47 import org.onap.aaf.cadi.Locator;
48 import org.onap.aaf.cadi.PropAccess;
49 import org.onap.aaf.cadi.SecuritySetter;
50 import org.onap.aaf.cadi.aaf.v2_0.AAFLocator;
51 import org.onap.aaf.cadi.client.Retryable;
52 import org.onap.aaf.cadi.config.Config;
53 import org.onap.aaf.cadi.config.SecurityInfoC;
54 import org.onap.aaf.cadi.http.HBasicAuthSS;
55 import org.onap.aaf.cadi.http.HMangr;
56 import org.onap.aaf.cadi.sso.AAFSSO;
57 import org.onap.aaf.misc.env.APIException;
59 import jline.console.ConsoleReader;
62 protected static PrintWriter pw;
63 protected HMangr hman;
64 // Storage for last reused client. We can do this
65 // because we're technically "single" threaded calls.
66 public Retryable<?> prevCall;
68 protected SecuritySetter<HttpURLConnection> ss;
69 // protected AuthzEnv env;
70 private boolean close;
71 private List<Cmd> cmds;
74 private ArrayList<Integer> expect = new ArrayList<Integer>();
75 private boolean verbose = true;
77 private SecurityInfoC<HttpURLConnection> si;
78 private boolean request = false;
79 private String force = null;
80 private boolean gui = false;
85 private static int TIMEOUT = Integer.parseInt(Config.AAF_CONN_TIMEOUT_DEF);
86 private static boolean isConsole = false;
87 private static boolean isTest = false;
88 private static boolean showDetails = false;
89 private static boolean ignoreDelay = false;
90 private static int globalDelay=0;
92 public static int timeout() {
96 // Create when only have Access
97 public AAFcli(Access access, Writer wtr, HMangr hman, SecurityInfoC<HttpURLConnection> si, SecuritySetter<HttpURLConnection> ss) throws APIException {
98 this(access,new AuthzEnv(access.getProperties()),wtr,hman, si,ss);
101 public AAFcli(Access access, AuthzEnv env, Writer wtr, HMangr hman, SecurityInfoC<HttpURLConnection> si, SecuritySetter<HttpURLConnection> ss) throws APIException {
103 this.access = access;
107 if (wtr instanceof PrintWriter) {
108 pw = (PrintWriter) wtr;
111 pw = new PrintWriter(wtr);
119 cmds = new ArrayList<Cmd>();
121 Role role = new Role(this);
122 cmds.add(new Help(this, cmds));
123 cmds.add(new Version(this));
124 cmds.add(new Perm(role));
126 cmds.add(new User(this));
127 cmds.add(new NS(this));
128 cmds.add(new Mgmt(this));
131 public void verbose(boolean v) {
135 public void close() {
145 public boolean eval(String line) throws Exception {
146 if (line.length() == 0) {
148 } else if (line.startsWith("#")) {
153 String[] largs = argEval(line);
156 // Variable replacement
157 StringBuilder sb = null;
158 while (idx < largs.length) {
160 for (int v = largs[idx].indexOf("@["); v >= 0; v = largs[idx].indexOf("@[", v + 1)) {
162 sb = new StringBuilder();
164 sb.append(largs[idx], e, v);
165 if ((e = largs[idx].indexOf(']', v)) >= 0) {
166 String p = access.getProperty(largs[idx].substring(v + 2, e),null);
168 p = System.getProperty(largs[idx].substring(v+2,e));
176 if (sb != null && sb.length() > 0) {
177 sb.append(largs[idx], e, largs[idx].length());
178 largs[idx] = sb.toString();
186 while (rv && idx < largs.length) {
187 // Allow Script to change Credential
189 if("as".equalsIgnoreCase(largs[idx])) {
190 if (largs.length > ++idx) {
191 // get Password from Props with ID as Key
192 String user = largs[idx++];
193 int colon = user.indexOf(':');
196 pass = user.substring(colon + 1);
197 user = user.substring(0, colon);
199 pass = access.getProperty(user, null);
202 pass = access.decrypt(pass, false);
203 access.getProperties().put(user, pass);
204 ss = new HBasicAuthSS(si, user, pass);
205 pw.println("as " + user);
206 } else { // get Pass from System Properties, under name of
208 pw.println("ERROR: No password set for " + user);
213 } else if ("expect".equalsIgnoreCase(largs[idx])) {
215 if (largs.length > idx++) {
216 if (!"nothing".equals(largs[idx])) {
217 for (String str : largs[idx].split(",")) {
219 if ("Exception".equalsIgnoreCase(str)) {
222 expect.add(Integer.parseInt(str));
224 } catch (NumberFormatException e) {
225 throw new CadiException("\"expect\" should be followed by Number");
232 // Sleep, typically for reports, to allow DB to update
235 } else if ("sleep".equalsIgnoreCase(largs[idx])) {
236 Integer t = Integer.parseInt(largs[++idx]);
237 pw.println("sleep " + t);
241 } else if ("delay".equalsIgnoreCase(largs[idx])) {
242 delay = Integer.parseInt(largs[++idx]);
243 pw.println("delay " + delay);
246 } else if ("pause".equalsIgnoreCase(largs[idx])) {
247 pw.println("Press <Return> to continue...");
249 // Sonar insists we do something with the string, though it's only a pause. Not very helpful...
250 String sonar = new BufferedReader(new InputStreamReader(System.in)).readLine();
251 sonar=""; // this useless code brought to you by Sonar.
254 } else if ("exit".equalsIgnoreCase(largs[idx])) {
255 pw.println("Exiting...");
261 if("REQUEST".equalsIgnoreCase(largs[idx])) {
264 } else if("FORCE".equalsIgnoreCase(largs[idx])) {
267 } else if("DETAILS".equalsIgnoreCase(largs[idx])) {
270 } else if ("set".equalsIgnoreCase(largs[idx])) {
271 while (largs.length > ++idx) {
272 int equals = largs[idx].indexOf('=');
276 value = access.getProperty(Config.AAF_APPPASS,null);
280 value = access.decrypt(value, false);
284 access.getProperties().put(tag, value);
285 pw.println("set " + tag + " <encrypted>");
288 tag = largs[idx].substring(0, equals);
289 value = largs[idx].substring(++equals);
290 pw.println("set " + tag + ' ' + value);
292 boolean isTrue = "TRUE".equalsIgnoreCase(value);
293 if("FORCE".equalsIgnoreCase(tag)) {
295 } else if("REQUEST".equalsIgnoreCase(tag)) {
297 } else if("DETAILS".equalsIgnoreCase(tag)) {
298 showDetails = isTrue;
300 access.getProperties().put(tag, value);
304 // Allow Script to indicate if Failure is what is expected
309 if (largs[idx].equalsIgnoreCase(c.getName())) {
312 if (expect.size() > 0) {
313 pw.print("** Expect ");
314 boolean first = true;
315 for (Integer i : expect) {
327 ret = c.exec(++idx, largs);
328 if (delay+globalDelay > 0) {
329 Thread.sleep((long)(delay+globalDelay));
331 } catch (Exception e) {
332 if (expect.contains(-1)) {
333 pw.println(e.getMessage());
339 clearSingleLineProperties();
341 rv = expect.isEmpty() ? true : expect.contains(ret);
346 pw.print("!!! Unexpected Return Code: ");
348 pw.println(", VALIDATE OUTPUT!!!");
354 pw.write("Unknown Instruction \"");
355 pw.write(largs[idx]);
357 idx = largs.length;// always end after one command
362 private String[] argEval(String line) {
363 StringBuilder sb = new StringBuilder();
364 ArrayList<String> arr = new ArrayList<String>();
365 boolean start = true;
368 for (int i = 0; i < line.length(); ++i) {
370 if (Character.isWhitespace(ch = line.charAt(i))) {
371 if (start || last==',') {
373 } else if (quote != 0) {
376 arr.add(sb.toString());
380 } else if (ch == '\'' || ch == '"') { // toggle
386 } else if(ch=='|' && quote==0) {
387 arr.add(sb.toString());
396 if (sb.length() > 0) {
397 arr.add(sb.toString());
400 String[] rv = new String[arr.size()];
405 public static void keyboardHelp() {
406 System.out.println("'C-' means hold the ctrl key down while pressing the next key.");
407 System.out.println("'M-' means hold the alt key down while pressing the next key.");
408 System.out.println("For instance, C-b means hold ctrl key and press b, M-b means hold alt and press b\n");
410 System.out.println("Basic Keybindings:");
411 System.out.println("\tC-l - clear screen");
412 System.out.println("\tC-a - beginning of line");
413 System.out.println("\tC-e - end of line");
414 System.out.println("\tC-b - backward character (left arrow also works)");
415 System.out.println("\tM-b - backward word");
416 System.out.println("\tC-f - forward character (right arrow also works)");
417 System.out.println("\tM-f - forward word");
418 System.out.println("\tC-d - delete character under cursor");
419 System.out.println("\tM-d - delete word forward");
420 System.out.println("\tM-backspace - delete word backward");
421 System.out.println("\tC-k - delete from cursor to end of line");
422 System.out.println("\tC-u - delete entire line, regardless of cursor position\n");
424 System.out.println("Command History:");
425 System.out.println("\tC-r - search backward in history (repeating C-r continues the search)");
426 System.out.println("\tC-p - move backwards through history (up arrow also works)");
427 System.out.println("\tC-n - move forwards through history (down arrow also works)\n");
434 public static void main(String[] args) {
438 AAFSSO aafsso = new AAFSSO(args);
440 PropAccess access = aafsso.access();
443 AuthzEnv env = new AuthzEnv(access);
446 boolean exitOnFailure = true;
448 * Check for "-" options anywhere in command line
450 StringBuilder sb = new StringBuilder();
451 for (int i = 0; i < args.length; ++i) {
452 if ("-i".equalsIgnoreCase(args[i])) {
453 rdr = new InputStreamReader(System.in);
454 // } else if("-o".equalsIgnoreCase(args[i])) {
455 // // shall we do something different? Output stream is
457 } else if ("-f".equalsIgnoreCase(args[i])) {
458 if (args.length > i + 1) {
459 rdr = new FileReader(args[++i]);
461 } else if ("-a".equalsIgnoreCase(args[i])) {
462 exitOnFailure = false;
463 } else if ("-c".equalsIgnoreCase(args[i])) {
465 } else if ("-s".equalsIgnoreCase(args[i]) && args.length > i + 1) {
466 access.setProperty(Cmd.STARTDATE, args[++i]);
467 } else if ("-e".equalsIgnoreCase(args[i]) && args.length > i + 1) {
468 access.setProperty(Cmd.ENDDATE, args[++i]);
469 } else if ("-t".equalsIgnoreCase(args[i])) {
471 } else if ("-d".equalsIgnoreCase(args[i])) {
473 } else if ("-n".equalsIgnoreCase(args[i])) {
476 if (sb.length() > 0) {
483 SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(access, HttpURLConnection.class);
486 aafsso.setLogDefault();
487 aafsso.setStdErrDefault();
489 // Note, with AAF Locator, this may not longer be necessary 3/2018 Jonathan
490 if(!aafsso.loginOnly()) {
492 loc = new AAFLocator(si,new URI(access.getProperty(Config.AAF_URL)));
493 } catch (Throwable t) {
494 aafsso.setStdErrDefault();
497 // Other Access is done writing to StdOut and StdErr, reset Std out
498 aafsso.setLogDefault();
501 TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF));
502 HMangr hman = new HMangr(access, loc).readTimeout(TIMEOUT).apiVersion(Config.AAF_DEFAULT_VERSION);
504 if(access.getProperty(Config.AAF_DEFAULT_REALM)==null) {
505 access.setProperty(Config.AAF_DEFAULT_REALM, "people.osaaf.org");
506 aafsso.addProp(Config.AAF_DEFAULT_REALM, "people.osaaf.org");
510 AAFcli aafcli = new AAFcli(access,env, new OutputStreamWriter(System.out), hman, si,
511 new HBasicAuthSS(si,aafsso.user(), access.decrypt(aafsso.enc_pass(),false)));
513 File delay = new File("aafcli.delay");
515 BufferedReader br = new BufferedReader(new FileReader(delay));
517 globalDelay = Integer.parseInt(br.readLine());
518 } catch(Exception e) {
519 access.log(Level.DEBUG,e);
527 System.out.println("Type 'help' for short help or 'help -d' for detailed help with aafcli commands");
528 System.out.println("Type '?' for help with command line editing");
529 System.out.println("Type 'q', 'quit', or 'exit' to quit aafcli\n");
531 ConsoleReader reader = new ConsoleReader();
533 reader.setPrompt("aafcli > ");
536 while ((line = reader.readLine()) != null) {
537 showDetails = (line.contains("-d"))?true:false;
539 if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("q") || line.equalsIgnoreCase("exit")) {
541 } else if (line.equalsIgnoreCase("--help -d") || line.equalsIgnoreCase("help -d")
542 || line.equalsIgnoreCase("help")) {
544 } else if (line.equalsIgnoreCase("cls")) {
545 reader.clearScreen();
547 } else if (line.equalsIgnoreCase("?")) {
554 } catch (Exception e) {
555 pw.println(e.getMessage());
562 } else if (rdr != null) {
563 BufferedReader br = new BufferedReader(rdr);
565 while ((line = br.readLine()) != null) {
566 if (!aafcli.eval(line) && exitOnFailure) {
571 } else { // just run the command line
572 aafcli.verbose(false);
573 if (sb.length() == 0) {
576 rv = aafcli.eval(sb.toString()) ? 0 : 1;
582 // Don't close if No Reader, or it's a Reader of Standard In
583 if (rdr != null && !(rdr instanceof InputStreamReader)) {
591 StringBuilder err = aafsso.err();
592 String noexit = aafsso.access().getProperty("no_exit");
594 err.append("to continue...");
595 System.err.println(err);
602 } catch (MessageException e) {
603 System.out.println("MessageException caught");
605 System.err.println(e.getMessage());
606 } catch (Throwable e) {
607 e.printStackTrace(System.err);
612 public boolean isTest() {
613 return AAFcli.isTest;
616 public boolean isDetailed() {
617 return AAFcli.showDetails;
620 public String typeString(Class<?> cls, boolean json) {
621 return "application/" + cls.getSimpleName() + "+" + (json ? "json" : "xml") + ";version=" + hman.apiVersion();
624 public String forceString() {
628 public boolean addRequest() {
632 public void clearSingleLineProperties() {
638 public void gui(boolean b) {