1 /*
2 * Copyright (C) 2021 INRAE AgroClim
3 *
4 * This file is part of Indicators.
5 *
6 * Indicators is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * Indicators is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with Indicators. If not, see <http://www.gnu.org/licenses/>.
18 */
19 package fr.inrae.agroclim.indicators.xml;
20
21 import jakarta.xml.bind.JAXBContext;
22 import jakarta.xml.bind.JAXBException;
23 import jakarta.xml.bind.Marshaller;
24 import lombok.Setter;
25
26 /**
27 * Builder pattern to configure JAXB Marshaller.
28 *
29 * Last changed : $Date$
30 *
31 * @author $Author$
32 * @version $Revision$
33 */
34 public final class MarshallerBuilder {
35
36 /**
37 * DOCTYPE header for the XML file.
38 */
39 @Setter
40 private String docType;
41
42 /**
43 * The class related to the object to serialize.
44 */
45 @Setter
46 private Class<?>[] classesToBeBound;
47
48 /**
49 * Property used to specify the xsi:noNamespaceSchemaLocation attribute value in the marshalled XML output.
50 */
51 @Setter
52 private String noNamespaceSchemaLocation;
53
54 /**
55 * @return JAXB marshaller
56 * @throws JAXBException error while getting context, creating marshaller or setting properties
57 */
58 public Marshaller build() throws JAXBException {
59 final JAXBContext jaxbContext = JAXBContext.newInstance(classesToBeBound);
60 final Marshaller marshaller = jaxbContext.createMarshaller();
61 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
62 marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
63 if (docType != null) {
64 marshaller.setProperty("org.glassfish.jaxb.xmlHeaders", docType + "\n");
65 }
66 if (noNamespaceSchemaLocation != null) {
67 marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, noNamespaceSchemaLocation);
68 }
69 return marshaller;
70 }
71
72 }