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.

Revisions

  1. paflopes created this gist Jun 5, 2019.
    43 changes: 43 additions & 0 deletions JAXBElementReaderConverter.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    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);
    }
    }