Example usage for org.dom4j.io SAXReader SAXReader

List of usage examples for org.dom4j.io SAXReader SAXReader

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader SAXReader.

Prototype

public SAXReader() 

Source Link

Usage

From source file:com.mnt.base.mail.MailHelper.java

License:Open Source License

private static String[] loadMailTemplate(String templateName) {

    String[] titleContents = new String[2];

    InputStream in = BaseConfiguration.getRelativeFileStream("mail.template.xml");

    if (in != null) {
        try {//from  www .j  av  a 2s  .c o  m
            SAXReader reader = new SAXReader();
            Document document = reader.read(in);
            Element rootElt = document.getRootElement(); // 

            Element mailInfo = (Element) rootElt
                    .selectSingleNode("//templates/mail[@id='" + templateName + "']");

            if (mailInfo != null) {
                titleContents[0] = mailInfo.element("title").getText();
                titleContents[1] = mailInfo.element("content").getText();
            }
        } catch (Exception e) {
            log.error("fail to load the mail template: " + templateName, e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                log.error("fail to close the mail template file: " + templateName, e);
            }
        }
    } else {
        log.error("no corresponding mail template file be found: " + templateName);
    }

    return titleContents;
}

From source file:com.mor.blogengine.xml.io.XmlDataSourceProvider.java

License:Open Source License

/**
 * Setup validation features for given reader
 *
 * @param pReader given reader/* ww w  . j  a va 2 s  .  co m*/
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 * @param schemaSource
 * @return
 */
private SAXReader createReaderAgainstSchema(URL schemaSource) throws SAXException, ParserConfigurationException,
        IOException, MissingPropertyException, IncorrectPropertyValueException {

    trace("Parser created OK");
    SAXReader reader = new SAXReader();
    trace("reader created OK");
    trace("set reader properties");
    // set the validation feature to true to report validation errors
    reader.setFeature("http://xml.org/sax/features/validation", true);
    // set the validation/schema feature to true to report validation errors against a schema
    reader.setFeature("http://apache.org/xml/features/validation/schema", true);
    //set the validation/schema-full-checking feature to true to enable full schema, grammar-constraint checking
    reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    trace("returning reader...");
    return reader;

}

From source file:com.mothsoft.alexis.engine.numeric.President2012DataSetImporter.java

License:Apache License

@SuppressWarnings("unchecked")
private Map<Date, PollResults> getPage(final String after, final int pageNumber) {
    final Map<Date, PollResults> pageMap = new LinkedHashMap<Date, PollResults>();

    HttpClientResponse httpResponse = null;

    try {/* w w w. j a va  2  s .c o m*/
        final URL url = new URL(String.format(BASE_URL, after, pageNumber));
        httpResponse = NetworkingUtil.get(url, null, null);

        final SAXReader saxReader = new SAXReader();

        org.dom4j.Document document;
        try {
            document = saxReader.read(httpResponse.getInputStream());
        } catch (DocumentException e) {
            throw new IOException(e);
        } finally {
            httpResponse.close();
        }

        final SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);

        final List<Node> questions = document.selectNodes(XPATH_QUESTIONS);
        for (final Node question : questions) {
            final Date endDate;
            final Node poll = question.selectSingleNode(ANCESTOR_POLL);
            final Node endDateNode = poll.selectSingleNode(END_DATE);
            try {
                endDate = format.parse(endDateNode.getText());
                logger.debug(String.format("%s: %s", END_DATE, format.format(endDate)));
            } catch (final ParseException e) {
                throw new RuntimeException(e);
            }

            final List<Node> responses = question.selectNodes(XPATH_RESPONSE_FROM_QUESTION);
            for (final Node response : responses) {
                final Node choiceNode = response.selectSingleNode(CHOICE);
                final String choice = choiceNode.getText();

                if (President2012DataSetImporter.CANDIDATE_OPTIONS.contains(choice)) {
                    final Node valueNode = response.selectSingleNode(VALUE);
                    final Double value = Double.valueOf(valueNode.getText());
                    append(pageMap, endDate, choice, value);
                }
            }
        }

        httpResponse.close();
        httpResponse = null;

    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (httpResponse != null) {
            httpResponse.close();
        }
    }

    return pageMap;
}

From source file:com.mothsoft.alexis.engine.textual.ParseResponseMessageListener.java

License:Apache License

@SuppressWarnings("unchecked")
private ParsedContent readResponse(final String xml) throws IOException {
    // turn the content into a ParsedContent complex object
    final Map<Term, Integer> termCountMap = new HashMap<Term, Integer>();
    final Map<String, DocumentAssociation> associationCountMap = new HashMap<String, DocumentAssociation>();
    final List<DocumentNamedEntity> entities = new ArrayList<DocumentNamedEntity>();

    final List<Node> sentenceNodes = new ArrayList<Node>();

    final SAXReader saxReader = new SAXReader();

    org.dom4j.Document document;/*  w w  w.  ja v  a2s . c o m*/
    try {
        document = saxReader.read(new StringReader(xml));
    } catch (DocumentException e) {
        throw new IOException(e);
    }

    sentenceNodes.addAll(document.selectNodes("/document/sentences/s"));

    int sentencePosition = 1;

    for (final Node ith : sentenceNodes) {
        parseSentence(sentencePosition++, (Element) ith, termCountMap, associationCountMap);
    }
    sentenceNodes.clear();

    final List<Node> nameNodes = new ArrayList<Node>();
    nameNodes.addAll(document.selectNodes("/document/names/name"));
    for (final Node node : nameNodes) {
        final Element element = (Element) node;
        final String countString = element.attributeValue("count");
        final Integer count = (countString == null ? 0 : Integer.valueOf(countString));
        final String name = element.getTextTrim();
        entities.add(new DocumentNamedEntity(name, count));
    }

    // count up all the terms in the document
    Integer documentTermCount = 0;
    for (final Term ith : termCountMap.keySet()) {
        documentTermCount += (termCountMap.get(ith));
    }

    // individual term count
    final List<DocumentTerm> documentTerms = new ArrayList<DocumentTerm>();
    for (final Term term : termCountMap.keySet()) {
        final Integer count = termCountMap.get(term);
        documentTerms.add(new DocumentTerm(term, count));
    }

    // sort the named entities by count
    Collections.sort(entities, new Comparator<DocumentNamedEntity>() {
        @Override
        public int compare(final DocumentNamedEntity e1, DocumentNamedEntity e2) {
            return -1 * e1.getCount().compareTo(e2.getCount());
        }
    });

    return new ParsedContent(associationCountMap.values(), documentTerms, entities, documentTermCount);
}

