public Node representData(Object data) { Tag tag; String value; if (data instanceof Byte || data instanceof Short || data instanceof Integer || data instanceof Long || data instanceof BigInteger) { tag = Tag.INT; value = data.toString(); } else { Number number = (Number) data; tag = Tag.FLOAT; if (number.equals(Double.NaN)) { value = ".NaN"; } else if (number.equals(Double.POSITIVE_INFINITY)) { value = ".inf"; } else if (number.equals(Double.NEGATIVE_INFINITY)) { value = "-.inf"; } else { value = number.toString(); } } return representScalar(getTag(data.getClass(), tag), value); }
protected Node representSequence(Tag tag, Iterable<?> sequence, Boolean flowStyle) { int size = 10;// default for ArrayList if (sequence instanceof List<?>) { size = ((List<?>) sequence).size(); } List<Node> value = new ArrayList<Node>(size); SequenceNode node = new SequenceNode(tag, value, flowStyle); representedObjects.put(objectToRepresent, node); boolean bestStyle = true; for (Object item : sequence) { Node nodeItem = representData(item); if (!(nodeItem instanceof ScalarNode && ((ScalarNode) nodeItem).getStyle() == null)) { bestStyle = false; } value.add(nodeItem); } if (flowStyle == null) { if (defaultFlowStyle != FlowStyle.AUTO) { node.setFlowStyle(defaultFlowStyle.getStyleBoolean()); } else { node.setFlowStyle(bestStyle); } } return node; }
protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) { List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size()); MappingNode node = new MappingNode(tag, value, flowStyle); representedObjects.put(objectToRepresent, node); boolean bestStyle = true; for (Map.Entry<?, ?> entry : mapping.entrySet()) { Node nodeKey = representData(entry.getKey()); Node nodeValue = representData(entry.getValue()); if (!(nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).getStyle() == null)) { bestStyle = false; } if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) { bestStyle = false; } value.add(new NodeTuple(nodeKey, nodeValue)); } if (flowStyle == null) { if (defaultFlowStyle != FlowStyle.AUTO) { node.setFlowStyle(defaultFlowStyle.getStyleBoolean()); } else { node.setFlowStyle(bestStyle); } } return node; }
protected void addImplicitResolvers() { addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO"); /* * INT must be before FLOAT because the regular expression for FLOAT * matches INT (see issue 130) * http://code.google.com/p/snakeyaml/issues/detail?id=130 */ addImplicitResolver(Tag.INT, INT, "-+0123456789"); addImplicitResolver(Tag.FLOAT, FLOAT, "-+0123456789."); addImplicitResolver(Tag.MERGE, MERGE, "<"); addImplicitResolver(Tag.NULL, NULL, "~nN\0"); addImplicitResolver(Tag.NULL, EMPTY, null); addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, "0123456789"); // The following implicit resolver is only for documentation // purposes. // It cannot work // because plain scalars cannot start with '!', '&', or '*'. addImplicitResolver(Tag.YAML, YAML, "!&*"); }
public SafeConstructor() { this.yamlConstructors.put(Tag.NULL, new ConstructYamlNull()); this.yamlConstructors.put(Tag.BOOL, new ConstructYamlBool()); this.yamlConstructors.put(Tag.INT, new ConstructYamlInt()); this.yamlConstructors.put(Tag.FLOAT, new ConstructYamlFloat()); this.yamlConstructors.put(Tag.BINARY, new ConstructYamlBinary()); this.yamlConstructors.put(Tag.TIMESTAMP, new ConstructYamlTimestamp()); this.yamlConstructors.put(Tag.OMAP, new ConstructYamlOmap()); this.yamlConstructors.put(Tag.PAIRS, new ConstructYamlPairs()); this.yamlConstructors.put(Tag.SET, new ConstructYamlSet()); this.yamlConstructors.put(Tag.STR, new ConstructYamlStr()); this.yamlConstructors.put(Tag.SEQ, new ConstructYamlSeq()); this.yamlConstructors.put(Tag.MAP, new ConstructYamlMap()); this.yamlConstructors.put(null, undefinedConstructor); this.yamlClassConstructors.put(NodeId.scalar, undefinedConstructor); this.yamlClassConstructors.put(NodeId.sequence, undefinedConstructor); this.yamlClassConstructors.put(NodeId.mapping, undefinedConstructor); }
public static final <T> void addSerializer(ExtensibleRepresenter representer, Class<T> type, Function<T, String> function) { representer.addRepresenter(type, new Represent() { @SuppressWarnings("unchecked") @Override public Node representData(Object data) { String txt = function.apply((T) data); if (txt == null) { return new ScalarNode(Tag.NULL, "null", null, null, null); } return new ScalarNode(Tag.STR, txt, null, null, null); } }); }
public Node representData(Object data) { Class<?> type = data.getClass().getComponentType(); if (byte.class == type) { return representSequence(Tag.SEQ, asByteList(data), null); } else if (short.class == type) { return representSequence(Tag.SEQ, asShortList(data), null); } else if (int.class == type) { return representSequence(Tag.SEQ, asIntList(data), null); } else if (long.class == type) { return representSequence(Tag.SEQ, asLongList(data), null); } else if (float.class == type) { return representSequence(Tag.SEQ, asFloatList(data), null); } else if (double.class == type) { return representSequence(Tag.SEQ, asDoubleList(data), null); } else if (char.class == type) { return representSequence(Tag.SEQ, asCharList(data), null); } else if (boolean.class == type) { return representSequence(Tag.SEQ, asBooleanList(data), null); } throw new YAMLException("Unexpected primitive '" + type.getCanonicalName() + "'"); }
public static Yaml newYaml() { PropertyUtils propertyUtils = new AdvancedPropertyUtils(); propertyUtils.setSkipMissingProperties(true); Constructor constructor = new Constructor(Federations.class); TypeDescription federationDescription = new TypeDescription(Federations.class); federationDescription.putListPropertyType("federatedMetaStores", FederatedMetaStore.class); constructor.addTypeDescription(federationDescription); constructor.setPropertyUtils(propertyUtils); Representer representer = new AdvancedRepresenter(); representer.setPropertyUtils(new FieldOrderPropertyUtils()); representer.addClassTag(Federations.class, Tag.MAP); representer.addClassTag(AbstractMetaStore.class, Tag.MAP); representer.addClassTag(WaggleDanceConfiguration.class, Tag.MAP); representer.addClassTag(YamlStorageConfiguration.class, Tag.MAP); representer.addClassTag(GraphiteConfiguration.class, Tag.MAP); DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setIndent(2); dumperOptions.setDefaultFlowStyle(FlowStyle.BLOCK); return new Yaml(constructor, representer, dumperOptions); }
private void dumpConfiguration(Path configFilePath) { try (FileWriter fileWriter = new FileWriter(configFilePath.toFile())) { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Representer representer = new Representer() { @Override protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue,Tag customTag) { // if value of property is null, ignore it. if (propertyValue == null) { return null; } else { return super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); } } }; representer.addClassTag(Configuration.class, Tag.MAP); Yaml yaml = new Yaml(representer, options); yaml.dump(configuration, fileWriter); } catch (IOException e) { throw new RuntimeException("Failed to dump configuration in file " + configFilePath, e); } }
/** * Overrides the {@link * Representer#representJavaBeanProperty(Object, Property, Object, * Tag)} method to return {@code null} when the given property * value can be omitted from its YAML representation without loss * of information. * * @param bean the Java bean whose property value is being * represented; may be {@code null} * * @param property the {@link Property} whose value is being * represented; may be {@code null} * * @param value the value being represented; may be {@code null} * * @param tag the {@link Tag} in effect; may be {@code null} * * @return {@code null} or the result of invoking the {@link * Representer#representJavaBeanProperty(Object, Property, Object, * Tag)} method with the supplied values */ @Override protected final NodeTuple representJavaBeanProperty(final Object bean, final Property property, final Object value, final Tag tag) { final NodeTuple returnValue; if (value == null || value.equals(Boolean.FALSE)) { returnValue = null; } else if (value instanceof CharSequence) { if (((CharSequence)value).length() <= 0) { returnValue = null; } else { returnValue = super.representJavaBeanProperty(bean, property, value, tag); } } else if (value instanceof Collection) { if (((Collection<?>)value).isEmpty()) { returnValue = null; } else { returnValue = super.representJavaBeanProperty(bean, property, value, tag); } } else if (value instanceof Map) { if (((Map<?, ?>)value).isEmpty()) { returnValue = null; } else { returnValue = super.representJavaBeanProperty(bean, property, value, tag); } } else if (value.getClass().isArray()) { if (Array.getLength(value) <= 0) { returnValue = null; } else { returnValue = super.representJavaBeanProperty(bean, property, value, tag); } } else { returnValue = super.representJavaBeanProperty(bean, property, value, tag); } return returnValue; }
private void dumpAll(Iterator<?> data, Writer output, @Nullable Tag rootTag) { Serializer serializer = new Serializer(this.serialization, new Emitter(this.serialization, output, this.dumperOptions), this.resolver, this.dumperOptions, rootTag); try { serializer.open(); while (data.hasNext()) { Object next = data.next(); ClassLoader old = Thread.currentThread().getContextClassLoader(); if ((old == null) && (next != null)) { Thread.currentThread().setContextClassLoader(next.getClass().getClassLoader()); } try { Node node = this.representer.represent(next); serializer.serialize(node); } finally { if (old == null) { Thread.currentThread().setContextClassLoader(null); } } } serializer.close(); } catch (IOException e) { throw new YAMLException(e); } }
public Node representData(Object data) { String value; if (Boolean.TRUE.equals(data)) { value = "true"; } else { value = "false"; } return representScalar(Tag.BOOL, value); }
public final Node representNumber(Number data) { Tag tag; String value; if ((data instanceof Byte) || (data instanceof Short) || (data instanceof Integer) || (data instanceof Long) || (data instanceof BigInteger)) { tag = Tag.INT; value = data.toString(); } else { tag = Tag.FLOAT; if (data.equals(Double.NaN)) { value = ".NaN"; } else if (data.equals(Double.POSITIVE_INFINITY)) { value = ".inf"; } else if (data.equals(Double.NEGATIVE_INFINITY)) { value = "-.inf"; } else { value = data.toString(); } } return this.representer.representScalar(this.representer.getTag(data.getClass(), tag), value); }
@SuppressWarnings("unchecked") public Node representData(Object data) { Map<Object, Object> value = new LinkedHashMap<Object, Object>(); Set<Object> set = (Set<Object>) data; for (Object key : set) { value.put(key, null); } return representMapping(getTag(data.getClass(), Tag.SET), value, null); }
/** * Tag logic:<br/> * - explicit root tag is set in serializer <br/> * - if there is a predefined class tag it is used<br/> * - a global tag with class name is always used as tag. The JavaBean parent * of the specified JavaBean may set another tag (tag:yaml.org,2002:map) * when the property class is the same as runtime class * * @param properties * JavaBean getters * @param javaBean * instance for Node * @return Node to get serialized */ protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size()); Tag tag; Tag customTag = classTags.get(javaBean.getClass()); tag = customTag != null ? customTag : new Tag(javaBean.getClass()); // flow style will be chosen by BaseRepresenter MappingNode node = new MappingNode(tag, value, null); representedObjects.put(javaBean, node); boolean bestStyle = true; for (Property property : properties) { Object memberValue = property.get(javaBean); Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue .getClass()); NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag); if (tuple == null) { continue; } if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) { bestStyle = false; } Node nodeValue = tuple.getValueNode(); if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) { bestStyle = false; } value.add(tuple); } if (defaultFlowStyle != FlowStyle.AUTO) { node.setFlowStyle(defaultFlowStyle.getStyleBoolean()); } else { node.setFlowStyle(bestStyle); } return node; }
/** * Represent one JavaBean property. * * @param javaBean * - the instance to be represented * @param property * - the property of the instance * @param propertyValue * - value to be represented * @param customTag * - user defined Tag * @return NodeTuple to be used in a MappingNode. Return null to skip the * property */ protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) { ScalarNode nodeKey = (ScalarNode) representData(property.getName()); // the first occurrence of the node must keep the tag boolean hasAlias = this.representedObjects.containsKey(propertyValue); Node nodeValue = representData(propertyValue); if (propertyValue != null && !hasAlias) { NodeId nodeId = nodeValue.getNodeId(); if (customTag == null) { if (nodeId == NodeId.scalar) { if (propertyValue instanceof Enum<?>) { nodeValue.setTag(Tag.STR); } } else { if (nodeId == NodeId.mapping) { if (property.getType() == propertyValue.getClass()) { if (!(propertyValue instanceof Map<?, ?>)) { if (!nodeValue.getTag().equals(Tag.SET)) { nodeValue.setTag(Tag.MAP); } } } } checkGlobalTag(property, nodeValue, propertyValue); } } } return new NodeTuple(nodeKey, nodeValue); }
private void resetTag(Class<? extends Object> type, Node node) { Tag tag = node.getTag(); if (tag.matches(type)) { if (Enum.class.isAssignableFrom(type)) { node.setTag(Tag.STR); } else { node.setTag(Tag.MAP); } } }
protected Node representScalar(Tag tag, String value, Character style) { if (style == null) { style = this.defaultScalarStyle; } Node node = new ScalarNode(tag, value, null, null, style); return node; }
protected void composeMappingChildren(List<NodeTuple> children, MappingNode node) { Node itemKey = composeKeyNode(node); if (itemKey.getTag().equals(Tag.MERGE)) { node.setMerged(true); } Node itemValue = composeValueNode(node); children.add(new NodeTuple(itemKey, itemValue)); }
public TypeDescription(Class<? extends Object> clazz, Tag tag) { this.type = clazz; this.tag = tag; listProperties = new HashMap<String, Class<? extends Object>>(); keyProperties = new HashMap<String, Class<? extends Object>>(); valueProperties = new HashMap<String, Class<? extends Object>>(); }
@Override public Object construct(Node nnode) { if (nnode.getTag() == Tag.TIMESTAMP) { Construct dateConstructor = yamlConstructors.get(Tag.TIMESTAMP); if (nnode.getType().isAssignableFrom(DateTime.class)) { Date date = (Date) dateConstructor.construct(nnode); return new DateTime(date, DateTimeZone.UTC); } else { return dateConstructor.construct(nnode); } } else { return super.construct(nnode); } }
public Serializer(Emitable emitter, Resolver resolver, DumperOptions opts, Tag rootTag) { this.emitter = emitter; this.resolver = resolver; this.explicitStart = opts.isExplicitStart(); this.explicitEnd = opts.isExplicitEnd(); if (opts.getVersion() != null) { this.useVersion = opts.getVersion(); } this.useTags = opts.getTags(); this.serializedNodes = new HashSet<Node>(); this.anchors = new HashMap<Node, String>(); this.anchorGenerator = opts.getAnchorGenerator(); this.closed = null; this.explicitRoot = rootTag; }
private void dumpAll(Iterator<? extends Object> data, Writer output, Tag rootTag) { Serializer serializer = new Serializer(new Emitter(output, dumperOptions), resolver, dumperOptions, rootTag); try { serializer.open(); while (data.hasNext()) { Node node = representer.represent(data.next()); serializer.serialize(node); } serializer.close(); } catch (IOException e) { throw new YAMLException(e); } }
public Constructor(TypeDescription theRoot) { if (theRoot == null) { throw new NullPointerException("Root type must be provided."); } this.yamlConstructors.put(null, new ConstructYamlObject()); if (!Object.class.equals(theRoot.getType())) { rootTag = new Tag(theRoot.getType()); } typeTags = new HashMap<Tag, Class<? extends Object>>(); typeDefinitions = new HashMap<Class<? extends Object>, TypeDescription>(); yamlClassConstructors.put(NodeId.scalar, new ConstructScalar()); yamlClassConstructors.put(NodeId.mapping, new ConstructMapping()); yamlClassConstructors.put(NodeId.sequence, new ConstructSequence()); addTypeDescription(theRoot); }
private void resetTag(Class<?> type, Node node) { Tag tag = node.getTag(); if (tag.matches(type)) { if (Enum.class.isAssignableFrom(type)) { node.setTag(Tag.STR); } else { node.setTag(Tag.MAP); } } }
public final Node representSet(Set<?> data) { Map<Object, Object> value = new LinkedHashMap<>(data.size()); for (Object key : data) { value.put(key, null); } return this.representer.representMapping(this.representer.getTag(data.getClass(), Tag.SET), value, null); }
public SafeRepresenter() { this.nullRepresenter = new RepresentNull(); this.representers.put(String.class, new RepresentString()); this.representers.put(Boolean.class, new RepresentBoolean()); this.representers.put(Character.class, new RepresentString()); this.representers.put(UUID.class, new RepresentUuid()); this.representers.put(byte[].class, new RepresentByteArray()); Represent primitiveArray = new RepresentPrimitiveArray(); representers.put(short[].class, primitiveArray); representers.put(int[].class, primitiveArray); representers.put(long[].class, primitiveArray); representers.put(float[].class, primitiveArray); representers.put(double[].class, primitiveArray); representers.put(char[].class, primitiveArray); representers.put(boolean[].class, primitiveArray); this.multiRepresenters.put(Number.class, new RepresentNumber()); this.multiRepresenters.put(List.class, new RepresentList()); this.multiRepresenters.put(Map.class, new RepresentMap()); this.multiRepresenters.put(Set.class, new RepresentSet()); this.multiRepresenters.put(Iterator.class, new RepresentIterator()); this.multiRepresenters.put(new Object[0].getClass(), new RepresentArray()); this.multiRepresenters.put(Date.class, new RepresentDate()); this.multiRepresenters.put(Enum.class, new RepresentEnum()); this.multiRepresenters.put(Calendar.class, new RepresentDate()); classTags = new HashMap<Class<? extends Object>, Tag>(); }
protected Tag getTag(Class<?> clazz, Tag defaultTag) { if (classTags.containsKey(clazz)) { return classTags.get(clazz); } else { return defaultTag; } }
public Node representData(Object data) { Tag tag = Tag.STR; Character style = null; String value = data.toString(); if (!StreamReader.isPrintable(value)) { tag = Tag.BINARY; char[] binary; try { final byte[] bytes = value.getBytes("UTF-8"); // sometimes above will just silently fail - it will return incomplete data // it happens when String has invalid code points // (for example half surrogate character without other half) final String checkValue = new String(bytes, "UTF-8"); if (!checkValue.equals(value)) { throw new YAMLException("invalid string value has occurred"); } binary = Base64Coder.encode(bytes); } catch (UnsupportedEncodingException e) { throw new YAMLException(e); } value = String.valueOf(binary); style = '|'; } // if no other scalar style is explicitly set, use literal style for // multiline scalars if (defaultScalarStyle == null && MULTILINE_PATTERN.matcher(value).find()) { style = '|'; } return representScalar(tag, value, style); }
/** * Tag logic: * - explicit root tag is set in serializer * - if there is a predefined class tag it is used * - a global tag with class name is always used as tag. The JavaBean parent * of the specified JavaBean may set another tag (tag:yaml.org,2002:map) * when the property class is the same as runtime class * * @param properties * JavaBean getters * @param javaBean * instance for Node * @return Node to get serialized */ protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { List<NodeTuple> value = new ArrayList<NodeTuple>(properties.size()); Tag tag; Tag customTag = classTags.get(javaBean.getClass()); tag = customTag != null ? customTag : new Tag(javaBean.getClass()); // flow style will be chosen by BaseRepresenter MappingNode node = new MappingNode(tag, value, null); representedObjects.put(javaBean, node); boolean bestStyle = true; for (Property property : properties) { Object memberValue = property.get(javaBean); Tag customPropertyTag = memberValue == null ? null : classTags.get(memberValue .getClass()); NodeTuple tuple = representJavaBeanProperty(javaBean, property, memberValue, customPropertyTag); if (tuple == null) { continue; } if (((ScalarNode) tuple.getKeyNode()).getStyle() != null) { bestStyle = false; } Node nodeValue = tuple.getValueNode(); if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) { bestStyle = false; } value.add(tuple); } if (defaultFlowStyle != FlowStyle.AUTO) { node.setFlowStyle(defaultFlowStyle.getStyleBoolean()); } else { node.setFlowStyle(bestStyle); } return node; }