Example usage for org.jdom2 Element getChildren

List of usage examples for org.jdom2 Element getChildren

Introduction

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

Prototype

public List<Element> getChildren(final String cname) 

Source Link

Document

This returns a List of all the child elements nested directly (one level deep) within this element with the given local name and belonging to no namespace, returned as Element objects.

Usage

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);
                }// www  .  ja  v a 2s.c  om
                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:de.unigoettingen.sub.search.opac.ConfigOpacCatalogue.java

License:Open Source License

/**
 * Beautifier fr ein JDom-Object durchfhren ================================================================
 *//*from   ww  w .j  a v a  2s.  c o  m*/

private void executeBeautifierForElement(Element el) {
    String matchedValue = "";
    for (ConfigOpacCatalogueBeautifier beautifier : this.beautifySetList) {
        Element subfieldToChange = null;
        Element mainFieldToChange = null;
        /* eine Kopie der zu prfenden Elemente anlegen (damit man darin lschen kann */

        ArrayList<ConfigOpacCatalogueBeautifierElement> prooflist = new ArrayList<ConfigOpacCatalogueBeautifierElement>(
                beautifier.getTagElementsToProof());
        /* von jedem Record jedes Field durchlaufen */
        List<Element> elements = el.getChildren("field");
        boolean foundValue = false;
        for (Element field : elements) {
            String tag = field.getAttributeValue("tag");

            if (beautifier.getTagElementToChange().getTag().equals(tag)) {
                mainFieldToChange = field;
            }

            /* von jedem Field alle Subfelder durchlaufen */
            List<Element> subelements = field.getChildren("subfield");
            for (Element subfield : subelements) {
                String subtag = subfield.getAttributeValue("code");
                String value = subfield.getText();

                if (beautifier.getTagElementToChange().getTag().equals(tag)
                        && beautifier.getTagElementToChange().getSubtag().equals(subtag)) {
                    subfieldToChange = subfield;
                }
                /*
                 * wenn die Werte des Subfeldes in der Liste der zu prfenden Beutifier-Felder stehen, dieses aus der Liste der Beautifier
                 * entfernen
                 */
                if (!prooflist.isEmpty()) {
                    for (ConfigOpacCatalogueBeautifierElement cocbe : beautifier.getTagElementsToProof()) {
                        if (cocbe.getValue().equals("*")) {
                            if (cocbe.getTag().equals(tag) && cocbe.getSubtag().equals(subtag)) {
                                if (!foundValue) {
                                    matchedValue = value;
                                    foundValue = true;
                                }
                                prooflist.remove(cocbe);
                            }
                        } else if (cocbe.getTag().equals(tag) && cocbe.getSubtag().equals(subtag)
                                && value.matches(cocbe.getValue())) {
                            if (!foundValue) {
                                matchedValue = value;
                            }
                            prooflist.remove(cocbe);
                        }
                    }
                }
            }
        }
        /*
         * --------------------- wenn in der Kopie der zu prfenden Elemente keine Elemente mehr enthalten sind, kann der zu ndernde Wert
         * wirklich gendert werden -------------------
         */

        // check main field
        if (prooflist.size() == 0 && mainFieldToChange == null) {
            mainFieldToChange = new Element("field");
            mainFieldToChange.setAttribute("tag", beautifier.getTagElementToChange().getTag());
            elements.add(mainFieldToChange);
        }

        // check subfield
        if (prooflist.size() == 0 && subfieldToChange == null) {
            //                Element field = new Element("field");
            //                field.setAttribute("tag", beautifier.getTagElementToChange().getTag());
            subfieldToChange = new Element("subfield");
            subfieldToChange.setAttribute("code", beautifier.getTagElementToChange().getSubtag());
            mainFieldToChange.addContent(subfieldToChange);
            //                elements.add(field);
        }

        if (prooflist.size() == 0) {
            if (beautifier.getTagElementToChange().getValue().equals("*")) {
                subfieldToChange.setText(matchedValue);
            } else {
                subfieldToChange.setText(beautifier.getTagElementToChange().getValue());
            }
        }

    }

}

