2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2018 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=========================================================
22 package org.onap.aai.sa.searchdbabstraction.elasticsearch.dao;
24 import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE;
25 import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
26 import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
28 import com.fasterxml.jackson.annotation.JsonInclude.Include;
29 import com.fasterxml.jackson.core.JsonParseException;
30 import com.fasterxml.jackson.core.JsonProcessingException;
31 import com.fasterxml.jackson.databind.JsonMappingException;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import com.google.common.base.Throwables;
34 import java.io.BufferedReader;
36 import java.io.FileInputStream;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.InputStreamReader;
40 import java.io.OutputStream;
41 import java.io.OutputStreamWriter;
42 import java.io.PrintWriter;
43 import java.io.StringWriter;
44 import java.net.HttpURLConnection;
45 import java.net.MalformedURLException;
46 import java.net.ProtocolException;
48 import java.text.SimpleDateFormat;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.List;
52 import java.util.Optional;
53 import java.util.Properties;
54 import java.util.concurrent.atomic.AtomicBoolean;
55 import javax.ws.rs.HttpMethod;
56 import javax.ws.rs.core.MediaType;
57 import javax.ws.rs.core.Response.Status;
58 import javax.ws.rs.core.UriBuilder;
59 import org.eclipse.jetty.http.HttpStatus;
60 import org.json.simple.JSONArray;
61 import org.json.simple.JSONObject;
62 import org.json.simple.parser.JSONParser;
63 import org.json.simple.parser.ParseException;
64 import org.onap.aai.cl.api.LogFields;
65 import org.onap.aai.cl.api.LogLine;
66 import org.onap.aai.cl.api.Logger;
67 import org.onap.aai.cl.eelf.LoggerFactory;
68 import org.onap.aai.cl.mdc.MdcContext;
69 import org.onap.aai.cl.mdc.MdcOverride;
70 import org.onap.aai.sa.rest.AnalysisConfiguration;
71 import org.onap.aai.sa.rest.ApiUtils;
72 import org.onap.aai.sa.rest.BulkRequest;
73 import org.onap.aai.sa.rest.BulkRequest.OperationType;
74 import org.onap.aai.sa.rest.DocumentSchema;
75 import org.onap.aai.sa.searchdbabstraction.elasticsearch.config.ElasticSearchConfig;
76 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException;
77 import org.onap.aai.sa.searchdbabstraction.elasticsearch.exception.DocumentStoreOperationException.ErrorMessage;
78 import org.onap.aai.sa.searchdbabstraction.entity.AggregationResult;
79 import org.onap.aai.sa.searchdbabstraction.entity.AggregationResults;
80 import org.onap.aai.sa.searchdbabstraction.entity.Document;
81 import org.onap.aai.sa.searchdbabstraction.entity.DocumentOperationResult;
82 import org.onap.aai.sa.searchdbabstraction.entity.ErrorResult;
83 import org.onap.aai.sa.searchdbabstraction.entity.OperationResult;
84 import org.onap.aai.sa.searchdbabstraction.entity.OperationResultBuilder;
85 import org.onap.aai.sa.searchdbabstraction.entity.OperationResultBuilder.Type;
86 import org.onap.aai.sa.searchdbabstraction.entity.SearchHit;
87 import org.onap.aai.sa.searchdbabstraction.entity.SearchHits;
88 import org.onap.aai.sa.searchdbabstraction.entity.SearchOperationResult;
89 import org.onap.aai.sa.searchdbabstraction.entity.SuggestHit;
90 import org.onap.aai.sa.searchdbabstraction.entity.SuggestHits;
91 import org.onap.aai.sa.searchdbabstraction.logging.SearchDbMsgs;
92 import org.onap.aai.sa.searchdbabstraction.util.AggregationParsingUtil;
93 import org.onap.aai.sa.searchdbabstraction.util.DocumentSchemaUtil;
94 import org.onap.aai.sa.searchdbabstraction.util.ElasticSearchPayloadTranslator;
95 import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants;
98 * This class has the Elasticsearch implementation of the DB operations defined in DocumentStoreInterface.
100 public class ElasticSearchHttpController implements DocumentStoreInterface {
102 private static ElasticSearchHttpController instance = null;
104 private static final Logger logger =
105 LoggerFactory.getInstance().getLogger(ElasticSearchHttpController.class.getName());
106 private static final Logger metricsLogger =
107 LoggerFactory.getInstance().getMetricsLogger(ElasticSearchHttpController.class.getName());
109 private static final String URL_QUERY_VERSION = "version=";
111 private static final String JSON_ATTR_VERSION = "_version";
112 private static final String JSON_ATTR_ERROR = "error";
113 private static final String JSON_ATTR_REASON = "reason";
115 private static final String DEFAULT_TYPE = "default";
117 private static final String MSG_RESOURCE_MISSING = "Specified resource does not exist: ";
118 private static final String MSG_RESPONSE_CODE = "Response Code : ";
119 private static final String MSG_INVALID_DOCUMENT_URL = "Invalid document URL: ";
121 private static final String FAILED_TO_PARSE_ELASTIC_SEARCH_RESPONSE = "Failed to parse Elastic Search response.";
123 private static final String BULK_CREATE_WITHOUT_INDEX_TEMPLATE =
124 "{\"create\":{\"_index\" : \"%s\", \"_type\" : \"%s\"} }\n";
125 private static final String BULK_CREATE_WITH_INDEX_TEMPLATE =
126 "{\"create\":{\"_index\" : \"%s\", \"_type\" : \"%s\", \"_id\" : \"%s\" } }\n";
127 private static final String BULK_IMPORT_INDEX_TEMPLATE =
128 "{\"index\":{\"_index\":\"%s\",\"_type\":\"%s\",\"_id\":\"%s\", \"_version\":\"%s\"}}\n";
129 private static final String BULK_DELETE_TEMPLATE =
130 "{ \"delete\": { \"_index\": \"%s\", \"_type\": \"%s\", \"_id\": \"%s\", \"_version\":\"%s\"}}\n";
131 public final static String APPLICATION_XND_JSON_TYPE = new MediaType("application", "x-ndjson").toString();
133 private final ElasticSearchConfig config;
135 protected AnalysisConfiguration analysisConfig;
137 public ElasticSearchHttpController(ElasticSearchConfig config) {
138 this.config = config;
139 analysisConfig = new AnalysisConfiguration();
141 String rootUrl = null;
143 if ("https".equals(config.getUriScheme())) {
144 new ElasticSearchHttpsController(config);
146 rootUrl = buildUrl(createUriBuilder("")).toString();
147 logger.info(SearchDbMsgs.ELASTIC_SEARCH_CONNECTION_ATTEMPT, rootUrl);
149 logger.info(SearchDbMsgs.ELASTIC_SEARCH_CONNECTION_SUCCESS, rootUrl);
150 } catch (Exception e) {
151 logger.error(SearchDbMsgs.ELASTIC_SEARCH_CONNECTION_FAILURE, null, e, rootUrl, e.getMessage());
155 public static ElasticSearchHttpController getInstance() {
156 synchronized (ElasticSearchHttpController.class) {
157 if (instance == null) {
158 Properties properties = new Properties();
159 File file = new File(SearchDbConstants.ES_CONFIG_FILE);
161 properties.load(new FileInputStream(file));
162 } catch (Exception e) {
163 logger.error(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "ElasticSearchHTTPController.getInstance",
164 e.getLocalizedMessage());
167 ElasticSearchConfig config = new ElasticSearchConfig(properties);
168 instance = new ElasticSearchHttpController(config);
175 public AnalysisConfiguration getAnalysisConfig() {
176 return analysisConfig;
179 public ElasticSearchConfig getElasticSearchConfig() {
184 public OperationResult createIndex(String index, DocumentSchema documentSchema) {
186 // Submit the request to ElasticSearch to create the index using a default document type.
187 OperationResult result = createTable(index, DEFAULT_TYPE, analysisConfig.getEsIndexSettings(),
188 DocumentSchemaUtil.generateDocumentMappings(documentSchema));
190 // ElasticSearch will return us a 200 code on success when we
191 // want to report a 201, so translate the result here.
192 if (result.getResultCode() == Status.OK.getStatusCode()) {
193 result.setResultCode(Status.CREATED.getStatusCode());
196 if (isSuccess(result)) {
197 result.setResult("{\"url\": \"" + ApiUtils.buildIndexUri(index) + "\"}");
200 } catch (DocumentStoreOperationException | IOException e) {
201 return new OperationResultBuilder().useDefaults()
202 .failureCause("Document store operation failure. Cause: " + e.getMessage()).build();
207 public OperationResult createDynamicIndex(String index, String dynamicSchema) {
209 OperationResult result = createTable(index, dynamicSchema);
211 // ElasticSearch will return us a 200 code on success when we
212 // want to report a 201, so translate the result here.
213 if (result.getResultCode() == Status.OK.getStatusCode()) {
214 result.setResultCode(Status.CREATED.getStatusCode());
216 if (isSuccess(result)) {
217 result.setResult("{\"url\": \"" + ApiUtils.buildIndexUri(index) + "\"}");
220 } catch (DocumentStoreOperationException e) {
221 return new OperationResultBuilder().useDefaults()
222 .failureCause("Document store operation failure. Cause: " + e.getMessage()).build();
227 public OperationResult deleteIndex(String indexName) throws DocumentStoreOperationException {
228 MdcOverride override = getStartTime(new MdcOverride());
230 HttpURLConnection conn = createConnection(buildUrl(createUriBuilder(indexName)), HttpMethod.DELETE);
231 OperationResult opResult = handleResponse(conn);
232 logMetricsInfo(override, SearchDbMsgs.DELETE_INDEX_TIME, opResult, indexName);
233 shutdownConnection(conn);
239 protected OperationResult createTable(String indexName, String typeName, String indexSettings, String indexMappings)
240 throws DocumentStoreOperationException {
241 if (indexSettings == null) {
242 logger.debug("No settings provided.");
245 if (indexMappings == null) {
246 logger.debug("No mappings provided.");
249 MdcOverride override = getStartTime(new MdcOverride());
251 HttpURLConnection conn = createConnection(buildUrl(createUriBuilder(indexName)), HttpMethod.PUT);
253 StringBuilder sb = new StringBuilder(128);
254 sb.append("{ \"settings\" : ");
255 sb.append(indexSettings);
258 sb.append("\"mappings\" : {");
259 sb.append("\"" + typeName + "\" :");
260 sb.append(indexMappings);
264 attachContent(conn, ElasticSearchPayloadTranslator.translateESPayload(sb.toString()));
265 } catch (IOException e) {
266 logger.error(SearchDbMsgs.INDEX_CREATE_FAILURE, e);
267 throw new DocumentStoreOperationException(e.getMessage(), e);
270 logger.debug("Request content: " + sb);
272 OperationResult opResult = handleResponse(conn);
273 shutdownConnection(conn);
274 logMetricsInfo(override, SearchDbMsgs.CREATE_INDEX_TIME, opResult, indexName);
280 * Will send the passed in JSON payload to Elasticsearch using the provided index name in an attempt to create the
283 * @param indexName - The name of the index to be created
284 * @param settingsAndMappings - The actual JSON object that will define the index
285 * @return - The operation result of writing into Elasticsearch
286 * @throws DocumentStoreOperationException
288 protected OperationResult createTable(String indexName, String settingsAndMappings)
289 throws DocumentStoreOperationException {
290 MdcOverride override = getStartTime(new MdcOverride());
292 HttpURLConnection conn = createConnection(buildUrl(createUriBuilder(indexName)), HttpMethod.PUT);
294 attachContent(conn, ElasticSearchPayloadTranslator.translateESPayload(settingsAndMappings));
295 } catch (IOException e) {
296 logger.error(SearchDbMsgs.INDEX_CREATE_FAILURE, e);
297 throw new DocumentStoreOperationException(e.getMessage());
300 OperationResult result = handleResponse(conn);
301 logMetricsInfo(override, SearchDbMsgs.CREATE_INDEX_TIME, result, indexName);
307 public DocumentOperationResult createDocument(String indexName, DocumentStoreDataEntity document,
308 boolean allowImplicitIndexCreation) throws DocumentStoreOperationException {
310 if (!allowImplicitIndexCreation) {
311 // Before we do anything, make sure that the specified index actually exists in the
312 // document store - we don't want to rely on ElasticSearch to fail the document
313 // create because it could be configured to implicitly create a non-existent index,
314 // which can lead to hard-to-debug behaviour with queries down the road.
315 OperationResult indexExistsResult = checkIndexExistence(indexName);
316 if (!isSuccess(indexExistsResult)) {
317 String resultMsg = "Document Index '" + indexName + "' does not exist.";
318 return (DocumentOperationResult) new OperationResultBuilder(Type.DOCUMENT).status(Status.NOT_FOUND)
319 .result(resultMsg).failureCause(resultMsg).build();
323 if (document.getId() == null || document.getId().isEmpty()) {
324 return createDocumentWithoutId(indexName, document);
326 return createDocumentWithId(indexName, document);
331 public DocumentOperationResult updateDocument(String indexName, DocumentStoreDataEntity document,
332 boolean allowImplicitIndexCreation) throws DocumentStoreOperationException {
333 if (!allowImplicitIndexCreation) {
334 // Before we do anything, make sure that the specified index actually exists in the
335 // document store - we don't want to rely on ElasticSearch to fail the document
336 // create because it could be configured to implicitly create a non-existent index,
337 // which can lead to hard-to-debug behaviour with queries down the road.
338 OperationResult indexExistsResult = checkIndexExistence(indexName);
339 if (!isSuccess(indexExistsResult)) {
340 DocumentOperationResult opResult = new DocumentOperationResult();
341 opResult.setResultCode(Status.NOT_FOUND.getStatusCode());
342 String resultMsg = "Document Index '" + indexName + "' does not exist.";
343 opResult.setResult(resultMsg);
344 opResult.setFailureCause(resultMsg);
349 MdcOverride override = getStartTime(new MdcOverride());
351 final URL url = buildUrl(createUriBuilder(indexName, DEFAULT_TYPE, document.getId())
352 .replaceQuery(URL_QUERY_VERSION + document.getVersion()));
354 HttpURLConnection conn = createConnection(url, HttpMethod.PUT);
355 attachDocument(conn, document);
357 DocumentOperationResult opResult = getOperationResult(conn);
358 buildDocumentResult(opResult, indexName);
360 logMetricsInfo(override, SearchDbMsgs.UPDATE_DOCUMENT_TIME, opResult, indexName, document.getId());
362 shutdownConnection(conn);
368 public DocumentOperationResult deleteDocument(String indexName, DocumentStoreDataEntity document)
369 throws DocumentStoreOperationException {
370 final URL url = buildUrl(createUriBuilder(indexName, DEFAULT_TYPE, document.getId())
371 .replaceQuery(URL_QUERY_VERSION + document.getVersion()));
373 MdcOverride override = getStartTime(new MdcOverride());
375 HttpURLConnection conn = createConnection(url, HttpMethod.DELETE);
377 DocumentOperationResult opResult = getOperationResult(conn);
378 buildDocumentResult(opResult, indexName);
379 // supress the etag and url in response for delete as they are not required
380 if (opResult.getDocument() != null) {
381 opResult.getDocument().setEtag(null);
382 opResult.getDocument().setUrl(null);
385 logMetricsInfo(override, SearchDbMsgs.DELETE_DOCUMENT_TIME, opResult, indexName, document.getId());
387 shutdownConnection(conn);
393 public DocumentOperationResult getDocument(String indexName, DocumentStoreDataEntity document)
394 throws DocumentStoreOperationException {
395 final UriBuilder uriBuilder = createUriBuilder(indexName, DEFAULT_TYPE, document.getId());
396 if (document.getVersion() != null) {
397 uriBuilder.replaceQuery(URL_QUERY_VERSION + document.getVersion());
400 MdcOverride override = getStartTime(new MdcOverride());
401 HttpURLConnection conn = createConnection(buildUrl(uriBuilder), "GET");
403 DocumentOperationResult opResult = getOperationResult(conn);
404 buildDocumentResult(opResult, indexName);
406 logMetricsInfo(override, SearchDbMsgs.GET_DOCUMENT_TIME, opResult, indexName, document.getId());
408 shutdownConnection(conn);
414 public SearchOperationResult search(String indexName, String queryString) throws DocumentStoreOperationException {
415 final URL url = buildUrl(createUriBuilder(indexName, "_search").replaceQuery(queryString));
417 MdcOverride override = getStartTime(new MdcOverride());
419 HttpURLConnection conn = createConnection(url, "GET");
420 SearchOperationResult opResult = getSearchOperationResult(conn);
421 buildSearchResult(opResult, indexName);
423 logMetricsInfo(override, SearchDbMsgs.QUERY_DOCUMENT_TIME, opResult, indexName, queryString);
429 public SearchOperationResult searchWithPayload(String indexName, String query)
430 throws DocumentStoreOperationException {
431 if (logger.isDebugEnabled()) {
432 logger.debug("Querying index: " + indexName + " with query string: " + query);
434 final URL url = buildUrl(createUriBuilder(indexName, "_search"));
436 MdcOverride override = getStartTime(new MdcOverride());
438 HttpURLConnection conn = createConnection(url, HttpMethod.POST);
439 attachContent(conn, query);
440 logger.debug("Request body = Elasticsearch query = " + query);
442 SearchOperationResult opResult = getSearchOperationResult(conn);
443 buildSearchResult(opResult, indexName);
445 logMetricsInfo(override, SearchDbMsgs.QUERY_DOCUMENT_TIME, opResult, indexName, query);
447 shutdownConnection(conn);
453 public SearchOperationResult suggestionQueryWithPayload(String indexName, String query)
454 throws DocumentStoreOperationException {
455 if (logger.isDebugEnabled()) {
456 logger.debug("Querying Suggestion index: " + indexName + " with query string: " + query);
459 MdcOverride override = getStartTime(new MdcOverride());
460 HttpURLConnection conn = createConnection(buildUrl(createUriBuilder(indexName, "_suggest")), HttpMethod.POST);
461 attachContent(conn, query);
463 logger.debug("Request body = Elasticsearch query = " + query);
465 SearchOperationResult opResult = getSearchOperationResult(conn);
466 buildSuggestResult(opResult, indexName);
468 logMetricsInfo(override, SearchDbMsgs.QUERY_DOCUMENT_TIME, opResult, indexName, query);
470 shutdownConnection(conn);
476 public OperationResult performBulkOperations(BulkRequest[] requests) throws DocumentStoreOperationException {
477 if (logger.isDebugEnabled()) {
478 StringBuilder dbgString = new StringBuilder("ESController: performBulkOperations - Operations: ");
480 for (BulkRequest request : requests) {
481 dbgString.append("[").append(request).append("] ");
484 logger.debug(dbgString.toString());
487 MdcOverride override = getStartTime(new MdcOverride());
489 // Parse the supplied set of operations.
490 // Iterate over the list of operations which we were provided and
491 // translate them into a format that ElasticSearh understands.
493 StringBuilder esOperationSet = new StringBuilder(128);
494 List<ElasticSearchResultItem> rejected = new ArrayList<>();
495 for (BulkRequest request : requests) {
497 // Convert the request to the syntax ElasticSearch likes.
498 if (buildEsOperation(request, esOperationSet, rejected)) {
503 ElasticSearchBulkOperationResult opResult = null;
505 HttpURLConnection conn;
507 conn = (HttpURLConnection) buildUrl(createUriBuilder("_bulk")).openConnection();
508 conn.setRequestMethod(HttpMethod.PUT);
509 conn.setDoOutput(true);
510 conn.setRequestProperty(CONTENT_TYPE, APPLICATION_XND_JSON_TYPE);
511 if(config.useAuth()){
512 conn.setRequestProperty("Authorization", config.getAuthValue());
514 conn.setRequestProperty("Connection", "Close");
516 } catch (IOException e) {
518 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, e.getMessage());
519 if (logger.isDebugEnabled()) {
520 logger.debug(Throwables.getStackTraceAsString(e));
523 throw new DocumentStoreOperationException(
524 "Failed to open connection to document store. Cause: " + e.getMessage(), e);
527 StringBuilder bulkResult = new StringBuilder(128);
529 // Create an output stream to write our request to.
530 OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
532 if (logger.isDebugEnabled()) {
533 logger.debug("ESController: Sending 'BULK' request to " + conn.getURL());
534 logger.debug("ESController: operations: " + esOperationSet.toString().replaceAll("\n", "\\n"));
537 // Write the resulting request string to our output stream. (this sends the request to ES?)
538 out.write(esOperationSet.toString());
541 // Open an input stream on our connection in order to read back the results.
542 InputStream is = conn.getInputStream();
543 InputStreamReader inputstreamreader = new InputStreamReader(is);
544 BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
546 // Read the contents of the input stream into our result string...
547 String esResponseString = null;
549 while ((esResponseString = bufferedreader.readLine()) != null) {
550 bulkResult.append(esResponseString).append("\n");
553 } catch (IOException e) {
555 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, e.getMessage());
556 if (logger.isDebugEnabled()) {
557 StringWriter sw = new StringWriter();
558 e.printStackTrace(new PrintWriter(sw));
559 logger.debug(sw.toString());
562 throw new DocumentStoreOperationException(
563 "Failure interacting with document store. Cause: " + e.getMessage(), e);
566 if (logger.isDebugEnabled()) {
567 logger.debug("ESController: Received result string from ElasticSearch: = " + bulkResult.toString());
570 // ...and marshal the resulting string into a Java object.
572 opResult = marshallEsBulkResult(bulkResult.toString());
574 } catch (IOException e) {
575 logger.warn(SearchDbMsgs.BULK_OPERATION_FAILURE, e.getMessage());
576 if (logger.isDebugEnabled()) {
577 logger.debug(Throwables.getStackTraceAsString(e));
580 throw new DocumentStoreOperationException("Failed to marshal response body. Cause: " + e.getMessage(),
585 OperationResult result = new OperationResultBuilder() //
586 .resultCode(HttpStatus.MULTI_STATUS_207) //
587 .result(buildGenericBulkResultSet(opResult, rejected)) //
590 // In the success case we don't want the entire result string to be dumped into the metrics log, so concatenate
592 String resultStringForMetricsLog = result.getResult();
593 if (isSuccess(result)) {
594 resultStringForMetricsLog =
595 resultStringForMetricsLog.substring(0, Math.max(resultStringForMetricsLog.length(), 85)) + "...";
598 metricsLogger.info(SearchDbMsgs.BULK_OPERATIONS_TIME,
600 .setField(LogLine.DefinedFields.RESPONSE_CODE, result.getResultCode())
601 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, resultStringForMetricsLog),
609 * This method queryies ElasticSearch to determine if the supplied index is present in the document store.
611 * @param indexName - The index to look for.
612 * @return - An operation result indicating the success or failure of the check.
613 * @throws DocumentStoreOperationException
615 private OperationResult checkIndexExistence(String indexName) throws DocumentStoreOperationException {
616 MdcOverride override = getStartTime(new MdcOverride());
618 HttpURLConnection conn = createConnection(buildUrl(createUriBuilder(indexName)), HttpMethod.HEAD);
621 resultCode = conn.getResponseCode();
622 } catch (IOException ex) {
623 shutdownConnection(conn);
624 throw new DocumentStoreOperationException(ErrorMessage.NO_RESPONSE_CODE, ex);
626 logger.debug(MSG_RESPONSE_CODE + resultCode);
628 OperationResult opResult = new OperationResultBuilder().useDefaults().resultCode(resultCode).build();
629 logMetricsInfo(override, SearchDbMsgs.CHECK_INDEX_TIME, opResult, indexName);
630 shutdownConnection(conn);
635 private DocumentOperationResult createDocumentWithId(String indexName, DocumentStoreDataEntity document)
636 throws DocumentStoreOperationException {
637 // check if the document already exists
638 DocumentOperationResult opResult = checkDocumentExistence(indexName, document.getId());
640 if (opResult.getResultCode() != Status.NOT_FOUND.getStatusCode()) {
641 if (opResult.getResultCode() == Status.CONFLICT.getStatusCode()) {
642 opResult.setFailureCause("A document with the same id already exists.");
644 opResult.setFailureCause("Failed to verify a document with the specified id does not already exist.");
646 opResult.setResultCode(Status.CONFLICT.getStatusCode());
650 final URL url = buildUrl(createUriBuilder(indexName, DEFAULT_TYPE, document.getId()));
651 MdcOverride override = getStartTime(new MdcOverride());
653 HttpURLConnection conn = createConnection(url, HttpMethod.PUT);
654 attachDocument(conn, document);
656 opResult = getOperationResult(conn);
657 buildDocumentResult(opResult, indexName);
659 logMetricsInfo(override, SearchDbMsgs.CREATE_DOCUMENT_TIME, opResult, indexName);
661 shutdownConnection(conn);
666 private DocumentOperationResult createDocumentWithoutId(String indexName, DocumentStoreDataEntity document)
667 throws DocumentStoreOperationException {
668 final URL url = buildUrl(createUriBuilder(indexName, DEFAULT_TYPE));
670 MdcOverride override = getStartTime(new MdcOverride());
671 HttpURLConnection conn = createConnection(url, HttpMethod.POST);
672 attachDocument(conn, document);
674 DocumentOperationResult response = getOperationResult(conn);
675 buildDocumentResult(response, indexName);
677 logMetricsInfo(override, SearchDbMsgs.CREATE_DOCUMENT_TIME, response, indexName);
679 shutdownConnection(conn);
684 private void attachDocument(HttpURLConnection conn, DocumentStoreDataEntity doc)
685 throws DocumentStoreOperationException {
686 conn.setRequestProperty("Connection", "Close");
687 attachContent(conn, doc.getContentInJson());
690 private DocumentOperationResult checkDocumentExistence(String indexName, String docId)
691 throws DocumentStoreOperationException {
692 MdcOverride override = getStartTime(new MdcOverride());
693 HttpURLConnection conn =
694 createConnection(buildUrl(createUriBuilder(indexName, DEFAULT_TYPE, docId)), HttpMethod.HEAD);
697 resultCode = conn.getResponseCode();
698 } catch (IOException ex) {
699 shutdownConnection(conn);
700 throw new DocumentStoreOperationException(ErrorMessage.NO_RESPONSE_CODE, ex);
703 logger.debug(MSG_RESPONSE_CODE + resultCode);
705 DocumentOperationResult opResult = (DocumentOperationResult) new OperationResultBuilder(Type.DOCUMENT)
706 .useDefaults().resultCode(resultCode).build();
708 logMetricsInfo(override, SearchDbMsgs.GET_DOCUMENT_TIME, opResult, indexName, docId);
709 shutdownConnection(conn);
714 private void attachContent(HttpURLConnection conn, String content) throws DocumentStoreOperationException {
715 OutputStream outputStream = null;
716 OutputStreamWriter out = null;
719 outputStream = conn.getOutputStream();
720 } catch (IOException e) {
721 shutdownConnection(conn);
722 throw new DocumentStoreOperationException("Failed to get connection output stream.", e);
725 out = new OutputStreamWriter(outputStream);
730 } catch (IOException e) {
731 shutdownConnection(conn);
732 throw new DocumentStoreOperationException("Failed to write to the output stream.", e);
736 private HttpURLConnection initializeConnection(URL url) throws DocumentStoreOperationException {
737 HttpURLConnection conn = null;
739 conn = (HttpURLConnection) url.openConnection();
740 conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);
741 conn.setDoOutput(true);
742 if (config.useAuth()) {
743 conn.setRequestProperty("Authorization", config.getAuthValue());
745 } catch (IOException e) {
746 shutdownConnection(conn);
747 throw new DocumentStoreOperationException("Failed to open connection to URL " + url, e);
753 private OperationResult handleResponse(HttpURLConnection conn) throws DocumentStoreOperationException {
754 return handleResponse(conn, new OperationResultBuilder().useDefaults());
757 private OperationResult handleResponse(HttpURLConnection conn, OperationResultBuilder rb)
758 throws DocumentStoreOperationException {
762 resultCode = conn.getResponseCode();
763 } catch (IOException ex) {
764 shutdownConnection(conn);
765 throw new DocumentStoreOperationException(ErrorMessage.NO_RESPONSE_CODE, ex);
768 logger.debug(MSG_RESPONSE_CODE + resultCode);
770 InputStream inputStream = null;
772 if (!ApiUtils.isSuccessStatusCode(resultCode)) {
773 inputStream = conn.getErrorStream();
776 inputStream = conn.getInputStream();
777 } catch (IOException e) {
778 shutdownConnection(conn);
779 throw new DocumentStoreOperationException("Failed to get the response input stream.", e);
783 InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
784 BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
786 StringBuilder result = new StringBuilder(128);
787 String string = null;
790 while ((string = bufferedreader.readLine()) != null) {
791 result.append(string).append("\n");
793 } catch (IOException e) {
794 shutdownConnection(conn);
795 throw new DocumentStoreOperationException("Failed getting the response body payload.", e);
798 if (resultCode == Status.CONFLICT.getStatusCode()) {
799 rb.resultCode(Status.PRECONDITION_FAILED.getStatusCode());
801 rb.resultCode(resultCode);
803 if (logger.isDebugEnabled()) {
804 logger.debug("Raw result string from ElasticSearch = " + result.toString());
806 rb.result(result.toString());
807 rb.resultVersion(extractVersion(result.toString()));
811 private String extractVersion(String result) {
812 JSONParser parser = new JSONParser();
813 String version = null;
815 JSONObject root = (JSONObject) parser.parse(result);
816 if (root.get(JSON_ATTR_VERSION) != null) {
817 version = root.get(JSON_ATTR_VERSION).toString();
819 } catch (ParseException e) {
820 // Not all responses from ElasticSearch include a version, so
821 // if we don't get one back, just return an empty string rather
822 // than trigger a false failure.
829 * This convenience method gets the current system time and stores it in an attribute in the supplied
830 * {@link MdcOverride} object so that it can be used later by the metrics logger.
832 * @param override - The {@link MdcOverride} object to update.
833 * @return - The supplied {@link MdcOverride} object.
835 private MdcOverride getStartTime(MdcOverride override) {
837 // Grab the current time...
838 long startTimeInMs = System.currentTimeMillis();
840 // ...and add it as an attribute to the supplied MDC Override object.
841 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
842 override.addAttribute(MdcContext.MDC_START_TIME, formatter.format(startTimeInMs));
844 // Return the MdcOverride object that we were passed.
845 // This looks odd, but it allows us to do stuff like:
847 // MdcOverride ov = getStartTime(new MdcOverride())
849 // which is quite handy, but also allows us to pass in an existing
850 // MdcOverride object which already has some attributes set.
854 private boolean isSuccess(OperationResult result) {
855 return ApiUtils.isSuccessStatusCode(result.getResultCode());
858 private UriBuilder createUriBuilder(String path, String... paths) {
859 UriBuilder builder = UriBuilder.fromPath(path);
860 for (String other : paths) {
863 builder.host(config.getIpAddress());
864 String port = Optional.ofNullable(config.getHttpPort()).orElse("0");
865 builder.port(Integer.valueOf(port));
866 builder.scheme(config.getUriScheme());
870 private URL buildUrl(UriBuilder builder) throws DocumentStoreOperationException {
872 return builder.build().toURL();
873 } catch (MalformedURLException e) {
874 logger.error(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "buildUrl", e.getLocalizedMessage());
875 throw new DocumentStoreOperationException("Error building a URL with " + builder.toString(), e);
879 private HttpURLConnection createConnection(final URL url, final String method)
880 throws DocumentStoreOperationException {
881 HttpURLConnection conn = initializeConnection(url);
883 logger.debug("\nSending '" + method + "' request to URL : " + conn.getURL());
884 conn.setRequestMethod(method);
885 } catch (ProtocolException e) {
886 shutdownConnection(conn);
887 throw new DocumentStoreOperationException(ErrorMessage.SET_REQUEST_METHOD_FAILED, e, method);
892 private OperationResult checkConnection() throws IOException, DocumentStoreOperationException {
893 HttpURLConnection conn = createConnection(buildUrl(createUriBuilder("_cluster/health")), HttpMethod.GET);
894 int resultCode = conn.getResponseCode();
895 logger.debug("getClusterHealth() response Code : " + resultCode);
896 shutdownConnection(conn);
897 return new OperationResultBuilder().resultCode(resultCode).build();
900 private void shutdownConnection(HttpURLConnection connection) {
901 if (connection == null) {
905 final String methodName = "shutdownConnection";
906 InputStream inputstream = null;
907 OutputStream outputstream = null;
910 inputstream = connection.getInputStream();
911 } catch (IOException e) {
912 logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, methodName, e.getLocalizedMessage());
914 if (inputstream != null) {
917 } catch (IOException e) {
918 logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, methodName, e.getLocalizedMessage());
924 outputstream = connection.getOutputStream();
925 } catch (IOException e) {
926 logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, methodName, e.getLocalizedMessage());
928 if (outputstream != null) {
930 outputstream.close();
931 } catch (IOException e) {
932 logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, methodName, e.getLocalizedMessage());
937 connection.disconnect();
941 * This method converts a {@link BulkRequest} object into a json structure which can be understood by ElasticSearch.
943 * @param request - The request to be performed.
944 * @param sb - The string builder to append the json data to
945 * @throws DocumentStoreOperationException
947 private boolean buildEsOperation(BulkRequest request, StringBuilder sb, List<ElasticSearchResultItem> fails)
948 throws DocumentStoreOperationException {
950 boolean retVal = true;
951 // What kind of operation are we performing?
952 switch (request.getOperationType()) {
954 // Create a new document.
957 // Make sure that we were supplied a document payload.
958 if (request.getOperation().getDocument() == null) {
960 fails.add(generateRejectionEntry(request.getOperationType(), "Missing document payload",
961 request.getIndex(), request.getId(), 400, request.getOperation().getMetaData().getUrl()));
965 // Make sure that the supplied document URL is formatted
967 if (!ApiUtils.validateDocumentUri(request.getOperation().getMetaData().getUrl(), false)) {
968 fails.add(generateRejectionEntry(request.getOperationType(),
969 MSG_INVALID_DOCUMENT_URL + request.getOperation().getMetaData().getUrl(),
970 request.getIndex(), "", 400, request.getOperation().getMetaData().getUrl()));
974 // Validate that the specified index actually exists before we
975 // try to perform the create.
976 if (!indexExists(ApiUtils.extractIndexFromUri(request.getOperation().getMetaData().getUrl()))) {
978 fails.add(generateRejectionEntry(request.getOperationType(),
979 MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
980 request.getId(), 404, request.getOperation().getMetaData().getUrl()));
984 // If we were supplied an id for the new document, then
985 // include it in the bulk operation to Elastic Search
986 if (request.getId() == null) {
988 sb.append(String.format(BULK_CREATE_WITHOUT_INDEX_TEMPLATE, request.getIndex(), DEFAULT_TYPE));
990 // Otherwise, we just leave that parameter off and ElasticSearch
991 // will generate one for us.
993 sb.append(String.format(BULK_CREATE_WITH_INDEX_TEMPLATE, request.getIndex(), DEFAULT_TYPE,
998 // Append the document that we want to create.
999 sb.append(request.getOperation().getDocument().toJson()).append("\n");
1000 } catch (JsonProcessingException e) {
1001 throw new DocumentStoreOperationException("Failure parsing document to json", e);
1006 // Update an existing document.
1009 // Make sure that we were supplied a document payload.
1010 if (request.getOperation().getDocument() == null) {
1012 fails.add(generateRejectionEntry(request.getOperationType(), "Missing document payload",
1013 request.getIndex(), request.getId(), 400, request.getOperation().getMetaData().getUrl()));
1017 // Make sure that the supplied document URL is formatted
1019 if (!ApiUtils.validateDocumentUri(request.getOperation().getMetaData().getUrl(), true)) {
1020 fails.add(generateRejectionEntry(request.getOperationType(),
1021 MSG_INVALID_DOCUMENT_URL + request.getOperation().getMetaData().getUrl(),
1022 request.getIndex(), "", 400, request.getOperation().getMetaData().getUrl()));
1026 // Validate that the specified index actually exists before we
1027 // try to perform the update.
1028 if (!indexExists(request.getIndex())) {
1030 fails.add(generateRejectionEntry(request.getOperationType(),
1031 MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
1032 request.getId(), 404, request.getOperation().getMetaData().getUrl()));
1036 // Validate that the document we are trying to update actually
1037 // exists before we try to perform the update.
1038 if (!documentExists(request.getIndex(), request.getId())) {
1040 fails.add(generateRejectionEntry(request.getOperationType(),
1041 MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
1042 request.getId(), 404, request.getOperation().getMetaData().getUrl()));
1046 // It is mandatory that a version be supplied for an update operation,
1047 // so validate that now.
1048 if (request.getOperation().getMetaData().getEtag() == null) {
1050 fails.add(generateRejectionEntry(request.getOperationType(), "Missing mandatory ETag field",
1051 request.getIndex(), request.getId(), 400, request.getOperation().getMetaData().getUrl()));
1055 // Generate the update request...
1056 sb.append(String.format(BULK_IMPORT_INDEX_TEMPLATE, request.getIndex(), DEFAULT_TYPE, request.getId(),
1057 request.getOperation().getMetaData().getEtag()));
1059 // ...and append the document that we want to update.
1061 sb.append(request.getOperation().getDocument().toJson()).append("\n");
1062 } catch (JsonProcessingException e) {
1063 throw new DocumentStoreOperationException("Failure parsing document to json", e);
1067 // Delete an existing document.
1070 // Make sure that the supplied document URL is formatted
1072 if (!ApiUtils.validateDocumentUri(request.getOperation().getMetaData().getUrl(), true)) {
1073 fails.add(generateRejectionEntry(request.getOperationType(),
1074 MSG_INVALID_DOCUMENT_URL + request.getOperation().getMetaData().getUrl(),
1075 request.getIndex(), "", 400, request.getOperation().getMetaData().getUrl()));
1079 // Validate that the specified index actually exists before we
1080 // try to perform the delete.
1081 if (!indexExists(request.getIndex())) {
1083 fails.add(generateRejectionEntry(request.getOperationType(),
1084 MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
1085 request.getId(), 404, request.getOperation().getMetaData().getUrl()));
1089 // Validate that the document we are trying to update actually
1090 // exists before we try to perform the delete.
1091 if (!documentExists(request.getIndex(), request.getId())) {
1093 fails.add(generateRejectionEntry(request.getOperationType(),
1094 MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
1095 request.getId(), 404, request.getOperation().getMetaData().getUrl()));
1099 // It is mandatory that a version be supplied for a delete operation,
1100 // so validate that now.
1101 if (request.getOperation().getMetaData().getEtag() == null) {
1103 fails.add(generateRejectionEntry(request.getOperationType(), "Missing mandatory ETag field",
1104 request.getIndex(), request.getId(), 400, request.getOperation().getMetaData().getUrl()));
1108 // Generate the delete request.
1109 sb.append(String.format(BULK_DELETE_TEMPLATE, request.getIndex(), DEFAULT_TYPE, request.getId(),
1110 request.getOperation().getMetaData().getEtag()));
1118 private boolean indexExists(String index) throws DocumentStoreOperationException {
1119 return isSuccess(checkIndexExistence(index));
1122 private boolean documentExists(String index, String id) throws DocumentStoreOperationException {
1123 return isSuccess(checkDocumentExistence(index, id));
1127 * This method constructs a status entry for a bulk operation which has been rejected before even sending it to the
1130 * @param rejectReason - A message describing why the operation was rejected.
1131 * @param anId - The identifier associated with the document being acted on.
1132 * @param statusCode - An HTTP status code.
1133 * @return - A result set item.
1135 private ElasticSearchResultItem generateRejectionEntry(OperationType opType, String rejectReason, String index,
1136 String anId, int statusCode, String originalUrl) {
1138 ElasticSearchError err = new ElasticSearchError();
1139 err.setReason(rejectReason);
1141 ElasticSearchOperationStatus op = new ElasticSearchOperationStatus();
1144 op.setStatus(statusCode);
1146 op.setAdditionalProperties(ElasticSearchResultItem.REQUEST_URL, originalUrl);
1148 ElasticSearchResultItem rejectionResult = new ElasticSearchResultItem();
1152 rejectionResult.setCreate(op);
1155 rejectionResult.setIndex(op);
1158 rejectionResult.setDelete(op);
1163 return rejectionResult;
1167 * This method takes the json structure returned from ElasticSearch in response to a bulk operations request and
1168 * marshals it into a Java object.
1170 * @param jsonResult - The bulk operations response returned from ElasticSearch.
1171 * @return - The marshalled response.
1172 * @throws JsonParseException
1173 * @throws JsonMappingException
1174 * @throws IOException
1176 private ElasticSearchBulkOperationResult marshallEsBulkResult(String jsonResult) throws IOException {
1177 if (jsonResult != null) {
1178 if (logger.isDebugEnabled()) {
1179 logger.debug("ESController: Marshalling ES result set from json: " + jsonResult.replaceAll("\n", ""));
1182 ObjectMapper mapper = new ObjectMapper();
1183 mapper.setSerializationInclusion(Include.NON_EMPTY);
1185 return mapper.readValue(jsonResult, ElasticSearchBulkOperationResult.class);
1192 * This method takes the marshalled ElasticSearch bulk response and converts it into a generic response payload.
1194 * @param esResult - ElasticSearch bulk operations response.
1195 * @return - A generic result set.
1197 private String buildGenericBulkResultSet(ElasticSearchBulkOperationResult esResult,
1198 List<ElasticSearchResultItem> rejectedOps) {
1200 int totalSuccess = 0;
1203 if (logger.isDebugEnabled()) {
1205 logger.debug("ESController: Build generic result set. ES Results: "
1206 + ((esResult != null) ? esResult.toString() : "[]") + " Rejected Ops: " + rejectedOps.toString());
1209 // Build a combined list of result items from the results returned
1210 // from ElasticSearch and the list of operations that we rejected
1211 // without sending to ElasticSearch.
1212 List<ElasticSearchResultItem> combinedResults = new ArrayList<>();
1213 if (esResult != null) {
1214 combinedResults.addAll(Arrays.asList(esResult.getItems()));
1216 combinedResults.addAll(rejectedOps);
1218 // Iterate over the individual results in the resulting result set.
1219 StringBuilder resultsBuilder = new StringBuilder();
1220 AtomicBoolean firstItem = new AtomicBoolean(true);
1221 for (ElasticSearchResultItem item : combinedResults) {
1223 // Increment the operation counts.
1225 if (ApiUtils.isSuccessStatusCode(item.operationStatus().getStatus())) {
1231 // Prepend a comma to our response string unless this it the
1232 // first result in the set.
1233 if (!firstItem.compareAndSet(true, false)) {
1234 resultsBuilder.append(", ");
1237 // Append the current result as a generic json structure.
1238 resultsBuilder.append(item.toJson());
1241 return "{ \"total_operations\": " + totalOps + ", " + "\"total_success\": " + totalSuccess + ", "
1242 + "\"total_fails\": " + totalFails + ", " + "\"results\": [" + resultsBuilder.toString() + "]}";
1245 private DocumentOperationResult getOperationResult(HttpURLConnection conn) throws DocumentStoreOperationException {
1246 return (DocumentOperationResult) handleResponse(conn, new OperationResultBuilder(Type.DOCUMENT).useDefaults());
1249 private SearchOperationResult getSearchOperationResult(HttpURLConnection conn)
1250 throws DocumentStoreOperationException {
1251 return (SearchOperationResult) handleResponse(conn, new OperationResultBuilder(Type.SEARCH).useDefaults());
1254 private void buildDocumentResult(DocumentOperationResult result, String index)
1255 throws DocumentStoreOperationException {
1257 JSONParser parser = new JSONParser();
1260 root = (JSONObject) parser.parse(result.getResult());
1261 if (isSuccess(result)) {
1262 // Success response object
1263 Document doc = new Document();
1264 doc.setEtag(result.getResultVersion());
1265 doc.setUrl(buildDocumentResponseUrl(index, root.get("_id").toString()));
1267 doc.setContent((JSONObject) root.get("_source"));
1268 result.setDocument(doc);
1271 // Error response object
1272 JSONObject error = (JSONObject) root.get(JSON_ATTR_ERROR);
1273 if (error != null) {
1275 new ErrorResult(error.get("type").toString(), error.get(JSON_ATTR_REASON).toString()));
1279 } catch (Exception e) {
1280 throw new DocumentStoreOperationException(FAILED_TO_PARSE_ELASTIC_SEARCH_RESPONSE + result.getResult());
1284 private String buildDocumentResponseUrl(String index, String id) {
1285 return ApiUtils.buildDocumentUri(index, id);
1288 private void buildSearchResult(SearchOperationResult result, String index) throws DocumentStoreOperationException {
1289 JSONParser parser = new JSONParser();
1293 root = (JSONObject) parser.parse(result.getResult());
1294 if (isSuccess(result)) {
1295 JSONObject hits = (JSONObject) root.get("hits");
1296 JSONArray hitArray = (JSONArray) hits.get("hits");
1297 SearchHits searchHits = new SearchHits();
1298 searchHits.setTotalHits(hits.get("total").toString());
1299 ArrayList<SearchHit> searchHitArray = new ArrayList<>();
1301 for (int i = 0; i < hitArray.size(); i++) {
1302 JSONObject hit = (JSONObject) hitArray.get(i);
1303 SearchHit searchHit = new SearchHit();
1304 searchHit.setScore((hit.get("_score") != null) ? hit.get("_score").toString() : "");
1305 Document doc = new Document();
1306 if (hit.get(JSON_ATTR_VERSION) != null) {
1307 doc.setEtag((hit.get(JSON_ATTR_VERSION) != null) ? hit.get(JSON_ATTR_VERSION).toString() : "");
1311 buildDocumentResponseUrl(index, (hit.get("_id") != null) ? hit.get("_id").toString() : ""));
1312 doc.setContent((JSONObject) hit.get("_source"));
1313 searchHit.setDocument(doc);
1314 searchHitArray.add(searchHit);
1316 searchHits.setHits(searchHitArray.toArray(new SearchHit[searchHitArray.size()]));
1317 result.setSearchResult(searchHits);
1319 JSONObject aggregations = (JSONObject) root.get("aggregations");
1320 if (aggregations != null) {
1321 AggregationResult[] aggResults = AggregationParsingUtil.parseAggregationResults(aggregations);
1322 AggregationResults aggs = new AggregationResults();
1323 aggs.setAggregations(aggResults);
1324 result.setAggregationResult(aggs);
1329 JSONObject error = (JSONObject) root.get(JSON_ATTR_ERROR);
1330 if (error != null) {
1332 new ErrorResult(error.get("type").toString(), error.get(JSON_ATTR_REASON).toString()));
1335 } catch (Exception e) {
1336 throw new DocumentStoreOperationException(FAILED_TO_PARSE_ELASTIC_SEARCH_RESPONSE + result.getResult());
1340 private void buildSuggestResult(SearchOperationResult result, String index) throws DocumentStoreOperationException {
1341 JSONParser parser = new JSONParser();
1344 root = (JSONObject) parser.parse(result.getResult());
1345 if (isSuccess(result)) {
1346 JSONArray hitArray = (JSONArray) root.get("suggest-vnf");
1347 JSONObject hitdata = (JSONObject) hitArray.get(0);
1348 JSONArray optionsArray = (JSONArray) hitdata.get("options");
1349 SuggestHits suggestHits = new SuggestHits();
1350 suggestHits.setTotalHits(String.valueOf(optionsArray.size()));
1352 ArrayList<SuggestHit> suggestHitArray = new ArrayList<>();
1354 for (int i = 0; i < optionsArray.size(); i++) {
1355 JSONObject hit = (JSONObject) optionsArray.get(i);
1357 SuggestHit suggestHit = new SuggestHit();
1358 suggestHit.setScore((hit.get("score") != null) ? hit.get("score").toString() : "");
1359 suggestHit.setText((hit.get("text") != null) ? hit.get("text").toString() : "");
1360 Document doc = new Document();
1361 if (hit.get(JSON_ATTR_VERSION) != null) {
1362 doc.setEtag((hit.get(JSON_ATTR_VERSION) != null) ? hit.get(JSON_ATTR_VERSION).toString() : "");
1365 buildDocumentResponseUrl(index, (hit.get("_id") != null) ? hit.get("_id").toString() : ""));
1367 doc.setContent((JSONObject) hit.get("payload"));
1368 suggestHit.setDocument(doc);
1369 suggestHitArray.add(suggestHit);
1371 suggestHits.setHits(suggestHitArray.toArray(new SuggestHit[suggestHitArray.size()]));
1372 result.setSuggestResult(suggestHits);
1374 JSONObject aggregations = (JSONObject) root.get("aggregations");
1375 if (aggregations != null) {
1376 AggregationResult[] aggResults = AggregationParsingUtil.parseAggregationResults(aggregations);
1377 AggregationResults aggs = new AggregationResults();
1378 aggs.setAggregations(aggResults);
1379 result.setAggregationResult(aggs);
1384 JSONObject error = (JSONObject) root.get(JSON_ATTR_ERROR);
1385 if (error != null) {
1387 new ErrorResult(error.get("type").toString(), error.get(JSON_ATTR_REASON).toString()));
1390 } catch (Exception e) {
1391 throw new DocumentStoreOperationException(FAILED_TO_PARSE_ELASTIC_SEARCH_RESPONSE + result.getResult());
1396 * Record the timing of the operation in the metrics log.
1399 private void logMetricsInfo(MdcOverride override, SearchDbMsgs message, OperationResult operationResult,
1401 metricsLogger.info(message,
1403 .setField(LogLine.DefinedFields.RESPONSE_CODE, operationResult.getResultCode())
1404 .setField(LogLine.DefinedFields.RESPONSE_DESCRIPTION, operationResult.getResult())
1405 .setField(LogLine.DefinedFields.SERVER_IP, "ElasticHost-"+config.getIpAddress()),