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 com.github.fge.jsonschema.main.JsonSchema;
25 import com.github.fge.jsonschema.main.JsonSchemaFactory;
26 import java.io.IOException;
27 import java.util.concurrent.atomic.AtomicBoolean;
28 import javax.servlet.http.HttpServletRequest;
29 import org.onap.aai.cl.api.LogFields;
30 import org.onap.aai.cl.api.LogLine;
31 import org.onap.aai.cl.api.Logger;
32 import org.onap.aai.cl.eelf.LoggerFactory;
33 import org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterface;
34 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
35 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
36 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
37 import org.springframework.http.HttpHeaders;
38 import org.springframework.http.HttpStatus;
39 import org.springframework.http.MediaType;
40 import org.springframework.http.ResponseEntity;
43 * This class encapsulates the REST end points associated with performing bulk operations against the document store.
45 public class BulkApi {
48 * Indicates whether or not we have performed the one-time static initialization required for performing schema
51 protected static AtomicBoolean validationInitialized = new AtomicBoolean(false);
54 * Factory used for importing our payload schema for validation purposes.
56 protected static JsonSchemaFactory schemaFactory = null;
59 * Imported payload schema that will be used by our validation methods.
61 protected static JsonSchema schema = null;
63 protected SearchServiceApi searchService = null;
65 // Instantiate the loggers.
66 private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName());
67 private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(BulkApi.class.getName());
69 private static final String MSG_STACK_TRACE = "Stack Trace:\n";
72 * Create a new instance of the BulkApi end point.
74 public BulkApi(SearchServiceApi searchService) {
75 this.searchService = searchService;
80 * Processes client requests containing a set of operations to be performed in bulk.
85 * @param operations - JSON structure enumerating the operations to be performed.
86 * @param request - Raw HTTP request.
87 * @param headers - HTTP headers.
88 * @return - A standard REST response structure.
90 public ResponseEntity<String> processPost(String operations, HttpServletRequest request, HttpHeaders headers,
91 DocumentStoreInterface documentStore) {
92 ApiUtils.initMdcContext(request, headers);
94 if (logger.isDebugEnabled()) {
95 logger.debug("SEARCH: Process Bulk Request - operations = [" + operations.replaceAll("\n", "") + " ]");
98 // We expect a payload containing a JSON structure enumerating the operations to be performed.
99 if (operations == null) {
100 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
101 return buildResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Missing payload", request);
105 // Validate that the request is correctly authenticated before going any further.
106 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
107 ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
108 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
110 return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure.", request);
112 } catch (Exception e) {
113 // This is a catch all for any unexpected failure trying to perform the authentication.
114 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
115 "Unexpected authentication failure - cause: " + e.getMessage());
116 if (logger.isDebugEnabled()) {
117 logger.debug(MSG_STACK_TRACE + e.getStackTrace());
120 return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure - cause " + e.getMessage(),
124 // Marshal the supplied json string into a Java object.
125 ObjectMapper mapper = new ObjectMapper();
126 BulkRequest[] requests = null;
128 requests = mapper.readValue(operations, BulkRequest[].class);
129 } catch (IOException e) {
130 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Failed to marshal operations list: " + e.getMessage());
131 if (logger.isDebugEnabled()) {
132 logger.debug(MSG_STACK_TRACE + e.getStackTrace());
134 // Populate the result code and entity string for our HTTP response
135 // and return the response to the client..
136 return buildResponse(HttpStatus.BAD_REQUEST.value(), "Unable to marshal operations: " + e.getMessage(),
140 // Verify that our parsed operations list actually contains some valid operations.
141 if (requests.length == 0) {
142 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
144 // Populate the result code and entity string for our HTTP response
145 // and return the response to the client..
146 return buildResponse(HttpStatus.BAD_REQUEST.value(), "Empty operations list in bulk request", request);
153 // Now, forward the set of bulk operations to the DAO for processing.
154 OperationResult result = documentStore.performBulkOperations(requests);
156 resultCode = result.getResultCode();
157 resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
158 } catch (DocumentStoreOperationException e) {
159 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
160 "Unexpected failure communicating with document store: " + e.getMessage());
161 if (logger.isDebugEnabled()) {
162 logger.debug(MSG_STACK_TRACE + e.getStackTrace());
165 resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
166 resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
169 ResponseEntity<String> response =
170 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
172 if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
173 logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
175 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, response.getBody());
178 return buildResponse(resultCode, resultString, request);
182 * This method generates an audit log and returns an HTTP response object.
184 * @param resultCode - The result code to report.
185 * @param resultString - The result string to report.
186 * @param request - The HTTP request to extract data from for the audit log.
187 * @return - An HTTP response object.
189 private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request) {
190 ResponseEntity<String> response =
191 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
193 // Generate our audit log.
194 String unknownLogField = "Unknown";
195 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
196 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
197 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, ApiUtils.getHttpStatusString(resultCode)),
198 (request != null) ? request.getMethod() : unknownLogField,
199 (request != null) ? request.getRequestURL().toString() : unknownLogField,
200 (request != null) ? request.getRemoteHost() : unknownLogField,
201 Integer.toString(response.getStatusCodeValue()));
203 // Clear the MDC context so that no other transaction inadvertently
204 // uses our transaction id.
205 ApiUtils.clearMdcContext();