io.github.mmm.marshall.tvm.xml.impl.TvmXmlFormat Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mmm-marshall-tvm-xml Show documentation
Show all versions of mmm-marshall-tvm-xml Show documentation
Implementations of mmm-marshall API for XML using TeaVM.
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package io.github.mmm.marshall.tvm.xml.impl;
import java.io.IOException;
import java.io.Reader;
import org.teavm.jso.dom.xml.Document;
import io.github.mmm.marshall.MarshallableObject;
import io.github.mmm.marshall.MarshallingConfig;
import io.github.mmm.marshall.StructuredFormat;
import io.github.mmm.marshall.StructuredReader;
import io.github.mmm.marshall.StructuredWriter;
import io.github.mmm.marshall.spi.AbstractStructuredTextFormat;
/**
* Implementation of {@link StructuredFormat} for XML using TeaVM.
*
* @since 1.0.0
*/
public class TvmXmlFormat extends AbstractStructuredTextFormat {
private static final TvmXmlFormat DEFAULT = new TvmXmlFormat(MarshallingConfig.DEFAULTS);
/**
* The constructor.
*
* @param config the {@link MarshallingConfig}.
*/
public TvmXmlFormat(MarshallingConfig config) {
super(config);
}
@Override
public String getId() {
return ID_XML;
}
@Override
public StructuredReader reader(String xml) {
Document document = DOMParser.of().parseFromString(xml, StructuredFormat.ID_XML);
return new TvmXmlDocumentReader(document.getDocumentElement(), this);
}
@Override
public StructuredReader reader(Object data) {
if (data instanceof Document) {
return new TvmXmlDocumentReader(((Document) data).getDocumentElement(), this);
}
return super.reader(data);
}
@Override
public StructuredReader reader(Reader reader) {
try {
char[] buf = new char[1024];
StringBuilder sb = new StringBuilder();
int chars;
do {
chars = reader.read(buf, 0, buf.length);
if (chars > 0) {
sb.append(buf, 0, chars);
}
} while (chars >= 0);
return reader(sb.toString());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override
public String write(MarshallableObject object) {
if (object == null) {
return null;
}
StringBuilder writer = new StringBuilder(512);
StructuredWriter structuredWriter = new TvmXmlStringWriter(writer, this);
object.write(structuredWriter);
return writer.toString();
}
@Override
public StructuredWriter writer(Appendable writer) {
return new TvmXmlStringWriter(writer, this);
}
@Override
public boolean isSupportingComments() {
return true;
}
/**
* @return the default instance of {@link TvmXmlFormat}.
*/
public static TvmXmlFormat of() {
return DEFAULT;
}
}