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