From source file:delfos.configuration.scopes.ConfiguredDatasetsScope.java

License:Open Source License

private synchronized Collection<ConfiguredDataset> loadConfiguredDatasets() {
    File fileOfConfiguredDatasets = ConfigurationManager.getConfigurationFile(this);

    Collection<ConfiguredDataset> configuredDatasets = new ArrayList<>();

    if (!fileOfConfiguredDatasets.exists()) {
        Global.showWarning("The configured datasets file for this machine does not exists-");
        Global.showWarning("\tFile '" + fileOfConfiguredDatasets.getAbsolutePath() + "': not found.");
        Global.showWarning("The configured datasets file for this machine does not exists.");
        saveConfigurationScope();// ww w  .j  av  a2 s . c o m
    } else {
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage("Loading configured datasets from file '"
                    + fileOfConfiguredDatasets.getAbsolutePath() + "'\n");
        }
        try {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(fileOfConfiguredDatasets);

            Element rootElement = doc.getRootElement();
            if (!rootElement.getName().equals(CONFIGURED_DATASETS_ROOT_ELEMENT_NAME)) {
                IllegalArgumentException ex = new IllegalArgumentException(
                        "The XML does not contains the configured datasets.");
                ERROR_CODES.CANNOT_READ_CONFIGURED_DATASETS_FILE.exit(ex);
            }

            for (Element configuredDataset : rootElement.getChildren(CONFIGURED_DATASET_ELEMENT_NAME)) {
                String name = configuredDataset.getAttributeValue(CONFIGURED_DATASET_ELEMENT_NAME_ATTRIBUTE);
                String description = configuredDataset
                        .getAttributeValue(CONFIGURED_DATASET_ELEMENT_DESCRIPTION_ATTRIBUTE);
                Element datasetLoaderElement = configuredDataset.getChild(DatasetLoaderXML.ELEMENT_NAME);

                if (datasetLoaderElement == null) {
                    IllegalStateException ex = new IllegalStateException(
                            "Cannot retrieve configured dataset loader '" + name + "'");
                    ERROR_CODES.CANNOT_READ_CONFIGURED_DATASETS_FILE.exit(ex);
                }

                DatasetLoader<? extends Rating> datasetLoader = DatasetLoaderXML
                        .getDatasetLoader(datasetLoaderElement);

                if (Global.isVerboseAnnoying()) {
                    Global.showInfoMessage("\tConfigured dataset '" + name + "' loaded.\n");
                }

                configuredDatasets.add(new ConfiguredDataset(name, description, datasetLoader));

            }
            if (configuredDatasets.isEmpty()) {
                Global.showWarning("No configured datasets found, check configuration file.");
            }
        } catch (JDOMException | IOException ex) {
            ERROR_CODES.CANNOT_READ_CONFIGURED_DATASETS_FILE.exit(ex);
        }
    }

    return configuredDatasets;
}

From source file:delfos.group.grs.consensus.ConsensusOfIndividualRecommendationsToXML.java

License:Open Source License

