Example usage for org.jdom2 Element getAttribute

List of usage examples for org.jdom2 Element getAttribute

Introduction

In this page you can find the example usage for org.jdom2 Element getAttribute.

Prototype

public Attribute getAttribute(final String attname) 

Source Link

Document

This returns the attribute for this element with the given name and within no namespace, or null if no such attribute exists.

Usage

From source file:insa.h4401.utils.PlanningDocument.java

/**
 * Returns a collection of timeslots extracted from the XML description
 *
 * @param map The map document//  www  .j  av a 2s  .  co m
 * @return the list of timeSlots
 */
public ArrayList<TimeSlot> getTimeSlots(Map map) {
    // Get all the XML nodes representing timeslots
    List<Element> timeSlotElements = getDom().getRootElement().getChildren("PlagesHoraires").get(0)
            .getChildren();
    // Create the list f timeslots that will be returned 
    ArrayList<TimeSlot> timeslots = new ArrayList<>();
    // Loop on timeslots XML nodes
    for (Element timeSlotElement : timeSlotElements) {
        // Create current timeslot
        TimeSlot ts;
        // Get all deliveries scheduled in the current timeslot
        List<Element> deliveryElements = timeSlotElement.getChildren("Livraisons").get(0).getChildren();
        // Create a list of deliveries to attach to timeslot
        ArrayList<Delivery> deliveries = new ArrayList<>();
        // Loop on each delivery
        for (Element deliveryElement : deliveryElements) {
            // Create a delivery element
            Delivery delivery = null;
            try {
                int deliveryId = deliveryElement.getAttribute("id").getIntValue();
                int nodeId = deliveryElement.getAttribute("adresse").getIntValue();
                delivery = new Delivery(deliveryId, map.getNodeById(nodeId));
            } catch (DataConversionException ex) {
                Logger.getLogger(PlanningDocument.class.getName()).log(Level.SEVERE, null, ex);
            }
            // Add the delivery to the collection
            deliveries.add(delivery);
        }
        // Get timeslot attributes 
        int startTime = TypeWrapper.xmlTimeStringToSeconds(timeSlotElement.getAttributeValue("heureDebut"));
        int endTime = TypeWrapper.xmlTimeStringToSeconds(timeSlotElement.getAttributeValue("heureFin"));
        // Create new timeslot
        ts = new TimeSlot(startTime, endTime, deliveries);
        // Add new timeslot to the collection
        timeslots.add(ts);
    }

    // Return the collection of timeslots
    return timeslots;
}

From source file:insa.h4401.utils.PlanningDocument.java

/**
 * Checks the semantic integrity of the XML description using the given Map
 *
 * @param map Map used to check the semantic
 * @return true if the document is correct
 *//*from w w w .  ja va2s  . c  o  m*/
