Example usage for javax.xml.bind Marshaller marshal

List of usage examples for javax.xml.bind Marshaller marshal

Introduction

In this page you can find the example usage for javax.xml.bind Marshaller marshal.

Prototype

public void marshal(Object jaxbElement, javax.xml.stream.XMLEventWriter writer) throws JAXBException;

Source Link

Document

Marshal the content tree rooted at jaxbElement into a javax.xml.stream.XMLEventWriter .

Usage

From source file:es.caib.sgtsic.xml.XmlManager.java

private ByteArrayOutputStream marshal(T item, boolean formattedOutput) throws JAXBException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, formattedOutput);

    jaxbMarshaller.marshal(item, baos);

    return baos;/*from w  w w.  j  a v a 2s  .co  m*/
}

From source file:ee.ria.xroad.proxy.clientproxy.WsdlRequestProcessor.java

private SoapMessageImpl createMessage(ClientId client, final ServiceId service) throws Exception {
    ServiceId implementingService = GlobalConf.getServiceId(service);

    log.debug("Implementing service: {}", implementingService);

    SoapHeader header = new SoapHeader();
    header.setClient(client);//from   w  ww .j  a  v a  2s.  com
    header.setService(createGetWsdlService(implementingService));
    header.setQueryId(UUID.randomUUID().toString());
    header.setProtocolVersion(new ProtocolVersion());

    SoapBuilder sb = new SoapBuilder();
    sb.setHeader(header);
    sb.setCreateBodyCallback(soapBody -> {
        WsdlRequestData req = new WsdlRequestData();
        req.setServiceCode(implementingService.getServiceCode());
        req.setServiceVersion(implementingService.getServiceVersion());

        Marshaller marshaller = JaxbUtils.createMarshaller(req.getClass());
        marshaller.marshal(req, soapBody);
    });

    return sb.build();
}

From source file:com.castlemock.web.basis.support.FileRepositorySupport.java

public <T> void save(T type, String filename) {
    Writer writer = null;/*  w ww  .  j  a v  a 2  s  . co  m*/
    try {
        JAXBContext context = JAXBContext.newInstance(type.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        writer = new FileWriter(filename);
        marshaller.marshal(type, writer);
    } catch (JAXBException e) {
        LOGGER.error("Unable to parse file: " + filename, e);
        throw new IllegalStateException("Unable to parse the following file: " + filename);
    } catch (IOException e) {
        LOGGER.error("Unable to read file: " + filename, e);
        throw new IllegalStateException("Unable to read the following file: " + filename);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                LOGGER.error("Unable to close file writer for type " + type.getClass().getSimpleName(), e);
            }
        }
    }
}

From source file:org.jasig.portlet.courses.dao.xml.Jaxb2CourseSummaryHttpMessageConverter.java

@Override
protected void writeToResult(Object o, HttpHeaders headers, Result result) throws IOException {
    try {/*from   w  ww.  j av  a  2 s  . com*/
        Class clazz = ClassUtils.getUserClass(o);
        Marshaller marshaller = createWrapperMarshaller(clazz);
        setCharset(headers.getContentType(), marshaller);
        marshaller.marshal(o, result);
    } catch (MarshalException ex) {
        throw new HttpMessageNotWritableException("Could not marshal [" + o + "]: " + ex.getMessage(), ex);
    } catch (JAXBException ex) {
        throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex);
    }
}

