Example usage for org.jdom2 Element getChild

List of usage examples for org.jdom2 Element getChild

Introduction

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

Prototype

public Element getChild(final String cname) 

Source Link

Document

This returns the first child element within this element with the given local name and belonging to no namespace.

Usage

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

License:Apache License

public ReportRule(Element pElm) throws IllegalArgumentException {
    try {/*from   w w  w.  ja v  a  2 s . c  om*/
        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:delfos.configfile.rs.single.DatasetConfigurationFileParser.java

License:Open Source License

/**
 * Mtodo para recuperar los objetos que se deben usar segn los parmetros que dicta el fichero de configuracin
 * indicado. Como se devuelven mltiples valores y java no permite la devolucin de mltiples valores en una
 * funcin, se ha creado un objeto para almacenarlos.
 *
 * @param configFile Ruta del fichero de configuracin.
 * @return Devuelve un objeto que contiene los parmetros necesarios para definir completamente un sistema de
 * recomendacin./*from   w  w  w  . j a  va2 s . c om*/
 * @throws JDOMException Si el archivo de configuracin no tiene la estructura de objetos JDOM esperada, es decir,
 * no se reconoce el formato del archivo.
 * @throws CannotLoadContentDataset Si no se puede cargar el dataset de contenido.
 * @throws CannotLoadRatingsDataset Si no se puede cargar el dataset de valoraciones.
 * @throws FileNotFoundException Si el archivo indicado no existe.
 */
public static DatasetConfiguration loadDatasetLoaderFromConfigFile(File configFile)
        throws JDOMException, CannotLoadContentDataset, CannotLoadRatingsDataset, FileNotFoundException {
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;
    try {
        doc = builder.build(configFile);
    } catch (IOException ex) {
        Global.showError(ex);
        ERROR_CODES.CANNOT_LOAD_CONFIG_FILE.exit(ex);
        throw new IllegalStateException(ex);
    }

    Element config = doc.getRootElement();
    Element datasetLoaderElement = config.getChild(DatasetLoaderXML.ELEMENT_NAME);
    DatasetLoader<? extends Rating> datasetLoader = DatasetLoaderXML.getDatasetLoader(datasetLoaderElement);

    return new DatasetConfiguration(datasetLoader);
}

From source file:delfos.configfile.rs.single.RecommenderSystemConfigurationFileParser.java

License:Open Source License

private static RecommenderSystemConfiguration loadConfigFileWithExceptions(String configFilePath)
        throws JDOMException, FileNotFoundException {

    Global.showMessageTimestamped("Loading config file " + configFilePath);
    SAXBuilder builder = new SAXBuilder();
    Document doc = null;//from w  w w .  ja  v a 2 s .  c o  m

    File configFile = new File(configFilePath);
    try {
        doc = builder.build(configFile);
    } catch (IOException ex) {
        Global.showError(ex);
        ERROR_CODES.CANNOT_LOAD_CONFIG_FILE.exit(ex);
        throw new IllegalStateException(ex);
    }

    Element config = doc.getRootElement();

    Element rs = config.getChild(RecommenderSystemXML.ELEMENT_NAME);
    GenericRecommenderSystem<Object> recommender = RecommenderSystemXML.getRecommenderSystem(rs);

    Element datasetLoaderElement = config.getChild(DatasetLoaderXML.ELEMENT_NAME);
    DatasetLoader<? extends Rating> datasetLoader = DatasetLoaderXML.getDatasetLoader(datasetLoaderElement);

    Element relevanceCriteriaElement = config.getChild(RelevanceCriteriaXML.ELEMENT_NAME);
    RelevanceCriteria relevanceCriteria = RelevanceCriteriaXML.getRelevanceCriteria(relevanceCriteriaElement);

    //Persistence Method
    Element persistenceMethodElement = config.getChild(PersistenceMethodXML.PERSISTENCE_METHOD_ELEMENT);
    PersistenceMethod persistenceMethod = PersistenceMethodXML.getPersistenceMethod(persistenceMethodElement);

    //Obtiene el mtodo para devolver las recomendaciones.
    RecommendationsOutputMethod recommdendationsOutputMethod;
    {
        Element recommdendationsOutputMethodElement = config
                .getChild(RecommdendationsOutputMethodXML.RECOMMENDATIONS_OUTPUT_METHOD_ELEMENT_NAME);
        if (recommdendationsOutputMethodElement == null) {
            Global.showWarning(
                    "This configuration file is old, update to the new version which includes recommendations output management.");
            Global.showWarning("Using default RecommendationsOutputMethod --> "
                    + RecommendationsOutputStandardXML.class.getName());
            recommdendationsOutputMethod = new RecommendationsOutputStandardXML();
        } else {
            recommdendationsOutputMethod = RecommdendationsOutputMethodXML
                    .getRecommdendationsOutputMethod(recommdendationsOutputMethodElement);
        }
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage("Recommendation output method loaded: "
                    + recommdendationsOutputMethod.getNameWithParameters() + "\n");
        }
    }

    //Obtiene el mtodo para calcular los items candidatos a recomendacin.
    RecommendationCandidatesSelector recommendationCandidatesSelector;
    {
        Element recommendationCandidatesSelectorElement = config
                .getChild(RecommendationCandidatesSelectorXML.RECOMMENDATION_CANDIDATE_SELECTOR_ELEMENT_NAME);
        if (recommendationCandidatesSelectorElement == null) {
            Global.showWarning(
                    "This configuration file is old, update to the new version which includes recommendation candidates selector.");
            Global.showWarning("Using default RecommendationCandidatesSelector --> "
                    + RecommendationCandidatesSelector.defaultValue.getClass().getName());
            recommendationCandidatesSelector = RecommendationCandidatesSelector.defaultValue;
        } else {
            recommendationCandidatesSelector = RecommendationCandidatesSelectorXML
                    .getRecommendationsCandidatesSelector(recommendationCandidatesSelectorElement);
        }
        if (Global.isVerboseAnnoying()) {
            Global.showInfoMessage("Recommendation output method loaded: "
                    + recommdendationsOutputMethod.getNameWithParameters() + "\n");
        }
    }

    if (config.getChild("NUMBER_OF_RECOMMENDATIONS") != null) {
        Global.showWarning(
                "Deprecated RecommenderSystem Configuration element: _Number of recommendations. Use RecommendationOutputMethod parameter NUMBER_OF_RECOMMENDATIONS instead.");
    }

    RecommenderSystemConfiguration ret = new RecommenderSystemConfiguration(recommender, datasetLoader,
            persistenceMethod, recommendationCandidatesSelector, recommdendationsOutputMethod,
            relevanceCriteria);
    Global.showMessageTimestamped("Loaded config file " + configFilePath);

    return ret;

}

From source file:delfos.configuration.ConfigurationScope.java

License:Open Source License

/**
 * The scopeName property is set with the given value.
 *
 * @param propertyName Name of the property, separated with dots to indicate
 * route, e.g., swing-gui.position.x indicates that x element of
 * swing-gui/position is set to the provided value.
 * @param value value of the property.//w  w  w.ja  va2s.  c  o  m
 */
public void setProperty(String propertyName, String value) {
    loadConfigurationScope();

    List<String> path = Arrays.asList(propertyName.split("\\."));

    Element targetElement = null;

    for (String node : path) {
        Element targetElementChild;
        if (targetElement == null) {
            targetElementChild = document.getRootElement().getChild(node);
            if (targetElementChild == null) {
                targetElementChild = new Element(node);
                document.getRootElement().addContent(targetElementChild);
            }
        } else {
            targetElementChild = targetElement.getChild(node);
            if (targetElementChild == null) {
                targetElementChild = new Element(node);
                targetElement.addContent(targetElementChild);
            }
        }
        targetElement = targetElementChild;
    }
    targetElement.setAttribute("value", value);

    saveConfigurationScope();
}

From source file:delfos.configuration.ConfigurationScope.java

License:Open Source License

public String getProperty(String propertyName) {
    loadConfigurationScope();/*from  w w  w.  j a v  a 2  s  .  c  o  m*/

    List<String> path = new ArrayList<>(Arrays.asList(propertyName.split("\\.")));

    Element root = document.getRootElement();
    if (root == null) {
        throw new IllegalStateException("Root element cannot be null");
    }
    Element targetElement = root.getChild(path.remove(0));

    for (String node : path) {
        if (targetElement == null) {
            break;
        }
        targetElement = targetElement.getChild(node);
    }
    if (targetElement == null) {
        return null;
    } else {
        return targetElement.getAttributeValue("value");
    }
}

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();/*from   www .  j  a  v a2  s . com*/
    } 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() + ")");
    }/*from w w  w  .ja  v  a  2s  . co m*/

    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.casestudy.GroupCaseStudyXML.java

