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:org.eclipse.winery.topologymodeler.addons.topologycompleter.helper.JAXBHelper.java

/**
 * This method adds a selection of {@link TNodeTemplate}- and {@link TRelationshipTemplate}-XML-Strings to a {@link TTopologyTemplate}-XML-String using JAXB.
 * After the templates have been added, the {@link TTopologyTemplate} object is re-marshalled to an XML-String.
 *
 * This method is called by the selectionHandler.jsp after several Node or RelationshipTemplates have been chosen in a dialog.
 *
 * @param topology/*from  w w  w . jav a  2s. c  om*/
 *            the topology as XML string
 * @param allTemplateChoicesAsXML
 *            all possible template choices as TOSCA-XML strings containing the complete templates
 * @param selectedNodeTemplatesAsJSON
 *            the names of the selected NodeTemplates as JSONArray
 * @param selectedRelationshipTemplatesAsJSON
 *            the names of the selected RelationshipTemplates as JSONArray
 *
 * @return the complete topology XML string
 */
public static String addTemplatesToTopology(String topology, String allTemplateChoicesAsXML,
        String selectedNodeTemplatesAsJSON, String selectedRelationshipTemplatesAsJSON) {
    try {

        // initialization code for the jackson types used to convert JSON string arrays to a java.util.List
        ObjectMapper mapper = new ObjectMapper();
        TypeFactory factory = mapper.getTypeFactory();

        // convert the JSON array containing the names of the selected RelationshipTemplates to a java.util.List
        List<String> selectedRelationshipTemplates = mapper.readValue(selectedRelationshipTemplatesAsJSON,
                factory.constructCollectionType(List.class, String.class));

        // convert the topology and the choices to objects using JAXB
        TTopologyTemplate topologyTemplate = getTopologyAsJaxBObject(topology);
        List<TEntityTemplate> allTemplateChoices = getEntityTemplatesAsJaxBObject(allTemplateChoicesAsXML);

        // this distinction of cases is necessary because it is possible that only RelationshipTemplates have been selected
        if (selectedNodeTemplatesAsJSON != null) {

            // convert the JSON string array containing the names of the selected NodeTemplates to a java.util.List
            List<String> selectedNodeTemplates = mapper.readValue(selectedNodeTemplatesAsJSON,
                    factory.constructCollectionType(List.class, String.class));

            // search the selected NodeTemplate in the List of all choices by its name to receive its object which will ne added to the topology
            for (String nodeTemplateName : selectedNodeTemplates) {
                for (TEntityTemplate choice : allTemplateChoices) {
                    if (choice instanceof TNodeTemplate) {
                        TNodeTemplate nodeTemplate = (TNodeTemplate) choice;
                        // matching a name is usually unsafe because the uniqueness cannot be assured,
                        // however similar names are not possible at this location due to the implementation of the selection dialogs
                        if (nodeTemplateName.equals(nodeTemplate.getName())) {
                            // add the selected NodeTemplate to the topology
                            topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(nodeTemplate);

                            // due to the mapping of IDs in the selection dialog, the corresponding Relationship Template of the inserted Node Template misses its SourceElement.
                            // Re-add it to avoid errors.
                            for (TEntityTemplate entity : topologyTemplate
                                    .getNodeTemplateOrRelationshipTemplate()) {
                                if (entity instanceof TRelationshipTemplate) {
                                    TRelationshipTemplate relationshipTemplate = (TRelationshipTemplate) entity;
                                    if (relationshipTemplate.getSourceElement().getRef() == null) {
                                        // connect to the added NodeTemplate
                                        SourceElement sourceElement = new SourceElement();
                                        sourceElement.setRef(nodeTemplate);
                                        relationshipTemplate.setSourceElement(sourceElement);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // now search and add the selected RelationshipTemplate object connecting to the inserted NodeTemplate
            for (String relationshipTemplateName : selectedRelationshipTemplates) {
                for (TEntityTemplate toBeAdded : allTemplateChoices) {
                    if (toBeAdded instanceof TRelationshipTemplate) {
                        TRelationshipTemplate relationshipTemplate = (TRelationshipTemplate) toBeAdded;
                        if (relationshipTemplateName.equals(relationshipTemplate.getName())) {
                            topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(relationshipTemplate);
                        }
                    }
                }
            }

        } else {
            // in this case only Relationship Templates have been selected
            List<TRelationshipTemplate> allRelationshipTemplateChoices = JAXBHelper
                    .getRelationshipTemplatesAsJaxBObject(allTemplateChoicesAsXML);

            // add the target Node Template to the topology which is unique due to the implementation of the selection dialog
            topologyTemplate.getNodeTemplateOrRelationshipTemplate()
                    .add((TNodeTemplate) ((TRelationshipTemplate) allRelationshipTemplateChoices.get(0))
                            .getTargetElement().getRef());

            // search the JAXB object of the selected RelationshipTemplate and add it to the topology
            for (String relationshipTemplateName : selectedRelationshipTemplates) {
                for (TRelationshipTemplate choice : allRelationshipTemplateChoices) {
                    if (relationshipTemplateName.equals(choice.getName())) {
                        topologyTemplate.getNodeTemplateOrRelationshipTemplate().add(choice);
                    }
                }
            }

            for (TEntityTemplate entityTemplate : topologyTemplate.getNodeTemplateOrRelationshipTemplate()) {
                if (entityTemplate instanceof TRelationshipTemplate) {
                    TRelationshipTemplate relationship = (TRelationshipTemplate) entityTemplate;

                    // due to the mapping of IDs in the selection dialog, the corresponding Relationship Template of the inserted Node Template misses its SourceElement.
                    // Re-add it to avoid errors.
                    if (relationship.getSourceElement().getRef() == null) {
                        relationship.getSourceElement().setRef(
                                (TNodeTemplate) ((TRelationshipTemplate) allRelationshipTemplateChoices.get(0))
                                        .getTargetElement().getRef());
                    }
                }
            }
        }

        // re-convert the topology from a JAXB object to an XML string and return it
        Definitions definitions = new Definitions();
        TServiceTemplate st = new TServiceTemplate();
        st.setTopologyTemplate(topologyTemplate);
        definitions.getServiceTemplateOrNodeTypeOrNodeTypeImplementation().add(st);
        JAXBContext context = JAXBContext.newInstance(Definitions.class);
        Marshaller m = context.createMarshaller();
        StringWriter stringWriter = new StringWriter();

        m.marshal(definitions, stringWriter);

        return stringWriter.toString();

    } catch (JAXBException | IOException e) {
        logger.error(e.getLocalizedMessage());
    }

    return null;
}

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

public static String getExecutionresultString(String urlServer, String projectAreaAlias, String encoding,
        String executionWorkItemUrl, ScenarioState stateOf, Date _startDate, Date _endDate, String details)
        throws JAXBException, DatatypeConfigurationException {

    Date startDate = (Date) _startDate.clone();
    Date endDate = (Date) _endDate.clone();

    com.ibm.rqm.xml.bind.Executionresult.Executionworkitem workTest = new com.ibm.rqm.xml.bind.Executionresult.Executionworkitem();
    workTest.setHref(executionWorkItemUrl);

    State state = new State();
    Executionresult result = new Executionresult();
    if (stateOf.equals(ScenarioState.FAILED)) {
        state.setContent("com.ibm.rqm.execution.common.state.failed");
    } else {/*  w  ww . jav  a 2  s .  c o m*/
        if (stateOf.equals(ScenarioState.PENDING)) {
            state.setContent("com.ibm.rqm.execution.common.state.blocked");
        } else {
            state.setContent("com.ibm.rqm.execution.common.state.passed");
        }
    }

    result.setState(state);
    result.setExecutionworkitem(workTest);

    // Datas de incio e fim do teste
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(startDate);
    XMLGregorianCalendar startDateXml = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    result.setStarttime(startDateXml);

    c.setTime(endDate);
    XMLGregorianCalendar endDateXml = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    result.setEndtime(endDateXml);

    // Details
    Details d = new Details();
    d.getContent().add(details);
    result.setDetails(d);

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

    return resourceString.toString();
}

From source file:com.manydesigns.portofino.dispatcher.DispatcherLogic.java

/**
 * Persists a page to the file system./*  w w w .  j  a  va2s  . c  o  m*/
 * @param directory the directory where to save the page.xml file.
 * @param page the page to save.
 * @return the file where the page was saved.
 * @throws Exception in case the save fails.
 */
public static File savePage(File directory, Page page) throws Exception {
    File pageFile = getPageFile(directory);
    Marshaller marshaller = pagesJaxbContext.createMarshaller();
    marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(page, pageFile);
    pageCache.invalidate(pageFile);
    return pageFile;
}

From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java

public static String marshallToString(Class sourceClass, Object source) {
    try {//from ww  w  . j a  v a 2  s .com
        JAXBContext jaxbContext = JAXBContext.newInstance(sourceClass);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter sw = new StringWriter();
        marshaller.marshal(source, sw);
        return sw.toString();
    } catch (JAXBException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
}

From source file:com.ikon.util.impexp.RepositoryExporter.java

/**
 * Export mail from openkm repository to filesystem.
 *///from   w  w w  .  j a  v  a 2s.c o m
public static ImpExpStats exportMail(String token, String mailPath, String destPath, String metadata,
        Writer out, InfoDecorator deco) throws PathNotFoundException, RepositoryException, DatabaseException,
        IOException, AccessDeniedException, ParseException, NoSuchGroupException, MessagingException {
    MailModule mm = ModuleManager.getMailModule();
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    Mail mailChild = mm.getProperties(token, mailPath);
    Gson gson = new Gson();
    ImpExpStats stats = new ImpExpStats();
    MimeMessage msg = MailUtils.create(token, mailChild);
    FileOutputStream fos = new FileOutputStream(destPath);
    msg.writeTo(fos);
    IOUtils.closeQuietly(fos);
    FileLogger.info(BASE_NAME, "Created document ''{0}''", mailChild.getPath());

    // Metadata
    if (metadata.equals("JSON")) {
        MailMetadata mmd = ma.getMetadata(mailChild);
        String json = gson.toJson(mmd);
        fos = new FileOutputStream(destPath + Config.EXPORT_METADATA_EXT);
        IOUtils.write(json, fos);
        IOUtils.closeQuietly(fos);
    } else if (metadata.equals("XML")) {
        fos = new FileOutputStream(destPath + ".xml");

        MailMetadata mmd = ma.getMetadata(mailChild);
        JAXBContext jaxbContext;
        try {
            jaxbContext = JAXBContext.newInstance(MailMetadata.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(mmd, fos);
        } catch (JAXBException e) {
            log.error(e.getMessage(), e);
            FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage());
        }
    }

    if (out != null) {
        out.write(deco.print(mailChild.getPath(), mailChild.getSize(), null));
        out.flush();
    }

    // Stats
    stats.setSize(stats.getSize() + mailChild.getSize());
    stats.setMails(stats.getMails() + 1);

    return stats;
}

From source file:org.cleverbus.common.Tools.java

/**
 * Marshals object graph into XML./*w w  w.j ava 2  s.c  o  m*/
 *
 * @param obj   the object graph
 * @param qName the QName
 * @return XML as string
 * @see Marshaller
 */
@SuppressWarnings("unchecked")
public static <T> String marshalToXml(T obj, QName qName) {
    StringWriter stringWriter = new StringWriter();

    try {
        Marshaller marshaller = JAXBContext.newInstance(obj.getClass()).createMarshaller();
        Object element;
        if (qName != null) {
            element = new JAXBElement<T>(qName, (Class<T>) obj.getClass(), obj);
        } else {
            qName = new QName(obj.getClass().getPackage().getName(), obj.getClass().getSimpleName());
            element = new JAXBElement<T>(qName, (Class<T>) obj.getClass(), obj);
        }
        marshaller.marshal(element, stringWriter);
        return stringWriter.toString();
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.tellervo.desktop.wsi.WebJaxbAccessor.java

/**
 * Marshall this object to a JDOM Document
 * /* ww w  . ja v a 2  s .  co m*/
 * @param context
 * @param object
 * @param prefixMapper an implementation of namespacePrefixMapper
 * @return
 * @throws JAXBException
 */
protected static Document marshallToDocument(JAXBContext context, Object object,
        NamespacePrefixMapper prefixMapper) throws JAXBException {
    JDOMResult result = new JDOMResult();
    Marshaller m = context.createMarshaller();

    // set a namespace prefix mapper
    if (prefixMapper != null)
        m.setProperty("com.sun.xml.bind.namespacePrefixMapper", prefixMapper);

    m.marshal(object, result);

    return result.getDocument();
}

From source file:com.hpe.application.automation.tools.octane.executor.UFTTestDetectionService.java

/**
 * Serialize detectionResult to file in XML format
 *
 * @param fileToWriteTo/*from  www.  j  a  v  a  2s.c o m*/
 * @param taskListenerLog
 * @param detectionResult
 */
public static void publishDetectionResults(File fileToWriteTo, TaskListener taskListenerLog,
        UFTTestDetectionResult detectionResult) {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(UFTTestDetectionResult.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(detectionResult, fileToWriteTo);

    } catch (JAXBException e) {
        if (taskListenerLog != null) {
            taskListenerLog.error("Failed to persist detection results: " + e.getMessage());
        }
        logger.error("Failed to persist detection results: " + e.getMessage());
    }
}

From source file:Main.java

public static String toXml(Object jaxbElement, Map<String, Object> marshallerProps) {
    try {/*  ww w  .  j a va 2s.  com*/
        StringWriter stringWriter = new StringWriter();
        Marshaller marshaller = getJaxbMarshaller(jaxbElement.getClass(), marshallerProps);

        //         OutputFormat xmlOutputFormat = new OutputFormat();
        //         xmlOutputFormat.setCDataElements(new String[] {"^id"});
        //         xmlOutputFormat.setPreserveSpace(true);
        //         xmlOutputFormat.setIndenting(true);
        //         XMLSerializer xmlSerializer = new XMLSerializer(xmlOutputFormat);
        //         xmlSerializer.setOutputByteStream(System.out);
        //         marshaller.marshal(jaxbElement, xmlSerializer.asContentHandler());

        marshaller.marshal(jaxbElement, stringWriter);
        return stringWriter.toString();
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

private static void writeAsterixClusterConfigurationFile(AsterixInstance asterixInstance)
        throws IOException, EventException, JAXBException {
    String asterixInstanceName = asterixInstance.getName();
    Cluster cluster = asterixInstance.getCluster();

    JAXBContext ctx = JAXBContext.newInstance(Cluster.class);
    Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(cluster, new FileOutputStream(AsterixEventService.getAsterixDir() + File.separator
            + asterixInstanceName + File.separator + "cluster.xml"));
}