fdb02c70dfff154c1491bbe9b5b55eb5596067e0
[aaf/authz.git] / auth / auth-locate / src / main / java / org / onap / aaf / auth / locate / facade / LocateFacadeImpl.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.locate.facade;
23
24
25 import static org.onap.aaf.auth.layer.Result.ERR_ActionNotCompleted;
26 import static org.onap.aaf.auth.layer.Result.ERR_BadData;
27 import static org.onap.aaf.auth.layer.Result.ERR_ConflictAlreadyExists;
28 import static org.onap.aaf.auth.layer.Result.ERR_Denied;
29 import static org.onap.aaf.auth.layer.Result.ERR_NotFound;
30 import static org.onap.aaf.auth.layer.Result.ERR_NotImplemented;
31 import static org.onap.aaf.auth.layer.Result.ERR_Policy;
32 import static org.onap.aaf.auth.layer.Result.ERR_Security;
33 import static org.onap.aaf.auth.layer.Result.OK;
34
35 import java.lang.reflect.Method;
36 import java.util.HashMap;
37 import java.util.Map;
38
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41
42 import org.onap.aaf.auth.dao.cass.Status;
43 import org.onap.aaf.auth.env.AuthzEnv;
44 import org.onap.aaf.auth.env.AuthzTrans;
45 import org.onap.aaf.auth.layer.FacadeImpl;
46 import org.onap.aaf.auth.layer.Result;
47 import org.onap.aaf.auth.locate.mapper.Mapper;
48 import org.onap.aaf.auth.locate.mapper.Mapper.API;
49 import org.onap.aaf.auth.locate.service.LocateService;
50 import org.onap.aaf.auth.locate.service.LocateServiceImpl;
51 import org.onap.aaf.auth.rserv.RServlet;
52 import org.onap.aaf.auth.rserv.RouteReport;
53 import org.onap.aaf.auth.rserv.doc.ApiDoc;
54 import org.onap.aaf.cadi.aaf.client.Examples;
55 import org.onap.aaf.misc.env.APIException;
56 import org.onap.aaf.misc.env.Data;
57 import org.onap.aaf.misc.env.Env;
58 import org.onap.aaf.misc.env.TimeTaken;
59 import org.onap.aaf.misc.env.Data.TYPE;
60 import org.onap.aaf.misc.rosetta.env.RosettaDF;
61 import org.onap.aaf.misc.rosetta.env.RosettaData;
62
63 import locate_local.v1_0.Api;
64
65 /**
66  * AuthzFacade
67  * 
68  * This Service Facade encapsulates the essence of the API Service can do, and provides
69  * a single created object for elements such as RosettaDF.
70  *
71  * The Responsibilities of this class are to:
72  * 1) Interact with the Service Implementation (which might be supported by various kinds of Backend Storage)
73  * 2) Validate incoming data (if applicable)
74  * 3) Convert the Service response into the right Format, and mark the Content Type
75  *              a) In the future, we may support multiple Response Formats, aka JSON or XML, based on User Request.
76  * 4) Log Service info, warnings and exceptions as necessary
77  * 5) When asked by the API layer, this will create and write Error content to the OutputStream
78  * 
79  * Note: This Class does NOT set the HTTP Status Code.  That is up to the API layer, so that it can be 
80  * clearly coordinated with the API Documentation
81  * 
82  * @author Jonathan
83  *
84  */
85 public abstract class LocateFacadeImpl<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,ERROR> extends FacadeImpl implements LocateFacade 
86         {
87         private LocateService<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,ERROR> service;
88
89         private final RosettaDF<ERROR>                  errDF;
90         private final RosettaDF<Api>                            apiDF;
91         private final RosettaDF<ENDPOINTS>              epDF;
92         private final RosettaDF<MGMT_ENDPOINTS> mepDF;
93
94
95         private static long cacheClear = 0L, emptyCheck=0L;
96         private final static Map<String,String> epsCache = new HashMap<String, String>(); // protected manually, in getEndpoints
97
98         public LocateFacadeImpl(AuthzEnv env, LocateService<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,ERROR> service, Data.TYPE dataType) throws APIException {
99                 this.service = service;
100                 (errDF                          = env.newDataFactory(mapper().getClass(API.ERROR))).in(dataType).out(dataType);
101                 (apiDF                          = env.newDataFactory(Api.class)).in(dataType).out(dataType);
102                 (epDF                           = env.newDataFactory(mapper().getClass(API.ENDPOINTS))).in(dataType).out(dataType);
103                 (mepDF                          = env.newDataFactory(mapper().getClass(API.MGMT_ENDPOINTS))).in(dataType).out(dataType);
104         }
105         
106         public Mapper<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,ERROR> mapper() {
107                 return service.mapper();
108         }
109                 
110         /* (non-Javadoc)
111          * @see com.att.authz.facade.AuthzFacade#error(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, int)
112          * 
113          * Note: Conforms to AT&T TSS RESTful Error Structure
114          */
115         @Override
116         public void error(AuthzTrans trans, HttpServletResponse response, Result<?> result) {
117                 String msg = result.details==null?"":result.details.trim();
118                 String[] detail;
119                 if(result.variables==null) {
120                         detail = new String[1];
121                 } else {
122                         int l = result.variables.length;
123                         detail=new String[l+1];
124                         System.arraycopy(result.variables, 0, detail, 1, l);
125                 }
126                 error(trans, response, result.status,msg,detail);
127         }
128                 
129         @Override
130         public void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... _detail) {
131                 String[] detail = _detail;
132                 if(detail.length==0) {
133                     detail=new String[1];
134                 }
135                 boolean hidemsg = false;
136                 String msgId;
137                 switch(status) {
138                         case 202:
139                         case ERR_ActionNotCompleted:
140                                 msgId = "SVC1202";
141                                 detail[0] = "Accepted, Action not complete";
142                                 response.setStatus(/*httpstatus=*/202);
143                                 break;
144
145                         case 403:
146                         case ERR_Policy:
147                         case ERR_Security:
148                         case ERR_Denied:
149                                 msgId = "SVC1403";
150                                 detail[0] = "Forbidden";
151                                 response.setStatus(/*httpstatus=*/403);
152                                 break;
153                                 
154                         case 404:
155                         case ERR_NotFound:
156                                 msgId = "SVC1404";
157                                 detail[0] = "Not Found";
158                                 response.setStatus(/*httpstatus=*/404);
159                                 break;
160
161                         case 406:
162                         case ERR_BadData:
163                                 msgId="SVC1406";
164                                 detail[0] = "Not Acceptable";
165                                 response.setStatus(/*httpstatus=*/406);
166                                 break;
167                                 
168                         case 409:
169                         case ERR_ConflictAlreadyExists:
170                                 msgId = "SVC1409";
171                                 detail[0] = "Conflict Already Exists";
172                                 response.setStatus(/*httpstatus=*/409);
173                                 break;
174                         
175                         case 501:
176                         case ERR_NotImplemented:
177                                 msgId = "SVC1501";
178                                 detail[0] = "Not Implemented"; 
179                                 response.setStatus(/*httpstatus=*/501);
180                                 break;
181                                 
182                         default:
183                                 msgId = "SVC1500";
184                                 detail[0] = "General Service Error";
185                                 response.setStatus(/*httpstatus=*/500);
186                                 hidemsg = true;
187                                 break;
188                 }
189
190                 try {
191                         StringBuilder holder = new StringBuilder();
192                         ERROR em = mapper().errorFromMessage(holder,msgId,msg,detail);
193                         trans.checkpoint(
194                                         "ErrResp [" + 
195                                         msgId +
196                                         "] " +
197                                         holder.toString(),
198                                         Env.ALWAYS);
199                         if(hidemsg) {
200                                 holder.setLength(0);
201                                 em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request");
202                         }
203                         errDF.newData(trans).load(em).to(response.getOutputStream());
204                         
205                 } catch (Exception e) {
206                         trans.error().log(e,"unable to send response for",msg);
207                 }
208         }
209         
210         /* (non-Javadoc)
211          * @see com.att.authz.facade.AuthzFacade#getAPI(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse)
212          */
213         public final static String API_REPORT = "apiReport";
214         @Override
215         public Result<Void> getAPI(AuthzTrans trans, HttpServletResponse resp, RServlet<AuthzTrans> rservlet) {
216                 TimeTaken tt = trans.start(API_REPORT, Env.SUB);
217                 try {
218                         Api api = new Api();
219                         Api.Route ar;
220                         Method[] meths = LocateServiceImpl.class.getDeclaredMethods();
221                         for(RouteReport rr : rservlet.routeReport()) {
222                                 api.getRoute().add(ar = new Api.Route());
223                                 ar.setMeth(rr.meth.name());
224                                 ar.setPath(rr.path);
225                                 ar.setDesc(rr.desc);
226                                 ar.getContentType().addAll(rr.contextTypes);
227                                 for(Method m : meths) {
228                                         ApiDoc ad;
229                                         if((ad = m.getAnnotation(ApiDoc.class))!=null &&
230                                                         rr.meth.equals(ad.method()) &&
231                                                     rr.path.equals(ad.path())) {
232                                                 for(String param : ad.params()) {
233                                                         ar.getParam().add(param);
234                                                 }
235                                                 for(String text : ad.text()) {
236                                                         ar.getComments().add(text);
237                                                 }
238                                                 ar.setExpected(ad.expectedCode());
239                                                 for(int ec : ad.errorCodes()) {
240                                                         ar.getExplicitErr().add(ec);
241                                                 }
242                                         }
243                                 }
244                         }
245                         apiDF.newData(trans).load(api).to(resp.getOutputStream());
246                         setContentType(resp,apiDF.getOutType());
247                         return Result.ok();
248
249                 } catch (Exception e) {
250                         trans.error().log(e,IN,API_REPORT);
251                         return Result.err(e);
252                 } finally {
253                         tt.done();
254                 }
255         }
256         
257         public final static String API_EXAMPLE = "apiExample";
258         /* (non-Javadoc)
259          * @see com.att.authz.facade.AuthzFacade#getAPIExample(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String)
260          */
261         @Override
262         public Result<Void> getAPIExample(AuthzTrans trans, HttpServletResponse resp, String nameOrContentType, boolean optional) {
263                 TimeTaken tt = trans.start(API_EXAMPLE, Env.SUB);
264                 try {
265                         String content =Examples.print(apiDF.getEnv(), nameOrContentType, optional); 
266                         resp.getOutputStream().print(content);
267                         setContentType(resp,content.contains("<?xml")?TYPE.XML:TYPE.JSON);
268                         return Result.ok();
269                 } catch (Exception e) {
270                         trans.error().log(e,IN,API_EXAMPLE);
271                         return Result.err(Result.ERR_NotImplemented,e.getMessage());
272                 } finally {
273                         tt.done();
274                 }
275         }
276
277         public final static String GET_ENDPOINTS = "getEndpoints";
278         private final static Object LOCK = new Object();
279         /* (non-Javadoc)
280          * @see org.onap.aaf.auth.locate.facade.GwFacade#getEndpoints(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String, java.lang.String)
281          */
282         @Override
283         public Result<Void> getEndpoints(AuthzTrans trans, HttpServletResponse resp, String key, String service, String version, String other) {
284                 TimeTaken tt = trans.start(GET_ENDPOINTS, Env.SUB);
285                 try {
286                         String output=null;
287                         long temp=System.currentTimeMillis();
288                         synchronized(LOCK) {
289                                 if(cacheClear<temp) {
290                                         epsCache.clear();
291                                         cacheClear = temp+1000*60*2; // 2 mins standard cache clear
292                                 } else {
293                                         output = epsCache.get(key);
294                                         if("{}".equals(output) && emptyCheck<temp) {
295                                                 output = null;
296                                                 emptyCheck = temp+5000; // 5 second check  
297                                         }
298                                 }
299                         }
300                         if(output==null) {
301                                 Result<ENDPOINTS> reps = this.service.getEndPoints(trans,service,version,other);
302                                 if(reps.notOK()) {
303                                         return Result.err(reps);
304                                 } else {
305                                         output = epDF.newData(trans).load(reps.value).asString();
306                                         synchronized(LOCK) {
307                                                 epsCache.put(key, output);
308                                         }
309                                 }
310                         }
311                         resp.getOutputStream().println(output);
312                         setContentType(resp,epDF.getOutType());
313                         return Result.ok();
314                 } catch (Exception e) {
315                         trans.error().log(e,IN,API_EXAMPLE);
316                         return Result.err(Result.ERR_NotImplemented,e.getMessage());
317                 } finally {
318                         tt.done();
319                 }
320         }
321
322         private static final String PUT_MGMT_ENDPOINTS = "Put Mgmt Endpoints";
323         /* (non-Javadoc)
324          * @see org.onap.aaf.auth.locate.facade.GwFacade#putMgmtEndpoints(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
325          */
326         @Override
327         public Result<Void> putMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
328                 TimeTaken tt = trans.start(PUT_MGMT_ENDPOINTS, Env.SUB|Env.ALWAYS);
329                 try {
330                         MGMT_ENDPOINTS rreq;
331                         try {
332                                 RosettaData<MGMT_ENDPOINTS> data = mepDF.newData().load(req.getInputStream());
333                                 rreq = data.asObject();
334                         } catch(APIException e) {
335                                 trans.error().log("Invalid Input",IN,PUT_MGMT_ENDPOINTS);
336                                 return Result.err(Status.ERR_BadData,"Invalid Input");
337
338                         }
339                         Result<Void> rp = service.putMgmtEndPoints(trans, rreq);
340                         switch(rp.status) {
341                                 case OK: 
342                                         synchronized(LOCK) {
343                                                 cacheClear = 0L;
344                                         }
345                                         setContentType(resp,mepDF.getOutType());
346                                         return Result.ok();
347                                 default:
348                                         return rp;
349                         }
350                 } catch (Exception e) {
351                         trans.error().log(e,IN,PUT_MGMT_ENDPOINTS);
352                         return Result.err(e);
353                 } finally {
354                         tt.done();
355                 }
356         }
357
358         private static final String DELETE_MGMT_ENDPOINTS = "Delete Mgmt Endpoints";
359         /* (non-Javadoc)
360          * @see org.onap.aaf.auth.locate.facade.GwFacade#removeMgmtEndpoints(org.onap.aaf.auth.env.test.AuthzTrans, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
361          */
362         @Override
363         public Result<Void> removeMgmtEndpoints(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) {
364                 TimeTaken tt = trans.start(DELETE_MGMT_ENDPOINTS, Env.SUB|Env.ALWAYS);
365                 try {
366                         MGMT_ENDPOINTS rreq;
367                         try {
368                                 RosettaData<MGMT_ENDPOINTS> data = mepDF.newData().load(req.getInputStream());
369                                 rreq = data.asObject();
370                         } catch(APIException e) {
371                                 trans.error().log("Invalid Input",IN,DELETE_MGMT_ENDPOINTS);
372                                 return Result.err(Status.ERR_BadData,"Invalid Input");
373
374                         }
375                         Result<Void> rp = service.removeMgmtEndPoints(trans, rreq);
376                         switch(rp.status) {
377                                 case OK: 
378                                         synchronized(LOCK) {
379                                                 cacheClear = 0L;
380                                         }
381                                         setContentType(resp,mepDF.getOutType());
382                                         return Result.ok();
383                                 default:
384                                         return rp;
385                         }
386                 } catch (Exception e) {
387                         trans.error().log(e,IN,DELETE_MGMT_ENDPOINTS);
388                         return Result.err(e);
389                 } finally {
390                         tt.done();
391                 }
392         }
393
394 }