View Javadoc
1   package cn.home1.oss.lib.common;
2   
3   import com.sun.org.apache.xerces.internal.dom.TextImpl;
4   
5   import lombok.NoArgsConstructor;
6   
7   import org.w3c.dom.Node;
8   
9   import java.util.Map;
10  import java.util.stream.Collectors;
11  
12  import javax.xml.bind.JAXBElement;
13  import javax.xml.bind.annotation.adapters.XmlAdapter;
14  import javax.xml.namespace.QName;
15  
16  @NoArgsConstructor
17  public class JaxbMapAdapter extends XmlAdapter<JaxbMapWrapper, Map<String, String>> {
18  
19    @Override
20    public Map<String, String> unmarshal(final JaxbMapWrapper wrapper) throws Exception {
21      return wrapper.getElements().stream().collect( //
22        Collectors.toMap( //
23          k -> {
24            Node node = (Node) k;
25            return node.getLocalName();
26          },  //
27          v -> {
28            Node node = (Node) v;
29            TextImpl child = (TextImpl) node.getFirstChild();
30            return child.getData();
31          }));
32    }
33  
34    @Override
35    public JaxbMapWrapper marshal(final Map<String, String> map) throws Exception {
36      final JaxbMapWrapper wrapper = new JaxbMapWrapper();
37      map.forEach((key, value) -> //
38        wrapper.getElements().add(new JAXBElement<>(new QName(key), String.class, value)));
39  
40      return wrapper;
41    }
42  }