Skip to content

Instantly share code, notes, and snippets.

@AlexGabor
Created April 1, 2016 12:05
Show Gist options
  • Save AlexGabor/1725effa745bbd0acf601b4db8780788 to your computer and use it in GitHub Desktop.
Save AlexGabor/1725effa745bbd0acf601b4db8780788 to your computer and use it in GitHub Desktop.
package ro.oneandonly.bookstore.util;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import ro.oneandonly.bookstore.domain.BaseEntity;
import ro.oneandonly.bookstore.domain.Book;
import ro.oneandonly.bookstore.domain.validators.BookStoreException;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.*;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class XmlParser<T> {
private String filename;
public XmlParser(String fileName) {
this.filename = fileName;
}
public void save(T entity) throws JDOMException, IOException, IllegalAccessException, NoSuchFieldException {
SAXBuilder saxBuilder = new SAXBuilder();
Document document = saxBuilder.build(filename);
Element rootElement = document.getRootElement();
serializeField(rootElement, entity);
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(document, new FileWriter(filename));
}
private void serializeField(Element rootElement, Object entity) throws IllegalAccessException, NoSuchFieldException {
Element entityElement = new Element(entity.getClass().getSimpleName());
entityElement.setAttribute("type", entity.getClass().getTypeName());
rootElement.addContent(entityElement);
Field idField = entity.getClass().getSuperclass().getDeclaredField("id");
idField.setAccessible(true);
Element id = new Element(idField.getName());
id.setAttribute("type",idField.getType().getName());
id.setText(idField.get(entity).toString());
entityElement.addContent(id);
Field[] declaredFields = entity.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
Element element = new Element(field.getName());
if (Collection.class.isAssignableFrom(field.getType())) {
element.setAttribute("type", field.get(entity).getClass().getTypeName());
ParameterizedType genericType = (ParameterizedType) field.getGenericType();
element.setAttribute("parameter", genericType.getActualTypeArguments()[0].getTypeName());
Collection<?> collection = (Collection<?>) field.get(entity);
collection.forEach(e -> {
try {
serializeField(element, field.get(entity));
} catch (IllegalAccessException | NoSuchFieldException exception) {
throw new BookStoreException(exception.getMessage(), exception);
}
});
} else {
element.setAttribute("type", field.getType().getName());
element.setText(field.get(entity).toString());
}
entityElement.addContent(element);
}
}
public List<T> loadEntities() throws JDOMException, IOException {
SAXBuilder saxBuilder = new SAXBuilder();
Document document = saxBuilder.build(filename);
Element rootElement = document.getRootElement();
return rootElement.getChildren().stream().map(this::<T>deserializeField).collect(Collectors.toList());
}
private <E> E deserializeField(Element element) {
String type = element.getAttributeValue("type");
E entity;
Class entityClass;
try {
entityClass = Class.forName(type);
entity = (E) entityClass.newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
throw new BookStoreException(e.getMessage(), e);
}
element.getChildren().forEach(e -> {
Field field;
try {
field = entity.getClass().getDeclaredField(e.getName());
} catch (NoSuchFieldException exception) {
try {
field = entity.getClass().getSuperclass().getDeclaredField(e.getName());
} catch (NoSuchFieldException exception1) {
throw new BookStoreException(exception1.getMessage(), exception1);
}
}
field.setAccessible(true);
try {
Class type1 = Class.forName(e.getAttributeValue("type"));
if (Objects.equals(e.getAttributeValue("type"), "java.lang.Object"))
field.set(entity,Long.parseLong(e.getValue()));
else if (Integer.class.isAssignableFrom(type1))
field.set(entity, Integer.parseInt(e.getValue()));
else if (Collection.class.isAssignableFrom(type1)) {
// Class parameter = Class.forName(e.getAttributeValue("parameter")).;
Collection<Book> collection = (Collection<Book>) type1.newInstance();
element.getChildren().stream().map(this::deserializeField).forEach(value-> {
try {
//Class parameter = Class.forName(e.getAttributeValue("parameter"));
Method add = type1.getDeclaredMethod("add", Class.forName(e.getAttributeValue("parameter")));
add.invoke(collection, value);
} catch (NoSuchMethodException | ClassNotFoundException | IllegalAccessException | InvocationTargetException exception) {
throw new BookStoreException(exception.getMessage(), exception);
}
});
field.set(entity, collection);
}
else
field.set(entity, e.getValue());
} catch (IllegalAccessException | ClassNotFoundException | InstantiationException exception) {
throw new BookStoreException(exception.getMessage(), exception);
}
});
return entity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment