All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.squeakysand.commons.xml.JaxbHelper Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2010-2012 Craig S. Dickson (http://craigsdickson.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.squeakysand.commons.xml;

import com.squeakysand.commons.lang.StringUtils;
import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.squeakysand.commons.lang.ToStringHelper;

import org.apache.commons.io.FileUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JaxbHelper {

    private static final Logger LOG = LoggerFactory.getLogger(JaxbHelper.class);

    public static void marshallToFile(Object rootElement, File file, String schemaLocation) throws JAXBException, IOException {
        LOG.debug("marshalling {}, with class type {}, to file {}", new Object[] { ToStringHelper.toString(rootElement),
                ToStringHelper.toString(rootElement.getClass()), ToStringHelper.toString(file) });
        File dir = file.getParentFile();
        FileUtils.forceMkdir(dir);
        if (!dir.exists() || !dir.isDirectory() || !dir.canWrite()) {
            throw new IOException(String.format("directory '%s' either does not exist or is not writeable", dir));
        }
        JAXBContext jc = JAXBContext.newInstance(rootElement.getClass());
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        if (StringUtils.isNotNullOrEmpty(schemaLocation)) {
            marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation);
        }
        marshaller.marshal(rootElement, file);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy