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:com.healthcit.cacure.web.controller.FormExportController.java

@RequestMapping(method = RequestMethod.GET)
public void exportForm(@RequestParam(value = "id", required = true) Long formId,
        @RequestParam(value = "format", required = true) String format, HttpServletResponse response) {

    try {/* w  ww  .  j  av a  2 s  .c o m*/
        OutputStream oStream = response.getOutputStream();
        Cure cureXml = dataExporter.constructFormXML(formId);
        JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");

        if (ExportFormat.XML.name().endsWith(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xml;", formId);
            response.setHeader("Content-Disposition", fileNameHeader);
            response.setContentType("application/xml");

            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(cureXml, oStream);
            oStream.flush();
        } else if (ExportFormat.EXCEL.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xlxml;", formId);
            response.setHeader("Content-Disposition", fileNameHeader);
            response.setContentType("application/xml");
            StreamSource xslSource = new StreamSource(this.getClass().getClassLoader()
                    .getResourceAsStream(AppConfig.getString(Constants.EXPORT_EXCEL_XSLT_FILE)));
            JAXBSource xmlSource = new JAXBSource(jc, cureXml);
            Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
            transformer.transform(xmlSource, new StreamResult(oStream));
        }
    } catch (IOException e) {
        log.error("Unable to obtain output stream from the response");
        log.error(e.getMessage(), e);
    } catch (JAXBException e) {
        log.error("Unable to marshal the object");
        log.error(e.getMessage(), e);
    } catch (TransformerException e) {
        log.error("XSLT transformation failed");
        log.error(e.getMessage(), e);
    }
}

From source file:org.esbtools.gateway.GatewayRequest.java

public String toXML() {
    StringWriter thisXML = new StringWriter();

    try {// w w  w .j a  v a 2  s .  c om
        JAXBContext jaxbContext = JAXBContext.newInstance(this.getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        jaxbMarshaller.marshal(this, thisXML);

    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }
    return thisXML.toString();
}

From source file:com.healthcit.cacure.web.controller.ModuleImportExportController.java

@RequestMapping(method = RequestMethod.GET)
public void exportModule(@RequestParam(value = "moduleId", required = true) long id,
        @RequestParam(value = "format", required = true) String format, HttpServletResponse response) {

    try {//from w  w w  .  j ava 2 s  .  c o  m
        response.setContentType("text/xml");

        OutputStream oStream = response.getOutputStream();
        Cure cureXml = dataExporter.constructModuleXML(id);
        JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");
        if (ExportFormat.XML.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xml;", id);

            response.setHeader("Content-Disposition", fileNameHeader);
            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(cureXml, oStream);
        } else if (ExportFormat.EXCEL.name().equals(format)) {
            String fileNameHeader = String.format("attachment; filename=form-%d.xlxml;", id);

            response.setHeader("Content-Disposition", fileNameHeader);
            response.setContentType("application/xml");
            StreamSource xslSource = new StreamSource(this.getClass().getClassLoader()
                    .getResourceAsStream(AppConfig.getString(Constants.EXPORT_EXCEL_XSLT_FILE)));
            JAXBSource xmlSource = new JAXBSource(jc, cureXml);
            Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
            transformer.transform(xmlSource, new StreamResult(oStream));
        }
        oStream.flush();
    } catch (IOException e) {
        log.error("Unable to obtain output stream from the response");
        log.error(e.getMessage(), e);
    } catch (JAXBException e) {
        log.error("Unable to marshal the object");
        log.error(e.getMessage(), e);
    } catch (TransformerException e) {
        log.error("XSLT transformation failed");
        log.error(e.getMessage(), e);
    }
}

From source file:com.px100systems.util.XmlParser.java

/**
 * Serialize the bean to XML//w  w  w  . j a  v a  2  s .co m
 * @param bean teh bean to serialize
 * @return XML
 */
public String write(T bean) {
    StringBuilder result = new StringBuilder();
    Writer writer = new StringBuilderWriter(result);
    try {
        Marshaller m = jaxb.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        m.marshal(bean, writer);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
    return result.toString();
}

From source file:de.qucosa.dissemination.epicur.servlet.EpicurDisseminationServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    URI metsDocumentUri;//from w  w  w .j a v a2  s .co  m
    boolean transferUrlPidencode;
    String transferUrlPattern;
    String frontpageUrlPattern;
    Map<String, String> agentNameSubstitutions;
    try {
        String reqParameter = req.getParameter(REQUEST_PARAM_METS_URL);
        if (reqParameter == null || reqParameter.isEmpty()) {
            resp.sendError(SC_BAD_REQUEST, "Missing parameter '" + REQUEST_PARAM_METS_URL + "'");
            return;
        }
        metsDocumentUri = URI.create(reqParameter);

        ServletConfig config = getServletConfig();

        transferUrlPattern = getParameterValue(config, PARAM_TRANSFER_URL_PATTERN);
        frontpageUrlPattern = getParameterValue(config, PARAM_FRONTPAGE_URL_PATTERN);
        transferUrlPidencode = isParameterSet(config, PARAM_TRANSFER_URL_PIDENCODE);

        agentNameSubstitutions = decodeSubstitutions(getParameterValue(config, PARAM_AGENT_NAME_SUBSTITUTIONS));

    } catch (Exception e) {
        log.error(e.getMessage());
        resp.sendError(SC_INTERNAL_SERVER_ERROR);
        return;
    }

    try (CloseableHttpResponse httpResponse = httpClient.execute(new HttpGet(metsDocumentUri))) {
        if (httpResponse.getStatusLine().getStatusCode() != SC_OK) {
            resp.sendError(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
            return;
        }
        Document metsDocument = new SAXBuilder().build(httpResponse.getEntity().getContent());

        EpicurBuilder epicurBuilder = new EpicurBuilder().encodePid(transferUrlPidencode)
                .agentNameSubstitutions(agentNameSubstitutions).frontpageUrlPattern(frontpageUrlPattern)
                .mets(metsDocument).transferUrlPattern(transferUrlPattern).updateStatus(UpdateStatus.urn_new);
        Epicur epicur = epicurBuilder.build();

        StringWriter stringWriter = new StringWriter();

        Marshaller marshaller = marshallerPool.borrowObject();
        marshaller.marshal(epicur, stringWriter);
        marshallerPool.returnObject(marshaller);

        resp.setCharacterEncoding(Charset.defaultCharset().name());
        resp.setContentType("application/xml");
        resp.getOutputStream().print(stringWriter.toString());

    } catch (Exception e) {
        log.error("Error while writing XML content: " + e.getMessage());
        if (!resp.isCommitted()) {
            resp.sendError(SC_INTERNAL_SERVER_ERROR);
        } else {
            log.warn("Response already committed. Cannot send error code.");
        }
    }
}

From source file:com.olp.jpa.domain.docu.ut.DepartmentServiceTest.java

public void test_marshalling() throws JAXBException {

    List<DepartmentBean> list = __service.findAll();

    DepartmentBean bean = __service.findByDeptCode("OPRTN");

    JAXBContext ctx = JAXBContext.newInstance(DepartmentBean.class);
    StringWriter writer = new StringWriter();
    Marshaller m = ctx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(bean, writer);

    final String xml = writer.toString();
    System.out.println(xml);/*  w  ww. j  a va  2  s. c o m*/

}

From source file:com.openthinks.webscheduler.service.WebSecurityService.java

/**
 * save changes to disk file/*from www.  j av  a  2  s .  c o m*/
 */
public void saveToDisk() {
    Checker.require(this.securityConfig).notNull();
    Checker.require(this.webSecurity).notNull();
    File file = this.securityConfig.getConfigFile();
    try {
        FileOutputStream fos = new FileOutputStream(file);
        JAXBContext jaxbContext = JAXBContext.newInstance(WebSecurity.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(this.webSecurity, fos);
        fos.close();
        this.webSecurity.moveToSaved();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.fusesource.example.camel.ingest.FileIngestorRouteBuilderTest.java

protected void createAndMoveFile(AggregateRecordType agt) throws Exception {
    File testFile = new File("./target/test.xml");

    if (testFile.exists()) {
        testFile.delete();//from w  w w .j av a2  s  .  com
    }

    ObjectFactory objFact = new ObjectFactory();
    JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller m = context.createMarshaller();
    m.marshal(objFact.createAggregateRecord(agt), testFile);
    // not really atomic, but it works for tests
    FileUtils.moveFile(testFile, new File(pollingFolder, "test.xml"));
}

From source file:io.apiman.test.common.mock.EchoServlet.java

/**
 * Responds with a comprehensive echo.  This means bundling up all the
 * information about the inbound request into a java bean and responding
 * with that data as a JSON response.// w ww.  j  ava2  s  .c o m
 * @param req
 * @param resp
 * @param withBody
 */
protected void doEchoResponse(HttpServletRequest req, HttpServletResponse resp, boolean withBody)
        throws IOException {
    String acceptHeader = req.getHeader("Accept");
    String errorCode = req.getHeader("X-Echo-ErrorCode");
    if (errorCode != null) {
        int ec = new Integer(errorCode);
        String errorMsg = req.getHeader("X-Echo-ErrorMessage");
        resp.sendError(ec, errorMsg);
        return;
    }

    String queryString = req.getQueryString();
    if (queryString != null && queryString.startsWith("redirectTo=")) {
        String redirectTo = queryString.substring(11);
        resp.sendRedirect(redirectTo);
        return;
    }

    boolean isXml = acceptHeader != null && acceptHeader.contains("application/xml");

    EchoResponse response = response(req, withBody);
    response.setCounter(++servletCounter);
    resp.setHeader("Response-Counter", response.getCounter().toString());

    if (isXml) {
        resp.setContentType("application/xml");
        try {
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.marshal(response, resp.getOutputStream());
            IOUtils.closeQuietly(resp.getOutputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        resp.setContentType("application/json");
        try {
            mapper.writeValue(resp.getOutputStream(), response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

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

@Test
public void testXmlSmsSendRequestDto() throws Exception {

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

    SmsSendRequestDto request = new SmsSendRequestDto("bremersee", "0123456789", "Hello",
            new Date(System.currentTimeMillis() + 30000L));

    ByteArrayOutputStream out = new ByteArrayOutputStream();

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

    m.marshal(request, out);

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

    System.out.println(xmlStr);//  ww w  . j ava2s .  com

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

    m.marshal(readRequest, System.out);

    TestCase.assertEquals(request, readRequest);

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