Update DCAE Startup Info
[aaf/authz.git] / auth / auth-cmd / src / main / java / org / onap / aaf / auth / cmd / Cmd.java
1 /**
2  * ============LICENSE_START====================================================
3  * org.onap.aaf
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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====================================================
19  *
20  */
21
22 package org.onap.aaf.auth.cmd;
23
24 import java.io.PrintWriter;
25 import java.io.StringReader;
26 import java.sql.Date;
27 import java.text.DateFormat;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.Comparator;
31 import java.util.GregorianCalendar;
32 import java.util.List;
33 import java.util.Stack;
34 import java.util.concurrent.ConcurrentHashMap;
35
36 import org.onap.aaf.auth.env.AuthzEnv;
37 import org.onap.aaf.auth.org.OrganizationException;
38 import org.onap.aaf.auth.rserv.HttpMethods;
39 import org.onap.aaf.cadi.Access;
40 import org.onap.aaf.cadi.CadiException;
41 import org.onap.aaf.cadi.LocatorException;
42 import org.onap.aaf.cadi.client.Future;
43 import org.onap.aaf.cadi.client.Rcli;
44 import org.onap.aaf.cadi.client.Retryable;
45 import org.onap.aaf.cadi.config.Config;
46 import org.onap.aaf.cadi.http.HMangr;
47 import org.onap.aaf.misc.env.APIException;
48 import org.onap.aaf.misc.env.Data.TYPE;
49 import org.onap.aaf.misc.env.util.Chrono;
50 import org.onap.aaf.misc.rosetta.env.RosettaDF;
51
52 import aaf.v2_0.Error;
53 import aaf.v2_0.History;
54 import aaf.v2_0.History.Item;
55 import aaf.v2_0.Request;
56
57
58 public abstract class Cmd {
59     // Sonar claims DateFormat is not thread safe.  Leave as Instance Variable.
60     private final DateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
61     protected static final String BLANK = "";
62     protected static final String COMMA = ","; // for use in splits
63
64     protected static final int lineLength = 80;
65
66     private static final String hformat = "%-23s %-5s %-20s %-35s\n";
67
68     public static final String STARTDATE = "startdate";
69     public static final String ENDDATE = "enddate";
70
71     private String name;
72     private final Param[] params;
73     private int required;
74     protected final Cmd parent;
75     protected final List<Cmd> children;
76     private static final ConcurrentHashMap<Class<?>,RosettaDF<?>> dfs = new ConcurrentHashMap<>();
77     public final AAFcli aafcli;
78     protected Access access;
79     private AuthzEnv env;
80     private final String defaultRealm;
81
82     public Cmd(AAFcli aafcli, String name, Param ... params) {
83         this(aafcli,null, name,params);
84     }
85
86     public Cmd(Cmd parent, String name, Param ... params) {
87         this(parent.aafcli,parent, name,params);
88     }
89
90     Cmd(AAFcli aafcli, Cmd parent, String name, Param ... params) {
91         this.parent = parent;
92         this.aafcli = aafcli;
93         this.env = aafcli.env;
94         this.access = aafcli.access;
95         if (parent!=null) {
96             parent.children.add(this);
97         }
98         children = new ArrayList<>();
99         this.params = params;
100         this.name = name;
101         required=0;
102         for (Param p : params) {
103             if (p.required) {
104                 ++required;
105             }
106         }
107
108         String temp = access.getProperty(Config.AAF_DEFAULT_REALM,null);
109         if (temp!=null && !temp.startsWith("@")) {
110             defaultRealm = '@' + temp;
111         } else {
112             defaultRealm="<Set Default Realm>";
113         }
114     }
115
116     public final int exec(int idx, String ... args) throws CadiException, APIException, LocatorException {
117         if (args.length-idx<required) {
118             throw new CadiException(build(new StringBuilder("Too few args: "),null).toString());
119         }
120         return _exec(idx,args);
121     }
122
123     protected abstract int _exec(int idx, final String ... args) throws CadiException, APIException, LocatorException;
124
125     public void detailedHelp(int indent,StringBuilder sb) {
126     }
127
128     protected void detailLine(StringBuilder sb, int length, String s) {
129         multiChar(sb,length,' ',0);
130         sb.append(s);
131     }
132
133     public void apis(int indent,StringBuilder sb) {
134     }
135
136     protected void api(StringBuilder sb, int indent, HttpMethods meth, String pathInfo, Class<?> cls,boolean head) {
137         final String smeth = meth.name();
138         if (head) {
139             sb.append('\n');
140             detailLine(sb,indent,"APIs:");
141         }
142         indent+=2;
143         multiChar(sb,indent,' ',0);
144         sb.append(smeth);
145         sb.append(' ');
146         sb.append(pathInfo);
147         String cliString = aafcli.typeString(cls,true);
148         if (indent+smeth.length()+pathInfo.length()+cliString.length()+2>80) {
149             sb.append(" ...");
150             multiChar(sb,indent+3+smeth.length(),' ',0);
151         } else { // same line
152             sb.append(' ');
153         }
154         sb.append(cliString);
155     }
156
157     protected void multiChar(StringBuilder sb, int length, char c, int indent) {
158         sb.append('\n');
159         for (int i=0;i<indent;++i) {
160             sb.append(' ');
161         }
162         for (int i=indent;i<length;++i) {
163             sb.append(c);
164         }
165     }
166
167     public StringBuilder build(StringBuilder sb, StringBuilder detail) {
168         if (name!=null) {
169             sb.append(name);
170             sb.append(' ');
171         }
172         int line = sb.lastIndexOf("\n")+1;
173         if (line<0) {
174             line=0;
175         }
176         int indent = sb.length()-line;
177         for (Param p : params) {
178             sb.append(p.required?'<':'[');
179             sb.append(p.tag);
180             sb.append(p.required?"> ": "] ");
181         }
182
183         boolean first = true;
184         for (Cmd child : children) {
185             if (!(child instanceof DeprecatedCMD)) {
186                 if (first) {
187                     first = false;
188                 } else if (detail==null) {
189                     multiChar(sb,indent,' ',0);
190                 } else {
191                     // Write parents for Detailed Report
192                     Stack<String> stack = new Stack<>();
193                     for (Cmd c = child.parent;c!=null;c=c.parent) {
194                         if (c.name!=null) {
195                             stack.push(c.name);
196                         }
197                     }
198                     if (!stack.isEmpty()) {
199                         sb.append("  ");
200                         while (!stack.isEmpty()) {
201                             sb.append(stack.pop());
202                             sb.append(' ');
203                         }
204                     }
205                 }
206                 child.build(sb,detail);
207                 if (detail!=null) {
208                     child.detailedHelp(4, detail);
209                     // If Child wrote something, then add, bracketing by lines
210                     if (detail.length()>0) {
211                         multiChar(sb,80,'-',2);
212                         sb.append(detail);
213                         sb.append('\n');
214                         multiChar(sb,80,'-',2);
215                         sb.append('\n');
216                         detail.setLength(0); // reuse
217                     } else {
218                         sb.append('\n');
219                     }
220                 }
221             }
222         }
223         return sb;
224     }
225
226     protected void error(Future<?> future) {
227         StringBuilder sb = new StringBuilder("Failed");
228         String desc = future.body();
229         int code = future.code();
230         if (desc==null || desc.length()==0) {
231             withCode(sb,code);
232         } else if (desc.startsWith("{")) {
233             StringReader sr = new StringReader(desc);
234             try {
235                 // Note: 11-18-2013, JonathanGathman.  This rather convoluted Message Structure required by TSS Restful Specs, reflecting "Northbound" practices.
236                 Error err = getDF(Error.class).newData().in(TYPE.JSON).load(sr).asObject();
237                 sb.append(" [");
238                 sb.append(err.getMessageId());
239                 sb.append("]: ");
240                 String messageBody = err.getText();
241                 List<String> vars = err.getVariables();
242                 int pipe;
243                 for (int varCounter=0;varCounter<vars.size();) {
244                     String var = vars.get(varCounter);
245                     ++varCounter;
246                     if (messageBody.indexOf("%" + varCounter) >= 0) {
247                         if ((pipe = var.indexOf('|'))>=0) {  // In AAF, we use a PIPE for Choice
248                             if (aafcli.isTest()) {
249                                 String expiresStr = var.substring(pipe);
250                                 var = var.replace(expiresStr, "[Placeholder]");
251                             } else {
252                                 StringBuilder varsb = new StringBuilder(var);
253                                 varsb.deleteCharAt(pipe);
254                                 var = varsb.toString();
255                             }
256                             messageBody = messageBody.replace("%" + varCounter, varCounter-1 + ") " + var);
257                         } else {
258                             messageBody = messageBody.replace("%" + varCounter, var);
259                         }
260                     }
261                 }
262                 sb.append(messageBody);
263             } catch (Exception e) {
264                 withCode(sb,code);
265                 sb.append(" (Note: Details cannot be obtained from Error Structure)");
266             }
267         } else if (desc.startsWith("<html>")){ // Core Jetty, etc sends HTML for Browsers
268             withCode(sb,code);
269         } else {
270             sb.append(" with code ");
271             sb.append(code);
272             sb.append(", ");
273             sb.append(desc);
274         }
275         pw().println(sb);
276     }
277
278
279     private void withCode(StringBuilder sb, Integer code) {
280         sb.append(" with code ");
281         sb.append(code);
282         switch(code) {
283             case 401:
284                 sb.append(" (HTTP Not Authenticated)");
285                 break;
286             case 403:
287                 sb.append(" (HTTP Forbidden)");
288                 break;
289             case 404:
290                 sb.append(" (HTTP Not Found)");
291                 break;
292             default:
293         }
294     }
295
296     /**
297      * Consistently set start and end dates from Requests (all derived from Request)
298      * @param req
299      */
300     protected void setStartEnd(Request req) {
301         // Set Start/End Dates, if exist
302         String str;
303         if ((str = access.getProperty(Cmd.STARTDATE,null))!=null) {
304             req.setStart(Chrono.timeStamp(Date.valueOf(str)));
305         }
306
307         if ((str = access.getProperty(Cmd.ENDDATE,null))!=null) {
308             req.setEnd(Chrono.timeStamp(Date.valueOf(str)));
309         }
310     }
311
312     /**
313      * For Derived classes, who have ENV in this parent
314      *
315      * @param cls
316      * @return
317      * @throws APIException
318      */
319     protected <T> RosettaDF<T> getDF(Class<T> cls) throws APIException {
320         return getDF(env,cls);
321     }
322
323     /**
324      * This works well, making available for GUI, etc.
325      * @param env
326      * @param cls
327      * @return
328      * @throws APIException
329      */
330     @SuppressWarnings("unchecked")
331     public static <T> RosettaDF<T> getDF(AuthzEnv env, Class<T> cls) throws APIException {
332         RosettaDF<T> rdf = (RosettaDF<T>)dfs.get(cls);
333         if (rdf == null) {
334             rdf = env.newDataFactory(cls);
335             dfs.put(cls, rdf);
336         }
337         return rdf;
338     }
339
340     public void activity(History history, String header) {
341         if (history.getItem().isEmpty()) {
342             int start = header.indexOf('[');
343             if (start >= 0) {
344                 pw().println("No Activity Found for " + header.substring(start));
345             }
346         } else {
347             pw().println(header);
348             for (int i=0;i<lineLength;++i) {
349                 pw().print('-');
350             }
351             pw().println();
352
353             pw().format(hformat,"Date","Table","User","Memo");
354             for (int i=0;i<lineLength;++i) {
355                 pw().print('-');
356             }
357             pw().println();
358
359             // Save Server time by Sorting locally
360             List<Item> items = history.getItem();
361             java.util.Collections.sort(items, (Comparator<Item>) (o1, o2) -> o2.getTimestamp().compare(o1.getTimestamp()));
362
363             for (History.Item item : items) {
364                 GregorianCalendar gc = item.getTimestamp().toGregorianCalendar();
365                 pw().format(hformat,
366                     dateFmt.format(gc.getTime()),
367                     item.getTarget(),
368                     item.getUser(),
369                     item.getMemo());
370             }
371         }
372     }
373
374     /**
375      * Turn String Array into a | delimited String
376      * @param options
377      * @return
378      */
379     public static String optionsToString(String[] options) {
380         StringBuilder sb = new StringBuilder();
381         boolean first = true;
382         for (String s : options) {
383             if (first) {
384                 first = false;
385             } else {
386                 sb.append('|');
387             }
388             sb.append(s);
389         }
390         return sb.toString();
391     }
392
393     /**
394      * return which index number the Option matches.
395      *
396      * throws an Exception if not part of this Option Set
397      *
398      * @param options
399      * @param test
400      * @return
401      * @throws Exception
402      */
403     public int whichOption(String[] options, String test) throws CadiException {
404         for (int i=0;i<options.length;++i) {
405             if (options[i].equals(test)) {
406                 return i;
407             }
408         }
409         pw().printf("%s is not a valid cmd\n",test);
410         throw new CadiException(build(new StringBuilder("Invalid Option: "),null).toString());
411     }
412
413     protected HMangr hman() {
414         return aafcli.hman;
415     }
416
417     public<RET> RET same(Retryable<RET> retryable) throws APIException, CadiException, LocatorException {
418         // We're storing in AAFCli, because we know it's always the same, and single threaded
419         if (aafcli.prevCall!=null) {
420             retryable.item(aafcli.prevCall.item());
421             retryable.lastClient=aafcli.prevCall.lastClient;
422         }
423
424         RET ret = aafcli.hman.same(aafcli.ss,retryable);
425
426         // Store last call in AAFcli, because Cmds are all different instances.
427         aafcli.prevCall = retryable;
428         return ret;
429     }
430
431     public<RET> RET all(Retryable<RET> retryable) throws APIException, CadiException, LocatorException {
432         this.setQueryParamsOn(retryable.lastClient);
433         return aafcli.hman.all(aafcli.ss,retryable);
434     }
435
436     public<RET> RET oneOf(Retryable<RET> retryable,String host) throws APIException, CadiException, LocatorException {
437         this.setQueryParamsOn(retryable.lastClient);
438         return aafcli.hman.oneOf(aafcli.ss,retryable,true,host);
439     }
440
441     protected PrintWriter pw() {
442         return AAFcli.pw;
443     }
444
445     public String getName() {
446         return name;
447     }
448
449     public void reportHead(String ... str) {
450         pw().println();
451         boolean first = true;
452         int i=0;
453         for (String s : str) {
454             if (first) {
455                 if (++i>1) {
456                     first = false;
457                     pw().print("[");
458                 }
459             } else {
460                 pw().print("] [");
461             }
462             pw().print(s);
463         }
464         if (!first) {
465             pw().print(']');
466         }
467         pw().println();
468         reportLine();
469     }
470
471     public String reportColHead(String format, String ...  args) {
472         pw().format(format,(Object[])args);
473         reportLine();
474         return format;
475     }
476
477     public void reportLine() {
478         for (int i=0;i<lineLength;++i) {
479             pw().print('-');
480         }
481         pw().println();
482     }
483
484     protected void setQueryParamsOn(Rcli<?> rcli) {
485         StringBuilder sb=null;
486         String force;
487         if ((force=aafcli.forceString())!=null) {
488             sb = new StringBuilder("force=");
489             sb.append(force);
490         }
491         if (aafcli.addRequest()) {
492             if (sb==null) {
493                 sb = new StringBuilder("future=true");
494             } else {
495                 sb.append("&future=true");
496             }
497         }
498         if (sb!=null && rcli!=null) {
499             rcli.setQueryParams(sb.toString());
500         }
501     }
502 //
503 //    /**
504 //     * If Force is set, will return True once only, then revert to "FALSE".
505 //     *
506 //     * @return
507 //     */
508 //    protected String checkForce() {
509 //        if (TRUE.equalsIgnoreCase(env.getProperty(FORCE, FALSE))) {
510 //            env.setProperty(FORCE, FALSE);
511 //            return "true";
512 //        }
513 //        return FALSE;
514 //    }
515
516     public String toString() {
517         StringBuilder sb = new StringBuilder();
518         if (parent==null) { // ultimate parent
519             build(sb,null);
520             return sb.toString();
521         } else {
522             return parent.toString();
523         }
524     }
525
526     /**
527      * Appends shortID with Realm, but only when allowed by Organization
528      * @throws OrganizationException
529      */
530     public String fullID(String id) {
531         if (id != null) {
532             if (id.indexOf('@') < 0) {
533                 id+=defaultRealm;
534             } else {
535                 return id; // is already a full ID
536             }
537         }
538         return id;
539     }
540 }