2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.sa.rest;
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;
36 import org.springframework.http.HttpHeaders;
37 import org.springframework.http.HttpStatus;
38 // import org.springframework.http.server.HttpServletRequest;
39 import org.springframework.http.MediaType;
40 import org.springframework.http.ResponseEntity;
44 * This class encapsulates the REST end points associated with manipulating
45 * indexes in the document store.
47 public class IndexApi {
50 private static final String HEADER_VALIDATION_SUCCESS = "SUCCESS";
51 protected SearchServiceApi searchService = null;
54 * Configuration for the custom analyzers that will be used for indexing.
56 protected AnalysisConfiguration analysisConfig;
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());
65 public IndexApi(SearchServiceApi searchService) {
66 this.searchService = searchService;
72 * Initializes the end point.
74 * @throws FileNotFoundException
76 * @throws DocumentStoreOperationException
80 // Instantiate our analysis configuration object.
81 analysisConfig = new AnalysisConfiguration();
86 * Processes client requests to create a new index and document type in the
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
95 public ResponseEntity<String> processCreateIndex (String documentSchema,
96 HttpServletRequest request,
99 DocumentStoreInterface documentStore) {
101 int resultCode = 500;
102 String resultString = "Unexpected error";
104 // Initialize the MDC Context for logging purposes.
105 ApiUtils.initMdcContext(request, headers);
107 // Validate that the request is correctly authenticated before going
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(HttpStatus.FORBIDDEN, "Authentication failure.", request);
117 } catch (Exception e) {
119 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
120 "Unexpected authentication failure - cause: " + e.getMessage());
121 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
125 // We expect a payload containing the document schema. Make sure
127 if (documentSchema == null) {
128 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload");
129 return errorResponse(HttpStatus.valueOf(resultCode), "Missing payload", request);
134 // Marshal the supplied json string into a document schema object.
135 ObjectMapper mapper = new ObjectMapper();
136 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
138 // Now, ask the DAO to create the index.
139 OperationResult result = documentStore.createIndex(index, schema);
141 // Extract the result code and string from the OperationResult
142 // object so that we can use them to generate a standard REST
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();
151 } catch (com.fasterxml.jackson.core.JsonParseException
152 | com.fasterxml.jackson.databind.JsonMappingException e) {
154 // We were unable to marshal the supplied json string into a valid
155 // document schema, so return an appropriate error response.
156 resultCode = HttpStatus.BAD_REQUEST.value();
157 resultString = "Malformed schema: " + e.getMessage();
159 } catch (IOException e) {
161 // We'll treat this is a general internal error.
162 resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
163 resultString = "IO Failure: " + e.getMessage();
166 ResponseEntity<String> response = ResponseEntity.status(resultCode).contentType ( MediaType.APPLICATION_JSON ).body(resultString);
170 if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
171 logger.info(SearchDbMsgs.CREATED_INDEX, index);
173 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
176 // Generate our audit log.
177 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
179 .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
180 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
181 HttpStatus.valueOf(resultCode).toString()),
182 (request != null) ? request.getMethod().toString () : "Unknown",
183 (request != null) ? request.getRequestURL ().toString () : "Unknown",
184 (request != null) ? request.getRemoteHost () : "Unknown",
185 Integer.toString(response.getStatusCodeValue ()));
189 // Clear the MDC context so that no other transaction inadvertently
190 // uses our transaction id.
191 ApiUtils.clearMdcContext();
193 // Finally, return the response.
198 * This function accepts any JSON and will "blindly" write it to the
201 * Note, eventually this "dynamic" flow should follow the same JSON-Schema
202 * validation procedure as the normal create index flow.
204 * @param dynamicSchema - The JSON string that will be sent to the document store.
205 * @param index - The name of the index to be created.
206 * @param documentStore - The document store specific interface.
207 * @return The result of the document store interface's operation.
209 public ResponseEntity<String> processCreateDynamicIndex(String dynamicSchema, HttpServletRequest request,
210 HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
212 ResponseEntity<String> response = null;
214 ResponseEntity<String> validationResponse = validateRequest(request, headers, index, SearchDbMsgs.INDEX_CREATE_FAILURE);
217 if (validationResponse.getStatusCodeValue () != HttpStatus.OK.value ()) {
218 response = validationResponse;
220 OperationResult result = documentStore.createDynamicIndex(index, dynamicSchema);
222 int resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
223 String resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
225 response = ResponseEntity.status(resultCode).body(resultString);
232 * Processes a client request to remove an index from the document store.
233 * Note that this implicitly deletes all documents contained within that index.
235 * @param index - The index to be deleted.
236 * @return - A standard REST response.
238 public ResponseEntity<String> processDelete(String index,
239 HttpServletRequest request,
241 DocumentStoreInterface documentStore) {
243 // Initialize the MDC Context for logging purposes.
244 ApiUtils.initMdcContext(request, headers);
246 // Set a default response in case something unexpected goes wrong.
247 ResponseEntity<String> response = ResponseEntity.status ( HttpStatus.INTERNAL_SERVER_ERROR ).body ( "Unknown" );
249 // Validate that the request is correctly authenticated before going
253 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
254 ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
255 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
256 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
259 } catch (Exception e) {
261 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
262 "Unexpected authentication failure - cause: " + e.getMessage());
263 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
268 // Send the request to the document store.
269 response = responseFromOperationResult(documentStore.deleteIndex(index));
271 } catch (DocumentStoreOperationException e) {
272 response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType ( MediaType.APPLICATION_JSON ).body(e.getMessage());
276 if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
277 logger.info(SearchDbMsgs.DELETED_INDEX, index);
279 logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, (String) response.getBody ());
282 // Generate our audit log.
283 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
285 .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatusCodeValue())
286 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
287 response.getStatusCode ().getReasonPhrase()),
288 (request != null) ? request.getMethod().toString () : "Unknown",
289 (request != null) ? request.getRequestURL ().toString () : "Unknown",
290 (request != null) ? request.getRemoteHost () : "Unknown",
291 Integer.toString(response.getStatusCodeValue()));
293 // Clear the MDC context so that no other transaction inadvertently
294 // uses our transaction id.
295 ApiUtils.clearMdcContext();
302 * This method takes a JSON format document schema and produces a set of
303 * field mappings in the form that Elastic Search expects.
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
311 public String generateDocumentMappings(String documentSchema)
312 throws com.fasterxml.jackson.core.JsonParseException,
313 com.fasterxml.jackson.databind.JsonMappingException, IOException {
315 // Unmarshal the json content into a document schema object.
316 ObjectMapper mapper = new ObjectMapper();
317 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
319 // Now, generate the Elastic Search mapping json and return it.
320 StringBuilder sb = new StringBuilder();
322 sb.append("\"properties\": {");
324 boolean first = true;
325 for (DocumentFieldSchema field : schema.getFields()) {
333 sb.append("\"").append(field.getName()).append("\": {");
335 // The field type is mandatory.
336 sb.append("\"type\": \"").append(field.getDataType()).append("\"");
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("\"");
344 // If a search analyzer was specified, then append it.
345 if (field.getSearchAnalyzer() != null) {
346 sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\"");
349 // If an indexing analyzer was specified, then append it.
350 if (field.getIndexAnalyzer() != null) {
351 sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\"");
353 sb.append(", \"analyzer\": \"").append("whitespace").append("\"");
362 logger.debug("Generated document mappings: " + sb.toString());
364 return sb.toString();
369 * Converts an {@link OperationResult} to a standard REST {@link ResponseEntity}
372 * @param result - The {@link OperationResult} to be converted.
373 * @return - The equivalent {@link ResponseEntity} object.
375 public ResponseEntity<String> responseFromOperationResult(OperationResult result) {
377 if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
378 return ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(result.getResult());
380 if (result.getFailureCause() != null) {
381 return ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(result.getFailureCause());
383 return ResponseEntity.status(result.getResultCode()).contentType ( MediaType.APPLICATION_JSON ).body(result.getResult());
388 public ResponseEntity<String> errorResponse(HttpStatus status, String msg, HttpServletRequest request) {
390 // Generate our audit log.
391 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
393 .setField(LogLine.DefinedFields.RESPONSE_CODE, status.value ())
394 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
395 (request != null) ? request.getMethod().toString () : "Unknown",
396 (request != null) ? request.getRequestURL ().toString () : "Unknown",
397 (request != null) ? request.getRemoteHost () : "Unknown",
398 Integer.toString(status.value ()));
400 // Clear the MDC context so that no other transaction inadvertently
401 // uses our transaction id.
402 ApiUtils.clearMdcContext();
404 return ResponseEntity.status(status).contentType ( MediaType.APPLICATION_JSON ).body(msg);
409 * A helper method used for validating/authenticating an incoming request.
411 * @param request - The http request that will be validated.
412 * @param headers - The http headers that will be validated.
413 * @param index - The name of the index that the document store request is being made against.
414 * @param failureMsgEnum - The logging message to be used upon validation failure.
415 * @return A success or failure response
417 private ResponseEntity<String> validateRequest(HttpServletRequest request, HttpHeaders headers, String index, SearchDbMsgs failureMsgEnum) {
419 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
420 logger.warn(failureMsgEnum, index, "Authentication failure.");
421 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
423 } catch (Exception e) {
424 logger.warn(failureMsgEnum, index, "Unexpected authentication failure - cause: " + e.getMessage());
425 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
427 return ResponseEntity.status(HttpStatus.OK).body(HEADER_VALIDATION_SUCCESS);