package de.ivu.elect.jee.entity.customdata;

import java.io.Writer;

import org.apache.commons.io.output.StringBuilderWriter;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.CompactWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

public class XStreamCustomDataSerializer implements CustomDataSerializer {

  private static final XStream XSTREAM;

  static {
    XSTREAM = new XStream(new XppDriver() {
      @Override
      public HierarchicalStreamWriter createWriter(Writer out) {
        return new CompactWriter(out, getNameCoder());
      }
    });
    // ELECT-5949
    XStream.setupDefaultSecurity(XSTREAM);
    XSTREAM.allowTypesByWildcard(new String[]{"de.ivu.**"});
    XSTREAM.omitField(DefaultCustomData.class, "storageEntity");
    XSTREAM.omitField(DefaultCustomData.class, "technicalEntity");
    XSTREAM.ignoreUnknownElements(); // ELECT-13195
  }

  @Override
  public String serializeCustomData(Object customData) {
    // return XSTREAM.toXML(customData);
    // StringBuilder nutzen
    StringBuilderWriter writer = new StringBuilderWriter(100);
    XSTREAM.toXML(customData, writer);
    return writer.toString();
  }

  @Override
  public Object deserializeCustomData(String string) {
    return XSTREAM.fromXML(string);
  }

}