public static ConsensusOutputModel readConsensusOutputXML(File consensusIntputXML)
        throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(consensusIntputXML);

    Element root = doc.getRootElement();
    if (!root.getName().equals(CONSENSUS_OUTPUT_ROOT_NAME)) {
        throw new IllegalArgumentException(
                "The XML does not contains a Case Study (" + consensusIntputXML.getAbsolutePath() + ")");
    }/*  w  w w.j  a  v a  2 s.c  om*/

    Element consensus = root.getChild(CONSENSUS_OUTPUT_CONSENSUS_ELEMENT_NAME);

    int round = Integer.parseInt(consensus.getAttributeValue(CONSENSUS_OUTPUT_CONSENSUS_ATTRIBUTE_ROUND));
    double consensusDegree = Double
            .parseDouble(consensus.getAttributeValue(CONSENSUS_OUTPUT_CONSENSUS_ATTRIBUTE_CONSENSUS_DEGREE));

    Collection<Recommendation> consensusRecommendations = new ArrayList<>();

    for (Element alternative : consensus.getChildren(CONSENSUS_OUTPUT_ALTERNATVE_ELEMENT_NAME)) {
        int idItem = Integer
                .parseInt(alternative.getAttributeValue(CONSENSUS_OUTPUT_ALTERNATVE_ATTRIBUTE_ID_ITEM));
        double rank = Double
                .parseDouble(alternative.getAttributeValue(CONSENSUS_OUTPUT_ALTERNATVE_ATTRIBUTE_RANK));

        double preference = 1 / rank;
        consensusRecommendations.add(new Recommendation(idItem, preference));
    }

    return new ConsensusOutputModel(consensusDegree, round, consensusRecommendations);
}

From source file:delfos.group.io.xml.prefiltersforgroup.PreFilteringTechniqueXML.java

License:Open Source License

/**
 * Construye el objeto en memoria que representa a la tcnica de filtrado de
 * ratings para grupos descrita en el elemento que se pasa por parmetro.
 *
 * @param groupRatingsPreFilterElement Objeto XML que describe el filtro.
 * @return Tcnica de filtrado de ratings para grupo generada a partir de la
 * descripcin indicada en el parmetro.//w w  w.  j ava 2  s.  co  m
 */
public static GroupRatingsFilter getGroupRatingsFilter(Element groupRatingsPreFilterElement) {
    String filterName = groupRatingsPreFilterElement.getAttributeValue("name");
    GroupRatingsFilter filter = GroupRatingsFilterFactory.getInstance().getClassByName(filterName);
    for (Object o : groupRatingsPreFilterElement.getChildren(ParameterXML.PARAMETER_ELEMENT_NAME)) {
        Element parameterElement = (Element) o;
        ParameterXML.getParameterValue(filter, parameterElement);
    }
    return filter;
}

From source file:delfos.io.xml.evaluationmeasures.confusionmatricescurve.ConfusionMatricesCurveXML.java

License:Open Source License

/**
 * Convierte un {@link Element} que contenga la informacin de un
 * ConfusionMatricesCurve en un objeto {@link ConfusionMatricesCurve}.
 *
 *
 * @param element Objeto {@link Element} que contiene la informacin
 * necesaria para construir el objeto {@link ConfusionMatricesCurve}
 *
 * @return {@link ConfusionMatricesCurve} con la informacin que el
 * parmetro element contiene/*from w  w w . j a va  2s  .  c  o m*/
 *
 * @throws UnrecognizedElementException cuando el {@link Element} que se
 * desea convertir no tiene la informacin que se necesita para construir un
 * {@link ConfusionMatricesCurve} o no est estructurada como se esperaba.
 */
public static ConfusionMatricesCurve getConfusionMatricesCurve(Element element)
        throws UnrecognizedElementException {
    List<ConfusionMatrix> matrices = new ArrayList<ConfusionMatrix>();

    /*
     * Recorro todos los elementos que representan un punto dentro de esta
     * curva
     */
    List<Element> pares = element.getChildren(MATRIX);
    if (pares.isEmpty()) {
        if ((element.getChild(CURVE_ELEMENT) != null
                && !element.getChild(CURVE_ELEMENT).getChildren(MATRIX).isEmpty())
                || !element.getChildren().isEmpty()) {
            // (Si el elemento tiene como hijo una curva y este tiene varias matrices )                                 o   el elemento tiene algn hijo.
            //Global.showWarning("BAD USAGE, the curve belongs to a group of users. Perform 'element.getChild(CURVE_ELEMENT)' to call this method");
            pares = element.getChild(CURVE_ELEMENT).getChildren(MATRIX);
        }
    }

    for (Object par : pares) {
        Element parElement = (Element) par;

        int k = Integer.parseInt(parElement.getAttributeValue(K));
        int falsePositive = Integer.parseInt(parElement.getAttributeValue(FALSE_POSITIVE));
        int falseNegative = Integer.parseInt(parElement.getAttributeValue(FALSE_NEGATIVE));
        int truePositive = Integer.parseInt(parElement.getAttributeValue(TRUE_POSITIVE));
        int trueNegative = Integer.parseInt(parElement.getAttributeValue(TRUE_NEGATIVE));
        matrices.add(new ConfusionMatrix(falsePositive, falseNegative, truePositive, trueNegative));
    }

    if (matrices.isEmpty()) {
        return ConfusionMatricesCurve.emptyCurve();
    } else {
        return new ConfusionMatricesCurve(matrices.toArray(new ConfusionMatrix[0]));
    }
}

