Example usage for org.dom4j Node valueOf

List of usage examples for org.dom4j Node valueOf

Introduction

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

Prototype

String valueOf(String xpathExpression);

Source Link

Document

valueOf evaluates an XPath expression and returns the textual representation of the results the XPath string-value of this node.

Usage

From source file:com.adobe.ac.pmd.metrics.maven.generators.NcssReportGenerator.java

License:Apache License

private void doTotalPackageAnalysis(final Document document) {
    getSink().table();//www .  j  a va  2  s.  co m
    getSink().tableRow();
    headerCellHelper(getResourceBundle().getString("report.javancss.header.classetotal"));
    headerCellHelper(getResourceBundle().getString("report.javancss.header.functiontotal"));
    headerCellHelper(getResourceBundle().getString("report.javancss.header.ncsstotal"));
    getSink().tableRow_();
    final Node node = document.selectSingleNode("//javancss/packages/total");
    getSink().tableRow();
    tableCellHelper(node.valueOf(CLASSES));
    tableCellHelper(node.valueOf(FUNCTIONS));
    tableCellHelper(node.valueOf(NCSS));
    getSink().tableRow_();
    getSink().table_();
}

From source file:com.alefissak.parsers.PlanningParserImpl.java

License:Apache License

/**
 * {@inheritDoc}//from  w  w  w  .jav  a2 s . com
 */
@Override
public List<Planning> parse() throws AlefissakFileNotFoundException, AlefissakParsingException {

    LOG.debug("Retrieving the document object from configuration file.");

    final Document document = getDocument();

    List<Planning> pList = new ArrayList<Planning>();

    try {

        Node plannings = document.selectSingleNode(Constants.CFG_ROOT_PATH);

        if (plannings == null) {
            throw new AlefissakParsingException("root element missing");
        }

        @SuppressWarnings("unchecked")
        List<Node> planningNodes = document.selectNodes(Constants.CFG_PLANNINGS_PATH);

        Node planningNode, timeNode, messageNode, fromNode, workingNode;
        String planningName;

        int rank = 1;

        for (Iterator<Node> iter = planningNodes.iterator(); iter.hasNext();) {
            planningNode = iter.next();

            Planning planning = new Planning();
            planningName = planningNode.valueOf(CFG_NAME_ATTRIBUTE_NAME);
            planning.setName(planningName);

            timeNode = planningNode.selectSingleNode(Constants.CFG_TIME_ATTRIBUTE_NAME);
            if (timeNode == null) {
                throw new AlefissakParsingException(
                        "Time configuration attributes are not defined for the planning " + planningName);
            }

            workingNode = timeNode.selectSingleNode(Constants.CFG_START_TIME_ATTRIBUTE_NAME);
            if (workingNode == null) {
                throw new AlefissakParsingException(
                        "Time configuration attributes are not defined for the planning " + planningName);
            }

            planning.setStartTime(AlefissakUtil.toDate(workingNode.getText().toString()));

            workingNode = timeNode.selectSingleNode(Constants.CFG_END_TIME_ATTRIBUTE_NAME);
            if (workingNode == null) {
                throw new AlefissakParsingException(
                        "Time configuration attributes are not defined for the planning " + planningName);
            }

            planning.setEndTime(AlefissakUtil.toDate(workingNode.getText().toString().trim()));

            workingNode = timeNode.selectSingleNode(Constants.CFG_TIME_INTERVAL_ATTRIBUTE_NAME);
            if (workingNode == null) {
                throw new AlefissakParsingException(
                        "Time configuration attributes are not defined for the planning " + planningName);
            }

            final TimeInterval timeInterval = AlefissakUtil.toTimeInterval(workingNode.getText().toString());

            planning.setTimeInterval(timeInterval);
            planning.setCronExpression(AlefissakUtil.getCronExpression(timeInterval));

            Message message = new AlefissakMessageConcret();

            if ((messageNode = planningNode.selectSingleNode(Constants.CFG_MESSAGE_TAG_NAME)) == null) {

                throw new AlefissakParsingException("No message defined for the planning " + planningName);
            }

            workingNode = messageNode.selectSingleNode(Constants.CFG_MESSAGE_OBJECT_TAG_NAME);

            message.setObject(workingNode == null ? "" : workingNode.getText().toString());

            fromNode = messageNode.selectSingleNode(Constants.CFG_MESSAGE_FROM_TAG_NAME);

            if (fromNode == null) {

                throw new AlefissakParsingException("From tag is missing in the configuration file");
            }

            workingNode = fromNode.selectSingleNode(Constants.CFG_NAME_TAG_NAME);
            AlefissakSender sender = new AlefissakSender();

            sender.setName(workingNode == null ? "" : workingNode.getText().toString());

            workingNode = fromNode.selectSingleNode(Constants.CFG_MAIL_TAG_NAME);

            sender.setMail(workingNode == null ? "" : workingNode.getText().toString());

            message.setSender(sender);

            workingNode = messageNode.selectSingleNode(Constants.CFG_MESSAGE_CONTENT_TAG_NAME);

            if (workingNode == null) {

                throw new AlefissakParsingException(
                        "There is no message to send for the planning " + planningName);
            }

            message.setContent(workingNode.getText().toString());

            planning.setMessage(message);

            parseReceivers(planning, planningNode);

            planning.setRank(rank++);

            pList.add(planning); // Add the new planning to the plannings
            // list
        }

    } catch (Exception e) {

        throw new AlefissakParsingException(e);
    }

    return pList;
}