From source file:com.mpaike.core.config.xml.XMLConfigService.java

License:Open Source License

protected void parse(InputStream stream) {
    Map<String, ConfigElementReader> parsedElementReaders = null;
    Map<String, Evaluator> parsedEvaluators = null;
    List<ConfigSection> parsedConfigSections = new ArrayList<ConfigSection>();

    String currentArea = null;/*from www .  j ava  2s.  co m*/
    try {
        // get the root element
        SAXReader reader = new SAXReader();
        Document document = reader.read(stream);
        Element rootElement = document.getRootElement();

        // see if there is an area defined
        currentArea = rootElement.attributeValue("area");

        // parse the plug-ins section of a config file
        Element pluginsElement = rootElement.element(ELEMENT_PLUG_INS);
        if (pluginsElement != null) {
            // parse the evaluators section
            parsedEvaluators = parseEvaluatorsElement(pluginsElement.element(ELEMENT_EVALUATORS));

            // parse the element readers section
            parsedElementReaders = parseElementReadersElement(pluginsElement.element(ELEMENT_ELEMENT_READERS));
        }

        // parse each config section in turn
        @SuppressWarnings("unchecked")
        Iterator<Element> configElements = rootElement.elementIterator(ELEMENT_CONFIG);
        while (configElements.hasNext()) {
            Element configElement = configElements.next();
            parsedConfigSections.add(parseConfigElement(parsedElementReaders, configElement, currentArea));
        }
    } catch (Throwable e) {
        if (e instanceof ConfigException) {
            throw (ConfigException) e;
        } else {
            throw new ConfigException("Failed to parse config stream", e);
        }
    }

    try {
        // valid for this stream, now add to config service ...

        if (parsedEvaluators != null) {
            for (Map.Entry<String, Evaluator> entry : parsedEvaluators.entrySet()) {
                // add the evaluators to the config service
                addEvaluator(entry.getKey(), entry.getValue());
            }
        }

        if (parsedElementReaders != null) {
            for (Map.Entry<String, ConfigElementReader> entry : parsedElementReaders.entrySet()) {
                // add the element readers to the config service
                addConfigElementReader(entry.getKey(), entry.getValue());
            }
        }

        if (parsedConfigSections != null) {
            for (ConfigSection section : parsedConfigSections) {
                // add the config sections to the config service
                addConfigSection(section, currentArea);
            }
        }
    } catch (Throwable e) {
        throw new ConfigException("Failed to add config to config service", e);
    }
}

From source file:com.ms.commons.test.datareader.impl.TreeXmlReaderUtil.java

License:Open Source License

public static TreeDatabase read(String fileName) {
    String absPath = getAbsolutedPath(fileName);
    File file = new File(absPath);
    if (file.exists()) {
        checkDataFile(absPath);//from  w  w w.  j  a va2  s.c o  m
    }

    TreeDatabase database = new TreeDatabase();
    SAXReader reader = new SAXReader();
    Document doc;
    InputStream inputStream = null;
    try {
        inputStream = new BufferedInputStream(new FileInputStream(file));
        XStream xStream = new XStream();
        doc = reader.read(inputStream);

        initAlias(doc, xStream);

        List<TreeObject> objects = readObjects(doc, xStream);

        database.setTreeObjects(objects);
        inputStream.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        close(inputStream);
    }
    return database;
}

From source file:com.ms.commons.test.datareader.impl.XmlReaderUtil.java

License:Open Source License

@SuppressWarnings("unchecked")
public static MemoryDatabase readDocument(String file) {
    try {// w ww  .j  a va 2s  .c  o  m
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new BufferedInputStream(new FileInputStream(getAbsolutedPath(file))));
        List<Element> elements = doc.getRootElement().elements("table");
        List<MemoryTable> tableList = new ArrayList<MemoryTable>();
        for (Element tableE : elements) {
            tableList.add(readTable(tableE));
        }

        MemoryDatabase database = new MemoryDatabase();
        database.setTableList(tableList);
        return database;
    } catch (FileNotFoundException e) {
        throw new ResourceNotFoundException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.msg.wmTestHelper.util.XmlUtil.java

License:Apache License

/**
 * Parse an XML file via dom4j. Can throw a runtime exception.
 *
 * @param xmlFile the xml file.//ww w  .j a v a  2 s .co m
 * @return A dom4j document.
 */
public static Document parse(File xmlFile) {
    try {
        SAXReader reader = new SAXReader();

        return reader.read(xmlFile);
    } catch (DocumentException e) {
        String reason = String.format("Unable to parse file '%s'", xmlFile.getAbsolutePath());
        throw new TestHelperException(reason, e);
    }

}