Search in sources :

Example 11 with Element

use of org.eclipse.xtext.parsetree.reconstr.bug302128.Element in project pcgen by PCGen.

the class TravelMethodFactory method create.

public static TravelMethod create(Document methodSet) {
    Localized name;
    Map<String, Map<String, Combo>> multByRoadByTerrains;
    Map<String, List<Localized>> terrains2;
    Map<String, Map<Localized, String>> terrainsById2;
    Map<String, List<Localized>> routes2;
    Map<String, Map<Localized, String>> routesById2;
    List<Method> methods;
    Element travel = methodSet.getRootElement();
    NumberFormat nf = getNumberFormat(travel);
    name = new Localized(travel);
    multByRoadByTerrains = new HashMap<>();
    terrains2 = new HashMap<>();
    terrainsById2 = new HashMap<>();
    routes2 = new HashMap<>();
    routesById2 = new HashMap<>();
    methods = new ArrayList<>();
    for (Object methodObj : travel.getChildren()) {
        Element child = (Element) methodObj;
        if (child.getName().equals(XML_ELEMENT_WAY)) {
            String wayId = child.getAttributeValue(XML_ATTRIBUTE_ID);
            List<Localized> terrains = new ArrayList<>();
            terrains2.put(wayId, terrains);
            List<Localized> routes = new ArrayList<>();
            routes2.put(wayId, routes);
            Map<Localized, String> terrainsById = new HashMap<>();
            terrainsById2.put(wayId, terrainsById);
            Map<Localized, String> routesById = new HashMap<>();
            routesById2.put(wayId, routesById);
            for (Object o : child.getChildren()) {
                if (o instanceof Element) {
                    Element grandchild = (Element) o;
                    if (grandchild.getName().equals(XML_ELEMENT_TERRAIN)) {
                        String id = grandchild.getAttributeValue(XML_ATTRIBUTE_ID);
                        Localized terrain = new Localized(grandchild);
                        terrains.add(terrain);
                        terrainsById.put(terrain, id);
                        if (!multByRoadByTerrains.containsKey(id)) {
                            multByRoadByTerrains.put(id, new TreeMap<>());
                        }
                    } else if (grandchild.getName().equals(XML_ELEMENT_ROUTE)) {
                        String id = grandchild.getAttributeValue(XML_ATTRIBUTE_ID);
                        Localized route = new Localized(grandchild);
                        routes.add(route);
                        routesById.put(route, id);
                        for (Object gcc : grandchild.getChildren(XML_ELEMENT_COMBO)) {
                            if (gcc instanceof Element) {
                                Element grandgrandchild = (Element) gcc;
                                String idTerrain = grandgrandchild.getAttributeValue(XML_ELEMENT_TERRAIN);
                                Number mult = parseNumber(nf, grandgrandchild, XML_ATTRIBUTE_MULT, 1);
                                Number addMph = parseNumber(nf, grandgrandchild, XML_ATTRIBUTE_ADDMPH, 0);
                                Number addKmh = parseNumber(nf, grandgrandchild, XML_ATTRIBUTE_ADDKMH, 0);
                                if (!multByRoadByTerrains.containsKey(idTerrain)) {
                                    multByRoadByTerrains.put(idTerrain, new TreeMap<>());
                                }
                                multByRoadByTerrains.get(idTerrain).put(id, new Combo(mult, addMph, addKmh));
                            }
                        }
                    }
                }
            }
        // Sort the terrains by locale name
        // TODO sort, but with one that do toString on the object. Collections.sort(terrains, Collator.getInstance());
        // not sorting routes intentionally (it goes from easier to navigate to hardest)
        } else if (child.getName().equals(XML_ELEMENT_METHOD)) {
            String way = child.getAttributeValue(XML_ELEMENT_WAY);
            Method method = new Method(new Localized(child), way);
            methods.add(method);
            for (Object o : child.getChildren()) {
                if (o instanceof Element) {
                    Element grandchild = (Element) o;
                    if (grandchild.getName().equals(XML_ELEMENT_PACE)) {
                        Localized pace = new Localized(grandchild);
                        boolean useDays = Boolean.parseBoolean(grandchild.getAttributeValue(XML_ATTRIBUTE_DAYS));
                        Localized comment = new Localized(grandchild, XML_ATTRIBUTE_COMMENT);
                        Number mult = parseNumber(nf, grandchild, XML_ATTRIBUTE_MULT, 1);
                        Pace newPace = new Pace(pace, comment, useDays, mult);
                        method.add(newPace);
                    }
                    if (grandchild.getName().equals(XML_ELEMENT_CHOOSE_FROM)) {
                        // XXX other default?
                        Number kmh = parseNumber(nf, grandchild, XML_ATTRIBUTE_KMH, 0.75);
                        // XXX other default?
                        Number mph = parseNumber(nf, grandchild, XML_ATTRIBUTE_MPH, 0.5);
                        // XXX other default?
                        Number hoursInDay = parseNumber(nf, grandchild, XML_ATTRIBUTE_HOURSINDAY, 24);
                        for (Object o2 : grandchild.getChildren(XML_ELEMENT_CHOICE)) {
                            if (o2 instanceof Element) {
                                Element grandgrandchild = (Element) o2;
                                Localized choiceName = new Localized(grandgrandchild);
                                Number mult = parseNumber(nf, grandgrandchild, XML_ATTRIBUTE_MULT, 1);
                                Choice c = new Choice(choiceName, hoursInDay, mult.doubleValue() * kmh.doubleValue(), mult.doubleValue() * mph.doubleValue());
                                method.add(c);
                            }
                        }
                    }
                }
            }
        }
    }
    return new TravelMethodImplementation(name, multByRoadByTerrains, terrains2, terrainsById2, routes2, routesById2, methods);
}
Also used : Choice(plugin.overland.model.TravelMethodImplementation.Choice) HashMap(java.util.HashMap) Element(org.jdom2.Element) ArrayList(java.util.ArrayList) Combo(plugin.overland.model.TravelMethodImplementation.Combo) Pace(plugin.overland.model.TravelMethodImplementation.Pace) ArrayList(java.util.ArrayList) List(java.util.List) Method(plugin.overland.model.TravelMethodImplementation.Method) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) Map(java.util.Map) Localized(plugin.overland.util.Localized) NumberFormat(java.text.NumberFormat)

