36570dca8256db18febeea26952eee1e73765cfc
[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
25 import org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterface;
26 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
27 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
28 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
29 import org.onap.aai.cl.api.LogFields;
30 import org.onap.aai.cl.api.LogLine;
31 import org.onap.aai.cl.api.Logger;
32 import org.onap.aai.cl.eelf.LoggerFactory;
33 import org.onap.aai.sa.rest.DocumentFieldSchema;
34 import org.onap.aai.sa.rest.DocumentSchema;
35
36 import java.io.FileNotFoundException;
37 import java.io.IOException;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.ws.rs.core.HttpHeaders;
40 import javax.ws.rs.core.Response;
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   private static final String HEADER_VALIDATION_SUCCESS = "SUCCESS";
50   
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 Response 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(Response.Status.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(Response.Status.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(Response.Status.fromStatusCode(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 = javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode();
157       resultString = "Malformed schema: " + e.getMessage();
158
159     } catch (IOException e) {
160
161       // We'll treat this is a general internal error.
162       resultCode = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
163       resultString = "IO Failure: " + e.getMessage();
164     }
165
166     Response response = Response.status(resultCode).entity(resultString).build();
167
168     // Log the result.
169     if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
170       logger.info(SearchDbMsgs.CREATED_INDEX, index);
171     } else {
172       logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
173     }
174
175     // Generate our audit log.
176     auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
177         new LogFields()
178             .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
179             .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
180                 Response.Status.fromStatusCode(resultCode).toString()),
181         (request != null) ? request.getMethod() : "Unknown",
182         (request != null) ? request.getRequestURL().toString() : "Unknown",
183         (request != null) ? request.getRemoteHost() : "Unknown",
184         Integer.toString(response.getStatus()));
185
186     // Clear the MDC context so that no other transaction inadvertently
187     // uses our transaction id.
188     ApiUtils.clearMdcContext();
189
190     // Finally, return the response.
191     return response;
192   }
193   
194   /**
195    * This function accepts any JSON and will "blindly" write it to the 
196    * document store.
197    * 
198    * Note, eventually this "dynamic" flow should follow the same JSON-Schema
199    * validation procedure as the normal create index flow.
200    * 
201    * @param dynamicSchema - The JSON string that will be sent to the document store.
202    * @param index - The name of the index to be created.
203    * @param documentStore - The document store specific interface.
204    * @return The result of the document store interface's operation.
205    */
206   public Response processCreateDynamicIndex(String dynamicSchema, HttpServletRequest request,
207       HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
208
209     Response response = null;
210
211     Response validationResponse = validateRequest(request, headers, index, SearchDbMsgs.INDEX_CREATE_FAILURE);
212
213     if (validationResponse.getStatus() != Response.Status.OK.getStatusCode()) {
214       response = validationResponse;
215     } else {
216       OperationResult result = documentStore.createDynamicIndex(index, dynamicSchema);
217
218       int resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
219       String resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
220
221       response = Response.status(resultCode).entity(resultString).build();
222     }
223
224     return response;
225   }
226
227
228   /**
229    * Processes a client request to remove an index from the document store.
230    * Note that this implicitly deletes all documents contained within that index.
231    *
232    * @param index - The index to be deleted.
233    * @return - A standard REST response.
234    */
235   public Response processDelete(String index,
236                                 HttpServletRequest request,
237                                 HttpHeaders headers,
238                                 DocumentStoreInterface documentStore) {
239
240     // Initialize the MDC Context for logging purposes.
241     ApiUtils.initMdcContext(request, headers);
242
243     // Set a default response in case something unexpected goes wrong.
244     Response response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
245         .entity("Unknown")
246         .build();
247
248     // Validate that the request is correctly authenticated before going
249     // any further.
250     try {
251
252       if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
253           ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
254         logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
255         return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
256       }
257
258     } catch (Exception e) {
259
260       logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
261           "Unexpected authentication failure - cause: " + e.getMessage());
262       return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
263     }
264
265     try {
266       // Send the request to the document store.
267       response = responseFromOperationResult(documentStore.deleteIndex(index));
268
269     } catch (DocumentStoreOperationException e) {
270       response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
271           .entity(e.getMessage())
272           .build();
273     }
274     
275     // Log the result.
276     if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
277       logger.info(SearchDbMsgs.DELETED_INDEX, index);
278     } else {
279       logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, (String) response.getEntity());
280     }
281
282     // Generate our audit log.
283     auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
284         new LogFields()
285             .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
286             .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
287                 response.getStatusInfo().getReasonPhrase()),
288         (request != null) ? request.getMethod() : "Unknown",
289         (request != null) ? request.getRequestURL().toString() : "Unknown",
290         (request != null) ? request.getRemoteHost() : "Unknown",
291         Integer.toString(response.getStatus()));
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 Response}
370    * object.
371    *
372    * @param result - The {@link OperationResult} to be converted.
373    * @return - The equivalent {@link Response} object.
374    */
375   public Response responseFromOperationResult(OperationResult result) {
376
377     if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
378       return Response.status(result.getResultCode()).entity(result.getResult()).build();
379     } else {
380       if (result.getFailureCause() != null) {
381         return Response.status(result.getResultCode()).entity(result.getFailureCause()).build();
382       } else {
383         return Response.status(result.getResultCode()).entity(result.getResult()).build();
384       }
385     }
386   }
387
388   public Response errorResponse(Response.Status 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.getStatusCode())
394             .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
395         (request != null) ? request.getMethod() : "Unknown",
396         (request != null) ? request.getRequestURL().toString() : "Unknown",
397         (request != null) ? request.getRemoteHost() : "Unknown",
398         Integer.toString(status.getStatusCode()));
399
400     // Clear the MDC context so that no other transaction inadvertently
401     // uses our transaction id.
402     ApiUtils.clearMdcContext();
403
404     return Response.status(status)
405         .entity(msg)
406         .build();
407   }
408   
409   /**
410    * A helper method used for validating/authenticating an incoming request.
411    * 
412    * @param request - The http request that will be validated.
413    * @param headers - The http headers that will be validated.
414    * @param index - The name of the index that the document store request is being made against.
415    * @param failureMsgEnum - The logging message to be used upon validation failure.
416    * @return A success or failure response
417    */
418   private Response validateRequest(HttpServletRequest request, HttpHeaders headers, String index, SearchDbMsgs failureMsgEnum) {
419     try {
420       if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
421         logger.warn(failureMsgEnum, index, "Authentication failure.");
422         return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
423       }
424     } catch (Exception e) {
425       logger.warn(failureMsgEnum, index, "Unexpected authentication failure - cause: " + e.getMessage());
426       return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
427     }
428     return Response.status(Response.Status.OK).entity(HEADER_VALIDATION_SUCCESS).build();
429   }
430 }