Example usage for org.dom4j Node selectNodes

List of usage examples for org.dom4j Node selectNodes

Introduction

In this page you can find the example usage for org.dom4j Node selectNodes.

Prototype

List<Node> selectNodes(String xpathExpression);

Source Link

Document

selectNodes evaluates an XPath expression and returns the result as a List of Node instances or String instances depending on the XPath expression.

Usage

From source file:neat.NEAT.java

License:Open Source License

@Override
public NEAT loadFromXML(Node nd) {
    // Add properties
    loadProperties();/*from  ww w .  j a v  a2 s.  co  m*/

    // set generator
    generator = new NESRandom(FrevoMain.getSeed());

    this.input_number = Integer.parseInt(nd.valueOf("./@input_nodes"));
    this.output_number = Integer.parseInt(nd.valueOf("./@output_nodes"));

    this.recurrent = Boolean.parseBoolean(nd.valueOf("./@recurrent"));

    String fitnessString = nd.valueOf("./@fitness");
    if (!fitnessString.isEmpty()) {
        this.setFitness(Double.parseDouble(fitnessString));
    }

    // load genes
    ArrayList<NEATGene> genes = new ArrayList<NEATGene>();
    Node dgenes = nd.selectSingleNode("./genes");

    @SuppressWarnings("unchecked")
    List<? extends Node> gs = dgenes.selectNodes("./*");
    Iterator<? extends Node> it = gs.iterator();

    while (it.hasNext()) {
        Node n = it.next();
        String name = n.getName();

        if (name.equals("NEATlinkGene"))
            genes.add(new NEATLinkGene(n));
        else if (name.equals("NEATNodeGene"))
            genes.add(new NEATNodeGene(n));
        else
            genes.add(new NEATFeatureGene(n));
    }

    this.chromosome = new NEATChromosome(genes);

    updateNetStructure();

    return this;
}

From source file:net.asteasolutions.cinusuidi.sluncho.utils.XmlParse.java

private void setRelCommentProperties(Node originalQuestion, Map<String, Object> relQuestionMap) {
    Node thread = originalQuestion.selectSingleNode("Thread");
    List<Node> relComments = thread.selectNodes("RelComment");
    for (Node comment : relComments) {
        String commentId = comment.valueOf("@RELC_ID");
        if (relQuestionMap.isEmpty() || !relQuestionMap.containsKey(commentId)) {
            Map<String, Object> relCommentInfo = new LinkedHashMap<>();
            relCommentInfo.put("RelCBody", comment.selectSingleNode("RelCClean").getText());
            relCommentInfo.put("IsRelevantToOrgQ", comment.valueOf("@RELC_RELEVANCE2ORGQ"));
            relCommentInfo.put("IsRelevantToRelQ", comment.valueOf("@RELC_RELEVANCE2RELQ"));
            relQuestionMap.put(commentId, relCommentInfo);
        }/*from   w ww  . ja v  a 2  s. co  m*/
    }
}

From source file:net.bpfurtado.ljcolligo.GetComments.java

License:Open Source License

private String textFrom(Node n, String nodeName) {
    List nodes = n.selectNodes(nodeName);
    if (!nodes.isEmpty()) {
        return ((Node) nodes.get(0)).getText().trim();
    }/*from   w  w  w. j  a  v  a2 s .  c o m*/
    return null;
}

From source file:net.bpfurtado.tas.model.persistence.XMLAdventureReader.java

License:Open Source License

private void loadCombat(Node n, Scene s) {
    Node cn = n.selectSingleNode("combat");
    if (cn == null) {
        return;//from www .j av  a 2s  . c  o m
    }

    Combat c = new Combat();
    String type = cn.valueOf("@type");
    c.setType(CombatType.fromPersistentRepr(type));

    List<Node> enemyNodes = cn.selectNodes("./enemy");
    for (Node en : enemyNodes) {
        Fighter fighter = new Fighter(en.valueOf("@name"), Integer.valueOf(en.valueOf("@skill")),
                Integer.valueOf(en.valueOf("@stamina")));
        fighter.setDamage(Integer.valueOf(en.valueOf("@damage")));
        c.add(fighter);
    }

    s.setType(SceneType.combat);
    s.setCombat(c);
}

From source file:net.bpfurtado.tas.model.persistence.XMLAdventureReader.java

License:Open Source License

/**
 * @param scene/*from  w w w.j  a  v a 2 s . c  o  m*/
 * @param scenesNotScannedYet
 *            Just to keep the scenes not yet visited.
 */
