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