Example 12 with Element

use of org.eclipse.xtext.parsetree.reconstr.bug302128.Element in project ddf by codice.

the class OpenSearchSource method createResponseFromEntry.

/**
     * Creates a single response from input parameters. Performs XPath operations on the document to
     * retrieve data not passed in.
     *
     * @param entry a single Atom entry
     * @return single response
     * @throws ddf.catalog.source.UnsupportedQueryException
     */
private List<Result> createResponseFromEntry(SyndEntry entry) throws UnsupportedQueryException {
    String id = entry.getUri();
    if (id != null && !id.isEmpty()) {
        id = id.substring(id.lastIndexOf(':') + 1);
    }
    List<SyndContent> contents = entry.getContents();
    List<SyndCategory> categories = entry.getCategories();
    List<Metacard> metacards = new ArrayList<>();
    List<Element> foreignMarkup = entry.getForeignMarkup();
    String relevance = "";
    String source = "";
    for (Element element : foreignMarkup) {
        if (element.getName().equals("score")) {
            relevance = element.getContent(0).getValue();
        }
    }
    //we currently do not support downloading content via an RSS enclosure, this support can be added at a later date if we decide to include it
    for (SyndContent content : contents) {
        MetacardImpl metacard = getMetacardImpl(parseContent(content.getValue(), id));
        metacard.setSourceId(this.shortname);
        String title = metacard.getTitle();
        if (StringUtils.isEmpty(title)) {
            metacard.setTitle(entry.getTitle());
        }
        if (!source.isEmpty()) {
            metacard.setSourceId(source);
        }
        metacards.add(metacard);
    }
    for (int i = 0; i < categories.size() && i < metacards.size(); i++) {
        SyndCategory category = categories.get(i);
        Metacard metacard = metacards.get(i);
        if (StringUtils.isBlank(metacard.getContentTypeName())) {
            ((MetacardImpl) metacard).setContentTypeName(category.getName());
        }
    }
    List<Result> results = new ArrayList<>();
    for (Metacard metacard : metacards) {
        ResultImpl result = new ResultImpl(metacard);
        if (relevance == null || relevance.isEmpty()) {
            LOGGER.debug("couldn't find valid relevance. Setting relevance to 0");
            relevance = "0";
        }
        result.setRelevanceScore(new Double(relevance));
        results.add(result);
    }
    return results;
}
Also used : SyndCategory(com.rometools.rome.feed.synd.SyndCategory) Element(org.jdom2.Element) ArrayList(java.util.ArrayList) ResultImpl(ddf.catalog.data.impl.ResultImpl) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) Result(ddf.catalog.data.Result) Metacard(ddf.catalog.data.Metacard) SyndContent(com.rometools.rome.feed.synd.SyndContent)

