Example usage for javax.xml.xpath XPathConstants NODE

List of usage examples for javax.xml.xpath XPathConstants NODE

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODE.

Prototype

QName NODE

To view the source code for javax.xml.xpath XPathConstants NODE.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

From source file:org.apache.ode.bpel.rtrep.v2.xquery10.runtime.XQuery10ExpressionRuntime.java

/**
 * Cast XQuery sequence into an opaque list 
 *
 * @param type type //from   w ww. ja v  a 2  s .  c o m
 * @param result result 
 *
 * @return value
 *
 * @throws XQException XQException 
 */
private Object getResultValue(QName type, XQResultSequence result) throws XQException {
    Document document = DOMUtils.newDocument();
    Object resultValue = null;
    if (XPathConstants.NODESET.equals(type)) {
        List list = new ArrayList();

        while (result.next()) {
            Object itemValue = getItemValue(result.getItem());
            if (itemValue instanceof Node) {
                itemValue = DOMUtils.cloneNode(document, (Node) itemValue);
            }

            if (itemValue != null) {
                list.add(itemValue);
            }
        }

        resultValue = list;
    } else if (XPathConstants.NODE.equals(type)) {
        XQItem item = null;
        if (result.count() > 0) {
            result.first();
            if (result.isOnItem()) {
                item = result.getItem();
            }
        }
        if (item != null) {
            resultValue = getItemValue(item);
            if (resultValue instanceof Node) {
                resultValue = DOMUtils.cloneNode(document, (Node) resultValue);
            }
        }
    } else if (XPathConstants.STRING.equals(type)) {
        resultValue = result.getSequenceAsString(new Properties());
    } else if (XPathConstants.NUMBER.equals(type)) {
        resultValue = result.getSequenceAsString(new Properties());
        resultValue = Integer.parseInt((String) resultValue);
    } else if (XPathConstants.BOOLEAN.equals(type)) {
        resultValue = result.getSequenceAsString(new Properties());
        resultValue = Boolean.parseBoolean((String) resultValue);
    }
    return resultValue;
}

From source file:org.apache.oodt.cas.workflow.gui.model.repo.XmlWorkflowModelRepository.java

protected ModelGraph findGraph(List<FileBasedElement> rootElements, String modelIdRef, Metadata staticMetadata,
        ConcurrentHashMap<String, ConfigGroup> globalConfGroups, Set<String> supportedProcessorIds)
        throws XPathExpressionException, WorkflowException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//*[@id = '" + modelIdRef + "']");
    for (FileBasedElement rootElement : rootElements) {
        Node node = (Node) expr.evaluate(rootElement.getElement(), XPathConstants.NODE);
        if (node != null) {
            return this.loadGraph(rootElements, new FileBasedElement(rootElement.getFile(), (Element) node),
                    staticMetadata, globalConfGroups, supportedProcessorIds);
        }//from  ww  w.j a v  a  2  s.  co  m
    }
    return null;
}

From source file:org.apache.openaz.xacml.std.StdRequestAttributes.java

@Override
public Node getContentNodeByXpathExpression(XPathExpression xpathExpression) {
    if (xpathExpression == null) {
        throw new NullPointerException("Null XPathExpression");
    }/* w  ww .  j a v a2s  .c o  m*/
    Node nodeRootThis = this.getContentRoot();
    if (nodeRootThis == null) {
        return null;
    }
    Node matchingNode = null;
    try {
        matchingNode = (Node) xpathExpression.evaluate(nodeRootThis, XPathConstants.NODE);
    } catch (XPathExpressionException ex) {
        this.logger.warn("Failed to retrieve node for \"" + xpathExpression.toString() + "\"", ex);
    }
    return matchingNode;
}

From source file:org.apache.openmeetings.cli.ConnectionPropertiesPatcher.java

private static Attr getConnectionProperties(Document doc) throws Exception {
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath//  w  ww  . j  ava  2 s.  co m
            .compile("/persistence/persistence-unit/properties/property[@name='openjpa.ConnectionProperties']");

    Element element = (Element) expr.evaluate(doc, XPathConstants.NODE);
    return element.getAttributeNode("value");
}

