Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document getRootElement.

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:information.Information.java

License:Open Source License

private static void leerDatos() {
    java.io.File archivo = new java.io.File(informationPath);
    SAXBuilder saxBuilder = new SAXBuilder();
    try {/*from  w  ww .  j  av a  2s . co m*/
        Document documento = saxBuilder.build(archivo);
        Element raiz = documento.getRootElement();
        List<Element> elementosSalon = raiz.getChildren("Salon");
        for (Element salone : elementosSalon) {
            Salon salon = new Salon(salone.getAttributeValue("Nombre"));
            List<Element> elementosSala = salone.getChildren("Sala");
            for (Element salae : elementosSala) {
                Room sala = new Room(salae.getAttributeValue("Nombre"),
                        Boolean.parseBoolean(salae.getAttributeValue("Horizontal")),
                        Integer.parseInt(salae.getAttributeValue("SufijoIP")));
                List<Element> elementosFila = salae.getChildren("Fila");
                for (Element filae : elementosFila) {
                    Row fila = new Row(sala.isHorizontal());
                    List<Element> elementosEquipo = filae.getChildren("Equipo");
                    for (Element equipoe : elementosEquipo) {
                        ServerComputer equipo = new ServerComputer(sala);
                        equipo.setComputerNumber(Integer.parseInt(equipoe.getAttributeValue("Numero")));
                        equipo.setIP(equipoe.getChildText("IP"));
                        equipo.setMac(equipoe.getChildText("Mac"));
                        equipo.setHostname(equipoe.getChildText("Hostname"));
                        List<Element> elementosEjecucion = equipoe.getChildren("Ejecucion");
                        for (Element ejecucione : elementosEjecucion) {
                            String[] resultado = { ejecucione.getAttributeValue("Orden"),
                                    ejecucione.getAttributeValue("Resultado") };
                            equipo.addResult(resultado);
                        }
                        fila.addComputer(equipo);
                    }
                    sala.addRow(fila);
                }
                salon.addRoom(sala);
            }
            salons.add(salon);
        }
    } catch (JDOMException ex) {
        Logger.getLogger(Information.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Information.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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;
    try {//from   w w  w  .j av  a  2s  .co  m
        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:interfacermi.Traza.java

public void insertarTraza(String hora, String actor, String accion) {

    Document document = null;
    Element root = null;// ww  w .ja v  a2s  . c o  m
    File xmlFile = new File("Traza.xml");
    //Se comprueba si el archivo XML ya existe o no.
    if (xmlFile.exists()) {
        FileInputStream fis;
        try {
            fis = new FileInputStream(xmlFile);
            SAXBuilder sb = new SAXBuilder();
            document = sb.build(fis);
            //Si existe se obtiene su nodo raiz.
            root = document.getRootElement();
            fis.close();
        } catch (JDOMException | IOException e) {
            e.printStackTrace();
        }
    } else {
        //Si no existe se crea su nodo raz.
        document = new Document();
        root = new Element("Traza");
    }

    //Se crea un nodo Hecho para insertar la informacin.
    Element nodohecho = new Element("Hecho");
    //Se crea un nodo hora para insertar la informacin correspondiente a la hora.
    Element nodohora = new Element("Hora");
    //Se crea un nodo actor para insertar la informacin correspondiente al actor.
    Element nodoactor = new Element("Actor");
    //Se crea un nodo accion para insertar la informacin correspondiente a la accin.
    Element nodoaccion = new Element("Accion");

    //Se asignan los valores enviados para cada nodo.
    nodohora.setText(hora);
    nodoactor.setText(actor);
    nodoaccion.setText(accion);
    //Se aade el contenido al nodo Hecho.  
    nodohecho.addContent(nodohora);
    nodohecho.addContent(nodoactor);
    nodohecho.addContent(nodoaccion);
    //Se aade el nodo Hecho al nodo raz.
    root.addContent(nodohecho);
    document.setContent(root);

    //Se procede a exportar el nuevo o actualizado archivo de traza XML   
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());

    try {
        xmlOutput.output(document, new FileWriter("Traza.xml"));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:io.LoadSave.java

License:Open Source License

/**
 * loads a .oger file/*  w w w  .  ja  va2  s  .  c  om*/
 */
public static void load() {

    ParticipantTableModel tableModel = ParticipantTableModel.getInstance();
    RoomTreeModel slotModel = RoomTreeModel.getInstance();

    if (!Main.isSaved()) {

        // current game must be saved
        int saveResult = JOptionPane.showOptionDialog(null, "Mchten Sie vorher speichern?", "Speichern?",
                JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null);
        if (saveResult == JOptionPane.YES_OPTION) {
            save();
        }
    }

    Document document = new Document();
    Element root = new Element("root");

    SAXBuilder saxBuilder = new SAXBuilder();

    // Dialog to choose the oger file to parse
    JFileChooser fileChoser = new JFileChooser(".xml");
    fileChoser.setFileFilter(new OgerDialogFilter());

    int result = fileChoser.showOpenDialog(null);
    switch (result) {

    case JFileChooser.APPROVE_OPTION:
        try {
            // clear models
            tableModel.clear();
            slotModel.clear();

            // Create a new JDOM document from a oger file
            File file = fileChoser.getSelectedFile();
            document = saxBuilder.build(file);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Fehler beim Parsen der Datei!");
        }

        // Initialize the root Element with the document root Element
        try {
            root = document.getRootElement();
        } catch (NullPointerException e) {
            JOptionPane.showMessageDialog(null, "Fehler beim Parsen der Datei!");
        }

        // participants
        Element participantsElement = root.getChild("allParticipants");

        for (Element participant : participantsElement.getChildren("participant")) {
            String firstName = participant.getAttributeValue("firstName");
            String lastName = participant.getAttributeValue("lastName");
            String mail = participant.getAttributeValue("mail");
            int group = Integer.parseInt(participant.getAttributeValue("group"));

            Participant newParticipant = new Participant(firstName, lastName, mail, group);
            tableModel.addParticipant(newParticipant);
        }

        // slots
        final DateFormat dateFormat = new SimpleDateFormat("dd.MM.yy");
        final DateFormat timeFormat = new SimpleDateFormat("HH:mm");
        boolean parseFailed = false;

        Element slotsElement = root.getChild("Slots");
        for (Element slotElement : slotsElement.getChildren("Slot")) {
            Date date = null;
            Date beginTime = null;
            Date endTime = null;

            try {
                date = dateFormat.parse(slotElement.getAttributeValue("Date"));
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(null, "Konnte Slot-Datum nicht parsen", "Datum nicht erkannt",
                        JOptionPane.ERROR_MESSAGE);
                parseFailed = true;
            }

            try {
                beginTime = timeFormat.parse(slotElement.getAttributeValue("Begin"));
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(null, "Konnte Slot-Angfangszeit nicht parsen",
                        "Anfangszeit nicht erkannt", JOptionPane.ERROR_MESSAGE);
                parseFailed = true;
            }

            try {
                endTime = timeFormat.parse(slotElement.getAttributeValue("End"));
            } catch (ParseException e) {
                JOptionPane.showMessageDialog(null, "Konnte Slot-Endzeit nicht parsen", "Endzeit nicht erkannt",
                        JOptionPane.ERROR_MESSAGE);
                parseFailed = true;
            }

            if (!parseFailed) {
                Slot slot = new Slot(date, beginTime, endTime);
                SlotNode newSlotNode = new SlotNode();
                newSlotNode.setUserObject(slot);
                ((DefaultMutableTreeNode) RoomTreeModel.getInstance().getRoot()).add(newSlotNode);

                // Rooms
                Element roomsElement = slotElement.getChild("AllRooms");
                for (Element roomElement : roomsElement.getChildren("Room")) {
                    parseFailed = false;

                    String roomString = roomElement.getAttributeValue("ID");
                    Date roomBeginTime = null;
                    Date roomEndTime = null;

                    Boolean hasBeamer = false;
                    String hasBeamerString = roomElement.getAttributeValue("Beamer");
                    if (hasBeamerString.equals("false")) {
                        hasBeamer = false;
                    } else if (hasBeamerString.equals("true")) {
                        hasBeamer = true;
                    } else {
                        JOptionPane.showMessageDialog(null, "Beamer nicht erkannt", "Beamer nicht erkannt",
                                JOptionPane.ERROR_MESSAGE);
                        parseFailed = true;
                    }

                    try {
                        roomBeginTime = timeFormat.parse(roomElement.getAttributeValue("Begin"));
                    } catch (ParseException e) {
                        JOptionPane.showMessageDialog(null, "Konnte Slot-Angfangszeit nicht parsen",
                                "Anfangszeit nicht erkannt", JOptionPane.ERROR_MESSAGE);
                        parseFailed = true;
                    }

                    try {
                        roomEndTime = timeFormat.parse(roomElement.getAttributeValue("End"));
                    } catch (ParseException e) {
                        JOptionPane.showMessageDialog(null, "Konnte Slot-Endzeit nicht parsen",
                                "Endzeit nicht erkannt", JOptionPane.ERROR_MESSAGE);
                        parseFailed = true;
                    }

                    if (!parseFailed) {
                        Room room = new Room(roomString, hasBeamer, roomBeginTime, roomEndTime);

                        RoomNode newRoomNode = new RoomNode();
                        newRoomNode.setUserObject(room);

                        newSlotNode.add(newRoomNode);
                        Gui.getRoomTree().updateUI();
                    }
                }

                Gui.getRoomTree().updateUI();
            }
        }

    }

}

From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java

License:Apache License

protected Element parseXmlResponse(Response response, String method) {
    try {/*from w  ww.j a va 2  s . c  o  m*/
        Document d = new SAXBuilder().build(response.body().charStream());

        return d.getRootElement();
    } catch (IOException | JDOMException e) {
        throw new ElbException(e);
    }
}

From source file:io.sitespeed.jenkins.xml.impl.XMLToPageJDOM.java

License:Open Source License

public Page get(File pageXML) throws IOException {

    final SAXBuilder b = new SAXBuilder(new XMLReaderSAX2Factory(false));
    Document doc;
    try {/*from  ww w .j a  v a2s. c o m*/
        doc = b.build(pageXML);
    } catch (JDOMException e) {
        throw new IOException(e);
    }

    int numOfHosts = doc.getRootElement().getChild("g").getChild("ydns").getChild("components")
            .getChildren("item").size();

    String url = doc.getRootElement().getChildText("curl");
    Integer score = new Integer(doc.getRootElement().getChildText("o"));

    return new Page(url, score, getRules(doc), numOfHosts, getAssetsSize(doc), getNumberOfAssets(doc));
}

From source file:io.sitespeed.jenkins.xml.impl.XMLToPageJDOM.java

License:Open Source License

private Map<String, Integer> getRules(Document doc) {
    Map<String, Integer> rulesMap = new HashMap<String, Integer>();
    // add all the rules
    Element rules = doc.getRootElement().getChild("g");
    for (Element rule : rules.getChildren()) {
        rulesMap.put(rule.getName(), new Integer(rule.getChild("score").getValue()));
    }/* www .j  av a2 s .com*/
    return rulesMap;
}

From source file:io.sitespeed.jenkins.xml.impl.XMLToPageJDOM.java

License:Open Source License

private Map<String, String> getAssetsSize(Document doc) {
    Map<String, String> assetsAndSize = new HashMap<String, String>();

    Element assets = doc.getRootElement().getChild("stats");
    for (Element asset : assets.getChildren()) {

        // The sizes in YSlow xml is sometimes wrong, need to calculate?!?!
        assetsAndSize.put(asset.getName(), asset.getChild("w").getValue());
    }//from w w  w .  jav a  2 s .  c  o m
    return assetsAndSize;
}

From source file:io.sitespeed.jenkins.xml.impl.XMLToPageJDOM.java

License:Open Source License

private Map<String, Integer> getNumberOfAssets(Document doc) {
    Map<String, Integer> assetsAndNumber = new HashMap<String, Integer>();

    Element assets = doc.getRootElement().getChild("stats");
    for (Element asset : assets.getChildren()) {
        assetsAndNumber.put(asset.getName(), new Integer(asset.getChild("r").getValue()));
    }/* w ww. j a  v  a  2s. c  om*/
    return assetsAndNumber;
}

From source file:io.sitespeed.jenkins.xml.impl.XMLToPageTimingsJDOM.java

License:Open Source License

public PageTimings get(File browserTimeXML) throws IOException {

    final SAXBuilder b = new SAXBuilder(new XMLReaderSAX2Factory(false));
    Document doc;
    try {/*from   w w w.ja v a  2  s .c om*/
        doc = b.build(browserTimeXML);
    } catch (JDOMException e) {
        throw new IOException(e);
    }

    return new PageTimings(getPageData("actualUrl", doc), getPageData("browserName", doc),
            getPageData("browserVersion", doc), doc.getRootElement().getChild("runs").getChildren("run").size(),
            getMeasurements(doc));
}