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;
44 * This class encapsulates the REST end points associated with performing bulk operations against the document store.
46 public class BulkApi {
49 * Indicates whether or not we have performed the one-time static initialization required for performing schema
52 protected static AtomicBoolean validationInitialized = new AtomicBoolean(false);
55 * Factory used for importing our payload schema for validation purposes.
57 protected static JsonSchemaFactory schemaFactory = null;
60 * Imported payload schema that will be used by our validation methods.
62 protected static JsonSchema schema = null;
64 protected SearchServiceApi searchService = null;
66 // Instantiate the loggers.
67 private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName());
68 private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(BulkApi.class.getName());
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, ApiUtils apiUtils) {
94 // Initialize the MDC Context for logging purposes.
95 ApiUtils.initMdcContext(request, headers);
97 // Set a default result code and entity string for the request.
99 String resultString = "Unexpected error";
101 if (logger.isDebugEnabled()) {
102 logger.debug("SEARCH: Process Bulk Request - operations = [" + operations.replaceAll("\n", "") + " ]");
107 // Validate that the request is correctly authenticated before going
109 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
110 ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
111 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
113 return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure.", request, apiUtils);
116 } catch (Exception e) {
118 // This is a catch all for any unexpected failure trying to perform
119 // the authentication.
120 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
121 "Unexpected authentication failure - cause: " + e.getMessage());
122 if (logger.isDebugEnabled()) {
123 logger.debug("Stack Trace:\n" + e.getStackTrace());
126 return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure - cause " + e.getMessage(),
130 // We expect a payload containing a JSON structure enumerating the
131 // operations to be performed.
132 if (operations == null) {
133 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
135 return buildResponse(resultCode, "Missing payload", request, apiUtils);
139 // Marshal the supplied json string into a Java object.
140 ObjectMapper mapper = new ObjectMapper();
141 BulkRequest[] requests = null;
143 requests = mapper.readValue(operations, BulkRequest[].class);
145 } catch (IOException e) {
147 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Failed to marshal operations list: " + e.getMessage());
148 if (logger.isDebugEnabled()) {
149 logger.debug("Stack Trace:\n" + e.getStackTrace());
152 // Populate the result code and entity string for our HTTP response
153 // and return the response to the client..
154 return buildResponse(HttpStatus.BAD_REQUEST.value(), "Unable to marshal operations: " + e.getMessage(),
158 // Verify that our parsed operations list actually contains some valid
160 if (requests.length == 0) {
161 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
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(), "Empty operations list in bulk request", request,
171 // Now, forward the set of bulk operations to the DAO for processing.
172 OperationResult result = documentStore.performBulkOperations(requests);
174 // Populate the result code and entity string for our HTTP response.
175 resultCode = result.getResultCode();
176 resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
178 } catch (DocumentStoreOperationException e) {
180 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
181 "Unexpected failure communicating with document store: " + e.getMessage());
182 if (logger.isDebugEnabled()) {
183 logger.debug("Stack Trace:\n" + e.getStackTrace());
186 // Populate the result code and entity string for our HTTP response.
187 resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
188 resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
191 // Build our HTTP response.
192 ResponseEntity response =
193 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
196 if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
197 logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
199 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, (String) response.getBody());
202 // Finally, return the HTTP response to the client.
203 return buildResponse(resultCode, resultString, request, apiUtils);
208 * This method generates an audit log and returns an HTTP response object.
210 * @param resultCode - The result code to report.
211 * @param resultString - The result string to report.
212 * @param request - The HTTP request to extract data from for the audit log.
213 * @return - An HTTP response object.
215 private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request,
218 ResponseEntity<String> response =
219 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
221 // Generate our audit log.
222 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
223 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
224 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, ApiUtils.getHttpStatusString(resultCode)),
225 (request != null) ? request.getMethod().toString() : "Unknown",
226 (request != null) ? request.getRequestURL().toString() : "Unknown",
227 (request != null) ? request.getRemoteHost() : "Unknown",
228 Integer.toString(response.getStatusCodeValue()));
230 // Clear the MDC context so that no other transaction inadvertently
231 // uses our transaction id.
232 ApiUtils.clearMdcContext();