Class ObjectParser<Value,Context>

java.lang.Object
org.elasticsearch.xcontent.AbstractObjectParser<Value,Context>
org.elasticsearch.xcontent.ObjectParser<Value,Context>
All Implemented Interfaces:
BiFunction<XContentParser,Context,Value>, ContextParser<Context,Value>

public final class ObjectParser<Value,Context> extends AbstractObjectParser<Value,Context> implements BiFunction<XContentParser,Context,Value>, ContextParser<Context,Value>
A declarative, stateless parser that turns XContent into setter calls. A single parser should be defined for each object being parsed, nested elements can be added via AbstractObjectParser.declareObject(BiConsumer, ContextParser, ParseField) which should be satisfied where possible by passing another instance of ObjectParser, this one customized for that Object.

This class works well for object that do have a constructor argument or that can be built using information available from earlier in the XContent. For objects that have constructors with required arguments that are specified on the same level as other fields see ConstructingObjectParser.

Instances of ObjectParser should be setup by declaring a constant field for the parsers and declaring all fields in a static block just below the creation of the parser. Like this:


   private static final ObjectParser<Thing, SomeContext> PARSER = new ObjectParser<>("thing", Thing::new));
   static {
       PARSER.declareInt(Thing::setMineral, new ParseField("mineral"));
       PARSER.declareInt(Thing::setFruit, new ParseField("fruit"));
   }
 
