001package jmri.configurexml;
002
003import jmri.LocoAddress;
004import org.jdom2.Element;
005import org.slf4j.Logger;
006import org.slf4j.LoggerFactory;
007
008/**
009 * Handle XML configuration for LocoAddress objects.
010 *
011 * @author Bob Jacobsen Copyright: Copyright (c) 2005
012 */
013public class LocoAddressXml extends jmri.configurexml.AbstractXmlAdapter {
014
015    public LocoAddressXml() {
016    }
017
018    /**
019     * Default implementation for storing the contents of a LocoAddress
020     *
021     * @param o Object to store, of type LocoAddress
022     * @return Element containing the complete info
023     */
024    @Override
025    public Element store(Object o) {
026        LocoAddress p = (LocoAddress) o;
027
028        Element element = new Element("locoaddress");
029
030        // include contents, we shall also store the old format for backward compatability
031        DccLocoAddressXml adapter = new DccLocoAddressXml();
032
033        element.addContent(adapter.store(p));
034
035        if (p != null) {
036            element.addContent(new Element("number").addContent("" + p.getNumber()));
037            element.addContent(new Element("protocol").addContent(p.getProtocol().getShortName()));
038        } else {
039            element.addContent(new Element("number").addContent(""));
040            element.addContent(new Element("protocol").addContent(""));
041        }
042
043        return element;
044    }
045
046    @Override
047    public boolean load(Element shared, Element perNode) {
048        log.error("Invalid method called");
049        return false;
050    }
051
052    public LocoAddress getAddress(Element element) {
053        if (element.getChild("number") == null) {
054            DccLocoAddressXml adapter = new DccLocoAddressXml();
055            return adapter.getAddress(element.getChild("dcclocoaddress"));
056        }
057        int addr = 0;
058        try {
059            addr = Integer.parseInt(element.getChild("number").getText());
060        } catch (java.lang.NumberFormatException e) {
061            return null;
062        }
063        String protocol = element.getChild("protocol").getText();
064        LocoAddress.Protocol prot = LocoAddress.Protocol.getByShortName(protocol);
065        return new jmri.DccLocoAddress(addr, prot);
066    }
067
068    private final static Logger log = LoggerFactory.getLogger(LocoAddressXml.class);
069}