@SuppressWarnings("unchecked")
private void findAllTos(Scene scene, Collection<Scene> scenesNotScannedYet) {
    if (scenesNotScannedYet != null) {
        scenesNotScannedYet.remove(scene);
    }

    Node sceneNode = xmlDocument.selectSingleNode("//scene[@id='" + scene.getId() + "']");
    List<Node> pathNodes = sceneNode.selectNodes("./path");
    int i = 0;
    logger.debug("Scene=" + scene + ", pathNodes.sz=" + pathNodes.size());
    for (Node pathNode : pathNodes) {
        logger.debug(i);
        IPath p = scene.createPath(pathNode.getText());
        String orderStr = pathNode.valueOf("@order");
        if (orderStr == null || orderStr.length() == 0) {
            p.setOrder(i++);
        }
        String idToStr = pathNode.valueOf("@toScene");
        if (!GenericValidator.isBlankOrNull(idToStr)) {
            Scene to = adventure.getScene(Integer.parseInt(idToStr));
            boolean hadScenesFrom = !to.getScenesFrom().isEmpty();
            p.setTo(to);

            logger.debug(p);

            if (!hadScenesFrom) {
                logger.debug("BEFORE RECURSION: to=" + to);
                logger.debug("BEFORE RECURSION: all=" + scenesNotScannedYet);
                if (scenesNotScannedYet.contains(to)) {
                    findAllTos(to, scenesNotScannedYet);
                }
            }
        } else {
            logger.debug(p);
        }
    }
}

From source file:net.bpfurtado.tas.runner.savegame.SaveGamePersister.java

License:Open Source License

public static SaveGame read(File saveGameFile) {
    try {// ww  w.  ja  v a  2s . co m
        SAXReader xmlReader = new SAXReader();
        Document xml = xmlReader.read(saveGameFile);

        Element root = xml.getRootElement();

        Node xmlPlayer = root.selectSingleNode("player");

        Player player = new Player("noName", 0, integer(xmlPlayer, "stamina"));
        player.setDamage(integer(xmlPlayer, "damage"));

        List<Node> skills = xmlPlayer.selectNodes("skills/skill");
        for (Node skill : skills) {
            player.addSkill(skill.valueOf("@name"), integer(skill, "level"));
        }

        List<Node> attributes = xmlPlayer.selectNodes("attributes/attribute");
        for (Node attribute : attributes) {
            String key = attribute.valueOf("@key");
            String val = attribute.valueOf("@value");
            try {
                player.addAttribute(key, Integer.parseInt(val));
            } catch (NumberFormatException e) {
                player.addAttribute(key, val);
            }
        }

        Workspace workspace = Workspace.loadFrom(root.valueOf("@workspaceId"));
        SaveGame saveGame = new SaveGame(workspace, player, integer(root, "sceneId"),
                root.valueOf("@creation"));
        saveGame.setFile(saveGameFile);
        return saveGame;
    } catch (DocumentException e) {
        throw new AdventureReaderException("Error reading XML document", e);
    }
}

From source file:net.indigital.util.Properties.java

License:Open Source License

