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;
35 import org.springframework.http.HttpHeaders;
36 import org.springframework.http.HttpStatus;
37 import org.springframework.http.MediaType;
38 import org.springframework.http.ResponseEntity;
41 * This class encapsulates the REST end points associated with manipulating indexes in the document store.
43 public class IndexApi {
46 private static final String HEADER_VALIDATION_SUCCESS = "SUCCESS";
47 protected SearchServiceApi searchService = null;
50 * Configuration for the custom analyzers that will be used for indexing.
52 protected AnalysisConfiguration analysisConfig;
54 // Set up the loggers.
55 private static Logger logger = LoggerFactory.getInstance().getLogger(IndexApi.class.getName());
56 private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(IndexApi.class.getName());
59 public IndexApi(SearchServiceApi searchService) {
60 this.searchService = searchService;
66 * Initializes the end point.
68 * @throws FileNotFoundException
70 * @throws DocumentStoreOperationException
74 // Instantiate our analysis configuration object.
75 analysisConfig = new AnalysisConfiguration();
80 * Processes client requests to create a new index and document type in the document store.
82 * @param documentSchema - The contents of the request body which is expected to be a JSON structure which
83 * corresponds to the schema defined in document.schema.json
84 * @param index - The name of the index to create.
85 * @return - A Standard REST response
87 public ResponseEntity<String> processCreateIndex(String documentSchema, HttpServletRequest request,
88 HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
92 // Initialize the MDC Context for logging purposes.
93 ApiUtils.initMdcContext(request, headers);
95 // Validate that the request is correctly authenticated before going
99 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
100 ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
101 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
102 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
105 } catch (Exception e) {
107 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
108 "Unexpected authentication failure - cause: " + e.getMessage());
109 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
113 // We expect a payload containing the document schema. Make sure
115 if (documentSchema == null) {
116 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload");
117 return errorResponse(HttpStatus.valueOf(resultCode), "Missing payload", request);
123 // Marshal the supplied json string into a document schema object.
124 ObjectMapper mapper = new ObjectMapper();
125 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
127 // Now, ask the DAO to create the index.
128 OperationResult result = documentStore.createIndex(index, schema);
130 // Extract the result code and string from the OperationResult
131 // object so that we can use them to generate a standard REST
133 // Note that we want to return a 201 result code on a successful
134 // create, so if we get back a 200 from the document store,
135 // translate that int a 201.
136 resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
137 resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
139 } catch (com.fasterxml.jackson.core.JsonParseException
140 | com.fasterxml.jackson.databind.JsonMappingException e) {
142 // We were unable to marshal the supplied json string into a valid
143 // document schema, so return an appropriate error response.
144 resultCode = HttpStatus.BAD_REQUEST.value();
145 resultString = "Malformed schema: " + e.getMessage();
147 } catch (IOException e) {
149 // We'll treat this is a general internal error.
150 resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
151 resultString = "IO Failure: " + e.getMessage();
154 ResponseEntity<String> response =
155 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
159 if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
160 logger.info(SearchDbMsgs.CREATED_INDEX, index);
162 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
165 // Generate our audit log.
166 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
167 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode).setField(
168 LogLine.DefinedFields.RESPONSE_DESCRIPTION, HttpStatus.valueOf(resultCode).toString()),
169 (request != null) ? request.getMethod() : "Unknown",
170 (request != null) ? request.getRequestURL ().toString () : "Unknown",
171 (request != null) ? request.getRemoteHost () : "Unknown",
172 Integer.toString(response.getStatusCodeValue ()));
176 // Clear the MDC context so that no other transaction inadvertently
177 // uses our transaction id.
178 ApiUtils.clearMdcContext();
180 // Finally, return the response.
185 * This function accepts any JSON and will "blindly" write it to the document store.
187 * Note, eventually this "dynamic" flow should follow the same JSON-Schema validation procedure as the normal create
190 * @param dynamicSchema - The JSON string that will be sent to the document store.
191 * @param index - The name of the index to be created.
192 * @param documentStore - The document store specific interface.
193 * @return The result of the document store interface's operation.
195 public ResponseEntity<String> processCreateDynamicIndex(String dynamicSchema, HttpServletRequest request,
196 HttpHeaders headers, String index, DocumentStoreInterface documentStore) {
198 ResponseEntity<String> response = null;
200 ResponseEntity<String> validationResponse =
201 validateRequest(request, headers, index, SearchDbMsgs.INDEX_CREATE_FAILURE);
204 if (validationResponse.getStatusCodeValue () != HttpStatus.OK.value ()) {
205 response = validationResponse;
207 OperationResult result = documentStore.createDynamicIndex(index, dynamicSchema);
209 int resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
210 String resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
212 response = ResponseEntity.status(resultCode).body(resultString);
219 * Processes a client request to remove an index from the document store. Note that this implicitly deletes all
220 * documents contained within that index.
222 * @param index - The index to be deleted.
223 * @return - A standard REST response.
225 public ResponseEntity<String> processDelete(String index, HttpServletRequest request, HttpHeaders headers,
226 DocumentStoreInterface documentStore) {
228 // Initialize the MDC Context for logging purposes.
229 ApiUtils.initMdcContext(request, headers);
231 ResponseEntity<String> response;
233 // Validate that the request is correctly authenticated before going
236 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
237 ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
238 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
239 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
242 } catch (Exception e) {
243 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
244 "Unexpected authentication failure - cause: " + e.getMessage());
245 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
249 // Send the request to the document store.
250 response = responseFromOperationResult(documentStore.deleteIndex(index));
251 } catch (DocumentStoreOperationException e) {
252 response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON)
253 .body(e.getMessage());
257 if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
258 logger.info(SearchDbMsgs.DELETED_INDEX, index);
260 logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, response.getBody());
263 // Generate our audit log.
264 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
265 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatusCodeValue()).setField(
266 LogLine.DefinedFields.RESPONSE_DESCRIPTION, response.getStatusCode().getReasonPhrase()),
267 (request != null) ? request.getMethod() : "Unknown",
268 (request != null) ? request.getRequestURL ().toString () : "Unknown",
269 (request != null) ? request.getRemoteHost () : "Unknown",
270 Integer.toString(response.getStatusCodeValue()));
272 // Clear the MDC context so that no other transaction inadvertently
273 // uses our transaction id.
274 ApiUtils.clearMdcContext();
281 * This method takes a JSON format document schema and produces a set of field mappings in the form that Elastic
284 * @param documentSchema - A document schema expressed as a JSON string.
285 * @return - A JSON string expressing an Elastic Search mapping configuration.
286 * @throws com.fasterxml.jackson.core.JsonParseException
287 * @throws com.fasterxml.jackson.databind.JsonMappingException
288 * @throws IOException
290 public String generateDocumentMappings(String documentSchema) throws IOException {
292 // Unmarshal the json content into a document schema object.
293 ObjectMapper mapper = new ObjectMapper();
294 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
296 // Now, generate the Elastic Search mapping json and return it.
297 StringBuilder sb = new StringBuilder();
299 sb.append("\"properties\": {");
301 boolean first = true;
302 for (DocumentFieldSchema field : schema.getFields()) {
310 sb.append("\"").append(field.getName()).append("\": {");
312 // The field type is mandatory.
313 sb.append("\"type\": \"").append(field.getDataType()).append("\"");
315 // If the index field was specified, then append it.
316 if (field.getSearchable() != null) {
317 sb.append(", \"index\": \"").append(field.getSearchable() ? "analyzed" : "not_analyzed").append("\"");
320 // If a search analyzer was specified, then append it.
321 if (field.getSearchAnalyzer() != null) {
322 sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\"");
325 // If an indexing analyzer was specified, then append it.
326 if (field.getIndexAnalyzer() != null) {
327 sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\"");
329 sb.append(", \"analyzer\": \"").append("whitespace").append("\"");
338 logger.debug("Generated document mappings: " + sb.toString());
340 return sb.toString();
345 * Converts an {@link OperationResult} to a standard REST {@link ResponseEntity} object.
347 * @param result - The {@link OperationResult} to be converted.
348 * @return - The equivalent {@link ResponseEntity} object.
350 public ResponseEntity<String> responseFromOperationResult(OperationResult result) {
352 if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
353 return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
354 .body(result.getResult());
356 if (result.getFailureCause() != null) {
357 return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
358 .body(result.getFailureCause());
360 return ResponseEntity.status(result.getResultCode()).contentType(MediaType.APPLICATION_JSON)
361 .body(result.getResult());
366 public ResponseEntity<String> errorResponse(HttpStatus status, String msg, HttpServletRequest request) {
368 // Generate our audit log.
369 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
370 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, status.value())
371 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
372 (request != null) ? request.getMethod() : "Unknown",
373 (request != null) ? request.getRequestURL ().toString () : "Unknown",
374 (request != null) ? request.getRemoteHost() : "Unknown", Integer.toString(status.value()));
376 // Clear the MDC context so that no other transaction inadvertently
377 // uses our transaction id.
378 ApiUtils.clearMdcContext();
380 return ResponseEntity.status(status).contentType ( MediaType.APPLICATION_JSON ).body(msg);
385 * A helper method used for validating/authenticating an incoming request.
387 * @param request - The http request that will be validated.
388 * @param headers - The http headers that will be validated.
389 * @param index - The name of the index that the document store request is being made against.
390 * @param failureMsgEnum - The logging message to be used upon validation failure.
391 * @return A success or failure response
393 private ResponseEntity<String> validateRequest(HttpServletRequest request, HttpHeaders headers, String index,
394 SearchDbMsgs failureMsgEnum) {
396 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
397 ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
398 logger.warn(failureMsgEnum, index, "Authentication failure.");
399 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
401 } catch (Exception e) {
402 logger.warn(failureMsgEnum, index, "Unexpected authentication failure - cause: " + e.getMessage());
403 return errorResponse(HttpStatus.FORBIDDEN, "Authentication failure.", request);
405 return ResponseEntity.status(HttpStatus.OK).body(HEADER_VALIDATION_SUCCESS);