io.github.dumijdev.dpxml.parser.impl.pojo.BasicPojolizer Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of dp-xml Show documentation
Show all versions of dp-xml Show documentation
A Java lib to convert xml to POJO and POJO to xml
package io.github.dumijdev.dpxml.parser.impl.pojo;
import io.github.dumijdev.dpxml.exception.UnPojolizableException;
import io.github.dumijdev.dpxml.model.Node;
import io.github.dumijdev.dpxml.parser.Nodilizer;
import io.github.dumijdev.dpxml.parser.Pojolizer;
import io.github.dumijdev.dpxml.parser.impl.node.DefaultNodilizer;
import io.github.dumijdev.dpxml.stereotype.Element;
import io.github.dumijdev.dpxml.stereotype.IgnoreElement;
import io.github.dumijdev.dpxml.stereotype.Pojolizable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.*;
import java.util.stream.Collectors;
import static io.github.dumijdev.dpxml.utils.ParserUtils.*;
public class BasicPojolizer implements Pojolizer {
private final DateTimeFormatter dateFormatter;
private final DateTimeFormatter dateTimeFormatter;
private final ThreadLocal nodilizer = ThreadLocal.withInitial(DefaultNodilizer::new);
public BasicPojolizer() {
this.dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
this.dateTimeFormatter = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd[ HH[:mm[:ss[.S][.SS][.SSS]]]]")
.toFormatter();
}
@Override
@SuppressWarnings("unchecked")
public T pojoify(String xml, Class clazz) throws Exception {
if (String.class.equals(clazz)) {
return (T) xml;
}
if (!clazz.isAnnotationPresent(Pojolizable.class)) {
throw new UnPojolizableException(clazz.getSimpleName());
}
var node = nodilizer.get().nodify(xml);
return pojoify(node, clazz);
}
@Override
public T pojoify(Node node, Class clazz) throws Exception {
var instance = clazz.getDeclaredConstructor().newInstance();
for (var field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(IgnoreElement.class) || !field.trySetAccessible())
continue;
var name = getName(field);
if (isPrimitive(field.getType())) {
var child = node.child(name);
var value = convertValue(child.content(), field.getType());
if (Objects.nonNull(value))
field.set(instance, value);
} else if (isCollection(field.getType())) {
var parameterizedType = (ParameterizedType) field.getGenericType();
var actualTypeArgument = Class.forName(parameterizedType.getActualTypeArguments()[0].getTypeName());
Collection