Example usage for javax.xml.bind JAXBContext createUnmarshaller

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

Introduction

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

Prototype

public abstract Unmarshaller createUnmarshaller() throws JAXBException;

Source Link

Document

Create an Unmarshaller object that can be used to convert XML data into a java content tree.

Usage

From source file:main.java.refinement_class.Useful.java

public static boolean validation(String schema_file, String xml_file) {
    Object obj = null;//from w w w.j  av a  2 s .co  m

    // create a JAXBContext capable of handling classes generated into
    // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class );

    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance();

        // create an Unmarshaller
        Unmarshaller u = jc.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

        try {

            javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file));

            u.setSchema((javax.xml.validation.Schema) schema);
            u.setEventHandler(new ValidationEventHandler() {
                // allow unmarshalling to continue even if there are errors
                public boolean handleEvent(ValidationEvent ve) {
                    // ignore warnings
                    if (ve.getSeverity() != ValidationEvent.WARNING) {
                        ValidationEventLocator vel = ve.getLocator();
                        System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber()
                                + "]:" + ve.getMessage());
                    }
                    return true;
                }
            });
        } catch (org.xml.sax.SAXException se) {
            System.out.println("Unable to validate due to following error.");
            se.printStackTrace();
            LOG.error(se.toString());
        }

    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        LOG.error(e.toString());
    }

    return true;

}

From source file:main.java.refinement_class.Useful.java

public static Object unmashal(String schema_file, String xml_file, Class c) {
    Object obj = null;/*from   ww  w.ja  v a 2 s.c  o  m*/
    try {

        // create a JAXBContext capable of handling classes generated into
        // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class );

        JAXBContext jc = JAXBContext.newInstance(c);

        // create an Unmarshaller
        Unmarshaller u = jc.createUnmarshaller();

        SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);

        try {

            //                LOG.info("\n\n  XX -->> Schema file: " + schema_file);
            //                LOG.info("\n\n  XX -->> xml_file file: " + xml_file);
            //++
            javax.xml.validation.Schema schema;
            if (schema_file.contains("/tmp/")) {
                schema = sf.newSchema(new File(schema_file));
            } else {
                URL urlSchema = getUrl(H2mserviceImpl.class, schema_file);
                //                    LOG.info("\n\n  XX -->> urlSchema: " + urlSchema.getPath());
                schema = sf.newSchema(urlSchema);
            }
            //--
            //javax.xml.validation.Schema schema =  sf.newSchema(new File(schema_file));
            // ++

            u.setSchema((javax.xml.validation.Schema) schema);
            u.setEventHandler(new ValidationEventHandler() {
                // allow unmarshalling to continue even if there are errors
                public boolean handleEvent(ValidationEvent ve) {
                    // ignore warnings
                    if (ve.getSeverity() != ValidationEvent.WARNING) {
                        ValidationEventLocator vel = ve.getLocator();
                        System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber()
                                + "]:" + ve.getMessage());
                    }
                    return true;
                }
            });
        } catch (org.xml.sax.SAXException se) {
            System.out.println("Unable to validate due to following error.");
            se.printStackTrace();
            LOG.error("===>[1]ERROR Unmashaling \n\n" + se.toString());
            LOG.error(Useful.getStackTrace(se));
        } catch (Exception e) {
            LOG.error("===>[2]ERROR Unmashaling \n\n" + e.toString());
            LOG.error(Useful.getStackTrace(e));
        }

        if (xml_file.contains("/tmp/")) {
            obj = u.unmarshal(new File(xml_file));
        } else {
            URL url_xml_file = getUrl(H2mserviceImpl.class, xml_file);
            LOG.info("\n\n  XX -->> url_xml_file: " + url_xml_file.getPath());
            obj = u.unmarshal(url_xml_file);
        }

        //--
        //obj = u.unmarshal( new File( xml_file));

        //++

        // even though document was determined to be invalid unmarshalling,
        // marshal out result.
        //           System.out.println("");
        //         System.out.println("Still able to marshal invalid document");
        //       javax.xml.bind.Marshaller m = jc.createMarshaller();
        // m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
        //     m.marshal(poe, System.out);
    } catch (UnmarshalException ue) {
        // The JAXB specification does not mandate how the JAXB provider
        // must behave when attempting to unmarshal invalid XML data.
        // those cases, the JAXB provider is allowed to terminate the
        // call to unmarshal with an UnmarshalException.
        System.out.println("Caught UnmarshalException");
        LOG.error("===>[3]ERROR Unmashaling \n\n" + ue.toString());
    } catch (JAXBException je) {
        je.printStackTrace();
        LOG.error("===>[4]ERROR Unmashaling \n\n" + je.toString());
        LOG.error(Useful.getStackTrace(je));
    } catch (Exception e) {
        LOG.error("===>[5]ERROR Unmashaling \n\n" + e.toString());
        LOG.error(Useful.getStackTrace(e));
    }

    if (obj == null) {
        LOG.error("===>[6]ERROR Unmashaling Object NULL");
    }
    return obj;
}

