Update the license for 2017-2018 license
[aai/traversal.git] / aai-traversal / src / main / java / org / onap / aai / rest / search / ModelAndNamedQueryRestProvider.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-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 package org.onap.aai.rest.search;
21
22 import com.att.eelf.configuration.EELFLogger;
23 import com.att.eelf.configuration.EELFManager;
24 import org.onap.aai.dbgraphmap.SearchGraph;
25 import org.onap.aai.dbmap.DBConnectionType;
26 import org.onap.aai.exceptions.AAIException;
27 import org.onap.aai.extensions.AAIExtensionMap;
28 import org.onap.aai.logging.ErrorLogHelper;
29 import org.onap.aai.logging.LoggingContext;
30 import org.onap.aai.logging.StopWatch;
31 import org.onap.aai.restcore.HttpMethod;
32 import org.onap.aai.restcore.RESTAPI;
33 import org.onap.aai.util.AAIApiVersion;
34 import org.onap.aai.util.AAIConstants;
35
36 import javax.servlet.http.HttpServletRequest;
37 import javax.ws.rs.POST;
38 import javax.ws.rs.Path;
39 import javax.ws.rs.Produces;
40 import javax.ws.rs.QueryParam;
41 import javax.ws.rs.core.*;
42 import javax.ws.rs.core.Response.Status;
43 import java.util.ArrayList;
44 import java.util.concurrent.Callable;
45 import java.util.concurrent.TimeUnit;
46
47 /**
48  * Implements the search subdomain in the REST API. All API calls must include
49  * X-FromAppId and X-TransactionId in the header.
50  * 
51  
52  *
53  */
54
55 @Path("/search")
56 public class ModelAndNamedQueryRestProvider extends RESTAPI {
57         
58         protected static String authPolicyFunctionName = "search";
59         
60         public static final String NAMED_QUERY = "/named-query";
61         
62         public static final String MODEL_QUERY = "/model";
63         
64         public static final String TARGET_ENTITY = "DB";
65         private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ModelAndNamedQueryRestProvider.class);
66         
67         /**
68          * Gets the named query response.
69          *
70          * @param headers the headers
71          * @param req the req
72          * @param queryParameters the query parameters
73          * @return the named query response
74          */
75         /* ---------------- Start Named Query --------------------- */
76         @POST
77         @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
78         @Path(NAMED_QUERY)
79         public Response getNamedQueryResponse(@Context HttpHeaders headers,
80                                           @Context HttpServletRequest req,
81                                           String queryParameters,
82                                           @Context UriInfo info) {
83                 return runner(AAIConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
84                                 AAIConstants.AAI_TRAVERSAL_TIMEOUT_APP,
85                                 AAIConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT,
86                                 headers,
87                                 info,
88                                 HttpMethod.GET,
89                                 new Callable<Response>() {
90                                         @Override
91                                         public Response call() {
92                                                 return processNamedQueryResponse(headers, req, queryParameters);
93                                         }
94                                 }
95                 );
96         }
97
98         public Response processNamedQueryResponse(@Context HttpHeaders headers,
99                                               @Context HttpServletRequest req,
100                                               String queryParameters) {
101                 String methodName = "getNamedQueryResponse";
102                 AAIException ex = null;
103                 Response response = null;
104                 String fromAppId = null;
105                 String transId = null;
106                 double dbTimeMsecs = 0;
107                 String rqstTm = genDate();
108                 ArrayList<String> templateVars = new ArrayList<String>();       
109                 try { 
110                         LoggingContext.save();
111                         LoggingContext.targetEntity(TARGET_ENTITY);
112                         LoggingContext.targetServiceName(methodName);
113                         
114                         fromAppId = getFromAppId(headers);
115                         transId = getTransId(headers);
116                         
117                         AAIExtensionMap aaiExtMap = new AAIExtensionMap();
118                         aaiExtMap.setHttpHeaders(headers);
119                         aaiExtMap.setServletRequest(req);
120                         aaiExtMap.setApiVersion(AAIApiVersion.get());
121                         String realTime = headers.getRequestHeaders().getFirst("Real-Time");
122                         //only consider header value for search         
123                         DBConnectionType type = this.determineConnectionType("force-cache", realTime);
124                         
125                         SearchGraph searchGraph = new SearchGraph();
126                         LoggingContext.startTime();
127                         StopWatch.conditionalStart();
128                         
129                         response = searchGraph.runNamedQuery(fromAppId, transId, queryParameters, type, aaiExtMap);
130         
131                         dbTimeMsecs += StopWatch.stopIfStarted();
132                         LoggingContext.elapsedTime((long)dbTimeMsecs,TimeUnit.MILLISECONDS);
133                         LoggingContext.successStatusFields();
134                         
135                         
136                         LOGGER.info ("Completed");
137                         
138                         LoggingContext.restoreIfPossible();
139                         LoggingContext.successStatusFields();
140                         
141                         String respTm = genDate();
142
143                 } catch (AAIException e) {
144                         LoggingContext.restoreIfPossible();
145                         // send error response
146                         ex = e;
147                         templateVars.add("POST Search");
148                         templateVars.add("getNamedQueryResponse");
149                         response =  Response
150                                                 .status(e.getErrorObject().getHTTPResponseCode())
151                                                 .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
152                                                 .build();
153                 } catch (Exception e) {
154                         LoggingContext.restoreIfPossible();
155                         // send error response
156                         ex = new AAIException("AAI_4000", e);
157                         templateVars.add("POST Search");
158                         templateVars.add("getNamedQueryResponse");
159                         response = Response
160                                                 .status(Status.INTERNAL_SERVER_ERROR)
161                                                 .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
162                                                 .build();
163                 } finally {
164                         // log success or failure
165                         if (ex != null) {
166                                 ErrorLogHelper.logException(ex);
167                         }
168                 }
169                 return response;
170         }
171         
172         /**
173          * Gets the model query response.
174          *
175          * @param headers the headers
176          * @param req the req
177          * @param inboundPayload the inbound payload
178          * @param action the action
179          * @return the model query response
180          */
181         /* ---------------- Start Named Query --------------------- */
182         @POST
183         @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
184         @Path(MODEL_QUERY)
185         public Response getModelQueryResponse(@Context HttpHeaders headers,
186                                           @Context HttpServletRequest req,
187                                           String inboundPayload,
188                                           @QueryParam("action") String action,
189                                           @Context UriInfo info) {
190                 return runner(AAIConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
191                                 AAIConstants.AAI_TRAVERSAL_TIMEOUT_APP,
192                                 AAIConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT,
193                                 headers,
194                                 info,
195                                 HttpMethod.GET,
196                                 new Callable<Response>() {
197                                         @Override
198                                         public Response call() {
199                                                 return processModelQueryResponse(headers, req, inboundPayload, action);
200                                         }
201                                 }
202                 );
203         }
204
205         public Response processModelQueryResponse(@Context HttpHeaders headers,
206                                               @Context HttpServletRequest req,
207                                               String inboundPayload,
208                                               @QueryParam("action") String action) {
209                 String methodName = "getModelQueryResponse";
210                 AAIException ex = null;
211                 Response response = null;
212                 String fromAppId = null;
213                 String transId = null;
214                 double dbTimeMsecs = 0;
215                 
216                 String rqstTm = genDate();
217                 ArrayList<String> templateVars = new ArrayList<String>();       
218                 try { 
219                         LoggingContext.save();
220                         LoggingContext.targetEntity(TARGET_ENTITY);
221                         LoggingContext.targetServiceName(methodName);
222                         
223                         fromAppId = getFromAppId(headers);
224                         transId = getTransId(headers);
225                         
226                         AAIExtensionMap aaiExtMap = new AAIExtensionMap();
227                         aaiExtMap.setHttpHeaders(headers);
228                         aaiExtMap.setServletRequest(req);
229                         aaiExtMap.setApiVersion(AAIApiVersion.get());
230                         aaiExtMap.setFromAppId(fromAppId);
231                         aaiExtMap.setTransId(transId);
232                         
233                         String realTime = headers.getRequestHeaders().getFirst("Real-Time");
234                         //only consider header value for search         
235                         DBConnectionType type = this.determineConnectionType("force-cache", realTime);
236                         
237                         SearchGraph searchGraph = new SearchGraph();
238                         LoggingContext.startTime();
239                         StopWatch.conditionalStart();
240                         
241                         if (action != null && action.equalsIgnoreCase("DELETE")) { 
242                                 response = searchGraph.executeModelOperation(fromAppId, transId, inboundPayload, type, true, aaiExtMap);
243                         } else {
244                                 response = searchGraph.executeModelOperation(fromAppId, transId, inboundPayload, type, false, aaiExtMap);
245                         }
246                         dbTimeMsecs += StopWatch.stopIfStarted();
247                         LoggingContext.elapsedTime((long)dbTimeMsecs,TimeUnit.MILLISECONDS);
248                         LoggingContext.successStatusFields();
249                         
250                         LOGGER.info ("Completed");
251                         
252                         LoggingContext.restoreIfPossible();
253                         LoggingContext.successStatusFields();
254                         String respTm = genDate();
255                         
256                 } catch (AAIException e) {
257                         LoggingContext.restoreIfPossible();
258                         // send error response
259                         ex = e;
260                         templateVars.add("POST Search");
261                         templateVars.add("getModelQueryResponse");
262                         response =  Response
263                                                 .status(e.getErrorObject().getHTTPResponseCode())
264                                                 .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
265                                                 .build();
266                 } catch (Exception e) {
267                         LoggingContext.restoreIfPossible();
268                         // send error response
269                         ex = new AAIException("AAI_4000", e);
270                         templateVars.add("POST Search");
271                         templateVars.add("getModelQueryResponse");
272                         response = Response
273                                                 .status(Status.INTERNAL_SERVER_ERROR)
274                                                 .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
275                                                 .build();
276                 } finally {
277                         // log success or failure
278                         if (ex != null) {
279                                 ErrorLogHelper.logException(ex);
280                         }
281                 }
282                 return response;
283         }
284
285 }