From source file:org.apache.pdfbox.pdmodel.fdf.FDFAnnotation.java

/**
 * Constructor./*from  w  w w .  jav a 2 s .c  om*/
 *
 * @param element An XFDF element.
 *
 * @throws IOException If there is an error extracting data from the element.
 */
public FDFAnnotation(Element element) throws IOException {
    this();

    String page = element.getAttribute("page");
    if (page == null || page.isEmpty()) {
        throw new IOException("Error: missing required attribute 'page'");
    }
    setPage(Integer.parseInt(page));

    String color = element.getAttribute("color");
    if (color != null && color.length() == 7 && color.charAt(0) == '#') {
        int colorValue = Integer.parseInt(color.substring(1, 7), 16);
        setColor(new Color(colorValue));
    }

    setDate(element.getAttribute("date"));

    String flags = element.getAttribute("flags");
    if (flags != null) {
        String[] flagTokens = flags.split(",");
        for (String flagToken : flagTokens) {
            if (flagToken.equals("invisible")) {
                setInvisible(true);
            } else if (flagToken.equals("hidden")) {
                setHidden(true);
            } else if (flagToken.equals("print")) {
                setPrinted(true);
            } else if (flagToken.equals("nozoom")) {
                setNoZoom(true);
            } else if (flagToken.equals("norotate")) {
                setNoRotate(true);
            } else if (flagToken.equals("noview")) {
                setNoView(true);
            } else if (flagToken.equals("readonly")) {
                setReadOnly(true);
            } else if (flagToken.equals("locked")) {
                setLocked(true);
            } else if (flagToken.equals("togglenoview")) {
                setToggleNoView(true);
            }
        }
    }

    setName(element.getAttribute("name"));

    String rect = element.getAttribute("rect");
    if (rect == null) {
        throw new IOException("Error: missing attribute 'rect'");
    }
    String[] rectValues = rect.split(",");
    if (rectValues.length != 4) {
        throw new IOException("Error: wrong amount of numbers in attribute 'rect'");
    }
    float[] values = new float[4];
    for (int i = 0; i < 4; i++) {
        values[i] = Float.parseFloat(rectValues[i]);
    }
    COSArray array = new COSArray();
    array.setFloatArray(values);
    setRectangle(new PDRectangle(array));

    setTitle(element.getAttribute("title"));

    /*
     * Set the markup annotation attributes
     */
    setCreationDate(DateConverter.toCalendar(element.getAttribute("creationdate")));
    String opac = element.getAttribute("opacity");
    if (opac != null && !opac.isEmpty()) {
        setOpacity(Float.parseFloat(opac));
    }
    setSubject(element.getAttribute("subject"));
    setIntent(element.getAttribute("intent"));

    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        setContents(xpath.evaluate("contents[1]", element));
    } catch (XPathExpressionException e) {
        LOG.debug("Error while evaluating XPath expression for richtext contents");
    }

    try {
        Node richContents = (Node) xpath.evaluate("contents-richtext[1]", element, XPathConstants.NODE);
        if (richContents != null) {
            setRichContents(richContentsToString(richContents, true));
            setContents(richContents.getTextContent().trim());
        }
    } catch (XPathExpressionException e) {
        LOG.debug("Error while evaluating XPath expression for richtext contents");
    }

    PDBorderStyleDictionary borderStyle = new PDBorderStyleDictionary();
    String width = element.getAttribute("width");
    if (width != null && !width.isEmpty()) {
        borderStyle.setWidth(Float.parseFloat(width));
    }
    if (borderStyle.getWidth() > 0) {
        String style = element.getAttribute("style");
        if (style != null && !style.isEmpty()) {
            if (style.equals("dash")) {
                borderStyle.setStyle("D");
            } else if (style.equals("bevelled")) {
                borderStyle.setStyle("B");
            } else if (style.equals("inset")) {
                borderStyle.setStyle("I");
            } else if (style.equals("underline")) {
                borderStyle.setStyle("U");
            } else if (style.equals("cloudy")) {
                borderStyle.setStyle("S");
                PDBorderEffectDictionary borderEffect = new PDBorderEffectDictionary();
                borderEffect.setStyle("C");
                String intensity = element.getAttribute("intensity");
                if (intensity != null && !intensity.isEmpty()) {
                    borderEffect.setIntensity(Float.parseFloat(element.getAttribute("intensity")));
                }
                setBorderEffect(borderEffect);
            } else {
                borderStyle.setStyle("S");
            }
        }
        String dashes = element.getAttribute("dashes");
        if (dashes != null && !dashes.isEmpty()) {
            String[] dashesValues = dashes.split(",");
            COSArray dashPattern = new COSArray();
            for (String dashesValue : dashesValues) {
                dashPattern.add(COSNumber.get(dashesValue));
            }
            borderStyle.setDashStyle(dashPattern);
        }
        setBorderStyle(borderStyle);
    }
}

