Example usage for javax.xml.bind Unmarshaller unmarshal

List of usage examples for javax.xml.bind Unmarshaller unmarshal

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller unmarshal.

Prototype

public <T> JAXBElement<T> unmarshal(javax.xml.stream.XMLEventReader reader, Class<T> declaredType)
        throws JAXBException;

Source Link

Document

Unmarshal root element to JAXB mapped declaredType and return the resulting content tree.

Usage

From source file:com.netflix.subtitles.ttml.TtmlParagraphResolver.java

private static <T> T deepCopy(T object, Class<T> clazz, String packages) {
    try {// w  w w  . j av  a 2s .c  o  m
        JAXBContext jaxbContext = JAXBContext.newInstance(packages);

        //  create marshaller which disable validation step
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setEventHandler(event -> true);

        //  create unmarshaller which disable validation step
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setEventHandler(event -> true);

        JAXBElement<T> contentObject = new JAXBElement<>(new QName(clazz.getName()), clazz, object);
        return unmarshaller.unmarshal(new JAXBSource(marshaller, contentObject), clazz).getValue();
    } catch (JAXBException e) {
        throw new ParseException("Time overlaps in <p> cannot be resolved.", e);
    }
}

From source file:Main.java

public static Object parseXmlStringToBeanByJAXB(String xml, Class clase) throws Exception {

    JAXBContext context = JAXBContext.newInstance(clase);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    InputStream is = null;/*from   w  w w.  ja  va 2 s .c  om*/
    try {
        is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    if (is == null) {
        return null;
    }

    JAXBElement elm = unmarshaller.unmarshal(new StreamSource(is), clase);

    return elm.getValue();

}

From source file:com.dnastack.bob.rest.BasicTest.java

public static Object readObject(Class c, String url) throws JAXBException, MalformedURLException {
    JAXBContext jc = JAXBContext.newInstance(c);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setProperty(JAXBContextProperties.MEDIA_TYPE, "application/json");
    unmarshaller.setProperty(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
    StreamSource source = new StreamSource(url);
    JAXBElement jaxbElement = unmarshaller.unmarshal(source, c);

    return jaxbElement.getValue();
}

From source file:com.silverpeas.admin.components.Instanciateur.java

static WAComponent loadComponent(File file) throws IOException, JAXBException, XMLStreamException {
    JAXBContext context = JAXBContext.newInstance("com.silverpeas.admin.components");
    Unmarshaller unmarshaller = context.createUnmarshaller();
    InputStream in = new FileInputStream(file);
    try {/*from   ww w. j a va  2s .  c  o m*/
        return (unmarshaller.unmarshal(factory.createXMLStreamReader(in), WAComponent.class)).getValue();
    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:de.bloxel.engine.util.JAXBUtils.java

public static <T> T unmarschal(final InputStream inputStream, final Class<T> aClass) {
    try {/*from w  ww . j  a  v  a  2 s . c o  m*/
        // http://jaxb.java.net/faq/index.html#classloader
        final JAXBContext jc = JAXBContext.newInstance(getPackageCanonicalName(aClass));
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        // http://jaxb.java.net/guide/Unmarshalling_is_not_working__Help_.html
        unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
        final XMLInputFactory staxFactory = XMLInputFactory.newInstance();
        final XMLStreamReader xmlReader = staxFactory.createXMLStreamReader(inputStream);
        return unmarshaller.unmarshal(xmlReader, aClass).getValue();
    } catch (final JAXBException e) {
        throw new RuntimeException(String.format("Can't load unmarschal '%s'", aClass), e);
    } catch (final XMLStreamException e) {
        throw new RuntimeException(String.format("Can't load unmarschal '%s'", aClass), e);
    }
}

From source file:org.eclipse.mylyn.internal.hudson.core.client.RestfulHudsonClient.java

public static <T> T unmarshal(Node node, Class<T> clazz) throws JAXBException {
    JAXBContext ctx = JAXBContext.newInstance(clazz);

    Unmarshaller unmarshaller = ctx.createUnmarshaller();

    JAXBElement<T> hudsonElement = unmarshaller.unmarshal(node, clazz);
    return hudsonElement.getValue();
}

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final Vaadlets unmarshal(final Reader aReader, final Resource theSchemaResource) {
    try {/*from  w  w  w. j a  v a  2s  .  c  om*/
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            unmarshaller.setSchema(schema);
        }
        return unmarshaller
                .unmarshal(XMLInputFactory.newInstance().createXMLStreamReader(aReader), Vaadlets.class)
                .getValue();
    } catch (final JAXBException | SAXException | XMLStreamException | FactoryConfigurationError
            | IOException e) {
        throw new RuntimeException("Can't unmarschal", e);
    }
}

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>//  w  w w .j av  a  2s .  c om
 * 
 * @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;
}

From source file:eu.scape_project.tool.toolwrapper.data.components_spec.utils.Utils.java

/**
 * Method that creates a {@link Components} instance from the provided
 * component spec file, validating it against component spec XML Schema
 * /*  w w  w.  j  av a 2 s.  c o m*/
 * @param componentSpecFilePath
 *            path to the component spec file
 */
public static Components createComponents(String componentSpecFilePath) {
    Components component = null;
    File schemaFile = null;
    try {
        JAXBContext context = JAXBContext.newInstance(Components.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        // copy XML Schema from resources to a temporary location
        schemaFile = File.createTempFile("schema", null);
        FileUtils.copyInputStreamToFile(Utils.class.getResourceAsStream(COMPONENTS_SPEC_FILENAME_IN_RESOURCES),
                schemaFile);
        Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);

        // validate provided toolspec against XML Schema
        unmarshaller.setSchema(schema);

        // unmarshal it
        final FileInputStream stream = new FileInputStream(new File(componentSpecFilePath));
        try {
            component = unmarshaller.unmarshal(new StreamSource(stream), Components.class).getValue();
        } finally {
            stream.close();
        }
    } catch (JAXBException e) {
        log.error("The component spec provided doesn't validate against its schema!", e);
    } catch (SAXException e) {
        log.error("The XML Schema is not valid!", e);
    } catch (IOException e) {
        log.error("An error occured while copying the XML Schema from the resources to a temporary location!",
                e);
    } catch (Exception e) {
        log.error("An error occured!", e);
    } finally {
        if (schemaFile != null) {
            schemaFile.deleteOnExit();
        }
    }
    return component;
}

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

public static <T> T unmarshal(final Class<T> clazz, final InputSource inputSource,
        final JAXBContext jaxbContext, final boolean validate) {
    final Unmarshaller um = getUnmarshallerFor(clazz, jaxbContext, validate);

    LogUtils.tracef(clazz, "unmarshalling class %s from input source %s with unmarshaller %s",
            clazz.getSimpleName(), inputSource, um);
    try {/*ww  w.j a  va  2  s . com*/
        final XMLFilter filter = getXMLFilterForClass(clazz);
        final SAXSource source = new SAXSource(filter, inputSource);

        um.setEventHandler(new LoggingValidationEventHandler(clazz));

        final JAXBElement<T> element = um.unmarshal(source, clazz);
        return element.getValue();
    } catch (final SAXException e) {
        throw EXCEPTION_TRANSLATOR.translate("creating an XML reader object", e);
    } catch (final JAXBException e) {
        throw EXCEPTION_TRANSLATOR.translate("unmarshalling an object (" + clazz.getSimpleName() + ")", e);
    }
}