Example usage for org.jdom2 Element getChildText

List of usage examples for org.jdom2 Element getChildText

Introduction

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

Prototype

public String getChildText(final String cname) 

Source Link

Document

Returns the textual content of the named child element, or null if there's no such child.

Usage

From source file:de.knewcleus.openradar.gui.flightplan.lenny64.Lenny64XmlParser.java

License:Open Source License

public static List<FlightPlanData> parse(AirportData data, GuiRadarContact contact, Document document) {
    List<FlightPlanData> result = new ArrayList<FlightPlanData>();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String today = sdf.format(new Date());

    SimpleDateFormat xmlTimeFormat = new SimpleDateFormat("HH:mm:ss");
    SimpleDateFormat shortTimeFormat = new SimpleDateFormat("HH:mm");

    List<Element> eFlightPlans = document.getRootElement().getChildren("flightplan");
    if (eFlightPlans != null) {
        for (Element eFp : eFlightPlans) {
            String flightplanId = eFp.getChildText("flightplanId");
            String callsign = eFp.getChildText("callsign");
            String flightNumber = eFp.getChildText("flightNumber");
            String airportFrom = eFp.getChildText("airportFrom");
            String airportTo = eFp.getChildText("airportTo");
            String alternateDestination = eFp.getChildText("alternateDestination");
            String cruiseAltitude = eFp.getChildText("cruiseAltitude");
            String trueAirspeed = eFp.getChildText("trueAirspeed");
            String dateDeparture = eFp.getChildText("dateDeparture");
            String dateArrival = eFp.getChildText("dateArrival");
            String departureTime = eFp.getChildText("departureTime");
            String arrivalTime = eFp.getChildText("arrivalTime");
            String aircraft = eFp.getChildText("aircraft");
            String soulsOnBoard = eFp.getChildText("soulsOnBoard");
            String fuelTime = eFp.getChildText("fuelTime");
            String pilotName = eFp.getChildText("pilotName");
            String waypoints = eFp.getChildText("waypoints");
            String category = eFp.getChildText("category");
            //                String comments = eFp.getChildText("comments");
            //                StringBuilder messages = new StringBuilder();
            //                List<Element> eComments = document.getRootElement().getChild("comments").getChildren("comment");
            //                for (Element eComment : eComments) {
            //                    String user = eComment.getChildText("user");
            //                    String message = eComment.getChildText("message");
            //                    messages.append(user).append(": ").append(message).append("; ");
            //                }
            String status = eFp.getChildText("status");
            status = status.equals("") ? FlightPlanData.FlightPlanStatus.ACTIVE.toString()
                    : status.replaceAll("filled", "FILED");
            //                String additionalInformation = eFp.getChildText("additionalInformation");
            //                String lastUpdated = eFp.getChildText("lastUpdated");

            if ((status.equalsIgnoreCase(FlightPlanData.FlightPlanStatus.ACTIVE.toString())
                    || status.equalsIgnoreCase(FlightPlanData.FlightPlanStatus.FILED.toString()))
                    /*(airportFrom.equals(data.getAirportCode()) || airportTo.equals(data.getAirportCode()) ) */
                    && (dateDeparture.equals(today) || dateArrival.equals(today))) {
                // check for departure date
                try {
                    FlightPlanData fpd = contact.getFlightPlan().copy(); // creates a copy of the existing record
                    // now merge the data we have got and which we do not already know
                    fpd.setFlightPlanId(flightplanId);
                    fpd.setAircraft(aircraft);
                    fpd.setAlternativeDestinationAirports(alternateDestination);
                    // callsign is already known
                    cruiseAltitude = cruiseAltitude.equals("FL") ? "" : cruiseAltitude;
                    fpd.setCruisingAltitude(cruiseAltitude);
                    departureTime = shortTimeFormat.format(xmlTimeFormat.parse(departureTime));
                    fpd.setDeparture(departureTime); // todo
                    fpd.setDepartureAirport(airportFrom);
                    fpd.setDestinationAirport(airportTo);
                    arrivalTime = shortTimeFormat.format(xmlTimeFormat.parse(arrivalTime));
                    //fpd.setEstimatedFlightTime(estimatedFlightTime); // todo
                    fpd.setEstimatedFuelTime(fuelTime);
                    fpd.setFlightCode(flightNumber);
                    fpd.setFpStatus(status);
                    fpd.setPilotName(pilotName);
                    // fpd.setRemarks(messages.toString());
                    fpd.setRoute(waypoints);
                    if (null != soulsOnBoard && !"".equals(soulsOnBoard)) {
                        fpd.setSoulsOnBoard(Integer.parseInt(soulsOnBoard));
                    }//from  w  w w. ja  v a 2 s  . co m
                    trueAirspeed = trueAirspeed.equals("TAS") ? "" : trueAirspeed;
                    fpd.setTrueAirspeed(trueAirspeed);
                    fpd.setType(category);
                    result.add(fpd);
                } catch (Exception e) {
                    log.error("Error while parsing flightplan #" + flightNumber + " for " + callsign, e);
                }
            } else {
                log.trace("Skipping flightplan, it is for another airport: #" + flightNumber + " from:"
                        + airportFrom + " to:" + airportTo);
            }
        }
    }

    return result;
}