Example 13 with Element

use of org.eclipse.xtext.parsetree.reconstr.bug302128.Element in project JMRI by JMRI.

the class AbstractSignalHeadManagerXml method store.

/**
     * Default implementation for storing the contents of a SignalHeadManager.
     * <P>
     * Unlike most other managers, the individual SignalHead objects are stored
     * separately via the configuration system so they can have separate type
     * information.
     *
     * @param o Object to store, of type SignalHeadManager
     * @return Element containing the complete info
     */
@Override
public Element store(Object o) {
    Element signalheads = new Element("signalheads");
    setStoreElementClass(signalheads);
    SignalHeadManager sm = (SignalHeadManager) o;
    if (sm != null) {
        java.util.Iterator<String> iter = sm.getSystemNameList().iterator();
        // don't return an element if there are not signalheads to include
        if (!iter.hasNext()) {
            return null;
        }
        // store the signalheads
        while (iter.hasNext()) {
            String sname = iter.next();
            if (sname == null) {
                log.error("System name null during store, skipped");
                continue;
            }
            log.debug("system name is " + sname);
            SignalHead sub = sm.getBySystemName(sname);
            try {
                Element e = jmri.configurexml.ConfigXmlManager.elementFromObject(sub);
                if (e != null) {
                    signalheads.addContent(e);
                }
            } catch (Exception e) {
                log.error("Error storing signalhead: {}", e, e);
            }
        }
    }
    return signalheads;
}
Also used : AbstractSignalHeadManager(jmri.managers.AbstractSignalHeadManager) SignalHeadManager(jmri.SignalHeadManager) Element(org.jdom2.Element) SignalHead(jmri.SignalHead)

Example 14 with Element

use of org.eclipse.xtext.parsetree.reconstr.bug302128.Element in project JMRI by JMRI.

the class AbstractTurnoutManagerConfigXML method loadTurnouts.

/**
     * Utility method to load the individual Turnout objects. If there's no
     * additional info needed for a specific turnout type, invoke this with the
     * parent of the set of Turnout elements.
     *
     * @param shared Element containing the Turnout elements to load.
     * @param perNode Element containing per-node Turnout data.
     * @return true if succeeded
     */
