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