Example usage for org.springframework.oxm Unmarshaller unmarshal

List of usage examples for org.springframework.oxm Unmarshaller unmarshal

Introduction

In this page you can find the example usage for org.springframework.oxm Unmarshaller unmarshal.

Prototype

Object unmarshal(Source source) throws IOException, XmlMappingException;

Source Link

Document

Unmarshal the given Source into an object graph.

Usage

From source file:org.web4thejob.orm.TypeSerailizationTest.java

@Test
public void marshallingQueryTest() throws XmlMappingException, IOException {
    final Marshaller marshaller = ContextUtil.getBean(Marshaller.class);
    Assert.assertNotNull(marshaller);/*from   ww w  .  jav  a2  s .  co m*/

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Result result = new StreamResult(out);
    final Query query1 = entityFactory.buildQuery(Master1.class);
    query1.setName("123");
    query1.setOwner(ContextUtil.getBean(SecurityService.class).getAdministratorIdentity());
    ContextUtil.getDWS().save(query1);
    marshaller.marshal(query1, result);

    final Unmarshaller unmarshaller = ContextUtil.getBean(Unmarshaller.class);
    final Query query2 = (Query) unmarshaller
            .unmarshal(new StreamSource(new ByteArrayInputStream(out.toByteArray())));

    Assert.assertEquals(query1, query2);
}

From source file:org.web4thejob.orm.TypeSerailizationTest.java

@Test
public void marshallingTest() throws XmlMappingException, IOException {
    final Marshaller marshaller = ContextUtil.getBean(Marshaller.class);
    Assert.assertNotNull(marshaller);/*w  w w . ja  v  a 2  s  . co m*/

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Result result = new StreamResult(out);
    final Detail detail1 = ContextUtil.getDRS().getOne(Detail.class);
    marshaller.marshal(detail1, result);

    final Unmarshaller unmarshaller = ContextUtil.getBean(Unmarshaller.class);
    final Detail detail2 = (Detail) unmarshaller
            .unmarshal(new StreamSource(new ByteArrayInputStream(out.toByteArray())));

    Assert.assertEquals(detail1, detail2);
}

From source file:org.web4thejob.orm.TypeSerailizationTest.java

@Test
public void simpleMarshallingTest() throws XmlMappingException, IOException {
    final Marshaller marshaller = ContextUtil.getBean(Marshaller.class);
    Assert.assertNotNull(marshaller);/* w  w  w  .jav  a2 s .c om*/

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Result result = new StreamResult(out);
    final Master1 master1 = ContextUtil.getDRS().getOne(Master1.class);
    marshaller.marshal(master1, result);

    final Unmarshaller unmarshaller = ContextUtil.getBean(Unmarshaller.class);
    final Master1 master2 = (Master1) unmarshaller
            .unmarshal(new StreamSource(new ByteArrayInputStream(out.toByteArray())));

    Assert.assertEquals(master1, master2);
}

From source file:de.drv.dsrv.extra.marshaller.impl.ExtraUnmarschaller.java

@Override
public <X> X unmarshal(final Source source, final Class<X> extraTransportClass, final boolean validation)
        throws XmlMappingException, IOException {
    Assert.notNull(source, "StreamSource is null");
    Assert.notNull(extraTransportClass, "ExtraTransportClass is null");

    final Unmarshaller unmarshaller = findUnmarschaller(validation);
    final Object responseObject = unmarshaller.unmarshal(source);
    logger.debug("ResponseObject Class: {}", responseObject.getClass());
    Assert.notNull(responseObject, "Response is null");
    X extraTransport = null;/*  w ww. ja va2 s .c om*/
    if (ResponseTransport.class.isAssignableFrom(responseObject.getClass())) {
        extraTransport = extraTransportClass.cast(responseObject);
    } else if (JAXBElement.class.isAssignableFrom(responseObject.getClass())) {
        // TODO Wie funktioniert es besser?
        @SuppressWarnings("rawtypes")
        final JAXBElement jaxbElementResponse = JAXBElement.class.cast(responseObject);
        final Object jaxBElementValue = jaxbElementResponse.getValue();

        Assert.isAssignable(extraTransportClass, jaxBElementValue.getClass(),
                "JaxBElement.value  can not be converted to the response.ResponseTransport");
        extraTransport = extraTransportClass.cast(jaxBElementValue);
    } else {
        throw new IllegalArgumentException(
                "Response can not be converted to the response.ResponseTransport. ResponseObjectClass: "
                        + responseObject.getClass());
    }
    return extraTransport;
}

From source file:org.trpr.platform.integration.impl.xml.XMLTranscoderImpl.java

/**
 * Replacement method that uses JAXB directly instead of via Spring OXM. Provided just as an option
 *//*w w  w .jav  a2  s. c  o m*/
@SuppressWarnings("unchecked")
private <T> T unmarshalUsingJAXB(String xml, Class<T> clazz) throws XMLDataException {
    try {
        javax.xml.bind.JAXBContext context = javax.xml.bind.JAXBContext
                .newInstance(clazz.getPackage().getName());
        javax.xml.bind.Unmarshaller unmarshaller = context.createUnmarshaller();
        return (T) unmarshaller.unmarshal(new StringReader(xml));
    } catch (javax.xml.bind.JAXBException e) {
        throw new XMLDataException(
                "Error unmarshalling XML. XML:packageName is " + xml + ":" + clazz.getPackage().getName(), e);
    }
}

From source file:org.web4thejob.orm.CriterionImpl.java

