diff --git a/core/src/main/java/org/elasticsearch/ElasticsearchException.java b/core/src/main/java/org/elasticsearch/ElasticsearchException.java
index 225352c476e..9f3dc6f8b79 100644
--- a/core/src/main/java/org/elasticsearch/ElasticsearchException.java
+++ b/core/src/main/java/org/elasticsearch/ElasticsearchException.java
@@ -24,9 +24,10 @@ import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
+import org.elasticsearch.common.io.stream.NotSerializableExceptionWrapper;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
-import org.elasticsearch.common.io.stream.NotSerializableExceptionWrapper;
+import org.elasticsearch.common.logging.support.LoggerMessageFormat;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.HasRestHeaders;
@@ -48,21 +49,29 @@ public class ElasticsearchException extends RuntimeException implements ToXConte
/**
* Construct a ElasticsearchException
with the specified detail message.
*
+ * The message can be parameterized using {@code {}} as placeholders for the given
+ * arguments
+ *
* @param msg the detail message
+ * @param args the arguments for the message
*/
- public ElasticsearchException(String msg) {
- super(msg);
+ public ElasticsearchException(String msg, Object... args) {
+ super(LoggerMessageFormat.format(msg, args));
}
/**
* Construct a ElasticsearchException
with the specified detail message
* and nested exception.
*
+ * The message can be parameterized using {@code {}} as placeholders for the given
+ * arguments
+ *
* @param msg the detail message
* @param cause the nested exception
+ * @param args the arguments for the message
*/
- public ElasticsearchException(String msg, Throwable cause) {
- super(msg, cause);
+ public ElasticsearchException(String msg, Throwable cause, Object... args) {
+ super(LoggerMessageFormat.format(msg, args), cause);
}
public ElasticsearchException(StreamInput in) throws IOException {
diff --git a/core/src/main/java/org/elasticsearch/ElasticsearchParseException.java b/core/src/main/java/org/elasticsearch/ElasticsearchParseException.java
index 626d1162c04..1358ef54d9d 100644
--- a/core/src/main/java/org/elasticsearch/ElasticsearchParseException.java
+++ b/core/src/main/java/org/elasticsearch/ElasticsearchParseException.java
@@ -29,12 +29,12 @@ import java.io.IOException;
*/
public class ElasticsearchParseException extends ElasticsearchException {
- public ElasticsearchParseException(String msg) {
- super(msg);
+ public ElasticsearchParseException(String msg, Object... args) {
+ super(msg, args);
}
- public ElasticsearchParseException(String msg, Throwable cause) {
- super(msg, cause);
+ public ElasticsearchParseException(String msg, Throwable cause, Object... args) {
+ super(msg, cause, args);
}
public ElasticsearchParseException(StreamInput in) throws IOException {
diff --git a/core/src/main/java/org/elasticsearch/ElasticsearchTimeoutException.java b/core/src/main/java/org/elasticsearch/ElasticsearchTimeoutException.java
index 7860046e6ab..3cc4e7a477a 100644
--- a/core/src/main/java/org/elasticsearch/ElasticsearchTimeoutException.java
+++ b/core/src/main/java/org/elasticsearch/ElasticsearchTimeoutException.java
@@ -33,11 +33,11 @@ public class ElasticsearchTimeoutException extends ElasticsearchException {
super(in);
}
- public ElasticsearchTimeoutException(String message) {
+ public ElasticsearchTimeoutException(String message, Object... args) {
super(message);
}
- public ElasticsearchTimeoutException(String message, Throwable cause) {
- super(message, cause);
+ public ElasticsearchTimeoutException(String message, Throwable cause, Object... args) {
+ super(message, cause, args);
}
}
\ No newline at end of file
diff --git a/core/src/main/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequest.java b/core/src/main/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequest.java
index 4db5f4e927d..e5f21253ed2 100644
--- a/core/src/main/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequest.java
+++ b/core/src/main/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequest.java
@@ -20,7 +20,6 @@
package org.elasticsearch.action.admin.cluster.reroute;
import org.elasticsearch.ElasticsearchParseException;
-import org.elasticsearch.Version;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.support.master.AcknowledgedRequest;
import org.elasticsearch.cluster.routing.allocation.command.AllocationCommand;
@@ -102,13 +101,13 @@ public class ClusterRerouteRequest extends AcknowledgedRequest
try {
customs.put(name, proto.fromMap((Map) entry.getValue()));
} catch (IOException e) {
- throw new ElasticsearchParseException("failed to parse custom metadata for [" + name + "]");
+ throw new ElasticsearchParseException("failed to parse custom metadata for [{}]", name);
}
}
}
diff --git a/core/src/main/java/org/elasticsearch/action/admin/indices/template/put/PutIndexTemplateRequest.java b/core/src/main/java/org/elasticsearch/action/admin/indices/template/put/PutIndexTemplateRequest.java
index 5477c681849..21cf01f0567 100644
--- a/core/src/main/java/org/elasticsearch/action/admin/indices/template/put/PutIndexTemplateRequest.java
+++ b/core/src/main/java/org/elasticsearch/action/admin/indices/template/put/PutIndexTemplateRequest.java
@@ -296,7 +296,7 @@ public class PutIndexTemplateRequest extends MasterNodeRequest) entry.getValue()));
} catch (IOException e) {
- throw new ElasticsearchParseException("failed to parse custom metadata for [" + name + "]");
+ throw new ElasticsearchParseException("failed to parse custom metadata for [{}]", name);
}
}
}
diff --git a/core/src/main/java/org/elasticsearch/action/get/MultiGetRequest.java b/core/src/main/java/org/elasticsearch/action/get/MultiGetRequest.java
index 67c6141273c..ae9b360fdbe 100644
--- a/core/src/main/java/org/elasticsearch/action/get/MultiGetRequest.java
+++ b/core/src/main/java/org/elasticsearch/action/get/MultiGetRequest.java
@@ -418,7 +418,7 @@ public class MultiGetRequest extends ActionRequest implements I
} else if (token == XContentParser.Token.VALUE_STRING) {
fetchSourceContext = new FetchSourceContext(new String[]{parser.text()});
} else {
- throw new ElasticsearchParseException("illegal type for _source: [" + token + "]");
+ throw new ElasticsearchParseException("illegal type for _source: [{}]", token);
}
}
} else if (token == XContentParser.Token.START_ARRAY) {
@@ -447,7 +447,7 @@ public class MultiGetRequest extends ActionRequest implements I
} else if ("excludes".equals(currentFieldName) || "exclude".equals(currentFieldName)) {
currentList = excludes != null ? excludes : (excludes = new ArrayList<>(2));
} else {
- throw new ElasticsearchParseException("Source definition may not contain " + parser.text());
+ throw new ElasticsearchParseException("source definition may not contain [{}]", parser.text());
}
} else if (token == XContentParser.Token.START_ARRAY) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
diff --git a/core/src/main/java/org/elasticsearch/action/percolate/MultiPercolateRequest.java b/core/src/main/java/org/elasticsearch/action/percolate/MultiPercolateRequest.java
index d5df34368d2..2778e03d8bc 100644
--- a/core/src/main/java/org/elasticsearch/action/percolate/MultiPercolateRequest.java
+++ b/core/src/main/java/org/elasticsearch/action/percolate/MultiPercolateRequest.java
@@ -136,7 +136,7 @@ public class MultiPercolateRequest extends ActionRequest
percolateRequest.onlyCount(true);
parsePercolateAction(parser, percolateRequest, allowExplicitIndex);
} else {
- throw new ElasticsearchParseException(percolateAction + " isn't a supported percolate operation");
+ throw new ElasticsearchParseException("[{}] isn't a supported percolate operation", percolateAction);
}
}
}
diff --git a/core/src/main/java/org/elasticsearch/action/termvectors/MultiTermVectorsRequest.java b/core/src/main/java/org/elasticsearch/action/termvectors/MultiTermVectorsRequest.java
index 3cde0f41ce5..b56864acb5d 100644
--- a/core/src/main/java/org/elasticsearch/action/termvectors/MultiTermVectorsRequest.java
+++ b/core/src/main/java/org/elasticsearch/action/termvectors/MultiTermVectorsRequest.java
@@ -111,18 +111,16 @@ public class MultiTermVectorsRequest extends ActionRequest i
fields.add(parser.text());
}
} else {
- throw new ElasticsearchParseException(
- "The parameter fields must be given as an array! Use syntax : \"fields\" : [\"field1\", \"field2\",...]");
+ throw new ElasticsearchParseException("failed to parse term vectors request. field [fields] must be an array");
}
} else if (currentFieldName.equals("offsets")) {
termVectorsRequest.offsets(parser.booleanValue());
@@ -613,12 +612,12 @@ public class TermVectorsRequest extends SingleShardRequest i
termVectorsRequest.type = parser.text();
} else if ("_id".equals(currentFieldName)) {
if (termVectorsRequest.doc != null) {
- throw new ElasticsearchParseException("Either \"id\" or \"doc\" can be specified, but not both!");
+ throw new ElasticsearchParseException("failed to parse term vectors request. either [id] or [doc] can be specified, but not both!");
}
termVectorsRequest.id = parser.text();
} else if ("doc".equals(currentFieldName)) {
if (termVectorsRequest.id != null) {
- throw new ElasticsearchParseException("Either \"id\" or \"doc\" can be specified, but not both!");
+ throw new ElasticsearchParseException("failed to parse term vectors request. either [id] or [doc] can be specified, but not both!");
}
termVectorsRequest.doc(jsonBuilder().copyCurrentStructure(parser));
} else if ("_routing".equals(currentFieldName) || "routing".equals(currentFieldName)) {
@@ -628,8 +627,7 @@ public class TermVectorsRequest extends SingleShardRequest i
} else if ("_version_type".equals(currentFieldName) || "_versionType".equals(currentFieldName) || "version_type".equals(currentFieldName) || "versionType".equals(currentFieldName)) {
termVectorsRequest.versionType = VersionType.fromString(parser.text());
} else {
- throw new ElasticsearchParseException("The parameter " + currentFieldName
- + " is not valid for term vector request!");
+ throw new ElasticsearchParseException("failed to parse term vectors request. unknown field [{}]", currentFieldName);
}
}
}
@@ -645,8 +643,7 @@ public class TermVectorsRequest extends SingleShardRequest i
if (e.getValue() instanceof String) {
mapStrStr.put(e.getKey(), (String) e.getValue());
} else {
- throw new ElasticsearchException(
- "The analyzer at " + e.getKey() + " should be of type String, but got a " + e.getValue().getClass() + "!");
+ throw new ElasticsearchException("expecting the analyzer at [{}] to be a String, but found [{}] instead", e.getKey(), e.getValue().getClass());
}
}
return mapStrStr;
@@ -675,8 +672,7 @@ public class TermVectorsRequest extends SingleShardRequest i
} else if (currentFieldName.equals("max_word_length")) {
settings.maxWordLength = parser.intValue();
} else {
- throw new ElasticsearchParseException("The parameter " + currentFieldName
- + " is not valid for filter parameter for term vector request!");
+ throw new ElasticsearchParseException("failed to parse term vectors request. the field [{}] is not valid for filter parameter for term vector request", currentFieldName);
}
}
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/RepositoriesMetaData.java b/core/src/main/java/org/elasticsearch/cluster/metadata/RepositoriesMetaData.java
index f4d81028448..48e40d1a54f 100644
--- a/core/src/main/java/org/elasticsearch/cluster/metadata/RepositoriesMetaData.java
+++ b/core/src/main/java/org/elasticsearch/cluster/metadata/RepositoriesMetaData.java
@@ -139,7 +139,7 @@ public class RepositoriesMetaData extends AbstractDiffable implements Me
if (token == XContentParser.Token.FIELD_NAME) {
String name = parser.currentName();
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
- throw new ElasticsearchParseException("failed to parse repository [" + name + "], expected object");
+ throw new ElasticsearchParseException("failed to parse repository [{}], expected object", name);
}
String type = null;
Settings settings = Settings.EMPTY;
@@ -148,23 +148,23 @@ public class RepositoriesMetaData extends AbstractDiffable implements Me
String currentFieldName = parser.currentName();
if ("type".equals(currentFieldName)) {
if (parser.nextToken() != XContentParser.Token.VALUE_STRING) {
- throw new ElasticsearchParseException("failed to parse repository [" + name + "], unknown type");
+ throw new ElasticsearchParseException("failed to parse repository [{}], unknown type", name);
}
type = parser.text();
} else if ("settings".equals(currentFieldName)) {
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
- throw new ElasticsearchParseException("failed to parse repository [" + name + "], incompatible params");
+ throw new ElasticsearchParseException("failed to parse repository [{}], incompatible params", name);
}
settings = Settings.settingsBuilder().put(SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered())).build();
} else {
- throw new ElasticsearchParseException("failed to parse repository [" + name + "], unknown field [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("failed to parse repository [{}], unknown field [{}]", name, currentFieldName);
}
} else {
- throw new ElasticsearchParseException("failed to parse repository [" + name + "]");
+ throw new ElasticsearchParseException("failed to parse repository [{}]", name);
}
}
if (type == null) {
- throw new ElasticsearchParseException("failed to parse repository [" + name + "], missing repository type");
+ throw new ElasticsearchParseException("failed to parse repository [{}], missing repository type", name);
}
repository.add(new RepositoryMetaData(name, type, settings));
} else {
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateAllocationCommand.java
index 0bc3782651e..582ddb6cf76 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocateAllocationCommand.java
@@ -81,20 +81,20 @@ public class AllocateAllocationCommand implements AllocationCommand {
} else if ("allow_primary".equals(currentFieldName) || "allowPrimary".equals(currentFieldName)) {
allowPrimary = parser.booleanValue();
} else {
- throw new ElasticsearchParseException("[allocate] command does not support field [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
}
} else {
- throw new ElasticsearchParseException("[allocate] command does not support complex json tokens [" + token + "]");
+ throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
}
}
if (index == null) {
- throw new ElasticsearchParseException("[allocate] command missing the index parameter");
+ throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
}
if (shardId == -1) {
- throw new ElasticsearchParseException("[allocate] command missing the shard parameter");
+ throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
}
if (nodeId == null) {
- throw new ElasticsearchParseException("[allocate] command missing the node parameter");
+ throw new ElasticsearchParseException("[{}] command missing the node parameter", NAME);
}
return new AllocateAllocationCommand(new ShardId(index, shardId), nodeId, allowPrimary);
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocationCommands.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocationCommands.java
index db41a759d35..33a44188407 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocationCommands.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/AllocationCommands.java
@@ -173,10 +173,10 @@ public class AllocationCommands {
}
if (token == XContentParser.Token.FIELD_NAME) {
if (!parser.currentName().equals("commands")) {
- throw new ElasticsearchParseException("expected field name to be named `commands`, got " + parser.currentName());
+ throw new ElasticsearchParseException("expected field name to be named [commands], got [{}] instead", parser.currentName());
}
if (!parser.currentName().equals("commands")) {
- throw new ElasticsearchParseException("expected field name to be named `commands`, got " + parser.currentName());
+ throw new ElasticsearchParseException("expected field name to be named [commands], got [{}] instead", parser.currentName());
}
token = parser.nextToken();
if (token != XContentParser.Token.START_ARRAY) {
@@ -185,7 +185,7 @@ public class AllocationCommands {
} else if (token == XContentParser.Token.START_ARRAY) {
// ok...
} else {
- throw new ElasticsearchParseException("expected either field name commands, or start array, got " + token);
+ throw new ElasticsearchParseException("expected either field name [commands], or start array, got [{}] instead", token);
}
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
if (token == XContentParser.Token.START_OBJECT) {
@@ -196,10 +196,10 @@ public class AllocationCommands {
commands.add(AllocationCommands.lookupFactorySafe(commandName).fromXContent(parser));
// move to the end object one
if (parser.nextToken() != XContentParser.Token.END_OBJECT) {
- throw new ElasticsearchParseException("allocation command is malformed, done parsing a command, but didn't get END_OBJECT, got " + token);
+ throw new ElasticsearchParseException("allocation command is malformed, done parsing a command, but didn't get END_OBJECT, got [{}] instead", token);
}
} else {
- throw new ElasticsearchParseException("allocation command is malformed, got token " + token);
+ throw new ElasticsearchParseException("allocation command is malformed, got [{}] instead", token);
}
}
return commands;
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java
index 3e68aaf70bc..766559862a7 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/CancelAllocationCommand.java
@@ -83,20 +83,20 @@ public class CancelAllocationCommand implements AllocationCommand {
} else if ("allow_primary".equals(currentFieldName) || "allowPrimary".equals(currentFieldName)) {
allowPrimary = parser.booleanValue();
} else {
- throw new ElasticsearchParseException("[cancel] command does not support field [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
}
} else {
- throw new ElasticsearchParseException("[cancel] command does not support complex json tokens [" + token + "]");
+ throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
}
}
if (index == null) {
- throw new ElasticsearchParseException("[cancel] command missing the index parameter");
+ throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
}
if (shardId == -1) {
- throw new ElasticsearchParseException("[cancel] command missing the shard parameter");
+ throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
}
if (nodeId == null) {
- throw new ElasticsearchParseException("[cancel] command missing the node parameter");
+ throw new ElasticsearchParseException("[{}] command missing the node parameter", NAME);
}
return new CancelAllocationCommand(new ShardId(index, shardId), nodeId, allowPrimary);
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java
index 79a92388b69..86b2d4d7cb0 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/command/MoveAllocationCommand.java
@@ -81,23 +81,23 @@ public class MoveAllocationCommand implements AllocationCommand {
} else if ("to_node".equals(currentFieldName) || "toNode".equals(currentFieldName)) {
toNode = parser.text();
} else {
- throw new ElasticsearchParseException("[move] command does not support field [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
}
} else {
- throw new ElasticsearchParseException("[move] command does not support complex json tokens [" + token + "]");
+ throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
}
}
if (index == null) {
- throw new ElasticsearchParseException("[move] command missing the index parameter");
+ throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
}
if (shardId == -1) {
- throw new ElasticsearchParseException("[move] command missing the shard parameter");
+ throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
}
if (fromNode == null) {
- throw new ElasticsearchParseException("[move] command missing the from_node parameter");
+ throw new ElasticsearchParseException("[{}] command missing the from_node parameter", NAME);
}
if (toNode == null) {
- throw new ElasticsearchParseException("[move] command missing the to_node parameter");
+ throw new ElasticsearchParseException("[{}] command missing the to_node parameter", NAME);
}
return new MoveAllocationCommand(new ShardId(index, shardId), fromNode, toNode);
}
diff --git a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDecider.java b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDecider.java
index 011b80ec924..54d2d9422c9 100644
--- a/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDecider.java
+++ b/core/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDecider.java
@@ -102,7 +102,7 @@ public class DiskThresholdDecider extends AllocationDecider {
}
if (newLowWatermark != null) {
if (!validWatermarkSetting(newLowWatermark, CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK)) {
- throw new ElasticsearchParseException("Unable to parse low watermark: [" + newLowWatermark + "]");
+ throw new ElasticsearchParseException("unable to parse low watermark [{}]", newLowWatermark);
}
logger.info("updating [{}] to [{}]", CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, newLowWatermark);
DiskThresholdDecider.this.freeDiskThresholdLow = 100.0 - thresholdPercentageFromWatermark(newLowWatermark);
@@ -110,7 +110,7 @@ public class DiskThresholdDecider extends AllocationDecider {
}
if (newHighWatermark != null) {
if (!validWatermarkSetting(newHighWatermark, CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK)) {
- throw new ElasticsearchParseException("Unable to parse high watermark: [" + newHighWatermark + "]");
+ throw new ElasticsearchParseException("unable to parse high watermark [{}]", newHighWatermark);
}
logger.info("updating [{}] to [{}]", CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, newHighWatermark);
DiskThresholdDecider.this.freeDiskThresholdHigh = 100.0 - thresholdPercentageFromWatermark(newHighWatermark);
@@ -200,10 +200,10 @@ public class DiskThresholdDecider extends AllocationDecider {
String highWatermark = settings.get(CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, "90%");
if (!validWatermarkSetting(lowWatermark, CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK)) {
- throw new ElasticsearchParseException("Unable to parse low watermark: [" + lowWatermark + "]");
+ throw new ElasticsearchParseException("unable to parse low watermark [{}]", lowWatermark);
}
if (!validWatermarkSetting(highWatermark, CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK)) {
- throw new ElasticsearchParseException("Unable to parse high watermark: [" + highWatermark + "]");
+ throw new ElasticsearchParseException("unable to parse high watermark [{}]", highWatermark);
}
// Watermark is expressed in terms of used data, but we need "free" data watermark
this.freeDiskThresholdLow = 100.0 - thresholdPercentageFromWatermark(lowWatermark);
@@ -309,7 +309,7 @@ public class DiskThresholdDecider extends AllocationDecider {
double usedDiskPercentage = usage.getUsedDiskAsPercentage();
long freeBytes = usage.getFreeBytes();
if (logger.isTraceEnabled()) {
- logger.trace("Node [{}] has {}% used disk", node.nodeId(), usedDiskPercentage);
+ logger.trace("node [{}] has {}% used disk", node.nodeId(), usedDiskPercentage);
}
// a flag for whether the primary shard has been previously allocated
@@ -320,7 +320,7 @@ public class DiskThresholdDecider extends AllocationDecider {
// If the shard is a replica or has a primary that has already been allocated before, check the low threshold
if (!shardRouting.primary() || (shardRouting.primary() && primaryHasBeenAllocated)) {
if (logger.isDebugEnabled()) {
- logger.debug("Less than the required {} free bytes threshold ({} bytes free) on node {}, preventing allocation",
+ logger.debug("less than the required {} free bytes threshold ({} bytes free) on node {}, preventing allocation",
freeBytesThresholdLow, freeBytes, node.nodeId());
}
return allocation.decision(Decision.NO, NAME, "less than required [%s] free on node, free: [%s]",
@@ -329,7 +329,7 @@ public class DiskThresholdDecider extends AllocationDecider {
// Allow the shard to be allocated because it is primary that
// has never been allocated if it's under the high watermark
if (logger.isDebugEnabled()) {
- logger.debug("Less than the required {} free bytes threshold ({} bytes free) on node {}, " +
+ logger.debug("less than the required {} free bytes threshold ({} bytes free) on node {}, " +
"but allowing allocation because primary has never been allocated",
freeBytesThresholdLow, freeBytes, node.nodeId());
}
@@ -338,7 +338,7 @@ public class DiskThresholdDecider extends AllocationDecider {
// Even though the primary has never been allocated, the node is
// above the high watermark, so don't allow allocating the shard
if (logger.isDebugEnabled()) {
- logger.debug("Less than the required {} free bytes threshold ({} bytes free) on node {}, " +
+ logger.debug("less than the required {} free bytes threshold ({} bytes free) on node {}, " +
"preventing allocation even though primary has never been allocated",
freeBytesThresholdHigh, freeBytes, node.nodeId());
}
@@ -352,7 +352,7 @@ public class DiskThresholdDecider extends AllocationDecider {
// If the shard is a replica or has a primary that has already been allocated before, check the low threshold
if (!shardRouting.primary() || (shardRouting.primary() && primaryHasBeenAllocated)) {
if (logger.isDebugEnabled()) {
- logger.debug("More than the allowed {} used disk threshold ({} used) on node [{}], preventing allocation",
+ logger.debug("more than the allowed {} used disk threshold ({} used) on node [{}], preventing allocation",
Strings.format1Decimals(usedDiskThresholdLow, "%"),
Strings.format1Decimals(usedDiskPercentage, "%"), node.nodeId());
}
@@ -362,7 +362,7 @@ public class DiskThresholdDecider extends AllocationDecider {
// Allow the shard to be allocated because it is primary that
// has never been allocated if it's under the high watermark
if (logger.isDebugEnabled()) {
- logger.debug("More than the allowed {} used disk threshold ({} used) on node [{}], " +
+ logger.debug("more than the allowed {} used disk threshold ({} used) on node [{}], " +
"but allowing allocation because primary has never been allocated",
Strings.format1Decimals(usedDiskThresholdLow, "%"),
Strings.format1Decimals(usedDiskPercentage, "%"), node.nodeId());
@@ -372,7 +372,7 @@ public class DiskThresholdDecider extends AllocationDecider {
// Even though the primary has never been allocated, the node is
// above the high watermark, so don't allow allocating the shard
if (logger.isDebugEnabled()) {
- logger.debug("Less than the required {} free bytes threshold ({} bytes free) on node {}, " +
+ logger.debug("less than the required {} free bytes threshold ({} bytes free) on node {}, " +
"preventing allocation even though primary has never been allocated",
Strings.format1Decimals(freeDiskThresholdHigh, "%"),
Strings.format1Decimals(freeDiskPercentage, "%"), node.nodeId());
@@ -389,13 +389,13 @@ public class DiskThresholdDecider extends AllocationDecider {
double freeSpaceAfterShard = freeDiskPercentageAfterShardAssigned(usage, shardSize);
long freeBytesAfterShard = freeBytes - shardSize;
if (freeBytesAfterShard < freeBytesThresholdHigh.bytes()) {
- logger.warn("After allocating, node [{}] would have less than the required {} free bytes threshold ({} bytes free), preventing allocation",
+ logger.warn("after allocating, node [{}] would have less than the required {} free bytes threshold ({} bytes free), preventing allocation",
node.nodeId(), freeBytesThresholdHigh, freeBytesAfterShard);
return allocation.decision(Decision.NO, NAME, "after allocation less than required [%s] free on node, free: [%s]",
freeBytesThresholdLow, new ByteSizeValue(freeBytesAfterShard));
}
if (freeSpaceAfterShard < freeDiskThresholdHigh) {
- logger.warn("After allocating, node [{}] would have more than the allowed {} free disk threshold ({} free), preventing allocation",
+ logger.warn("after allocating, node [{}] would have more than the allowed {} free disk threshold ({} free), preventing allocation",
node.nodeId(), Strings.format1Decimals(freeDiskThresholdHigh, "%"), Strings.format1Decimals(freeSpaceAfterShard, "%"));
return allocation.decision(Decision.NO, NAME, "after allocation more than allowed [%s%%] used disk on node, free: [%s%%]",
usedDiskThresholdLow, freeSpaceAfterShard);
@@ -415,11 +415,11 @@ public class DiskThresholdDecider extends AllocationDecider {
double freeDiskPercentage = usage.getFreeDiskAsPercentage();
long freeBytes = usage.getFreeBytes();
if (logger.isDebugEnabled()) {
- logger.debug("Node [{}] has {}% free disk ({} bytes)", node.nodeId(), freeDiskPercentage, freeBytes);
+ logger.debug("node [{}] has {}% free disk ({} bytes)", node.nodeId(), freeDiskPercentage, freeBytes);
}
if (freeBytes < freeBytesThresholdHigh.bytes()) {
if (logger.isDebugEnabled()) {
- logger.debug("Less than the required {} free bytes threshold ({} bytes free) on node {}, shard cannot remain",
+ logger.debug("less than the required {} free bytes threshold ({} bytes free) on node {}, shard cannot remain",
freeBytesThresholdHigh, freeBytes, node.nodeId());
}
return allocation.decision(Decision.NO, NAME, "after allocation less than required [%s] free on node, free: [%s]",
@@ -427,7 +427,7 @@ public class DiskThresholdDecider extends AllocationDecider {
}
if (freeDiskPercentage < freeDiskThresholdHigh) {
if (logger.isDebugEnabled()) {
- logger.debug("Less than the required {}% free disk threshold ({}% free) on node {}, shard cannot remain",
+ logger.debug("less than the required {}% free disk threshold ({}% free) on node {}, shard cannot remain",
freeDiskThresholdHigh, freeDiskPercentage, node.nodeId());
}
return allocation.decision(Decision.NO, NAME, "after allocation less than required [%s%%] free disk on node, free: [%s%%]",
@@ -446,7 +446,7 @@ public class DiskThresholdDecider extends AllocationDecider {
// use the average usage for all nodes as the usage for this node
usage = averageUsage(node, usages);
if (logger.isDebugEnabled()) {
- logger.debug("Unable to determine disk usage for {}, defaulting to average across nodes [{} total] [{} free] [{}% free]",
+ logger.debug("unable to determine disk usage for {}, defaulting to average across nodes [{} total] [{} free] [{}% free]",
node.nodeId(), usage.getTotalBytes(), usage.getFreeBytes(), usage.getFreeDiskAsPercentage());
}
}
@@ -552,7 +552,7 @@ public class DiskThresholdDecider extends AllocationDecider {
// Allow allocation regardless if only a single node is available
if (allocation.nodes().size() <= 1) {
if (logger.isTraceEnabled()) {
- logger.trace("Only a single node is present, allowing allocation");
+ logger.trace("only a single node is present, allowing allocation");
}
return allocation.decision(Decision.YES, NAME, "only a single node is present");
}
@@ -561,7 +561,7 @@ public class DiskThresholdDecider extends AllocationDecider {
final ClusterInfo clusterInfo = allocation.clusterInfo();
if (clusterInfo == null) {
if (logger.isTraceEnabled()) {
- logger.trace("Cluster info unavailable for disk threshold decider, allowing allocation.");
+ logger.trace("cluster info unavailable for disk threshold decider, allowing allocation.");
}
return allocation.decision(Decision.YES, NAME, "cluster info unavailable");
}
@@ -570,7 +570,7 @@ public class DiskThresholdDecider extends AllocationDecider {
// Fail open if there are no disk usages available
if (usages.isEmpty()) {
if (logger.isTraceEnabled()) {
- logger.trace("Unable to determine disk usages for disk-aware allocation, allowing allocation");
+ logger.trace("unable to determine disk usages for disk-aware allocation, allowing allocation");
}
return allocation.decision(Decision.YES, NAME, "disk usages unavailable");
}
diff --git a/core/src/main/java/org/elasticsearch/common/geo/GeoUtils.java b/core/src/main/java/org/elasticsearch/common/geo/GeoUtils.java
index 77ff66db688..5c146598325 100644
--- a/core/src/main/java/org/elasticsearch/common/geo/GeoUtils.java
+++ b/core/src/main/java/org/elasticsearch/common/geo/GeoUtils.java
@@ -369,10 +369,10 @@ public class GeoUtils {
throw new ElasticsearchParseException("geohash must be a string");
}
} else {
- throw new ElasticsearchParseException("field must be either '" + LATITUDE + "', '" + LONGITUDE + "' or '" + GEOHASH + "'");
+ throw new ElasticsearchParseException("field must be either [{}], [{}] or [{}]", LATITUDE, LONGITUDE, GEOHASH);
}
} else {
- throw new ElasticsearchParseException("Token '"+parser.currentToken()+"' not allowed");
+ throw new ElasticsearchParseException("token [{}] not allowed", parser.currentToken());
}
}
@@ -383,9 +383,9 @@ public class GeoUtils {
return point.resetFromGeoHash(geohash);
}
} else if (Double.isNaN(lat)) {
- throw new ElasticsearchParseException("field [" + LATITUDE + "] missing");
+ throw new ElasticsearchParseException("field [{}] missing", LATITUDE);
} else if (Double.isNaN(lon)) {
- throw new ElasticsearchParseException("field [" + LONGITUDE + "] missing");
+ throw new ElasticsearchParseException("field [{}] missing", LONGITUDE);
} else {
return point.reset(lat, lon);
}
@@ -403,7 +403,7 @@ public class GeoUtils {
throw new ElasticsearchParseException("only two values allowed");
}
} else {
- throw new ElasticsearchParseException("Numeric value expected");
+ throw new ElasticsearchParseException("numeric value expected");
}
}
return point.reset(lat, lon);
diff --git a/core/src/main/java/org/elasticsearch/common/geo/builders/ShapeBuilder.java b/core/src/main/java/org/elasticsearch/common/geo/builders/ShapeBuilder.java
index 3e733dbd619..4cea9c21b78 100644
--- a/core/src/main/java/org/elasticsearch/common/geo/builders/ShapeBuilder.java
+++ b/core/src/main/java/org/elasticsearch/common/geo/builders/ShapeBuilder.java
@@ -721,7 +721,7 @@ public abstract class ShapeBuilder implements ToXContent {
if (parser.currentToken() == XContentParser.Token.VALUE_NULL) {
return null;
} else if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
- throw new ElasticsearchParseException("Shape must be an object consisting of type and coordinates");
+ throw new ElasticsearchParseException("shape must be an object consisting of type and coordinates");
}
GeoShapeType shapeType = null;
@@ -758,14 +758,13 @@ public abstract class ShapeBuilder implements ToXContent {
}
if (shapeType == null) {
- throw new ElasticsearchParseException("Shape type not included");
+ throw new ElasticsearchParseException("shape type not included");
} else if (node == null && GeoShapeType.GEOMETRYCOLLECTION != shapeType) {
- throw new ElasticsearchParseException("Coordinates not included");
+ throw new ElasticsearchParseException("coordinates not included");
} else if (geometryCollections == null && GeoShapeType.GEOMETRYCOLLECTION == shapeType) {
throw new ElasticsearchParseException("geometries not included");
} else if (radius != null && GeoShapeType.CIRCLE != shapeType) {
- throw new ElasticsearchParseException("Field [" + CircleBuilder.FIELD_RADIUS + "] is supported for [" + CircleBuilder.TYPE
- + "] only");
+ throw new ElasticsearchParseException("field [{}] is supported for [{}] only", CircleBuilder.FIELD_RADIUS, CircleBuilder.TYPE);
}
switch (shapeType) {
@@ -779,14 +778,13 @@ public abstract class ShapeBuilder implements ToXContent {
case ENVELOPE: return parseEnvelope(node, requestedOrientation);
case GEOMETRYCOLLECTION: return geometryCollections;
default:
- throw new ElasticsearchParseException("Shape type [" + shapeType + "] not included");
+ throw new ElasticsearchParseException("shape type [{}] not included", shapeType);
}
}
protected static void validatePointNode(CoordinateNode node) {
if (node.isEmpty()) {
- throw new ElasticsearchParseException("Invalid number of points (0) provided when expecting a single coordinate "
- + "([lat, lng])");
+ throw new ElasticsearchParseException("invalid number of points (0) provided when expecting a single coordinate ([lat, lng])");
} else if (node.coordinate == null) {
if (node.children.isEmpty() == false) {
throw new ElasticsearchParseException("multipoint data provided when single point data expected.");
@@ -806,8 +804,8 @@ public abstract class ShapeBuilder implements ToXContent {
protected static EnvelopeBuilder parseEnvelope(CoordinateNode coordinates, Orientation orientation) {
// validate the coordinate array for envelope type
if (coordinates.children.size() != 2) {
- throw new ElasticsearchParseException("Invalid number of points (" + coordinates.children.size() + ") provided for " +
- "geo_shape ('envelope') when expecting an array of 2 coordinates");
+ throw new ElasticsearchParseException("invalid number of points [{}] provided for " +
+ "geo_shape [{}] when expecting an array of 2 coordinates", coordinates.children.size(), GeoShapeType.ENVELOPE.shapename);
}
// verify coordinate bounds, correct if necessary
Coordinate uL = coordinates.children.get(0).coordinate;
@@ -826,7 +824,7 @@ public abstract class ShapeBuilder implements ToXContent {
throw new ElasticsearchParseException("single coordinate found when expecting an array of " +
"coordinates. change type to point or change data to an array of >0 coordinates");
}
- throw new ElasticsearchParseException("No data provided for multipoint object when expecting " +
+ throw new ElasticsearchParseException("no data provided for multipoint object when expecting " +
">0 points (e.g., [[lat, lng]] or [[lat, lng], ...])");
} else {
for (CoordinateNode point : coordinates.children) {
@@ -852,8 +850,7 @@ public abstract class ShapeBuilder implements ToXContent {
* LineStringBuilder should throw a graceful exception if < 2 coordinates/points are provided
*/
if (coordinates.children.size() < 2) {
- throw new ElasticsearchParseException("Invalid number of points in LineString (found " +
- coordinates.children.size() + " - must be >= 2)");
+ throw new ElasticsearchParseException("invalid number of points in LineString (found [{}] - must be >= 2)", coordinates.children.size());
}
LineStringBuilder line = newLineString();
@@ -884,19 +881,17 @@ public abstract class ShapeBuilder implements ToXContent {
" No coordinate array provided" : " Found a single coordinate when expecting a coordinate array";
throw new ElasticsearchParseException(error);
} else if (coordinates.children.size() < 4) {
- throw new ElasticsearchParseException("Invalid number of points in LinearRing (found " +
- coordinates.children.size() + " - must be >= 4)");
+ throw new ElasticsearchParseException("invalid number of points in LinearRing (found [{}] - must be >= 4)", coordinates.children.size());
} else if (!coordinates.children.get(0).coordinate.equals(
coordinates.children.get(coordinates.children.size() - 1).coordinate)) {
- throw new ElasticsearchParseException("Invalid LinearRing found (coordinates are not closed)");
+ throw new ElasticsearchParseException("invalid LinearRing found (coordinates are not closed)");
}
return parseLineString(coordinates);
}
protected static PolygonBuilder parsePolygon(CoordinateNode coordinates, Orientation orientation) {
if (coordinates.children == null || coordinates.children.isEmpty()) {
- throw new ElasticsearchParseException("Invalid LinearRing provided for type polygon. Linear ring must be an array of " +
- "coordinates");
+ throw new ElasticsearchParseException("invalid LinearRing provided for type polygon. Linear ring must be an array of coordinates");
}
LineStringBuilder shell = parseLinearRing(coordinates.children.get(0));
@@ -924,7 +919,7 @@ public abstract class ShapeBuilder implements ToXContent {
*/
protected static GeometryCollectionBuilder parseGeometries(XContentParser parser, Orientation orientation) throws IOException {
if (parser.currentToken() != XContentParser.Token.START_ARRAY) {
- throw new ElasticsearchParseException("Geometries must be an array of geojson objects");
+ throw new ElasticsearchParseException("geometries must be an array of geojson objects");
}
XContentParser.Token token = parser.nextToken();
diff --git a/core/src/main/java/org/elasticsearch/common/joda/DateMathParser.java b/core/src/main/java/org/elasticsearch/common/joda/DateMathParser.java
index 16be9cea211..7246db21344 100644
--- a/core/src/main/java/org/elasticsearch/common/joda/DateMathParser.java
+++ b/core/src/main/java/org/elasticsearch/common/joda/DateMathParser.java
@@ -58,7 +58,7 @@ public class DateMathParser {
try {
time = now.call();
} catch (Exception e) {
- throw new ElasticsearchParseException("Could not read the current timestamp", e);
+ throw new ElasticsearchParseException("could not read the current timestamp", e);
}
mathString = text.substring("now".length());
} else {
@@ -95,12 +95,12 @@ public class DateMathParser {
} else if (c == '-') {
sign = -1;
} else {
- throw new ElasticsearchParseException("operator not supported for date math [" + mathString + "]");
+ throw new ElasticsearchParseException("operator not supported for date math [{}]", mathString);
}
}
if (i >= mathString.length()) {
- throw new ElasticsearchParseException("truncated date math [" + mathString + "]");
+ throw new ElasticsearchParseException("truncated date math [{}]", mathString);
}
final int num;
@@ -112,13 +112,13 @@ public class DateMathParser {
i++;
}
if (i >= mathString.length()) {
- throw new ElasticsearchParseException("truncated date math [" + mathString + "]");
+ throw new ElasticsearchParseException("truncated date math [{}]", mathString);
}
num = Integer.parseInt(mathString.substring(numFrom, i));
}
if (round) {
if (num != 1) {
- throw new ElasticsearchParseException("rounding `/` can only be used on single unit types [" + mathString + "]");
+ throw new ElasticsearchParseException("rounding `/` can only be used on single unit types [{}]", mathString);
}
}
char unit = mathString.charAt(i++);
@@ -175,7 +175,7 @@ public class DateMathParser {
}
break;
default:
- throw new ElasticsearchParseException("unit [" + unit + "] not supported for date math [" + mathString + "]");
+ throw new ElasticsearchParseException("unit [{}] not supported for date math [{}]", unit, mathString);
}
if (propertyToRound != null) {
if (roundUp) {
@@ -200,7 +200,7 @@ public class DateMathParser {
return parser.parseMillis(value);
} catch (IllegalArgumentException e) {
- throw new ElasticsearchParseException("failed to parse date field [" + value + "] with format [" + dateTimeFormatter.format() + "]", e);
+ throw new ElasticsearchParseException("failed to parse date field [{}] with format [{}]", e, value, dateTimeFormatter.format());
}
}
diff --git a/core/src/main/java/org/elasticsearch/common/settings/loader/XContentSettingsLoader.java b/core/src/main/java/org/elasticsearch/common/settings/loader/XContentSettingsLoader.java
index ddc5e70f805..ffbe1669d47 100644
--- a/core/src/main/java/org/elasticsearch/common/settings/loader/XContentSettingsLoader.java
+++ b/core/src/main/java/org/elasticsearch/common/settings/loader/XContentSettingsLoader.java
@@ -62,7 +62,7 @@ public abstract class XContentSettingsLoader implements SettingsLoader {
return settings;
}
if (token != XContentParser.Token.START_OBJECT) {
- throw new ElasticsearchParseException("malformed, expected settings to start with 'object', instead was [" + token + "]");
+ throw new ElasticsearchParseException("malformed, expected settings to start with 'object', instead was [{}]", token);
}
serializeObject(settings, sb, path, jp, null);
return settings;
diff --git a/core/src/main/java/org/elasticsearch/common/unit/ByteSizeValue.java b/core/src/main/java/org/elasticsearch/common/unit/ByteSizeValue.java
index 167a4849a53..d036ad5b9a8 100644
--- a/core/src/main/java/org/elasticsearch/common/unit/ByteSizeValue.java
+++ b/core/src/main/java/org/elasticsearch/common/unit/ByteSizeValue.java
@@ -214,14 +214,14 @@ public class ByteSizeValue implements Streamable {
} else {
// Missing units:
if (Settings.getSettingsRequireUnits()) {
- throw new ElasticsearchParseException("Failed to parse setting [" + settingName + "] with value [" + sValue + "] as a size in bytes: unit is missing or unrecognized") ;
+ throw new ElasticsearchParseException("failed to parse setting [{}] with value [{}] as a size in bytes: unit is missing or unrecognized", settingName, sValue);
} else {
// Leniency default to bytes:
bytes = Long.parseLong(sValue);
}
}
} catch (NumberFormatException e) {
- throw new ElasticsearchParseException("Failed to parse [" + sValue + "]", e);
+ throw new ElasticsearchParseException("failed to parse [{}]", e, sValue);
}
return new ByteSizeValue(bytes, ByteSizeUnit.BYTES);
}
diff --git a/core/src/main/java/org/elasticsearch/common/unit/MemorySizeValue.java b/core/src/main/java/org/elasticsearch/common/unit/MemorySizeValue.java
index daf0ffd209a..686ad522446 100644
--- a/core/src/main/java/org/elasticsearch/common/unit/MemorySizeValue.java
+++ b/core/src/main/java/org/elasticsearch/common/unit/MemorySizeValue.java
@@ -40,11 +40,11 @@ public enum MemorySizeValue {
try {
final double percent = Double.parseDouble(percentAsString);
if (percent < 0 || percent > 100) {
- throw new ElasticsearchParseException("Percentage should be in [0-100], got " + percentAsString);
+ throw new ElasticsearchParseException("percentage should be in [0-100], got [{}]", percentAsString);
}
return new ByteSizeValue((long) ((percent / 100) * JvmInfo.jvmInfo().getMem().getHeapMax().bytes()), ByteSizeUnit.BYTES);
} catch (NumberFormatException e) {
- throw new ElasticsearchParseException("Failed to parse [" + percentAsString + "] as a double", e);
+ throw new ElasticsearchParseException("failed to parse [{}] as a double", e, percentAsString);
}
} else {
return parseBytesSizeValue(sValue, settingName);
diff --git a/core/src/main/java/org/elasticsearch/common/unit/RatioValue.java b/core/src/main/java/org/elasticsearch/common/unit/RatioValue.java
index f4dc3a9b4f8..3893101a366 100644
--- a/core/src/main/java/org/elasticsearch/common/unit/RatioValue.java
+++ b/core/src/main/java/org/elasticsearch/common/unit/RatioValue.java
@@ -55,21 +55,21 @@ public class RatioValue {
try {
final double percent = Double.parseDouble(percentAsString);
if (percent < 0 || percent > 100) {
- throw new ElasticsearchParseException("Percentage should be in [0-100], got " + percentAsString);
+ throw new ElasticsearchParseException("Percentage should be in [0-100], got [{}]", percentAsString);
}
return new RatioValue(Math.abs(percent));
} catch (NumberFormatException e) {
- throw new ElasticsearchParseException("Failed to parse [" + percentAsString + "] as a double", e);
+ throw new ElasticsearchParseException("Failed to parse [{}] as a double", e, percentAsString);
}
} else {
try {
double ratio = Double.parseDouble(sValue);
if (ratio < 0 || ratio > 1.0) {
- throw new ElasticsearchParseException("Ratio should be in [0-1.0], got " + ratio);
+ throw new ElasticsearchParseException("Ratio should be in [0-1.0], got [{}]", ratio);
}
return new RatioValue(100.0 * Math.abs(ratio));
} catch (NumberFormatException e) {
- throw new ElasticsearchParseException("Invalid ratio or percentage: [" + sValue + "]");
+ throw new ElasticsearchParseException("Invalid ratio or percentage [{}]", sValue);
}
}
diff --git a/core/src/main/java/org/elasticsearch/common/unit/SizeValue.java b/core/src/main/java/org/elasticsearch/common/unit/SizeValue.java
index 44d7155a2d2..586f305df00 100644
--- a/core/src/main/java/org/elasticsearch/common/unit/SizeValue.java
+++ b/core/src/main/java/org/elasticsearch/common/unit/SizeValue.java
@@ -190,7 +190,7 @@ public class SizeValue implements Streamable {
singles = Long.parseLong(sValue);
}
} catch (NumberFormatException e) {
- throw new ElasticsearchParseException("Failed to parse [" + sValue + "]", e);
+ throw new ElasticsearchParseException("failed to parse [{}]", e, sValue);
}
return new SizeValue(singles, SizeUnit.SINGLE);
}
diff --git a/core/src/main/java/org/elasticsearch/common/unit/TimeValue.java b/core/src/main/java/org/elasticsearch/common/unit/TimeValue.java
index 14b7d32338f..5f9eb953a42 100644
--- a/core/src/main/java/org/elasticsearch/common/unit/TimeValue.java
+++ b/core/src/main/java/org/elasticsearch/common/unit/TimeValue.java
@@ -259,7 +259,7 @@ public class TimeValue implements Streamable {
} else {
if (Settings.getSettingsRequireUnits()) {
// Missing units:
- throw new ElasticsearchParseException("Failed to parse setting [" + settingName + "] with value [" + sValue + "] as a time value: unit is missing or unrecognized");
+ throw new ElasticsearchParseException("Failed to parse setting [{}] with value [{}] as a time value: unit is missing or unrecognized", settingName, sValue);
} else {
// Leniency default to msec for bwc:
millis = Long.parseLong(sValue);
@@ -267,7 +267,7 @@ public class TimeValue implements Streamable {
}
return new TimeValue(millis, TimeUnit.MILLISECONDS);
} catch (NumberFormatException e) {
- throw new ElasticsearchParseException("Failed to parse [" + sValue + "]", e);
+ throw new ElasticsearchParseException("Failed to parse [{}]", e, sValue);
}
}
diff --git a/core/src/main/java/org/elasticsearch/index/IndexException.java b/core/src/main/java/org/elasticsearch/index/IndexException.java
index ef94c1c55d6..c309ebcb7f1 100644
--- a/core/src/main/java/org/elasticsearch/index/IndexException.java
+++ b/core/src/main/java/org/elasticsearch/index/IndexException.java
@@ -33,11 +33,11 @@ public class IndexException extends ElasticsearchException {
private final Index index;
- public IndexException(Index index, String msg) {
- this(index, msg, null);
+ public IndexException(Index index, String msg, Object... args) {
+ this(index, msg, null, args);
}
- public IndexException(Index index, String msg, Throwable cause) {
+ public IndexException(Index index, String msg, Throwable cause, Object... args) {
super(msg, cause);
this.index = index;
}
diff --git a/core/src/main/java/org/elasticsearch/index/mapper/core/CompletionFieldMapper.java b/core/src/main/java/org/elasticsearch/index/mapper/core/CompletionFieldMapper.java
index 97030ea5f46..1a97fccc7ae 100644
--- a/core/src/main/java/org/elasticsearch/index/mapper/core/CompletionFieldMapper.java
+++ b/core/src/main/java/org/elasticsearch/index/mapper/core/CompletionFieldMapper.java
@@ -355,7 +355,7 @@ public class CompletionFieldMapper extends AbstractFieldMapper {
String name = parser.text();
ContextMapping mapping = fieldType().getContextMapping().get(name);
if (mapping == null) {
- throw new ElasticsearchParseException("context [" + name + "] is not defined");
+ throw new ElasticsearchParseException("context [{}] is not defined", name);
} else {
token = parser.nextToken();
configs.put(name, mapping.parseContext(context, parser));
diff --git a/core/src/main/java/org/elasticsearch/index/mapper/core/TypeParsers.java b/core/src/main/java/org/elasticsearch/index/mapper/core/TypeParsers.java
index 1c3d5f9b0bd..6c026446172 100644
--- a/core/src/main/java/org/elasticsearch/index/mapper/core/TypeParsers.java
+++ b/core/src/main/java/org/elasticsearch/index/mapper/core/TypeParsers.java
@@ -87,12 +87,12 @@ public class TypeParsers {
firstType = type;
}
} else {
- throw new MapperParsingException("No type specified for property [" + propName + "]");
+ throw new MapperParsingException("no type specified for property [" + propName + "]");
}
Mapper.TypeParser typeParser = parserContext.typeParser(type);
if (typeParser == null) {
- throw new MapperParsingException("No handler for type [" + type + "] declared on field [" + fieldName + "]");
+ throw new MapperParsingException("no handler for type [" + type + "] declared on field [" + fieldName + "]");
}
if (propName.equals(name)) {
mainFieldBuilder = (AbstractFieldMapper.Builder) typeParser.parse(propName, propNode, parserContext);
@@ -256,14 +256,14 @@ public class TypeParsers {
NamedAnalyzer analyzer = parserContext.analysisService().analyzer(propNode.toString());
if (analyzer == null) {
- throw new MapperParsingException("Analyzer [" + propNode.toString() + "] not found for field [" + name + "]");
+ throw new MapperParsingException("analyzer [" + propNode.toString() + "] not found for field [" + name + "]");
}
indexAnalyzer = analyzer;
iterator.remove();
} else if (propName.equals("search_analyzer")) {
NamedAnalyzer analyzer = parserContext.analysisService().analyzer(propNode.toString());
if (analyzer == null) {
- throw new MapperParsingException("Analyzer [" + propNode.toString() + "] not found for field [" + name + "]");
+ throw new MapperParsingException("analyzer [" + propNode.toString() + "] not found for field [" + name + "]");
}
searchAnalyzer = analyzer;
iterator.remove();
@@ -313,14 +313,14 @@ public class TypeParsers {
} else if (propNode instanceof Map) {
multiFieldsPropNodes = (Map) propNode;
} else {
- throw new MapperParsingException("Expected map for property [fields] on field [" + propNode + "] or " +
+ throw new MapperParsingException("expected map for property [fields] on field [" + propNode + "] or " +
"[" + propName + "] but got a " + propNode.getClass());
}
for (Map.Entry multiFieldEntry : multiFieldsPropNodes.entrySet()) {
String multiFieldName = multiFieldEntry.getKey();
if (!(multiFieldEntry.getValue() instanceof Map)) {
- throw new MapperParsingException("Illegal field [" + multiFieldName + "], only fields can be specified inside fields");
+ throw new MapperParsingException("illegal field [" + multiFieldName + "], only fields can be specified inside fields");
}
@SuppressWarnings("unchecked")
Map multiFieldNodes = (Map) multiFieldEntry.getValue();
@@ -330,7 +330,7 @@ public class TypeParsers {
if (typeNode != null) {
type = typeNode.toString();
} else {
- throw new MapperParsingException("No type specified for property [" + multiFieldName + "]");
+ throw new MapperParsingException("no type specified for property [" + multiFieldName + "]");
}
if (type.equals(ObjectMapper.CONTENT_TYPE) || type.equals(ObjectMapper.NESTED_CONTENT_TYPE)) {
throw new MapperParsingException("Type [" + type + "] cannot be used in multi field");
@@ -338,7 +338,7 @@ public class TypeParsers {
Mapper.TypeParser typeParser = parserContext.typeParser(type);
if (typeParser == null) {
- throw new MapperParsingException("No handler for type [" + type + "] declared on field [" + multiFieldName + "]");
+ throw new MapperParsingException("no handler for type [" + type + "] declared on field [" + multiFieldName + "]");
}
builder.addMultiField(typeParser.parse(multiFieldName, multiFieldNodes, parserContext));
multiFieldNodes.remove("type");
@@ -360,7 +360,7 @@ public class TypeParsers {
} else if (INDEX_OPTIONS_DOCS.equalsIgnoreCase(value)) {
return IndexOptions.DOCS;
} else {
- throw new ElasticsearchParseException("Failed to parse index option [" + value + "]");
+ throw new ElasticsearchParseException("failed to parse index option [{}]", value);
}
}
@@ -389,7 +389,7 @@ public class TypeParsers {
builder.storeTermVectorOffsets(true);
builder.storeTermVectorPayloads(true);
} else {
- throw new MapperParsingException("Wrong value for termVector [" + termVector + "] for field [" + fieldName + "]");
+ throw new MapperParsingException("wrong value for termVector [" + termVector + "] for field [" + fieldName + "]");
}
}
@@ -404,7 +404,7 @@ public class TypeParsers {
builder.index(true);
builder.tokenized(true);
} else {
- throw new MapperParsingException("Wrong value for index [" + index + "] for field [" + fieldName + "]");
+ throw new MapperParsingException("wrong value for index [" + index + "] for field [" + fieldName + "]");
}
}
@@ -425,7 +425,7 @@ public class TypeParsers {
} else if ("full".equals(path)) {
return ContentPath.Type.FULL;
} else {
- throw new MapperParsingException("Wrong value for pathType [" + path + "] for object [" + name + "]");
+ throw new MapperParsingException("wrong value for pathType [" + path + "] for object [" + name + "]");
}
}
diff --git a/core/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryParser.java b/core/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryParser.java
index e05d35118ed..439b0e90544 100644
--- a/core/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryParser.java
+++ b/core/src/main/java/org/elasticsearch/index/query/GeoBoundingBoxQueryParser.java
@@ -39,6 +39,8 @@ import java.io.IOException;
*/
public class GeoBoundingBoxQueryParser implements QueryParser {
+ public static final String NAME = "geo_bbox";
+
public static final String TOP = "top";
public static final String LEFT = "left";
public static final String RIGHT = "right";
@@ -54,7 +56,6 @@ public class GeoBoundingBoxQueryParser implements QueryParser {
public static final String BOTTOMLEFT = "bottomLeft";
public static final String BOTTOMRIGHT = "bottomRight";
- public static final String NAME = "geo_bbox";
public static final String FIELD = "field";
@Inject
@@ -126,11 +127,11 @@ public class GeoBoundingBoxQueryParser implements QueryParser {
bottom = sparse.getLat();
left = sparse.getLon();
} else {
- throw new ElasticsearchParseException("Unexpected field [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("failed to parse [{}] query. unexpected field [{}]", NAME, currentFieldName);
}
}
} else {
- throw new ElasticsearchParseException("fieldname expected but [" + token + "] found");
+ throw new ElasticsearchParseException("failed to parse [{}] query. field name expected but [{}] found", NAME, token);
}
}
} else if (token.isValue()) {
@@ -141,7 +142,7 @@ public class GeoBoundingBoxQueryParser implements QueryParser {
} else if ("type".equals(currentFieldName)) {
type = parser.text();
} else {
- throw new QueryParsingException(parseContext, "[geo_bbox] query does not support [" + currentFieldName + "]");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. unexpected field [{}]", NAME, currentFieldName);
}
}
}
@@ -163,10 +164,10 @@ public class GeoBoundingBoxQueryParser implements QueryParser {
MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
if (fieldType == null) {
- throw new QueryParsingException(parseContext, "failed to find geo_point field [" + fieldName + "]");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. could not find [{}] field [{}]", NAME, GeoPointFieldMapper.CONTENT_TYPE, fieldName);
}
if (!(fieldType instanceof GeoPointFieldMapper.GeoPointFieldType)) {
- throw new QueryParsingException(parseContext, "field [" + fieldName + "] is not a geo_point field");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. field [{}] is expected to be of type [{}], but is of [{}] type instead", NAME, fieldName, GeoPointFieldMapper.CONTENT_TYPE, fieldType.names().shortName());
}
GeoPointFieldMapper.GeoPointFieldType geoFieldType = ((GeoPointFieldMapper.GeoPointFieldType) fieldType);
@@ -177,8 +178,7 @@ public class GeoBoundingBoxQueryParser implements QueryParser {
IndexGeoPointFieldData indexFieldData = parseContext.getForField(fieldType);
filter = new InMemoryGeoBoundingBoxQuery(topLeft, bottomRight, indexFieldData);
} else {
- throw new QueryParsingException(parseContext, "geo bounding box type [" + type
- + "] not supported, either 'indexed' or 'memory' are allowed");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. geo bounding box type [{}] is not supported. either [indexed] or [memory] are allowed", NAME, type);
}
if (queryName != null) {
diff --git a/core/src/main/java/org/elasticsearch/index/query/GeohashCellQuery.java b/core/src/main/java/org/elasticsearch/index/query/GeohashCellQuery.java
index b0f95eabd12..814aca43738 100644
--- a/core/src/main/java/org/elasticsearch/index/query/GeohashCellQuery.java
+++ b/core/src/main/java/org/elasticsearch/index/query/GeohashCellQuery.java
@@ -193,7 +193,7 @@ public class GeohashCellQuery {
XContentParser.Token token;
if ((token = parser.currentToken()) != Token.START_OBJECT) {
- throw new ElasticsearchParseException(NAME + " must be an object");
+ throw new ElasticsearchParseException("failed to parse [{}] query. expected an object but found [{}] instead", NAME, token);
}
while ((token = parser.nextToken()) != Token.END_OBJECT) {
@@ -229,27 +229,26 @@ public class GeohashCellQuery {
}
}
} else {
- throw new ElasticsearchParseException("unexpected token [" + token + "]");
+ throw new ElasticsearchParseException("failed to parse [{}] query. unexpected token [{}]", NAME, token);
}
}
if (geohash == null) {
- throw new QueryParsingException(parseContext, "no geohash value provided to geohash_cell filter");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing geohash value", NAME);
}
MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
if (fieldType == null) {
- throw new QueryParsingException(parseContext, "failed to find geo_point field [" + fieldName + "]");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing [{}] field [{}]", NAME, GeoPointFieldMapper.CONTENT_TYPE, fieldName);
}
if (!(fieldType instanceof GeoPointFieldMapper.GeoPointFieldType)) {
- throw new QueryParsingException(parseContext, "field [" + fieldName + "] is not a geo_point field");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. field [{}] is not a geo_point field", NAME, fieldName);
}
GeoPointFieldMapper.GeoPointFieldType geoFieldType = ((GeoPointFieldMapper.GeoPointFieldType) fieldType);
if (!geoFieldType.isGeohashPrefixEnabled()) {
- throw new QueryParsingException(parseContext, "can't execute geohash_cell on field [" + fieldName
- + "], geohash_prefix is not enabled");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. [geohash_prefix] is not enabled for field [{}]", NAME, fieldName);
}
if(levels > 0) {
diff --git a/core/src/main/java/org/elasticsearch/index/query/MultiMatchQueryBuilder.java b/core/src/main/java/org/elasticsearch/index/query/MultiMatchQueryBuilder.java
index 8c242854458..56909415d5f 100644
--- a/core/src/main/java/org/elasticsearch/index/query/MultiMatchQueryBuilder.java
+++ b/core/src/main/java/org/elasticsearch/index/query/MultiMatchQueryBuilder.java
@@ -147,7 +147,7 @@ public class MultiMatchQueryBuilder extends QueryBuilder implements BoostableQue
}
}
if (type == null) {
- throw new ElasticsearchParseException("No type found for value: " + value);
+ throw new ElasticsearchParseException("failed to parse [{}] query type [{}]. unknown type.", MultiMatchQueryParser.NAME, value);
}
return type;
}
diff --git a/core/src/main/java/org/elasticsearch/index/query/QueryParsingException.java b/core/src/main/java/org/elasticsearch/index/query/QueryParsingException.java
index b13a403f759..f904b740948 100644
--- a/core/src/main/java/org/elasticsearch/index/query/QueryParsingException.java
+++ b/core/src/main/java/org/elasticsearch/index/query/QueryParsingException.java
@@ -39,12 +39,12 @@ public class QueryParsingException extends IndexException {
private final int lineNumber;
private final int columnNumber;
- public QueryParsingException(QueryParseContext parseContext, String msg) {
- this(parseContext, msg, null);
+ public QueryParsingException(QueryParseContext parseContext, String msg, Object... args) {
+ this(parseContext, msg, null, args);
}
- public QueryParsingException(QueryParseContext parseContext, String msg, Throwable cause) {
- super(parseContext.index(), msg, cause);
+ public QueryParsingException(QueryParseContext parseContext, String msg, Throwable cause, Object... args) {
+ super(parseContext.index(), msg, cause, args);
int lineNumber = UNKNOWN_POSITION;
int columnNumber = UNKNOWN_POSITION;
XContentParser parser = parseContext.parser();
diff --git a/core/src/main/java/org/elasticsearch/index/query/functionscore/DecayFunctionParser.java b/core/src/main/java/org/elasticsearch/index/query/functionscore/DecayFunctionParser.java
index 1a59e9aecb6..0350efeeda3 100644
--- a/core/src/main/java/org/elasticsearch/index/query/functionscore/DecayFunctionParser.java
+++ b/core/src/main/java/org/elasticsearch/index/query/functionscore/DecayFunctionParser.java
@@ -135,11 +135,11 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
} else if (MULTI_VALUE_MODE.match(currentFieldName)) {
multiValueMode = parser.text();
} else {
- throw new ElasticsearchParseException("Malformed score function score parameters.");
+ throw new ElasticsearchParseException("malformed score function score parameters.");
}
}
if (fieldName == null) {
- throw new ElasticsearchParseException("Malformed score function score parameters.");
+ throw new ElasticsearchParseException("malformed score function score parameters.");
}
XContentParser variableParser = XContentFactory.xContent(variableContent.string()).createParser(variableContent.string());
scoreFunction = parseVariable(fieldName, variableParser, parseContext, MultiValueMode.fromString(multiValueMode.toUpperCase(Locale.ROOT)));
@@ -153,7 +153,7 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
// the doc later
MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
if (fieldType == null) {
- throw new QueryParsingException(parseContext, "Unknown field [" + fieldName + "]");
+ throw new QueryParsingException(parseContext, "unknown field [{}]", fieldName);
}
// dates and time need special handling
@@ -165,8 +165,7 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
} else if (fieldType instanceof NumberFieldMapper.NumberFieldType) {
return parseNumberVariable(fieldName, parser, parseContext, (NumberFieldMapper.NumberFieldType) fieldType, mode);
} else {
- throw new QueryParsingException(parseContext, "Field " + fieldName + " is of type " + fieldType
- + ", but only numeric types are supported.");
+ throw new QueryParsingException(parseContext, "field [{}] is of type [{}], but only numeric types are supported.", fieldName, fieldType);
}
}
@@ -194,12 +193,11 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
} else if (parameterName.equals(DecayFunctionBuilder.OFFSET)) {
offset = parser.doubleValue();
} else {
- throw new ElasticsearchParseException("Parameter " + parameterName + " not supported!");
+ throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
}
}
if (!scaleFound || !refFound) {
- throw new ElasticsearchParseException("Both " + DecayFunctionBuilder.SCALE + " and " + DecayFunctionBuilder.ORIGIN
- + " must be set for numeric fields.");
+ throw new ElasticsearchParseException("both [{}] and [{}] must be set for numeric fields.", DecayFunctionBuilder.SCALE, DecayFunctionBuilder.ORIGIN);
}
IndexNumericFieldData numericFieldData = parseContext.getForField(fieldType);
return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode);
@@ -225,11 +223,11 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
} else if (parameterName.equals(DecayFunctionBuilder.OFFSET)) {
offsetString = parser.text();
} else {
- throw new ElasticsearchParseException("Parameter " + parameterName + " not supported!");
+ throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
}
}
if (origin == null || scaleString == null) {
- throw new ElasticsearchParseException(DecayFunctionBuilder.ORIGIN + " and " + DecayFunctionBuilder.SCALE + " must be set for geo fields.");
+ throw new ElasticsearchParseException("[{}] and [{}] must be set for geo fields.", DecayFunctionBuilder.ORIGIN, DecayFunctionBuilder.SCALE);
}
double scale = DistanceUnit.DEFAULT.parse(scaleString, DistanceUnit.DEFAULT);
double offset = DistanceUnit.DEFAULT.parse(offsetString, DistanceUnit.DEFAULT);
@@ -258,7 +256,7 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
} else if (parameterName.equals(DecayFunctionBuilder.OFFSET)) {
offsetString = parser.text();
} else {
- throw new ElasticsearchParseException("Parameter " + parameterName + " not supported!");
+ throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
}
}
long origin = SearchContext.current().nowInMillis();
@@ -267,7 +265,7 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
}
if (scaleString == null) {
- throw new ElasticsearchParseException(DecayFunctionBuilder.SCALE + " must be set for date fields.");
+ throw new ElasticsearchParseException("[{}] must be set for date fields.", DecayFunctionBuilder.SCALE);
}
TimeValue val = TimeValue.parseTimeValue(scaleString, TimeValue.timeValueHours(24), getClass().getSimpleName() + ".scale");
double scale = val.getMillis();
diff --git a/core/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryParser.java b/core/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryParser.java
index a747d98a439..d25deb82825 100644
--- a/core/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryParser.java
+++ b/core/src/main/java/org/elasticsearch/index/query/functionscore/FunctionScoreQueryParser.java
@@ -52,14 +52,16 @@ import java.util.Arrays;
public class FunctionScoreQueryParser implements QueryParser {
public static final String NAME = "function_score";
- ScoreFunctionParserMapper functionParserMapper;
+
// For better readability of error message
- static final String MISPLACED_FUNCTION_MESSAGE_PREFIX = "You can either define \"functions\":[...] or a single function, not both. ";
- static final String MISPLACED_BOOST_FUNCTION_MESSAGE_SUFFIX = " Did you mean \"boost\" instead?";
+ static final String MISPLACED_FUNCTION_MESSAGE_PREFIX = "you can either define [functions] array or a single function, not both. ";
+ static final String MISPLACED_BOOST_FUNCTION_MESSAGE_SUFFIX = " did you mean [boost] instead?";
public static final ParseField WEIGHT_FIELD = new ParseField("weight");
private static final ParseField FILTER_FIELD = new ParseField("filter").withAllDeprecated("query");
+ ScoreFunctionParserMapper functionParserMapper;
+
@Inject
public FunctionScoreQueryParser(ScoreFunctionParserMapper functionParserMapper) {
this.functionParserMapper = functionParserMapper;
@@ -121,7 +123,7 @@ public class FunctionScoreQueryParser implements QueryParser {
minScore = parser.floatValue();
} else if ("functions".equals(currentFieldName)) {
if (singleFunctionFound) {
- String errorString = "Found \"" + singleFunctionName + "\" already, now encountering \"functions\": [...].";
+ String errorString = "already found [" + singleFunctionName + "], now encountering [functions].";
handleMisplacedFunctionsDeclaration(errorString, singleFunctionName);
}
currentFieldName = parseFiltersAndFunctions(parseContext, parser, filterFunctions, currentFieldName);
@@ -138,12 +140,11 @@ public class FunctionScoreQueryParser implements QueryParser {
scoreFunction = functionParserMapper.get(parseContext, currentFieldName).parse(parseContext, parser);
}
if (functionArrayFound) {
- String errorString = "Found \"functions\": [...] already, now encountering \"" + currentFieldName + "\".";
+ String errorString = "already found [functions] array, now encountering [" + currentFieldName + "].";
handleMisplacedFunctionsDeclaration(errorString, currentFieldName);
}
if (filterFunctions.size() > 0) {
- String errorString = "Found function " + singleFunctionName + " already, now encountering \"" + currentFieldName + "\". Use functions[{...},...] if you want to define several functions.";
- throw new ElasticsearchParseException(errorString);
+ throw new ElasticsearchParseException("failed to parse [{}] query. already found function [{}], now encountering [{}]. use [functions] array if you want to define several functions.", NAME, singleFunctionName, currentFieldName);
}
filterFunctions.add(new FiltersFunctionScoreQuery.FilterFunction(null, scoreFunction));
singleFunctionFound = true;
@@ -195,7 +196,7 @@ public class FunctionScoreQueryParser implements QueryParser {
if (Arrays.asList(FactorParser.NAMES).contains(functionName)) {
errorString = errorString + MISPLACED_BOOST_FUNCTION_MESSAGE_SUFFIX;
}
- throw new ElasticsearchParseException(errorString);
+ throw new ElasticsearchParseException("failed to parse [{}] query. [{}]", NAME, errorString);
}
private String parseFiltersAndFunctions(QueryParseContext parseContext, XContentParser parser,
@@ -206,8 +207,7 @@ public class FunctionScoreQueryParser implements QueryParser {
ScoreFunction scoreFunction = null;
Float functionWeight = null;
if (token != XContentParser.Token.START_OBJECT) {
- throw new QueryParsingException(parseContext, NAME + ": malformed query, expected a " + XContentParser.Token.START_OBJECT
- + " while parsing functions but got a " + token);
+ throw new QueryParsingException(parseContext, "failed to parse [{}]. malformed query, expected a [{}] while parsing functions but got a [{}] instead", XContentParser.Token.START_OBJECT, token, NAME);
} else {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
@@ -234,7 +234,7 @@ public class FunctionScoreQueryParser implements QueryParser {
filter = Queries.newMatchAllQuery();
}
if (scoreFunction == null) {
- throw new ElasticsearchParseException("function_score: One entry in functions list is missing a function.");
+ throw new ElasticsearchParseException("failed to parse [{}] query. an entry in functions list is missing a function.", NAME);
}
filterFunctions.add(new FiltersFunctionScoreQuery.FilterFunction(filter, scoreFunction));
@@ -257,7 +257,7 @@ public class FunctionScoreQueryParser implements QueryParser {
} else if ("first".equals(scoreMode)) {
return FiltersFunctionScoreQuery.ScoreMode.First;
} else {
- throw new QueryParsingException(parseContext, NAME + " illegal score_mode [" + scoreMode + "]");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. illegal score_mode [{}]", NAME, scoreMode);
}
}
@@ -265,7 +265,7 @@ public class FunctionScoreQueryParser implements QueryParser {
String boostMode = parser.text();
CombineFunction cf = combineFunctionsMap.get(boostMode);
if (cf == null) {
- throw new QueryParsingException(parseContext, NAME + " illegal boost_mode [" + boostMode + "]");
+ throw new QueryParsingException(parseContext, "failed to parse [{}] query. illegal boost_mode [{}]", NAME, boostMode);
}
return cf;
}
diff --git a/core/src/main/java/org/elasticsearch/index/query/functionscore/ScoreFunctionParser.java b/core/src/main/java/org/elasticsearch/index/query/functionscore/ScoreFunctionParser.java
index c4315a159fc..74c3d08bd4f 100644
--- a/core/src/main/java/org/elasticsearch/index/query/functionscore/ScoreFunctionParser.java
+++ b/core/src/main/java/org/elasticsearch/index/query/functionscore/ScoreFunctionParser.java
@@ -28,13 +28,13 @@ import java.io.IOException;
public interface ScoreFunctionParser {
- public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException;
+ ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException;
/**
* Returns the name of the function, for example "linear", "gauss" etc. This
* name is used for registering the parser in
* {@link FunctionScoreQueryParser}.
* */
- public String[] getNames();
+ String[] getNames();
}
diff --git a/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardSnapshot.java b/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardSnapshot.java
index 475031aefc8..093319cec2a 100644
--- a/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardSnapshot.java
+++ b/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardSnapshot.java
@@ -287,13 +287,13 @@ public class BlobStoreIndexShardSnapshot {
metaHash.offset = 0;
metaHash.length = metaHash.bytes.length;
} else {
- throw new ElasticsearchParseException("unknown parameter [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("unknown parameter [{}]", currentFieldName);
}
} else {
- throw new ElasticsearchParseException("unexpected token [" + token + "]");
+ throw new ElasticsearchParseException("unexpected token [{}]", token);
}
} else {
- throw new ElasticsearchParseException("unexpected token [" + token + "]");
+ throw new ElasticsearchParseException("unexpected token [{}]",token);
}
}
}
@@ -480,7 +480,7 @@ public class BlobStoreIndexShardSnapshot {
} else if (ParseFields.TOTAL_SIZE.match(currentFieldName)) {
totalSize = parser.longValue();
} else {
- throw new ElasticsearchParseException("unknown parameter [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("unknown parameter [{}]", currentFieldName);
}
} else if (token == XContentParser.Token.START_ARRAY) {
if (ParseFields.FILES.match(currentFieldName)) {
@@ -488,13 +488,13 @@ public class BlobStoreIndexShardSnapshot {
indexFiles.add(FileInfo.fromXContent(parser));
}
} else {
- throw new ElasticsearchParseException("unknown parameter [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("unknown parameter [{}]", currentFieldName);
}
} else {
- throw new ElasticsearchParseException("unexpected token [" + token + "]");
+ throw new ElasticsearchParseException("unexpected token [{}]", token);
}
} else {
- throw new ElasticsearchParseException("unexpected token [" + token + "]");
+ throw new ElasticsearchParseException("unexpected token [{}]", token);
}
}
}
diff --git a/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardSnapshots.java b/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardSnapshots.java
index 907d23d19b7..f2b006bcf09 100644
--- a/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardSnapshots.java
+++ b/core/src/main/java/org/elasticsearch/index/snapshots/blobstore/BlobStoreIndexShardSnapshots.java
@@ -231,13 +231,13 @@ public class BlobStoreIndexShardSnapshots implements Iterable, To
if (token == XContentParser.Token.START_OBJECT) {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token != XContentParser.Token.FIELD_NAME) {
- throw new ElasticsearchParseException("unexpected token [" + token + "]");
+ throw new ElasticsearchParseException("unexpected token [{}]", token);
}
String currentFieldName = parser.currentName();
token = parser.nextToken();
if (token == XContentParser.Token.START_ARRAY) {
if (ParseFields.FILES.match(currentFieldName) == false) {
- throw new ElasticsearchParseException("unknown array [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("unknown array [{}]", currentFieldName);
}
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
FileInfo fileInfo = FileInfo.fromXContent(parser);
@@ -245,22 +245,22 @@ public class BlobStoreIndexShardSnapshots implements Iterable, To
}
} else if (token == XContentParser.Token.START_OBJECT) {
if (ParseFields.SNAPSHOTS.match(currentFieldName) == false) {
- throw new ElasticsearchParseException("unknown object [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("unknown object [{}]", currentFieldName);
}
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token != XContentParser.Token.FIELD_NAME) {
- throw new ElasticsearchParseException("unknown object [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("unknown object [{}]", currentFieldName);
}
String snapshot = parser.currentName();
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
- throw new ElasticsearchParseException("unknown object [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("unknown object [{}]", currentFieldName);
}
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
if (parser.nextToken() == XContentParser.Token.START_ARRAY) {
if (ParseFields.FILES.match(currentFieldName) == false) {
- throw new ElasticsearchParseException("unknown array [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("unknown array [{}]", currentFieldName);
}
List fileNames = newArrayList();
while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
@@ -272,7 +272,7 @@ public class BlobStoreIndexShardSnapshots implements Iterable, To
}
}
} else {
- throw new ElasticsearchParseException("unexpected token [" + token + "]");
+ throw new ElasticsearchParseException("unexpected token [{}]", token);
}
}
}
diff --git a/core/src/main/java/org/elasticsearch/percolator/PercolatorService.java b/core/src/main/java/org/elasticsearch/percolator/PercolatorService.java
index f99fa3385a2..9d56f718fbe 100644
--- a/core/src/main/java/org/elasticsearch/percolator/PercolatorService.java
+++ b/core/src/main/java/org/elasticsearch/percolator/PercolatorService.java
@@ -325,7 +325,7 @@ public class PercolatorService extends AbstractComponent {
if ("size".equals(currentFieldName)) {
context.size(parser.intValue());
if (context.size() < 0) {
- throw new ElasticsearchParseException("size is set to [" + context.size() + "] and is expected to be higher or equal to 0");
+ throw new ElasticsearchParseException("size is set to [{}] and is expected to be higher or equal to 0", context.size());
}
} else if ("sort".equals(currentFieldName)) {
parseSort(parser, context);
diff --git a/core/src/main/java/org/elasticsearch/repositories/blobstore/BlobStoreRepository.java b/core/src/main/java/org/elasticsearch/repositories/blobstore/BlobStoreRepository.java
index 9f37b8c88cf..58fb03789b0 100644
--- a/core/src/main/java/org/elasticsearch/repositories/blobstore/BlobStoreRepository.java
+++ b/core/src/main/java/org/elasticsearch/repositories/blobstore/BlobStoreRepository.java
@@ -471,7 +471,7 @@ public abstract class BlobStoreRepository extends AbstractLifecycleComponent {
XContentParser.Token token;
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT) {
- throw new ElasticsearchParseException("Expected START_OBJECT but got " + token.name() + " " + parser.currentName());
+ throw new ElasticsearchParseException("failed to parse search source. source must be an object, but found [{}] instead", token.name());
}
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
@@ -775,14 +762,14 @@ public class SearchService extends AbstractLifecycleComponent {
parser.nextToken();
SearchParseElement element = elementParsers.get(fieldName);
if (element == null) {
- throw new SearchParseException(context, "No parser for element [" + fieldName + "]", parser.getTokenLocation());
+ throw new SearchParseException(context, "failed to parse search source. unknown search element [" + fieldName + "]", parser.getTokenLocation());
}
element.parse(parser, context);
} else {
if (token == null) {
- throw new ElasticsearchParseException("End of query source reached but query is not complete.");
+ throw new ElasticsearchParseException("failed to parse search source. end of query source reached but query is not complete.");
} else {
- throw new ElasticsearchParseException("Expected field name but got " + token.name() + " \"" + parser.currentName() + "\"");
+ throw new ElasticsearchParseException("failed to parse search source. expected field name but got [{}]", token);
}
}
}
@@ -793,7 +780,8 @@ public class SearchService extends AbstractLifecycleComponent {
} catch (Throwable e1) {
// ignore
}
- throw new SearchParseException(context, "Failed to parse source [" + sSource + "]", parser.getTokenLocation(), e);
+ XContentLocation location = parser != null ? parser.getTokenLocation() : null;
+ throw new SearchParseException(context, "failed to parse search source [" + sSource + "]", location, e);
} finally {
if (parser != null) {
parser.close();
diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/Aggregator.java b/core/src/main/java/org/elasticsearch/search/aggregations/Aggregator.java
index fd9519499a8..9782ff9b21b 100644
--- a/core/src/main/java/org/elasticsearch/search/aggregations/Aggregator.java
+++ b/core/src/main/java/org/elasticsearch/search/aggregations/Aggregator.java
@@ -145,7 +145,7 @@ public abstract class Aggregator extends BucketCollector implements Releasable {
return mode;
}
}
- throw new ElasticsearchParseException("No " + KEY.getPreferredName() + " found for value [" + value + "]");
+ throw new ElasticsearchParseException("no [{}] found for value [{}]", KEY.getPreferredName(), value);
}
}
}
diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/GND.java b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/GND.java
index 5fd6a5ad937..bd86ccdbf22 100644
--- a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/GND.java
+++ b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/GND.java
@@ -123,7 +123,7 @@ public class GND extends NXYSignificanceHeuristic {
parser.nextToken();
backgroundIsSuperset = parser.booleanValue();
} else {
- throw new ElasticsearchParseException("Field " + parser.currentName().toString() + " unknown for " + givenName);
+ throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown field [{}]", givenName, parser.currentName());
}
token = parser.nextToken();
}
diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/JLHScore.java b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/JLHScore.java
index f7fdf224df1..b41484e2e77 100644
--- a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/JLHScore.java
+++ b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/JLHScore.java
@@ -110,7 +110,7 @@ public class JLHScore extends SignificanceHeuristic {
public SignificanceHeuristic parse(XContentParser parser) throws IOException, QueryParsingException {
// move to the closing bracket
if (!parser.nextToken().equals(XContentParser.Token.END_OBJECT)) {
- throw new ElasticsearchParseException("expected }, got " + parser.currentName() + " instead in jhl score");
+ throw new ElasticsearchParseException("failed to parse [jhl] significance heuristic. expected an empty object, but found [{}] instead", parser.currentToken());
}
return new JLHScore();
}
diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/NXYSignificanceHeuristic.java b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/NXYSignificanceHeuristic.java
index a8f84c8070a..d11700f37d6 100644
--- a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/NXYSignificanceHeuristic.java
+++ b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/NXYSignificanceHeuristic.java
@@ -150,7 +150,7 @@ public abstract class NXYSignificanceHeuristic extends SignificanceHeuristic {
parser.nextToken();
backgroundIsSuperset = parser.booleanValue();
} else {
- throw new ElasticsearchParseException("Field " + parser.currentName().toString() + " unknown for " + givenName);
+ throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown field [{}]", givenName, parser.currentName());
}
token = parser.nextToken();
}
diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/PercentageScore.java b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/PercentageScore.java
index a55dc044c85..aecc2c6c993 100644
--- a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/PercentageScore.java
+++ b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/PercentageScore.java
@@ -79,7 +79,7 @@ public class PercentageScore extends SignificanceHeuristic {
public SignificanceHeuristic parse(XContentParser parser) throws IOException, QueryParsingException {
// move to the closing bracket
if (!parser.nextToken().equals(XContentParser.Token.END_OBJECT)) {
- throw new ElasticsearchParseException("expected }, got " + parser.currentName() + " instead in percentage score");
+ throw new ElasticsearchParseException("failed to parse [percentage] significance heuristic. expected an empty object, but got [{}] instead", parser.currentToken());
}
return new PercentageScore();
}
diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/ScriptHeuristic.java b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/ScriptHeuristic.java
index dbc46599eff..d764af4ccc9 100644
--- a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/ScriptHeuristic.java
+++ b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/ScriptHeuristic.java
@@ -30,14 +30,9 @@ import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParsingException;
-import org.elasticsearch.script.ExecutableScript;
-import org.elasticsearch.script.Script;
+import org.elasticsearch.script.*;
import org.elasticsearch.script.Script.ScriptField;
-import org.elasticsearch.script.ScriptContext;
-import org.elasticsearch.script.ScriptParameterParser;
import org.elasticsearch.script.ScriptParameterParser.ScriptParameterValue;
-import org.elasticsearch.script.ScriptService;
-import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.search.aggregations.InternalAggregation;
import java.io.IOException;
@@ -134,7 +129,8 @@ public class ScriptHeuristic extends SignificanceHeuristic {
@Override
public SignificanceHeuristic parse(XContentParser parser) throws IOException, QueryParsingException {
- NAMES_FIELD.match(parser.currentName(), ParseField.EMPTY_FLAGS);
+ String heuristicName = parser.currentName();
+ NAMES_FIELD.match(heuristicName, ParseField.EMPTY_FLAGS);
Script script = null;
XContentParser.Token token;
Map params = null;
@@ -149,10 +145,10 @@ public class ScriptHeuristic extends SignificanceHeuristic {
} else if ("params".equals(currentFieldName)) { // TODO remove in 2.0 (here to support old script APIs)
params = parser.map();
} else {
- throw new ElasticsearchParseException("unknown object " + currentFieldName + " in script_heuristic");
+ throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown object [{}]", heuristicName, currentFieldName);
}
} else if (!scriptParameterParser.token(currentFieldName, token, parser)) {
- throw new ElasticsearchParseException("unknown field " + currentFieldName + " in script_heuristic");
+ throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown field [{}]", heuristicName, currentFieldName);
}
}
@@ -165,17 +161,17 @@ public class ScriptHeuristic extends SignificanceHeuristic {
script = new Script(scriptValue.script(), scriptValue.scriptType(), scriptParameterParser.lang(), params);
}
} else if (params != null) {
- throw new ElasticsearchParseException("script params must be specified inside script object");
+ throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. script params must be specified inside script object", heuristicName);
}
if (script == null) {
- throw new ElasticsearchParseException("No script found in script_heuristic");
+ throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. no script found in script_heuristic", heuristicName);
}
ExecutableScript searchScript;
try {
searchScript = scriptService.executable(script, ScriptContext.Standard.AGGS);
} catch (Exception e) {
- throw new ElasticsearchParseException("The script [" + script + "] could not be loaded", e);
+ throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. the script [{}] could not be loaded", e, script, heuristicName);
}
return new ScriptHeuristic(searchScript, script);
}
diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/SignificanceHeuristicParser.java b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/SignificanceHeuristicParser.java
index dca0d2e542f..e2668388da2 100644
--- a/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/SignificanceHeuristicParser.java
+++ b/core/src/main/java/org/elasticsearch/search/aggregations/bucket/significant/heuristics/SignificanceHeuristicParser.java
@@ -20,17 +20,14 @@
package org.elasticsearch.search.aggregations.bucket.significant.heuristics;
-import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParsingException;
-import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
-import java.util.EnumSet;
public interface SignificanceHeuristicParser {
- public SignificanceHeuristic parse(XContentParser parser) throws IOException, QueryParsingException;
+ SignificanceHeuristic parse(XContentParser parser) throws IOException, QueryParsingException;
- public String[] getNames();
+ String[] getNames();
}
diff --git a/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/movavg/models/HoltWintersModel.java b/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/movavg/models/HoltWintersModel.java
index 4a25c590639..a0dcd7e3e8d 100644
--- a/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/movavg/models/HoltWintersModel.java
+++ b/core/src/main/java/org/elasticsearch/search/aggregations/pipeline/movavg/models/HoltWintersModel.java
@@ -26,10 +26,8 @@ import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
-import org.elasticsearch.search.SearchParseException;
import org.elasticsearch.search.aggregations.AggregationExecutionException;
import org.elasticsearch.search.aggregations.pipeline.movavg.MovAvgParser;
-import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
import java.text.ParseException;
@@ -59,12 +57,8 @@ public class HoltWintersModel extends MovAvgModel {
SeasonalityType result = null;
for (SeasonalityType policy : values()) {
if (policy.parseField.match(text)) {
- if (result == null) {
- result = policy;
- } else {
- throw new IllegalStateException("Text can be parsed to 2 different seasonality types: text=[" + text
- + "], " + "policies=" + Arrays.asList(result, policy));
- }
+ result = policy;
+ break;
}
}
if (result == null) {
@@ -72,7 +66,7 @@ public class HoltWintersModel extends MovAvgModel {
for (SeasonalityType policy : values()) {
validNames.add(policy.getName());
}
- throw new ElasticsearchParseException("Invalid seasonality type: [" + text + "], accepted values: " + validNames);
+ throw new ElasticsearchParseException("failed to parse seasonality type [{}]. accepted values are [{}]", text, validNames);
}
return result;
}
diff --git a/core/src/main/java/org/elasticsearch/search/fetch/source/FetchSourceParseElement.java b/core/src/main/java/org/elasticsearch/search/fetch/source/FetchSourceParseElement.java
index 2cf5e9a6a68..3eb212fb250 100644
--- a/core/src/main/java/org/elasticsearch/search/fetch/source/FetchSourceParseElement.java
+++ b/core/src/main/java/org/elasticsearch/search/fetch/source/FetchSourceParseElement.java
@@ -74,7 +74,7 @@ public class FetchSourceParseElement implements SearchParseElement {
} else if ("excludes".equals(currentFieldName) || "exclude".equals(currentFieldName)) {
currentList = excludes != null ? excludes : (excludes = new ArrayList<>(2));
} else {
- throw new ElasticsearchParseException("Source definition may not contain " + parser.text());
+ throw new ElasticsearchParseException("source definition may not contain [{}]", parser.text());
}
} else if (token == XContentParser.Token.START_ARRAY) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
@@ -87,7 +87,7 @@ public class FetchSourceParseElement implements SearchParseElement {
}
}
} else {
- throw new ElasticsearchParseException("source element value can be of type " + token.name());
+ throw new ElasticsearchParseException("source element value can be of type [{}]", token.name());
}
return new FetchSourceContext(
diff --git a/core/src/main/java/org/elasticsearch/search/lookup/LeafFieldsLookup.java b/core/src/main/java/org/elasticsearch/search/lookup/LeafFieldsLookup.java
index b3835f10a32..de611deef4d 100644
--- a/core/src/main/java/org/elasticsearch/search/lookup/LeafFieldsLookup.java
+++ b/core/src/main/java/org/elasticsearch/search/lookup/LeafFieldsLookup.java
@@ -151,7 +151,7 @@ public class LeafFieldsLookup implements Map {
fieldVisitor.postProcess(data.fieldType());
data.fields(ImmutableMap.of(name, fieldVisitor.fields().get(data.fieldType().names().indexName())));
} catch (IOException e) {
- throw new ElasticsearchParseException("failed to load field [" + name + "]", e);
+ throw new ElasticsearchParseException("failed to load field [{}]", e, name);
}
}
return data;
diff --git a/core/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortParser.java b/core/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortParser.java
index 28d522b42e1..e7941a41d13 100644
--- a/core/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortParser.java
+++ b/core/src/main/java/org/elasticsearch/search/sort/GeoDistanceSortParser.java
@@ -218,7 +218,7 @@ public class GeoDistanceSortParser implements SortParser {
double lon = parser.doubleValue();
parser.nextToken();
if (!parser.currentToken().equals(XContentParser.Token.VALUE_NUMBER)) {
- throw new ElasticsearchParseException("geo point parsing: expected second number but got" + parser.currentToken());
+ throw new ElasticsearchParseException("geo point parsing: expected second number but got [{}] instead", parser.currentToken());
}
double lat = parser.doubleValue();
GeoPoint point = new GeoPoint();
diff --git a/core/src/main/java/org/elasticsearch/search/suggest/context/ContextBuilder.java b/core/src/main/java/org/elasticsearch/search/suggest/context/ContextBuilder.java
index 201625b6139..0a1ea7eea88 100644
--- a/core/src/main/java/org/elasticsearch/search/suggest/context/ContextBuilder.java
+++ b/core/src/main/java/org/elasticsearch/search/suggest/context/ContextBuilder.java
@@ -115,7 +115,7 @@ public abstract class ContextBuilder {
final Object argType = config.get(ContextMapping.FIELD_TYPE);
if (argType == null) {
- throw new ElasticsearchParseException("missing [" + ContextMapping.FIELD_TYPE + "] in context mapping");
+ throw new ElasticsearchParseException("missing [{}] in context mapping", ContextMapping.FIELD_TYPE);
}
final String type = argType.toString();
@@ -125,7 +125,7 @@ public abstract class ContextBuilder {
} else if (CategoryContextMapping.TYPE.equals(type)) {
contextMapping = CategoryContextMapping.load(name, config);
} else {
- throw new ElasticsearchParseException("unknown context type[" + type + "]");
+ throw new ElasticsearchParseException("unknown context type [{}]", type);
}
config.remove(ContextMapping.FIELD_TYPE);
DocumentMapperParser.checkNoRemainingFields(name, config, indexVersionCreated);
diff --git a/core/src/main/java/org/elasticsearch/search/suggest/context/ContextMapping.java b/core/src/main/java/org/elasticsearch/search/suggest/context/ContextMapping.java
index f856721d1de..43956c99dc9 100644
--- a/core/src/main/java/org/elasticsearch/search/suggest/context/ContextMapping.java
+++ b/core/src/main/java/org/elasticsearch/search/suggest/context/ContextMapping.java
@@ -293,7 +293,7 @@ public abstract class ContextMapping implements ToXContent {
String name = parser.text();
ContextMapping mapping = mappings.get(name);
if (mapping == null) {
- throw new ElasticsearchParseException("no mapping defined for [" + name + "]");
+ throw new ElasticsearchParseException("no mapping defined for [{}]", name);
}
parser.nextToken();
querySet.put(name, mapping.parseQuery(name, parser));
diff --git a/core/src/main/java/org/elasticsearch/search/suggest/context/GeolocationContextMapping.java b/core/src/main/java/org/elasticsearch/search/suggest/context/GeolocationContextMapping.java
index 74cb0a52ff0..22975ff83f3 100644
--- a/core/src/main/java/org/elasticsearch/search/suggest/context/GeolocationContextMapping.java
+++ b/core/src/main/java/org/elasticsearch/search/suggest/context/GeolocationContextMapping.java
@@ -174,14 +174,14 @@ public class GeolocationContextMapping extends ContextMapping {
} else if (def instanceof Map) {
Map latlonMap = (Map) def;
if (!latlonMap.containsKey("lat") || !(latlonMap.get("lat") instanceof Double)) {
- throw new ElasticsearchParseException("field [" + FIELD_MISSING + "] map must have field lat and a valid latitude");
+ throw new ElasticsearchParseException("field [{}] map must have field lat and a valid latitude", FIELD_MISSING);
}
if (!latlonMap.containsKey("lon") || !(latlonMap.get("lon") instanceof Double)) {
- throw new ElasticsearchParseException("field [" + FIELD_MISSING + "] map must have field lon and a valid longitude");
+ throw new ElasticsearchParseException("field [{}] map must have field lon and a valid longitude", FIELD_MISSING);
}
builder.addDefaultLocation(Double.valueOf(latlonMap.get("lat").toString()), Double.valueOf(latlonMap.get("lon").toString()));
} else {
- throw new ElasticsearchParseException("field [" + FIELD_MISSING + "] must be of type string or list");
+ throw new ElasticsearchParseException("field [{}] must be of type string or list", FIELD_MISSING);
}
config.remove(FIELD_MISSING);
}
@@ -350,7 +350,7 @@ public class GeolocationContextMapping extends ContextMapping {
throw new ElasticsearchParseException("latitude must be a number");
}
} else {
- throw new ElasticsearchParseException("only lat/lon or [" + FIELD_VALUE + "] is allowed");
+ throw new ElasticsearchParseException("only lat/lon or [{}] is allowed", FIELD_VALUE);
}
} else if ("lon".equals(fieldName)) {
if(point == null) {
@@ -364,7 +364,7 @@ public class GeolocationContextMapping extends ContextMapping {
throw new ElasticsearchParseException("longitude must be a number");
}
} else {
- throw new ElasticsearchParseException("only lat/lon or [" + FIELD_VALUE + "] is allowed");
+ throw new ElasticsearchParseException("only lat/lon or [{}] is allowed", FIELD_VALUE);
}
} else if (FIELD_PRECISION.equals(fieldName)) {
if(parser.nextToken() == Token.START_ARRAY) {
@@ -381,10 +381,10 @@ public class GeolocationContextMapping extends ContextMapping {
parser.nextToken();
point = GeoUtils.parseGeoPoint(parser);
} else {
- throw new ElasticsearchParseException("only lat/lon or [" + FIELD_VALUE + "] is allowed");
+ throw new ElasticsearchParseException("only lat/lon or [{}] is allowed", FIELD_VALUE);
}
} else {
- throw new ElasticsearchParseException("unexpected fieldname [" + fieldName + "]");
+ throw new ElasticsearchParseException("unexpected fieldname [{}]", fieldName);
}
}
diff --git a/core/src/main/java/org/elasticsearch/snapshots/SnapshotShardFailure.java b/core/src/main/java/org/elasticsearch/snapshots/SnapshotShardFailure.java
index 9edea5c8720..216052ee57d 100644
--- a/core/src/main/java/org/elasticsearch/snapshots/SnapshotShardFailure.java
+++ b/core/src/main/java/org/elasticsearch/snapshots/SnapshotShardFailure.java
@@ -201,15 +201,15 @@ public class SnapshotShardFailure implements ShardOperationFailedException {
} else if ("status".equals(currentFieldName)) {
snapshotShardFailure.status = RestStatus.valueOf(parser.text());
} else {
- throw new ElasticsearchParseException("unknown parameter [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("unknown parameter [{}]", currentFieldName);
}
}
} else {
- throw new ElasticsearchParseException("unexpected token [" + token + "]");
+ throw new ElasticsearchParseException("unexpected token [{}]", token);
}
}
} else {
- throw new ElasticsearchParseException("unexpected token [" + token + "]");
+ throw new ElasticsearchParseException("unexpected token [{}]", token);
}
return snapshotShardFailure;
}
diff --git a/core/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java b/core/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java
index 284ae0f2d68..4fc94d92fef 100644
--- a/core/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java
+++ b/core/src/test/java/org/elasticsearch/index/query/SimpleIndexQueryParserTests.java
@@ -2297,7 +2297,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest {
queryParser.parse(query).query();
fail("FunctionScoreQueryParser should throw an exception here because two functions in body are not allowed.");
} catch (QueryParsingException e) {
- assertThat(e.getDetailedMessage(), containsString("Use functions[{...},...] if you want to define several functions."));
+ assertThat(e.getDetailedMessage(), containsString("use [functions] array if you want to define several functions."));
}
}
@@ -2353,7 +2353,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest {
queryParser.parse(query).query();
fail("Expect exception here because array of functions and one weight in body is not allowed.");
} catch (QueryParsingException e) {
- assertThat(e.getDetailedMessage(), containsString("You can either define \"functions\":[...] or a single function, not both. Found \"functions\": [...] already, now encountering \"weight\"."));
+ assertThat(e.getDetailedMessage(), containsString("you can either define [functions] array or a single function, not both. already found [functions] array, now encountering [weight]."));
}
query = jsonBuilder().startObject().startObject("function_score")
.field("weight", 2)
@@ -2365,7 +2365,7 @@ public class SimpleIndexQueryParserTests extends ElasticsearchSingleNodeTest {
queryParser.parse(query).query();
fail("Expect exception here because array of functions and one weight in body is not allowed.");
} catch (QueryParsingException e) {
- assertThat(e.getDetailedMessage(), containsString("You can either define \"functions\":[...] or a single function, not both. Found \"weight\" already, now encountering \"functions\": [...]."));
+ assertThat(e.getDetailedMessage(), containsString("you can either define [functions] array or a single function, not both. already found [weight], now encountering [functions]."));
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java
index 83705bf7d73..13491b46627 100644
--- a/core/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java
+++ b/core/src/test/java/org/elasticsearch/search/aggregations/bucket/significant/SignificanceHeuristicTests.java
@@ -168,19 +168,19 @@ public class SignificanceHeuristicTests extends ElasticsearchTestCase {
// test exceptions
String faultyHeuristicdefinition = "\"mutual_information\":{\"include_negatives\": false, \"some_unknown_field\": false}";
- String expectedError = "unknown for mutual_information";
+ String expectedError = "unknown field [some_unknown_field]";
checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError);
faultyHeuristicdefinition = "\"chi_square\":{\"unknown_field\": true}";
- expectedError = "unknown for chi_square";
+ expectedError = "unknown field [unknown_field]";
checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError);
faultyHeuristicdefinition = "\"jlh\":{\"unknown_field\": true}";
- expectedError = "expected }, got ";
+ expectedError = "expected an empty object, but found ";
checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError);
faultyHeuristicdefinition = "\"gnd\":{\"unknown_field\": true}";
- expectedError = "unknown for gnd";
+ expectedError = "unknown field [unknown_field]";
checkParseException(heuristicParserMapper, searchContext, faultyHeuristicdefinition, expectedError);
}
diff --git a/core/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreTests.java b/core/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreTests.java
index aef01106e9e..51770fb925f 100644
--- a/core/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreTests.java
+++ b/core/src/test/java/org/elasticsearch/search/functionscore/DecayFunctionScoreTests.java
@@ -46,23 +46,11 @@ import java.util.concurrent.ExecutionException;
import static org.elasticsearch.client.Requests.indexRequest;
import static org.elasticsearch.client.Requests.searchRequest;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
-import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery;
-import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery;
-import static org.elasticsearch.index.query.QueryBuilders.termQuery;
-import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.exponentialDecayFunction;
-import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.gaussDecayFunction;
-import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.linearDecayFunction;
+import static org.elasticsearch.index.query.QueryBuilders.*;
+import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.*;
import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertOrderedSearchHits;
-import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchHits;
-import static org.hamcrest.Matchers.anyOf;
-import static org.hamcrest.Matchers.closeTo;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.isOneOf;
-import static org.hamcrest.Matchers.lessThan;
+import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.*;
+import static org.hamcrest.Matchers.*;
public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest {
@@ -816,7 +804,7 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest {
fail("Search should result in SearchPhaseExecutionException");
} catch (SearchPhaseExecutionException e) {
logger.info(e.shardFailures()[0].reason());
- assertTrue(e.shardFailures()[0].reason().contains("Found \"functions\": [...] already, now encountering \"boost_factor\". Did you mean \"boost\" instead?"));
+ assertThat(e.shardFailures()[0].reason(), containsString("already found [functions] array, now encountering [boost_factor]. did you mean [boost] instead?"));
}
query = XContentFactory.jsonBuilder();
@@ -829,7 +817,7 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest {
fail("Search should result in SearchPhaseExecutionException");
} catch (SearchPhaseExecutionException e) {
logger.info(e.shardFailures()[0].reason());
- assertTrue(e.shardFailures()[0].reason().contains("Found \"boost_factor\" already, now encountering \"functions\": [...]. Did you mean \"boost\" instead?"));
+ assertThat(e.shardFailures()[0].reason(), containsString("already found [boost_factor], now encountering [functions]. did you mean [boost] instead?"));
}
query = XContentFactory.jsonBuilder();
@@ -842,8 +830,8 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest {
fail("Search should result in SearchPhaseExecutionException");
} catch (SearchPhaseExecutionException e) {
logger.info(e.shardFailures()[0].reason());
- assertTrue(e.shardFailures()[0].reason().contains("Found \"random_score\" already, now encountering \"functions\": [...]."));
- assertFalse(e.shardFailures()[0].reason().contains("Did you mean \"boost\" instead?"));
+ assertThat(e.shardFailures()[0].reason(), containsString("already found [random_score], now encountering [functions]"));
+ assertThat(e.shardFailures()[0].reason(), not(containsString("did you mean [boost] instead?")));
}
}
@@ -882,8 +870,8 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest {
searchSource().query(query))).actionGet();
fail("Should fail with SearchPhaseExecutionException");
} catch (SearchPhaseExecutionException failure) {
- assertTrue(failure.toString().contains("SearchParseException"));
- assertFalse(failure.toString().contains("NullPointerException"));
+ assertThat(failure.toString(), containsString("SearchParseException"));
+ assertThat(failure.toString(), not(containsString("NullPointerException")));
}
query = "{\n" +
@@ -916,26 +904,26 @@ public class DecayFunctionScoreTests extends ElasticsearchIntegrationTest {
searchSource().query(query))).actionGet();
fail("Should fail with SearchPhaseExecutionException");
} catch (SearchPhaseExecutionException failure) {
- assertTrue(failure.toString().contains("SearchParseException"));
- assertFalse(failure.toString().contains("NullPointerException"));
- assertTrue(failure.toString().contains("One entry in functions list is missing a function"));
+ assertThat(failure.toString(), containsString("SearchParseException"));
+ assertThat(failure.toString(), not(containsString("NullPointerException")));
+ assertThat(failure.toString(), containsString("an entry in functions list is missing a function"));
}
// next test java client
try {
client().prepareSearch("t").setQuery(QueryBuilders.functionScoreQuery(QueryBuilders.matchAllQuery(), null)).get();
} catch (IllegalArgumentException failure) {
- assertTrue(failure.toString().contains("function must not be null"));
+ assertThat(failure.toString(), containsString("function must not be null"));
}
try {
client().prepareSearch("t").setQuery(QueryBuilders.functionScoreQuery().add(QueryBuilders.matchAllQuery(), null)).get();
} catch (IllegalArgumentException failure) {
- assertTrue(failure.toString().contains("function must not be null"));
+ assertThat(failure.toString(), containsString("function must not be null"));
}
try {
client().prepareSearch("t").setQuery(QueryBuilders.functionScoreQuery().add(null)).get();
} catch (IllegalArgumentException failure) {
- assertTrue(failure.toString().contains("function must not be null"));
+ assertThat(failure.toString(), containsString("function must not be null"));
}
}
diff --git a/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreTests.java b/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreTests.java
index 43b572d8a12..b5550b04e05 100644
--- a/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreTests.java
+++ b/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreTests.java
@@ -960,7 +960,7 @@ public class DedicatedClusterSnapshotRestoreTests extends AbstractSnapshotTests
}
data = parser.text();
} else {
- throw new ElasticsearchParseException("failed to parse snapshottable metadata, unknown field [" + currentFieldName + "]");
+ throw new ElasticsearchParseException("failed to parse snapshottable metadata, unknown field [{}]", currentFieldName);
}
} else {
throw new ElasticsearchParseException("failed to parse snapshottable metadata");