Skip to content

Instantly share code, notes, and snippets.

@paflopes
Created June 5, 2019 03:39
Show Gist options
  • Select an option

  • Save paflopes/eb2e0772da8843626be84ad1fb80ccb5 to your computer and use it in GitHub Desktop.

Select an option

Save paflopes/eb2e0772da8843626be84ad1fb80ccb5 to your computer and use it in GitHub Desktop.
package com.bideafactory.wom.usageconsuption.converter;
import org.bson.Document;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import java.util.LinkedHashMap;
import java.util.List;
@ReadingConverter
public class JAXBElementReaderConverter implements Converter<Document, JAXBElement> {
private final MongoConverter converter;
public JAXBElementReaderConverter(MongoConverter converter) {
this.converter = converter;
}
@Override
@SuppressWarnings("unchecked")
public JAXBElement convert(Document dbObject) {
Class declaredType, scope;
Document qName = (Document) dbObject.get("name");
QName name = new QName(qName.getString("namespaceURI"), qName.getString("localPart"), qName.getString("prefix"));
Object rawValue = dbObject.get("value");
try {
declaredType = Class.forName((String) dbObject.get("declaredType"));
} catch (ClassNotFoundException e) {
if (rawValue.getClass().isArray()) declaredType = List.class;
else declaredType = LinkedHashMap.class;
}
try {
scope = Class.forName((String) dbObject.get("scope"));
} catch (ClassNotFoundException e) {
scope = JAXBElement.GlobalScope.class;
}
Object value = rawValue instanceof Document ? converter.read(declaredType, (Document) rawValue) : rawValue;
return new JAXBElement(name, declaredType, scope, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment