Search in sources :

Example 46 with XPath

use of javax.xml.xpath.XPath in project lucene-solr by apache.

the class IndexSchema method readSchema.

protected void readSchema(InputSource is) {
    try {
        // pass the config resource loader to avoid building an empty one for no reason:
        // in the current case though, the stream is valid so we wont load the resource by name
        Config schemaConf = new Config(loader, SCHEMA, is, SLASH + SCHEMA + SLASH);
        Document document = schemaConf.getDocument();
        final XPath xpath = schemaConf.getXPath();
        String expression = stepsToPath(SCHEMA, AT + NAME);
        Node nd = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        String coreName = getCoreName("null");
        StringBuilder sb = new StringBuilder();
        // Another case where the initialization from the test harness is different than the "real world"
        sb.append("[");
        sb.append(coreName);
        sb.append("] ");
        if (nd == null) {
            sb.append("schema has no name!");
            log.warn(sb.toString());
        } else {
            name = nd.getNodeValue();
            sb.append("Schema ");
            sb.append(NAME);
            sb.append("=");
            sb.append(name);
            log.info(sb.toString());
        }
        //                      /schema/@version
        expression = stepsToPath(SCHEMA, AT + VERSION);
        version = schemaConf.getFloat(expression, 1.0f);
        // load the Field Types
        final FieldTypePluginLoader typeLoader = new FieldTypePluginLoader(this, fieldTypes, schemaAware);
        expression = getFieldTypeXPathExpressions();
        NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
        typeLoader.load(loader, nodes);
        // load the fields
        Map<String, Boolean> explicitRequiredProp = loadFields(document, xpath);
        //   /schema/similarity
        expression = stepsToPath(SCHEMA, SIMILARITY);
        Node node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        similarityFactory = readSimilarity(loader, node);
        if (similarityFactory == null) {
            final boolean modernSim = getDefaultLuceneMatchVersion().onOrAfter(Version.LUCENE_6_0_0);
            final Class simClass = modernSim ? SchemaSimilarityFactory.class : ClassicSimilarityFactory.class;
            // use the loader to ensure proper SolrCoreAware handling
            similarityFactory = loader.newInstance(simClass.getName(), SimilarityFactory.class);
            similarityFactory.init(new ModifiableSolrParams());
        } else {
            isExplicitSimilarity = true;
        }
        if (!(similarityFactory instanceof SolrCoreAware)) {
            // then we are responsible for erroring if a field type is trying to specify a sim.
            for (FieldType ft : fieldTypes.values()) {
                if (null != ft.getSimilarity()) {
                    String msg = "FieldType '" + ft.getTypeName() + "' is configured with a similarity, but the global similarity does not support it: " + similarityFactory.getClass();
                    log.error(msg);
                    throw new SolrException(ErrorCode.SERVER_ERROR, msg);
                }
            }
        }
        //                      /schema/defaultSearchField/text()
        expression = stepsToPath(SCHEMA, "defaultSearchField", TEXT_FUNCTION);
        node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        if (node != null) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Setting defaultSearchField in schema not supported since Solr 7");
        }
        //                      /schema/solrQueryParser/@defaultOperator
        expression = stepsToPath(SCHEMA, "solrQueryParser", AT + "defaultOperator");
        node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        if (node != null) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Setting default operator in schema (solrQueryParser/@defaultOperator) not supported");
        }
        //                      /schema/uniqueKey/text()
        expression = stepsToPath(SCHEMA, UNIQUE_KEY, TEXT_FUNCTION);
        node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        if (node == null) {
            log.warn("no " + UNIQUE_KEY + " specified in schema.");
        } else {
            uniqueKeyField = getIndexedField(node.getNodeValue().trim());
            if (null != uniqueKeyField.getDefaultValue()) {
                String msg = UNIQUE_KEY + " field (" + uniqueKeyFieldName + ") can not be configured with a default value (" + uniqueKeyField.getDefaultValue() + ")";
                log.error(msg);
                throw new SolrException(ErrorCode.SERVER_ERROR, msg);
            }
            if (!uniqueKeyField.stored()) {
                log.warn(UNIQUE_KEY + " is not stored - distributed search and MoreLikeThis will not work");
            }
            if (uniqueKeyField.multiValued()) {
                String msg = UNIQUE_KEY + " field (" + uniqueKeyFieldName + ") can not be configured to be multivalued";
                log.error(msg);
                throw new SolrException(ErrorCode.SERVER_ERROR, msg);
            }
            uniqueKeyFieldName = uniqueKeyField.getName();
            uniqueKeyFieldType = uniqueKeyField.getType();
            // Unless the uniqueKeyField is marked 'required=false' then make sure it exists
            if (Boolean.FALSE != explicitRequiredProp.get(uniqueKeyFieldName)) {
                uniqueKeyField.required = true;
                requiredFields.add(uniqueKeyField);
            }
        }
        /////////////// parse out copyField commands ///////////////
        // Map<String,ArrayList<SchemaField>> cfields = new HashMap<String,ArrayList<SchemaField>>();
        // expression = "/schema/copyField";
        dynamicCopyFields = new DynamicCopy[] {};
        loadCopyFields(document, xpath);
        postReadInform();
    } catch (SolrException e) {
        throw new SolrException(ErrorCode.getErrorCode(e.code()), "Can't load schema " + loader.resourceLocation(resourceName) + ": " + e.getMessage(), e);
    } catch (Exception e) {
        // unexpected exception...
        throw new SolrException(ErrorCode.SERVER_ERROR, "Can't load schema " + loader.resourceLocation(resourceName) + ": " + e.getMessage(), e);
    }
    // create the field analyzers
    refreshAnalyzers();
    log.info("Loaded schema {}/{} with uniqueid field {}", name, version, uniqueKeyFieldName);
}
Also used : XPath(javax.xml.xpath.XPath) SolrConfig(org.apache.solr.core.SolrConfig) Config(org.apache.solr.core.Config) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) SchemaSimilarityFactory(org.apache.solr.search.similarities.SchemaSimilarityFactory) ClassicSimilarityFactory(org.apache.solr.search.similarities.ClassicSimilarityFactory) Document(org.w3c.dom.Document) ModifiableSolrParams(org.apache.solr.common.params.ModifiableSolrParams) XPathExpressionException(javax.xml.xpath.XPathExpressionException) SolrException(org.apache.solr.common.SolrException) IOException(java.io.IOException) SolrCoreAware(org.apache.solr.util.plugin.SolrCoreAware) SolrException(org.apache.solr.common.SolrException)