From source file:com.hpe.application.automation.tools.octane.executor.UFTTestDetectionService.java

public static UFTTestDetectionResult readDetectionResults(Run run) {

    File file = getReportXmlFile(run);
    try {/*w  w w  . ja  v a 2  s . c  om*/
        JAXBContext context = JAXBContext.newInstance(UFTTestDetectionResult.class);
        Unmarshaller m = context.createUnmarshaller();
        return (UFTTestDetectionResult) m.unmarshal(new FileReader(file));
    } catch (JAXBException | FileNotFoundException e) {
        return null;
    }
}

From source file:org.apache.directory.fortress.core.rest.RestUtils.java

/**
 * Unmarshall the XML response into its associated Java objects.
 *
 * @param szResponse//ww  w  .j ava2 s . co m
 * @return FortResponse
 * @throws RestException
 */
public static FortResponse unmarshall(String szResponse) throws RestException {
    FortResponse response;
    try {
        // Create a JAXB context passing in the class of the object we want to marshal/unmarshal
        final JAXBContext context = cachedJaxbContext.getJaxbContext(FortResponse.class);

        // Create the unmarshaller, that will transform the XML back into an object
        final Unmarshaller unmarshaller = context.createUnmarshaller();
        response = (FortResponse) unmarshaller.unmarshal(new StringReader(szResponse));
    } catch (JAXBException je) {
        String error = "unmarshall caught JAXBException=" + je;
        throw new RestException(GlobalErrIds.REST_UNMARSHALL_ERR, error, je);
    }
    return response;
}

From source file:org.apache.falcon.regression.core.util.Util.java

/**
 * Converts service response to api result form.
 * @param response service response/*from  ww  w .  ja  va  2s. c  o  m*/
 * @return api result
 * @throws JAXBException
 */
public static APIResult parseResponse(ServiceResponse response) throws JAXBException {
    if (!isXML(response.getMessage())) {
        return new APIResult(APIResult.Status.FAILED, response.getMessage());
    }
    JAXBContext jc = JAXBContext.newInstance(APIResult.class);
    Unmarshaller u = jc.createUnmarshaller();
    if (response.getMessage().contains("requestId")) {
        return (APIResult) u.unmarshal(new InputSource(new StringReader(response.getMessage())));
    } else {
        return new APIResult(response.getCode() == 200 ? APIResult.Status.SUCCEEDED : APIResult.Status.FAILED,
                response.getMessage());
    }
}

From source file:com.jkoolcloud.tnt4j.streams.configure.state.AbstractFileStreamStateHandler.java

/**
 * Loads XML persisted streamed files access state.
 *
 * @param stateFile//from  ww w .  ja  v  a2  s  .  c o  m
 *            XML file of persisted streamed files access state
 *
 * @return loaded streamed files access state
 *
 * @throws JAXBException
 *             if state unmarshaling fails
 */
private static FileAccessState unmarshal(File stateFile) throws JAXBException {
    JAXBContext jaxb = JAXBContext.newInstance(FileAccessState.class);
    final Unmarshaller unmarshaller = jaxb.createUnmarshaller();
    return (FileAccessState) unmarshaller.unmarshal(stateFile);
}

From source file:com.netxforge.oss2.core.xml.JaxbUtils.java

/**
 * Get a JAXB unmarshaller for the given object.  If no JAXBContext is provided,
 * JAXBUtils will create and cache a context for the given object.
 * @param obj The object type to be unmarshaled.
 * @param jaxbContext An optional JAXB context to create the unmarshaller from.
 * @param validate TODO/*from  w ww.  ja  v a  2  s .  c o m*/
 * @return an Unmarshaller
 */
