Format Java code to ONAP standard
[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, ApiUtils apiUtils) {
92
93
94         // Initialize the MDC Context for logging purposes.
95         ApiUtils.initMdcContext(request, headers);
96
97         // Set a default result code and entity string for the request.
98         int resultCode = 500;
99         String resultString = "Unexpected error";
100
101         if (logger.isDebugEnabled()) {
102             logger.debug("SEARCH: Process Bulk Request - operations = [" + operations.replaceAll("\n", "") + " ]");
103         }
104
105         try {
106
107             // Validate that the request is correctly authenticated before going
108             // any further.
109             if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
110                     ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
111                 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
112
113                 return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure.", request, apiUtils);
114             }
115
116         } catch (Exception e) {
117
118             // This is a catch all for any unexpected failure trying to perform
119             // the authentication.
120             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
121                     "Unexpected authentication failure - cause: " + e.getMessage());
122             if (logger.isDebugEnabled()) {
123                 logger.debug("Stack Trace:\n" + e.getStackTrace());
124             }
125
126             return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure - cause " + e.getMessage(),
127                     request, apiUtils);
128         }
129
130         // We expect a payload containing a JSON structure enumerating the
131         // operations to be performed.
132         if (operations == null) {
133             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
134
135             return buildResponse(resultCode, "Missing payload", request, apiUtils);
136         }
137
138
139         // Marshal the supplied json string into a Java object.
140         ObjectMapper mapper = new ObjectMapper();
141         BulkRequest[] requests = null;
142         try {
143             requests = mapper.readValue(operations, BulkRequest[].class);
144
145         } catch (IOException e) {
146
147             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Failed to marshal operations list: " + e.getMessage());
148             if (logger.isDebugEnabled()) {
149                 logger.debug("Stack Trace:\n" + e.getStackTrace());
150             }
151
152             // Populate the result code and entity string for our HTTP response
153             // and return the response to the client..
154             return buildResponse(HttpStatus.BAD_REQUEST.value(), "Unable to marshal operations: " + e.getMessage(),
155                     request, apiUtils);
156         }
157
158         // Verify that our parsed operations list actually contains some valid
159         // operations.
160         if (requests.length == 0) {
161             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
162
163
164             // Populate the result code and entity string for our HTTP response
165             // and return the response to the client..
166             return buildResponse(HttpStatus.BAD_REQUEST.value(), "Empty operations list in bulk request", request,
167                     apiUtils);
168         }
169         try {
170
171             // Now, forward the set of bulk operations to the DAO for processing.
172             OperationResult result = documentStore.performBulkOperations(requests);
173
174             // Populate the result code and entity string for our HTTP response.
175             resultCode = result.getResultCode();
176             resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
177
178         } catch (DocumentStoreOperationException e) {
179
180             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
181                     "Unexpected failure communicating with document store: " + e.getMessage());
182             if (logger.isDebugEnabled()) {
183                 logger.debug("Stack Trace:\n" + e.getStackTrace());
184             }
185
186             // Populate the result code and entity string for our HTTP response.
187             resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
188             resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
189         }
190
191         // Build our HTTP response.
192         ResponseEntity response =
193                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
194
195         // Log the result.
196         if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
197             logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
198         } else {
199             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, (String) response.getBody());
200         }
201
202         // Finally, return the HTTP response to the client.
203         return buildResponse(resultCode, resultString, request, apiUtils);
204     }
205
206
207     /**
208      * This method generates an audit log and returns an HTTP response object.
209      *
210      * @param resultCode - The result code to report.
211      * @param resultString - The result string to report.
212      * @param request - The HTTP request to extract data from for the audit log.
213      * @return - An HTTP response object.
214      */
215     private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request,
216             ApiUtils apiUtils) {
217
218         ResponseEntity<String> response =
219                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
220
221         // Generate our audit log.
222         auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
223                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
224                         .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, ApiUtils.getHttpStatusString(resultCode)),
225                 (request != null) ? request.getMethod().toString() : "Unknown",
226                 (request != null) ? request.getRequestURL().toString() : "Unknown",
227                 (request != null) ? request.getRemoteHost() : "Unknown",
228                 Integer.toString(response.getStatusCodeValue()));
229
230         // Clear the MDC context so that no other transaction inadvertently
231         // uses our transaction id.
232         ApiUtils.clearMdcContext();
233
234         return response;
235     }
236 }