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