From source file:eu.eexcess.zbw.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {

    // Configure/*from   w w w  .  j av a2s .  c  o  m*/
    try {
        Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientJAXBContext());
        queryGenerator = PartnerConfigurationEnum.CONFIG.getQueryGenerator();

        String query = getQueryGenerator().toQuery(userProfile);
        query = query.replaceAll("\"", "");
        query = query.replaceAll("\\(", " ");
        query = query.replaceAll("\\)", " ");
        query = URLEncoder.encode(query, "UTF-8");
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("query", query);
        if (userProfile.numResults != null)
            valuesMap.put("size", userProfile.numResults.toString());
        else
            valuesMap.put("size", "10");
        String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);

        WebResource service = client.resource(searchRequest);
        log.log(Level.INFO, "SearchRequest: " + searchRequest);

        Builder builder = service.accept(MediaType.APPLICATION_XML);
        String response = builder.get(String.class);
        StringReader respStringReader = new StringReader(response);
        client.destroy();
        JAXBContext jaxbContext = JAXBContext.newInstance(ZBWDocument.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        ZBWDocument zbwResponse = (ZBWDocument) jaxbUnmarshaller.unmarshal(respStringReader);
        for (ZBWDocumentHit hit : zbwResponse.hits.hit) {
            try {
                if (hit.element.type.equals("event")) {
                    Document detail = fetchDocumentDetails(hit.element.id);
                    PartnerdataTracer.dumpFile(this.getClass(), partnerConfiguration, detail, "detail-response",
                            logger);
                    String latValue = getValueWithXPath("/doc/record/geocode/lat", detail);
                    String longValue = getValueWithXPath("/doc/record/geocode/lng", detail);
                    hit.element.lat = latValue;
                    hit.element.lng = longValue;
                }
            } catch (Exception e) {
                log.log(Level.WARNING,
                        "Could not get longitude and latitude for event element " + hit.element.id, e);
            }
            // put all creators in the creatorString
            if (hit.element.creator != null) {
                for (String creator : hit.element.creator) {
                    if (hit.element.creatorString == null)
                        hit.element.creatorString = "";
                    if (hit.element.creatorString.length() > 0)
                        hit.element.creatorString += ", ";
                    hit.element.creatorString += creator;
                }
            }
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(zbwResponse, document);

        return document;
    } catch (Exception e) {
        throw new IOException("Cannot query partner REST API!", e);
    }

}

From source file:mx.bigdata.sat.cfd.CFDv2.java

private Comprobante copy(Comprobante comprobante) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from  ww  w. j a v  a  2  s.c  om*/
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Marshaller m = context.createMarshaller();
    m.marshal(comprobante, doc);
    Unmarshaller u = context.createUnmarshaller();
    return (Comprobante) u.unmarshal(doc);
}

From source file:org.bremersee.sms.test.ModelTests.java

@Test
public void testXmlSmsSendResponseDto() throws Exception {

    System.out.println("Testing XML SmsSendResponseDto ...");

    GoyyaSmsSendResponseDto goyyaResponse = new GoyyaSmsSendResponseDto("OK");

    SmsSendResponseDto response = new SmsSendResponseDto(new SmsSendRequestDto("bremersee", "0123456789",
            "Hello", new Date(System.currentTimeMillis() + 30000L)), goyyaResponse.isOk(), goyyaResponse);

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    Marshaller m = jaxbContext.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    m.marshal(response, out);

    String xmlStr = new String(out.toByteArray(), "UTF-8");

    System.out.println(xmlStr);//from   www  .  ja va  2 s. c  o  m

    SmsSendResponseDto readResponse = (SmsSendResponseDto) jaxbContext.createUnmarshaller()
            .unmarshal(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));

    m.marshal(readResponse, System.out);

    GoyyaSmsSendResponseDto tmp = ExtensionUtils.transform(readResponse.getExtension(),
            GoyyaSmsSendResponseDto.class, jaxbContext, new ObjectMapper());
    readResponse.setExtension(tmp);

    TestCase.assertEquals(response, readResponse);

    System.out.println("OK\n");
}

From source file:com.savoirtech.jaxb.engine.PooledMarshaller.java

public void marshal(Object o, OutputStream os) {

    Marshaller marshaller = null;
    try {//from   ww  w  . j  a v a  2s  .c om
        marshaller = (Marshaller) (pool.borrowObject());
        marshaller.marshal(o, os);
    } catch (Exception e) {
        LOG.error("Could not marshal code ", e);
    } finally {
        try {
            if (null != marshaller) {
                pool.returnObject(marshaller);
            }
        } catch (Exception e) {
            // ignored
        }
    }
}

From source file:com.savoirtech.jaxb.engine.PooledMarshaller.java

public void marshal(Object o, Result res) {

    Marshaller marshaller = null;
    try {//from   w  ww  . ja v a2 s .  c o m
        marshaller = (Marshaller) (pool.borrowObject());
        marshaller.marshal(o, res);
    } catch (Exception e) {
        LOG.error("Could not marshal code ", e);
    } finally {
        try {
            if (null != marshaller) {
                pool.returnObject(marshaller);
            }
        } catch (Exception e) {
            // ignored
        }
    }
}

From source file:com.savoirtech.jaxb.engine.PooledMarshaller.java

public void marshal(Object o, File file) {

    Marshaller marshaller = null;
    try {/*from   w w w  .  j  av  a2  s .  c  o m*/
        marshaller = (Marshaller) (pool.borrowObject());
        marshaller.marshal(o, file);
    } catch (Exception e) {
        LOG.error("Could not marshal code ", e);
    } finally {
        try {
            if (null != marshaller) {
                pool.returnObject(marshaller);
            }
        } catch (Exception e) {
            // ignored
        }
    }
}