From source file:com.alibaba.intl.bcds.goldroom.remote.DoubanBookInfoFetcher.java

License:Open Source License

private List<String> queryByXpathForList(String xpathExpression, String valueExpresssion, Document document) {
    try {/*  w w w  .j  a va  2  s .  c om*/
        XPath xPath = createXpath(xpathExpression);
        List<Node> nodes = xPath.selectNodes(document);
        if (nodes != null && nodes.size() > 0) {
            List<String> returnValue = new ArrayList<String>();
            for (Node n : nodes) {
                returnValue.add(n.valueOf(valueExpresssion));
            }
            return returnValue;
        }
        return new ArrayList<String>(0);
    } catch (RuntimeException e) {
        return new ArrayList<String>(0);
    }
}

From source file:com.appeligo.ccdataindexer.Indexer.java

License:Apache License

public boolean indexProgram(File programFile, Network network) throws IOException {
    log.debug("processing file " + programFile + " for " + network.getStationName());
    boolean needToClose = openIndex();
    StringBuilder captions = new StringBuilder();
    InputStream is = null;/*from w  ww  .  j  a v a  2  s .co m*/
    try {
        is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(programFile)));

        SAXReader reader = new SAXReader();
        reader.setEntityResolver(new ExternalResolver());
        Document document = null;
        try {
            document = reader.read(is);
        } catch (DocumentException e) {
            log.warn("Could not open document " + programFile + "; ", e);
            return false;
        }

        //Node startTimeNode = document.selectSingleNode("//meta[@name='StartTime']");
        Node startTimeNode = document.selectSingleNode("//*[name()='meta'][@name='StartTime']");
        long startTime;
        try {
            startTime = Long.parseLong(startTimeNode.valueOf("@content"));
        } catch (NumberFormatException e) {
            log.warn("Error parsing StartTime " + startTimeNode + "; ", e);
            return false;
        }
        //Node programNode = document.selectSingleNode("//meta[@name='ProgramID']");
        Node programNode = document.selectSingleNode("//*[name()='meta'][@name='ProgramID']");
        String programId = programNode.valueOf("@content");
        programId = updateProgramId(programId);
        //Node endTimeNode = document.selectSingleNode("//meta[@name='EndTime']");
        Node endTimeNode = document.selectSingleNode("//*[name()='meta'][@name='EndTime']");
        long endTime;
        try {
            endTime = Long.parseLong(endTimeNode.valueOf("@content"));
        } catch (NumberFormatException e) {
            log.warn("Error parsing endTime " + endTimeNode + "; ", e);
            return false;
        }

        //List divs = document.selectNodes("/html/body/div");
        List divs = document.selectNodes("/*[name()='html']/*[name()='body']/*[name()='div']");

        while (divs.size() > 0) {
            Element div = (Element) divs.remove(0);
            List children = div.selectNodes("child::node()");
            while (children.size() > 0) {
                Node a = (Node) children.remove(0);
                while (!("a".equals(a.getName()))) {
                    if (children.size() == 0) {
                        break;
                    }
                    a = (Node) children.remove(0);
                }
                if (!("a".equals(a.getName()))) {
                    break;
                }

                Node afterA = (Node) children.remove(0);
                if (afterA instanceof Element) {
                    if (!("span".equals(afterA.getName()))) {
                        throw new IOException("span expected... bad data in " + programFile);
                    }
                    //Don't include this in the captions or should we?
                    //Element span = (Element)afterA;
                    //captions.append(' ');
                    //captions.append(span.getText().replace("&gt;&gt;", "").trim());
                    afterA = (Node) children.remove(0);
                }

                StringBuilder sentence = new StringBuilder();
                if (afterA instanceof Text) {
                    Text sentenceNode = (Text) afterA;
                    sentence.append(sentenceNode.getText());
                } else {
                    Entity entity = (Entity) afterA;
                    sentence.append(entity.asXML());
                }
                /*
                while (children.get(0) instanceof Text) {
                   Text moreText = (Text)children.remove(0);
                   captions.append(' ');
                   captions.append(DocumentUtil.prettySentence(moreText.getText()));
                }
                */
                while (children.get(0) instanceof Text || children.get(0) instanceof Entity) {
                    if (children.get(0) instanceof Text) {
                        Text moreText = (Text) children.remove(0);
                        sentence.append(moreText.getText());
                    } else {
                        Entity entity = (Entity) children.remove(0);
                        sentence.append(entity.asXML());
                    }
                }
                captions.append(DocumentUtil.prettySentence(sentence.toString().trim()));
                captions.append(' ');
            }
        }
        ArrayList<ScheduledProgram> skedulePrograms = new ArrayList<ScheduledProgram>();
        long lookupTimeStart = System.currentTimeMillis();
        for (String lineupId : networkLineups) {
            log.debug("looking for future scheduled program: " + programId + "  on lineup " + lineupId);
            ScheduledProgram skedProg = epg.getNextShowing(lineupId, programId, false, true);
            if (skedProg == null) {
                log.debug("looking for past scheduled program: " + programId + "  on lineup " + lineupId);
                skedProg = epg.getLastShowing(lineupId, programId);
            }
            log.debug("Sked prog for program: " + programId + " is null " + (skedProg == null));
            //We Can we fake a scheduled program?
            //Program program = epg.getProgram(programId);
            if (skedProg == null) {
                log.debug("Unable to locate ScheduleProgram for " + programId);
                Program program = epg.getProgram(programId);
                if (program != null) {
                    skedProg = new ScheduledProgram();
                    skedProg.setNetwork(network);
                    skedProg.setDescription(program.getDescription());
                    skedProg.setDescriptionWithActors(program.getDescriptionWithActors());
                    skedProg.setEndTime(new Date(endTime));
                    skedProg.setStartTime(new Date(startTime));
                    skedProg.setCredits(program.getCredits());
                    skedProg.setGenreDescription(program.getGenreDescription());
                    skedProg.setProgramId(program.getProgramId());
                    skedProg.setProgramTitle(program.getProgramTitle());
                    skedProg.setEpisodeTitle(program.getEpisodeTitle());
                    skedProg.setLastModified(program.getLastModified());
                    skedProg.setOriginalAirDate(program.getOriginalAirDate());
                    skedProg.setRunTime(program.getRunTime());
                    skedProg.setScheduleId(0);
                    skedProg.setTvRating(program.getTvRating());
                    skedProg.setNewEpisode(false);
                    skedProg.setLineupId(lineupId);
                }
            }
            if (skedProg != null) {
                skedulePrograms.add(skedProg);
                if (indexWriter == null) { // probably only doing composite index, so one is all we need
                    break;
                }
            }
        }
        lookupTime += (System.currentTimeMillis() - lookupTimeStart);
        if (captions.length() > 250 && skedulePrograms.size() > 0) {
            //Delete any old duplicates
            Term term = new Term("programID", skedulePrograms.get(0).getProgramId());
            if (indexWriter != null) {
                indexWriter.deleteDocuments(term);
                //Now insert the new document.
                org.apache.lucene.document.Document doc = new org.apache.lucene.document.Document();
                DocumentUtil.addCaptions(doc, captions.toString());
                DocumentUtil.populateDocument(doc, skedulePrograms, new Date());
                indexWriter.addDocument(doc);
            }

            if (compositeIndexWriter != null) {
                compositeIndexWriter.deleteDocuments(term);
                org.apache.lucene.document.Document compositeDoc = new org.apache.lucene.document.Document();
                DocumentUtil.populateCompositeDocument(compositeDoc,
                        captions.toString().replaceAll("[.!?]* ", " "), skedulePrograms);
                compositeIndexWriter.addDocument(compositeDoc);
            }

            log.debug("Adding to index now:" + skedulePrograms.get(0).getProgramId() + " "
                    + skedulePrograms.get(0).getProgramTitle());
            return true;
        } else {
            log.debug("Limited CC data(" + captions.length()
                    + " character) or unable to locate EPG date for the program. Not adding this program to the index:"
                    + programId);
            return false;
        }
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                log.error("Error closing file", e);
            }
        }
        if (needToClose) {
            closeIndex();
        }
    }
}