From source file:delfos.io.xml.parameterowner.parameter.ParameterOwnerParameterXML.java

License:Open Source License

public static ParameterOwner getParameterOwnerParameterValue(ParameterOwner parameterOwner,
        Element parameterElement) {

    if (parameterElement == null) {
        throw new IllegalArgumentException("The element cannot be null.");
    }//from  w w w .java  2 s.  c  o  m

    if (!parameterElement.getName().equals(ParameterXML.PARAMETER_ELEMENT_NAME)) {
        throw new IllegalArgumentException("The element does not describe a parameter.");
    }

    if (!parameterElement.getAttributeValue(ParameterXML.PARAMETER_TYPE)
            .equals(ParameterOwnerRestriction.class.getSimpleName())) {
        throw new IllegalArgumentException(
                "The element does not describe a parameter of type " + ParameterOwnerRestriction.class);
    }

    String parameterName = parameterElement.getAttributeValue(ParameterXML.PARAMETER_NAME);
    Parameter parameterByName = parameterOwner.getParameterByName(parameterName);
    if (parameterByName == null) {
        IllegalStateException ex = new IllegalStateException(
                parameterOwner.getName() + " doesn't have the parameter '" + parameterName + "'\n");
        ERROR_CODES.PARAMETER_OWNER_NOT_HAVE_PARAMETER.exit(ex);
        throw ex;
    }

    String parameterValueString = parameterElement.getAttributeValue(ParameterXML.PARAMETER_VALUE);

    ParameterOwner innerParameterOwner = null;
    try {
        innerParameterOwner = (ParameterOwner) parameterByName.parseString(parameterValueString);
    } catch (ClassCastException ex) {
        throw new IllegalStateException("El tipo del parametro no es el detectado!!");
    } catch (CannotParseParameterValue ex) {
        ERROR_CODES.PARAMETER_OWNER_ILLEGAL_PARAMETER_VALUE.exit(ex);
        throw new IllegalStateException(ex);
    }

    if (innerParameterOwner == null) {
        throw new IllegalStateException("Parameter owner '" + parameterValueString + "' not found.");
    }

    for (Element innerParameterElement : parameterElement.getChildren(ParameterXML.PARAMETER_ELEMENT_NAME)) {
        String innerParameterName = innerParameterElement.getAttributeValue(ParameterXML.PARAMETER_NAME);

        Parameter innerParameter = innerParameterOwner.getParameterByName(innerParameterName);
        Object innerParameterValue = ParameterXML.getParameterValue(innerParameterOwner, innerParameterElement);
        innerParameterOwner.setParameterValue(innerParameter, innerParameterValue);
    }
    return innerParameterOwner;
}

From source file:delfos.io.xml.parameterowner.ParameterOwnerXML.java

License:Open Source License

/**
 * Construye el objeto en memoria que representa al sistema de recomendacin descrito en el elemento que se pasa por
 * parmetro.//www .j  a  v  a2s .  com
 *
 * @param parameterOwnerElement Objeto XML con la informacin para recuperar el objeto.
 *
 * @return Sistema de recomendacin generado a partir de la descripcin pasada por parmetro
 */
