вторник, 21 октября 2014 г.

JAXB: Marshalling and Unmarshalling XML

XML -> Java

xml:
<SubscriptionNotificationsConfig>
    <AppUrl>http://192.168.0.1:9080/develop/</AppUrl>
    <From>admin@tele2.ru</From>
    <Documents>
        <Document Class="DiagnosticTask" EventHandlerClass="ru.brbpm.eatd_subscriptions.DocumentEventHandler">
            <Recipient>Пользователи задания
            <Recipient>Кураторы задания
            <Event name="CreationEvent" template="CreateDoc">
            <Event name="UpdateEvent" template="UpdateDoc">
            <Event name="DeletionEvent" template="DeleteDoc">
        </Document>
        <Document Class="DiagnosticReport" EventHandlerClass="ru.brbpm.eatd_subscriptions.DocumentEventHandler">
            <Recipient>Пользователи технического отчета
            <Recipient>Кураторы технического отчета
            <Event name="CreationEvent" template="CreateDoc">
            <Event name="UpdateEvent" template="UpdateDoc">
            <Event name="DeletionEvent" template="DeleteDoc">
        </Document>
    </Documents>
    <Templates>
        <Template Name="CreateDoc" Title="Уведомление о размещении документа" Url="%s#!cardservice;objectStoreName=OS1;id=%s;objectType=DOCUMENT">
            <![CDATA[По состоянию на %s размещен документ: %s "%s"]]>
            
        <Template Name="UpdateDoc" Title="Уведомление о новой версии документа" Url="%s#!cardservice;objectStoreName=OS1;id=%s;objectType=DOCUMENT">
            <![CDATA[По состоянию на %s создана новая версия документа: %s "%s"]]>
        </Template>
    </Templates>
</SubscriptionNotificationsConfig>

Java code:
package ru.brbpm.subscriptions;

import javax.xml.bind.annotation.*;
import java.util.List;

/**
 * Created by nbochkarev on 08.09.2014.
 */
@XmlRootElement(name = "SubscriptionNotificationsConfig")
@XmlAccessorType(XmlAccessType.FIELD)
public class SubscriptionNotificationsConfig   {
    @XmlElement(name="AppUrl")
    String lecmAppUrl;
    @XmlElement(name="From")
    String fromAddress;
    @XmlElementWrapper(name="Documents")
    @XmlElement(name="Document")
    List<DocumentConfig> documents;
    @XmlElementWrapper(name="Templates")
    @XmlElement(name="Template")
    List<TemplateConfig> templates;

    public List<DocumentConfig> getDocuments() {
        return documents;
    }
    public void setLecmAppUrl(String lecmAppUrl) {
        this.lecmAppUrl = lecmAppUrl;
    }
...

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class DocumentConfig  {
    @XmlAttribute(name="Class")
    String className;
    @XmlAttribute(name="EventHandlerClass")
    String eventHandlerClass;
    @XmlElement(name="Recipient")
    List<String> recipients;
    @XmlElement(name="Event")
    List<EventConfig> events;

...

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class EventConfig {
    @XmlAttribute(name="Name")
    String eventName;
    @XmlAttribute(name="Template")
    String template;

...

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class TemplateConfig {
    @XmlAttribute(name="Name")
    String name;
    @XmlAttribute(name="Title")
    String title;
    @XmlAttribute(name="Url")
    String url;
    @XmlValue
    String body;
Пример кода сериализации/десериализации:
import ru.brbpm.subscriptions.SubscriptionNotificationsConfig;
import ru.brbpm.subscriptions.DocumentConfig;
import ru.brbpm.subscriptions.EventConfig;
import ru.brbpm.subscriptions.TemplateConfig;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;


@Test
public void unMarshalingTest() throws JAXBException
{
    System.out.println("Start unMarshalingTest");
    JAXBContext jaxbContext = JAXBContext.newInstance(SubscriptionNotificationsConfig.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

    //We had written this file in marshalling example
    SubscriptionNotificationsConfig config = (SubscriptionNotificationsConfig) jaxbUnmarshaller.unmarshal( new File("C:\\Work\\SubscriptionNotifications.xml") );
    System.out.println(config.getDocuments().size());
    System.out.println(config.getTemplates().size());
}

@Test
public void marshalingTest() throws JAXBException
{
    SubscriptionNotificationsConfig config = new SubscriptionNotificationsConfig();
    config.setLecmAppUrl("http://app");
    DocumentConfig docCfg = new DocumentConfig();
    docCfg.setClassName("class1");
    config.getDocuments().add(docCfg);

    JAXBContext jaxbContext = JAXBContext.newInstance(SubscriptionNotificationsConfig.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
 
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
     
    //Marshal in console
    jaxbMarshaller.marshal(config, System.out);
     
    //Marshal in file
    jaxbMarshaller.marshal(config, new File("c:/temp/config.xml"));
}