From source file:com.appeligo.channelfeed.work.FileReaderThread.java

License:Apache License

public void run() {

    try {//www.  ja v  a  2 s  . c o  m
        SAXReader reader = new SAXReader();
        Document document;
        try {
            document = reader.read(new File(ccDocumentRoot + captionFilename));
        } catch (DocumentException e) {
            log.error("Could not open document " + ccDocumentRoot + captionFilename + "; ", e);
            return;
        }

        do {
            //Node startTimeNode = document.selectSingleNode("//meta[@name='StartTime']");
            Node startTimeNode = document.selectSingleNode("//*[name()='meta'][@name='StartTime']");
            long startTime;
            try {
                startTime = Long.parseLong(startTimeNode.valueOf("@content"));
            } catch (NumberFormatException e) {
                throw new Error(e);
            }

            //Node endTimeNode = document.selectSingleNode("//meta[@name='EndTime']");
            Node endTimeNode = document.selectSingleNode("//*[name()='meta'][@name='EndTime']");
            long endTime;
            try {
                endTime = Long.parseLong(endTimeNode.valueOf("@content"));
            } catch (NumberFormatException e) {
                throw new Error(e);
            }

            long durationMillis = endTime - startTime;

            if (autoAdvance) {
                long durationSeconds = durationMillis / 1000;
                Calendar midnight = Calendar.getInstance();
                midnight.setTime(new Date());
                midnight.setTimeZone(TimeZone.getTimeZone("GMT"));
                int year = midnight.get(Calendar.YEAR);
                int month = midnight.get(Calendar.MONTH);
                int dayOfMonth = midnight.get(Calendar.DAY_OF_MONTH);
                midnight.clear();
                midnight.set(year, month, dayOfMonth);
                long midnightMillis = midnight.getTimeInMillis();
                long secondsSinceMidnight = (System.currentTimeMillis() - midnightMillis) / 1000;
                //int loopsSinceMidnight = (int)(secondsSinceMidnight / durationSeconds);
                advanceSeconds = (int) (secondsSinceMidnight % durationSeconds);
            }

            long newStartTime = System.currentTimeMillis() - (advanceSeconds * 1000);
            long newEndTime = newStartTime + durationMillis;

            setProgram(newStartTime).setStartTime(new Date(newStartTime));

            //            List divs = document.selectNodes("/html/body/div");
            List divs = document.selectNodes("/*[name()='html']/*[name()='body']/*[name()='div']");

            while ((divs.size() > 0) && (!aborted)) {
                Element div = (Element) divs.remove(0);
                List children = div.selectNodes("child::node()");
                while ((children.size() > 0) && (!aborted)) {
                    Node a = (Node) children.remove(0);
                    while (!("a".equals(a.getName()))) {
                        if (children.size() == 0) {
                            break;
                        }
                        a = (Node) children.remove(0);
                    }
                    if (!("a".equals(a.getName()))) {
                        break;
                    }
                    long timestamp;
                    try {
                        timestamp = Long.parseLong(a.valueOf("@name"));
                    } catch (NumberFormatException e) {
                        throw new Error(e);
                    }
                    long offset = timestamp - startTime;
                    long delayUntil = newStartTime + offset;
                    log.debug("Next sentence in " + ((delayUntil - System.currentTimeMillis()) / 1000)
                            + " seconds");
                    while (System.currentTimeMillis() < delayUntil) {
                        try {
                            Thread.sleep(delayUntil - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                        }
                    }

                    String speakerChange = null;
                    Node afterA = (Node) children.remove(0);
                    if (afterA instanceof Element) {
                        if (!("span".equals(afterA.getName()))) {
                            throw new Error("span expected");
                        }
                        Element span = (Element) afterA;
                        speakerChange = span.getText().replace("&gt;&gt;", "").trim();
                        afterA = (Node) children.remove(0);
                    }

                    String sentence;
                    if (afterA instanceof Text) {
                        Text sentenceNode = (Text) afterA;
                        sentence = sentenceNode.getText();
                    } else {
                        Entity entity = (Entity) afterA;
                        sentence = entity.asXML();
                    }
                    while (children.get(0) instanceof Text || children.get(0) instanceof Entity) {
                        if (children.get(0) instanceof Text) {
                            Text moreText = (Text) children.remove(0);
                            sentence += moreText.getText();
                        } else {
                            Entity entity = (Entity) children.remove(0);
                            sentence += entity.asXML();
                        }
                    }
                    sentence = sentence.trim();

                    /*
                    if (!docOpened) {
                       openDoc(newStartTime - SCHEDULE_VARIANCE);
                    }
                    */
                    //if (program != null) {
                    getDestinations().writeSentence(getProgram(), delayUntil, speakerChange, sentence);
                    //}
                }
            }

            if (loop) {
                autoAdvance = false;
                advanceSeconds = 0;
                log.debug("Waiting for end of program in " + ((newEndTime - System.currentTimeMillis()) / 1000)
                        + " seconds");
                while (System.currentTimeMillis() < newEndTime) {
                    try {
                        Thread.sleep(newEndTime - System.currentTimeMillis());
                    } catch (InterruptedException e) {
                    }
                }
            }
        } while (loop);
    } catch (Exception e) {
        log.error("Uncaught exception!", e);
    }
}

From source file:com.beetle.framework.web.cache.imp.CacheConfig.java

License:Apache License

public synchronized void readCacheURLs(InputStream xmlIs) {
    url_cacheAttr.clear();/* w  ww. ja va 2s.  c o m*/
    if (xmlIs == null) {
        return;
    }
    SAXReader reader = new SAXReader();
    Document doc = null;
    try {
        doc = reader.read(xmlIs);
        Node node = doc.selectSingleNode(convertPath("mappings.caches"));
        if (node != null) {
            config.setDiskStorePath(node.valueOf("@diskStorePath"));
            config.setMaxElementsInMemory(toInt(node.valueOf("@maxElementsInMemory")));
            config.setMemoryStoreEvictionPolicy(node.valueOf("memoryStoreEvictionPolicy"));
            Iterator<?> it = node.selectNodes("cItem").iterator();
            while (it.hasNext()) {
                CacheAttr attr = new CacheAttr();
                Element e = (Element) it.next();
                attr.setUrl(e.valueOf("@name"));
                attr.setScope(e.valueOf("@scope"));
                attr.setTime(toInt(e.valueOf("@time")));
                url_cacheAttr.put(attr.getUrl(), attr);
            }
        }
    } catch (Exception de) {
        de.printStackTrace();
    } finally {
        if (doc != null) {
            doc.clearContent();
        }
        reader = null;
    }
}

From source file:com.btmatthews.maven.plugins.ldap.dsml.DSMLFormatReader.java

License:Apache License

/**
 * Read the next change record from the underlying input stream.
 *
 * @return The next change record or {@code null} if the end of the input stream has been reached.
 *///ww w  . j av  a2 s. co m
@Override
public LDIFChangeRecord nextRecord() {
    if (entryIterator.hasNext()) {
        try {
            final Node entryNode = entryIterator.next();
            final String dn = entryNode.valueOf("@dn");
            final List<Attribute> attributes = new ArrayList<Attribute>();

            final List<Node> objectClassList = (List<Node>) objectClassXPath.selectNodes(entryNode);
            final String[] objectClasses = new String[objectClassList.size()];
            for (int j = 0; j < objectClasses.length; ++j) {
                objectClasses[j] = objectClassList.get(j).getStringValue();
            }
            attributes.add(new Attribute("objectclass", objectClasses));
            for (final Node attributeNode : (List<Node>) attrXPath.selectNodes(entryNode)) {
                final String attributeName = attributeNode.valueOf("@name");
                final List<Node> attributeValueNodes = (List<Node>) attrValueXPath.selectNodes(attributeNode);
                switch (attributeValueNodes.size()) {
                case 0:
                    break;
                case 1: {
                    final String attributeValue = attributeValueNodes.get(0).getStringValue();
                    attributes.add(new Attribute(attributeName, attributeValue));
                    break;
                }
                default: {
                    final String[] attributeValues = new String[attributeValueNodes.size()];
                    for (int j = 0; j < attributeValueNodes.size(); ++j) {
                        attributeValues[j] = attributeValueNodes.get(j).getStringValue();
                    }
                    attributes.add(new Attribute(attributeName, attributeValues));
                    break;
                }
                }
            }
            return new LDIFAddChangeRecord(dn, attributes);
        } catch (final JaxenException e) {
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.genericworkflownodes.knime.config.impl.DOMHelper.java

License:Open Source License

public static String valueOf(Node n, String query) throws Exception {
    String val = n.valueOf(query);
    if (val == null) {
        throw new Exception("XPath query yielded null result");
    }//from   w w w .j a va 2 s .c o m
    return val;
}

From source file:com.genericworkflownodes.knime.config.impl.GalaxyNodeConfigurationReader.java

License:Open Source License

private void processParameter(Node n) throws Exception {
    Parameter<?> ret = null;
    String type = n.valueOf("@type");
    if (type.equals("")) {
        throw new Exception("type information for parameter not set");
    }//from   ww  w  .  j  a v  a  2  s .  c o  m

    String key = n.valueOf("@name");
    String val = n.valueOf("@value");

    System.out.println("processing param " + key + " type:" + type + " value: " + val);

    if (type.equals("integer")) {
        ret = new IntegerParameter(key, val);
    }
    if (type.equals("float")) {
        ret = new DoubleParameter(key, val);
    }
    if (type.equals("boolean")) {
        ret = new BoolParameter(key, val);
    }
    if (type.equals("text")) {
        ret = new StringParameter(key, val);
    }
    if (type.equals("select")) {
        List<Node> options = DOMHelper.selectNodes(n, "option");
        List<String> opts = new ArrayList<String>();
        List<String> labs = new ArrayList<String>();
        for (Node option : options) {
            String optval = option.valueOf("@value");
            String label = option.valueOf("text()");
            opts.add(optval);
            labs.add(label);
        }
        ret = new StringChoiceParameter(key, opts, labs);
        ((StringChoiceParameter) ret).setValue(val);
        ret.setIsOptional(false);
    }
    String descr = n.valueOf("label/text()");

    if (ret != null) {
        ret.setKey(key);
        ret.setDescription(descr);
    }

    config.addParameter(key, ret);
}

From source file:com.genericworkflownodes.knime.config.impl.GalaxyNodeConfigurationReader.java

License:Open Source License

private Port readInPort(Node portnode) throws Exception {
    Port port = new Port();

    port.setOptional(true);//from   ww  w .j  a  va 2  s . c o  m

    Node n = DOMHelper.selectSingleNode(portnode, "label");

    String portdescr = n.valueOf("text()");
    port.setDescription(portdescr);

    String extension = DOMHelper.valueOf(portnode, "@format");
    port.addMimeType(extension);

    String portname = DOMHelper.valueOf(portnode, "@name");
    port.setName(portname);

    String optional = DOMHelper.valueOf(portnode, "@optional");
    if (optional.equals("false")) {
        port.setOptional(false);
    }

    return port;
}