/******************************************************************************* * Copyright 2019 Graz University of Technology * MOA ZS has been developed in a cooperation between EGIZ * and Graz University of Technology. * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/news/understanding-eupl-v12 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * * This product combines work with different licenses. See the "NOTICE" text * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ package at.gv.egiz.moazs.scheme; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import javax.xml.transform.Result; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.InputStream; import java.io.StringWriter; import java.util.HashMap; /** * @author xerx593 * Source: https://stackoverflow.com/questions/44676532/how-to-use-spring-to-marshal-and-unmarshal-xml */ public class Marshaller { private final Jaxb2Marshaller jaxbMarshaller; public Marshaller(boolean isMzs) { this.jaxbMarshaller = new Jaxb2Marshaller(); jaxbMarshaller.setClassesToBeBound( at.gv.zustellung.app2mzs.xsd.ObjectFactory.class, at.gv.zustellung.app2mzs.xsd.persondata.ObjectFactory.class, at.gv.zustellung.msg.xsd.ObjectFactory.class); var map = new HashMap(); map.put(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true); map.put("com.sun.xml.bind.namespacePrefixMapper", new MoaZSPrefixMapper(isMzs)); jaxbMarshaller.setMarshallerProperties(map); } public String marshallXml(final T obj) { if (obj == null) { return "null"; } StringWriter sw = new StringWriter(); Result result = new StreamResult(sw); jaxbMarshaller.marshal(obj, result); return sw.toString(); } public T unmarshallXml(final InputStream xml) { return (T) jaxbMarshaller.unmarshal(new StreamSource(xml)); } }