001package com.identityworksllc.iiq.common.vo;
002
003import com.fasterxml.jackson.core.JsonGenerator;
004import com.fasterxml.jackson.databind.SerializerProvider;
005import com.fasterxml.jackson.databind.ser.std.StdSerializer;
006import com.identityworksllc.iiq.common.Utilities;
007import sailpoint.api.SailPointContext;
008import sailpoint.api.SailPointFactory;
009import sailpoint.object.Script;
010import sailpoint.tools.GeneralException;
011import sailpoint.tools.xml.AbstractXmlObject;
012import sailpoint.tools.xml.XMLClass;
013import sailpoint.tools.xml.XMLObjectFactory;
014
015import java.io.IOException;
016import java.nio.charset.Charset;
017import java.util.Base64;
018import java.util.Date;
019import java.util.List;
020import java.util.Map;
021
022/**
023 * A Jackson serializer implementation for any object that can be serialized
024 * to XML by IIQ's XML serializer. The output will be a JSON object with a
025 * 'type' (the fully qualified class name) and an 'xml' (the serialized XML
026 * of the input object).
027 */
028public class IIQObjectSerializer extends StdSerializer<Object> {
029    protected IIQObjectSerializer() {
030        this(null);
031    }
032
033    public IIQObjectSerializer(Class<Object> t) {
034        super(t);
035    }
036
037    @Override
038    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
039        if (value == null || value instanceof AbstractXmlObject || value instanceof Script || value instanceof Map || value instanceof List || value instanceof String || value instanceof Date) {
040            gen.writeStartObject();
041
042            if (value != null) {
043                String xml = XMLObjectFactory.getInstance().toXml(value);
044                gen.writeStringField("xml", xml);
045            } else {
046                gen.writeStringField("xml", null);
047            }
048
049            String xmlClass;
050
051            if (value == null || value instanceof AbstractXmlObject || value instanceof Script) {
052                // Returns string 'null' if the input is null
053                xmlClass = Utilities.safeClassName(value);
054            } else if (value instanceof Map) {
055                xmlClass = "java.util.Map";
056            } else if (value instanceof List) {
057                xmlClass = "java.util.List";
058            } else if (value instanceof Date) {
059                xmlClass = Date.class.getName();
060            } else {
061                xmlClass = String.class.getName();
062            }
063
064            gen.writeStringField("type", xmlClass);
065
066            gen.writeEndObject();
067        } else {
068            throw new IOException("Input type must be serializable by IIQ XMLObjectFactory");
069        }
070    }
071}