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.comcast.cats.service.util.HttpClientUtil.java

public static synchronized byte[] getPayload(Object domain, boolean prettyPrint) {
    byte[] payload = null;

    String xml = null;/*  ww w  .ja v a  2s . com*/

    StringWriter writer = new StringWriter();

    try {
        JAXBContext context = JAXBContext.newInstance(domain.getClass());

        Marshaller marshaller = context.createMarshaller();

        if (prettyPrint) {
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        }

        marshaller.marshal(domain, writer);
        xml = writer.toString();
    } catch (JAXBException e) {
        logger.error("[ JAXBException   ] " + e.getMessage());
    }

    logger.trace("[ PAYLOAD  ] " + xml);

    if (null != xml) {
        payload = xml.getBytes();
    }

    return payload;
}

From source file:com.vangent.hieos.services.xds.bridge.utils.JUnitHelper.java

/**
 * Method description/*from ww  w.jav  a 2 s  .  c o  m*/
 *
 *
 *
 *
 * @param file
 * @param count
 * @param documentIds
 * @return
 *
 * @throws Exception
 */
public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception {

    ObjectFactory factory = new ObjectFactory();
    SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest();

    IdType pid = factory.createIdType();

    pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478");
    sdr.setPatientId(pid);

    ClassLoader classLoader = JUnitHelper.class.getClassLoader();

    DocumentsType documents = factory.createDocumentsType();

    for (int i = 0; i < count; ++i) {

        DocumentType document = factory.createDocumentType();

        if ((documentIds != null) && (documentIds.length > i)) {
            document.setId(documentIds[i]);
        }

        CodeType type = factory.createCodeType();

        type.setCode("51855-5");
        type.setCodeSystem("2.16.840.1.113883.6.1");

        document.setType(type);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        InputStream is = classLoader.getResourceAsStream(file);

        assertNotNull(is);

        IOUtils.copy(is, bos);

        document.setContent(bos.toByteArray());

        documents.getDocument().add(document);
    }

    sdr.setDocuments(documents);

    QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest");
    JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class);
    Marshaller marshaller = jc.createMarshaller();

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr);

    StringWriter sw = new StringWriter();

    marshaller.marshal(element, sw);

    String xml = sw.toString();

    logger.debug(xml);

    OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml);

    List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content",
            URIConstants.XDSBRIDGE_URI);

    for (OMElement contentNode : list) {

        OMText binaryNode = (OMText) contentNode.getFirstOMChild();

        if (binaryNode != null) {
            binaryNode.setOptimize(true);
        }
    }

    return result;
}

From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static String marshal(Object obj, String rootElementName) {
    StringWriter sw = new StringWriter();
    try {/* w  ww  .  jav  a2s.  co m*/
        JAXBContext jaxbCtx = JAXBContext.newInstance(obj.getClass().getPackage().getName());
        Marshaller marshaller = jaxbCtx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(new JAXBElement(new QName(rootElementName), obj.getClass(), obj), sw);
        sw.close();

    } catch (PropertyException e) {
        e.printStackTrace();
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return sw.toString();
}

From source file:com.kcs.core.utilities.Utility.java

public static OutputStream generate(Object jaxbElement, OutputStream output) throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(jaxbElement.getClass());
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(jaxbElement, output);
    return output;
}

From source file:eu.openanalytics.rsb.Util.java

/**
 * Marshals an {@link ErrorResult} to XML.
 * //w w w .  j av a 2  s  . com
 * @param errorResult
 * @return
 */
