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