6af283568b33e4689217126613d34bdfc1c0ba74
[aaf/authz.git] / auth / auth-core / src / main / java / org / onap / aaf / auth / rserv / TypedCode.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.rserv;
23
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27
28
29
30 import org.onap.aaf.misc.env.Env;
31 import org.onap.aaf.misc.env.TimeTaken;
32 import org.onap.aaf.misc.env.Trans;
33
34
35 /**
36  * TypedCode organizes implementation code based on the Type and Version of code it works with so that it can
37  * be located quickly at runtime based on the "Accept" HTTP Header.
38  *
39  * FYI: For those in the future wondering why I would create a specialized set of "Pair" for the data content:
40  *   1) TypeCode is used in Route, and this code is used for every transaction... it needs to be blazingly fast
41  *   2) The actual number of objects accessed is quite small and built at startup.  Arrays are best
42  *   3) I needed a small, well defined tree where each level is a different Type.  Using a "Pair" Generic definitions,
43  *      I created type-safety at each level, which you can't get from a TreeSet, etc.
44  *   4) Chaining through the Network is simply object dereferencing, which is as fast as Java can go.
45  *   5) The drawback is that in your code is that all the variables are named "x" and "y", which can be a bit hard to
46  *       read both in code, and in the debugger.  However, TypeSafety allows your IDE (Eclipse) to help you make the
47  *      choices.  Also, make sure you have a good "toString()" method on each object so you can see what's happening
48  *      in the IDE Debugger.
49  *
50  * Empirically, this method of obtaining routes proved to be much faster than the HashSet implementations available in otherwise
51  * competent Open Source.
52  *
53  * @author Jonathan
54  *
55  * @param <TRANS>
56  */
57 public class TypedCode<TRANS extends Trans> extends Content<TRANS> {
58         private List<Pair<String, Pair<HttpCode<TRANS,?>,List<Pair<String, Object>>>>> types;
59
60         public TypedCode() {
61             types = new ArrayList<>();
62         }
63
64         /**
65          * Construct Typed Code based on ContentType parameters passed in
66          *
67          * @param code
68          * @param others
69          * @return
70          */
71         public TypedCode<TRANS> add(HttpCode<TRANS,?> code, String ... others) {
72             StringBuilder sb = new StringBuilder();
73             boolean first = true;
74             for (String str : others) {
75                 if (first) {
76                     first = false;
77                 } else {
78                     sb.append(',');
79                 }
80                 sb.append(str);
81             }
82             parse(code, sb.toString());
83
84             return this;
85         }
86
87         @Override
88         protected Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> types(HttpCode<TRANS,?> code, String str) {
89             Pair<String, Pair<HttpCode<TRANS,?>,List<Pair<String, Object>>>> type = null;
90             ArrayList<Pair<String, Object>> props = new ArrayList<>();
91             // Want Q percentage is to be first in the array everytime.  If not listed, 1.0 is default
92             props.add(new Pair<String,Object>(Q,1f));
93             Pair<HttpCode<TRANS,?>, List<Pair<String,Object>>> cl = new Pair<HttpCode<TRANS,?>, List<Pair<String,Object>>>(code, props);
94 //            // breakup "plus" stuff, i.e. application/xaml+xml
95 //            int plus = str.indexOf('+');
96 //            if (plus<0) {
97                 type = new Pair<String, Pair<HttpCode<TRANS,?>,List<Pair<String,Object>>>>(str, cl);
98                 types.add(type);
99                 return type;
100 //            } else {
101 //                int prev = str.indexOf('/')+1;
102 //                String first = str.substring(0,prev);
103 //                String nstr;
104 //                while (prev!=0) {
105 //                    nstr = first + (plus>-1?str.substring(prev,plus):str.substring(prev));
106 //                    type = new Pair<String, Pair<HttpCode<TRANS,?>,List<Pair<String,Object>>>>(nstr, cl);
107 //                    types.add(type);
108 //                    prev = plus+1;
109 //                    plus = str.indexOf('+',prev);
110 //                }
111 //            return type;
112 //            }
113         }
114
115         @Override
116         protected boolean props(Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type, String tag, String value) {
117             if (tag.equals(Q)) { // reset the Q value (first in array)
118                 boolean rv = true;
119                 try {
120                     type.y.y.get(0).y=Float.parseFloat(value);
121                     return rv;
122                 } catch (NumberFormatException e) {
123                     rv=false; // Note: this awkward syntax forced by Sonar, which doesn't like doing nothing with Exception
124                               // which is what should happen
125                 }
126             }
127             return type.y.y.add(new Pair<String,Object>(tag,"version".equals(tag)?new Version(value):value));
128         }
129
130         public Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> prep(TRANS trans, String compare){
131             Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> c,rv=null;
132             if (types.size()==1 && "".equals((c=types.get(0)).x)) { // if there are no checks for type, skip
133                 rv = c;
134             } else {
135                 if (compare==null || compare.length()==0) {
136                     rv = types.get(0); // first code is used
137                 } else {
138                     Acceptor<TRANS> acc = new Acceptor<TRANS>(types);
139                     boolean accepted;
140                     TimeTaken tt = trans.start(compare, Env.SUB);
141                     try {
142                         accepted = acc.parse(null, compare);
143                     } finally {
144                         tt.done();
145                     }
146                     if (accepted) {
147                         switch(acc.acceptable.size()) {
148                             case 0:
149 //                                // TODO best Status Code?
150 //                                resp.setStatus(HttpStatus.NOT_ACCEPTABLE_406);
151                                 break;
152                             case 1:
153                                 rv = acc.acceptable.get(0);
154                                 break;
155                             default: // compare Q values to get Best Match
156                                 float bestQ = -1.0f;
157                                 Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> bestT = null;
158                                 for (Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type : acc.acceptable) {
159                                     Float f = (Float)type.y.y.get(0).y; // first property is always Q
160                                     if (f>bestQ) {
161                                         bestQ=f;
162                                         bestT = type;
163                                     }
164                                 }
165                                 if (bestT!=null) {
166                                     // When it is a GET, the matched type is what is returned, so set ContentType
167 //                                    if (isGet)resp.setContentType(bestT.x); // set ContentType of Code<TRANS,?>
168 //                                    rv = bestT.y.x;
169                                     rv = bestT;
170                                 }
171                         }
172                     } else {
173                         trans.checkpoint("No Match found for Accept");
174                     }
175                 }
176             }
177             return rv;
178         }
179
180         /**
181          * Print on String Builder content related to specific Code
182          *
183          * This is for Reporting and Debugging purposes, so the content is not cached.
184          *
185          * If code is "null", then all content is matched
186          *
187          * @param code
188          * @return
189          */
190         public StringBuilder relatedTo(HttpCode<TRANS, ?> code, StringBuilder sb) {
191             boolean first = true;
192             for (Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> pair : types) {
193                 if (code==null || pair.y.x == code) {
194                     if (first) {
195                         first = false;
196                     } else {
197                         sb.append(',');
198                     }
199                     sb.append(pair.x);
200                     for (Pair<String,Object> prop : pair.y.y) {
201                         // Don't print "Q".  it's there for internal use, but it is only meaningful for "Accepts"
202                         if (!prop.x.equals(Q) || !prop.y.equals(1f) ) {
203                             sb.append(';');
204                             sb.append(prop.x);
205                             sb.append('=');
206                             sb.append(prop.y);
207                         }
208                     }
209                 }
210             }
211             return sb;
212         }
213
214         public List<Pair<String, Object>> getContent(HttpCode<TRANS,?> code) {
215             for (Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> pair : types) {
216                 if (pair.y.x == code) {
217                     return pair.y.y;
218                 }
219             }
220             return null;
221         }
222
223         public String toString() {
224             return relatedTo(null,new StringBuilder()).toString();
225         }
226
227         public void api(RouteReport tr) {
228             // Need to build up a map, because Prop entries can be in several places.
229             HashMap<HttpCode<?,?>,StringBuilder> psb = new HashMap<>();
230             StringBuilder temp;
231             tr.desc = null;
232
233             // Read through Code/TypeCode trees for all accepted Typecodes
234             for (Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> tc : types) {
235                 // If new, then it's new Code set, create prefix content
236                 if ((temp=psb.get(tc.y.x))==null) {
237                     psb.put(tc.y.x,temp=new StringBuilder());
238                     if (tr.desc==null) {
239                         tr.desc = tc.y.x.desc();
240                     }
241                 } else {
242                     temp.append(',');
243                 }
244                 temp.append(tc.x);
245
246                 // add all properties
247                 for (Pair<String, Object> props : tc.y.y) {
248                     temp.append(';');
249                     temp.append(props.x);
250                     temp.append('=');
251                     temp.append(props.y);
252                 }
253             }
254             // Gather all ContentType possibilities for the same code together
255
256             for (StringBuilder sb : psb.values()) {
257                 tr.contextTypes.add(sb.toString());
258             }
259         }
260
261         public String first() {
262             if (types.size()>0) {
263                 return types.get(0).x;
264             }
265             return null;
266         }
267
268     }