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
45 * bulk operations against the document store.
47 public class BulkApi {
50 * Indicates whether or not we have performed the one-time static
51 * initialization required for performing schema validation.
53 protected static AtomicBoolean validationInitialized = new AtomicBoolean(false);
56 * Factory used for importing our payload schema for validation purposes.
58 protected static JsonSchemaFactory schemaFactory = null;
61 * Imported payload schema that will be used by our validation methods.
63 protected static JsonSchema schema = null;
65 protected SearchServiceApi searchService = null;
67 // Instantiate the loggers.
68 private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName());
69 private static Logger auditLogger = LoggerFactory.getInstance()
70 .getAuditLogger(BulkApi.class.getName());
74 * Create a new instance of the BulkApi end point.
76 public BulkApi(SearchServiceApi searchService) {
77 this.searchService = searchService;
82 * Processes client requests containing a set of operations to be
87 * @param operations - JSON structure enumerating the operations to be
89 * @param request - Raw HTTP request.
90 * @param headers - HTTP headers.
91 * @return - A standard REST response structure.
93 public ResponseEntity<String> processPost(String operations,
94 HttpServletRequest request,
96 DocumentStoreInterface documentStore,
100 // Initialize the MDC Context for logging purposes.
101 ApiUtils.initMdcContext(request, headers);
103 // Set a default result code and entity string for the request.
104 int resultCode = 500;
105 String resultString = "Unexpected error";
107 if (logger.isDebugEnabled()) {
108 logger.debug("SEARCH: Process Bulk Request - operations = ["
109 + operations.replaceAll("\n", "") + " ]");
114 // Validate that the request is correctly authenticated before going
116 if (!searchService.validateRequest(headers, request,
117 ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
118 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
120 return buildResponse(HttpStatus.FORBIDDEN.value (),
121 "Authentication failure.", request, apiUtils);
124 } catch (Exception e) {
126 // This is a catch all for any unexpected failure trying to perform
127 // the authentication.
128 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
129 "Unexpected authentication failure - cause: " + e.getMessage());
130 if (logger.isDebugEnabled()) {
131 logger.debug("Stack Trace:\n" + e.getStackTrace());
134 return buildResponse(HttpStatus.FORBIDDEN.value (),
135 "Authentication failure - cause " + e.getMessage(),
140 // We expect a payload containing a JSON structure enumerating the
141 // operations to be performed.
142 if (operations == null) {
143 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
145 return buildResponse(resultCode, "Missing payload", request, apiUtils);
149 // Marshal the supplied json string into a Java object.
150 ObjectMapper mapper = new ObjectMapper();
151 BulkRequest[] requests = null;
153 requests = mapper.readValue(operations, BulkRequest[].class);
155 } catch (IOException e) {
157 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
158 "Failed to marshal operations list: " + e.getMessage());
159 if (logger.isDebugEnabled()) {
160 logger.debug("Stack Trace:\n" + e.getStackTrace());
163 // Populate the result code and entity string for our HTTP response
164 // and return the response to the client..
165 return buildResponse(HttpStatus.BAD_REQUEST.value(),
166 "Unable to marshal operations: " + e.getMessage(),
171 // Verify that our parsed operations list actually contains some valid
173 if (requests.length == 0) {
174 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
177 // Populate the result code and entity string for our HTTP response
178 // and return the response to the client..
179 return buildResponse(HttpStatus.BAD_REQUEST.value(),
180 "Empty operations list in bulk request",
186 // Now, forward the set of bulk operations to the DAO for processing.
187 OperationResult result = documentStore.performBulkOperations(requests);
189 // Populate the result code and entity string for our HTTP response.
190 resultCode = result.getResultCode();
191 resultString = (result.getFailureCause() == null)
192 ? result.getResult() : result.getFailureCause();
194 } catch (DocumentStoreOperationException e) {
196 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
197 "Unexpected failure communicating with document store: " + e.getMessage());
198 if (logger.isDebugEnabled()) {
199 logger.debug("Stack Trace:\n" + e.getStackTrace());
202 // Populate the result code and entity string for our HTTP response.
203 resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value ();
204 resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
207 // Build our HTTP response.
208 ResponseEntity response = ResponseEntity.status(resultCode).contentType ( MediaType.APPLICATION_JSON ).body(resultString);
211 if ((response.getStatusCodeValue () >= 200) && (response.getStatusCodeValue () < 300)) {
212 logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
214 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, (String) response.getBody ());
217 // Finally, return the HTTP response to the client.
218 return buildResponse(resultCode, resultString, request, apiUtils);
223 * This method generates an audit log and returns an HTTP response object.
225 * @param resultCode - The result code to report.
226 * @param resultString - The result string to report.
227 * @param request - The HTTP request to extract data from for the audit log.
228 * @return - An HTTP response object.
230 private ResponseEntity<String> buildResponse(int resultCode, String resultString,
231 HttpServletRequest request, ApiUtils apiUtils) {
233 ResponseEntity<String> response = ResponseEntity.status(resultCode).contentType ( MediaType.APPLICATION_JSON ) .body(resultString);
235 // Generate our audit log.
236 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
238 .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
239 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
240 ApiUtils.getHttpStatusString(resultCode)),
241 (request != null) ? request.getMethod().toString () : "Unknown",
242 (request != null) ? request.getRequestURL ().toString () : "Unknown",
243 (request != null) ? request.getRemoteHost () : "Unknown",
244 Integer.toString(response.getStatusCodeValue ()));
246 // Clear the MDC context so that no other transaction inadvertently
247 // uses our transaction id.
248 ApiUtils.clearMdcContext();