public static ParameterOwner getParameterOwner(Element parameterOwnerElement) {

    String className = parameterOwnerElement.getAttributeValue(PARAMETER_OWNER_ATTRIBUTE_NAME);
    String typeName = parameterOwnerElement.getAttributeValue(PARAMETER_OWNER_ATTRIBUTE_TYPE);
    ParameterOwnerType parameterOwnerType = ParameterOwnerType.valueOf(typeName);

    ParameterOwner parameterOwner = parameterOwnerType.createObjectFromClassName(className);

    for (Element parameterElement : parameterOwnerElement.getChildren(ParameterXML.PARAMETER_ELEMENT_NAME)) {
        final String parameterName = parameterElement.getAttributeValue(ParameterXML.PARAMETER_NAME);

        Parameter parameter = parameterOwner.getParameterByName(parameterName);
        if (parameter != null) {
            Object parameterValue = ParameterXML.getParameterValue(parameterOwner, parameterElement);
            if (parameterValue == null) {
                parameterValue = ParameterXML.getParameterValue(parameterOwner, parameterElement);
            }

            parameterOwner.setParameterValue(parameter, parameterValue);
        }
    }
    return parameterOwner;

}

From source file:delfos.io.xml.recommendations.RecommendationsToXML.java

License:Open Source License

/**
 * Convierte el elemento XML indicado en un objeto que representa las recomendaciones al usuario.
 *
 * @param element Elemento XML a convertir.
 * @return Recomendaciones./*from   w  w  w  .  j  ava 2s .  co m*/
 *
 * @throws IllegalArgumentException Si el elemento no contiene la informacin necesaria para recuperar un objeto
 * {@link Recommendations}.
 *
 * @see RecommendationsToXML#getRecommendationsElement(delfos.RS.Recommendation.Recommendations)
 *
 */
public static Recommendations getRecommendations(Element element) {

    if (!element.getName().equals(RECOMMENDATIONS_ELEMENT_NAME)) {
        throw new IllegalArgumentException("Element name doesn't match this reader: found '" + element.getName()
                + "' expected '" + RECOMMENDATIONS_ELEMENT_NAME + "'");
    }

    String idTarget = element.getAttributeValue(ID_TARGET_ATTRIBUTE_NAME);

    Map<DetailField, Object> details = new TreeMap<>();
    for (Attribute attribute : element.getAttributes()) {

        if (ID_TARGET_ATTRIBUTE_NAME.equals(attribute.getName())) {
            continue;
        }

        DetailField detailField = DetailField.valueOfNoCase(attribute.getName());

        String detailFieldValueString = attribute.getValue();
        Object detailFieldValue = detailField.parseValue(detailFieldValueString);

        details.put(detailField, detailFieldValue);

    }

    RecommendationComputationDetails recommendationComputationDetails = new RecommendationComputationDetails(
            details);
    List<Recommendation> recommendations = new LinkedList<>();
    for (Object r : element.getChildren(RECOMMENDATION_ELEMENT_NAME)) {
        Element recommendationElement = (Element) r;

        if (!recommendationElement.getName().equals(RECOMMENDATION_ELEMENT_NAME)) {
            throw new IllegalArgumentException("Element name doesn't match this reader: found '"
                    + recommendationElement.getName() + "' expected '" + RECOMMENDATION_ELEMENT_NAME + "'");
        }
        int idItem = Integer.parseInt(recommendationElement.getAttributeValue(ID_ITEM_ATTRIBUTE_NAME));
        double preference = Double
                .parseDouble(recommendationElement.getAttributeValue(PREFERENCE_ATTRIBUTE_NAME));
        recommendations.add(new Recommendation(idItem, preference));
    }

    return RecommendationsFactory.createRecommendations(idTarget, recommendations,
            recommendationComputationDetails);
}

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 {/*from   w  w w .  java  2 s  .c o  m*/

        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;
}