3a7b797f84e6f0e9ba2289e32d525cd4b17e939f
[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     private static final String MSG_STACK_TRACE = "Stack Trace:\n";
71
72     /**
73      * Create a new instance of the BulkApi end point.
74      */
75     public BulkApi(SearchServiceApi searchService) {
76         this.searchService = searchService;
77     }
78
79
80     /**
81      * Processes client requests containing a set of operations to be performed in bulk.
82      *
83      * <p>
84      * Method: POST
85      *
86      * @param operations - JSON structure enumerating the operations to be performed.
87      * @param request - Raw HTTP request.
88      * @param headers - HTTP headers.
89      * @return - A standard REST response structure.
90      */
91     public ResponseEntity<String> processPost(String operations, HttpServletRequest request, HttpHeaders headers,
92             DocumentStoreInterface documentStore) {
93         ApiUtils.initMdcContext(request, headers);
94
95         if (logger.isDebugEnabled()) {
96             logger.debug("SEARCH: Process Bulk Request - operations = [" + operations.replaceAll("\n", "") + " ]");
97         }
98
99         // We expect a payload containing a JSON structure enumerating the operations to be performed.
100         if (operations == null) {
101             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Missing operations list payload");
102             return buildResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Missing payload", request);
103         }
104
105         try {
106             // Validate that the request is correctly authenticated before going any further.
107             if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
108                     ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
109                 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Authentication failure.");
110
111                 return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure.", request);
112             }
113         } catch (Exception e) {
114             // This is a catch all for any unexpected failure trying to perform the authentication.
115             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
116                     "Unexpected authentication failure - cause: " + e.getMessage());
117             if (logger.isDebugEnabled()) {
118                 logger.debug(MSG_STACK_TRACE + e.getStackTrace());
119             }
120
121             return buildResponse(HttpStatus.FORBIDDEN.value(), "Authentication failure - cause " + e.getMessage(),
122                     request);
123         }
124
125         // Marshal the supplied json string into a Java object.
126         ObjectMapper mapper = new ObjectMapper();
127         BulkRequest[] requests = null;
128         try {
129             requests = mapper.readValue(operations, BulkRequest[].class);
130         } catch (IOException e) {
131             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Failed to marshal operations list: " + e.getMessage());
132             if (logger.isDebugEnabled()) {
133                 logger.debug(MSG_STACK_TRACE + e.getStackTrace());
134             }
135             // Populate the result code and entity string for our HTTP response
136             // and return the response to the client..
137             return buildResponse(HttpStatus.BAD_REQUEST.value(), "Unable to marshal operations: " + e.getMessage(),
138                     request);
139         }
140
141         // Verify that our parsed operations list actually contains some valid operations.
142         if (requests.length == 0) {
143             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, "Empty operations list in bulk request");
144
145             // Populate the result code and entity string for our HTTP response
146             // and return the response to the client..
147             return buildResponse(HttpStatus.BAD_REQUEST.value(), "Empty operations list in bulk request", request);
148         }
149
150         int resultCode;
151         String resultString;
152
153         try {
154             // Now, forward the set of bulk operations to the DAO for processing.
155             OperationResult result = documentStore.performBulkOperations(requests);
156
157             resultCode = result.getResultCode();
158             resultString = (result.getFailureCause() == null) ? result.getResult() : result.getFailureCause();
159         } catch (DocumentStoreOperationException e) {
160             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE,
161                     "Unexpected failure communicating with document store: " + e.getMessage());
162             if (logger.isDebugEnabled()) {
163                 logger.debug(MSG_STACK_TRACE + e.getStackTrace());
164             }
165
166             resultCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
167             resultString = "Unexpected failure processing bulk operations: " + e.getMessage();
168         }
169
170         ResponseEntity<String> response =
171                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
172
173         if ((response.getStatusCodeValue() >= 200) && (response.getStatusCodeValue() < 300)) {
174             logger.info(SearchDbMsgs.PROCESSED_BULK_OPERATIONS);
175         } else {
176             logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, response.getBody());
177         }
178
179         return buildResponse(resultCode, resultString, request);
180     }
181
182     /**
183      * This method generates an audit log and returns an HTTP response object.
184      *
185      * @param resultCode - The result code to report.
186      * @param resultString - The result string to report.
187      * @param request - The HTTP request to extract data from for the audit log.
188      * @return - An HTTP response object.
189      */
190     private ResponseEntity<String> buildResponse(int resultCode, String resultString, HttpServletRequest request) {
191         ResponseEntity<String> response =
192                 ResponseEntity.status(resultCode).contentType(MediaType.APPLICATION_JSON).body(resultString);
193
194         // Generate our audit log.
195         String unknownLogField = "Unknown";
196         auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
197                 new LogFields().setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
198                         .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, ApiUtils.getHttpStatusString(resultCode)),
199                 (request != null) ? request.getMethod() : unknownLogField,
200                 (request != null) ? request.getRequestURL().toString() : unknownLogField,
201                 (request != null) ? request.getRemoteHost() : unknownLogField,
202                 Integer.toString(response.getStatusCodeValue()));
203
204         // Clear the MDC context so that no other transaction inadvertently
205         // uses our transaction id.
206         ApiUtils.clearMdcContext();
207
208         return response;
209     }
210 }