Fix simple Sonar Lint issues
[aai/search-data-service.git] / src / main / java / org / onap / aai / sa / rest / IndexApi.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 Amdocs
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.sa.rest;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import java.io.FileNotFoundException;
25 import java.io.IOException;
26 import javax.servlet.http.HttpServletRequest;
27 import org.onap.aai.cl.api.LogFields;
28 import org.onap.aai.cl.api.LogLine;
29 import org.onap.aai.cl.api.Logger;
30 import org.onap.aai.cl.eelf.LoggerFactory;
31 import org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterface;
32 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
33 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
34 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
35 import org.springframework.http.HttpHeaders;
36 import org.springframework.http.HttpStatus;
37 import org.springframework.http.MediaType;
38 import org.springframework.http.ResponseEntity;
39
40 /**
41  * This class encapsulates the REST end points associated with manipulating indexes in the document store.
42  */
43 public class IndexApi {
44
45
46   private static final String HEADER_VALIDATION_SUCCESS = "SUCCESS";
47   protected SearchServiceApi searchService = null;
48
49   /**
50    * Configuration for the custom analyzers that will be used for indexing.
51    */
52   protected AnalysisConfiguration analysisConfig;
53
54   // Set up the loggers.
55     private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName());
56     private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(IndexApi.class.getName());
57
58
59   public IndexApi(SearchServiceApi searchService) {
60     this.searchService = searchService;
61     init();
62   }
63
64
65   /**
66    * Initializes the end point.
67    *
68    * @throws FileNotFoundException
69    * @throws IOException
70    * @throws DocumentStoreOperationException
71    */
72   public void init() {
73
74     // Instantiate our analysis configuration object.
75     analysisConfig = new AnalysisConfiguration();
76   }
77
78
79   /**
80      * Processes client requests to create a new index and document type in the document store.
81    *
82      * @param documentSchema - The contents of the request body which is expected to be a JSON structure which
83      *        corresponds to the schema defined in document.schema.json
84    * @param index          - The name of the index to create.
85    * @return - A Standard REST response
86    */
87     public ResponseEntity<String> processCreateIndex(String documentSchema, HttpServletRequest request,
88             HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
89
90     int resultCode = 500;
91    
92     // Initialize the MDC Context for logging purposes.
93     ApiUtils.initMdcContext(request, headers);
94
95     // Validate that the request is correctly authenticated before going
96     // any further.
97     try {
98
99             if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
100                     ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
101         logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
102         return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
103       }
104
105     } catch (Exception e) {
106
107       logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
108                   "Unexpected authentication failure - cause: " + e.getMessage());
109       return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
110     }
111
112
113     // We expect a payload containing the document schema.  Make sure
114     // it is present.
115     if (documentSchema == null) {
116       logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload");
117       return errorResponse(HttpStatus.valueOf(resultCode), "Missing payload", request);
118     }
119
120         String resultString;
121
122     try {
123       // Marshal the supplied json string into a document schema object.
124       ObjectMapper mapper = new ObjectMapper();
125       DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
126
127       // Now, ask the DAO to create the index.
128       OperationResult result = documentStore.createIndex(index, schema);
129
130       // Extract the result code and string from the OperationResult
131       // object so that we can use them to generate a standard REST
132       // response.
133       // Note that we want to return a 201 result code on a successful
134       // create, so if we get back a 200 from the document store,
135       // translate that int a 201.
136       resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
137             resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
138
139     } catch (com.fasterxml.jackson.core.JsonParseException
140              | com.fasterxml.jackson.databind.JsonMappingException e) {
141
142       // We were unable to marshal the supplied json string into a valid
143       // document schema, so return an appropriate error response.
144       resultCode = HttpStatus.BAD_REQUEST.value();
145       resultString = "Malformed schema: " + e.getMessage();
146
147     } catch (IOException e) {
148
149       // We'll treat this is a general internal error.
150       resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
151       resultString = "IO Failure: " + e.getMessage();
152     }
153
154         ResponseEntity<String> response =
155                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
156
157
158     // Log the result.
159     if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
160       logger.info(SearchDbMsgs.CREATED_INDEX, index);
161     } else {
162       logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
163     }
164
165     // Generate our audit log.
166     auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
167                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode).setField(
168                         LogLine.DefinedFields.RESPONSE_DESCRIPTION, HttpStatus.valueOf(resultCode).toString()),
169                 (request != null) ? request.getMethod() : "Unknown",
170                      (request != null) ? request.getRequestURL ().toString () : "Unknown",
171                      (request != null) ? request.getRemoteHost () : "Unknown",
172                      Integer.toString(response.getStatusCodeValue ()));
173
174
175
176     // Clear the MDC context so that no other transaction inadvertently
177     // uses our transaction id.
178     ApiUtils.clearMdcContext();
179
180     // Finally, return the response.
181     return response;
182   }
183
184   /**
185      * This function accepts any JSON and will "blindly" write it to the document store.
186    *
187      * Note, eventually this "dynamic" flow should follow the same JSON-Schema validation procedure as the normal create
188      * index flow.
189    *
190    * @param dynamicSchema - The JSON string that will be sent to the document store.
191    * @param index - The name of the index to be created.
192    * @param documentStore - The document store specific interface.
193    * @return The result of the document store interface's operation.
194    */
195   public ResponseEntity<String> processCreateDynamicIndex(String dynamicSchema, HttpServletRequest request,
196                                             HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
197
198     ResponseEntity<String> response = null;
199
200         ResponseEntity<String> validationResponse =
201                 validateRequest(request, headers, index, SearchDbMsgs.INDEX_CREATE_FAILURE);
202
203
204     if (validationResponse.getStatusCodeValue () != HttpStatus.OK.value ()) {
205       response = validationResponse;
206     } else {
207       OperationResult result = documentStore.createDynamicIndex(index, dynamicSchema);
208
209       int resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
210       String resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
211
212       response = ResponseEntity.status(resultCode).body(resultString);
213     }
214
215     return response;
216   }
217
218   /**
219      * Processes a client request to remove an index from the document store. Note that this implicitly deletes all
220      * documents contained within that index.
221    *
222    * @param index - The index to be deleted.
223    * @return - A standard REST response.
224    */
225     public ResponseEntity<String> processDelete(String index, HttpServletRequest request, HttpHeaders headers,
226                                               DocumentStoreInterface documentStore) {
227
228     // Initialize the MDC Context for logging purposes.
229     ApiUtils.initMdcContext(request, headers);
230
231         ResponseEntity<String> response;
232
233     // Validate that the request is correctly authenticated before going
234     // any further.
235     try {
236       if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
237                                          ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
238         logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
239         return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
240       }
241
242     } catch (Exception e) {
243       logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
244                   "Unexpected authentication failure - cause: " + e.getMessage());
245       return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
246     }
247
248     try {
249       // Send the request to the document store.
250       response = responseFromOperationResult(documentStore.deleteIndex(index));
251     } catch (DocumentStoreOperationException e) {
252             response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
253                     .body(e.getMessage());
254     }
255
256     // Log the result.
257     if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
258       logger.info(SearchDbMsgs.DELETED_INDEX, index);
259     } else {
260             logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, response.getBody());
261     }
262
263     // Generate our audit log.
264     auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
265                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatusCodeValue()).setField(
266                         LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusCode().getReasonPhrase()),
267                 (request != null) ? request.getMethod() : "Unknown",
268                      (request != null) ? request.getRequestURL ().toString () : "Unknown",
269                      (request != null) ? request.getRemoteHost () : "Unknown",
270                      Integer.toString(response.getStatusCodeValue()));
271
272     // Clear the MDC context so that no other transaction inadvertently
273     // uses our transaction id.
274     ApiUtils.clearMdcContext();
275
276     return response;
277   }
278
279
280   /**
281      * This method takes a JSON format document schema and produces a set of field mappings in the form that Elastic
282      * Search expects.
283    *
284    * @param documentSchema - A document schema expressed as a JSON string.
285    * @return - A JSON string expressing an Elastic Search mapping configuration.
286    * @throws com.fasterxml.jackson.core.JsonParseException
287    * @throws com.fasterxml.jackson.databind.JsonMappingException
288    * @throws IOException
289    */
290     public String generateDocumentMappings(String documentSchema) throws IOException {
291
292     // Unmarshal the json content into a document schema object.
293     ObjectMapper mapper = new ObjectMapper();
294     DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
295
296     // Now, generate the Elastic Search mapping json and return it.
297     StringBuilder sb = new StringBuilder();
298     sb.append("{");
299     sb.append("\"properties\": {");
300
301     boolean first = true;
302     for (DocumentFieldSchema field : schema.getFields()) {
303
304       if (!first) {
305         sb.append(",");
306       } else {
307         first = false;
308       }
309
310       sb.append("\"").append(field.getName()).append("\": {");
311
312       // The field type is mandatory.
313       sb.append("\"type\": \"").append(field.getDataType()).append("\"");
314
315       // If the index field was specified, then append it.
316       if (field.getSearchable() != null) {
317                 sb.append(", \"index\": \"").append(field.getSearchable() ? "analyzed" : "not_analyzed").append("\"");
318       }
319
320       // If a search analyzer was specified, then append it.
321       if (field.getSearchAnalyzer() != null) {
322         sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\"");
323       }
324
325       // If an indexing analyzer was specified, then append it.
326       if (field.getIndexAnalyzer() != null) {
327         sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\"");
328       } else {
329         sb.append(", \"analyzer\": \"").append("whitespace").append("\"");
330       }
331
332       sb.append("}");
333     }
334
335     sb.append("}");
336     sb.append("}");
337
338     logger.debug("Generated document mappings: " + sb.toString());
339
340     return sb.toString();
341   }
342
343
344   /**
345      * Converts an {@link OperationResult} to a standard REST {@link ResponseEntity} object.
346    *
347    * @param result - The {@link OperationResult} to be converted.
348    * @return - The equivalent {@link ResponseEntity} object.
349    */
350   public ResponseEntity<String> responseFromOperationResult(OperationResult result) {
351
352     if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
353             return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
354                     .body(result.getResult());
355     } else {
356       if (result.getFailureCause() != null) {
357                 return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
358                         .body(result.getFailureCause());
359       } else {
360                 return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
361                         .body(result.getResult());
362       }
363     }
364   }
365
366   public ResponseEntity<String> errorResponse(HttpStatus status, String msg, HttpServletRequest request) {
367
368     // Generate our audit log.
369     auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
370                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, status.value())
371                      .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
372                 (request != null) ? request.getMethod() : "Unknown",
373                      (request != null) ? request.getRequestURL ().toString () : "Unknown",
374                 (request != null) ? request.getRemoteHost() : "Unknown", Integer.toString(status.value()));
375
376     // Clear the MDC context so that no other transaction inadvertently
377     // uses our transaction id.
378     ApiUtils.clearMdcContext();
379
380     return ResponseEntity.status(status).contentType ( MediaType.APPLICATION_JSON ).body(msg);
381   }
382
383
384   /**
385    * A helper method used for validating/authenticating an incoming request.
386    *
387    * @param request - The http request that will be validated.
388    * @param headers - The http headers that will be validated.
389    * @param index - The name of the index that the document store request is being made against.
390    * @param failureMsgEnum - The logging message to be used upon validation failure.
391    * @return A success or failure response
392    */
393     private ResponseEntity<String> validateRequest(HttpServletRequest request, HttpHeaders headers, String index,
394             SearchDbMsgs failureMsgEnum) {
395     try {
396             if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
397                     ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
398         logger.warn(failureMsgEnum, index, "Authentication failure.");
399         return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
400       }
401     } catch (Exception e) {
402       logger.warn(failureMsgEnum, index, "Unexpected authentication failure - cause: " + e.getMessage());
403       return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
404     }
405     return ResponseEntity.status(HttpStatus.OK).body(HEADER_VALIDATION_SUCCESS);
406   }
407 }