@SuppressWarnings("unchecked")
public boolean loadTurnouts(Element shared, Element perNode) {
    boolean result = true;
    List<Element> operationList = shared.getChildren("operations");
    if (operationList.size() > 1) {
        log.warn("unexpected extra elements found in turnout operations list");
        result = false;
    }
    if (operationList.size() > 0) {
        TurnoutOperationManagerXml tomx = new TurnoutOperationManagerXml();
        tomx.load(operationList.get(0), null);
    }
    List<Element> turnoutList = shared.getChildren("turnout");
    if (log.isDebugEnabled()) {
        log.debug("Found " + turnoutList.size() + " turnouts");
    }
    TurnoutManager tm = InstanceManager.turnoutManagerInstance();
    try {
        if (shared.getChild("defaultclosedspeed") != null) {
            String closedSpeed = shared.getChild("defaultclosedspeed").getText();
            if (closedSpeed != null && !closedSpeed.equals("")) {
                tm.setDefaultClosedSpeed(closedSpeed);
            }
        }
    } catch (jmri.JmriException ex) {
        log.error(ex.toString());
    }
    try {
        if (shared.getChild("defaultthrownspeed") != null) {
            String thrownSpeed = shared.getChild("defaultthrownspeed").getText();
            if (thrownSpeed != null && !thrownSpeed.equals("")) {
                tm.setDefaultThrownSpeed(thrownSpeed);
            }
        }
    } catch (jmri.JmriException ex) {
        log.error(ex.toString());
    }
    for (int i = 0; i < turnoutList.size(); i++) {
        Element elem = turnoutList.get(i);
        String sysName = getSystemName(elem);
        if (sysName == null) {
            log.error("unexpected null in systemName " + elem);
            result = false;
            break;
        }
        String userName = getUserName(elem);
        checkNameNormalization(sysName, userName, tm);
        if (log.isDebugEnabled()) {
            log.debug("create turnout: (" + sysName + ")(" + (userName == null ? "<null>" : userName) + ")");
        }
        Turnout t = tm.getBySystemName(sysName);
        if (t == null) {
            t = tm.newTurnout(sysName, userName);
        //Nothing is logged in the console window as the newTurnoutFunction already does this.
        } else if (userName != null) {
            t.setUserName(userName);
        }
        // Load common parts
        loadCommon(t, elem);
        // now add feedback if needed
        Attribute a;
        a = elem.getAttribute("feedback");
        if (a != null) {
            try {
                t.setFeedbackMode(a.getValue());
            } catch (IllegalArgumentException e) {
                log.error("Can not set feedback mode: '" + a.getValue() + "' for turnout: '" + sysName + "' user name: '" + (userName == null ? "" : userName) + "'");
                result = false;
            }
        }
        a = elem.getAttribute("sensor1");
        if (a != null) {
            try {
                t.provideFirstFeedbackSensor(a.getValue());
            } catch (jmri.JmriException e) {
                result = false;
            }
        }
        a = elem.getAttribute("sensor2");
        if (a != null) {
            try {
                t.provideSecondFeedbackSensor(a.getValue());
            } catch (jmri.JmriException e) {
                result = false;
            }
        }
        // check for turnout inverted
        t.setInverted(getAttributeBool(elem, "inverted", false));
        // check for turnout decoder
        a = turnoutList.get(i).getAttribute("decoder");
        if (a != null) {
            t.setDecoderName(a.getValue());
        }
        // check for turnout lock mode
        a = turnoutList.get(i).getAttribute("lockMode");
        if (a != null) {
            if (a.getValue().equals("both")) {
                t.enableLockOperation(Turnout.CABLOCKOUT + Turnout.PUSHBUTTONLOCKOUT, true);
            }
            if (a.getValue().equals("cab")) {
                t.enableLockOperation(Turnout.CABLOCKOUT, true);
                t.enableLockOperation(Turnout.PUSHBUTTONLOCKOUT, false);
            }
            if (a.getValue().equals("pushbutton")) {
                t.enableLockOperation(Turnout.PUSHBUTTONLOCKOUT, true);
                t.enableLockOperation(Turnout.CABLOCKOUT, false);
            }
        }
        // check for turnout locked
        a = turnoutList.get(i).getAttribute("locked");
        if (a != null) {
            t.setLocked(Turnout.CABLOCKOUT + Turnout.PUSHBUTTONLOCKOUT, a.getValue().equals("true"));
        }
        // number of bits, if present - if not, defaults to 1
        a = turnoutList.get(i).getAttribute("numBits");
        if (a == null) {
            t.setNumberOutputBits(1);
        } else {
            int iNum = Integer.parseInt(a.getValue());
            if ((iNum == 1) || (iNum == 2)) {
                t.setNumberOutputBits(iNum);
            } else {
                log.warn("illegal number of output bits for control of turnout " + sysName);
                t.setNumberOutputBits(1);
                result = false;
            }
        }
        // control type, if present - if not, defaults to 0
        a = turnoutList.get(i).getAttribute("controlType");
        if (a == null) {
            t.setControlType(0);
        } else {
            int iType = Integer.parseInt(a.getValue());
            if (iType >= 0) {
                t.setControlType(iType);
            } else {
                log.warn("illegal control type for control of turnout " + sysName);
                t.setControlType(0);
                result = false;
            }
        }
        // operation stuff
        List<Element> myOpList = turnoutList.get(i).getChildren("operation");
        if (myOpList.size() > 0) {
            if (myOpList.size() > 1) {
                log.warn("unexpected extra elements found in turnout-specific operations");
                result = false;
            }
            TurnoutOperation toper = TurnoutOperationXml.loadOperation(myOpList.get(0));
            t.setTurnoutOperation(toper);
        } else {
            a = turnoutList.get(i).getAttribute("automate");
            if (a != null) {
                String str = a.getValue();
                if (str.equals("Off")) {
                    t.setInhibitOperation(true);
                } else if (!str.equals("Default")) {
                    t.setInhibitOperation(false);
                    TurnoutOperation toper = TurnoutOperationManager.getInstance().getOperation(str);
                    t.setTurnoutOperation(toper);
                } else {
                    t.setInhibitOperation(false);
                }
            }
        }
        //  set initial state from sensor feedback if appropriate
        t.setInitialKnownStateFromFeedback();
        try {
            t.setDivergingSpeed("Global");
            if (elem.getChild("divergingSpeed") != null) {
                String speed = elem.getChild("divergingSpeed").getText();
                if (speed != null && !speed.equals("") && !speed.contains("Global")) {
                    t.setDivergingSpeed(speed);
                }
            }
        } catch (jmri.JmriException ex) {
            log.error(ex.toString());
        }
        try {
            t.setStraightSpeed("Global");
            if (elem.getChild("straightSpeed") != null) {
                String speed = elem.getChild("straightSpeed").getText();
                if (speed != null && !speed.equals("") && !speed.contains("Global")) {
                    t.setStraightSpeed(speed);
                }
            }
        } catch (jmri.JmriException ex) {
            log.error(ex.toString());
        }
    }
    return result;
}
Also used : TurnoutOperation(jmri.TurnoutOperation) Attribute(org.jdom2.Attribute) Element(org.jdom2.Element) TurnoutManager(jmri.TurnoutManager) TurnoutOperationManagerXml(jmri.configurexml.TurnoutOperationManagerXml) Turnout(jmri.Turnout)

