Cleanup project's name in Sonar
[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 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.onap.aai.sa.rest;
24
25 import com.fasterxml.jackson.databind.ObjectMapper;
26
27 import org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterface;
28 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
29 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
30 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
31 import org.openecomp.cl.api.LogFields;
32 import org.openecomp.cl.api.LogLine;
33 import org.openecomp.cl.api.Logger;
34 import org.openecomp.cl.eelf.LoggerFactory;
35 import org.onap.aai.sa.rest.DocumentFieldSchema;
36 import org.onap.aai.sa.rest.DocumentSchema;
37
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.core.HttpHeaders;
42 import javax.ws.rs.core.Response;
43
44
45 /**
46  * This class encapsulates the REST end points associated with manipulating
47  * indexes in the document store.
48  */
49 public class IndexApi {
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   /**
196    * Processes a client request to remove an index from the document store.
197    * Note that this implicitly deletes all documents contained within that index.
198    *
199    * @param index - The index to be deleted.
200    * @return - A standard REST response.
201    */
202   public Response processDelete(String index,
203                                 HttpServletRequest request,
204                                 HttpHeaders headers,
205                                 DocumentStoreInterface documentStore) {
206
207     // Initialize the MDC Context for logging purposes.
208     ApiUtils.initMdcContext(request, headers);
209
210     // Set a default response in case something unexpected goes wrong.
211     Response response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
212         .entity("Unknown")
213         .build();
214
215     // Validate that the request is correctly authenticated before going
216     // any further.
217     try {
218
219       if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
220           ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
221         logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
222         return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
223       }
224
225     } catch (Exception e) {
226
227       logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
228           "Unexpected authentication failure - cause: " + e.getMessage());
229       return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
230     }
231
232
233     try {
234       // Send the request to the document store.
235       response = responseFromOperationResult(documentStore.deleteIndex(index));
236
237     } catch (DocumentStoreOperationException e) {
238       response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
239           .entity(e.getMessage())
240           .build();
241     }
242
243
244     // Log the result.
245     if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
246       logger.info(SearchDbMsgs.DELETED_INDEX, index);
247     } else {
248       logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, (String) response.getEntity());
249     }
250
251     // Generate our audit log.
252     auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
253         new LogFields()
254             .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
255             .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
256                 response.getStatusInfo().getReasonPhrase()),
257         (request != null) ? request.getMethod() : "Unknown",
258         (request != null) ? request.getRequestURL().toString() : "Unknown",
259         (request != null) ? request.getRemoteHost() : "Unknown",
260         Integer.toString(response.getStatus()));
261
262     // Clear the MDC context so that no other transaction inadvertently
263     // uses our transaction id.
264     ApiUtils.clearMdcContext();
265
266     return response;
267   }
268
269
270   /**
271    * This method takes a JSON format document schema and produces a set of
272    * field mappings in the form that Elastic Search expects.
273    *
274    * @param documentSchema - A document schema expressed as a JSON string.
275    * @return - A JSON string expressing an Elastic Search mapping configuration.
276    * @throws com.fasterxml.jackson.core.JsonParseException
277    * @throws com.fasterxml.jackson.databind.JsonMappingException
278    * @throws IOException
279    */
280   public String generateDocumentMappings(String documentSchema)
281       throws com.fasterxml.jackson.core.JsonParseException,
282       com.fasterxml.jackson.databind.JsonMappingException, IOException {
283
284     // Unmarshal the json content into a document schema object.
285     ObjectMapper mapper = new ObjectMapper();
286     DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
287
288     // Now, generate the Elastic Search mapping json and return it.
289     StringBuilder sb = new StringBuilder();
290     sb.append("{");
291     sb.append("\"properties\": {");
292
293     boolean first = true;
294     for (DocumentFieldSchema field : schema.getFields()) {
295
296       if (!first) {
297         sb.append(",");
298       } else {
299         first = false;
300       }
301
302       sb.append("\"").append(field.getName()).append("\": {");
303
304       // The field type is mandatory.
305       sb.append("\"type\": \"").append(field.getDataType()).append("\"");
306
307       // If the index field was specified, then append it.
308       if (field.getSearchable() != null) {
309         sb.append(", \"index\": \"").append(field.getSearchable()
310             ? "analyzed" : "not_analyzed").append("\"");
311       }
312
313       // If a search analyzer was specified, then append it.
314       if (field.getSearchAnalyzer() != null) {
315         sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\"");
316       }
317
318       // If an indexing analyzer was specified, then append it.
319       if (field.getIndexAnalyzer() != null) {
320         sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\"");
321       } else {
322         sb.append(", \"analyzer\": \"").append("whitespace").append("\"");
323       }
324
325       sb.append("}");
326     }
327
328     sb.append("}");
329     sb.append("}");
330
331     logger.debug("Generated document mappings: " + sb.toString());
332
333     return sb.toString();
334   }
335
336
337   /**
338    * Converts an {@link OperationResult} to a standard REST {@link Response}
339    * object.
340    *
341    * @param result - The {@link OperationResult} to be converted.
342    * @return - The equivalent {@link Response} object.
343    */
344   public Response responseFromOperationResult(OperationResult result) {
345
346     if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
347       return Response.status(result.getResultCode()).entity(result.getResult()).build();
348     } else {
349       if (result.getFailureCause() != null) {
350         return Response.status(result.getResultCode()).entity(result.getFailureCause()).build();
351       } else {
352         return Response.status(result.getResultCode()).entity(result.getResult()).build();
353       }
354     }
355   }
356
357   public Response errorResponse(Response.Status status, String msg, HttpServletRequest request) {
358
359     // Generate our audit log.
360     auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
361         new LogFields()
362             .setField(LogLine.DefinedFields.RESPONSE_CODE, status.getStatusCode())
363             .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
364         (request != null) ? request.getMethod() : "Unknown",
365         (request != null) ? request.getRequestURL().toString() : "Unknown",
366         (request != null) ? request.getRemoteHost() : "Unknown",
367         Integer.toString(status.getStatusCode()));
368
369     // Clear the MDC context so that no other transaction inadvertently
370     // uses our transaction id.
371     ApiUtils.clearMdcContext();
372
373     return Response.status(status)
374         .entity(msg)
375         .build();
376   }
377
378
379 }