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.onap.aai.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;
29 import org.onap.aai.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterface;
30 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
31 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
32 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
33 import org.openecomp.cl.api.LogFields;
34 import org.openecomp.cl.api.LogLine;
35 import org.openecomp.cl.api.Logger;
36 import org.openecomp.cl.eelf.LoggerFactory;
38 import java.io.IOException;
39 import java.util.concurrent.atomic.AtomicBoolean;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.core.HttpHeaders;
43 import javax.ws.rs.core.Response;
47 * This class encapsulates the REST end points associated with performing
48 * bulk operations against the document store.
51 public class BulkApi {
54 * Indicates whether or not we have performed the one-time static
55 * initialization required for performing schema validation.
57 protected static AtomicBoolean validationInitialized = new AtomicBoolean(false);
60 * Factory used for importing our payload schema for validation purposes.
62 protected static JsonSchemaFactory schemaFactory = null;
65 * Imported payload schema that will be used by our validation methods.
67 protected static JsonSchema schema = null;
69 protected SearchServiceApi searchService = null;
71 // Instantiate the loggers.
72 private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName());
73 private static Logger auditLogger = LoggerFactory.getInstance()
74 .getAuditLogger(BulkApi.class.getName());
78 * Create a new instance of the BulkApi end point.
80 public BulkApi(SearchServiceApi searchService) {
81 this.searchService = searchService;
86 * Processes client requests containing a set of operations to be
91 * @param operations - JSON structure enumerating the operations to be
93 * @param request - Raw HTTP request.
94 * @param headers - HTTP headers.
95 * @return - A standard REST response structure.
97 public Response processPost(String operations,
98 HttpServletRequest request,
100 DocumentStoreInterface documentStore,
104 // Initialize the MDC Context for logging purposes.
105 ApiUtils.initMdcContext(request, headers);
107 // Set a default result code and entity string for the request.
108 int resultCode = 500;
109 String resultString = "Unexpected error";
111 if (logger.isDebugEnabled()) {
112 logger.debug("SEARCH: Process Bulk Request - operations = ["
113 + operations.replaceAll("\n", "") + " ]");
118 // Validate that the request is correctly authenticated before going
120 if (!searchService.validateRequest(headers, request,
121 ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
122 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
124 return buildResponse(Response.Status.FORBIDDEN.getStatusCode(),
125 "Authentication failure.", request, apiUtils);
128 } catch (Exception e) {
130 // This is a catch all for any unexpected failure trying to perform
131 // the authentication.
132 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
133 "Unexpected authentication failure - cause: " + e.getMessage());
134 if (logger.isDebugEnabled()) {
135 logger.debug("Stack Trace:\n" + e.getStackTrace());
138 return buildResponse(Response.Status.FORBIDDEN.getStatusCode(),
139 "Authentication failure - cause " + e.getMessage(),
144 // We expect a payload containing a JSON structure enumerating the
145 // operations to be performed.
146 if (operations == null) {
147 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
149 return buildResponse(resultCode, "Missing payload", request, apiUtils);
153 // Marshal the supplied json string into a Java object.
154 ObjectMapper mapper = new ObjectMapper();
155 BulkRequest[] requests = null;
157 requests = mapper.readValue(operations, BulkRequest[].class);
159 } catch (IOException e) {
161 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
162 "Failed to marshal operations list: " + e.getMessage());
163 if (logger.isDebugEnabled()) {
164 logger.debug("Stack Trace:\n" + e.getStackTrace());
167 // Populate the result code and entity string for our HTTP response
168 // and return the response to the client..
169 return buildResponse(javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode(),
170 "Unable to marshal operations: " + e.getMessage(),
175 // Verify that our parsed operations list actually contains some valid
177 if (requests.length == 0) {
178 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
181 // Populate the result code and entity string for our HTTP response
182 // and return the response to the client..
183 return buildResponse(javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode(),
184 "Empty operations list in bulk request",
190 // Now, forward the set of bulk operations to the DAO for processing.
191 OperationResult result = documentStore.performBulkOperations(requests);
193 // Populate the result code and entity string for our HTTP response.
194 resultCode = result.getResultCode();
195 resultString = (result.getFailureCause() == null)
196 ? result.getResult() : result.getFailureCause();
198 } catch (DocumentStoreOperationException e) {
200 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
201 "Unexpected failure communicating with document store: " + e.getMessage());
202 if (logger.isDebugEnabled()) {
203 logger.debug("Stack Trace:\n" + e.getStackTrace());
206 // Populate the result code and entity string for our HTTP response.
207 resultCode = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
208 resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
211 // Build our HTTP response.
212 Response response = Response.status(resultCode).entity(resultString).build();
215 if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
216 logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
218 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, (String) response.getEntity());
221 // Finally, return the HTTP response to the client.
222 return buildResponse(resultCode, resultString, request, apiUtils);
227 * This method generates an audit log and returns an HTTP response object.
229 * @param resultCode - The result code to report.
230 * @param resultString - The result string to report.
231 * @param request - The HTTP request to extract data from for the audit log.
232 * @return - An HTTP response object.
234 private Response buildResponse(int resultCode, String resultString,
235 HttpServletRequest request, ApiUtils apiUtils) {
237 Response response = Response.status(resultCode).entity(resultString).build();
239 // Generate our audit log.
240 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
242 .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
243 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
244 ApiUtils.getHttpStatusString(resultCode)),
245 (request != null) ? request.getMethod() : "Unknown",
246 (request != null) ? request.getRequestURL().toString() : "Unknown",
247 (request != null) ? request.getRemoteHost() : "Unknown",
248 Integer.toString(response.getStatus()));
250 // Clear the MDC context so that no other transaction inadvertently
251 // uses our transaction id.
252 ApiUtils.clearMdcContext();