Example 47 with XPath

use of javax.xml.xpath.XPath in project lucene-solr by apache.

the class BaseTestHarness method getXpath.

public static XPath getXpath() {
    try {
        XPath xpath = xpathTL.get();
        if (xpath == null) {
            xpath = XPathFactory.newInstance().newXPath();
            xpathTL.set(xpath);
        }
        return xpath;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpressionException(javax.xml.xpath.XPathExpressionException) IOException(java.io.IOException) SolrException(org.apache.solr.common.SolrException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 48 with XPath

use of javax.xml.xpath.XPath in project geode by apache.

the class XmlUtils method query.

public static NodeList query(Node node, String searchString, XPathContext xpathcontext) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(xpathcontext);
    return (NodeList) xpath.evaluate(searchString, node, XPathConstants.NODESET);
}
Also used : XPath(javax.xml.xpath.XPath) NodeList(org.w3c.dom.NodeList)

Example 49 with XPath

use of javax.xml.xpath.XPath in project robovm by robovm.

the class JaxenXPathTestSuite method contextToTestSuite.

/**
     * Populates the test suite with tests from the given XML context element.
     */
private static void contextToTestSuite(TestSuite suite, String url, InputSource inputSource, Element element) {
    /*
         * Each context element has this structure:
         *
         * <context select="...">
         *   <test .../>
         *   <test .../>
         *   <test .../>
         *   <valueOf .../>
         *   <valueOf .../>
         *   <valueOf .../>
         * </context>
         */
    String select = element.getAttribute("select");
    Context context = new Context(inputSource, url, select);
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setXPathVariableResolver(new ElementVariableResolver(element));
    for (Element test : elementsOf(element.getChildNodes())) {
        if (test.getTagName().equals("test")) {
            suite.addTest(createFromTest(xpath, context, test));
        } else if (test.getTagName().equals("valueOf")) {
            suite.addTest(createFromValueOf(xpath, context, test));
        } else {
            throw new UnsupportedOperationException("Unsupported test: " + context);
        }
    }
}
Also used : XPath(javax.xml.xpath.XPath) Element(org.w3c.dom.Element)

Example 50 with XPath

use of javax.xml.xpath.XPath in project languagetool by languagetool-org.

the class AtDEvaluator method getRuleMatches.

private List<RuleMatch> getRuleMatches(String resultXml, AnnotatedText text) throws XPathExpressionException {
    List<RuleMatch> matches = new ArrayList<>();
    Document document = getDocument(resultXml);
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList errors = (NodeList) xPath.evaluate("//error", document, XPathConstants.NODESET);
    for (int i = 0; i < errors.getLength(); i++) {
        Node error = errors.item(i);
        String string = xPath.evaluate("string", error);
        String description = xPath.evaluate("description", error);
        String preContext = xPath.evaluate("precontext", error);
        String errorText = preContext + " " + string;
        int fromPos = text.getPlainText().indexOf(errorText) + preContext.length() + 1;
        int toPos = fromPos + string.length();
        NodeList suggestions = (NodeList) xPath.evaluate("suggestions", error, XPathConstants.NODESET);
        RuleMatch ruleMatch = new RuleMatch(new AtdRule(), text.getOriginalTextPositionFor(fromPos), text.getOriginalTextPositionFor(toPos), description);
        for (int j = 0; j < suggestions.getLength(); j++) {
            Node option = suggestions.item(j);
            String optionStr = xPath.evaluate("option", option);
            ruleMatch.setSuggestedReplacement(optionStr);
        }
        matches.add(ruleMatch);
    }
    return matches;
}
Also used : XPath(javax.xml.xpath.XPath) RuleMatch(org.languagetool.rules.RuleMatch) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document)

Aggregations

XPath (javax.xml.xpath.XPath)526 Document (org.w3c.dom.Document)254 NodeList (org.w3c.dom.NodeList)230 XPathFactory (javax.xml.xpath.XPathFactory)215 Node (org.w3c.dom.Node)171 XPathExpressionException (javax.xml.xpath.XPathExpressionException)159 XPathExpression (javax.xml.xpath.XPathExpression)142 DocumentBuilder (javax.xml.parsers.DocumentBuilder)125 Element (org.w3c.dom.Element)118 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)97 IOException (java.io.IOException)89 Test (org.junit.Test)80 InputSource (org.xml.sax.InputSource)59 File (java.io.File)57 SAXException (org.xml.sax.SAXException)57 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)51 ByteArrayInputStream (java.io.ByteArrayInputStream)44 ArrayList (java.util.ArrayList)44 InputStream (java.io.InputStream)39 DSNamespaceContext (org.apache.xml.security.test.dom.DSNamespaceContext)37