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