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