public static List<Mapping> configure(String configFileLocation) {
    Document document = getDocument(configFileLocation);
    List<Node> mappingNodes = selectNodes(document, mapping);

    Integer pauseMySQLReconnections; //ms
    Integer pauseCassandraReconnections; //ms
    Integer refresh; //ms
    Integer elementsAtOnce; //num elements

    String mysqlHost;/*from  www.  j  a  va  2s  .c  om*/
    Integer mysqlPort;
    String user;
    String pass;
    String db;
    String table;
    String numericKeyStr;
    String cassHost;
    Integer cassPort;
    String keysType;
    Boolean truncateDataBase;

    /* Common to all the mappings. This structure will allow the threads
    *  to know which Cassandra keyspace has already been tried to be removed. */
    Lock lock = new ReentrantLock();
    Map<String, Boolean> keyspaces = new HashMap<String, Boolean>();

    /* All the fields to be mapped. */
    List<Map<String, String>> maps;
    /* A list of parsed Mapping nodes. */
    List<Mapping> listMapping = new ArrayList<Mapping>();

    /*
    * We need to check that we don't have repeated mappings.
    * We based this on calculating an id with the values of the mapping.
    */
    String id;
    List<String> mapsIdList = new ArrayList<String>();

    if (mappingNodes.size() < 1) {
        Log.error("You need at least one mapping node");
        System.exit(0);
    }

    for (Node node : mappingNodes) {
        maps = new ArrayList<Map<String, String>>();

        if ((node.getName() == null) || (!(node.getName().equals("mapping")))
                || (node.selectSingleNode("@refresh") == null)
                || (node.selectSingleNode("@refresh").getStringValue().isEmpty())
                || (node.selectSingleNode("@elementsAtOnce") == null)
                || (node.selectSingleNode("@elementsAtOnce").getStringValue().isEmpty())) {
            Log.error("Found an incorrect mapping node");
            System.exit(0);
        }
        refresh = Integer.parseInt(node.selectSingleNode("@refresh").getStringValue());
        elementsAtOnce = Integer.parseInt(node.selectSingleNode("@elementsAtOnce").getStringValue());

        List<Node> mysqlNodes = node.selectNodes("mysql");
        List<Node> cassandraNodes = node.selectNodes("cassandra");
        List<Node> mapsNodes = node.selectNodes("maps");
        if ((mysqlNodes.size() != 1) || (cassandraNodes.size() != 1) || (mapsNodes.size() != 1)) {
            Log.error("Each mapping needs one mysql|cassandra|maps node");
            System.exit(0);
        }

        /* Parsing mySQL information */
        Node mysqlNode = (Node) mysqlNodes.toArray()[0];
        if ((mysqlNode.selectSingleNode("@host") == null)
                || (mysqlNode.selectSingleNode("@host").getStringValue().isEmpty())
                || (mysqlNode.selectSingleNode("@user") == null)
                || (mysqlNode.selectSingleNode("@user").getStringValue().isEmpty())
                || (mysqlNode.selectSingleNode("@pass") == null)
                || (mysqlNode.selectSingleNode("@pass").getStringValue().isEmpty())
                || (mysqlNode.selectSingleNode("@db") == null)
                || (mysqlNode.selectSingleNode("@db").getStringValue().isEmpty())
                || (mysqlNode.selectSingleNode("@table") == null)
                || (mysqlNode.selectSingleNode("@table").getStringValue().isEmpty())
                || (mysqlNode.selectSingleNode("@numericKeyStr") == null)
                || (mysqlNode.selectSingleNode("@numericKeyStr").getStringValue().isEmpty())
                || (mysqlNode.selectSingleNode("@truncateDataBase") == null)
                || (mysqlNode.selectSingleNode("@truncateDataBase").getStringValue().isEmpty())
                || (mysqlNode.selectSingleNode("@pauseReconnections") == null)
                || (mysqlNode.selectSingleNode("@pauseReconnections").getStringValue().isEmpty())) {
            Log.error("Found an incorrect mysql node");
            System.exit(0);
        }
        /* Setting variables for the mySQL parsed information */
        mysqlHost = mysqlNode.selectSingleNode("@host").getStringValue();
        mysqlPort = Integer.parseInt(mysqlNode.selectSingleNode("@port").getStringValue());
        user = mysqlNode.selectSingleNode("@user").getStringValue();
        pass = mysqlNode.selectSingleNode("@pass").getStringValue();
        db = mysqlNode.selectSingleNode("@db").getStringValue();
        table = mysqlNode.selectSingleNode("@table").getStringValue();
        numericKeyStr = mysqlNode.selectSingleNode("@numericKeyStr").getStringValue();

        if ((!(mysqlNode.selectSingleNode("@truncateDataBase").getStringValue().equals("true")))
                && (!(mysqlNode.selectSingleNode("@truncateDataBase").getStringValue().equals("false")))) {
            Log.error("Found an incorrect type in a column: "
                    + mysqlNode.selectSingleNode("@truncateDataBase").getStringValue());
            System.exit(0);
        }

        if (mysqlNode.selectSingleNode("@truncateDataBase").getStringValue().equals("true")) {
            truncateDataBase = Boolean.TRUE;
        } else {
            truncateDataBase = Boolean.FALSE;
        }

        pauseMySQLReconnections = Integer
                .parseInt(mysqlNode.selectSingleNode("@pauseReconnections").getStringValue());

        /* Parsing cassandra information */
        Node cassandraNode = (Node) cassandraNodes.toArray()[0];
        if ((cassandraNode.selectSingleNode("@host") == null)
                || (cassandraNode.selectSingleNode("@host").getStringValue().isEmpty())
                || (cassandraNode.selectSingleNode("@port") == null)
                || (cassandraNode.selectSingleNode("@port").getStringValue().isEmpty())
                || (cassandraNode.selectSingleNode("@pauseReconnections") == null)
                || (cassandraNode.selectSingleNode("@pauseReconnections").getStringValue().isEmpty())
                || (cassandraNode.selectSingleNode("@keysType") == null)
                || (cassandraNode.selectSingleNode("@keysType").getStringValue().isEmpty())) {
            Log.error("Found an incorrect cassandra node. Host, port, pauseReconnections or keysType non-set");
            System.exit(0);
        }

        if ((!(cassandraNode.selectSingleNode("@keysType").getStringValue().equals("int")))
                && (!(cassandraNode.selectSingleNode("@keysType").getStringValue().equals("string")))) {
            Log.error("Found an incorrect type for the Cassandra keys: "
                    + cassandraNode.selectSingleNode("@keysType").getStringValue());
            System.exit(0);
        }

        /* Setting variables for the Cassandra parsed information */
        cassHost = cassandraNode.selectSingleNode("@host").getStringValue();
        cassPort = Integer.parseInt(cassandraNode.selectSingleNode("@port").getStringValue());
        pauseCassandraReconnections = Integer
                .parseInt(cassandraNode.selectSingleNode("@pauseReconnections").getStringValue());
        keysType = cassandraNode.selectSingleNode("@keysType").getStringValue();

        /* Parsing the columns and adding a 'map' for each column. */
        Node mapsNode = (Node) mapsNodes.toArray()[0];
        List<Node> columnNodes = mapsNode.selectNodes("column");
        if (columnNodes.size() < 2) {
            Log.error("You need at least two columns in the maps");
            System.exit(0);
        }
        for (Node column : columnNodes) {
            if (!(column.getName().equals("column"))) {
                Log.error("Found an incorrect maps");
                System.exit(0);
            }

            if ((column.selectSingleNode("@name") == null)
                    || (column.selectSingleNode("@name").getStringValue().isEmpty())
                    || (column.selectSingleNode("@type") == null)
                    || (column.selectSingleNode("@type").getStringValue().isEmpty())
                    || (column.selectSingleNode("@secondaryIndex") == null)
                    || (column.selectSingleNode("@secondaryIndex").getStringValue().isEmpty())) {
                Log.error("Found an incorrect column node");
                System.exit(0);
            }

            if ((!(column.selectSingleNode("@type").getStringValue().equals("int")))
                    && (!(column.selectSingleNode("@type").getStringValue().equals("string")))
                    && (!(column.selectSingleNode("@type").getStringValue().equals("datetime")))) {
                Log.error("Found an incorrect type in a column: "
                        + column.selectSingleNode("@type").getStringValue());
                System.exit(0);
            }

            if ((!(column.selectSingleNode("@secondaryIndex").getStringValue().equals("true")))
                    && (!(column.selectSingleNode("@secondaryIndex").getStringValue().equals("false")))) {
                Log.error("Found an incorrect type in a column: "
                        + column.selectSingleNode("@secondaryIndex").getStringValue());
                System.exit(0);
            }

            Map<String, String> tmp = new HashMap<String, String>();
            tmp.put("name", column.selectSingleNode("@name").getStringValue());
            tmp.put("type", column.selectSingleNode("@type").getStringValue());
            tmp.put("secondaryIndex", column.selectSingleNode("@secondaryIndex").getStringValue());
            maps.add(tmp);

            Log.debug("name:" + column.selectSingleNode("@name").getStringValue() + ", type:"
                    + column.selectSingleNode("@type").getStringValue() + ", secondaryIndex:"
                    + column.selectSingleNode("@secondaryIndex").getStringValue());
        }

        /* Checking if a mapping node similar to the actual has been inserted.*/
        id = mysqlHost + mysqlPort + db + table + cassHost + cassPort;
        if (mapsIdList.contains(id)) {
            Log.error("Found a repeated mapping node with id: " + id);
            System.exit(0);
        } else {
            mapsIdList.add(id);
        }

        /* Finally creating and adding another mapping node. */
        Mapping m = new Mapping(lock, keyspaces, truncateDataBase, keysType, pauseMySQLReconnections,
                pauseCassandraReconnections, refresh, elementsAtOnce, mysqlHost, mysqlPort, db, user, pass,
                table, numericKeyStr, maps, cassHost, cassPort);
        listMapping.add(m);
        Log.debug("Success while adding another mapping!");

    }

    /* Finally returning the desired object. */
    return listMapping;
}

