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 org.onap.aai.cl.api.LogFields;
27 import org.onap.aai.cl.api.LogLine;
28 import org.onap.aai.cl.api.Logger;
29 import org.onap.aai.cl.eelf.LoggerFactory;
30 import org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterface;
31 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
32 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
33 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
34 import org.springframework.http.HttpHeaders;
35 import org.springframework.http.HttpStatus;
36 import org.springframework.http.MediaType;
37 import org.springframework.http.ResponseEntity;
39 import javax.servlet.http.HttpServletRequest;
40 import java.io.IOException;
41 import java.util.concurrent.atomic.AtomicBoolean;
45 * This class encapsulates the REST end points associated with performing
46 * bulk operations against the document store.
48 public class BulkApi {
51 * Indicates whether or not we have performed the one-time static
52 * initialization required for performing schema validation.
54 protected static AtomicBoolean validationInitialized = new AtomicBoolean(false);
57 * Factory used for importing our payload schema for validation purposes.
59 protected static JsonSchemaFactory schemaFactory = null;
62 * Imported payload schema that will be used by our validation methods.
64 protected static JsonSchema schema = null;
66 protected SearchServiceApi searchService = null;
68 // Instantiate the loggers.
69 private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName());
70 private static Logger auditLogger = LoggerFactory.getInstance()
71 .getAuditLogger(BulkApi.class.getName());
75 * Create a new instance of the BulkApi end point.
77 public BulkApi(SearchServiceApi searchService) {
78 this.searchService = searchService;
83 * Processes client requests containing a set of operations to be
88 * @param operations - JSON structure enumerating the operations to be
90 * @param request - Raw HTTP request.
91 * @param headers - HTTP headers.
92 * @return - A standard REST response structure.
94 public ResponseEntity<String> processPost(String operations,
95 HttpServletRequest request,
97 DocumentStoreInterface documentStore,
101 // Initialize the MDC Context for logging purposes.
102 ApiUtils.initMdcContext(request, headers);
104 // Set a default result code and entity string for the request.
105 int resultCode = 500;
106 String resultString = "Unexpected error";
108 if (logger.isDebugEnabled()) {
109 logger.debug("SEARCH: Process Bulk Request - operations = ["
110 + operations.replaceAll("\n", "") + " ]");
115 // Validate that the request is correctly authenticated before going
117 if (!searchService.validateRequest(headers, request,
118 ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
119 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
121 return buildResponse(HttpStatus.FORBIDDEN.value (),
122 "Authentication failure.", request, apiUtils);
125 } catch (Exception e) {
127 // This is a catch all for any unexpected failure trying to perform
128 // the authentication.
129 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
130 "Unexpected authentication failure - cause: " + e.getMessage());
131 if (logger.isDebugEnabled()) {
132 logger.debug("Stack Trace:\n" + e.getStackTrace());
135 return buildResponse(HttpStatus.FORBIDDEN.value (),
136 "Authentication failure - cause " + e.getMessage(),
141 // We expect a payload containing a JSON structure enumerating the
142 // operations to be performed.
143 if (operations == null) {
144 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
146 return buildResponse(resultCode, "Missing payload", request, apiUtils);
150 // Marshal the supplied json string into a Java object.
151 ObjectMapper mapper = new ObjectMapper();
152 BulkRequest[] requests = null;
154 requests = mapper.readValue(operations, BulkRequest[].class);
156 } catch (IOException e) {
158 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
159 "Failed to marshal operations list: " + e.getMessage());
160 if (logger.isDebugEnabled()) {
161 logger.debug("Stack Trace:\n" + e.getStackTrace());
164 // Populate the result code and entity string for our HTTP response
165 // and return the response to the client..
166 return buildResponse(HttpStatus.BAD_REQUEST.value(),
167 "Unable to marshal operations: " + e.getMessage(),
172 // Verify that our parsed operations list actually contains some valid
174 if (requests.length == 0) {
175 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
178 // Populate the result code and entity string for our HTTP response
179 // and return the response to the client..
180 return buildResponse(HttpStatus.BAD_REQUEST.value(),
181 "Empty operations list in bulk request",
187 // Now, forward the set of bulk operations to the DAO for processing.
188 OperationResult result = documentStore.performBulkOperations(requests);
190 // Populate the result code and entity string for our HTTP response.
191 resultCode = result.getResultCode();
192 resultString = (result.getFailureCause() == null)
193 ? result.getResult() : result.getFailureCause();
195 } catch (DocumentStoreOperationException e) {
197 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
198 "Unexpected failure communicating with document store: " + e.getMessage());
199 if (logger.isDebugEnabled()) {
200 logger.debug("Stack Trace:\n" + e.getStackTrace());
203 // Populate the result code and entity string for our HTTP response.
204 resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value ();
205 resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
208 // Build our HTTP response.
209 ResponseEntity response = ResponseEntity.status(resultCode).contentType ( MediaType.APPLICATION_JSON ).body(resultString);
212 if ((response.getStatusCodeValue () >= 200) && (response.getStatusCodeValue () < 300)) {
213 logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
215 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, (String) response.getBody ());
218 // Finally, return the HTTP response to the client.
219 return buildResponse(resultCode, resultString, request, apiUtils);
224 * This method generates an audit log and returns an HTTP response object.
226 * @param resultCode - The result code to report.
227 * @param resultString - The result string to report.
228 * @param request - The HTTP request to extract data from for the audit log.
229 * @return - An HTTP response object.
231 private ResponseEntity<String> buildResponse(int resultCode, String resultString,
232 HttpServletRequest request, ApiUtils apiUtils) {
234 ResponseEntity<String> response = ResponseEntity.status(resultCode).contentType ( MediaType.APPLICATION_JSON ) .body(resultString);
236 // Generate our audit log.
237 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
239 .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
240 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
241 ApiUtils.getHttpStatusString(resultCode)),
242 (request != null) ? request.getMethod().toString () : "Unknown",
243 (request != null) ? request.getRequestURL ().toString () : "Unknown",
244 (request != null) ? request.getRemoteHost () : "Unknown",
245 Integer.toString(response.getStatusCodeValue ()));
247 // Clear the MDC context so that no other transaction inadvertently
248 // uses our transaction id.
249 ApiUtils.clearMdcContext();