License:Open Source License

/**
 * Carga la descripcin de un caso de estudio para sistemas de recomendacin
 * para grupos./*from  w  ww .j  a  v a 2  s.  c  o m*/
 *
 * @param file Archivo donde se encuentra almacenado el caso de estudio.
 * @return Caso de estudio recuperado del archivo.
 * @throws org.jdom2.JDOMException Cuando se intenta cargar un xml que no
 * tiene la estructura esperada. Chequear si esta desfasada la versin.
 * @throws IOException Cuando no se puede leer el archivo indicado o existe
 * algun fallo de conversin de datos al leer el contenido del mismo.
 */
public static GroupCaseStudyConfiguration loadGroupCaseDescription(File file)
        throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();

    Document doc = builder.build(file);
    Element caseStudy = doc.getRootElement();
    if (!caseStudy.getName().equals(CASE_ROOT_ELEMENT_NAME)) {
        throw new IllegalArgumentException("The XML does not contains a Case Study.");
    }
    GroupRecommenderSystem<Object, Object> groupRecommenderSystem = GroupRecommenderSystemXML
            .getGroupRecommenderSystem(caseStudy.getChild(GroupRecommenderSystemXML.ELEMENT_NAME));

    GroupFormationTechnique groupFormationTechnique = GroupFormationTechniqueXML
            .getGroupFormationTechnique(caseStudy.getChild(GroupFormationTechniqueXML.ELEMENT_NAME));
    ValidationTechnique validationTechnique = ValidationTechniqueXML
            .getValidationTechnique(caseStudy.getChild(ValidationTechniqueXML.ELEMENT_NAME));
    GroupPredictionProtocol groupPredictionProtocol = GroupPredictionProtocolXML
            .getGroupPredictionProtocol(caseStudy.getChild(GroupPredictionProtocolXML.ELEMENT_NAME));
    RelevanceCriteria relevanceCriteria = RelevanceCriteriaXML
            .getRelevanceCriteria(caseStudy.getChild(RelevanceCriteriaXML.ELEMENT_NAME));

    DatasetLoader<? extends Rating> datasetLoader = DatasetLoaderXML
            .getDatasetLoader(caseStudy.getChild(DatasetLoaderXML.ELEMENT_NAME));

    long seed = Long.parseLong(caseStudy.getAttributeValue(SeedHolder.SEED.getName()));
    int numExecutions = Integer.parseInt(caseStudy.getAttributeValue(NUM_EXEC_ATTRIBUTE_NAME));
    String caseStudyAlias = caseStudy.getAttributeValue(ParameterOwner.ALIAS.getName());

    return new GroupCaseStudyConfiguration(groupRecommenderSystem, datasetLoader, groupFormationTechnique,
            validationTechnique, groupPredictionProtocol, relevanceCriteria, caseStudyAlias, numExecutions,
            seed, null);
}

