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