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.openecomp.sa.rest;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import org.openecomp.cl.api.LogFields;
27 import org.openecomp.cl.api.LogLine;
28 import org.openecomp.cl.api.Logger;
29 import org.openecomp.cl.eelf.LoggerFactory;
30 import org.openecomp.sa.searchdbabstraction.elasticsearch.dao.DocumentStoreInterface;
31 import org.openecomp.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
32 import org.openecomp.sa.searchdbabstraction.entity.OperationResult;
33 import org.openecomp.sa.searchdbabstraction.logging.SearchDbMsgs;
35 import java.io.FileNotFoundException;
36 import java.io.IOException;
37 import javax.servlet.http.HttpServletRequest;
38 import javax.ws.rs.core.HttpHeaders;
39 import javax.ws.rs.core.Response;
43 * This class encapsulates the REST end points associated with manipulating
44 * indexes in the document store.
46 public class IndexApi {
48 protected SearchServiceApi searchService = null;
51 * Configuration for the custom analyzers that will be used for indexing.
53 protected AnalysisConfiguration analysisConfig;
55 // Set up the loggers.
56 private static Logger logger = LoggerFactory.getInstance()
57 .getLogger(IndexApi.class.getName());
58 private static Logger auditLogger = LoggerFactory.getInstance()
59 .getAuditLogger(IndexApi.class.getName());
62 public IndexApi(SearchServiceApi searchService) {
63 this.searchService = searchService;
69 * Initializes the end point.
71 * @throws FileNotFoundException
73 * @throws DocumentStoreOperationException
77 // Instantiate our analysis configuration object.
78 analysisConfig = new AnalysisConfiguration();
83 * Processes client requests to create a new index and document type in the
86 * @param documentSchema - The contents of the request body which is expected
87 * to be a JSON structure which corresponds to the
88 * schema defined in document.schema.json
89 * @param index - The name of the index to create.
90 * @return - A Standard REST response
92 public Response processCreateIndex(String documentSchema,
93 HttpServletRequest request,
96 DocumentStoreInterface documentStore) {
99 String resultString = "Unexpected error";
101 // Initialize the MDC Context for logging purposes.
102 ApiUtils.initMdcContext(request, headers);
104 // Validate that the request is correctly authenticated before going
108 if (!searchService.validateRequest(headers, request,
109 ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
110 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
111 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
114 } catch (Exception e) {
116 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
117 "Unexpected authentication failure - cause: " + e.getMessage());
118 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
122 // We expect a payload containing the document schema. Make sure
124 if (documentSchema == null) {
125 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload");
126 return errorResponse(Response.Status.fromStatusCode(resultCode), "Missing payload", request);
131 // Marshal the supplied json string into a document schema object.
132 ObjectMapper mapper = new ObjectMapper();
133 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
135 // Now, ask the DAO to create the index.
136 OperationResult result = documentStore.createIndex(index, schema);
138 // Extract the result code and string from the OperationResult
139 // object so that we can use them to generate a standard REST
141 // Note that we want to return a 201 result code on a successful
142 // create, so if we get back a 200 from the document store,
143 // translate that int a 201.
144 resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
145 resultString = (result.getFailureCause() == null)
146 ? result.getResult() : result.getFailureCause();
148 } catch (com.fasterxml.jackson.core.JsonParseException
149 | com.fasterxml.jackson.databind.JsonMappingException e) {
151 // We were unable to marshal the supplied json string into a valid
152 // document schema, so return an appropriate error response.
153 resultCode = javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode();
154 resultString = "Malformed schema: " + e.getMessage();
156 } catch (IOException e) {
158 // We'll treat this is a general internal error.
159 resultCode = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
160 resultString = "IO Failure: " + e.getMessage();
163 Response response = Response.status(resultCode).entity(resultString).build();
166 if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
167 logger.info(SearchDbMsgs.CREATED_INDEX, index);
169 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
172 // Generate our audit log.
173 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
175 .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
176 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
177 Response.Status.fromStatusCode(resultCode).toString()),
178 (request != null) ? request.getMethod() : "Unknown",
179 (request != null) ? request.getRequestURL().toString() : "Unknown",
180 (request != null) ? request.getRemoteHost() : "Unknown",
181 Integer.toString(response.getStatus()));
183 // Clear the MDC context so that no other transaction inadvertently
184 // uses our transaction id.
185 ApiUtils.clearMdcContext();
187 // Finally, return the response.
193 * Processes a client request to remove an index from the document store.
194 * Note that this implicitly deletes all documents contained within that index.
196 * @param index - The index to be deleted.
197 * @return - A standard REST response.
199 public Response processDelete(String index,
200 HttpServletRequest request,
202 DocumentStoreInterface documentStore) {
204 // Initialize the MDC Context for logging purposes.
205 ApiUtils.initMdcContext(request, headers);
207 // Set a default response in case something unexpected goes wrong.
208 Response response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
212 // Validate that the request is correctly authenticated before going
216 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
217 ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
218 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
219 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
222 } catch (Exception e) {
224 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
225 "Unexpected authentication failure - cause: " + e.getMessage());
226 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
231 // Send the request to the document store.
232 response = responseFromOperationResult(documentStore.deleteIndex(index));
234 } catch (DocumentStoreOperationException e) {
235 response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
236 .entity(e.getMessage())
242 if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
243 logger.info(SearchDbMsgs.DELETED_INDEX, index);
245 logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, (String) response.getEntity());
248 // Generate our audit log.
249 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
251 .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
252 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
253 response.getStatusInfo().getReasonPhrase()),
254 (request != null) ? request.getMethod() : "Unknown",
255 (request != null) ? request.getRequestURL().toString() : "Unknown",
256 (request != null) ? request.getRemoteHost() : "Unknown",
257 Integer.toString(response.getStatus()));
259 // Clear the MDC context so that no other transaction inadvertently
260 // uses our transaction id.
261 ApiUtils.clearMdcContext();
268 * This method takes a JSON format document schema and produces a set of
269 * field mappings in the form that Elastic Search expects.
271 * @param documentSchema - A document schema expressed as a JSON string.
272 * @return - A JSON string expressing an Elastic Search mapping configuration.
273 * @throws com.fasterxml.jackson.core.JsonParseException
274 * @throws com.fasterxml.jackson.databind.JsonMappingException
275 * @throws IOException
277 public String generateDocumentMappings(String documentSchema)
278 throws com.fasterxml.jackson.core.JsonParseException,
279 com.fasterxml.jackson.databind.JsonMappingException, IOException {
281 // Unmarshal the json content into a document schema object.
282 ObjectMapper mapper = new ObjectMapper();
283 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
285 // Now, generate the Elastic Search mapping json and return it.
286 StringBuilder sb = new StringBuilder();
288 sb.append("\"properties\": {");
290 boolean first = true;
291 for (DocumentFieldSchema field : schema.getFields()) {
299 sb.append("\"").append(field.getName()).append("\": {");
301 // The field type is mandatory.
302 sb.append("\"type\": \"").append(field.getDataType()).append("\"");
304 // If the index field was specified, then append it.
305 if (field.getSearchable() != null) {
306 sb.append(", \"index\": \"").append(field.getSearchable()
307 ? "analyzed" : "not_analyzed").append("\"");
310 // If a search analyzer was specified, then append it.
311 if (field.getSearchAnalyzer() != null) {
312 sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\"");
315 // If an indexing analyzer was specified, then append it.
316 if (field.getIndexAnalyzer() != null) {
317 sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\"");
319 sb.append(", \"analyzer\": \"").append("whitespace").append("\"");
328 logger.debug("Generated document mappings: " + sb.toString());
330 return sb.toString();
335 * Converts an {@link OperationResult} to a standard REST {@link Response}
338 * @param result - The {@link OperationResult} to be converted.
339 * @return - The equivalent {@link Response} object.
341 public Response responseFromOperationResult(OperationResult result) {
343 if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
344 return Response.status(result.getResultCode()).entity(result.getResult()).build();
346 if (result.getFailureCause() != null) {
347 return Response.status(result.getResultCode()).entity(result.getFailureCause()).build();
349 return Response.status(result.getResultCode()).entity(result.getResult()).build();
354 public Response errorResponse(Response.Status status, String msg, HttpServletRequest request) {
356 // Generate our audit log.
357 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
359 .setField(LogLine.DefinedFields.RESPONSE_CODE, status.getStatusCode())
360 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
361 (request != null) ? request.getMethod() : "Unknown",
362 (request != null) ? request.getRequestURL().toString() : "Unknown",
363 (request != null) ? request.getRemoteHost() : "Unknown",
364 Integer.toString(status.getStatusCode()));
366 // Clear the MDC context so that no other transaction inadvertently
367 // uses our transaction id.
368 ApiUtils.clearMdcContext();
370 return Response.status(status)