Example usage for javax.xml.bind JAXBContext newInstance

List of usage examples for javax.xml.bind JAXBContext newInstance

Introduction

In this page you can find the example usage for javax.xml.bind JAXBContext newInstance.

Prototype

public static JAXBContext newInstance(Class<?>... classesToBeBound) throws JAXBException 

Source Link

Document

Create a new instance of a JAXBContext class.

Usage

From source file:Main.java

/**
 * Saves the object to the file.//from w  ww.java 2 s. com
 *
 * @param <T> the object type.
 * @param path the XML file.
 * @param object the object to be saved.
 */
public static <T> void saveObject(Path path, T object) {

    if (path == null || object == null) {
        throw new RuntimeException("The path to file or object is null!");
    }

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(object, path.toFile());
    } catch (Exception ex) {
        throw new RuntimeException("Error saving the object to path " + path.toString(), ex);
    }
}

From source file:Main.java

/**
 * //from w  w w.j  a  v  a2s . co  m
 * @param object
 * @return
 * @throws JAXBException
 */
public static String pojoToXml(Object object) throws JAXBException {

    JAXBContext context = JAXBContext.newInstance(object.getClass());
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    // marshaller.setProperty(Marshaller.JAXB_ENCODING, "U");
    StringWriter writer = new StringWriter();
    marshaller.marshal(object, writer);
    String xmlData = writer.toString();
    return xmlData;
}

From source file:Main.java

/**
 * Loads the object from the file./*ww  w  . j a  v  a  2 s.  co  m*/
 *
 * @param <T> the object type.
 * @param path the XML file.
 * @param clazz the class of the object.
 * @return the corresponding object.
 */
public static <T> T loadObject(Path path, Class<T> clazz) {
    T result;
    if (path == null || clazz == null) {
        throw new RuntimeException("The path to file or class is null!");
    }

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        result = (T) jaxbUnmarshaller.unmarshal(path.toFile());
    } catch (Exception ex) {
        throw new RuntimeException("Error loading the xml from path " + path.toString(), ex);
    }
    return result;
}

From source file:se.inera.intyg.intygstjanst.web.integration.util.SendMessageToCareUtil.java

public static SendMessageToCareType getSendMessageToCareTypeFromFile(String fileName) throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(SendMessageToCareType.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    return unmarshaller.unmarshal(new StreamSource(new ClassPathResource(fileName).getInputStream()),
            SendMessageToCareType.class).getValue();
}

From source file:Main.java

/**
 * XML to Object/*  w  w  w. j a v a  2s .c o m*/
 * @param <T>
 * @param clazz
 * @param reader
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> T convertToObject(Class<T> clazz, Reader reader) {
    try {
        if (!uMap.containsKey(clazz)) {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            uMap.put(clazz, unmarshaller);
        }
        return (T) uMap.get(clazz).unmarshal(reader);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static <T> void serialize(T object, OutputStream out) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(object, out);
}

From source file:Main.java

/**
 * Unmarshal./*from  w  ww.  j ava 2 s. c  o m*/
 *
 * @param inputSource the input source
 * @param clazz the clazz
 * @return the object
 * @throws JAXBException the jAXB exception
 */
public static Object unmarshal(InputSource inputSource, Class<?> clazz) throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(clazz);
    Unmarshaller u = jc.createUnmarshaller();
    ValidationEventCollector vec = new ValidationEventCollector();
    u.setEventHandler(vec);
    Object o1 = u.unmarshal(inputSource);
    return o1;

}

From source file:Main.java

/**
 * Unmarshal XML data from XML string using XSD string and return the resulting JAXB content tree
 *
 * @param dummyCtxObject//from  www.  j a  v a2 s.  c o  m
 *            Dummy contect object for creating related JAXB context
 * @param strXML
 *            XML
 * @param strXSD
 *            XSD
 * @return resulting JAXB content tree
 * @throws Exception
 *             in error case
 */
public static Object doUnmarshalling(Object dummyCtxObject, String strXML, String strXSD) throws Exception {
    if (dummyCtxObject == null) {
        throw new RuntimeException("No dummy context objekt (null)!");
    }
    if (strXML == null) {
        throw new RuntimeException("No XML document (null)!");
    }
    if (strXSD == null) {
        throw new RuntimeException("No XSD document (null)!");
    }

    Object unmarshalledObject = null;
    StringReader readerXSD = null;
    StringReader readerXML = null;

    try {
        JAXBContext jaxbCtx = JAXBContext.newInstance(dummyCtxObject.getClass().getPackage().getName());
        Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
        readerXSD = new StringReader(strXSD);
        readerXML = new StringReader(strXML);

        javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory
                .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new StreamSource(readerXSD));
        unmarshaller.setSchema(schema);

        unmarshalledObject = unmarshaller.unmarshal(new StreamSource(readerXML));
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error);
        throw e;
    } finally {
        if (readerXSD != null) {
            readerXSD.close();
            readerXSD = null;
        }
        if (readerXML != null) {
            readerXML.close();
            readerXML = null;
        }
    }

    return unmarshalledObject;
}

From source file:Main.java

/**
 * Unmarshal XML data from XML file path using XSD from file path and return the resulting JAXB content tree
 *
 * @param dummyCtxObject/*from   w  ww. j  a  v  a 2 s .  c  om*/
 *            Dummy contect object for creating related JAXB context
 * @param strXMLFilePath
 *            XML file path
 * @param strXSDFilePath
 *            XSD file path
 * @return resulting JAXB content tree
 * @throws Exception
 *             in error case
 */
public static Object doUnmarshallingFromFiles(Object dummyCtxObject, String strXMLFilePath,
        String strXSDFilePath) throws Exception {
    if (dummyCtxObject == null) {
        throw new RuntimeException("No dummy context object (null)!");
    }
    if (strXMLFilePath == null) {
        throw new RuntimeException("No XML file path (null)!");
    }
    if (strXSDFilePath == null) {
        throw new RuntimeException("No XSD file path (null)!");
    }

    Object unmarshalledObject = null;

    FileInputStream fis = null;
    try {
        JAXBContext jaxbCtx = JAXBContext.newInstance(dummyCtxObject.getClass().getPackage().getName());
        Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
        // unmarshaller.setValidating(true);
        javax.xml.validation.Schema schema = javax.xml.validation.SchemaFactory
                .newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new java.io.File(strXSDFilePath));
        unmarshaller.setSchema(schema); // register schema for validation

        fis = new FileInputStream(strXMLFilePath);
        unmarshalledObject = unmarshaller.unmarshal(fis);
    } catch (Exception e) {
        //            Logger.XMLEval.logState("Unmarshalling failed: " + e.getMessage(), LogLevel.Error);
        throw e;
    } finally {
        if (fis != null) {
            fis.close();
            fis = null;
        }
    }

    return unmarshalledObject;
}

From source file:Main.java

/**
 * Parse XML using JAXB and a model class.
 * //from w w  w  .j av  a  2  s.c  o m
 * @param in an input stream
 * @return the requested object
 * @param cls the root class
 * @throws JAXBException thrown on an error
 */
@SuppressWarnings("unchecked")
public static <T> T parseJaxb(Class<T> cls, InputStream in) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(cls);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    Unmarshaller um = context.createUnmarshaller();
    return (T) um.unmarshal(in);
}