public static Unmarshaller getUnmarshallerFor(final Object obj, final JAXBContext jaxbContext,
        boolean validate) {
    final Class<?> clazz = (Class<?>) (obj instanceof Class<?> ? obj : obj.getClass());

    Unmarshaller unmarshaller = null;

    Map<Class<?>, Unmarshaller> unmarshallers = m_unMarshallers.get();
    if (jaxbContext == null) {
        if (unmarshallers == null) {
            unmarshallers = new WeakHashMap<Class<?>, Unmarshaller>();
            m_unMarshallers.set(unmarshallers);
        }
        if (unmarshallers.containsKey(clazz)) {
            LogUtils.tracef(clazz, "found unmarshaller for %s", clazz);
            unmarshaller = unmarshallers.get(clazz);
        }
    }

    if (unmarshaller == null) {
        try {
            final JAXBContext context;
            if (jaxbContext == null) {
                context = getContextFor(clazz);
            } else {
                context = jaxbContext;
            }
            unmarshaller = context.createUnmarshaller();
        } catch (final JAXBException e) {
            throw EXCEPTION_TRANSLATOR.translate("creating XML marshaller", e);
        }
    }

    LogUtils.tracef(clazz, "created unmarshaller for %s", clazz);

    if (validate) {
        final Schema schema = getValidatorFor(clazz);
        if (schema == null) {
            LogUtils.tracef(clazz, "Validation is enabled, but no XSD found for class %s",
                    clazz.getSimpleName());
        }
        unmarshaller.setSchema(schema);
    }
    if (jaxbContext == null)
        unmarshallers.put(clazz, unmarshaller);

    return unmarshaller;
}

From source file:Main.java

/**
 *
 * @param elmnt// w  w w. j  a  v a  2s  .co m
 * @param xsltSource
 * @param cls
 * @return
 * @throws TransformerConfigurationException
 * @throws JAXBException
 * @throws TransformerException
 */
public static synchronized Object deserialize(Element elmnt, InputStream xsltSource, Class cls)
        throws TransformerConfigurationException, JAXBException, TransformerException {
    Object obj = null;
    JAXBContext jc = JAXBContext.newInstance(cls);

    if (xsltSource != null) {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;
        transformer = factory.newTransformer(new StreamSource(xsltSource));

        JAXBResult result = new JAXBResult(jc);
        transformer.transform(new DOMSource(elmnt), result);
        obj = result.getResult();
    } else {
        obj = jc.createUnmarshaller().unmarshal(elmnt);
    }
    return obj;
}

From source file:Main.java

/**
 *
 * @param source//  w  w  w  . ja  va  2  s . c  om
 * @param xsltSource
 * @param cls
 * @return
 * @throws TransformerConfigurationException
 * @throws JAXBException
 * @throws TransformerException
 */
public static synchronized Object deserialize(InputStream source, InputStream xsltSource, Class cls)
        throws TransformerConfigurationException, JAXBException, TransformerException {
    Object obj = null;
    JAXBContext jc = JAXBContext.newInstance(cls);

    if (xsltSource != null) {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;
        transformer = factory.newTransformer(new StreamSource(xsltSource));

        JAXBResult result = new JAXBResult(jc);
        transformer.transform(new StreamSource(source), result);
        obj = result.getResult();
    } else {
        obj = jc.createUnmarshaller().unmarshal(source);
    }
    return obj;
}

From source file:org.psikeds.knowledgebase.xml.impl.XMLParser.java

/**
 * Helper for parsing big XML files using JAXB in combination with StAX.<br>
 * Only XML-Elements of the specified Top-Level-Class will be parsed.<br>
 * <b>Note:</b> The XML reader will not be closed. This must be invoked by
 * the caller afterwards!<br>//from  w  w w. j a  va2 s . c  o  m
 * 
 * @param xml
 *          Reader for XML-Data
 * @param elementClass
 *          Top-Level-Class used for JAXB-Unmarshalling
 * @param handler
 *          Callback handler used to process every single found XML
 *          element (@see
 *          org.psikeds.knowledgebase.xml.KBParserCallback#handleElement
 *          (java.lang.Object))
 * @param filter
 *          EventFilter used for StAX-Parsing
 * @param numSkipped
 *          Number of Elements to be skipped,
 *          e.g. numSkipped = 1 for skipping the XML-Root-Element.
 * @return Total number of unmarshalled XML-Elements
 * @throws XMLStreamException
 * @throws JAXBException
 */
public static long parseXmlElements(final Reader xml, final Class<?> elemClazz, final KBParserCallback handler,
        final EventFilter filter, final int numSkipped) throws XMLStreamException, JAXBException {

    // init stream reader
    final XMLInputFactory staxFactory = XMLInputFactory.newInstance();
    final XMLEventReader staxReader = staxFactory.createXMLEventReader(xml);
    final XMLEventReader filteredReader = filter == null ? staxReader
            : staxFactory.createFilteredReader(staxReader, filter);

    skipXmlElements(filteredReader, numSkipped);

    // JAXB with specific top-level-class
    final JAXBContext jaxbCtx = JAXBContext.newInstance(elemClazz);
    final Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();

    // parsing und unmarshalling
    long counter = 0;
    while (filteredReader.peek() != null) {
        final Object element = unmarshaller.unmarshal(staxReader, elemClazz);
        handleElement(handler, element);
        counter++;
    }
    return counter;
}