It's highly recommended to use the high level declare methods like AbstractObjectParser.declareString(BiConsumer, ParseField) instead of declareField(org.elasticsearch.xcontent.ObjectParser.Parser<Value, Context>, org.elasticsearch.xcontent.ParseField, org.elasticsearch.xcontent.ObjectParser.ValueType) which can be used to implement exceptional parsing operations not covered by the high level methods.
  • Constructor Details

    • ObjectParser

      public ObjectParser(String name)
      Creates a new ObjectParser.
      Parameters:
      name - the parsers name, used to reference the parser in exceptions and messages.
    • ObjectParser

      public ObjectParser(String name, @Nullable Supplier<Value> valueSupplier)
      Creates a new ObjectParser.
      Parameters:
      name - the parsers name, used to reference the parser in exceptions and messages.
      valueSupplier - A supplier that creates a new Value instance. Used when the parser is used as an inner object parser.
    • ObjectParser

      public ObjectParser(String name, boolean ignoreUnknownFields, @Nullable Supplier<Value> valueSupplier)
      Creates a new ObjectParser.
      Parameters:
      name - the parsers name, used to reference the parser in exceptions and messages.
      ignoreUnknownFields - Should this parser ignore unknown fields? This should generally be set to true only when parsing responses from external systems, never when parsing requests from users.
      valueSupplier - a supplier that creates a new Value instance used when the parser is used as an inner object parser.
    • ObjectParser

      public ObjectParser(String name, ObjectParser.UnknownFieldConsumer<Value> unknownFieldConsumer, @Nullable Supplier<Value> valueSupplier)
      Creates a new ObjectParser that consumes unknown fields as generic Objects.
      Parameters:
      name - the parsers name, used to reference the parser in exceptions and messages.
      unknownFieldConsumer - how to consume parsed unknown fields
      valueSupplier - a supplier that creates a new Value instance used when the parser is used as an inner object parser.
    • ObjectParser

      public ObjectParser(String name, Class<C> categoryClass, BiConsumer<Value,C> unknownFieldConsumer, @Nullable Supplier<Value> valueSupplier)
      Creates a new ObjectParser that attempts to resolve unknown fields as namedObjects.
      Type Parameters:
      C - the type of named object that unknown fields are expected to be
      Parameters:
      name - the parsers name, used to reference the parser in exceptions and messages.
      categoryClass - the type of named object that unknown fields are expected to be
      unknownFieldConsumer - how to consume parsed unknown fields
      valueSupplier - a supplier that creates a new Value instance used when the parser is used as an inner object parser.
  • Method Details

    • fromList

      public static <Value, ElementValue> BiConsumer<Value,List<ElementValue>> fromList(Class<ElementValue> c, BiConsumer<Value,ElementValue[]> consumer)
      Adapts an array (or varags) setter into a list setter.
    • fromBuilder

      public static <Value, Context> ObjectParser<Value,Context> fromBuilder(String name, Function<Context,Value> valueBuilder)
      Creates a new ObjectParser.
      Parameters:
      name - the parsers name, used to reference the parser in exceptions and messages.
      valueBuilder - A function that creates a new Value from the parse Context. Used when the parser is used as an inner object parser.
    • parse

      public Value parse(XContentParser parser, Context context) throws IOException
      Parses a Value from the given XContentParser
      Specified by:
      parse in interface ContextParser<Value,Context>
      Parameters:
      parser - the parser to build a value from
      context - context needed for parsing
      Returns:
      a new value instance drawn from the provided value supplier on ObjectParser(String, Supplier)
      Throws:
      IOException - if an IOException occurs.
    • parse

      public Value parse(XContentParser parser, Value value, Context context) throws IOException
      Parses a Value from the given XContentParser
      Parameters:
      parser - the parser to build a value from
      value - the value to fill from the parser
      context - a context that is passed along to all declared field parsers
      Returns:
      the parsed value
      Throws:
      IOException - if an IOException occurs.
    • apply

      public Value apply(XContentParser parser, Context context)
      Specified by:
      apply in interface BiFunction<XContentParser,Context,Value>
    • declareField

      public void declareField(ObjectParser.Parser<Value,Context> p, ParseField parseField, ObjectParser.ValueType type)
    • declareField

      public <T> void declareField(BiConsumer<Value,T> consumer, ContextParser<Context,T> parser, ParseField parseField, ObjectParser.ValueType type)
      Description copied from class: AbstractObjectParser
      Specified by:
      declareField in class AbstractObjectParser<Value,Context>
    • declareObjectOrDefault

      public <T> void declareObjectOrDefault(BiConsumer<Value,T> consumer, BiFunction<XContentParser,Context,T> objectParser, Supplier<T> defaultValue, ParseField field)
    • declareNamedObject

      public <T> void declareNamedObject(BiConsumer<Value,T> consumer, ObjectParser.NamedObjectParser<T,Context> namedObjectParser, ParseField field)
      Description copied from class: AbstractObjectParser
      Declares a single named object.
       
       {
         "object_name": {
           "instance_name": { "field1": "value1", ... }
           }
         }
       }
       
       
      Specified by:
      declareNamedObject in class AbstractObjectParser<Value,Context>
      Parameters:
      consumer - sets the value once it has been parsed
      namedObjectParser - parses the named object
      field - the field to parse
    • declareNamedObjects

      public <T> void declareNamedObjects(BiConsumer<Value,List<T>> consumer, ObjectParser.NamedObjectParser<T,Context> namedObjectParser, Consumer<Value> orderedModeCallback, ParseField field)
      Description copied from class: AbstractObjectParser
      Declares named objects in the style of highlighting's field element. These are usually named inside and object like this:
       
       {
         "highlight": {
           "fields": {        <------ this one
             "title": {},
             "body": {},
             "category": {}
           }
         }
       }
       
       
      but, when order is important, some may be written this way:
       
       {
         "highlight": {
           "fields": [        <------ this one
             {"title": {}},
             {"body": {}},
             {"category": {}}
           ]
         }
       }
       
       
      This is because json doesn't enforce ordering. Elasticsearch reads it in the order sent but tools that generate json are free to put object members in an unordered Map, jumbling them. Thus, if you care about order you can send the object in the second way. See NamedObjectHolder in ObjectParserTests for examples of how to invoke this.
      Specified by:
      declareNamedObjects in class AbstractObjectParser<Value,Context>
      Parameters:
      consumer - sets the values once they have been parsed
      namedObjectParser - parses each named object
      orderedModeCallback - called when the named object is parsed using the "ordered" mode (the array of objects)
      field - the field to parse
    • declareNamedObjects

      public <T> void declareNamedObjects(BiConsumer<Value,List<T>> consumer, ObjectParser.NamedObjectParser<T,Context> namedObjectParser, ParseField field)
      Description copied from class: AbstractObjectParser
      Declares named objects in the style of aggregations. These are named inside and object like this:
       
       {
         "aggregations": {
           "name_1": { "aggregation_type": {} },
           "name_2": { "aggregation_type": {} },
           "name_3": { "aggregation_type": {} }
           }
         }
       }
       
       
      Unlike the other version of this method, "ordered" mode (arrays of objects) is not supported. See NamedObjectHolder in ObjectParserTests for examples of how to invoke this.
      Specified by:
      declareNamedObjects in class AbstractObjectParser<Value,Context>
      Parameters:
      consumer - sets the values once they have been parsed
      namedObjectParser - parses each named object
      field - the field to parse
    • getName

      public String getName()
      Get the name of the parser.
      Specified by:
      getName in class AbstractObjectParser<Value,Context>
    • declareRequiredFieldSet

      public void declareRequiredFieldSet(String... requiredSet)
      Description copied from class: AbstractObjectParser
      Declares a set of fields that are required for parsing to succeed. Only one of the values provided per String[] must be matched. E.g. declareRequiredFieldSet("foo", "bar"); means at least one of "foo" or "bar" fields must be present. If neither of those fields are present, an exception will be thrown. Multiple required sets can be configured:
      
         parser.declareRequiredFieldSet("foo", "bar");
         parser.declareRequiredFieldSet("bizz", "buzz");
       
      requires that one of "foo" or "bar" fields are present, and also that one of "bizz" or "buzz" fields are present. In JSON, it means any of these combinations are acceptable:
      • {"foo":"...", "bizz": "..."}
      • {"bar":"...", "bizz": "..."}
      • {"foo":"...", "buzz": "..."}
      • {"bar":"...", "buzz": "..."}
      • {"foo":"...", "bar":"...", "bizz": "..."}
      • {"foo":"...", "bar":"...", "buzz": "..."}
      • {"foo":"...", "bizz":"...", "buzz": "..."}
      • {"bar":"...", "bizz":"...", "buzz": "..."}
      • {"foo":"...", "bar":"...", "bizz": "...", "buzz": "..."}
      The following would however be rejected:
      failure cases
      Provided JSONReason for failure
      {"foo":"..."}Missing "bizz" or "buzz" field
      {"bar":"..."}Missing "bizz" or "buzz" field
      {"bizz": "..."}Missing "foo" or "bar" field
      {"buzz": "..."}Missing "foo" or "bar" field
      {"foo":"...", "bar": "..."}Missing "bizz" or "buzz" field
      {"bizz":"...", "buzz": "..."}Missing "foo" or "bar" field
      {"unrelated":"..."} Missing "foo" or "bar" field, and missing "bizz" or "buzz" field
      Specified by:
      declareRequiredFieldSet in class AbstractObjectParser<Value,Context>
      Parameters:
      requiredSet - A set of required fields, where at least one of the fields in the array _must_ be present
    • declareExclusiveFieldSet

      public void declareExclusiveFieldSet(String... exclusiveSet)
      Description copied from class: AbstractObjectParser
      Declares a set of fields of which at most one must appear for parsing to succeed E.g. declareExclusiveFieldSet("foo", "bar"); means that only one of 'foo' or 'bar' must be present, and if both appear then an exception will be thrown. Note that this does not make 'foo' or 'bar' required - see AbstractObjectParser.declareRequiredFieldSet(String...) for required fields. Multiple exclusive sets may be declared
      Specified by:
      declareExclusiveFieldSet in class AbstractObjectParser<Value,Context>
      Parameters:
      exclusiveSet - a set of field names, at most one of which must appear
    • toString

      public String toString()
      Overrides:
      toString in class Object