package org.onap.aai.sa.searchdbabstraction.elasticsearch.dao;
+import static javax.ws.rs.core.HttpHeaders.CONTENT_TYPE;
+import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
+import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.Response.Status.Family;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.onap.aai.sa.searchdbabstraction.util.DocumentSchemaUtil;
import org.onap.aai.sa.searchdbabstraction.util.ElasticSearchPayloadTranslator;
import org.onap.aai.sa.searchdbabstraction.util.SearchDbConstants;
-import org.springframework.http.HttpStatus;
/**
* This class has the Elasticsearch implementation of the DB operations defined in DocumentStoreInterface.
private static final Logger metricsLogger =
LoggerFactory.getInstance().getMetricsLogger(ElasticSearchHttpController.class.getName());
+ private static final String JSON_ATTR_VERSION = "_version";
+ private static final String JSON_ATTR_ERROR = "error";
+ private static final String JSON_ATTR_REASON = "reason";
+
+ private static final String QUERY_PARAM_VERSION = "?version=";
+
+ private static final String MSG_RESOURCE_MISSING = "Specified resource does not exist: ";
+ private static final String MSG_RESPONSE_CODE = "Response Code : ";
+ private static final String MSG_INVALID_DOCUMENT_URL = "Invalid document URL: ";
+ private static final String MSG_HTTP_PUT_FAILED = "Failed to set HTTP request method to PUT.";
+ private static final String MSG_HTTP_POST_FAILED = "Failed to set HTTP request method to POST.";
+ private static final String INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT =
+ "Internal Error: ElasticSearch operation fault occurred";
+ private static final String FAILED_TO_GET_THE_RESPONSE_CODE_FROM_THE_CONNECTION =
+ "Failed to get the response code from the connection.";
+ private static final String FAILED_TO_PARSE_ELASTIC_SEARCH_RESPONSE = "Failed to parse Elastic Search response.";
+
private static final String BULK_CREATE_WITHOUT_INDEX_TEMPLATE =
"{\"create\":{\"_index\" : \"%s\", \"_type\" : \"%s\"} }\n";
private static final String BULK_CREATE_WITH_INDEX_TEMPLATE =
private static final String BULK_DELETE_TEMPLATE =
"{ \"delete\": { \"_index\": \"%s\", \"_type\": \"%s\", \"_id\": \"%s\", \"_version\":\"%s\"}}\n";
- private static final String INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT =
- "Internal Error: ElasticSearch operation fault occurred";
private final ElasticSearchConfig config;
private static final String DEFAULT_TYPE = "default";
protected AnalysisConfiguration analysisConfig;
public static ElasticSearchHttpController getInstance() {
-
synchronized (ElasticSearchHttpController.class) {
-
if (instance == null) {
-
Properties properties = new Properties();
File file = new File(SearchDbConstants.ES_CONFIG_FILE);
try {
}
}
-
public AnalysisConfiguration getAnalysisConfig() {
return analysisConfig;
}
@Override
public OperationResult createIndex(String index, DocumentSchema documentSchema) {
-
OperationResult result = new OperationResult();
- result.setResultCode(500);
+ result.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
try {
// ElasticSearch will return us a 200 code on success when we
// want to report a 201, so translate the result here.
- result.setResultCode((result.getResultCode() == 200) ? 201 : result.getResultCode());
+ if (result.getResultCode() == Status.OK.getStatusCode()) {
+ result.setResultCode(Status.CREATED.getStatusCode());
+ }
+
if (isSuccess(result)) {
result.setResult("{\"url\": \"" + ApiUtils.buildIndexUri(index) + "\"}");
}
-
} catch (DocumentStoreOperationException | IOException e) {
-
result.setFailureCause("Document store operation failure. Cause: " + e.getMessage());
}
@Override
public OperationResult createDynamicIndex(String index, String dynamicSchema) {
OperationResult result = new OperationResult();
- result.setResultCode(500);
+ result.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
try {
result = createTable(index, dynamicSchema);
// ElasticSearch will return us a 200 code on success when we
// want to report a 201, so translate the result here.
- result.setResultCode((result.getResultCode() == 200) ? 201 : result.getResultCode());
+ if (result.getResultCode() == Status.OK.getStatusCode()) {
+ result.setResultCode(Status.CREATED.getStatusCode());
+ }
if (isSuccess(result)) {
result.setResult("{\"url\": \"" + ApiUtils.buildIndexUri(index) + "\"}");
}
return result;
}
-
@Override
public OperationResult deleteIndex(String indexName) throws DocumentStoreOperationException {
// Initialize operation result with a failure codes / fault string
OperationResult opResult = new OperationResult();
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
opResult.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
// Grab the current time so we can use it to generate a metrics log.
return opResult;
}
-
- private OperationResult checkConnection() throws Exception {
-
+ private OperationResult checkConnection() throws IOException {
String fullUrl = getFullUrl("/_cluster/health", false);
URL url = null;
HttpURLConnection conn = null;
return;
}
+ final String methodName = "shutdownConnection";
InputStream inputstream = null;
OutputStream outputstream = null;
try {
inputstream = connection.getInputStream();
} catch (IOException e) {
- logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "shutdownConnection", e.getLocalizedMessage());
+ logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, methodName, e.getLocalizedMessage());
} finally {
if (inputstream != null) {
try {
inputstream.close();
} catch (IOException e) {
- logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "shutdownConnection",
- e.getLocalizedMessage());
+ logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, methodName, e.getLocalizedMessage());
}
}
}
try {
outputstream = connection.getOutputStream();
} catch (IOException e) {
- logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "shutdownConnection", e.getLocalizedMessage());
+ logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, methodName, e.getLocalizedMessage());
} finally {
if (outputstream != null) {
try {
outputstream.close();
} catch (IOException e) {
- logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, "shutdownConnection",
- e.getLocalizedMessage());
+ logger.debug(SearchDbMsgs.EXCEPTION_DURING_METHOD_CALL, methodName, e.getLocalizedMessage());
}
}
}
OperationResult opResult = new OperationResult();
// Initialize operation result with a failure codes / fault string
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
opResult.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
// Grab the current time so we can use it to generate a metrics log.
try {
conn.setRequestMethod("PUT");
- conn.setRequestProperty("Content-Type", "application/json");
} catch (ProtocolException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to set HTTP request method to PUT.", e);
+ throw new DocumentStoreOperationException(MSG_HTTP_PUT_FAILED, e);
}
StringBuilder sb = new StringBuilder(128);
protected OperationResult createTable(String indexName, String settingsAndMappings)
throws DocumentStoreOperationException {
OperationResult result = new OperationResult();
- result.setResultCode(500);
+ result.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
result.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
// Grab the current time so we can use it to generate a metrics log.
try {
conn.setRequestMethod("PUT");
- conn.setRequestProperty("Content-Type", "application/json");
} catch (ProtocolException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to set HTTP request method to PUT.", e);
+ throw new DocumentStoreOperationException(MSG_HTTP_PUT_FAILED, e);
}
try {
boolean allowImplicitIndexCreation) throws DocumentStoreOperationException {
if (!allowImplicitIndexCreation) {
-
// Before we do anything, make sure that the specified index actually exists in the
// document store - we don't want to rely on ElasticSearch to fail the document
// create because it could be configured to implicitly create a non-existent index,
// which can lead to hard-to-debug behaviour with queries down the road.
OperationResult indexExistsResult = checkIndexExistence(indexName);
- if ((indexExistsResult.getResultCode() < 200) || (indexExistsResult.getResultCode() >= 300)) {
-
+ if (!isSuccess(indexExistsResult)) {
DocumentOperationResult opResult = new DocumentOperationResult();
- opResult.setResultCode(HttpStatus.NOT_FOUND.value());
- opResult.setResult("Document Index '" + indexName + "' does not exist.");
- opResult.setFailureCause("Document Index '" + indexName + "' does not exist.");
+ opResult.setResultCode(Status.NOT_FOUND.getStatusCode());
+ String resultMsg = "Document Index '" + indexName + "' does not exist.";
+ opResult.setResult(resultMsg);
+ opResult.setFailureCause(resultMsg);
return opResult;
}
}
// check if the document already exists
DocumentOperationResult opResult = checkDocumentExistence(indexName, document.getId());
-
- if (opResult.getResultCode() != HttpStatus.NOT_FOUND.value()) {
- if (opResult.getResultCode() == HttpStatus.CONFLICT.value()) {
+ if (opResult.getResultCode() != Status.NOT_FOUND.getStatusCode()) {
+ if (opResult.getResultCode() == Status.CONFLICT.getStatusCode()) {
opResult.setFailureCause("A document with the same id already exists.");
} else {
opResult.setFailureCause("Failed to verify a document with the specified id does not already exist.");
}
- opResult.setResultCode(HttpStatus.CONFLICT.value());
+ opResult.setResultCode(Status.CONFLICT.getStatusCode());
return opResult;
}
opResult = new DocumentOperationResult();
// Initialize operation result with a failure codes / fault string
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
opResult.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
// Grab the current time so we can use it to generate a metrics log.
conn.setRequestMethod("PUT");
} catch (ProtocolException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to set HTTP request method to PUT.", e);
+ throw new DocumentStoreOperationException(MSG_HTTP_PUT_FAILED, e);
}
attachDocument(conn, document);
shutdownConnection(conn);
return opResult;
-
}
private DocumentOperationResult createDocumentWithoutId(String indexName, DocumentStoreDataEntity document)
DocumentOperationResult response = new DocumentOperationResult();
// Initialize operation result with a failure codes / fault string
- response.setResultCode(500);
+ response.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
response.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
// Grab the current time so we can use it to generate a metrics log.
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to set HTTP request method to POST.", e);
+ throw new DocumentStoreOperationException(MSG_HTTP_POST_FAILED, e);
}
attachDocument(conn, document);
private void attachDocument(HttpURLConnection conn, DocumentStoreDataEntity doc)
throws DocumentStoreOperationException {
- conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Connection", "Close");
attachContent(conn, doc.getContentInJson());
}
DocumentOperationResult opResult = new DocumentOperationResult();
// Initialize operation result with a failure codes / fault string
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
// Grab the current time so we can use it to generate a metrics log.
MdcOverride override = getStartTime(new MdcOverride());
resultCode = conn.getResponseCode();
} catch (IOException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to get the response code from the connection.", e);
+ throw new DocumentStoreOperationException(FAILED_TO_GET_THE_RESPONSE_CODE_FROM_THE_CONNECTION, e);
}
- logger.debug("Response Code : " + resultCode);
+ logger.debug(MSG_RESPONSE_CODE + resultCode);
opResult.setResultCode(resultCode);
// create because it could be configured to implicitly create a non-existent index,
// which can lead to hard-to-debug behaviour with queries down the road.
OperationResult indexExistsResult = checkIndexExistence(indexName);
- if ((indexExistsResult.getResultCode() < 200) || (indexExistsResult.getResultCode() >= 300)) {
-
+ if (!isSuccess(indexExistsResult)) {
DocumentOperationResult opResult = new DocumentOperationResult();
- opResult.setResultCode(HttpStatus.NOT_FOUND.value());
- opResult.setResult("Document Index '" + indexName + "' does not exist.");
- opResult.setFailureCause("Document Index '" + indexName + "' does not exist.");
+ opResult.setResultCode(Status.NOT_FOUND.getStatusCode());
+ String resultMsg = "Document Index '" + indexName + "' does not exist.";
+ opResult.setResult(resultMsg);
+ opResult.setFailureCause(resultMsg);
return opResult;
}
}
DocumentOperationResult opResult = new DocumentOperationResult();
// Initialize operation result with a failure codes / fault string
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
opResult.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
// Grab the current time so we can use it to generate a metrics log.
MdcOverride override = getStartTime(new MdcOverride());
- String fullUrl = getFullUrl(
- "/" + indexName + "/" + DEFAULT_TYPE + "/" + document.getId() + "?version=" + document.getVersion(),
- false);
+ String fullUrl = getFullUrl("/" + indexName + "/" + DEFAULT_TYPE + "/" + document.getId() + QUERY_PARAM_VERSION
+ + document.getVersion(), false);
HttpURLConnection conn = initializeConnection(fullUrl);
try {
conn.setRequestMethod("PUT");
- conn.setRequestProperty("Content-Type", "application/json");
} catch (ProtocolException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to set HTTP request method to PUT.", e);
+ throw new DocumentStoreOperationException(MSG_HTTP_PUT_FAILED, e);
}
attachDocument(conn, document);
DocumentOperationResult opResult = new DocumentOperationResult();
// Initialize operation result with a failure codes / fault string
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
opResult.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
// Grab the current time so we can use it to generate a metrics log.
MdcOverride override = getStartTime(new MdcOverride());
- String fullUrl = getFullUrl(
- "/" + indexName + "/" + DEFAULT_TYPE + "/" + document.getId() + "?version=" + document.getVersion(),
- false);
+ String fullUrl = getFullUrl("/" + indexName + "/" + DEFAULT_TYPE + "/" + document.getId() + QUERY_PARAM_VERSION
+ + document.getVersion(), false);
HttpURLConnection conn = initializeConnection(fullUrl);
try {
DocumentOperationResult opResult = new DocumentOperationResult();
// Initialize operation result with a failure codes / fault string
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
opResult.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
// Grab the current time so we can use it to generate a metrics log.
if (document.getVersion() == null) {
fullUrl = getFullUrl("/" + indexName + "/" + DEFAULT_TYPE + "/" + document.getId(), false);
} else {
- fullUrl = getFullUrl(
- "/" + indexName + "/" + DEFAULT_TYPE + "/" + document.getId() + "?version=" + document.getVersion(),
- false);
+ fullUrl = getFullUrl("/" + indexName + "/" + DEFAULT_TYPE + "/" + document.getId() + QUERY_PARAM_VERSION
+ + document.getVersion(), false);
}
HttpURLConnection conn = initializeConnection(fullUrl);
SearchOperationResult opResult = new SearchOperationResult();
// Initialize operation result with a failure codes / fault string
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
opResult.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
String fullUrl = getFullUrl("/" + indexName + "/_search" + "?" + queryString, false);
}
// Initialize operation result with a failure codes / fault string
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
opResult.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
String fullUrl = getFullUrl("/" + indexName + "/_search", false);
try {
conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type", "application/json");
} catch (ProtocolException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to set HTTP request method to POST.", e);
+ throw new DocumentStoreOperationException(MSG_HTTP_POST_FAILED, e);
}
attachContent(conn, query);
}
// Initialize operation result with a failure codes / fault string
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
opResult.setResult(INTERNAL_SERVER_ERROR_ELASTIC_SEARCH_OPERATION_FAULT);
String fullUrl = getFullUrl("/" + indexName + "/_suggest", false);
try {
conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type", "application/json");
} catch (ProtocolException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to set HTTP request method to POST.", e);
+ throw new DocumentStoreOperationException(MSG_HTTP_POST_FAILED, e);
}
attachContent(conn, query);
try {
conn = (HttpURLConnection) url.openConnection();
+ conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);
conn.setDoOutput(true);
} catch (IOException e) {
shutdownConnection(conn);
private void handleResponse(HttpURLConnection conn, OperationResult opResult)
throws DocumentStoreOperationException {
- int resultCode = 200;
+ int resultCode;
try {
resultCode = conn.getResponseCode();
} catch (IOException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to get the response code from the connection.", e);
+ throw new DocumentStoreOperationException(FAILED_TO_GET_THE_RESPONSE_CODE_FROM_THE_CONNECTION, e);
}
- logger.debug("Response Code : " + resultCode);
+ logger.debug(MSG_RESPONSE_CODE + resultCode);
InputStream inputStream = null;
- if (!(resultCode >= 200 && resultCode <= 299)) { // 2xx response indicates success
+ if (!isSuccessCode(resultCode)) {
inputStream = conn.getErrorStream();
} else {
try {
throw new DocumentStoreOperationException("Failed getting the response body payload.", e);
}
- if (resultCode == HttpStatus.CONFLICT.value()) {
- opResult.setResultCode(HttpStatus.PRECONDITION_FAILED.value());
+ if (resultCode == Status.CONFLICT.getStatusCode()) {
+ opResult.setResultCode(Status.PRECONDITION_FAILED.getStatusCode());
} else {
opResult.setResultCode(resultCode);
}
String version = null;
try {
JSONObject root = (JSONObject) parser.parse(result);
- if (root.get("_version") != null) {
- version = root.get("_version").toString();
+ if (root.get(JSON_ATTR_VERSION) != null) {
+ version = root.get(JSON_ATTR_VERSION).toString();
}
} catch (ParseException e) {
// Not all responses from ElasticSearch include a version, so
}
private boolean isSuccess(OperationResult result) {
-
return isSuccessCode(result.getResultCode());
}
-
private boolean isSuccessCode(int statusCode) {
- return ((statusCode >= 200) && (statusCode < 300));
+ return Family.familyOf(statusCode).equals(Family.SUCCESSFUL);
}
-
@Override
public OperationResult performBulkOperations(BulkRequest[] requests) throws DocumentStoreOperationException {
if (logger.isDebugEnabled()) {
- String dbgString = "ESController: performBulkOperations - Operations: ";
+ StringBuilder dbgString = new StringBuilder("ESController: performBulkOperations - Operations: ");
for (BulkRequest request : requests) {
- dbgString += "[" + request.toString() + "] ";
+ dbgString.append("[").append(request).append("] ");
}
- logger.debug(dbgString);
+ logger.debug(dbgString.toString());
}
// Grab the current time so we can use it to generate a metrics log.
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
- conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
+ conn.setRequestProperty(CONTENT_TYPE, APPLICATION_FORM_URLENCODED);
conn.setRequestProperty("Connection", "Close");
} catch (IOException e) {
// In the success case we don't want the entire result string to be
// dumped into the metrics log, so concatenate it.
String resultStringForMetricsLog = result.getResult();
- if ((result.getResultCode() >= 200) && (result.getResultCode() < 300)) {
+ if (isSuccess(result)) {
resultStringForMetricsLog =
resultStringForMetricsLog.substring(0, Math.max(resultStringForMetricsLog.length(), 85)) + "...";
}
// correctly.
if (!ApiUtils.validateDocumentUri(request.getOperation().getMetaData().getUrl(), false)) {
fails.add(generateRejectionEntry(request.getOperationType(),
- "Invalid document URL: " + request.getOperation().getMetaData().getUrl(),
+ MSG_INVALID_DOCUMENT_URL + request.getOperation().getMetaData().getUrl(),
request.getIndex(), "", 400, request.getOperation().getMetaData().getUrl()));
return false;
}
if (!indexExists(ApiUtils.extractIndexFromUri(request.getOperation().getMetaData().getUrl()))) {
fails.add(generateRejectionEntry(request.getOperationType(),
- "Specified resource does not exist: " + request.getOperation().getMetaData().getUrl(),
- request.getIndex(), request.getId(), 404, request.getOperation().getMetaData().getUrl()));
+ MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
+ request.getId(), 404, request.getOperation().getMetaData().getUrl()));
return false;
}
// correctly.
if (!ApiUtils.validateDocumentUri(request.getOperation().getMetaData().getUrl(), true)) {
fails.add(generateRejectionEntry(request.getOperationType(),
- "Invalid document URL: " + request.getOperation().getMetaData().getUrl(),
+ MSG_INVALID_DOCUMENT_URL + request.getOperation().getMetaData().getUrl(),
request.getIndex(), "", 400, request.getOperation().getMetaData().getUrl()));
return false;
}
if (!indexExists(request.getIndex())) {
fails.add(generateRejectionEntry(request.getOperationType(),
- "Specified resource does not exist: " + request.getOperation().getMetaData().getUrl(),
- request.getIndex(), request.getId(), 404, request.getOperation().getMetaData().getUrl()));
+ MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
+ request.getId(), 404, request.getOperation().getMetaData().getUrl()));
return false;
}
if (!documentExists(request.getIndex(), request.getId())) {
fails.add(generateRejectionEntry(request.getOperationType(),
- "Specified resource does not exist: " + request.getOperation().getMetaData().getUrl(),
- request.getIndex(), request.getId(), 404, request.getOperation().getMetaData().getUrl()));
+ MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
+ request.getId(), 404, request.getOperation().getMetaData().getUrl()));
return false;
}
// correctly.
if (!ApiUtils.validateDocumentUri(request.getOperation().getMetaData().getUrl(), true)) {
fails.add(generateRejectionEntry(request.getOperationType(),
- "Invalid document URL: " + request.getOperation().getMetaData().getUrl(),
+ MSG_INVALID_DOCUMENT_URL + request.getOperation().getMetaData().getUrl(),
request.getIndex(), "", 400, request.getOperation().getMetaData().getUrl()));
return false;
}
if (!indexExists(request.getIndex())) {
fails.add(generateRejectionEntry(request.getOperationType(),
- "Specified resource does not exist: " + request.getOperation().getMetaData().getUrl(),
- request.getIndex(), request.getId(), 404, request.getOperation().getMetaData().getUrl()));
+ MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
+ request.getId(), 404, request.getOperation().getMetaData().getUrl()));
return false;
}
if (!documentExists(request.getIndex(), request.getId())) {
fails.add(generateRejectionEntry(request.getOperationType(),
- "Specified resource does not exist: " + request.getOperation().getMetaData().getUrl(),
- request.getIndex(), request.getId(), 404, request.getOperation().getMetaData().getUrl()));
+ MSG_RESOURCE_MISSING + request.getOperation().getMetaData().getUrl(), request.getIndex(),
+ request.getId(), 404, request.getOperation().getMetaData().getUrl()));
return false;
}
}
private boolean indexExists(String index) throws DocumentStoreOperationException {
-
- OperationResult indexExistsResult = checkIndexExistence(index);
-
- return ((indexExistsResult.getResultCode() >= 200) && (indexExistsResult.getResultCode() < 300));
+ return isSuccess(checkIndexExistence(index));
}
private boolean documentExists(String index, String id) throws DocumentStoreOperationException {
-
- OperationResult docExistsResult = checkDocumentExistence(index, id);
-
- return ((docExistsResult.getResultCode() >= 200) && (docExistsResult.getResultCode() < 300));
+ return isSuccess(checkDocumentExistence(index, id));
}
/**
// Initialize operation result with a failure codes / fault string
OperationResult opResult = new OperationResult();
- opResult.setResultCode(500);
+ opResult.setResultCode(Status.INTERNAL_SERVER_ERROR.getStatusCode());
// Grab the current time so we can use it to generate a metrics log.
MdcOverride override = getStartTime(new MdcOverride());
resultCode = conn.getResponseCode();
} catch (IOException e) {
shutdownConnection(conn);
- throw new DocumentStoreOperationException("Failed to get the response code from the connection.", e);
+ throw new DocumentStoreOperationException(FAILED_TO_GET_THE_RESPONSE_CODE_FROM_THE_CONNECTION, e);
}
- logger.debug("Response Code : " + resultCode);
+ logger.debug(MSG_RESPONSE_CODE + resultCode);
opResult.setResultCode(resultCode);
JSONObject root;
try {
root = (JSONObject) parser.parse(result.getResult());
-
- if (result.getResultCode() >= 200 && result.getResultCode() <= 299) {
+ if (isSuccess(result)) {
// Success response object
Document doc = new Document();
doc.setEtag(result.getResultVersion());
} else {
// Error response object
- JSONObject error = (JSONObject) root.get("error");
+ JSONObject error = (JSONObject) root.get(JSON_ATTR_ERROR);
if (error != null) {
- result.setError(new ErrorResult(error.get("type").toString(), error.get("reason").toString()));
+ result.setError(
+ new ErrorResult(error.get("type").toString(), error.get(JSON_ATTR_REASON).toString()));
}
}
} catch (Exception e) {
- throw new DocumentStoreOperationException("Failed to parse Elastic Search response." + result.getResult());
+ throw new DocumentStoreOperationException(FAILED_TO_PARSE_ELASTIC_SEARCH_RESPONSE + result.getResult());
}
-
-
}
private String buildDocumentResponseUrl(String index, String id) {
try {
root = (JSONObject) parser.parse(result.getResult());
- if (result.getResultCode() >= 200 && result.getResultCode() <= 299) {
+ if (isSuccess(result)) {
JSONObject hits = (JSONObject) root.get("hits");
JSONArray hitArray = (JSONArray) hits.get("hits");
SearchHits searchHits = new SearchHits();
SearchHit searchHit = new SearchHit();
searchHit.setScore((hit.get("_score") != null) ? hit.get("_score").toString() : "");
Document doc = new Document();
- if (hit.get("_version") != null) {
- doc.setEtag((hit.get("_version") != null) ? hit.get("_version").toString() : "");
+ if (hit.get(JSON_ATTR_VERSION) != null) {
+ doc.setEtag((hit.get(JSON_ATTR_VERSION) != null) ? hit.get(JSON_ATTR_VERSION).toString() : "");
}
doc.setUrl(
// success
} else {
- JSONObject error = (JSONObject) root.get("error");
+ JSONObject error = (JSONObject) root.get(JSON_ATTR_ERROR);
if (error != null) {
- result.setError(new ErrorResult(error.get("type").toString(), error.get("reason").toString()));
+ result.setError(
+ new ErrorResult(error.get("type").toString(), error.get(JSON_ATTR_REASON).toString()));
}
}
} catch (Exception e) {
- throw new DocumentStoreOperationException("Failed to parse Elastic Search response." + result.getResult());
+ throw new DocumentStoreOperationException(FAILED_TO_PARSE_ELASTIC_SEARCH_RESPONSE + result.getResult());
}
}
JSONObject root;
try {
root = (JSONObject) parser.parse(result.getResult());
- if (result.getResultCode() >= 200 && result.getResultCode() <= 299) {
+ if (isSuccess(result)) {
JSONArray hitArray = (JSONArray) root.get("suggest-vnf");
JSONObject hitdata = (JSONObject) hitArray.get(0);
JSONArray optionsArray = (JSONArray) hitdata.get("options");
suggestHit.setScore((hit.get("score") != null) ? hit.get("score").toString() : "");
suggestHit.setText((hit.get("text") != null) ? hit.get("text").toString() : "");
Document doc = new Document();
- if (hit.get("_version") != null) {
- doc.setEtag((hit.get("_version") != null) ? hit.get("_version").toString() : "");
+ if (hit.get(JSON_ATTR_VERSION) != null) {
+ doc.setEtag((hit.get(JSON_ATTR_VERSION) != null) ? hit.get(JSON_ATTR_VERSION).toString() : "");
}
doc.setUrl(
buildDocumentResponseUrl(index, (hit.get("_id") != null) ? hit.get("_id").toString() : ""));
// success
} else {
- JSONObject error = (JSONObject) root.get("error");
+ JSONObject error = (JSONObject) root.get(JSON_ATTR_ERROR);
if (error != null) {
- result.setError(new ErrorResult(error.get("type").toString(), error.get("reason").toString()));
+ result.setError(
+ new ErrorResult(error.get("type").toString(), error.get(JSON_ATTR_REASON).toString()));
}
}
} catch (Exception e) {
- throw new DocumentStoreOperationException("Failed to parse Elastic Search response." + result.getResult());
+ throw new DocumentStoreOperationException(FAILED_TO_PARSE_ELASTIC_SEARCH_RESPONSE + result.getResult());
}
}
}