Fix simple Sonar Lint 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 /**
44  * This class encapsulates the REST end points associated with performing bulk operations against the document store.
45  */
46 public class BulkApi {
47
48     /**
49      * Indicates whether or not we have performed the one-time static initialization required for performing schema
50      * validation.
51      */
52     protected static AtomicBoolean validationInitialized = new AtomicBoolean(false);
53
54     /**
55      * Factory used for importing our payload schema for validation purposes.
56      */
57     protected static JsonSchemaFactory schemaFactory = null;
58
59     /**
60      * Imported payload schema that will be used by our validation methods.
61      */
62     protected static JsonSchema schema = null;
63
64     protected SearchServiceApi searchService = null;
65
66     // Instantiate the loggers.
67     private static Logger logger = LoggerFactory.getInstance().getLogger(BulkApi.class.getName());
68     private static Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(BulkApi.class.getName());
69
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         // Initialize the MDC Context for logging purposes.
93         ApiUtils.initMdcContext(request, headers);
94
95         // Set a default result code and entity string for the request.
96         int resultCode = 500;
97         String resultString;
98
99         if (logger.isDebugEnabled()) {
100             logger.debug("SEARCH: Process Bulk Request - operations = [" + operations.replaceAll("\n", "") + " ]");
101         }
102
103         try {
104             // Validate that the request is correctly authenticated before going
105             // 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
114             // the authentication.
115             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
116                     "Unexpected authentication failure - cause: " + e.getMessage());
117             if (logger.isDebugEnabled()) {
118                 logger.debug("Stack Trace:\n" + e.getStackTrace());
119             }
120
121             return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure - cause " + e.getMessage(),
122                     request);
123         }
124
125         // We expect a payload containing a JSON structure enumerating the
126         // operations to be performed.
127         if (operations == null) {
128             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
129             return buildResponse(resultCode, "Missing payload", request);
130         }
131
132         // Marshal the supplied json string into a Java object.
133         ObjectMapper mapper = new ObjectMapper();
134         BulkRequest[] requests = null;
135         try {
136             requests = mapper.readValue(operations, BulkRequest[].class);
137         } catch (IOException e) {
138             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Failed to marshal operations list: " + e.getMessage());
139             if (logger.isDebugEnabled()) {
140                 logger.debug("Stack Trace:\n" + e.getStackTrace());
141             }
142             // Populate the result code and entity string for our HTTP response
143             // and return the response to the client..
144             return buildResponse(HttpStatus.BAD_REQUEST.value(), "Unable to marshal operations: " + e.getMessage(),
145                     request);
146         }
147
148         // Verify that our parsed operations list actually contains some valid
149         // operations.
150         if (requests.length == 0) {
151             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
152
153
154             // Populate the result code and entity string for our HTTP response
155             // and return the response to the client..
156             return buildResponse(HttpStatus.BAD_REQUEST.value(), "Empty operations list in bulk request", request);
157         }
158         try {
159
160             // Now, forward the set of bulk operations to the DAO for processing.
161             OperationResult result = documentStore.performBulkOperations(requests);
162
163             // Populate the result code and entity string for our HTTP response.
164             resultCode = result.getResultCode();
165             resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
166
167         } catch (DocumentStoreOperationException e) {
168
169             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
170                     "Unexpected failure communicating with document store: " + e.getMessage());
171             if (logger.isDebugEnabled()) {
172                 logger.debug("Stack Trace:\n" + e.getStackTrace());
173             }
174
175             // Populate the result code and entity string for our HTTP response.
176             resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
177             resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
178         }
179
180         // Build our HTTP response.
181         ResponseEntity<String> response =
182                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
183
184         // Log the result.
185         if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
186             logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
187         } else {
188             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, response.getBody());
189         }
190
191         // Finally, return the HTTP response to the client.
192         return buildResponse(resultCode, resultString, request);
193     }
194
195
196     /**
197      * This method generates an audit log and returns an HTTP response object.
198      *
199      * @param resultCode - The result code to report.
200      * @param resultString - The result string to report.
201      * @param request - The HTTP request to extract data from for the audit log.
202      * @return - An HTTP response object.
203      */
204     private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request) {
205         ResponseEntity<String> response =
206                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
207
208         // Generate our audit log.
209         auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
210                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
211                         .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, ApiUtils.getHttpStatusString(resultCode)),
212                 (request != null) ? request.getMethod() : "Unknown",
213                 (request != null) ? request.getRequestURL().toString() : "Unknown",
214                 (request != null) ? request.getRemoteHost() : "Unknown",
215                 Integer.toString(response.getStatusCodeValue()));
216
217         // Clear the MDC context so that no other transaction inadvertently
218         // uses our transaction id.
219         ApiUtils.clearMdcContext();
220
221         return response;
222     }
223 }