From source file:delfos.group.io.xml.casestudy.GroupCaseStudyXML.java

License:Open Source License

/**
 * Carga la descripcin de un caso de estudio para sistemas de recomendacin
 * para grupos./*w  w  w.j a va2s  .  c  o m*/
 *
 * @param file Archivo donde se encuentra almacenado el caso de estudio.
 * @return Caso de estudio recuperado del archivo.
 * @throws org.jdom2.JDOMException Cuando se intenta cargar un xml que no
 * tiene la estructura esperada. Chequear si esta desfasada la versin.
 * @throws IOException Cuando no se puede leer el archivo indicado o existe
 * algun fallo de conversin de datos al leer el contenido del mismo.
 */
public static GroupCaseStudyConfiguration loadGroupCaseWithResults(File file)
        throws JDOMException, IOException {
    SAXBuilder builder = new SAXBuilder();

    Document doc = builder.build(file);
    Element caseStudy = doc.getRootElement();
    if (!caseStudy.getName().equals(CASE_ROOT_ELEMENT_NAME)) {
        throw new IllegalArgumentException("The XML does not contains a Case Study.");
    }
    GroupRecommenderSystem<Object, Object> groupRecommenderSystem = GroupRecommenderSystemXML
            .getGroupRecommenderSystem(caseStudy.getChild(GroupRecommenderSystemXML.ELEMENT_NAME));

    GroupFormationTechnique groupFormationTechnique = GroupFormationTechniqueXML
            .getGroupFormationTechnique(caseStudy.getChild(GroupFormationTechniqueXML.ELEMENT_NAME));
    ValidationTechnique validationTechnique = ValidationTechniqueXML
            .getValidationTechnique(caseStudy.getChild(ValidationTechniqueXML.ELEMENT_NAME));
    GroupPredictionProtocol groupPredictionProtocol = GroupPredictionProtocolXML
            .getGroupPredictionProtocol(caseStudy.getChild(GroupPredictionProtocolXML.ELEMENT_NAME));
    RelevanceCriteria relevanceCriteria = RelevanceCriteriaXML
            .getRelevanceCriteria(caseStudy.getChild(RelevanceCriteriaXML.ELEMENT_NAME));

    DatasetLoader<? extends Rating> datasetLoader = DatasetLoaderXML
            .getDatasetLoader(caseStudy.getChild(DatasetLoaderXML.ELEMENT_NAME));

    Map<GroupEvaluationMeasure, GroupEvaluationMeasureResult> groupEvaluationMeasuresResults = getEvaluationMeasures(
            caseStudy);

    long seed = Long.parseLong(caseStudy.getAttributeValue(SeedHolder.SEED.getName()));
    int numExecutions = Integer.parseInt(caseStudy.getAttributeValue(NUM_EXEC_ATTRIBUTE_NAME));
    String caseStudyAlias = caseStudy.getAttributeValue(ParameterOwner.ALIAS.getName());

    return new GroupCaseStudyConfiguration(groupRecommenderSystem, datasetLoader, groupFormationTechnique,
            validationTechnique, groupPredictionProtocol, relevanceCriteria, caseStudyAlias, numExecutions,
            seed, groupEvaluationMeasuresResults);
}