From source file:org.apache.sling.testing.mock.osgi.OsgiMetadataUtil.java

private static Node queryNode(Document metadata, String xpathQuery) {
    try {//from  w w w . j ava2 s  .com
        XPath xpath = XPATH_FACTORY.newXPath();
        xpath.setNamespaceContext(NAMESPACE_CONTEXT);
        return (Node) xpath.evaluate(xpathQuery, metadata, XPathConstants.NODE);
    } catch (XPathExpressionException ex) {
        throw new RuntimeException("Error evaluating XPath: " + xpathQuery, ex);
    }
}

From source file:org.apache.solr.core.Config.java

public Node getNode(String path, boolean errIfMissing) {
    XPath xpath = xpathFactory.newXPath();
    Node nd = null;/*from  ww  w  . j  a v  a  2s. co  m*/
    String xstr = normalize(path);

    try {
        nd = (Node) xpath.evaluate(xstr, doc, XPathConstants.NODE);

        if (nd == null) {
            if (errIfMissing) {
                throw new RuntimeException(name + " missing " + path);
            } else {
                log.debug(name + " missing optional " + path);
                return null;
            }
        }

        log.trace(name + ":" + path + "=" + nd);
        return nd;

    } catch (XPathExpressionException e) {
        SolrException.log(log, "Error in xpath", e);
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error in xpath:" + xstr + " for " + name,
                e, false);
    } catch (SolrException e) {
        throw (e);
    } catch (Throwable e) {
        SolrException.log(log, "Error in xpath", e);
        throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error in xpath:" + xstr + " for " + name,
                e, false);
    }
}

From source file:org.apache.solr.schema.IndexSchema.java

