Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import java.io.Reader;

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

import javax.xml.bind.Unmarshaller;

import org.w3c.dom.Node;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T> T unmarshall(Class<T> clazz, Node node, Unmarshaller.Listener listener) throws JAXBException {
        Unmarshaller unmarshaller = getUnmarshaller(clazz, listener);
        return (T) unmarshaller.unmarshal(node);
    }

    @SuppressWarnings("unchecked")
    public static <T> T unmarshall(Class<T> clazz, Reader reader, Unmarshaller.Listener listener)
            throws JAXBException {
        Unmarshaller unmarshaller = getUnmarshaller(clazz, listener);
        return (T) unmarshaller.unmarshal(reader);
    }

    @SuppressWarnings("unchecked")
    public static <T> T unmarshall(Class<T> clazz, InputStream inputStream, Unmarshaller.Listener listener)
            throws JAXBException {
        Unmarshaller unmarshaller = getUnmarshaller(clazz, listener);
        return (T) unmarshaller.unmarshal(inputStream);
    }

    public static <T> T unmarshall(Class<T> clazz, String filename, Unmarshaller.Listener listener)
            throws JAXBException, IOException {
        FileInputStream is = null;
        T object;
        try {
            is = new FileInputStream(filename);
            object = unmarshall(clazz, is, listener);
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return object;
    }

    private static <T> Unmarshaller getUnmarshaller(Class<T> clazz, Unmarshaller.Listener listener)
            throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(clazz);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        if (listener != null) {
            unmarshaller.setListener(listener);
        }
        return unmarshaller;
    }
}