From source file:nnga.NNGA.java

License:Open Source License

@Override
public ArrayList<ArrayList<AbstractRepresentation>> loadFromXML(Document doc) {
    // final list to be returned
    ArrayList<ArrayList<AbstractRepresentation>> populations = new ArrayList<ArrayList<AbstractRepresentation>>();

    // get population root node
    Node dpopulations = doc.selectSingleNode("/frevo/populations");

    // get number of populations
    int populationCount = Integer.parseInt(dpopulations.valueOf("./@count"));
    // get number of current generation
    int currentGeneration = Integer.parseInt(dpopulations.valueOf("./@generation"));

    // get population size
    @SuppressWarnings("unchecked")
    List<? extends Node> populationsNode = dpopulations.selectNodes(".//population");
    int populationSize = populationsNode.get(0).selectNodes("*").size();

    // calculate total representations
    int totalRepresentations = populationCount * populationSize;
    int currentPopulation = 0;
    int currentRepresentation = 0;

    // Iterate through the population nodes
    Iterator<?> populationIterator = populationsNode.iterator();
    while (populationIterator.hasNext()) {
        Node populationNode = (Node) populationIterator.next();

        // create list of candidate representations for this population
        ArrayList<AbstractRepresentation> result = new ArrayList<AbstractRepresentation>();

        // track current progress
        currentRepresentation = 0;//from  w  w w  .  j  a v  a 2 s.c o m
        try {
            // Obtain an iterator over the representations
            List<?> representations = populationNode.selectNodes("./*");
            Iterator<?> representationsIterator = representations.iterator();

            while (representationsIterator.hasNext()) {
                // calculate current position for progress reporting
                int currentItem = currentPopulation * populationSize + currentRepresentation + 1;

                // report loading state
                FrevoMain.setLoadingProgress((float) currentItem / totalRepresentations);

                // step to next node
                Node net = (Node) representationsIterator.next();

                // construct representation based on loaded representation
                // data
                ComponentXMLData representation = FrevoMain
                        .getSelectedComponent(ComponentType.FREVO_REPRESENTATION);
                AbstractRepresentation member = representation.getNewRepresentationInstance(0, 0, null);

                // load representation data from the XML into the instance
                member.loadFromXML(net);

                // add data to current population list
                result.add(member);

                // increment tracker
                currentRepresentation++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        populations.add(result);

        currentPopulation++;
    }

    // Load the number of generations
    XMLFieldEntry gensize = getProperties().get("generations");
    if (gensize != null) {
        int generations = Integer.parseInt(gensize.getValue());
        // TODO check max fitness also
        // set boolean value which shows possibility of continuation of experiment
        // if maximum number of generations hasn't been reached.
        setCanContinue(currentGeneration + 1 < generations);
    }

    return populations;
}

From source file:org.b5chat.crossfire.core.plugin.PluginCacheConfigurator.java

License:Open Source License

private Map<String, String> readInitParams(Node configData) {
    Map<String, String> paramMap = new HashMap<String, String>();
    @SuppressWarnings("unchecked")
    List<Node> params = configData.selectNodes("init-params/init-param");
    for (Node param : params) {
        String paramName = param.selectSingleNode("param-name").getStringValue();
        String paramValue = param.selectSingleNode("param-value").getStringValue();
        paramMap.put(paramName, paramValue);
    }/*ww  w .  ja  v  a 2s  .c  o  m*/

    return paramMap;
}

From source file:org.ballproject.knime.base.config.CTDFileNodeConfigurationReader.java

License:Open Source License

@SuppressWarnings("unchecked")
public void readParameters() throws Exception {
    Node root = this.doc.selectSingleNode("/tool/PARAMETERS");
    List<Node> items = root.selectNodes("//ITEM[not(contains(@tags,'" + this.OUTPUTFILE_TAG
            + "')) and not(contains(@tags,'" + this.INPUTFILE_TAG + "'))]");
    for (Node n : items) {
        this.processItem(n);
    }/*from  ww  w  . ja v  a  2s . co  m*/
    items = root.selectNodes("//ITEMLIST[not(contains(@tags,'" + this.OUTPUTFILE_TAG
            + "')) and not(contains(@tags,'" + this.INPUTFILE_TAG + "'))]");
    for (Node n : items) {
        this.processMultiItem(n);
    }
}