001/*
002 * Copyright 2010-2014 Ning, Inc.
003 * Copyright 2014-2015 The Billing Project, LLC
004 *
005 * The Billing Project licenses this file to you under the Apache License, version 2.0
006 * (the "License"); you may not use this file except in compliance with the
007 * License.  You may obtain a copy of the License at:
008 *
009 *    http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
013 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
014 * License for the specific language governing permissions and limitations
015 * under the License.
016 */
017
018package com.ning.billing.recurly.model.jackson;
019
020import java.io.IOException;
021
022import javax.xml.namespace.QName;
023
024import com.ning.billing.recurly.model.RecurlyObject;
025import com.ning.billing.recurly.model.RecurlyObjects;
026
027import com.fasterxml.jackson.core.JsonGenerator;
028import com.fasterxml.jackson.databind.SerializerProvider;
029import com.fasterxml.jackson.databind.ser.std.StdSerializer;
030import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
031
032public class RecurlyObjectsSerializer<T extends RecurlyObjects<U>, U extends RecurlyObject> extends StdSerializer<T> {
033
034    private final String elementName;
035
036    public RecurlyObjectsSerializer(final Class<T> recurlyObjectsClassName, final String elementName) {
037        super(recurlyObjectsClassName);
038        this.elementName = elementName;
039    }
040
041    @Override
042    public void serialize(final T values, final JsonGenerator jgen, final SerializerProvider provider) throws IOException {
043        if (values.isEmpty()) {
044            jgen.writeStartArray();
045            jgen.writeEndArray();
046            return;
047        }
048
049        final ToXmlGenerator xmlgen = (ToXmlGenerator) jgen;
050        // Nested RecurlyObjects
051        xmlgen.getOutputContext().writeFieldName(elementName);
052        boolean firstValue = true;
053        for (final U value : values) {
054            if (firstValue) {
055                xmlgen.setNextName(new QName(null, elementName));
056            } else {
057                xmlgen.writeFieldName(elementName);
058            }
059            firstValue = false;
060
061            xmlgen.writeObject(value);
062        }
063    }
064}