From e06e122f9fa2363b67b3162406717b4356efbf77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christoph=20B=C3=BCscher?= Date: Mon, 18 Apr 2016 15:24:08 +0200 Subject: [PATCH] Wrap xcontent parser creation in try-with-resource statement where possible --- .../indices/create/CreateIndexRequest.java | 6 +- .../template/put/PutIndexTemplateRequest.java | 9 ++- .../elasticsearch/cluster/ClusterState.java | 13 +++-- .../cluster/metadata/AliasMetaData.java | 8 +-- .../cluster/metadata/AliasValidator.java | 6 +- .../cluster/metadata/IndexMetaData.java | 9 +-- .../metadata/IndexTemplateMetaData.java | 7 ++- .../gateway/MetaDataStateFormat.java | 6 +- .../index/query/GeoShapeQueryBuilder.java | 8 +-- .../index/query/MoreLikeThisQueryBuilder.java | 9 +-- .../index/query/PercolatorQueryBuilder.java | 9 +-- .../functionscore/DecayFunctionBuilder.java | 12 ++-- .../RestRenderSearchTemplateAction.java | 57 ++++++++++--------- .../elasticsearch/script/ScriptService.java | 3 +- .../elasticsearch/search/SearchService.java | 4 ++ .../search/builder/SearchSourceBuilder.java | 7 ++- .../CompletionSuggestionBuilder.java | 7 ++- .../index/reindex/RestReindexAction.java | 21 +++---- 18 files changed, 108 insertions(+), 93 deletions(-) diff --git a/core/src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexRequest.java b/core/src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexRequest.java index 39e3673868a..43d45672aec 100644 --- a/core/src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexRequest.java +++ b/core/src/main/java/org/elasticsearch/action/admin/indices/create/CreateIndexRequest.java @@ -21,7 +21,6 @@ package org.elasticsearch.action.admin.indices.create; import org.elasticsearch.ElasticsearchGenerationException; import org.elasticsearch.ElasticsearchParseException; -import org.elasticsearch.action.ActionRequest; import org.elasticsearch.action.ActionRequestValidationException; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.admin.indices.alias.Alias; @@ -49,9 +48,9 @@ import java.util.Map; import java.util.Set; import static org.elasticsearch.action.ValidateActions.addValidationError; -import static org.elasticsearch.common.settings.Settings.Builder.EMPTY_SETTINGS; import static org.elasticsearch.common.settings.Settings.readSettingsFromStream; import static org.elasticsearch.common.settings.Settings.writeSettingsToStream; +import static org.elasticsearch.common.settings.Settings.Builder.EMPTY_SETTINGS; /** * A request to create an index. Best created with {@link org.elasticsearch.client.Requests#createIndexRequest(String)}. @@ -305,8 +304,7 @@ public class CreateIndexRequest extends AcknowledgedRequest * Sets the aliases that will be associated with the index when it gets created */ public CreateIndexRequest aliases(BytesReference source) { - try { - XContentParser parser = XContentHelper.createParser(source); + try (XContentParser parser = XContentHelper.createParser(source)) { //move to the first alias parser.nextToken(); while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) { 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 94d436d57d8..76c665c7b8f 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 @@ -47,9 +47,9 @@ import java.util.Map; import java.util.Set; import static org.elasticsearch.action.ValidateActions.addValidationError; -import static org.elasticsearch.common.settings.Settings.Builder.EMPTY_SETTINGS; import static org.elasticsearch.common.settings.Settings.readSettingsFromStream; import static org.elasticsearch.common.settings.Settings.writeSettingsToStream; +import static org.elasticsearch.common.settings.Settings.Builder.EMPTY_SETTINGS; /** * A request to create an index template. @@ -71,7 +71,7 @@ public class PutIndexTemplateRequest extends MasterNodeRequest mappings = new HashMap<>(); private final Set aliases = new HashSet<>(); - + private Map customs = new HashMap<>(); public PutIndexTemplateRequest() { @@ -356,7 +356,7 @@ public class PutIndexTemplateRequest extends MasterNodeRequest customs() { return this.customs; } - + public Set aliases() { return this.aliases; } @@ -393,8 +393,7 @@ public class PutIndexTemplateRequest extends MasterNodeRequest { builder.startObject("mappings"); for (ObjectObjectCursor cursor1 : templateMetaData.mappings()) { byte[] mappingSource = cursor1.value.uncompressed(); - XContentParser parser = XContentFactory.xContent(mappingSource).createParser(mappingSource); - Map mapping = parser.map(); + Map mapping; + try (XContentParser parser = XContentFactory.xContent(mappingSource).createParser(mappingSource)) { + mapping = parser.map(); + } if (mapping.size() == 1 && mapping.containsKey(cursor1.key)) { // the type name is the root value, reduce it mapping = (Map) mapping.get(cursor1.key); @@ -470,8 +473,10 @@ public class ClusterState implements ToXContent, Diffable { builder.startObject("mappings"); for (ObjectObjectCursor cursor : indexMetaData.getMappings()) { byte[] mappingSource = cursor.value.source().uncompressed(); - XContentParser parser = XContentFactory.xContent(mappingSource).createParser(mappingSource); - Map mapping = parser.map(); + Map mapping; + try (XContentParser parser = XContentFactory.xContent(mappingSource).createParser(mappingSource)) { + mapping = parser.map(); + } if (mapping.size() == 1 && mapping.containsKey(cursor.key)) { // the type name is the root value, reduce it mapping = (Map) mapping.get(cursor.key); diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasMetaData.java b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasMetaData.java index c083396482e..d6d13b55bd7 100644 --- a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasMetaData.java +++ b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasMetaData.java @@ -290,10 +290,10 @@ public class AliasMetaData extends AbstractDiffable { builder.field("filter", aliasMetaData.filter.compressed()); } else { byte[] data = aliasMetaData.filter().uncompressed(); - XContentParser parser = XContentFactory.xContent(data).createParser(data); - Map filter = parser.mapOrdered(); - parser.close(); - builder.field("filter", filter); + try (XContentParser parser = XContentFactory.xContent(data).createParser(data)) { + Map filter = parser.mapOrdered(); + builder.field("filter", filter); + } } } if (aliasMetaData.indexRouting() != null) { diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java index dd8da761dfc..a3d776a4edb 100644 --- a/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java +++ b/core/src/main/java/org/elasticsearch/cluster/metadata/AliasValidator.java @@ -118,8 +118,7 @@ public class AliasValidator extends AbstractComponent { */ public void validateAliasFilter(String alias, String filter, QueryShardContext queryShardContext) { assert queryShardContext != null; - try { - XContentParser parser = XContentFactory.xContent(filter).createParser(filter); + try (XContentParser parser = XContentFactory.xContent(filter).createParser(filter)) { validateAliasFilter(parser, queryShardContext); } catch (Throwable e) { throw new IllegalArgumentException("failed to parse filter for alias [" + alias + "]", e); @@ -133,8 +132,7 @@ public class AliasValidator extends AbstractComponent { */ public void validateAliasFilter(String alias, byte[] filter, QueryShardContext queryShardContext) { assert queryShardContext != null; - try { - XContentParser parser = XContentFactory.xContent(filter).createParser(filter); + try (XContentParser parser = XContentFactory.xContent(filter).createParser(filter)) { validateAliasFilter(parser, queryShardContext); } catch (Throwable e) { throw new IllegalArgumentException("failed to parse filter for alias [" + alias + "]", e); diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java b/core/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java index d493e3f9031..7d99f8fd74d 100644 --- a/core/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java +++ b/core/src/main/java/org/elasticsearch/cluster/metadata/IndexMetaData.java @@ -23,6 +23,7 @@ import com.carrotsearch.hppc.LongArrayList; import com.carrotsearch.hppc.cursors.IntObjectCursor; import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; + import org.elasticsearch.Version; import org.elasticsearch.cluster.Diff; import org.elasticsearch.cluster.Diffable; @@ -927,10 +928,10 @@ public class IndexMetaData implements Diffable, FromXContentBuild builder.value(cursor.value.source().compressed()); } else { byte[] data = cursor.value.source().uncompressed(); - XContentParser parser = XContentFactory.xContent(data).createParser(data); - Map mapping = parser.mapOrdered(); - parser.close(); - builder.map(mapping); + try (XContentParser parser = XContentFactory.xContent(data).createParser(data)) { + Map mapping = parser.mapOrdered(); + builder.map(mapping); + } } } builder.endArray(); diff --git a/core/src/main/java/org/elasticsearch/cluster/metadata/IndexTemplateMetaData.java b/core/src/main/java/org/elasticsearch/cluster/metadata/IndexTemplateMetaData.java index 6ae9a6746e5..dce78a3dda4 100644 --- a/core/src/main/java/org/elasticsearch/cluster/metadata/IndexTemplateMetaData.java +++ b/core/src/main/java/org/elasticsearch/cluster/metadata/IndexTemplateMetaData.java @@ -20,6 +20,7 @@ package org.elasticsearch.cluster.metadata; import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; + import org.elasticsearch.cluster.AbstractDiffable; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.collect.MapBuilder; @@ -329,8 +330,10 @@ public class IndexTemplateMetaData extends AbstractDiffable cursor : indexTemplateMetaData.mappings()) { byte[] mappingSource = cursor.value.uncompressed(); - XContentParser parser = XContentFactory.xContent(mappingSource).createParser(mappingSource); - Map mapping = parser.map(); + Map mapping; + try (XContentParser parser = XContentFactory.xContent(mappingSource).createParser(mappingSource)) {; + mapping = parser.map(); + } if (mapping.size() == 1 && mapping.containsKey(cursor.key)) { // the type name is the root value, reduce it mapping = (Map) mapping.get(cursor.key); diff --git a/core/src/main/java/org/elasticsearch/gateway/MetaDataStateFormat.java b/core/src/main/java/org/elasticsearch/gateway/MetaDataStateFormat.java index 8795a7e7d15..9a78925368e 100644 --- a/core/src/main/java/org/elasticsearch/gateway/MetaDataStateFormat.java +++ b/core/src/main/java/org/elasticsearch/gateway/MetaDataStateFormat.java @@ -295,15 +295,15 @@ public abstract class MetaDataStateFormat { try { final Path stateFile = pathAndStateId.file; final long id = pathAndStateId.id; - final XContentParser parser; if (pathAndStateId.legacy) { // read the legacy format -- plain XContent final byte[] data = Files.readAllBytes(stateFile); if (data.length == 0) { logger.debug("{}: no data for [{}], ignoring...", prefix, stateFile.toAbsolutePath()); continue; } - parser = XContentHelper.createParser(new BytesArray(data)); - state = fromXContent(parser); + try (final XContentParser parser = XContentHelper.createParser(new BytesArray(data))) { + state = fromXContent(parser); + } if (state == null) { logger.debug("{}: no data for [{}], ignoring...", prefix, stateFile.toAbsolutePath()); } diff --git a/core/src/main/java/org/elasticsearch/index/query/GeoShapeQueryBuilder.java b/core/src/main/java/org/elasticsearch/index/query/GeoShapeQueryBuilder.java index 9f7b83c543e..e1734394e5b 100644 --- a/core/src/main/java/org/elasticsearch/index/query/GeoShapeQueryBuilder.java +++ b/core/src/main/java/org/elasticsearch/index/query/GeoShapeQueryBuilder.java @@ -382,9 +382,7 @@ public class GeoShapeQueryBuilder extends AbstractQueryBuilder public void doXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(getName()); builder.field(fieldName); - XContentParser parser = XContentFactory.xContent(functionBytes).createParser(functionBytes); - builder.copyCurrentStructure(parser); + try (XContentParser parser = XContentFactory.xContent(functionBytes).createParser(functionBytes)) { + builder.copyCurrentStructure(parser); + } builder.field(DecayFunctionParser.MULTI_VALUE_MODE.getPreferredName(), multiValueMode.name()); builder.endObject(); } @@ -181,8 +182,11 @@ public abstract class DecayFunctionBuilder @Override protected ScoreFunction doToFunction(QueryShardContext context) throws IOException { - XContentParser parser = XContentFactory.xContent(functionBytes).createParser(functionBytes); - return parseVariable(fieldName, parser, context, multiValueMode); + AbstractDistanceScoreFunction scoreFunction; + try (XContentParser parser = XContentFactory.xContent(functionBytes).createParser(functionBytes)) { + scoreFunction = parseVariable(fieldName, parser, context, multiValueMode); + } + return scoreFunction; } /** diff --git a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/template/RestRenderSearchTemplateAction.java b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/template/RestRenderSearchTemplateAction.java index f1308657528..1cbe7b95816 100644 --- a/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/template/RestRenderSearchTemplateAction.java +++ b/core/src/main/java/org/elasticsearch/rest/action/admin/indices/validate/template/RestRenderSearchTemplateAction.java @@ -63,35 +63,40 @@ public class RestRenderSearchTemplateAction extends BaseRestHandler { protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception { RenderSearchTemplateRequest renderSearchTemplateRequest; BytesReference source = RestActions.getRestContent(request); - XContentParser parser = XContentFactory.xContent(source).createParser(source); - String templateId = request.param("id"); - final Template template; - if (templateId == null) { - template = Template.parse(parser, parseFieldMatcher); - } else { - Map params = null; - String currentFieldName = null; - XContentParser.Token token = parser.nextToken(); - if (token != XContentParser.Token.START_OBJECT) { - throw new ElasticsearchParseException("failed to parse request. request body must be an object but found [{}] instead", token); - } - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { - if (token == XContentParser.Token.FIELD_NAME) { - currentFieldName = parser.currentName(); - } else if (parseFieldMatcher.match(currentFieldName, ScriptField.PARAMS)) { - if (token == XContentParser.Token.START_OBJECT) { - params = parser.map(); - } else { - throw new ElasticsearchParseException("failed to parse request. field [{}] is expected to be an object, but found [{}] instead", currentFieldName, token); - } - } else { - throw new ElasticsearchParseException("failed to parse request. unknown field [{}] of type [{}]", currentFieldName, token); + try (XContentParser parser = XContentFactory.xContent(source).createParser(source)) { + String templateId = request.param("id"); + final Template template; + if (templateId == null) { + template = Template.parse(parser, parseFieldMatcher); + } else { + Map params = null; + String currentFieldName = null; + XContentParser.Token token = parser.nextToken(); + if (token != XContentParser.Token.START_OBJECT) { + throw new ElasticsearchParseException("failed to parse request. request body must be an object but found [{}] instead", + token); } + while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + if (token == XContentParser.Token.FIELD_NAME) { + currentFieldName = parser.currentName(); + } else if (parseFieldMatcher.match(currentFieldName, ScriptField.PARAMS)) { + if (token == XContentParser.Token.START_OBJECT) { + params = parser.map(); + } else { + throw new ElasticsearchParseException( + "failed to parse request. field [{}] is expected to be an object, but found [{}] instead", + currentFieldName, token); + } + } else { + throw new ElasticsearchParseException("failed to parse request. unknown field [{}] of type [{}]", currentFieldName, + token); + } + } + template = new Template(templateId, ScriptType.INDEXED, Template.DEFAULT_LANG, null, params); } - template = new Template(templateId, ScriptType.INDEXED, Template.DEFAULT_LANG, null, params); + renderSearchTemplateRequest = new RenderSearchTemplateRequest(); + renderSearchTemplateRequest.template(template); } - renderSearchTemplateRequest = new RenderSearchTemplateRequest(); - renderSearchTemplateRequest.template(template); client.admin().cluster().renderSearchTemplate(renderSearchTemplateRequest, new RestBuilderListener(channel) { @Override diff --git a/core/src/main/java/org/elasticsearch/script/ScriptService.java b/core/src/main/java/org/elasticsearch/script/ScriptService.java index 8d37783d7c2..fc375901607 100644 --- a/core/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/core/src/main/java/org/elasticsearch/script/ScriptService.java @@ -361,8 +361,7 @@ public class ScriptService extends AbstractComponent implements Closeable { } private void validate(BytesReference scriptBytes, String scriptLang) { - try { - XContentParser parser = XContentFactory.xContent(scriptBytes).createParser(scriptBytes); + try (XContentParser parser = XContentFactory.xContent(scriptBytes).createParser(scriptBytes)) { parser.nextToken(); Template template = TemplateQueryBuilder.parse(scriptLang, parser, parseFieldMatcher, "params", "script", "template"); if (Strings.hasLength(template.getScript())) { diff --git a/core/src/main/java/org/elasticsearch/search/SearchService.java b/core/src/main/java/org/elasticsearch/search/SearchService.java index 7f2cd4c4c1b..c03a13b5ee7 100644 --- a/core/src/main/java/org/elasticsearch/search/SearchService.java +++ b/core/src/main/java/org/elasticsearch/search/SearchService.java @@ -811,6 +811,10 @@ public class SearchService extends AbstractLifecycleComponent imp } XContentLocation location = extParser != null ? extParser.getTokenLocation() : null; throw new SearchParseException(context, "failed to parse ext source [" + sSource + "]", location, e); + } finally { + if (extParser != null) { + extParser.close(); + } } } if (source.version() != null) { diff --git a/core/src/main/java/org/elasticsearch/search/builder/SearchSourceBuilder.java b/core/src/main/java/org/elasticsearch/search/builder/SearchSourceBuilder.java index a39d0273c2f..3675320184b 100644 --- a/core/src/main/java/org/elasticsearch/search/builder/SearchSourceBuilder.java +++ b/core/src/main/java/org/elasticsearch/search/builder/SearchSourceBuilder.java @@ -1257,9 +1257,10 @@ public final class SearchSourceBuilder extends ToXContentToBytes implements Writ if (ext != null) { builder.field(EXT_FIELD.getPreferredName()); - XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(ext); - parser.nextToken(); - builder.copyCurrentStructure(parser); + try (XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(ext)) { + parser.nextToken(); + builder.copyCurrentStructure(parser); + } } } diff --git a/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestionBuilder.java b/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestionBuilder.java index ce75351dfb5..2d9307a8820 100644 --- a/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestionBuilder.java +++ b/core/src/main/java/org/elasticsearch/search/suggest/completion/CompletionSuggestionBuilder.java @@ -255,9 +255,10 @@ public class CompletionSuggestionBuilder extends SuggestionBuilder destParser = new ObjectParser<>("dest");