Example usage for org.dom4j Node selectSingleNode

List of usage examples for org.dom4j Node selectSingleNode

Introduction

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

Prototype

Node selectSingleNode(String xpathExpression);

Source Link

Document

selectSingleNode evaluates an XPath expression and returns the result as a single Node instance.

Usage

From source file:log4JToXml.xmlToProperties.XmlToLog4jConverterImpl.java

private void processLoggers() {
    //logger, optional
    List<Node> loggerNodes = doc.selectNodes("/log4j:configuration/logger");

    if (!loggerNodes.isEmpty()) {
        for (Node logger : loggerNodes) {

            String loggerContent = "";

            //level, 0-1
            Node loggerLevel = logger.selectSingleNode("./level");

            if (loggerLevel != null) {
                loggerContent += loggerLevel.valueOf("@value").toUpperCase();
            }/*from   w  w  w.  j a  v  a2  s.c om*/

            //appender-refs, optional
            List<Node> loggerAppenderRefs = logger.selectNodes("./appender-ref");

            if (!loggerAppenderRefs.isEmpty()) {
                for (Node appenderRef : loggerAppenderRefs) {
                    loggerContent += ", " + appenderRef.valueOf("@ref");
                }
            }

            String loggerName = "log4j.logger." + logger.valueOf("@name");
            log4jProperties.setProperty(loggerName, loggerContent);

            //logger additivity
            if (logger.valueOf("@additivity").equals("false")) {
                log4jProperties.setProperty("log4j.additivity." + logger.valueOf("@name"), "false");
            }
        }
    }
}

From source file:MyLibrary.DoExchangeRate.java

/**
 * yahooapi??/*from www  . ja  v  a  2  s.co m*/
 * @param sourceCurrency ???
 * @return doublenull
 * @throws Exception 
 */
@SuppressWarnings("unchecked")
public double getExchangeRateByYahooApi(String sourceCurrency) throws Exception {
    String url = "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote";
    String httpResult = DoHttpRequest1.doGet(url, "utf-8", 2);
    Document Document1 = DocumentHelper.parseText(httpResult);
    Element root = Document1.getRootElement();
    List<Node> nodes = root.selectNodes("//resource");
    Predicate<Node> usd = (node) -> node.selectSingleNode("field").getText().equals("USD/" + sourceCurrency);
    Object[] results = nodes.stream().filter(usd).map((node) -> {
        Node n = (Node) node;
        String xmlStr = n.selectSingleNode("field[2]").getText();
        double rate = 1.00 / Double.parseDouble(xmlStr);
        return rate;
    }).toArray();
    Double result = (Double) results[0];
    return result;
}

From source file:neat.NEAT.java

License:Open Source License

@Override
public NEAT loadFromXML(Node nd) {
    // Add properties
    loadProperties();/*w w  w . ja  v  a  2 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);
        }//w w w.j  a  v a 2  s .c o m
    }
}

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

private Map<String, Object> setRelQProperties(Node originalQuestion, Map<String, Object> relQuestionMap) {
    Node thread = originalQuestion.selectSingleNode("Thread");
    Node relQuestion = thread.selectSingleNode("RelQuestion");
    String relQId = relQuestion.valueOf("@RELQ_ID");
    Map<String, Object> relQuestionInfo = new LinkedHashMap<>();
    if (relQuestionMap.isEmpty() || !relQuestionMap.containsKey(relQId)) {
        relQuestionInfo.put("IsRelevant", relQuestion.valueOf("@RELQ_RELEVANCE2ORGQ"));
        relQuestionInfo.put("RelQBody", relQuestion.valueOf("RelQClean"));
        relQuestionInfo.put("RelComment", new LinkedHashMap<String, Object>());
        relQuestionMap.put(relQId, relQuestionInfo);
    }//w ww  .  ja  v a  2s. com
    return relQuestionInfo;
}

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

private Map<String, Object> setOriginalQProperties(Node originalQuestion) {
    Map<String, Object> orgQuestionInfo = new LinkedHashMap<>();

    orgQuestionInfo.put("OrgQBody", originalQuestion.selectSingleNode("OrgQClean").getText());
    orgQuestionInfo.put("RelQuestion", new LinkedHashMap<String, Object>());
    return orgQuestionInfo;
}

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

License:Open Source License

private Scene loadSceneAttributes(Node n, int id) {
    Scene s = null;/*from  w w  w.j  a v  a2s  .  c  o m*/
    if (id == 0) {
        s = adventure.getStart();
    } else {
        s = adventure.createScene(id, Boolean.valueOf(n.valueOf("@isEnd")));
    }
    s.setImageId(n.valueOf("@imageId"));
    if (s.getImageId() != null && s.getImageId().trim().length() == 0) {
        s.setImageId(null);
    }

    s.setName(n.valueOf("@name"));
    s.setTags(n.valueOf("@tags"));
    s.setText(n.selectSingleNode("./text").getText());

    try {
        s.setCode(n.selectSingleNode("./code").getText());
        if (s.getCode() == null) {
            s.setCode("");
        }
    } catch (NullPointerException npe) {
        logger.warn("No code node");
    }

    loadCombat(n, s);
    loadSkillTest(n, s);

    return s;
}

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

License:Open Source License

private void loadSkillTest(Node n, Scene s) {
    Node cn = n.selectSingleNode("skill-test");
    if (cn == null) {
        return;/*w  w w. j a  va2 s. c o m*/
    }
    String name = cn.valueOf("@name");
    s.setType(SceneType.skillTest);
    s.setSkillToTest(new Skill(name));
}

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;//  w  w w. j a  v a 2  s.co  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.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  w  w w.j  a  v  a2  s .  co  m
    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;
}