From source file:de.rallye.api.LandingPage.java

License:Open Source License

private void replaceKgRooms(Document doc, String groupsCode) {
    List<Element> days = doc.getRootElement().getChild("days").getChildren("day");
    for (Element day : days) {
        String dateStr = formatDate(day.getChildText("heading"));

        List<Element> events = day.getChild("events").getChildren("event");
        for (Element event : events) {
            if (event.getChildText("type").equals("kleingruppe")) {

                String locCode = event.getChildText("location");
                RoomCode code = roomCodeMap.get(locCode);
                if (code == null)
                    continue;

                String room = "Kleingruppe";
                if (groupsCode != null) {
                    char ch = groupsCode.charAt(code.digit);
                    int groupIdx = Character.getNumericValue(ch);

                    room = code.rooms.get(groupIdx);
                }// w  w w  . ja  v  a  2 s.co  m

                event.getChild("location").removeContent();
                event.getChild("location").addContent(room);
            }
        }
    }
}

From source file:de.rallye.api.LandingPage.java

License:Open Source License

@GET
@Produces("text/calendar")
@Path("timetable/{groupsCode}.ics")
@Template(name = "/calendar")
public List<Event> getCalendar(@PathParam("groupsCode") String groupsCode) throws JDOMException, IOException {
    try {//w ww.j  a  v a 2  s. co  m
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));

        Document doc = new SAXBuilder()
                .build(StadtRallye.class.getResourceAsStream("timetable/stundenplan.xml"));
        replaceKgRooms(doc, groupsCode);

        List<Event> result = new ArrayList<>();

        List<Element> days = doc.getRootElement().getChild("days").getChildren("day");
        for (Element day : days) {
            String dateStr = formatDate(day.getChildText("heading"));

            List<Element> events = day.getChild("events").getChildren("event");
            for (int i = 0; i < events.size(); i++) {
                Element event = events.get(i);

                if (event.getChildText("type").equals("spacer"))
                    continue;

                Time startT = Time.fromString(event.getChildText("starttime"));
                String start = startT.toString();

                Time endT = new Time(20, 200);
                if (i < events.size() - 1) {
                    Element next = events.get(i + 1);
                    String endStr = next.getChildText("starttime");
                    endT = Time.fromString(endStr);

                    endT = endT.subtractMinutes(10);
                } else {
                    float dur = Float.parseFloat(event.getChildText("duration")) * 55;
                    endT = startT.addMinutes((int) dur);
                }

                String title = event.getChildText("title");
                String titleR = title.replace("&amp;", "&");

                Event e = new Event(year + dateStr + "T" + start + "00",
                        year + dateStr + "T" + endT.toString() + "00", titleR, event.getChildText("location"));
                result.add(e);
            }
        }

        return result;
    } catch (RuntimeException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.tor.tribes.util.report.ReportRule.java

License:Apache License

public ReportRule(Element pElm) throws IllegalArgumentException {
    try {//  w w  w .j  av a  2  s  .  c  o  m
        type = RuleType.valueOf(pElm.getChildText("type"));
        targetSet = pElm.getChildText("targetSet");
        Element settings = pElm.getChild("settings");

        //check arguments and throw Exception if illigal
        switch (type) {
        case AGE:
            Long maxAge = Long.parseLong(settings.getText());
            filterComponent = maxAge;
            break;
        case ATTACKER_ALLY:
            List<Ally> attAllyList = new ArrayList<>();
            for (Element e : settings.getChildren("ally")) {
                int id = Integer.parseInt(e.getText());
                attAllyList.add(DataHolder.getSingleton().getAllies().get(id));
            }
            filterComponent = attAllyList;
            break;
        case ATTACKER_TRIBE:
            List<Tribe> attTribeList = new ArrayList<>();
            for (Element e : settings.getChildren("tribe")) {
                int id = Integer.parseInt(e.getText());
                attTribeList.add(DataHolder.getSingleton().getTribes().get(id));
            }
            filterComponent = attTribeList;
            break;
        case COLOR:
            Integer color = Integer.parseInt(settings.getText());
            filterComponent = color;
            break;
        case DATE:
            String dates[] = settings.getText().split("-");
            Long start = Long.parseLong(dates[0]);
            Long end = Long.parseLong(dates[1]);
            Range<Long> dateSpan = Range.between(start, end);
            filterComponent = dateSpan;
            break;
        case DEFENDER_ALLY:
            List<Ally> defAllyList = new ArrayList<>();
            for (Element e : settings.getChildren("ally")) {
                int id = Integer.parseInt(e.getText());
                defAllyList.add(DataHolder.getSingleton().getAllies().get(id));
            }
            filterComponent = defAllyList;
            break;
        case DEFENDER_TRIBE:
            List<Tribe> defTribeList = new ArrayList<>();
            for (Element e : settings.getChildren("tribe")) {
                int id = Integer.parseInt(e.getText());
                defTribeList.add(DataHolder.getSingleton().getTribes().get(id));
            }
            filterComponent = defTribeList;
            break;
        case CATA:
        case CONQUERED:
        case FAKE:
        case FARM:
        case OFF:
        case WALL:
            filterComponent = null;
            break;
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:de.tsystems.mms.apm.performancesignature.viewer.rest.DashboardXMLReader.java

License:Apache License

void parseXML(final String xml) throws IOException, JDOMException {
    Document jdomDoc = useSAXParser(xml);
    Element root = jdomDoc.getRootElement();
    List<Element> xmlDashboardReports = root.getChildren("dashboardReport");
    for (Element xmlDashboardReport : xmlDashboardReports) {
        DashboardReport dashboardReport = new DashboardReport(xmlDashboardReport.getChildText("name"));
        List<Element> chartDashletElements = xmlDashboardReport.getChildren("chartDashlet");
        for (Element chartDashletElement : chartDashletElements) {
            ChartDashlet chartDashlet = new ChartDashlet(chartDashletElement);

            List<Element> measureElements = chartDashletElement.getChildren("measure");
            for (Element measureElement : measureElements) {
                Measure measure = new Measure(measureElement);

                List<Element> measurementElements = measureElement.getChildren("measurement");
                for (Element mearsurementElement : measurementElements) {
                    Measurement measurement = new Measurement(mearsurementElement);
                    measure.addMeasurement(measurement);
                }//from ww w  .j ava  2 s .  c  o m
                chartDashlet.addMeasure(measure);
            }
            dashboardReport.addChartDashlet(chartDashlet);
        }

        List<Element> incidentElements = xmlDashboardReport.getChildren("incident");
        for (Element incidentElement : incidentElements) {
            IncidentChart incidentChart = new IncidentChart(incidentElement);

            List<Element> violationElements = incidentElement.getChildren("violation");
            for (Element violationElement : violationElements) {
                IncidentViolation incidentViolation = new IncidentViolation(violationElement);
                incidentChart.add(incidentViolation);
            }
            dashboardReport.addIncident(incidentChart);
        }

        dashboardReports.add(dashboardReport);
    }
}

From source file:diuf.diva.dia.ms.script.command.TrainSCAE.java

License:Open Source License

@Override
public String execute(Element element) throws Exception {

    // Get the SCAE
    String ref = readAttribute(element, "ref");
    SCAE scae = script.scae.get(ref);/*from   w w  w .ja  va  2s  . co  m*/
    if (scae == null) {
        error("cannot find " + ref + ", check the id");
    }

    assert (scae != null);

    // Parse the dataset
    String dataset = readElement(element, "dataset");
    Dataset ds = script.datasets.get(dataset);
    NoisyDataset nds = script.noisyDataSets.get(dataset);

    if (ds == null && nds == null && element.getChild("filenamebased") == null) {
        error("cannot find dataset " + dataset);
    }

    // Parse the (optional, used only in supervised) ground truth dataset
    Dataset gt = null;
    if (element.getChild("groundTruth") != null) {
        gt = script.datasets.get(readElement(element, "groundTruth"));
    }

    // Parse parameter for training
    this.SAMPLES = Integer.parseInt(readElement(element, "samples"));
    this.MAXTIME = Integer.parseInt(readElement(element, "max-time"));

    if (SAMPLES == 0 && MAXTIME == 0) {
        error("cannot set both epochs and max-time to 0");
    }
    if (SAMPLES == 0) {
        MAXTIME = Integer.MAX_VALUE;
    }

    if (MAXTIME == 0) {
        MAXTIME = Integer.MAX_VALUE;
    }

    // If display-progress is present, init the tracer
    tracer = null;
    if (element.getChild("save-progress") != null) {
        try {

            /* Expected points on the plots are the number of expected epochs.
             * So number of total samples divided by size of epoch
             */
            int expectedSamples;
            if (ds != null) {
                expectedSamples = SAMPLES / ds.size();
            } else {
                expectedSamples = SAMPLES / nds.clean.size();
            }
            tracer = new Tracer("SCAE training error", "Epoch", "Error", expectedSamples,
                    element.getChild("display-progress") != null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // If display-feature tag is present init it
    FeatureDisplay featureDisplay = null;
    if (element.getChild("display-features") != null) {
        featureDisplay = new FeatureDisplay(scae);
        try {
            tracerFeaturesUpdateStep = Integer.parseInt(element.getChildText("display-features"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // If recoding tag is present init it
    RecodingDisplay recodingDisplay = null;
    if (element.getChild("display-recoding") != null) {
        Image img = new Image(element.getChild("display-recoding").getTextTrim());
        img.convertTo(script.colorspace);
        DataBlock imgDB = new DataBlock(img);
        recodingDisplay = new RecodingDisplay(imgDB, scae);
    }

    // Return value of the function
    String returnValue = null;

    // Query the normal datasets
    if (ds != null) {
        // Verify dataset size before training
        for (DataBlock db : ds) {
            if (db.getWidth() < scae.getInputPatchWidth() || db.getHeight() < scae.getInputPatchHeight()) {
                error("an image of the dataset is smaller than the input of the autoencoder:\n" + "["
                        + db.getWidth() + "x" + db.getHeight() + "]<[" + scae.getInputPatchWidth() + "x"
                        + scae.getInputPatchHeight() + "]");
            }
        }

        if (gt != null) {
            returnValue = String
                    .valueOf(trainSupervisedAutoEncoder(scae, ds, gt, featureDisplay, recodingDisplay));
        } else {
            returnValue = String.valueOf(trainAutoencoder(scae, ds, featureDisplay, recodingDisplay));
        }
    }

    // Query the noisy dataset
    if (nds != null) {
        // Verify dataset size before training (on clean only is sufficient!)
        for (DataBlock db : nds.clean) {
            if (db.getWidth() < scae.getInputPatchWidth() || db.getHeight() < scae.getInputPatchHeight()) {
                error("an image of the dataset is smaller than the input of the autoencoder:\n" + "["
                        + db.getWidth() + "x" + db.getHeight() + "] < [" + scae.getInputPatchWidth() + "x"
                        + scae.getInputPatchHeight() + "]");
            }
        }
        returnValue = String.valueOf(trainDenoisingAutoEncoder(scae, nds, featureDisplay, recodingDisplay));
    }

    /** If the tag </filenamebased> is present
     *  call the relative method. Otherwise go on
     *  with typical training.
     */
    if (element.getChild("filenamebased") != null) {
        returnValue = String.valueOf(
                trainSupervisedFileNameBasedAutoEncoder(scae, element, featureDisplay, recodingDisplay));
    }

    // If a result has been computed
    if (returnValue != null) {
        // If tracer has been used
        if (tracer != null) {
            tracer.addRawData();
            tracer.addCumulatedAverage();
            tracer.addMovingAverage();
            tracer.addMovingMedian();
            // Show the plot
            tracer.display();

            // If requires, save the plot on disk at the provided path
            if (element.getChild("save-progress") != null) {
                try {
                    tracer.savePlot(readElement(element, "save-progress"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return returnValue;
    }

    return "";
}

From source file:docubricks.data.Brick.java

public static Brick fromXML(File basepath, DocubricksProject proj, Element root) {
    Brick u = new Brick();
    u.id = root.getAttributeValue("id");

    u.name = root.getChildText("name");
    u.vabstract = root.getChildText("abstract");
    u.longdesc = root.getChildText("long_description");
    u.notes = root.getChildText("notes");
    u.license = root.getChildText("license");

    for (Element child : root.getChildren())
        if (child.getName().equals("author")) {
            String id = child.getAttributeValue("id");
            u.authors.add(proj.getAuthor(id));
        }//from  w  ww.  ja v  a 2 s .c o m
    for (Element child : root.getChildren())
        if (child.getName().equals("logical_part") || child.getName().equals("function"))
            u.functions.add(Function.fromXML(basepath, proj, child));
    for (Element child : root.getChildren())
        if (child.getName().equals("instruction")) {
            StepByStepInstruction i = StepByStepInstruction.fromXML(u, basepath, child);
            i.name = child.getAttributeValue("name");
            u.instructions.add(i);
        }

    u.asmInstruction = StepByStepInstruction.fromXML(u, basepath, root.getChild("assembly_instruction"));

    u.media = MediaSet.fromXML(basepath, root.getChild("media"));

    return u;
}

From source file:Domain.Model.Student.java

public boolean studentExists(String studentId) {

    boolean result = false;
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("./src/Students.xml");

    try {/*w ww.j a  v a2 s  . c om*/

        Document document = (Document) builder.build(xmlFile);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren("student");

        for (int i = 0; i < list.size(); i++) {

            Element node = (Element) list.get(i);

            String id = node.getChildText("studentId");

            if (id.equals(studentId)) {
                result = true;
                break;
            }

        }

    } catch (IOException io) {
        System.out.println(io.getMessage());
    } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
    }

    System.out.println(result);
    return result;
}

From source file:edd.practica1_201504480.leerxml.java

Lista_Simple datos(File tipo1) {

    SAXBuilder builder = new SAXBuilder();
    try {//from   w ww. ja v a2 s  .c  o  m

        //Se obtiene la lista de hijos de la raiz 'tables'
        Document document = builder.build(tipo1);
        Element rootNode = document.getRootElement();
        //  JOptionPane.showMessageDialog(null," e1: "+(rootNode.getChildText("dimension"))); 
        tam = Integer.parseInt(rootNode.getChildText("dimension"));
        Element dobles = rootNode.getChild("dobles");

        List list = dobles.getChildren("casilla");
        for (int i = 0; i < list.size(); i++) {
            Element tabla = (Element) list.get(i);
            d1.enlistar(tabla.getChildTextTrim("x"));

            d1.enlistar(tabla.getChildTextTrim("y"));
            //              JOptionPane.showMessageDialog(null,""+tabla.getChildTextTrim("x").toString());
            //                JOptionPane.showMessageDialog(null,""+tabla.getChildTextTrim("y").toString());
        }

        Element triples = rootNode.getChild("triples");

        List listt = triples.getChildren("casilla");
        for (int i = 0; i < listt.size(); i++) {
            Element tabla = (Element) listt.get(i);
            d2.enlistar(tabla.getChildTextTrim("x"));
            d2.enlistar(tabla.getChildTextTrim("y"));
            //              JOptionPane.showMessageDialog(null,""+tabla.getChildTextTrim("x").toString());
            //                JOptionPane.showMessageDialog(null,""+tabla.getChildTextTrim("y").toString());
        }
        Element dicc = rootNode.getChild("diccionario");
        List dic = dicc.getChildren();

        for (int i = 0; i < dic.size(); i++) {
            Element tabla = (Element) dic.get(i);
            //JOptionPane.showMessageDialog(null,""+tabla.getText().toString());
            d.enlistar(tabla.getText().toString());

        }

    } catch (JDOMException | IOException | NumberFormatException | HeadlessException e) {
        JOptionPane.showMessageDialog(null, " error de archivo");
    }
    return d;

}

From source file:edu.byu.ece.rapidSmith.design.subsite.CellLibrary.java

License:Open Source License

private void loadCellFromXml(Element cellEl, Map<SiteType, Map<String, SiteProperty>> sitePropertiesMap) {
    String type = cellEl.getChildText("type");
    SimpleLibraryCell libCell = new SimpleLibraryCell(type);
    libCell.setVccSource(cellEl.getChild("vcc_source") != null);
    libCell.setGndSource(cellEl.getChild("gnd_source") != null);
    libCell.setIsPort(cellEl.getChild("is_port") != null);
    Element lutType = cellEl.getChild("is_lut");
    if (lutType != null) {
        String strInputs = lutType.getChildText("num_inputs");
        libCell.setNumLutInputs(Integer.parseInt(strInputs));
    }/*from  ww w . j a  v a2  s.  co m*/

    if (libCell.isVccSource())
        vccSource = libCell;
    if (libCell.isGndSource())
        gndSource = libCell;

    loadConfigurationPropertiesFromXml(cellEl, libCell);
    loadPinsFromXml(cellEl, libCell);
    loadPossibleBelsFromXml(libCell, cellEl, sitePropertiesMap);
    add(libCell);
}