com.yahoo.text.MapParser Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of vespajlib Show documentation
Show all versions of vespajlib Show documentation
Library for use in Java components of Vespa. Shared code which do
not fit anywhere else.
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.text;
import java.util.HashMap;
import java.util.Map;
/**
* Superclasses of parsers of a map represented textually as
* {key1:value1,"anystringkey":value2,'anystringkey2':value3 ...}
.
* This parser must be extended to override the way values are parsed and constructed.
*
* Example: To create a Double map parser:
*
* public static final class DoubleMapParser extends MapParser<Double> {
*
* @Override
* protected Double parseValue(String value) {
* return Double.parseDouble(value);
* }
*
* }
*
*
* Map parsers are NOT multithread safe, but are cheap to construct.
*
* @author bratseth
*/
public abstract class MapParser extends SimpleMapParser {
private Map map;
/**
* Convenience method doing return parse(s,new HashMap<String,VALUETYPE>())
*/
public Map parseToMap(String s) {
return parse(s,new HashMap<>());
}
/**
* Parses a map on the form {key1:value1,key2:value2 ...}
*
* @param string the textual representation of the map
* @param map the map to which the values will be added
* @return the input map instance for convenience
*/
public Map parse(String string,Map map) {
this.map = map;
parse(string);
return this.map;
}
protected void handleKeyValue(String key, String value) {
map.put(key, parseValue(value));
}
protected abstract VALUETYPE parseValue(String value);
}