private void readSchema(InputSource is) {
    log.info("Reading Solr Schema from " + resourceName);

    try {// w  w  w . j a  va2s  .  c  o m
        // 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();
        final List<SchemaAware> schemaAware = new ArrayList<SchemaAware>();
        String expression = stepsToPath(SCHEMA, AT + NAME);
        Node nd = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        if (nd == null) {
            log.warn("schema has no name!");
        } else {
            name = nd.getNodeValue();
            log.info("Schema " + NAME + "=" + name);
        }

        //                      /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);

        //               /schema/types/fieldtype | /schema/types/fieldType 
        expression = stepsToPath(SCHEMA, TYPES, FIELD_TYPE.toLowerCase(Locale.ROOT)) // backcompat(?) 
                + XPATH_OR + stepsToPath(SCHEMA, TYPES, FIELD_TYPE);
        NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
        typeLoader.load(loader, nodes);

        // load the Fields

        // Hang on to the fields that say if they are required -- this lets us set a reasonable default for the unique key
        Map<String, Boolean> explicitRequiredProp = new HashMap<String, Boolean>();
        ArrayList<DynamicField> dFields = new ArrayList<DynamicField>();

        //               /schema/fields/field | /schema/fields/dynamicField
        expression = stepsToPath(SCHEMA, FIELDS, FIELD) + XPATH_OR + stepsToPath(SCHEMA, FIELDS, DYNAMIC_FIELD);
        nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);

            NamedNodeMap attrs = node.getAttributes();

            String name = DOMUtil.getAttr(attrs, NAME, "field definition");
            log.trace("reading field def " + name);
            String type = DOMUtil.getAttr(attrs, TYPE, "field " + name);

            FieldType ft = fieldTypes.get(type);
            if (ft == null) {
                throw new SolrException(ErrorCode.BAD_REQUEST,
                        "Unknown " + FIELD_TYPE + " '" + type + "' specified on field " + name);
            }

            Map<String, String> args = DOMUtil.toMapExcept(attrs, NAME, TYPE);
            if (null != args.get(REQUIRED)) {
                explicitRequiredProp.put(name, Boolean.valueOf(args.get(REQUIRED)));
            }

            SchemaField f = SchemaField.create(name, ft, args);

            if (node.getNodeName().equals(FIELD)) {
                SchemaField old = fields.put(f.getName(), f);
                if (old != null) {
                    String msg = "[schema.xml] Duplicate field definition for '" + f.getName() + "' [[["
                            + old.toString() + "]]] and [[[" + f.toString() + "]]]";
                    throw new SolrException(ErrorCode.SERVER_ERROR, msg);
                }
                log.debug("field defined: " + f);
                if (f.getDefaultValue() != null) {
                    log.debug(name + " contains default value: " + f.getDefaultValue());
                    fieldsWithDefaultValue.add(f);
                }
                if (f.isRequired()) {
                    log.debug(name + " is required in this schema");
                    requiredFields.add(f);
                }
            } else if (node.getNodeName().equals(DYNAMIC_FIELD)) {
                if (isValidFieldGlob(name)) {
                    // make sure nothing else has the same path
                    addDynamicField(dFields, f);
                } else {
                    String msg = "Dynamic field name '" + name
                            + "' should have either a leading or a trailing asterisk, and no others.";
                    throw new SolrException(ErrorCode.SERVER_ERROR, msg);
                }
            } else {
                // we should never get here
                throw new RuntimeException("Unknown field type");
            }
        }

        //fields with default values are by definition required
        //add them to required fields, and we only have to loop once
        // in DocumentBuilder.getDoc()
        requiredFields.addAll(getFieldsWithDefaultValue());

        // OK, now sort the dynamic fields largest to smallest size so we don't get
        // any false matches.  We want to act like a compiler tool and try and match
        // the largest string possible.
        Collections.sort(dFields);

        log.trace("Dynamic Field Ordering:" + dFields);

        // stuff it in a normal array for faster access
        dynamicFields = dFields.toArray(new DynamicField[dFields.size()]);

        expression = stepsToPath(SCHEMA, SIMILARITY); //   /schema/similarity
        Node node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        similarityFactory = readSimilarity(loader, node);
        if (similarityFactory == null) {
            similarityFactory = new DefaultSimilarityFactory();
        } else {
            isExplicitSimilarity = true;
        }
        if (similarityFactory instanceof SchemaAware) {
            ((SchemaAware) similarityFactory).inform(this);
        } else {
            // if the sim factory isn't schema aware, 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);
                }
            }
        }
        similarity = similarityFactory.getSimilarity();

        //                      /schema/defaultSearchField/@text()
        expression = stepsToPath(SCHEMA, DEFAULT_SEARCH_FIELD, TEXT_FUNCTION);
        node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        if (node == null) {
            log.debug("no default search field specified in schema.");
        } else {
            defaultSearchFieldName = node.getNodeValue().trim();
            // throw exception if specified, but not found or not indexed
            if (defaultSearchFieldName != null) {
                SchemaField defaultSearchField = getFields().get(defaultSearchFieldName);
                if ((defaultSearchField == null) || !defaultSearchField.indexed()) {
                    String msg = "default search field '" + defaultSearchFieldName
                            + "' not defined or not indexed";
                    throw new SolrException(ErrorCode.SERVER_ERROR, msg);
                }
            }
            log.info("default search field in schema is " + defaultSearchFieldName);
        }

        //                      /schema/solrQueryParser/@defaultOperator
        expression = stepsToPath(SCHEMA, SOLR_QUERY_PARSER, AT + DEFAULT_OPERATOR);
        node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        if (node == null) {
            log.debug("using default query parser operator (OR)");
        } else {
            isExplicitQueryParserDefaultOperator = true;
            queryParserDefaultOperator = node.getNodeValue().trim();
            log.info("query parser default operator is " + queryParserDefaultOperator);
        }

        //                      /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();
            log.info("unique key field: " + uniqueKeyFieldName);

            // 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[] {};
        expression = "//" + COPY_FIELD;
        nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            node = nodes.item(i);
            NamedNodeMap attrs = node.getAttributes();

            String source = DOMUtil.getAttr(attrs, SOURCE, COPY_FIELD + " definition");
            String dest = DOMUtil.getAttr(attrs, DESTINATION, COPY_FIELD + " definition");
            String maxChars = DOMUtil.getAttr(attrs, MAX_CHARS);
            int maxCharsInt = CopyField.UNLIMITED;
            if (maxChars != null) {
                try {
                    maxCharsInt = Integer.parseInt(maxChars);
                } catch (NumberFormatException e) {
                    log.warn("Couldn't parse " + MAX_CHARS + " attribute for " + COPY_FIELD + " from " + source
                            + " to " + dest + " as integer. The whole field will be copied.");
                }
            }

            if (dest.equals(uniqueKeyFieldName)) {
                String msg = UNIQUE_KEY + " field (" + uniqueKeyFieldName + ") can not be the " + DESTINATION
                        + " of a " + COPY_FIELD + "(" + SOURCE + "=" + source + ")";
                log.error(msg);
                throw new SolrException(ErrorCode.SERVER_ERROR, msg);

            }

            registerCopyField(source, dest, maxCharsInt);
        }

        for (Map.Entry<SchemaField, Integer> entry : copyFieldTargetCounts.entrySet()) {
            if (entry.getValue() > 1 && !entry.getKey().multiValued()) {
                log.warn("Field " + entry.getKey().name + " is not multivalued "
                        + "and destination for multiple " + COPY_FIELDS + " (" + entry.getValue() + ")");
            }
        }

        //Run the callbacks on SchemaAware now that everything else is done
        for (SchemaAware aware : schemaAware) {
            aware.inform(this);
        }
    } catch (SolrException e) {
        throw e;
    } catch (Exception e) {
        // unexpected exception...
        throw new SolrException(ErrorCode.SERVER_ERROR, "Schema Parsing Failed: " + e.getMessage(), e);
    }

    // create the field analyzers
    refreshAnalyzers();
}