From source file:delfos.group.io.xml.casestudy.GroupCaseStudyXML.java

License:Open Source License

private static Map<GroupEvaluationMeasure, GroupEvaluationMeasureResult> getEvaluationMeasures(
        Element caseStudy) {

    Map<GroupEvaluationMeasure, GroupEvaluationMeasureResult> groupEvaluationMeasures = new TreeMap<>();

    Element aggregateValues = caseStudy.getChild(AGGREGATE_VALUES_ELEMENT_NAME);

    if (aggregateValues == null) {
        throw new IllegalStateException(
                "Unable to load a case study description only, the XML must have results details.");
    }//from w  w w  .j a  v a  2 s  .  c  om

    for (Element groupEvaluationMeasureResultElement : aggregateValues.getChildren()) {
        String name = groupEvaluationMeasureResultElement.getName();

        GroupEvaluationMeasure groupEvaluationMeasure = GroupEvaluationMeasuresFactory.getInstance()
                .getClassByName(name);
        if (groupEvaluationMeasure == null) {
            throw new IllegalStateException(
                    "The group evaluation measure '" + name + "' does not exists in delfos' factory");
        } else {
            groupEvaluationMeasures.put(groupEvaluationMeasure, groupEvaluationMeasure
                    .getGroupEvaluationMeasureResultFromXML(groupEvaluationMeasureResultElement));
        }
    }

    return groupEvaluationMeasures;
}