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;
27 import org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterface;
28 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
29 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
30 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
31 import org.onap.aai.cl.api.LogFields;
32 import org.onap.aai.cl.api.LogLine;
33 import org.onap.aai.cl.api.Logger;
34 import org.onap.aai.cl.eelf.LoggerFactory;
36 import java.io.IOException;
37 import java.util.concurrent.atomic.AtomicBoolean;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.ws.rs.Path;
40 import javax.ws.rs.core.HttpHeaders;
41 import javax.ws.rs.core.Response;
45 * This class encapsulates the REST end points associated with performing
46 * bulk operations against the document store.
49 public class BulkApi {
52 * Indicates whether or not we have performed the one-time static
53 * initialization required for performing schema validation.
55 protected static AtomicBoolean validationInitialized = new AtomicBoolean(false);
58 * Factory used for importing our payload schema for validation purposes.
60 protected static JsonSchemaFactory schemaFactory = null;
63 * Imported payload schema that will be used by our validation methods.
65 protected static JsonSchema schema = null;
67 protected SearchServiceApi searchService = null;
69 // Instantiate the loggers.
70 private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName());
71 private static Logger auditLogger = LoggerFactory.getInstance()
72 .getAuditLogger(BulkApi.class.getName());
76 * Create a new instance of the BulkApi end point.
78 public BulkApi(SearchServiceApi searchService) {
79 this.searchService = searchService;
84 * Processes client requests containing a set of operations to be
89 * @param operations - JSON structure enumerating the operations to be
91 * @param request - Raw HTTP request.
92 * @param headers - HTTP headers.
93 * @return - A standard REST response structure.
95 public Response processPost(String operations,
96 HttpServletRequest request,
98 DocumentStoreInterface documentStore,
102 // Initialize the MDC Context for logging purposes.
103 ApiUtils.initMdcContext(request, headers);
105 // Set a default result code and entity string for the request.
106 int resultCode = 500;
107 String resultString = "Unexpected error";
109 if (logger.isDebugEnabled()) {
110 logger.debug("SEARCH: Process Bulk Request - operations = ["
111 + operations.replaceAll("\n", "") + " ]");
116 // Validate that the request is correctly authenticated before going
118 if (!searchService.validateRequest(headers, request,
119 ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
120 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
122 return buildResponse(Response.Status.FORBIDDEN.getStatusCode(),
123 "Authentication failure.", request, apiUtils);
126 } catch (Exception e) {
128 // This is a catch all for any unexpected failure trying to perform
129 // the authentication.
130 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
131 "Unexpected authentication failure - cause: " + e.getMessage());
132 if (logger.isDebugEnabled()) {
133 logger.debug("Stack Trace:\n" + e.getStackTrace());
136 return buildResponse(Response.Status.FORBIDDEN.getStatusCode(),
137 "Authentication failure - cause " + e.getMessage(),
142 // We expect a payload containing a JSON structure enumerating the
143 // operations to be performed.
144 if (operations == null) {
145 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
147 return buildResponse(resultCode, "Missing payload", request, apiUtils);
151 // Marshal the supplied json string into a Java object.
152 ObjectMapper mapper = new ObjectMapper();
153 BulkRequest[] requests = null;
155 requests = mapper.readValue(operations, BulkRequest[].class);
157 } catch (IOException e) {
159 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
160 "Failed to marshal operations list: " + e.getMessage());
161 if (logger.isDebugEnabled()) {
162 logger.debug("Stack Trace:\n" + e.getStackTrace());
165 // Populate the result code and entity string for our HTTP response
166 // and return the response to the client..
167 return buildResponse(javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode(),
168 "Unable to marshal operations: " + e.getMessage(),
173 // Verify that our parsed operations list actually contains some valid
175 if (requests.length == 0) {
176 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
179 // Populate the result code and entity string for our HTTP response
180 // and return the response to the client..
181 return buildResponse(javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode(),
182 "Empty operations list in bulk request",
188 // Now, forward the set of bulk operations to the DAO for processing.
189 OperationResult result = documentStore.performBulkOperations(requests);
191 // Populate the result code and entity string for our HTTP response.
192 resultCode = result.getResultCode();
193 resultString = (result.getFailureCause() == null)
194 ? result.getResult() : result.getFailureCause();
196 } catch (DocumentStoreOperationException e) {
198 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
199 "Unexpected failure communicating with document store: " + e.getMessage());
200 if (logger.isDebugEnabled()) {
201 logger.debug("Stack Trace:\n" + e.getStackTrace());
204 // Populate the result code and entity string for our HTTP response.
205 resultCode = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
206 resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
209 // Build our HTTP response.
210 Response response = Response.status(resultCode).entity(resultString).build();
213 if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
214 logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
216 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, (String) response.getEntity());
219 // Finally, return the HTTP response to the client.
220 return buildResponse(resultCode, resultString, request, apiUtils);
225 * This method generates an audit log and returns an HTTP response object.
227 * @param resultCode - The result code to report.
228 * @param resultString - The result string to report.
229 * @param request - The HTTP request to extract data from for the audit log.
230 * @return - An HTTP response object.
232 private Response buildResponse(int resultCode, String resultString,
233 HttpServletRequest request, ApiUtils apiUtils) {
235 Response response = Response.status(resultCode).entity(resultString).build();
237 // Generate our audit log.
238 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
240 .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
241 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
242 ApiUtils.getHttpStatusString(resultCode)),
243 (request != null) ? request.getMethod() : "Unknown",
244 (request != null) ? request.getRequestURL().toString() : "Unknown",
245 (request != null) ? request.getRemoteHost() : "Unknown",
246 Integer.toString(response.getStatus()));
248 // Clear the MDC context so that no other transaction inadvertently
249 // uses our transaction id.
250 ApiUtils.clearMdcContext();