public boolean checkIntegrity(Map map) {
    Element root = getDom().getRootElement();
    // TEST : check if there is only one warehouse
    if (root.getChildren("Entrepot").size() != 1) {
        setErrorMsg("The planning specifies zero or more than one warehouse !");
        return false; // Interrupt check here
    } else {
        // TEST : check warehouse id
        if (root.getChild("Entrepot").getAttributeValue("adresse") != null) {
            try {
                // TEST : check if id of the node referenced by the warehouse exists in the map 
                int id = root.getChild("Entrepot").getAttribute("adresse").getIntValue();
                if (map.getNodeById(id) == null) {
                    setErrorMsg("The node referenced by the warehouse is missing in the map !");
                    return false; // Interrupt check here
                }
            } catch (DataConversionException ex) {
                Logger.getLogger(PlanningDocument.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            setErrorMsg("Missing <adresse> attribute in warehouse node !");
            return false; // Interrupt check here
        }
        // TEST : check if planning file specifies one or more timeslots
        if (root.getChildren("PlagesHoraires").get(0).getChildren().size() < 1) {
            setErrorMsg("At least one timeslot should be specified by planning file !");
            return false; // Interrupt check here
        }

        // TEST : check if each timeSlot contains at least one delivery
        for (Element ts : root.getChildren("PlagesHoraires").get(0).getChildren()) {

            // TEST : check if timeSlot attributes are not missing and correct
            int startTime;
            int endTime;
            if (ts.getAttributeValue("heureDebut") != null) {
                startTime = TypeWrapper.xmlTimeStringToSeconds(ts.getAttributeValue("heureDebut"));
            } else {
                setErrorMsg("Missing <heureDebut> attribute in at least one timeSlot !");
                return false; // Interrupt check here
            }
            if (ts.getAttributeValue("heureFin") != null) {
                endTime = TypeWrapper.xmlTimeStringToSeconds(ts.getAttributeValue("heureFin"));
            } else {
                setErrorMsg("Missing <heureFin> attribute in at least one timeSlot !");
                return false; // Interrupt check here
            }

            // TEST : check if endTime > startTime
            if (startTime >= endTime) {
                setErrorMsg("At least one timeSlot has an end time before its start time !");
                return false; // Interrupt check here
            }

            List<Element> deliveries = ts.getChildren("Livraisons").get(0).getChildren();
            if (deliveries.size() < 1) {
                setErrorMsg("All timeslots must specify at least one delivery !");
                return false; // Interrupt check here
            }
            ArrayList<Integer> ids = new ArrayList<>();
            ArrayList<Integer> addresses = new ArrayList<>();

            for (Element delivery : deliveries) {
                // TEST : if delivery has an address
                if (delivery.getAttributeValue("adresse") == null) {
                    setErrorMsg("At least one delivery doesn't reference it's node id !");
                    return false; // Interrupt check here
                } else {
                    try {

                        int address = delivery.getAttribute("adresse").getIntValue();
                        addresses.add(address);
                        int id = delivery.getAttribute("id").getIntValue();
                        ids.add(id);
                        // TEST : if delivery reference an existing node in the map
                        if (map.getNodeById(id) == null) {
                            setErrorMsg("At least one delivery has its node missing in the map !");
                            return false; // Interrupt check here
                        }
                    } catch (DataConversionException ex) {
                        Logger.getLogger(PlanningDocument.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            // TEST : check if two nodes share the same id in the timeslot
            for (Integer id : ids) {
                if (Collections.frequency(ids, id) > 1) {
                    setErrorMsg("At least two deliveries share the same id !");
                    return false; // Interrupt check here
                }
            }
            // TEST : check if two nodes share the same address in the timeslot
            for (Integer address : addresses) {
                if (Collections.frequency(addresses, address) > 1) {
                    setErrorMsg("At least two deliveries share the same <adresse> !");
                    return false; // Interrupt check here
                }
            }
        }
    }

    return true;
}

From source file:instanceXMLParser.Instance.java

public void buildINstanceJDom(String path) {
    //creating JDOM SAX parser
    SAXBuilder builder = new SAXBuilder();

    //reading XML document
    Document xml = null;/*from w  ww. j a v  a  2s.co  m*/
    try {
        xml = builder.build(new File(path));
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //getting root element from XML document
    Element root = xml.getRootElement();
    List<Element> list = root.getChildren();
    for (Element element : list) {
        List<Element> list1;
        if (element.getName().equals("board")) {
            list1 = element.getChildren();
            for (Element element2 : list1) {
                if (element2.getName().equals("size_n")) {//size of the space
                    size_n = Integer.parseInt(element2.getText());
                } else if (element2.getName().equals("size_m")) {//size of the space
                    size_m = Integer.parseInt(element2.getText());
                    //inizializzo matrice solo dop aver letto le due dimensioni
                    //NOTA CHE SIZE_M E SIZE_N devono essere i primi elementi e in quell ordine!
                    boardState = new CellLogicalState[size_n][size_m];
                    for (int j = 0; j < size_n; j++) {
                        for (int k = 0; k < size_m; k++) {
                            boardState[j][k] = new CellLogicalState();
                        }
                    }

                } else if (element2.getName().equals("tile_state")) {//tile states
                    int x, y, value;
                    CellLogicalState state = new CellLogicalState();
                    String stateString;
                    x = Integer.parseInt(element2.getAttribute("x").getValue());
                    y = Integer.parseInt(element2.getAttribute("y").getValue());

                    stateString = element2.getText();

                    if (stateString.equals("obstacle")) {
                        state.setLocState(LocationState.Obstacle);
                    } else if (stateString.equals("dirty")) {
                        state.setLocState(LocationState.Dirty);
                        value = 1;
                        if (element2.getAttribute("value").getValue() != null) {
                            value = Integer.parseInt(element2.getAttribute("value").getValue());
                        }
                        state.setDirtyAmount(value);

                    }

                    boardState[x][y] = state;

                }
            }
        } else if (element.getName().equals("agent")) {//agent
            List<Element> list3 = element.getChildren();
            for (Element element3 : list3) {
                if (element3.getName().equals("x")) {
                    agentPos.setX(Integer.parseInt(element3.getValue()));
                } else if (element3.getName().equals("y")) {
                    agentPos.setY(Integer.parseInt(element3.getValue()));
                } else if (element3.getName().equals("energy")) {
                    energy = Double.parseDouble(element3.getValue());
                }
            }
        } else if (element.getName().equals("base")) {//agent
            List<Element> list3 = element.getChildren();
            for (Element element3 : list3) {
                if (element3.getName().equals("x")) {
                    basePos.setX(Integer.parseInt(element3.getValue()));
                } else if (element3.getName().equals("y")) {
                    basePos.setY(Integer.parseInt(element3.getValue()));
                }
            }
        } else if (element.getName().equals("action_costs")) {//agent
            List<Element> list3 = element.getChildren();
            for (Element element3 : list3) {
                if (element3.getName().equals("up") || element3.getName().equals("left")
                        || element3.getName().equals("down") || element3.getName().equals("right")
                        || element3.getName().equals("suck")) {

                    actionCosts.put(element3.getName(), Double.parseDouble(element3.getValue()));

                }
            }
        }

    }
}

From source file:io.wcm.handler.richtext.impl.RichTextRewriteContentHandlerImpl.java

License:Apache License

/**
 * Support legacy data structures where link metadata is stored as JSON fragment in single HTML5 data attribute.
 * @param pResourceProps Valuemap to write link metadata to
 * @param element Link element/*  w w w .  j a  v  a  2s . c  om*/
 */
private boolean getAnchorLegacyMetadataFromSingleData(ValueMap pResourceProps, Element element) {
    boolean foundAny = false;

    JSONObject metadata = null;
    Attribute dataAttribute = element.getAttribute("data");
    if (dataAttribute != null) {
        String metadataString = dataAttribute.getValue();
        if (StringUtils.isNotEmpty(metadataString)) {
            try {
                metadata = new JSONObject(metadataString);
            } catch (JSONException ex) {
                RichTextHandlerImpl.log.debug("Invalid link metadata: " + metadataString, ex);
            }
        }
    }
    if (metadata != null) {
        JSONArray names = metadata.names();
        for (int i = 0; i < names.length(); i++) {
            String name = names.optString(i);
            pResourceProps.put(name, metadata.opt(name));
            foundAny = true;
        }
    }

    return foundAny;
}

From source file:jmri.implementation.configurexml.DccSignalHeadXml.java

License:Open Source License

/**
 * Create a LsDecSignalHead//from   w  ww .  j  ava 2s  .co m
 *
 * @param element Top level Element to unpack.
 * @return true if successful
 */
public boolean load(Element element) {
    // put it together
    String sys = getSystemName(element);
    String uname = getUserName(element);
    DccSignalHead h;
    if (uname == null) {
        h = new DccSignalHead(sys);
    } else {
        h = new DccSignalHead(sys, uname);
    }

    loadCommon(h, element);

    if (element.getChild("useAddressOffSet") != null) {
        if (element.getChild("useAddressOffSet").getText().equals("yes")) {
            h.useAddressOffSet(true);
        }
    }

    List<Element> list = element.getChildren("aspect");
    for (Element e : list) {
        String aspect = e.getAttribute("defines").getValue();
        int number = -1;
        try {
            String value = e.getChild("number").getValue();
            number = Integer.parseInt(value);

        } catch (Exception ex) {
            log.error("failed to convert DCC number");
        }
        int indexOfAspect = -1;

        for (int i = 0; i < h.getValidStates().length; i++) {
            if (h.getValidStateNames()[i].equals(aspect)) {
                indexOfAspect = i;
                break;
            }
        }
        if (indexOfAspect != -1) {
            h.setOutputForAppearance(h.getValidStates()[indexOfAspect], number);
        }
    }

    InstanceManager.signalHeadManagerInstance().register(h);
    return true;
}

From source file:jmri.implementation.configurexml.LsDecSignalHeadXml.java

License:Open Source License

NamedBeanHandle<Turnout> loadTurnout(Object o) {
    Element e = (Element) o;
    String name = e.getAttribute("systemName").getValue();
    Turnout t = InstanceManager.turnoutManagerInstance().getTurnout(name);
    return jmri.InstanceManager.getDefault(jmri.NamedBeanHandleManager.class).getNamedBeanHandle(name, t);
}

From source file:jmri.implementation.configurexml.LsDecSignalHeadXml.java

License:Open Source License

int loadTurnoutStatus(Object o) {
    Element e = (Element) o;
    String rState = e.getAttribute("state").getValue();
    int tSetState = Turnout.CLOSED;
    if (rState.equals("THROWN")) {
        tSetState = Turnout.THROWN;//  w w  w.ja va  2 s  .  c o m
    }
    return tSetState;
}

From source file:jmri.implementation.configurexml.MergSD2SignalHeadXml.java

License:Open Source License

/**
 * Create a MergSD2SignalHead/*from  www.  j a v  a2 s.co  m*/
 *
 * @param element Top level Element to unpack.
 * @return true if successful
 */
public boolean load(Element element) {
    int aspects = 2;
    List<Element> l = element.getChildren("turnoutname");
    if (l.size() == 0) {
        l = element.getChildren("turnout");
        aspects = l.size() + 1;
    }
    NamedBeanHandle<Turnout> input1 = null;
    NamedBeanHandle<Turnout> input2 = null;
    NamedBeanHandle<Turnout> input3 = null;
    String yesno = "";
    boolean feather = false;
    boolean home = true;

    // put it together
    String sys = getSystemName(element);
    String uname = getUserName(element);

    if (element.getAttribute("feather") != null) {
        yesno = element.getAttribute("feather").getValue();
    }
    if ((yesno != null) && (!yesno.equals(""))) {
        if (yesno.equals("yes")) {
            feather = true;
        } else if (yesno.equals("no")) {
            feather = false;
        }
    }

    if (element.getAttribute("home") != null) {
        yesno = element.getAttribute("home").getValue();
    }
    if ((yesno != null) && (!yesno.equals(""))) {
        if (yesno.equals("yes")) {
            home = true;
        } else if (yesno.equals("no")) {
            home = false;
        }
    }
    try {
        aspects = element.getAttribute("aspects").getIntValue();
    } catch (org.jdom2.DataConversionException e) {
        log.warn("Could not parse level attribute!");
    } catch (NullPointerException e) { // considered normal if the attribute not present
    }

    SignalHead h;
    //int aspects = l.size()+1;  //Number of aspects is equal to the number of turnouts used plus 1.
    //@TODO could re-arange this so that it falls through
    switch (aspects) {
    case 2:
        input1 = loadTurnout(l.get(0));
        break;
    case 3:
        input1 = loadTurnout(l.get(0));
        input2 = loadTurnout(l.get(1));
        break;
    case 4:
        input1 = loadTurnout(l.get(0));
        input2 = loadTurnout(l.get(1));
        input3 = loadTurnout(l.get(2));
        break;
    default:
        log.error("incorrect number of aspects " + aspects + " when loading Signal " + sys);
    }
    if (uname == null) {
        h = new MergSD2SignalHead(sys, aspects, input1, input2, input3, feather, home);
    } else {
        h = new MergSD2SignalHead(sys, uname, aspects, input1, input2, input3, feather, home);
    }

    loadCommon(h, element);

    InstanceManager.signalHeadManagerInstance().register(h);
    return true;
}

From source file:jmri.implementation.configurexml.MergSD2SignalHeadXml.java

License:Open Source License

NamedBeanHandle<Turnout> loadTurnout(Object o) {
    Element e = (Element) o;

    if (e.getName().equals("turnout")) {
        String name = e.getAttribute("systemName").getValue();
        Turnout t;//from ww w .  j a va2  s.  c o m
        if (e.getAttribute("userName") != null && !e.getAttribute("userName").getValue().equals("")) {
            name = e.getAttribute("userName").getValue();
            t = InstanceManager.turnoutManagerInstance().getTurnout(name);
        } else {
            t = InstanceManager.turnoutManagerInstance().getBySystemName(name);
        }
        return jmri.InstanceManager.getDefault(jmri.NamedBeanHandleManager.class).getNamedBeanHandle(name, t);
    } else {
        String name = e.getText();
        Turnout t = InstanceManager.turnoutManagerInstance().provideTurnout(name);
        return jmri.InstanceManager.getDefault(jmri.NamedBeanHandleManager.class).getNamedBeanHandle(name, t);
    }
}

From source file:jmri.jmrit.dispatcher.OptionsFile.java

License:Open Source License

public void readDispatcherOptions(DispatcherFrame f) throws org.jdom2.JDOMException, java.io.IOException {
    log.debug("entered readDispatcherOptions");
    // check if file exists
    if (checkFile(defaultFileName)) {
        // file is present, 
        root = rootFromName(defaultFileName);
        dispatcher = f;/* w  w  w  .ja  v  a  2s  .com*/
        if (root != null) {
            // there is a file
            Element options = root.getChild("options");
            if (options != null) {
                // there are options defined, read and set Dispatcher options
                if (options.getAttribute("lename") != null) {
                    // there is a layout editor name selected
                    String leName = options.getAttribute("lename").getValue();
                    // get list of Layout Editor panels
                    ArrayList<LayoutEditor> layoutEditorList = jmri.jmrit.display.PanelMenu.instance()
                            .getLayoutEditorPanelList();
                    if (layoutEditorList.size() == 0) {
                        log.warn("Dispatcher options specify a Layout Editor panel that is not present.");
                    } else {
                        boolean found = false;
                        for (int i = 0; i < layoutEditorList.size(); i++) {
                            if (leName.equals(layoutEditorList.get(i).getTitle())) {
                                found = true;
                                dispatcher.setLayoutEditor(layoutEditorList.get(i));
                            }
                        }
                        if (!found) {
                            log.warn("Layout Editor panel - " + leName + " - not found.");
                        }
                    }
                }
                if (options.getAttribute("usesignaltype") != null) {
                    dispatcher.setSignalType(0x00);
                    if (options.getAttribute("usesignaltype").getValue().equals("signalmast")) {
                        dispatcher.setSignalType(0x01);
                    }
                }
                if (options.getAttribute("useconnectivity") != null) {
                    dispatcher.setUseConnectivity(true);
                    if (options.getAttribute("useconnectivity").getValue().equals("no")) {
                        dispatcher.setUseConnectivity(false);
                    }
                }
                if (options.getAttribute("trainsfromroster") != null) {
                    dispatcher.setTrainsFromRoster(true);
                    if (options.getAttribute("trainsfromroster").getValue().equals("no")) {
                        dispatcher.setTrainsFromRoster(false);
                    }
                }
                if (options.getAttribute("trainsfromtrains") != null) {
                    dispatcher.setTrainsFromTrains(true);
                    if (options.getAttribute("trainsfromtrains").getValue().equals("no")) {
                        dispatcher.setTrainsFromTrains(false);
                    }
                }
                if (options.getAttribute("trainsfromuser") != null) {
                    dispatcher.setTrainsFromUser(true);
                    if (options.getAttribute("trainsfromuser").getValue().equals("no")) {
                        dispatcher.setTrainsFromUser(false);
                    }
                }
                if (options.getAttribute("autoallocate") != null) {
                    dispatcher.setAutoAllocate(false);
                    if (options.getAttribute("autoallocate").getValue().equals("yes")) {
                        dispatcher.setAutoAllocate(true);
                    }
                }
                if (options.getAttribute("autoturnouts") != null) {
                    dispatcher.setAutoTurnouts(true);
                    if (options.getAttribute("autoturnouts").getValue().equals("no")) {
                        dispatcher.setAutoTurnouts(false);
                    }
                }
                if (options.getAttribute("hasoccupancydetection") != null) {
                    dispatcher.setHasOccupancyDetection(true);
                    if (options.getAttribute("hasoccupancydetection").getValue().equals("no")) {
                        dispatcher.setHasOccupancyDetection(false);
                    }
                }
                if (options.getAttribute("shortactivetrainnamesr") != null) {
                    dispatcher.setShortActiveTrainNames(true);
                    if (options.getAttribute("shortactivetrainnames").getValue().equals("no")) {
                        dispatcher.setShortActiveTrainNames(false);
                    }
                }
                if (options.getAttribute("shortnameinblock") != null) {
                    dispatcher.setShortNameInBlock(true);
                    if (options.getAttribute("shortnameinblock").getValue().equals("no")) {
                        dispatcher.setShortNameInBlock(false);
                    }
                }
                if (options.getAttribute("extracolorforallocated") != null) {
                    dispatcher.setExtraColorForAllocated(true);
                    if (options.getAttribute("extracolorforallocated").getValue().equals("no")) {
                        dispatcher.setExtraColorForAllocated(false);
                    }
                }
                if (options.getAttribute("nameinallocatedblock") != null) {
                    dispatcher.setNameInAllocatedBlock(true);
                    if (options.getAttribute("nameinallocatedblock").getValue().equals("no")) {
                        dispatcher.setNameInAllocatedBlock(false);
                    }
                }
                if (options.getAttribute("supportvsdecoder") != null) {
                    dispatcher.setSupportVSDecoder(true);
                    if (options.getAttribute("supportvsdecoder").getValue().equals("no")) {
                        dispatcher.setSupportVSDecoder(false);
                    }
                }
                if (options.getAttribute("layoutscale") != null) {
                    String s = (options.getAttribute("layoutscale")).getValue();
                    for (int i = 1; i <= Scale.NUM_SCALES; i++) {
                        if (Scale.getShortScaleID(i).equals(s)) {
                            dispatcher.setScale(i);
                        }
                    }
                }
                if (options.getAttribute("usescalemeters") != null) {
                    dispatcher.setUseScaleMeters(true);
                    if (options.getAttribute("usescalemeters").getValue().equals("no")) {
                        dispatcher.setUseScaleMeters(false);
                    }
                }
                if (options.getAttribute("userosterentryinblock") != null) {
                    dispatcher.setRosterEntryInBlock(false);
                    if (options.getAttribute("userosterentryinblock").getValue().equals("yes")) {
                        dispatcher.setRosterEntryInBlock(true);
                    }
                }
            }
        }
    }
}