Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * Copyright (c) 2011, 2014 Eurotech and/or its affiliates
 *
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Eurotech
 */

import java.io.StringWriter;
import java.io.Writer;

import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;

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

import javax.xml.bind.ValidationEvent;
import javax.xml.bind.util.ValidationEventCollector;

public class Main {
    @SuppressWarnings("rawtypes")
    private static Map<Class, JAXBContext> s_contexts = new HashMap<Class, JAXBContext>();

    public static String marshal(Object object) throws JAXBException {
        StringWriter sw = new StringWriter();
        marshal(object, sw);
        return sw.toString();
    }

    @SuppressWarnings("rawtypes")
    public static void marshal(Object object, Writer w) throws JAXBException {
        Class clazz = object.getClass();
        JAXBContext context = s_contexts.get(clazz);
        if (context == null) {
            context = JAXBContext.newInstance(clazz);
            s_contexts.put(clazz, context);
        }

        ValidationEventCollector valEventHndlr = new ValidationEventCollector();
        Marshaller marshaller = context.createMarshaller();
        marshaller.setSchema(null);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setEventHandler(valEventHndlr);

        try {
            marshaller.marshal(object, w);
        } catch (Exception e) {
            if (e instanceof JAXBException) {
                throw (JAXBException) e;
            } else {
                throw new MarshalException(e.getMessage(), e);
            }
        }
        if (valEventHndlr.hasEvents()) {
            for (ValidationEvent valEvent : valEventHndlr.getEvents()) {
                if (valEvent.getSeverity() != ValidationEvent.WARNING) {
                    // throw a new Marshall Exception if there is a parsing error
                    throw new MarshalException(valEvent.getMessage(), valEvent.getLinkedException());
                }
            }
        }
    }
}