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