2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017 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 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.openecomp.sa.rest;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.github.fge.jsonschema.main.JsonSchema;
27 import com.github.fge.jsonschema.main.JsonSchemaFactory;
28 import org.openecomp.cl.api.LogFields;
29 import org.openecomp.cl.api.LogLine;
30 import org.openecomp.cl.api.Logger;
31 import org.openecomp.cl.eelf.LoggerFactory;
32 import org.openecomp.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterface;
33 import org.openecomp.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
34 import org.openecomp.sa.searchdbabstraction.entity.OperationResult;
35 import org.openecomp.sa.searchdbabstraction.logging.SearchDbMsgs;
37 import java.io.IOException;
38 import java.util.concurrent.atomic.AtomicBoolean;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.ws.rs.Path;
41 import javax.ws.rs.core.HttpHeaders;
42 import javax.ws.rs.core.Response;
46 * This class encapsulates the REST end points associated with performing
47 * bulk operations against the document store.
50 public class BulkApi {
53 * Indicates whether or not we have performed the one-time static
54 * initialization required for performing schema validation.
56 protected static AtomicBoolean validationInitialized = new AtomicBoolean(false);
59 * Factory used for importing our payload schema for validation purposes.
61 protected static JsonSchemaFactory schemaFactory = null;
64 * Imported payload schema that will be used by our validation methods.
66 protected static JsonSchema schema = null;
68 protected SearchServiceApi searchService = null;
70 // Instantiate the loggers.
71 private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName());
72 private static Logger auditLogger = LoggerFactory.getInstance()
73 .getAuditLogger(BulkApi.class.getName());
77 * Create a new instance of the BulkApi end point.
79 public BulkApi(SearchServiceApi searchService) {
80 this.searchService = searchService;
85 * Processes client requests containing a set of operations to be
90 * @param operations - JSON structure enumerating the operations to be
92 * @param request - Raw HTTP request.
93 * @param headers - HTTP headers.
94 * @return - A standard REST response structure.
96 public Response processPost(String operations,
97 HttpServletRequest request,
99 DocumentStoreInterface documentStore,
103 // Initialize the MDC Context for logging purposes.
104 ApiUtils.initMdcContext(request, headers);
106 // Set a default result code and entity string for the request.
107 int resultCode = 500;
108 String resultString = "Unexpected error";
110 if (logger.isDebugEnabled()) {
111 logger.debug("SEARCH: Process Bulk Request - operations = ["
112 + operations.replaceAll("\n", "") + " ]");
117 // Validate that the request is correctly authenticated before going
119 if (!searchService.validateRequest(headers, request,
120 ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
121 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
123 return buildResponse(Response.Status.FORBIDDEN.getStatusCode(),
124 "Authentication failure.", request, apiUtils);
127 } catch (Exception e) {
129 // This is a catch all for any unexpected failure trying to perform
130 // the authentication.
131 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
132 "Unexpected authentication failure - cause: " + e.getMessage());
133 if (logger.isDebugEnabled()) {
134 logger.debug("Stack Trace:\n" + e.getStackTrace());
137 return buildResponse(Response.Status.FORBIDDEN.getStatusCode(),
138 "Authentication failure - cause " + e.getMessage(),
143 // We expect a payload containing a JSON structure enumerating the
144 // operations to be performed.
145 if (operations == null) {
146 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
148 return buildResponse(resultCode, "Missing payload", request, apiUtils);
152 // Marshal the supplied json string into a Java object.
153 ObjectMapper mapper = new ObjectMapper();
154 BulkRequest[] requests = null;
156 requests = mapper.readValue(operations, BulkRequest[].class);
158 } catch (IOException e) {
160 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
161 "Failed to marshal operations list: " + e.getMessage());
162 if (logger.isDebugEnabled()) {
163 logger.debug("Stack Trace:\n" + e.getStackTrace());
166 // Populate the result code and entity string for our HTTP response
167 // and return the response to the client..
168 return buildResponse(javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode(),
169 "Unable to marshal operations: " + e.getMessage(),
174 // Verify that our parsed operations list actually contains some valid
176 if (requests.length == 0) {
177 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
180 // Populate the result code and entity string for our HTTP response
181 // and return the response to the client..
182 return buildResponse(javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode(),
183 "Empty operations list in bulk request",
189 // Now, forward the set of bulk operations to the DAO for processing.
190 OperationResult result = documentStore.performBulkOperations(requests);
192 // Populate the result code and entity string for our HTTP response.
193 resultCode = result.getResultCode();
194 resultString = (result.getFailureCause() == null)
195 ? result.getResult() : result.getFailureCause();
197 } catch (DocumentStoreOperationException e) {
199 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
200 "Unexpected failure communicating with document store: " + e.getMessage());
201 if (logger.isDebugEnabled()) {
202 logger.debug("Stack Trace:\n" + e.getStackTrace());
205 // Populate the result code and entity string for our HTTP response.
206 resultCode = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
207 resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
210 // Build our HTTP response.
211 Response response = Response.status(resultCode).entity(resultString).build();
214 if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
215 logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
217 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, (String) response.getEntity());
220 // Finally, return the HTTP response to the client.
221 return buildResponse(resultCode, resultString, request, apiUtils);
226 * This method generates an audit log and returns an HTTP response object.
228 * @param resultCode - The result code to report.
229 * @param resultString - The result string to report.
230 * @param request - The HTTP request to extract data from for the audit log.
231 * @return - An HTTP response object.
233 private Response buildResponse(int resultCode, String resultString,
234 HttpServletRequest request, ApiUtils apiUtils) {
236 Response response = Response.status(resultCode).entity(resultString).build();
238 // Generate our audit log.
239 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
241 .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
242 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
243 ApiUtils.getHttpStatusString(resultCode)),
244 (request != null) ? request.getMethod() : "Unknown",
245 (request != null) ? request.getRequestURL().toString() : "Unknown",
246 (request != null) ? request.getRemoteHost() : "Unknown",
247 Integer.toString(response.getStatus()));
249 // Clear the MDC context so that no other transaction inadvertently
250 // uses our transaction id.
251 ApiUtils.clearMdcContext();