Fix file formatting issues
[aai/search-data-service.git] / src / main / java / org / onap / aai / sa / rest / BulkApi.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
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
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21 package org.onap.aai.sa.rest;
22
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;
41
42 /**
43  * This class encapsulates the REST end points associated with performing bulk operations against the document store.
44  */
45 public class BulkApi {
46
47     /**
48      * Indicates whether or not we have performed the one-time static initialization required for performing schema
49      * validation.
50      */
51     protected static AtomicBoolean validationInitialized = new AtomicBoolean(false);
52
53     /**
54      * Factory used for importing our payload schema for validation purposes.
55      */
56     protected static JsonSchemaFactory schemaFactory = null;
57
58     /**
59      * Imported payload schema that will be used by our validation methods.
60      */
61     protected static JsonSchema schema = null;
62
63     protected SearchServiceApi searchService = null;
64
65     // Instantiate the loggers.
66     private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName());
67     private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(BulkApi.class.getName());
68
69     private static final String MSG_STACK_TRACE = "Stack Trace:\n";
70
71     /**
72      * Create a new instance of the BulkApi end point.
73      */
74     public BulkApi(SearchServiceApi searchService) {
75         this.searchService = searchService;
76     }
77
78
79     /**
80      * Processes client requests containing a set of operations to be performed in bulk.
81      *
82      * <p>
83      * Method: POST
84      *
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.
89      */
90     public ResponseEntity<String> processPost(String operations, HttpServletRequest request, HttpHeaders headers,
91             DocumentStoreInterface documentStore) {
92         ApiUtils.initMdcContext(request, headers);
93
94         if (logger.isDebugEnabled()) {
95             logger.debug("SEARCH: Process Bulk Request - operations = [" + operations.replaceAll("\n", "") + " ]");
96         }
97
98         // We expect a payload containing a JSON structure enumerating the operations to be performed.
99         if (operations == null) {
100             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
101             return buildResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Missing payload", request);
102         }
103
104         try {
105             // Validate that the request is correctly authenticated before going any further.
106             if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
107                     ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
108                 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
109
110                 return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure.", request);
111             }
112         } catch (Exception e) {
113             // This is a catch all for any unexpected failure trying to perform the authentication.
114             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
115                     "Unexpected authentication failure - cause: " + e.getMessage());
116             if (logger.isDebugEnabled()) {
117                 logger.debug(MSG_STACK_TRACE + e.getStackTrace());
118             }
119
120             return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure - cause " + e.getMessage(),
121                     request);
122         }
123
124         // Marshal the supplied json string into a Java object.
125         ObjectMapper mapper = new ObjectMapper();
126         BulkRequest[] requests = null;
127         try {
128             requests = mapper.readValue(operations, BulkRequest[].class);
129         } catch (IOException e) {
130             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Failed to marshal operations list: " + e.getMessage());
131             if (logger.isDebugEnabled()) {
132                 logger.debug(MSG_STACK_TRACE + e.getStackTrace());
133             }
134             // Populate the result code and entity string for our HTTP response
135             // and return the response to the client..
136             return buildResponse(HttpStatus.BAD_REQUEST.value(), "Unable to marshal operations: " + e.getMessage(),
137                     request);
138         }
139
140         // Verify that our parsed operations list actually contains some valid operations.
141         if (requests.length == 0) {
142             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
143
144             // Populate the result code and entity string for our HTTP response
145             // and return the response to the client..
146             return buildResponse(HttpStatus.BAD_REQUEST.value(), "Empty operations list in bulk request", request);
147         }
148
149         int resultCode;
150         String resultString;
151
152         try {
153             // Now, forward the set of bulk operations to the DAO for processing.
154             OperationResult result = documentStore.performBulkOperations(requests);
155
156             resultCode = result.getResultCode();
157             resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
158         } catch (DocumentStoreOperationException e) {
159             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
160                     "Unexpected failure communicating with document store: " + e.getMessage());
161             if (logger.isDebugEnabled()) {
162                 logger.debug(MSG_STACK_TRACE + e.getStackTrace());
163             }
164
165             resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
166             resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
167         }
168
169         ResponseEntity<String> response =
170                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
171
172         if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
173             logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
174         } else {
175             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, response.getBody());
176         }
177
178         return buildResponse(resultCode, resultString, request);
179     }
180
181     /**
182      * This method generates an audit log and returns an HTTP response object.
183      *
184      * @param resultCode - The result code to report.
185      * @param resultString - The result string to report.
186      * @param request - The HTTP request to extract data from for the audit log.
187      * @return - An HTTP response object.
188      */
189     private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request) {
190         ResponseEntity<String> response =
191                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
192
193         // Generate our audit log.
194         String unknownLogField = "Unknown";
195         auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
196                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
197                         .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, ApiUtils.getHttpStatusString(resultCode)),
198                 (request != null) ? request.getMethod() : unknownLogField,
199                 (request != null) ? request.getRequestURL().toString() : unknownLogField,
200                 (request != null) ? request.getRemoteHost() : unknownLogField,
201                 Integer.toString(response.getStatusCodeValue()));
202
203         // Clear the MDC context so that no other transaction inadvertently
204         // uses our transaction id.
205         ApiUtils.clearMdcContext();
206
207         return response;
208     }
209 }