From e57f76aa2da2aef2241744f93702682dc5d843cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christoph=20B=C3=BCscher?= Date: Fri, 5 Aug 2016 18:55:46 +0200 Subject: [PATCH] Ensure PutMappingRequest.buildFromSimplifiedDef fails when input isn't pairs The method requires pairs of fieldnames and property arguments and will fail if the varargs input is an uneven number. We should check this and fail with an appropriate IllegalArgumentException instead. --- .../admin/indices/mapping/put/PutMappingRequest.java | 10 ++++++++++ .../indices/mapping/put/PutMappingRequestTests.java | 7 +++++++ 2 files changed, 17 insertions(+) diff --git a/core/src/main/java/org/elasticsearch/action/admin/indices/mapping/put/PutMappingRequest.java b/core/src/main/java/org/elasticsearch/action/admin/indices/mapping/put/PutMappingRequest.java index c638a429b10..152bc516549 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/indices/mapping/put/PutMappingRequest.java +++ b/core/src/main/java/org/elasticsearch/action/admin/indices/mapping/put/PutMappingRequest.java @@ -177,7 +177,17 @@ public class PutMappingRequest extends AcknowledgedRequest im return source(buildFromSimplifiedDef(type, source)); } + /** + * @param type the mapping type + * @param source consisting of field/properties pairs (e.g. "field1", + * "type=string,store=true"). If the number of arguments is not + * divisible by two an {@link IllegalArgumentException} is thrown + * @return the mappings definition + */ public static XContentBuilder buildFromSimplifiedDef(String type, Object... source) { + if (source.length % 2 != 0) { + throw new IllegalArgumentException("mapping source must be pairs of fieldnames and properties definition."); + } try { XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/mapping/put/PutMappingRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/mapping/put/PutMappingRequestTests.java index 04892b82339..9c93e5c73d9 100644 --- a/core/src/test/java/org/elasticsearch/action/admin/indices/mapping/put/PutMappingRequestTests.java +++ b/core/src/test/java/org/elasticsearch/action/admin/indices/mapping/put/PutMappingRequestTests.java @@ -57,4 +57,11 @@ public class PutMappingRequestTests extends ESTestCase { "Validation Failed: 1: either concrete index or unresolved indices can be set," + " concrete index: [[foo/bar]] and indices: [myindex];"); } + + public void testBuildFromSimplifiedDef() { + // test that method rejects input where input varargs fieldname/properites are not paired correctly + IllegalArgumentException e = expectThrows(IllegalArgumentException.class, + () -> PutMappingRequest.buildFromSimplifiedDef("type", "only_field")); + assertEquals("mapping source must be pairs of fieldnames and properties definition.", e.getMessage()); + } }