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.PrintWriter;
25 import java.io.StringReader;
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;
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;
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;
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
64 protected static final int lineLength = 80;
66 private static final String hformat = "%-23s %-5s %-20s %-35s\n";
68 public static final String STARTDATE = "startdate";
69 public static final String ENDDATE = "enddate";
72 private final Param[] params;
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;
80 private final String defaultRealm;
82 public Cmd(AAFcli aafcli, String name, Param ... params) {
83 this(aafcli,null, name,params);
86 public Cmd(Cmd parent, String name, Param ... params) {
87 this(parent.aafcli,parent, name,params);
90 Cmd(AAFcli aafcli, Cmd parent, String name, Param ... params) {
93 this.env = aafcli.env;
94 this.access = aafcli.access;
96 parent.children.add(this);
98 children = new ArrayList<>();
102 for (Param p : params) {
108 String temp = access.getProperty(Config.AAF_DEFAULT_REALM,null);
109 if (temp!=null && !temp.startsWith("@")) {
110 defaultRealm = '@' + temp;
112 defaultRealm="<Set Default Realm>";
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());
120 return _exec(idx,args);
123 protected abstract int _exec(int idx, final String ... args) throws CadiException, APIException, LocatorException;
125 public void detailedHelp(int indent,StringBuilder sb) {
128 protected void detailLine(StringBuilder sb, int length, String s) {
129 multiChar(sb,length,' ',0);
133 public void apis(int indent,StringBuilder sb) {
136 protected void api(StringBuilder sb, int indent, HttpMethods meth, String pathInfo, Class<?> cls,boolean head) {
137 final String smeth = meth.name();
140 detailLine(sb,indent,"APIs:");
143 multiChar(sb,indent,' ',0);
147 String cliString = aafcli.typeString(cls,true);
148 if (indent+smeth.length()+pathInfo.length()+cliString.length()+2>80) {
150 multiChar(sb,indent+3+smeth.length(),' ',0);
151 } else { // same line
154 sb.append(cliString);
157 protected void multiChar(StringBuilder sb, int length, char c, int indent) {
159 for (int i=0;i<indent;++i) {
162 for (int i=indent;i<length;++i) {
167 public StringBuilder build(StringBuilder sb, StringBuilder detail) {
172 int line = sb.lastIndexOf("\n")+1;
176 int indent = sb.length()-line;
177 for (Param p : params) {
178 sb.append(p.required?'<':'[');
180 sb.append(p.required?"> ": "] ");
183 boolean first = true;
184 for (Cmd child : children) {
185 if (!(child instanceof DeprecatedCMD)) {
188 } else if (detail==null) {
189 multiChar(sb,indent,' ',0);
191 // Write parents for Detailed Report
192 Stack<String> stack = new Stack<>();
193 for (Cmd c = child.parent;c!=null;c=c.parent) {
198 if (!stack.isEmpty()) {
200 while (!stack.isEmpty()) {
201 sb.append(stack.pop());
206 child.build(sb,detail);
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);
214 multiChar(sb,80,'-',2);
216 detail.setLength(0); // reuse
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) {
232 } else if (desc.startsWith("{")) {
233 StringReader sr = new StringReader(desc);
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();
238 sb.append(err.getMessageId());
240 String messageBody = err.getText();
241 List<String> vars = err.getVariables();
243 for (int varCounter=0;varCounter<vars.size();) {
244 String var = vars.get(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]");
252 StringBuilder varsb = new StringBuilder(var);
253 varsb.deleteCharAt(pipe);
254 var = varsb.toString();
256 messageBody = messageBody.replace("%" + varCounter, varCounter-1 + ") " + var);
258 messageBody = messageBody.replace("%" + varCounter, var);
262 sb.append(messageBody);
263 } catch (Exception e) {
265 sb.append(" (Note: Details cannot be obtained from Error Structure)");
267 } else if (desc.startsWith("<html>")){ // Core Jetty, etc sends HTML for Browsers
270 sb.append(" with code ");
279 private void withCode(StringBuilder sb, Integer code) {
280 sb.append(" with code ");
284 sb.append(" (HTTP Not Authenticated)");
287 sb.append(" (HTTP Forbidden)");
290 sb.append(" (HTTP Not Found)");
297 * Consistently set start and end dates from Requests (all derived from Request)
300 protected void setStartEnd(Request req) {
301 // Set Start/End Dates, if exist
303 if ((str = access.getProperty(Cmd.STARTDATE,null))!=null) {
304 req.setStart(Chrono.timeStamp(Date.valueOf(str)));
307 if ((str = access.getProperty(Cmd.ENDDATE,null))!=null) {
308 req.setEnd(Chrono.timeStamp(Date.valueOf(str)));
313 * For Derived classes, who have ENV in this parent
317 * @throws APIException
319 protected <T> RosettaDF<T> getDF(Class<T> cls) throws APIException {
320 return getDF(env,cls);
324 * This works well, making available for GUI, etc.
328 * @throws APIException
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);
334 rdf = env.newDataFactory(cls);
340 public void activity(History history, String header) {
341 if (history.getItem().isEmpty()) {
342 int start = header.indexOf('[');
344 pw().println("No Activity Found for " + header.substring(start));
347 pw().println(header);
348 for (int i=0;i<lineLength;++i) {
353 pw().format(hformat,"Date","Table","User","Memo");
354 for (int i=0;i<lineLength;++i) {
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()));
363 for (History.Item item : items) {
364 GregorianCalendar gc = item.getTimestamp().toGregorianCalendar();
366 dateFmt.format(gc.getTime()),
375 * Turn String Array into a | delimited String
379 public static String optionsToString(String[] options) {
380 StringBuilder sb = new StringBuilder();
381 boolean first = true;
382 for (String s : options) {
390 return sb.toString();
394 * return which index number the Option matches.
396 * throws an Exception if not part of this Option Set
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)) {
409 throw new CadiException(build(new StringBuilder("Invalid Option: "),null).toString());
412 protected HMangr hman() {
416 public<RET> RET same(Retryable<RET> retryable) throws APIException, CadiException, LocatorException {
417 // We're storing in AAFCli, because we know it's always the same, and single threaded
418 if (aafcli.prevCall!=null) {
419 retryable.item(aafcli.prevCall.item());
420 retryable.lastClient=aafcli.prevCall.lastClient;
423 RET ret = aafcli.hman.same(aafcli.ss,retryable);
425 // Store last call in AAFcli, because Cmds are all different instances.
426 aafcli.prevCall = retryable;
430 public<RET> RET all(Retryable<RET> retryable) throws APIException, CadiException, LocatorException {
431 this.setQueryParamsOn(retryable.lastClient);
432 return aafcli.hman.all(aafcli.ss,retryable);
435 public<RET> RET oneOf(Retryable<RET> retryable,String host) throws APIException, CadiException, LocatorException {
436 this.setQueryParamsOn(retryable.lastClient);
437 return aafcli.hman.oneOf(aafcli.ss,retryable,true,host);
440 protected PrintWriter pw() {
444 public String getName() {
448 public void reportHead(String ... str) {
450 boolean first = true;
452 for (String s : str) {
470 public String reportColHead(String format, String ... args) {
471 pw().format(format,(Object[])args);
476 public void reportLine() {
477 for (int i=0;i<lineLength;++i) {
483 protected void setQueryParamsOn(Rcli<?> rcli) {
484 StringBuilder sb=null;
486 if ((force=aafcli.forceString())!=null) {
487 sb = new StringBuilder("force=");
490 if (aafcli.addRequest()) {
492 sb = new StringBuilder("future=true");
494 sb.append("&future=true");
497 if (sb!=null && rcli!=null) {
498 rcli.setQueryParams(sb.toString());
503 // * If Force is set, will return True once only, then revert to "FALSE".
507 // protected String checkForce() {
508 // if (TRUE.equalsIgnoreCase(env.getProperty(FORCE, FALSE))) {
509 // env.setProperty(FORCE, FALSE);
515 public String toString() {
516 StringBuilder sb = new StringBuilder();
517 if (parent==null) { // ultimate parent
519 return sb.toString();
521 return parent.toString();
526 * Appends shortID with Realm, but only when allowed by Organization
527 * @throws OrganizationException
529 public String fullID(String id) {
531 if (id.indexOf('@') < 0) {
534 return id; // is already a full ID