MarshallerBuilder.java

/*
 * Copyright (C) 2021 INRAE AgroClim
 *
 * This file is part of Indicators.
 *
 * Indicators is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Indicators is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indicators. If not, see <http://www.gnu.org/licenses/>.
 */
package fr.inrae.agroclim.indicators.xml;

import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import lombok.Setter;

/**
 * Builder pattern to configure JAXB Marshaller.
 *
 * Last changed : $Date$
 *
 * @author $Author$
 * @version $Revision$
 */
public final class MarshallerBuilder {

    /**
     * DOCTYPE header for the XML file.
     */
    @Setter
    private String docType;

    /**
     * The class related to the object to serialize.
     */
    @Setter
    private Class<?>[] classesToBeBound;

    /**
     * Property used to specify the xsi:noNamespaceSchemaLocation attribute value in the marshalled XML output.
     */
    @Setter
    private String noNamespaceSchemaLocation;

    /**
     * @return JAXB marshaller
     * @throws JAXBException error while getting context, creating marshaller or setting properties
     */
    public Marshaller build() throws JAXBException {
        final JAXBContext jaxbContext = JAXBContext.newInstance(classesToBeBound);
        final Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        if (docType != null) {
            marshaller.setProperty("org.glassfish.jaxb.xmlHeaders", docType + "\n");
        }
        if (noNamespaceSchemaLocation != null) {
            marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, noNamespaceSchemaLocation);
        }
        return marshaller;
    }

}