2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.onap.aai.sa.rest;
25 import com.fasterxml.jackson.databind.ObjectMapper;
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.openecomp.cl.api.LogFields;
32 import org.openecomp.cl.api.LogLine;
33 import org.openecomp.cl.api.Logger;
34 import org.openecomp.cl.eelf.LoggerFactory;
35 import org.onap.aai.sa.rest.DocumentFieldSchema;
36 import org.onap.aai.sa.rest.DocumentSchema;
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.core.HttpHeaders;
42 import javax.ws.rs.core.Response;
46 * This class encapsulates the REST end points associated with manipulating
47 * indexes in the document store.
49 public class IndexApi {
51 protected SearchServiceApi searchService = null;
54 * Configuration for the custom analyzers that will be used for indexing.
56 protected AnalysisConfiguration analysisConfig;
58 // Set up the loggers.
59 private static Logger logger = LoggerFactory.getInstance()
60 .getLogger(IndexApi.class.getName());
61 private static Logger auditLogger = LoggerFactory.getInstance()
62 .getAuditLogger(IndexApi.class.getName());
65 public IndexApi(SearchServiceApi searchService) {
66 this.searchService = searchService;
72 * Initializes the end point.
74 * @throws FileNotFoundException
76 * @throws DocumentStoreOperationException
80 // Instantiate our analysis configuration object.
81 analysisConfig = new AnalysisConfiguration();
86 * Processes client requests to create a new index and document type in the
89 * @param documentSchema - The contents of the request body which is expected
90 * to be a JSON structure which corresponds to the
91 * schema defined in document.schema.json
92 * @param index - The name of the index to create.
93 * @return - A Standard REST response
95 public Response processCreateIndex(String documentSchema,
96 HttpServletRequest request,
99 DocumentStoreInterface documentStore) {
101 int resultCode = 500;
102 String resultString = "Unexpected error";
104 // Initialize the MDC Context for logging purposes.
105 ApiUtils.initMdcContext(request, headers);
107 // Validate that the request is correctly authenticated before going
111 if (!searchService.validateRequest(headers, request,
112 ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
113 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
114 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
117 } catch (Exception e) {
119 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
120 "Unexpected authentication failure - cause: " + e.getMessage());
121 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
125 // We expect a payload containing the document schema. Make sure
127 if (documentSchema == null) {
128 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload");
129 return errorResponse(Response.Status.fromStatusCode(resultCode), "Missing payload", request);
134 // Marshal the supplied json string into a document schema object.
135 ObjectMapper mapper = new ObjectMapper();
136 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
138 // Now, ask the DAO to create the index.
139 OperationResult result = documentStore.createIndex(index, schema);
141 // Extract the result code and string from the OperationResult
142 // object so that we can use them to generate a standard REST
144 // Note that we want to return a 201 result code on a successful
145 // create, so if we get back a 200 from the document store,
146 // translate that int a 201.
147 resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
148 resultString = (result.getFailureCause() == null)
149 ? result.getResult() : result.getFailureCause();
151 } catch (com.fasterxml.jackson.core.JsonParseException
152 | com.fasterxml.jackson.databind.JsonMappingException e) {
154 // We were unable to marshal the supplied json string into a valid
155 // document schema, so return an appropriate error response.
156 resultCode = javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode();
157 resultString = "Malformed schema: " + e.getMessage();
159 } catch (IOException e) {
161 // We'll treat this is a general internal error.
162 resultCode = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
163 resultString = "IO Failure: " + e.getMessage();
166 Response response = Response.status(resultCode).entity(resultString).build();
169 if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
170 logger.info(SearchDbMsgs.CREATED_INDEX, index);
172 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
175 // Generate our audit log.
176 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
178 .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
179 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
180 Response.Status.fromStatusCode(resultCode).toString()),
181 (request != null) ? request.getMethod() : "Unknown",
182 (request != null) ? request.getRequestURL().toString() : "Unknown",
183 (request != null) ? request.getRemoteHost() : "Unknown",
184 Integer.toString(response.getStatus()));
186 // Clear the MDC context so that no other transaction inadvertently
187 // uses our transaction id.
188 ApiUtils.clearMdcContext();
190 // Finally, return the response.
196 * Processes a client request to remove an index from the document store.
197 * Note that this implicitly deletes all documents contained within that index.
199 * @param index - The index to be deleted.
200 * @return - A standard REST response.
202 public Response processDelete(String index,
203 HttpServletRequest request,
205 DocumentStoreInterface documentStore) {
207 // Initialize the MDC Context for logging purposes.
208 ApiUtils.initMdcContext(request, headers);
210 // Set a default response in case something unexpected goes wrong.
211 Response response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
215 // Validate that the request is correctly authenticated before going
219 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
220 ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
221 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
222 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
225 } catch (Exception e) {
227 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
228 "Unexpected authentication failure - cause: " + e.getMessage());
229 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
234 // Send the request to the document store.
235 response = responseFromOperationResult(documentStore.deleteIndex(index));
237 } catch (DocumentStoreOperationException e) {
238 response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
239 .entity(e.getMessage())
245 if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
246 logger.info(SearchDbMsgs.DELETED_INDEX, index);
248 logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, (String) response.getEntity());
251 // Generate our audit log.
252 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
254 .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
255 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
256 response.getStatusInfo().getReasonPhrase()),
257 (request != null) ? request.getMethod() : "Unknown",
258 (request != null) ? request.getRequestURL().toString() : "Unknown",
259 (request != null) ? request.getRemoteHost() : "Unknown",
260 Integer.toString(response.getStatus()));
262 // Clear the MDC context so that no other transaction inadvertently
263 // uses our transaction id.
264 ApiUtils.clearMdcContext();
271 * This method takes a JSON format document schema and produces a set of
272 * field mappings in the form that Elastic Search expects.
274 * @param documentSchema - A document schema expressed as a JSON string.
275 * @return - A JSON string expressing an Elastic Search mapping configuration.
276 * @throws com.fasterxml.jackson.core.JsonParseException
277 * @throws com.fasterxml.jackson.databind.JsonMappingException
278 * @throws IOException
280 public String generateDocumentMappings(String documentSchema)
281 throws com.fasterxml.jackson.core.JsonParseException,
282 com.fasterxml.jackson.databind.JsonMappingException, IOException {
284 // Unmarshal the json content into a document schema object.
285 ObjectMapper mapper = new ObjectMapper();
286 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
288 // Now, generate the Elastic Search mapping json and return it.
289 StringBuilder sb = new StringBuilder();
291 sb.append("\"properties\": {");
293 boolean first = true;
294 for (DocumentFieldSchema field : schema.getFields()) {
302 sb.append("\"").append(field.getName()).append("\": {");
304 // The field type is mandatory.
305 sb.append("\"type\": \"").append(field.getDataType()).append("\"");
307 // If the index field was specified, then append it.
308 if (field.getSearchable() != null) {
309 sb.append(", \"index\": \"").append(field.getSearchable()
310 ? "analyzed" : "not_analyzed").append("\"");
313 // If a search analyzer was specified, then append it.
314 if (field.getSearchAnalyzer() != null) {
315 sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\"");
318 // If an indexing analyzer was specified, then append it.
319 if (field.getIndexAnalyzer() != null) {
320 sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\"");
322 sb.append(", \"analyzer\": \"").append("whitespace").append("\"");
331 logger.debug("Generated document mappings: " + sb.toString());
333 return sb.toString();
338 * Converts an {@link OperationResult} to a standard REST {@link Response}
341 * @param result - The {@link OperationResult} to be converted.
342 * @return - The equivalent {@link Response} object.
344 public Response responseFromOperationResult(OperationResult result) {
346 if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
347 return Response.status(result.getResultCode()).entity(result.getResult()).build();
349 if (result.getFailureCause() != null) {
350 return Response.status(result.getResultCode()).entity(result.getFailureCause()).build();
352 return Response.status(result.getResultCode()).entity(result.getResult()).build();
357 public Response errorResponse(Response.Status status, String msg, HttpServletRequest request) {
359 // Generate our audit log.
360 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
362 .setField(LogLine.DefinedFields.RESPONSE_CODE, status.getStatusCode())
363 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
364 (request != null) ? request.getMethod() : "Unknown",
365 (request != null) ? request.getRequestURL().toString() : "Unknown",
366 (request != null) ? request.getRemoteHost() : "Unknown",
367 Integer.toString(status.getStatusCode()));
369 // Clear the MDC context so that no other transaction inadvertently
370 // uses our transaction id.
371 ApiUtils.clearMdcContext();
373 return Response.status(status)