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