public static String toXml(final ErrorResult errorResult) {
    try {
        final Marshaller marshaller = ERROR_RESULT_JAXB_CONTEXT.createMarshaller();
        final StringWriter sw = new StringWriter();
        marshaller.marshal(errorResult, sw);
        return sw.toString();
    } catch (final JAXBException je) {
        final String objectAsString = ToStringBuilder.reflectionToString(errorResult,
                ToStringStyle.SHORT_PREFIX_STYLE);
        throw new RuntimeException("Failed to XML marshall: " + objectAsString, je);
    }
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getExecutionworkitemString(String urlServer, String projectAreaAlias, String encoding,
        String testCaseId, String testPlanId) throws JAXBException {

    // Workitem//w  w w. j  ava2 s. c  om
    com.ibm.rqm.xml.bind.Executionworkitem.Testcase workTest = new com.ibm.rqm.xml.bind.Executionworkitem.Testcase();
    workTest.setHref(urlServer + "resources/" + projectAreaAlias + "/testcase/" + testCaseId);

    // Testplan
    com.ibm.rqm.xml.bind.Executionworkitem.Testplan testPlan = new com.ibm.rqm.xml.bind.Executionworkitem.Testplan();
    testPlan.setHref(
            urlServer + "resources/" + projectAreaAlias + "/testplan/urn:com.ibm.rqm:testplan:" + testPlanId);

    // Criao do Execution Work Item
    Executionworkitem work = new Executionworkitem();
    work.setFrequency("Once");
    work.setRegression(false);
    work.setTitle("Registro de Execuo Automatizado - Plano de Teste " + testPlanId);
    work.setWeight(100);
    work.setTestcase(workTest);
    work.setTestplan(testPlan);

    JAXBContext jaxb = JAXBContext.newInstance(Executionworkitem.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter resourceString = new StringWriter();
    marshaller.marshal(work, resourceString);

    return resourceString.toString();
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getTestplanString(String urlServer, String projectAreaAlias, String encoding,
        String testCaseId, Testplan currentPlan) throws JAXBException {

    // Adiciona o novo test case se no existir
    boolean exists = false;
    String newTestCaseId = urlServer + "resources/" + projectAreaAlias + "/testcase/" + testCaseId;

    if (currentPlan.getTestcase() != null) {
        for (com.ibm.rqm.xml.bind.Testplan.Testcase link : currentPlan.getTestcase()) {
            if (link.getHref().equals(newTestCaseId)) {
                exists = true;/*from  ww  w  .  j  a va  2 s  .com*/
                break;
            }
        }
    }

    if (!exists) {
        com.ibm.rqm.xml.bind.Testplan.Testcase testcase = new com.ibm.rqm.xml.bind.Testplan.Testcase();
        testcase.setHref(newTestCaseId);
        currentPlan.getTestcase().add(testcase);
    }

    JAXBContext jaxb = JAXBContext.newInstance(Testplan.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter testPlanString = new StringWriter();
    marshaller.marshal(currentPlan, testPlanString);

    return testPlanString.toString();
}

From source file:com.evolveum.midpoint.cli.common.ToolsUtils.java

public static void serializeObject(Object object, Writer writer) throws JAXBException {
    if (object == null) {
        return;//from ww  w .  ja va  2  s  . c  o m
    }

    Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

    if (object instanceof ObjectType) {
        object = new JAXBElement(C_OBJECT, Object.class, object);
    }

    marshaller.marshal(object, writer);
}

From source file:br.ufpb.dicomflow.integrationAPI.tools.ReadService.java

private static void saveMessages(List<MessageIF> messages, File destDir) throws JAXBException, IOException {
    Iterator<MessageIF> it = messages.iterator();
    while (it.hasNext()) {
        MessageIF messageIF = (MessageIF) it.next();
        ServiceIF service = messageIF.getService();
        Logger.v(rb.getString("loaded-service") + service.getName() + " - " + service.getAction() + " - "
                + service.getMessageID());

        JAXBContext jaxbContext = JAXBContext.newInstance(messageIF.getService().getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        FileOutputStream fos = new FileOutputStream(destDir.getAbsolutePath() + File.pathSeparator
                + service.getName() + "_" + service.getAction() + "_" + service.getMessageID());
        jaxbMarshaller.marshal(messageIF.getService(), fos);

        if (messageIF.getAttach() != null && messageIF.getAttach().length > 0) {
            fos = new FileOutputStream(destDir.getAbsolutePath() + File.pathSeparator + service.getName() + "_"
                    + service.getAction() + "_" + service.getMessageID() + "_attach");
            fos.write(messageIF.getAttach());
            fos.close();/*from w  ww.ja va 2 s.c o  m*/
        }

    }
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getTestcaseString(String urlServer, String projectAreaAlias, String encoding, String name,
        String steps, Testcase currentTestCase) throws JAXBException {

    Richtext textDesgin = new Richtext();
    textDesgin.getContent().add(escapeHTMLForAlm(steps));

    currentTestCase.setTitle(name);// w  ww  .  j a v  a  2  s .c o  m
    currentTestCase.setSuspect(false);
    currentTestCase.setWeight(100);
    currentTestCase.setComIbmRqmPlanningEditorSectionTestCaseDesign(textDesgin);

    // Valor da Categoria
    String categoryTipoExecucao = BehaveConfig.getIntegration_CategoryTipoExecucao();

    // Verifica se no caso de teste vindo da ALM existe a categoria
    // "Tipo de Execuo", se no existe cria.
    boolean objExists = false;
    for (Testcase.Category c : currentTestCase.getCategory()) {
        if (c.getTerm().toLowerCase().trim().equals("tipo de execuo")) {
            objExists = true;
            // Altera para "Automtica"
            c.setValue(categoryTipoExecucao);
            break;
        }
    }

    if (!objExists) {
        Testcase.Category newC = new Testcase.Category();
        newC.setTerm("Tipo de Execuo");
        newC.setValue(categoryTipoExecucao);
        currentTestCase.getCategory().add(newC);
    }

    JAXBContext jaxb = JAXBContext.newInstance(Testcase.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter testCaseString = new StringWriter();
    marshaller.marshal(currentTestCase, testCaseString);

    return testCaseString.toString();
}