From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java

public String getSubscribeId(String parentFolderId, String fname) {
    final Map<String, String> variables = new HashMap<String, String>();
    variables.put("parentFolderId", parentFolderId);
    variables.put("fname", fname);

    final Document userLayout = this.getUserLayoutDOM();
    final Element fnameNode = this.xpathOperations.evaluate(
            "//folder[@ID=$parentFolderId]/descendant::channel[@fname=$fname]", variables, userLayout,
            XPathConstants.NODE);
    if (fnameNode != null) {
        return fnameNode.getAttribute("ID");
    }/*www . j  a  va2  s  .c  o  m*/

    return null;
}

From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java

public String getRootFolderId() {
    if (rootNodeId == null) {
        Document layout = getUserLayoutDOM();

        Element rootNode = this.xpathOperations.evaluate("//layout/folder", layout, XPathConstants.NODE);
        if (rootNode == null || !rootNode.getAttribute(Constants.ATT_TYPE).equals(Constants.ROOT_FOLDER_ID)) {
            LOG.error("Unable to locate root node in layout of " + owner.getAttribute(IPerson.USERNAME)
                    + ". Resetting corrupted layout.");
            resetLayout((String) null);

            rootNode = this.xpathOperations.evaluate("//layout/folder", layout, XPathConstants.NODE);
            if (rootNode == null
                    || !rootNode.getAttribute(Constants.ATT_TYPE).equals(Constants.ROOT_FOLDER_ID)) {
                throw new PortalException("Corrupted layout detected for "
                        + owner.getAttribute(IPerson.USERNAME) + " and resetting layout failed.");
            }//from   w  w w .j  a  v a  2 s . c o m
        }
        rootNodeId = rootNode.getAttribute("ID");
    }
    return rootNodeId;
}