Example 15 with Element

use of org.eclipse.xtext.parsetree.reconstr.bug302128.Element in project JMRI by JMRI.

the class JmriUserPreferencesManager method saveSimplePreferenceState.

private void saveSimplePreferenceState() {
    this.setChangeMade(false);
    if (this.allowSave) {
        Element element = new Element(SETTINGS_ELEMENT, SETTINGS_NAMESPACE);
        getSimplePreferenceStateList().stream().forEach((setting) -> {
            element.addContent(new Element("setting").addContent(setting));
        });
        this.saveElement(element);
        this.resetChangeMade();
    }
}
Also used : Element(org.jdom2.Element)

Aggregations

Element (org.jdom2.Element)829 Attribute (org.jdom2.Attribute)76 Document (org.jdom2.Document)75 Test (org.junit.Test)70 File (java.io.File)53 ArrayList (java.util.ArrayList)45 JDOMException (org.jdom2.JDOMException)37 IOException (java.io.IOException)34 HashMap (java.util.HashMap)28 NamedIcon (jmri.jmrit.catalog.NamedIcon)27 List (java.util.List)26 XmlFile (jmri.jmrit.XmlFile)24 SAXBuilder (org.jdom2.input.SAXBuilder)21 Turnout (jmri.Turnout)20 DataConversionException (org.jdom2.DataConversionException)20 DocType (org.jdom2.DocType)19 Editor (jmri.jmrit.display.Editor)18 XMLOutputter (org.jdom2.output.XMLOutputter)18 Namespace (org.jdom2.Namespace)17 Point (java.awt.Point)15