2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 * ECOMP and OpenECOMP are trademarks
23 * and service marks of AT&T Intellectual Property.
25 package org.openecomp.sa.rest;
27 import com.fasterxml.jackson.databind.ObjectMapper;
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;
37 import java.io.FileNotFoundException;
38 import java.io.IOException;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.ws.rs.core.HttpHeaders;
41 import javax.ws.rs.core.Response;
45 * This class encapsulates the REST end points associated with manipulating
46 * indexes in the document store.
48 public class IndexApi {
50 protected SearchServiceApi searchService = null;
53 * Configuration for the custom analyzers that will be used for indexing.
55 protected AnalysisConfiguration analysisConfig;
57 // Set up the loggers.
58 private static Logger logger = LoggerFactory.getInstance()
59 .getLogger(IndexApi.class.getName());
60 private static Logger auditLogger = LoggerFactory.getInstance()
61 .getAuditLogger(IndexApi.class.getName());
64 public IndexApi(SearchServiceApi searchService) {
65 this.searchService = searchService;
71 * Initializes the end point.
73 * @throws FileNotFoundException
75 * @throws DocumentStoreOperationException
79 // Instantiate our analysis configuration object.
80 analysisConfig = new AnalysisConfiguration();
85 * Processes client requests to create a new index and document type in the
88 * @param documentSchema - The contents of the request body which is expected
89 * to be a JSON structure which corresponds to the
90 * schema defined in document.schema.json
91 * @param index - The name of the index to create.
92 * @return - A Standard REST response
94 public Response processCreateIndex(String documentSchema,
95 HttpServletRequest request,
98 DocumentStoreInterface documentStore) {
100 int resultCode = 500;
101 String resultString = "Unexpected error";
103 // Initialize the MDC Context for logging purposes.
104 ApiUtils.initMdcContext(request, headers);
106 // Validate that the request is correctly authenticated before going
110 if (!searchService.validateRequest(headers, request,
111 ApiUtils.Action.POST, ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
112 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
113 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
116 } catch (Exception e) {
118 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
119 "Unexpected authentication failure - cause: " + e.getMessage());
120 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
124 // We expect a payload containing the document schema. Make sure
126 if (documentSchema == null) {
127 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Missing document schema payload");
128 return errorResponse(Response.Status.fromStatusCode(resultCode), "Missing payload", request);
133 // Marshal the supplied json string into a document schema object.
134 ObjectMapper mapper = new ObjectMapper();
135 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
137 // Now, ask the DAO to create the index.
138 OperationResult result = documentStore.createIndex(index, schema);
140 // Extract the result code and string from the OperationResult
141 // object so that we can use them to generate a standard REST
143 // Note that we want to return a 201 result code on a successful
144 // create, so if we get back a 200 from the document store,
145 // translate that int a 201.
146 resultCode = (result.getResultCode() == 200) ? 201 : result.getResultCode();
147 resultString = (result.getFailureCause() == null)
148 ? result.getResult() : result.getFailureCause();
150 } catch (com.fasterxml.jackson.core.JsonParseException
151 | com.fasterxml.jackson.databind.JsonMappingException e) {
153 // We were unable to marshal the supplied json string into a valid
154 // document schema, so return an appropriate error response.
155 resultCode = javax.ws.rs.core.Response.Status.BAD_REQUEST.getStatusCode();
156 resultString = "Malformed schema: " + e.getMessage();
158 } catch (IOException e) {
160 // We'll treat this is a general internal error.
161 resultCode = javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
162 resultString = "IO Failure: " + e.getMessage();
165 Response response = Response.status(resultCode).entity(resultString).build();
168 if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
169 logger.info(SearchDbMsgs.CREATED_INDEX, index);
171 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, resultString);
174 // Generate our audit log.
175 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
177 .setField(LogLine.DefinedFields.RESPONSE_CODE, resultCode)
178 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
179 Response.Status.fromStatusCode(resultCode).toString()),
180 (request != null) ? request.getMethod() : "Unknown",
181 (request != null) ? request.getRequestURL().toString() : "Unknown",
182 (request != null) ? request.getRemoteHost() : "Unknown",
183 Integer.toString(response.getStatus()));
185 // Clear the MDC context so that no other transaction inadvertently
186 // uses our transaction id.
187 ApiUtils.clearMdcContext();
189 // Finally, return the response.
195 * Processes a client request to remove an index from the document store.
196 * Note that this implicitly deletes all documents contained within that index.
198 * @param index - The index to be deleted.
199 * @return - A standard REST response.
201 public Response processDelete(String index,
202 HttpServletRequest request,
204 DocumentStoreInterface documentStore) {
206 // Initialize the MDC Context for logging purposes.
207 ApiUtils.initMdcContext(request, headers);
209 // Set a default response in case something unexpected goes wrong.
210 Response response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
214 // Validate that the request is correctly authenticated before going
218 if (!searchService.validateRequest(headers, request, ApiUtils.Action.POST,
219 ApiUtils.SEARCH_AUTH_POLICY_NAME)) {
220 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index, "Authentication failure.");
221 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
224 } catch (Exception e) {
226 logger.warn(SearchDbMsgs.INDEX_CREATE_FAILURE, index,
227 "Unexpected authentication failure - cause: " + e.getMessage());
228 return errorResponse(Response.Status.FORBIDDEN, "Authentication failure.", request);
233 // Send the request to the document store.
234 response = responseFromOperationResult(documentStore.deleteIndex(index));
236 } catch (DocumentStoreOperationException e) {
237 response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR)
238 .entity(e.getMessage())
244 if ((response.getStatus() >= 200) && (response.getStatus() < 300)) {
245 logger.info(SearchDbMsgs.DELETED_INDEX, index);
247 logger.warn(SearchDbMsgs.INDEX_DELETE_FAILURE, index, (String) response.getEntity());
250 // Generate our audit log.
251 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
253 .setField(LogLine.DefinedFields.RESPONSE_CODE, response.getStatus())
254 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION,
255 response.getStatusInfo().getReasonPhrase()),
256 (request != null) ? request.getMethod() : "Unknown",
257 (request != null) ? request.getRequestURL().toString() : "Unknown",
258 (request != null) ? request.getRemoteHost() : "Unknown",
259 Integer.toString(response.getStatus()));
261 // Clear the MDC context so that no other transaction inadvertently
262 // uses our transaction id.
263 ApiUtils.clearMdcContext();
270 * This method takes a JSON format document schema and produces a set of
271 * field mappings in the form that Elastic Search expects.
273 * @param documentSchema - A document schema expressed as a JSON string.
274 * @return - A JSON string expressing an Elastic Search mapping configuration.
275 * @throws com.fasterxml.jackson.core.JsonParseException
276 * @throws com.fasterxml.jackson.databind.JsonMappingException
277 * @throws IOException
279 public String generateDocumentMappings(String documentSchema)
280 throws com.fasterxml.jackson.core.JsonParseException,
281 com.fasterxml.jackson.databind.JsonMappingException, IOException {
283 // Unmarshal the json content into a document schema object.
284 ObjectMapper mapper = new ObjectMapper();
285 DocumentSchema schema = mapper.readValue(documentSchema, DocumentSchema.class);
287 // Now, generate the Elastic Search mapping json and return it.
288 StringBuilder sb = new StringBuilder();
290 sb.append("\"properties\": {");
292 boolean first = true;
293 for (DocumentFieldSchema field : schema.getFields()) {
301 sb.append("\"").append(field.getName()).append("\": {");
303 // The field type is mandatory.
304 sb.append("\"type\": \"").append(field.getDataType()).append("\"");
306 // If the index field was specified, then append it.
307 if (field.getSearchable() != null) {
308 sb.append(", \"index\": \"").append(field.getSearchable()
309 ? "analyzed" : "not_analyzed").append("\"");
312 // If a search analyzer was specified, then append it.
313 if (field.getSearchAnalyzer() != null) {
314 sb.append(", \"search_analyzer\": \"").append(field.getSearchAnalyzer()).append("\"");
317 // If an indexing analyzer was specified, then append it.
318 if (field.getIndexAnalyzer() != null) {
319 sb.append(", \"analyzer\": \"").append(field.getIndexAnalyzer()).append("\"");
321 sb.append(", \"analyzer\": \"").append("whitespace").append("\"");
330 logger.debug("Generated document mappings: " + sb.toString());
332 return sb.toString();
337 * Converts an {@link OperationResult} to a standard REST {@link Response}
340 * @param result - The {@link OperationResult} to be converted.
341 * @return - The equivalent {@link Response} object.
343 public Response responseFromOperationResult(OperationResult result) {
345 if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
346 return Response.status(result.getResultCode()).entity(result.getResult()).build();
348 if (result.getFailureCause() != null) {
349 return Response.status(result.getResultCode()).entity(result.getFailureCause()).build();
351 return Response.status(result.getResultCode()).entity(result.getResult()).build();
356 public Response errorResponse(Response.Status status, String msg, HttpServletRequest request) {
358 // Generate our audit log.
359 auditLogger.info(SearchDbMsgs.PROCESS_REST_REQUEST,
361 .setField(LogLine.DefinedFields.RESPONSE_CODE, status.getStatusCode())
362 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, status.getReasonPhrase()),
363 (request != null) ? request.getMethod() : "Unknown",
364 (request != null) ? request.getRequestURL().toString() : "Unknown",
365 (request != null) ? request.getRemoteHost() : "Unknown",
366 Integer.toString(status.getStatusCode()));
368 // Clear the MDC context so that no other transaction inadvertently
369 // uses our transaction id.
370 ApiUtils.clearMdcContext();
372 return Response.status(status)