@SuppressWarnings("rawtypes")
private Object deserializeValue(String flatValue) {
    final Unmarshaller unmarshaller = ContextUtil.getBean(Unmarshaller.class);
    try {/*ww  w. j a va 2 s .co m*/
        Object value = unmarshaller
                .unmarshal(new StreamSource(new ByteArrayInputStream(flatValue.getBytes("UTF-8"))));
        if (value instanceof Entity) {

            try {
                value = ContextUtil.getDRS().refresh((Entity) value);
            } catch (HibernateObjectRetrievalFailureException e) {
                //probably the record has been deleted.
                return null;
            }

        } else if (value instanceof List) {
            List list = (List) value;
            if (!list.isEmpty() && list.get(0) instanceof Entity) {
                for (Object item : list) {

                    try {
                        ContextUtil.getDRS().refresh((Entity) item);
                    } catch (HibernateObjectRetrievalFailureException e) {
                        //probably the record has been deleted.
                        return list.remove(item);
                    }

                }
            }
        }
        return value;
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.zergiu.tvman.shows.tvrage.TVRageShowLoaderJob.java

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    log.debug("Starting the InitialTVLoader Job");
    log.debug("Job : " + context.getJobDetail().getJobBuilder().toString());
    TVShow show = getShow(context);/*from   www .  j av a2 s  .c o  m*/
    Unmarshaller unmarshaler = getUnmarshaller();

    //http://services.tvrage.com/feeds/full_show_info.php?sid=<series id>
    try (InputStream in = getShowDataStream(
            "http://services.tvrage.com/feeds/full_show_info.php?sid=" + show.getProviderSeriesId())) {
        TVRageShow tvRageShow = (TVRageShow) unmarshaler.unmarshal(new StreamSource(in));
        merge(show, tvRageShow);
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
        ex.printStackTrace();
    }

    log.debug("got show:" + show);
}

From source file:com.hack23.cia.service.external.common.impl.XmlAgentImpl.java

@Override
public Object unmarshallXml(final Unmarshaller unmarshaller, final String accessUrl, final String nameSpace,
        final String replace, final String with) throws Exception {

    LOGGER.info("Calls {}", accessUrl);

    final boolean isWeb = accessUrl.toLowerCase().startsWith("http://")
            || accessUrl.toLowerCase().startsWith("https://");

    String xmlContent;//from   w  ww. ja va2  s  .  c  o  m
    if (isWeb) {
        xmlContent = Request.Get(accessUrl.replace(" ", "")).execute().returnContent()
                .asString(StandardCharsets.UTF_8);
    } else {
        xmlContent = readInputStream(accessUrl.replace(" ", ""));
    }

    if (replace != null) {
        xmlContent = xmlContent.replace(replace, with);
    }

    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            xmlContent.getBytes(StandardCharsets.UTF_8));

    Source source;
    if (nameSpace != null) {
        source = setNameSpaceOnXmlStream(byteArrayInputStream, nameSpace);
    } else {
        source = new StreamSource(byteArrayInputStream);
    }

    return unmarshaller.unmarshal(source);
}

From source file:org.apereo.portal.io.xml.IdentityImportExportTestUtilities.java

public static <T> void testIdentityImportExport(TransactionOperations transactionOperations,
        final IDataImporter<T> dataImporter, final IDataExporter<?> dataExporter, Resource resource,
        Function<T, String> getName) throws Exception {

    final String importData = toString(resource);

    final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
    final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new StringReader(importData));

    //Unmarshall from XML
    final Unmarshaller unmarshaller = dataImporter.getUnmarshaller();
    final StAXSource source = new StAXSource(xmlEventReader);
    @SuppressWarnings("unchecked")
    final T dataImport = (T) unmarshaller.unmarshal(source);

    //Make sure the data was unmarshalled
    assertNotNull("Unmarshalled import data was null", dataImport);

    //Import the data
    dataImporter.importData(dataImport);

    //Export the data
    final String name = getName.apply(dataImport);
    final Object dataExport = transactionOperations.execute(new TransactionCallback<Object>() {
        /* (non-Javadoc)
         * @see org.springframework.transaction.support.TransactionCallback#doInTransaction(org.springframework.transaction.TransactionStatus)
         *///from  w w  w .j ava2s .com
        @Override
        public Object doInTransaction(TransactionStatus status) {
            return dataExporter.exportData(name);
        }
    });

    //Make sure the data was exported
    assertNotNull("Exported data was null", dataExport);

    //Marshall to XML
    final Marshaller marshaller = dataExporter.getMarshaller();

    final StringWriter result = new StringWriter();
    marshaller.marshal(dataExport, new StreamResult(result));

    //Compare the exported XML data with the imported XML data, they should match
    final String resultString = result.toString();
    try {
        XMLUnit.setIgnoreWhitespace(true);
        Diff d = new Diff(new StringReader(importData), new StringReader(resultString));
        assertTrue("Export result differs from import" + d, d.similar());
    } catch (Exception e) {
        throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString,
                e);
    } catch (Error e) {
        throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString,
                e);
    }
}

From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java

protected Object unmarshallData(final XMLEventReader bufferedXmlEventReader,
        final IDataImporter<Object> dataImporterExporter) {
    final Unmarshaller unmarshaller = dataImporterExporter.getUnmarshaller();

    try {/*from w  w w  . ja v  a 2  s .  c  o  m*/
        final StAXSource source = new StAXSource(bufferedXmlEventReader);
        return unmarshaller.unmarshal(source);
    } catch (XmlMappingException e) {
        throw new RuntimeException("Failed to map provided XML to portal data", e);
    } catch (IOException e) {
        throw new RuntimeException("Failed to read the provided XML data", e);
    } catch (XMLStreamException e) {
        throw new RuntimeException("Failed to create StAX Source to read XML data", e);
    }
}