org.timebench.util.xml.MapAdapters Maven / Gradle / Ivy
Show all versions of util Show documentation
package org.timebench.util.xml;
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlAdapter;
/**
* generic mapping of a HashMap for JAXB (experimental).
*
* Disclaimer: This is as general as I managed to write this class, however:
*
* It will probably not work with keys or values
* that are supported by JAXB out of the box (e.g., {@link java.awt.Color}).
*
* Generated XML declares xs and xsi namespaces multiple times,
* though it is enough to declare them once in the root element.
*
* A workaround is to use this class as a template for an adapter
* and a marshalled form without generics (e.g.,
* visuexplore.persistence.CategoricalPaletteXmlAdapter)
*
* @author Alex Rind
*
*/
public class MapAdapters {
/*
* insert subclasses if needed; the subclasses are not actually necessary --
* JaxbDemo moreData also works with the generic class
*/
/**
* @author Alex Rind
*
*/
public static class StringStringLinkedHashMapXmlAdapter extends
LinkedHashMapXmlAdapter {
}
/**
* @author Alex Rind
*
*/
public static class IntegerStringLinkedHashMapXmlAdapter extends
LinkedHashMapXmlAdapter {
}
/**
* @author Alex Rind
*
* @param
* @param
*/
public static class LinkedHashMapXmlAdapter extends
XmlAdapter, LinkedHashMap> {
@Override
public MarshalledForm marshal(LinkedHashMap v)
throws Exception {
MarshalledForm result = new MarshalledForm();
for (Map.Entry var : v.entrySet()) {
result.entries.add(new KeyValuePair(var.getKey(), var
.getValue()));
}
return result;
}
@Override
public LinkedHashMap unmarshal(MarshalledForm v)
throws Exception {
LinkedHashMap result = new LinkedHashMap();
for (KeyValuePair var : v.entries) {
result.put(var.key, var.value);
}
return result;
}
}
/**
* @author Alex Rind
*
* @param
* @param
*/
static class MarshalledForm {
@XmlElement(name = "option")
LinkedList> entries = new LinkedList>();
}
/**
* @author Alex Rind
*
* @param
* @param
*/
static class KeyValuePair {
@XmlElement
// @XmlAttribute(required = true)
K key;
@XmlElement
// @XmlValue
V value;
public KeyValuePair() {
}
KeyValuePair(K key, V value) {
this.key = key;
this.value = value;
}
}
}