Java Examples for javax.xml.namespace.NamespaceContext

The following java examples will help you to understand the usage of javax.xml.namespace.NamespaceContext. These source code samples are taken from different open source projects.

Example 1
Project: mldht-master  File: XMLUtils.java View source code
public static XPathExpression buildXPath(String path, Map<String, String> map) {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    if (map != null)
        xpath.setNamespaceContext(new NamespaceContext() {

            public Iterator getPrefixes(String namespaceURI) {
                throw new UnsupportedOperationException();
            }

            public String getPrefix(String namespaceURI) {
                throw new UnsupportedOperationException();
            }

            public String getNamespaceURI(String prefix) {
                Objects.requireNonNull(prefix);
                if (map.containsKey(prefix))
                    return map.get(prefix);
                return XMLConstants.NULL_NS_URI;
            }
        });
    try {
        return xpath.compile(path);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}
Example 2
Project: xchain-master  File: AttributesUtil.java View source code
public static void validateAttributeValueTemplate(String attributeValueTemplate, NamespaceContext namespaceContext) throws JXPathException {
    List<String> parsedAvt = null;
    try {
        parsedAvt = parseAttributeValueTemplate(attributeValueTemplate);
    } catch (SAXException saxe) {
        throw new JXPathException(saxe.getMessage());
    }
    // validate the xpaths nested in the attribute value template.
    for (int i = 1; i < parsedAvt.size(); i += 2) {
        JXPathValidator.validate(parsedAvt.get(i), namespaceContext);
    }
}
Example 3
Project: spring-ws-master  File: NamespaceUtils.java View source code
/**
	 * Creates a {@code NamespaceContext} for the specified method, based on {@link Namespaces @Namespaces} and {@link
	 * Namespace @Namespace} annotations.
	 *
	 * <p>This method will search for {@link Namespaces @Namespaces} and {@link Namespace @Namespace} annotation in the
	 * given method, its class, and its package, in reverse order. That is: package-level annotations are overridden by
	 * class-level annotations, which again are overridden by method-level annotations.
	 *
	 * @param method the method to create the namespace context for
	 * @return the namespace context
	 */
public static NamespaceContext getNamespaceContext(Method method) {
    Assert.notNull(method, "'method' must not be null");
    SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
    Class<?> endpointClass = method.getDeclaringClass();
    Package endpointPackage = endpointClass.getPackage();
    if (endpointPackage != null) {
        addNamespaceAnnotations(endpointPackage, namespaceContext);
    }
    addNamespaceAnnotations(endpointClass, namespaceContext);
    addNamespaceAnnotations(method, namespaceContext);
    return namespaceContext;
}
Example 4
Project: spring-ws-test-master  File: XPathExpressionEvaluator.java View source code
public String evaluateExpression(Document document, String expression, URI uri, NamespaceContext namespaceContext) {
    XPathFactory factory = XPathFactory.newInstance();
    factory.setXPathVariableResolver(new WsTestXPathVariableResolver(uri));
    try {
        XPath xpath = factory.newXPath();
        if (namespaceContext != null) {
            xpath.setNamespaceContext(namespaceContext);
        }
        String result = xpath.evaluate(expression, document);
        logger.debug("Expression \"" + expression + "\" resolved to \"" + result + "\"");
        return result;
    } catch (XPathExpressionException e) {
        throw new ExpressionResolverException("Could not evaluate XPath expression \"" + expression + "\" : \"" + e.getMessage() + "\"", e);
    }
}
Example 5
Project: ddf-catalog-master  File: XPathHelper.java View source code
/**
     * @param xpathExpression
     * @param returnType
     * @param nsContext
     * @return
     * @throws XPathExpressionException
     */
public synchronized Object evaluate(String xpathExpressionKey, QName returnType, NamespaceContext nsContext) throws XPathExpressionException {
    XPathCache.getXPath().setNamespaceContext(nsContext);
    XPathExpression compiledExpression = XPathCache.getCompiledExpression(xpathExpressionKey);
    Thread thread = Thread.currentThread();
    ClassLoader loader = thread.getContextClassLoader();
    thread.setContextClassLoader(this.getClass().getClassLoader());
    try {
        return compiledExpression.evaluate(document, returnType);
    } finally {
        thread.setContextClassLoader(loader);
    }
}
Example 6
Project: ddf-master  File: MockNamespaceResolver.java View source code
public String getNamespaceURI(String prefix) {
    String methodName = "getNamespaceURI";
    LOGGER.trace("ENTERING: {}", methodName);
    String namespaceUri = null;
    for (NamespaceContext nc : namespaceContexts) {
        namespaceUri = nc.getNamespaceURI(prefix);
        if (namespaceUri != null) {
            break;
        }
    }
    LOGGER.trace("EXITING: {}    (namespaceUri = {} )", methodName, namespaceUri);
    return namespaceUri;
}
Example 7
Project: xmlunit-master  File: Convert.java View source code
/**
     * Creates a JAXP NamespaceContext from a Map prefix => Namespace URI.
     */
public static NamespaceContext toNamespaceContext(Map<String, String> prefix2URI) {
    final Map<String, String> copy = new LinkedHashMap<String, String>(prefix2URI);
    return new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            if (prefix == null) {
                throw new IllegalArgumentException("prefix must not be null");
            }
            if (XMLConstants.XML_NS_PREFIX.equals(prefix)) {
                return XMLConstants.XML_NS_URI;
            }
            if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) {
                return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
            }
            String uri = copy.get(prefix);
            return uri != null ? uri : XMLConstants.NULL_NS_URI;
        }

        public String getPrefix(String uri) {
            Iterator i = getPrefixes(uri);
            return i.hasNext() ? (String) i.next() : null;
        }

        public Iterator getPrefixes(String uri) {
            if (uri == null) {
                throw new IllegalArgumentException("uri must not be null");
            }
            Collection<String> c = new LinkedHashSet<String>();
            boolean done = false;
            if (XMLConstants.XML_NS_URI.equals(uri)) {
                c.add(XMLConstants.XML_NS_PREFIX);
                done = true;
            }
            if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(uri)) {
                c.add(XMLConstants.XMLNS_ATTRIBUTE);
                done = true;
            }
            if (!done) {
                for (Map.Entry<String, String> entry : copy.entrySet()) {
                    if (uri.equals(entry.getValue())) {
                        c.add(entry.getKey());
                    }
                }
            }
            return c.iterator();
        }
    };
}
Example 8
Project: crux-master  File: XPathUtils.java View source code
/**
	 * @return
	 */
public static XPath getCruxPagesXPath() {
    XPathFactory factory = XPathFactory.newInstance();
    XPath findPath = factory.newXPath();
    findPath.setNamespaceContext(new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            if (prefix.equals("c")) {
                return "http://www.cruxframework.org/crux";
            } else if (prefix.equals("v")) {
                return "http://www.cruxframework.org/view";
            }
            return "";
        }

        public String getPrefix(String namespaceURI) {
            if (namespaceURI.equals("http://www.cruxframework.org/crux")) {
                return "c";
            } else if (namespaceURI.equals("http://www.cruxframework.org/view")) {
                return "v";
            }
            return "";
        }

        public Iterator<?> getPrefixes(String namespaceURI) {
            List<String> prefixes = new ArrayList<String>();
            prefixes.add("c");
            prefixes.add("v");
            return prefixes.iterator();
        }
    });
    return findPath;
}
Example 9
Project: hale-master  File: XslTransformationUtil.java View source code
/**
	 * Create a XPath statement to select instances specified by the given type
	 * entity definition.
	 * 
	 * @param ted the type entity definition
	 * @param context the context for the XPath expression, e.g. the empty
	 *            string for the document root or <code>/</code> for anywhere in
	 *            the document
	 * @param namespaces the namespace context
	 * @return the XPath expression or <code>null</code> if there are no
	 *         elements that match the type
	 */
public static String selectInstances(TypeEntityDefinition ted, String context, NamespaceContext namespaces) {
    TypeDefinition type = ted.getDefinition();
    // get the XML elements associated to the type
    XmlElements elements = type.getConstraint(XmlElements.class);
    if (elements.getElements().isEmpty()) {
        /*
			 * XXX dirty hack
			 * 
			 * In CityGML 1.0 no element for AppearanceType is defined, only a
			 * property that is not detected in this way. The source route
			 * element is not known here, so we also cannot do a search based on
			 * the type. Thus for now we handle it as a special case.
			 */
        QName typeName = ted.getDefinition().getName();
        if ("http://www.opengis.net/citygml/appearance/1.0".equals(typeName.getNamespaceURI()) && "AppearanceType".equals(typeName.getLocalPart())) {
            // create a dummy XML element
            elements = new XmlElements();
            elements.addElement(new XmlElement(new QName("http://www.opengis.net/citygml/appearance/1.0", "Appearance"), ted.getDefinition(), null));
        } else
            // XXX dirty hack end
            return null;
    }
    // XXX which elements should be used?
    // for now use all elements
    StringBuilder select = new StringBuilder();
    boolean first = true;
    for (XmlElement element : elements.getElements()) {
        if (first) {
            first = false;
        } else {
            select.append(" | ");
        }
        select.append(context);
        select.append('/');
        String ns = element.getName().getNamespaceURI();
        if (ns != null && !ns.isEmpty()) {
            String prefix = namespaces.getPrefix(ns);
            if (prefix != null && !prefix.isEmpty()) {
                select.append(prefix);
                select.append(':');
            }
        }
        select.append(element.getName().getLocalPart());
    }
    // filter
    if (ted.getFilter() != null) {
        String filterxpath = FilterToXPath.toXPath(ted.getDefinition(), namespaces, ted.getFilter());
        if (filterxpath != null && !filterxpath.isEmpty()) {
            select.insert(0, '(');
            select.append(")[");
            select.append(StringEscapeUtils.escapeXml(filterxpath));
            select.append(']');
        }
    }
    return select.toString();
}
Example 10
Project: irond-master  File: Filter.java View source code
/**
	 * This method should contain the logic to check
	 * whether or not this {@link Metadata} object matches the
	 * given {@link Filter} f.
	 *
	 * @param metadata
	 * @param filter
	 * @return
	 */
public boolean matches(Metadata metadata) {
    //shortcut
    if (isMatchEverything()) {
        return true;
    }
    //shortcut
    if (isMatchNothing()) {
        return false;
    }
    //		NullCheck.check(f, "filter is null");
    sLogger.trace("matching with filter " + this.toString());
    String fs = this.getFilterString();
    XPath xpath = xPathFactory.newXPath();
    Map<String, String> nsMap = this.getNamespaceMap();
    if (sLogger.isTraceEnabled()) {
        int cnt = 1;
        sLogger.trace("Namespace map used for matching:");
        for (Entry<String, String> e : nsMap.entrySet()) {
            sLogger.trace(cnt++ + ":\t" + e.getKey() + " -- " + e.getValue());
        }
    }
    NamespaceContext nsCtx = new SimpleNamespaceContext(nsMap);
    xpath.setNamespaceContext(nsCtx);
    sLogger.trace("Filter before adaption: " + fs);
    // add * to lonely brackets
    fs = FilterAdaption.adaptFilterString(fs);
    sLogger.trace("Filter after adaption: " + fs);
    XPathExpression expr = null;
    // this should never happen, as we checked it before
    try {
        expr = xpath.compile(fs);
    } catch (XPathExpressionException e1) {
        sLogger.error("UNEXPECTED: Could not compile filterstring" + fs);
        return false;
    }
    Object ret = null;
    try {
        ret = expr.evaluate(metadata.toW3cDocument(), XPathConstants.BOOLEAN);
        sLogger.trace("matching result is " + ((Boolean) ret).booleanValue());
    } catch (XPathExpressionException e) {
        e.printStackTrace();
        sLogger.error("evaluate failed badly: " + e.getMessage());
        return false;
    }
    return ((Boolean) ret).booleanValue();
}
Example 11
Project: MyPublicRepo-master  File: BetterToolingQETest.java View source code
public List<String> getNodeDetails(NamespaceContext nsc, String exprString, String filePath) throws XPathExpressionException {
    List<String> list = new ArrayList<String>();
    XPathFactory factory = XPathFactory.newInstance();
    // 2. Use the XPathFactory to create a new XPath object
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(nsc);
    // 3. Compile an XPath string into an XPathExpression
    XPathExpression expression = xpath.compile(exprString);
    // 4. Evaluate the XPath expression on an input document
    Node result = (Node) expression.evaluate(new org.xml.sax.InputSource(filePath), XPathConstants.NODE);
    String svcName = null;
    NamedNodeMap attMap = result.getAttributes();
    Node att = attMap.getNamedItem("group");
    if (att != null)
        svcName = att.getNodeValue();
    if (result != null) {
        list.add(result.getNodeName());
        list.add(result.getTextContent());
        list.add(svcName);
    }
    return list;
}
Example 12
Project: OpenESPI-Common-java-master  File: TestUtils.java View source code
public static NamespaceContext getNamespaceContext() {
    return new NamespaceContext() {

        @Override
        public String getNamespaceURI(String prefix) {
            return namespaces().get(prefix);
        }

        @Override
        public String getPrefix(String namespaceURI) {
            return null;
        }

        @SuppressWarnings("rawtypes")
        // world
        @Override
        public Iterator getPrefixes(String namespaceURI) {
            return null;
        }
    };
}
Example 13
Project: openhab1-addons-master  File: WSBaseDataType.java View source code
public static String parseValue(String xml, String xpathExpression) throws IhcExecption {
    InputStream is;
    try {
        is = new ByteArrayInputStream(xml.getBytes("UTF8"));
    } catch (UnsupportedEncodingException e) {
        throw new IhcExecption(e);
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    InputSource inputSource = new InputSource(is);
    xpath.setNamespaceContext(new NamespaceContext() {

        @Override
        public String getNamespaceURI(String prefix) {
            if (prefix == null) {
                throw new NullPointerException("Null prefix");
            } else if ("SOAP-ENV".equals(prefix)) {
                return "http://schemas.xmlsoap.org/soap/envelope/";
            } else if ("ns1".equals(prefix)) {
                return "utcs";
            } else if ("ns2".equals(prefix)) {
                return "utcs.values";
            }
            return null;
        }

        @Override
        public String getPrefix(String uri) {
            return null;
        }

        @Override
        @SuppressWarnings("rawtypes")
        public Iterator getPrefixes(String uri) {
            throw new UnsupportedOperationException();
        }
    });
    try {
        return (String) xpath.evaluate(xpathExpression, inputSource, XPathConstants.STRING);
    } catch (XPathExpressionException e) {
        throw new IhcExecption(e);
    }
}
Example 14
Project: seam-2.2-master  File: ComponentHandler.java View source code
@Override
public void attributes(Object object, QName qName, ElementBinding elementBinding, Attributes attrs, NamespaceContext namespaceContext) {
    super.attributes(object, qName, elementBinding, attrs, namespaceContext);
    AbstractComponentMetaData component = (AbstractComponentMetaData) object;
    for (int i = 0; i < attrs.getLength(); ++i) {
        String localName = attrs.getLocalName(i);
        if ("scope".equals(localName))
            component.setScope(ScopeType.valueOf(attrs.getValue(i)));
    }
}
Example 15
Project: seam2jsf2-master  File: ComponentHandler.java View source code
@Override
public void attributes(Object object, QName qName, ElementBinding elementBinding, Attributes attrs, NamespaceContext namespaceContext) {
    super.attributes(object, qName, elementBinding, attrs, namespaceContext);
    AbstractComponentMetaData component = (AbstractComponentMetaData) object;
    for (int i = 0; i < attrs.getLength(); ++i) {
        String localName = attrs.getLocalName(i);
        if ("scope".equals(localName))
            component.setScope(ScopeType.valueOf(attrs.getValue(i)));
    }
}
Example 16
Project: turmeric-runtime-master  File: BetterToolingQETest.java View source code
public List<String> getNodeDetails(NamespaceContext nsc, String exprString, String filePath) throws XPathExpressionException {
    List<String> list = new ArrayList<String>();
    XPathFactory factory = XPathFactory.newInstance();
    // 2. Use the XPathFactory to create a new XPath object
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(nsc);
    // 3. Compile an XPath string into an XPathExpression
    XPathExpression expression = xpath.compile(exprString);
    // 4. Evaluate the XPath expression on an input document
    Node result = (Node) expression.evaluate(new org.xml.sax.InputSource(filePath), XPathConstants.NODE);
    String svcName = null;
    NamedNodeMap attMap = result.getAttributes();
    Node att = attMap.getNamedItem("group");
    if (att != null)
        svcName = att.getNodeValue();
    if (result != null) {
        list.add(result.getNodeName());
        list.add(result.getTextContent());
        list.add(svcName);
    }
    return list;
}
Example 17
Project: Wilma-master  File: NameSpaceProvider.java View source code
/**
     * Sets the namespace of an xpath.
     * @param xpath the {@link XPath} object that will receive the namespace
     */
public void setNameSpaceContext(final XPath xpath) {
    xpath.setNamespaceContext(new NamespaceContext() {

        @Override
        public String getNamespaceURI(final String prefix) {
            String result;
            if (prefix == null) {
                throw new NullPointerException("Null prefix");
            } else if (nameSpacePrefix.equals(prefix)) {
                result = nameSpaceUri;
            } else if ("xml".equals(prefix)) {
                result = XMLConstants.XML_NS_URI;
            } else {
                result = XMLConstants.NULL_NS_URI;
            }
            return result;
        }

        // This method isn't necessary for XPath processing.
        @Override
        public String getPrefix(final String uri) {
            throw new UnsupportedOperationException();
        }

        // This method isn't necessary for XPath processing either.
        @Override
        public Iterator<?> getPrefixes(final String uri) {
            throw new UnsupportedOperationException();
        }
    });
}
Example 18
Project: yangtools-master  File: StmtNamespaceContext.java View source code
@Override
public String getNamespaceURI(final String prefix) {
    // API-mandated by NamespaceContext
    Preconditions.checkArgument(prefix != null);
    final String uri = URIToPrefixMap.inverse().get(prefix);
    if (uri != null) {
        return uri;
    }
    if (prefix.isEmpty()) {
        return localNamespaceURI();
    }
    final QNameModule module = Utils.getModuleQNameByPrefix(ctx, prefix);
    return module == null ? null : module.getNamespace().toString();
}
Example 19
Project: classlib6-master  File: SCD.java View source code
/**
     * Parses the string representation of SCD.
     *
     * <p>
     * This method involves parsing the path expression and preparing the in-memory
     * structure, so this is useful when you plan to use the same SCD against
     * different context node multiple times.
     *
     * <p>
     * If you want to evaluate SCD just once, use {@link XSComponent#select} methods.
     *
     * @param path
     *      the string representation of SCD, such as "/foo/bar".
     * @param nsContext
     *      Its {@link NamespaceContext#getNamespaceURI(String)} is used
     *      to resolve prefixes in the SCD to the namespace URI.
     */
public static SCD create(String path, NamespaceContext nsContext) throws java.text.ParseException {
    try {
        SCDParser p = new SCDParser(path, nsContext);
        List<?> list = p.RelativeSchemaComponentPath();
        return new SCDImpl(path, list.toArray(new Step[list.size()]));
    } catch (TokenMgrError e) {
        throw setCause(new java.text.ParseException(e.getMessage(), -1), e);
    } catch (ParseException e) {
        throw setCause(new java.text.ParseException(e.getMessage(), e.currentToken.beginColumn), e);
    }
}
Example 20
Project: com.idega.core-master  File: XPathUtil.java View source code
private void compileXPathExpression(String xpathExpressionStr, NamespaceContext nmspcContext) {
    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        variableResolver = new XPathVariableResolverImpl();
        xpath.setXPathVariableResolver(variableResolver);
        if (nmspcContext != null)
            xpath.setNamespaceContext(nmspcContext);
        xpathExpression = xpath.compile(xpathExpressionStr);
    } catch (XPathException e) {
        throw new RuntimeException("Could not compile XPath expression: " + e.getMessage(), e);
    }
}
Example 21
Project: extreme-fishbowl-master  File: HasXPathTest.java View source code
@Override
protected void setUp() throws Exception {
    super.setUp();
    xml = parse("" + "<root type='food'>\n" + "  <something id='a'><cheese>Edam</cheese></something>\n" + "  <something id='b'><cheese>Cheddar</cheese></something>\n" + "  <f:foreignSomething xmlns:f=\"http://cheese.com\" milk=\"camel\">Caravane</f:foreignSomething>\n" + "  <emptySomething />\n" + "  <f:emptySomething xmlns:f=\"http://cheese.com\" />" + "</root>\n");
    ns = new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            return ("cheese".equals(prefix) ? "http://cheese.com" : null);
        }

        public String getPrefix(String namespaceURI) {
            return ("http://cheese.com".equals(namespaceURI) ? "cheese" : null);
        }

        public Iterator<String> getPrefixes(String namespaceURI) {
            HashSet<String> prefixes = new HashSet<String>();
            String prefix = getPrefix(namespaceURI);
            if (prefix != null) {
                prefixes.add(prefix);
            }
            return prefixes.iterator();
        }
    };
}
Example 22
Project: hsac-fitnesse-fixtures-master  File: XPathHelper.java View source code
/**
     * Evaluates xPathExpr against xml, returning all matches.
     * @param xml xml document to apply XPath to.
     * @param xPathExpr XPath expression to evaluate.
     * @return text() of all nodes matching XPath, null if xml is null.
     */
public List<String> getAllXPath(NamespaceContext context, String xml, String xPathExpr) {
    List<String> result = null;
    NodeList nodes = (NodeList) evaluateXpath(context, xml, xPathExpr, XPathConstants.NODESET);
    if (nodes != null) {
        result = new ArrayList<String>(nodes.getLength());
        for (int i = 0; i < nodes.getLength(); i++) {
            result.add(nodes.item(i).getNodeValue());
        }
    }
    return result;
}
Example 23
Project: ikvm-openjdk-master  File: SCD.java View source code
/**
     * Parses the string representation of SCD.
     *
     * <p>
     * This method involves parsing the path expression and preparing the in-memory
     * structure, so this is useful when you plan to use the same SCD against
     * different context node multiple times.
     *
     * <p>
     * If you want to evaluate SCD just once, use {@link XSComponent#select} methods.
     *
     * @param path
     *      the string representation of SCD, such as "/foo/bar".
     * @param nsContext
     *      Its {@link NamespaceContext#getNamespaceURI(String)} is used
     *      to resolve prefixes in the SCD to the namespace URI.
     */
public static SCD create(String path, NamespaceContext nsContext) throws java.text.ParseException {
    try {
        SCDParser p = new SCDParser(path, nsContext);
        List<?> list = p.RelativeSchemaComponentPath();
        return new SCDImpl(path, list.toArray(new Step[list.size()]));
    } catch (TokenMgrError e) {
        throw setCause(new java.text.ParseException(e.getMessage(), -1), e);
    } catch (ParseException e) {
        throw setCause(new java.text.ParseException(e.getMessage(), e.currentToken.beginColumn), e);
    }
}
Example 24
Project: jbpm-master  File: XPATHReturnValueEvaluator.java View source code
public Object evaluate(final ProcessContext context) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpathEvaluator = factory.newXPath();
    xpathEvaluator.setXPathFunctionResolver(new XPathFunctionResolver() {

        public XPathFunction resolveFunction(QName functionName, int arity) {
            String localName = functionName.getLocalPart();
            if ("getVariable".equals(localName)) {
                return new GetVariableData();
            } else {
                throw new IllegalArgumentException("Unknown BPMN function: " + functionName);
            }
        }

        class GetVariableData implements XPathFunction {

            public Object evaluate(List args) throws XPathFunctionException {
                String varname = (String) args.get(0);
                return context.getVariable(varname);
            }
        }
    });
    xpathEvaluator.setXPathVariableResolver(new XPathVariableResolver() {

        public Object resolveVariable(QName variableName) {
            return context.getVariable(variableName.getLocalPart());
        }
    });
    xpathEvaluator.setNamespaceContext(new NamespaceContext() {

        private static final String DROOLS_NAMESPACE_URI = "http://www.jboss.org/drools";

        private String[] prefixes = { "drools", "bpmn2" };

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            return Arrays.asList(prefixes).iterator();
        }

        @Override
        public String getPrefix(String namespaceURI) {
            if (DROOLS_NAMESPACE_URI.equalsIgnoreCase(namespaceURI)) {
                return "bpmn2";
            }
            return null;
        }

        @Override
        public String getNamespaceURI(String prefix) {
            if ("bpmn2".equalsIgnoreCase(prefix)) {
                return DROOLS_NAMESPACE_URI;
            }
            return null;
        }
    });
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    return xpathEvaluator.evaluate(this.expression, builder.newDocument(), XPathConstants.BOOLEAN);
}
Example 25
Project: jlibs-master  File: XPathEngine.java View source code
@SuppressWarnings({ "unchecked" })
public List<?> translate(Object result, NamespaceContext nsContext) {
    List nodeList = new ArrayList<NodeItem>();
    if (result instanceof NodeList) {
        NodeList nodeSet = (NodeList) result;
        for (int i = 0; i < nodeSet.getLength(); i++) {
            Node node = nodeSet.item(i);
            NodeItem item = new NodeItem(node, nsContext);
            nodeList.add(item);
        }
    } else {
        if (result instanceof List) {
            for (Object obj : (Collection) result) {
                Object item;
                if (obj instanceof Node)
                    item = new NodeItem((Node) obj, nsContext);
                else if (obj instanceof net.sf.saxon.om.NodeInfo) {
                    net.sf.saxon.om.NodeInfo info = (net.sf.saxon.om.NodeInfo) obj;
                    Node node = (Node) ((DOMNodeWrapper) info.getParent()).getUnderlyingNode();
                    item = new NodeItem(node, info.getLocalPart(), info.getStringValue(), nsContext);
                } else if (obj instanceof NodeList)
                    item = translate(obj, nsContext);
                else
                    throw new ImpossibleException(obj.getClass().getName());
                nodeList.add(item);
            }
        }
    }
    return nodeList;
}
Example 26
Project: ManagedRuntimeInitiative-master  File: SCD.java View source code
/**
     * Parses the string representation of SCD.
     *
     * <p>
     * This method involves parsing the path expression and preparing the in-memory
     * structure, so this is useful when you plan to use the same SCD against
     * different context node multiple times.
     *
     * <p>
     * If you want to evaluate SCD just once, use {@link XSComponent#select} methods.
     *
     * @param path
     *      the string representation of SCD, such as "/foo/bar".
     * @param nsContext
     *      Its {@link NamespaceContext#getNamespaceURI(String)} is used
     *      to resolve prefixes in the SCD to the namespace URI.
     */
public static SCD create(String path, NamespaceContext nsContext) throws java.text.ParseException {
    try {
        SCDParser p = new SCDParser(path, nsContext);
        List<?> list = p.RelativeSchemaComponentPath();
        return new SCDImpl(path, list.toArray(new Step[list.size()]));
    } catch (TokenMgrError e) {
        throw setCause(new java.text.ParseException(e.getMessage(), -1), e);
    } catch (ParseException e) {
        throw setCause(new java.text.ParseException(e.getMessage(), e.currentToken.beginColumn), e);
    }
}
Example 27
Project: narayana-master  File: QNameHelper.java View source code
/**
     * Return the qname represented by the qualified name.
     * @param namespaceContext The namespace context.
     * @param qualifiedName The qualified name.
     * @return The qname.
     */
public static QName toQName(final NamespaceContext namespaceContext, final String qualifiedName) {
    final int index = qualifiedName.indexOf(':');
    if (index == -1) {
        return new QName(qualifiedName);
    } else {
        final String prefix = qualifiedName.substring(0, index);
        final String localName = qualifiedName.substring(index + 1);
        final String namespaceURI = getNormalisedValue(namespaceContext.getNamespaceURI(prefix));
        return new QName(namespaceURI, localName, prefix);
    }
}
Example 28
Project: openjdk-master  File: SCD.java View source code
/**
     * Parses the string representation of SCD.
     *
     * <p>
     * This method involves parsing the path expression and preparing the in-memory
     * structure, so this is useful when you plan to use the same SCD against
     * different context node multiple times.
     *
     * <p>
     * If you want to evaluate SCD just once, use {@link XSComponent#select} methods.
     *
     * @param path
     *      the string representation of SCD, such as "/foo/bar".
     * @param nsContext
     *      Its {@link NamespaceContext#getNamespaceURI(String)} is used
     *      to resolve prefixes in the SCD to the namespace URI.
     */
public static SCD create(String path, NamespaceContext nsContext) throws java.text.ParseException {
    try {
        SCDParser p = new SCDParser(path, nsContext);
        List<?> list = p.RelativeSchemaComponentPath();
        return new SCDImpl(path, list.toArray(new Step[list.size()]));
    } catch (TokenMgrError e) {
        throw setCause(new java.text.ParseException(e.getMessage(), -1), e);
    } catch (ParseException e) {
        throw setCause(new java.text.ParseException(e.getMessage(), e.currentToken.beginColumn), e);
    }
}
Example 29
Project: rest-assured-master  File: XPathITest.java View source code
@Test
public void xpath_works_with_namespaces_when_xml_config_is_configured_to_be_namespace_aware() {
    // Given
    NamespaceContext namespaceContext = new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            return "http://marklogic.com/manage/package/databases";
        }

        public String getPrefix(String namespaceURI) {
            return "db";
        }

        public Iterator getPrefixes(String namespaceURI) {
            return Arrays.asList("db").iterator();
        }
    };
    // When
    given().config(RestAssuredConfig.newConfig().xmlConfig(xmlConfig().with().namespaceAware(true))).expect().body(hasXPath("/db:package-database", namespaceContext)).when().get("/package-db-xml");
}
Example 30
Project: rhq-master  File: SynchronizationConstants.java View source code
public static NamespaceContext createConfigurationExportNamespaceContext() {
    return new NamespaceContext() {

        //this map has to correspond to the namespaces defined in the code above
        private final Map<String, String> PREFIXES = new HashMap<String, String>();

        {
            PREFIXES.put(EXPORT_NAMESPACE_PREFIX, EXPORT_NAMESPACE);
            PREFIXES.put(CONFIGURATION_INSTANCE_NAMESPACE_PREFIX, CONFIGURATION_INSTANCE_NAMESPACE);
            PREFIXES.put(CONFIGURATION_NAMESPACE_PREFIX, CONFIGURATION_NAMESPACE);
        }

        @Override
        public Iterator<String> getPrefixes(String namespaceURI) {
            String prefix = getPrefix(namespaceURI);
            if (prefix == null) {
                return Collections.<String>emptySet().iterator();
            } else {
                return Collections.singleton(prefix).iterator();
            }
        }

        @Override
        public String getPrefix(String namespaceURI) {
            if (namespaceURI == null) {
                throw new IllegalArgumentException();
            } else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) {
                return XMLConstants.XMLNS_ATTRIBUTE;
            } else if (XMLConstants.XML_NS_URI.equals(namespaceURI)) {
                return XMLConstants.XML_NS_PREFIX;
            } else {
                String prefix = null;
                for (Map.Entry<String, String> e : PREFIXES.entrySet()) {
                    String p = e.getKey();
                    String namespace = e.getValue();
                    if (namespaceURI.equals(namespace)) {
                        prefix = p;
                        break;
                    }
                }
                return prefix;
            }
        }

        @Override
        public String getNamespaceURI(String prefix) {
            return PREFIXES.get(prefix);
        }
    };
}
Example 31
Project: tibco-fcunit-master  File: Resources.java View source code
/**
	 * 
	 * @return le noeud dont le chemin est xPathExpression
	 */
public static Node getNodeFromXPath(File file, String xPathExpression) {
    if (file != null && !file.exists() || file.isDirectory()) {
        return null;
    }
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    dbFactory.setValidating(false);
    DocumentBuilder dBuilder;
    Document document;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        document = dBuilder.parse(file);
    } catch (ParserConfigurationException e2) {
        return null;
    } catch (SAXException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    NamespaceContext namespaces = new NamespaceContext() {

        public Iterator<?> getPrefixes(String namespaceURI) {
            return null;
        }

        public String getPrefix(String namespaceURI) {
            if ("http://xmlns.tibco.com/bw/process/2003".equals(namespaceURI)) {
                return "pd";
            } else if ("http://www.tibco.com/xmlns/repo/types/2002".equals(namespaceURI)) {
                return "Repository";
            } else {
                return null;
            }
        }

        public String getNamespaceURI(String prefix) {
            if ("pd".equals(prefix)) {
                return "http://xmlns.tibco.com/bw/process/2003";
            } else if ("Repository".equals(prefix)) {
                return "http://www.tibco.com/xmlns/repo/types/2002";
            } else {
                return null;
            }
        }
    };
    xpath.setNamespaceContext(namespaces);
    String expression = xPathExpression;
    try {
        Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
        return widgetNode;
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    return null;
}
Example 32
Project: opencast-master  File: DublinCoreXmlFormatTest.java View source code
@Test
public void readFromNode() throws Exception {
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    final Document doc = dbf.newDocumentBuilder().parse(IoSupport.classPathResourceAsFile("/matterhorn-inlined-list-records-response.xml").get());
    final NamespaceContext ctx = XmlNamespaceContext.mk(XmlNamespaceBinding.mk("inlined", "http://www.opencastproject.org/oai/matterhorn-inlined"), XmlNamespaceBinding.mk("mp", "http://mediapackage.opencastproject.org"), XmlNamespaceBinding.mk("dc", DublinCores.OC_DC_CATALOG_NS_URI));
    // extract media package
    final Node mpNode = Xpath.mk(doc, ctx).node("//inlined:inlined/mp:mediapackage").get();
    final MediaPackage mp = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().loadFromXml(mpNode);
    assertNotNull(mp);
    assertEquals("10.0000/5820", mp.getIdentifier().toString());
    // extract episode DublinCore
    final Node dcNode = Xpath.mk(doc, ctx).node("//inlined:inlined/inlined:episode-dc/dc:dublincore").get();
    final DublinCoreCatalog dc = DublinCoreXmlFormat.read(dcNode);
    assertNotNull(dc);
    assertEquals("10.0000/5820", DublinCores.mkOpencastEpisode(dc).getDcIdentifier().get());
}
Example 33
Project: petals-wsstar-master  File: XPathDOMAnalyzer.java View source code
final synchronized NodeList evaluate(final String xpathExpression, final Document document, final Map<String, String> contextMap) throws WsnbException {
    final List<String> xpathExpressions = new ArrayList<String>();
    xpathExpressions.add(xpathExpression);
    NamespaceContext context = new NamespaceContextMap(contextMap);
    NodeList nodes = null;
    try {
        if (document != null) {
            for (final String xpathExprItem : xpathExpressions) {
                final XPath engine = XPathFactory.newInstance().newXPath();
                engine.setNamespaceContext(context);
                XPathExpression expr;
                expr = engine.compile(xpathExprItem);
                final Object result = expr.evaluate(document, XPathConstants.NODESET);
                if (result instanceof NodeList) {
                    nodes = (NodeList) result;
                    //						}
                    break;
                }
            }
            if (nodes == null && log.isLoggable(Level.FINE)) {
                log.fine("No xpath expressions " + xpathExpressions + " match with: \n " + Wsnb4ServUtils.prettyPrint(document.getOwnerDocument()));
            }
        }
    } catch (XPathExpressionException e) {
        throw new WsnbException(e);
    }
    return nodes;
}
Example 34
Project: aalto-xml-master  File: OutputElement.java View source code
@SuppressWarnings("unchecked")
public Iterator<String> getPrefixes(String uri, NamespaceContext rootNsContext) {
    List<String> l = null;
    if (_defaultNsURI.equals(uri)) {
        l = new ArrayList<String>();
        l.add("");
    }
    if (_nsBinder != null) {
        l = _nsBinder.getPrefixesBoundToUri(uri, l);
    }
    if (rootNsContext != null) {
        Iterator<String> it = (Iterator<String>) rootNsContext.getPrefixes(uri);
        while (it.hasNext()) {
            String prefix = it.next();
            if (prefix.length() == 0) {
                // default NS already checked
                continue;
            }
            // slow check... but what the heck
            if (l == null) {
                l = new ArrayList<String>();
            } else if (l.contains(prefix)) {
                // double-defined...
                continue;
            }
            l.add(prefix);
        }
    }
    if (l == null) {
        return EmptyIterator.getInstance();
    }
    return l.iterator();
}
Example 35
Project: aorra-master  File: XlsxDataSource.java View source code
private void setupExternalRef(Integer refnr, InputStream in) throws Exception {
    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new NamespaceContext() {

        @Override
        public String getNamespaceURI(String prefix) {
            if (StringUtils.equalsIgnoreCase(REL_PREFIX, prefix)) {
                return REL_NS_URI;
            }
            return "";
        }

        @Override
        public String getPrefix(String namespaceURI) {
            if (StringUtils.equalsIgnoreCase(REL_NS_URI, namespaceURI)) {
                return REL_PREFIX;
            }
            return "";
        }

        @Override
        public Iterator<?> getPrefixes(String namespaceURI) {
            return Lists.newArrayList(getPrefix(namespaceURI)).iterator();
        }
    });
    String target = xp.evaluate("/ref:Relationships/ref:Relationship/@Target", new InputSource(in));
    if (StringUtils.isNotBlank(target)) {
        rmap.put(refnr, target);
    }
}
Example 36
Project: bpelunit-master  File: DataExtraction.java View source code
// ************************** Implementation *************************
public void evaluate(ActivityContext context, Element literalData, NamespaceContext namespaceContext, ContextXPathVariableResolver variableResolver) {
    final XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(namespaceContext);
    if (variableResolver != null) {
        xpath.setXPathVariableResolver(variableResolver);
    }
    try {
        final QName returnType = getXPathReturnType();
        fExtracted = xpath.evaluate(fExpression, literalData, returnType);
        fStatus = ArtefactStatus.createPassedStatus();
        final IExtractedDataContainer targetContainer = getTargetContainer();
        targetContainer.putExtractedData(fVariable, fExtracted);
    } catch (Exception e) {
        Throwable root = BPELUnitUtil.findRootThrowable(e);
        fStatus = ArtefactStatus.createErrorStatus(root.getMessage());
    }
}
Example 37
Project: camel-master  File: MockEndpointFixture.java View source code
protected void assertMessageReceived(Document aExpectedDoc, Document aActual) throws Exception, XPathExpressionException {
    Document noTime = XmlFixture.stripTimestamp(aActual);
    Document noUUID = XmlFixture.stripUUID(noTime);
    XmlFixture.assertXMLIgnorePrefix("failed to match", aExpectedDoc, noUUID);
    // assert that we have a timestamp and datetime
    // can't rely on the datetime being the same due to timezone differences
    // instead, we'll assert that the values exist.
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xp = xpf.newXPath();
    xp.setNamespaceContext(new NamespaceContext() {

        public String getNamespaceURI(String aArg0) {
            return "urn:org.apache.camel.component:jmx";
        }

        public String getPrefix(String aArg0) {
            return "jmx";
        }

        public Iterator<Object> getPrefixes(String aArg0) {
            return null;
        }
    });
    assertEquals("1", xp.evaluate("count(//jmx:timestamp)", aActual));
    assertEquals("1", xp.evaluate("count(//jmx:dateTime)", aActual));
    resetMockEndpoint();
}
Example 38
Project: com.revolsys.open-master  File: XmlUtil.java View source code
static QName getXmlQName(final NamespaceContext context, final String value) {
    if (value == null) {
        return null;
    } else {
        final int colonIndex = value.indexOf(':');
        if (colonIndex == -1) {
            return new QName(value);
        } else {
            final String prefix = value.substring(0, colonIndex);
            final String name = value.substring(colonIndex + 1);
            final String namespaceUri = context.getNamespaceURI(prefix);
            return new QName(namespaceUri, name, prefix);
        }
    }
}
Example 39
Project: cxf-master  File: ElementReader.java View source code
private void extractXsiType() {
    /*
         * We're making a conscious choice here -- garbage in == garbage out.
         */
    String xsiTypeQname = root.getAttributeValue(Constants.URI_2001_SCHEMA_XSI, "type");
    if (xsiTypeQname != null) {
        Matcher m = QNAME_PATTERN.matcher(xsiTypeQname);
        if (m.matches()) {
            NamespaceContext nc = root.getNamespaceContext();
            this.xsiType = new QName(nc.getNamespaceURI(m.group(1)), m.group(2), m.group(1));
        } else {
            this.xsiType = new QName(this.namespace, xsiTypeQname, "");
        }
    }
}
Example 40
Project: eu.geclipse.core-master  File: XPathDocument.java View source code
private NamespaceContext getNamespaceContext() {
    return new NamespaceContext() {

        // TODO mariusz parse source jsdl document add here all prefixes and namespaces (user may use these prefixes)
        public String getNamespaceURI(final String prefix) {
            String namespace = XMLConstants.NULL_NS_URI;
            if ("jsdl".equals(prefix)) {
                //$NON-NLS-1$
                //$NON-NLS-1$
                namespace = "http://schemas.ggf.org/jsdl/2005/11/jsdl";
            } else if ("jsdl-posix".equals(prefix)) {
                //$NON-NLS-1$
                //$NON-NLS-1$
                namespace = "http://schemas.ggf.org/jsdl/2005/11/jsdl-posix";
            } else if ("sweep".equals(prefix)) {
                //$NON-NLS-1$
                //$NON-NLS-1$
                namespace = "http://schemas.ogf.org/jsdl/2007/01/jsdl-sweep";
            } else if ("sweepfunc".equals(prefix)) {
                //$NON-NLS-1$
                //$NON-NLS-1$
                namespace = "http://schemas.ogf.org/jsdl/2007/01/jsdl-sweep/functions";
            } else if ("xml".equals(prefix)) {
                //$NON-NLS-1$
                namespace = XMLConstants.XML_NS_URI;
            } else if ("fn".equals(prefix)) {
                //$NON-NLS-1$
                //$NON-NLS-1$
                namespace = "http://www.w3.org/2005/xpath-functions";
            }
            return namespace;
        }

        public String getPrefix(final String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        @SuppressWarnings("unchecked")
        public Iterator getPrefixes(final String namespaceURI) {
            throw new UnsupportedOperationException();
        }
    };
}
Example 41
Project: ganttproject-master  File: RssParser.java View source code
private XPathExpression getXPath(String expression) throws XPathExpressionException {
    XPath xpath = myXPathFactory.newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {

        @Override
        public String getNamespaceURI(String s) {
            if ("atom".equals(s)) {
                return "http://www.w3.org/2005/Atom";
            }
            throw new IllegalArgumentException(s);
        }

        @Override
        public String getPrefix(String s) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator<?> getPrefixes(String s) {
            throw new UnsupportedOperationException();
        }
    });
    return xpath.compile(expression);
}
Example 42
Project: groupbasedpolicy-master  File: IseReplyUtil.java View source code
/**
     * @return initiated xpath with ise namespace context injected
     */
public static XPath setupXpath() {
    final NamespaceContext nsContext = new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            final String outcome;
            if (prefix == null) {
                throw new NullPointerException("Null prefix");
            }
            if ("ns5".equals(prefix)) {
                outcome = "ers.ise.cisco.com";
            } else if ("ns3".equals(prefix)) {
                outcome = "v2.ers.ise.cisco.com";
            } else if ("ns4".equals(prefix)) {
                outcome = "trustsec.ers.ise.cisco.com";
            } else {
                outcome = XMLConstants.NULL_NS_URI;
            }
            return outcome;
        }

        // This method isn't necessary for XPath processing.
        public String getPrefix(String uri) {
            throw new UnsupportedOperationException();
        }

        // This method isn't necessary for XPath processing either.
        public Iterator getPrefixes(String uri) {
            throw new UnsupportedOperationException();
        }
    };
    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(nsContext);
    return xpath;
}
Example 43
Project: jaxb-master  File: SCD.java View source code
/**
     * Parses the string representation of SCD.
     *
     * <p>
     * This method involves parsing the path expression and preparing the in-memory
     * structure, so this is useful when you plan to use the same SCD against
     * different context node multiple times.
     *
     * <p>
     * If you want to evaluate SCD just once, use {@link XSComponent#select} methods.
     *
     * @param path
     *      the string representation of SCD, such as "/foo/bar".
     * @param nsContext
     *      Its {@link NamespaceContext#getNamespaceURI(String)} is used
     *      to resolve prefixes in the SCD to the namespace URI.
     */
public static SCD create(String path, NamespaceContext nsContext) throws java.text.ParseException {
    try {
        SCDParser p = new SCDParser(path, nsContext);
        List<?> list = p.RelativeSchemaComponentPath();
        return new SCDImpl(path, list.toArray(new Step[list.size()]));
    } catch (TokenMgrError e) {
        throw setCause(new java.text.ParseException(e.getMessage(), -1), e);
    } catch (ParseException e) {
        throw setCause(new java.text.ParseException(e.getMessage(), e.currentToken.beginColumn), e);
    }
}
Example 44
Project: jolie-dbus-master  File: SCD.java View source code
/**
     * Parses the string representation of SCD.
     *
     * <p>
     * This method involves parsing the path expression and preparing the in-memory
     * structure, so this is useful when you plan to use the same SCD against
     * different context node multiple times.
     *
     * <p>
     * If you want to evaluate SCD just once, use {@link XSComponent#select} methods.
     *
     * @param path
     *      the string representation of SCD, such as "/foo/bar".
     * @param nsContext
     *      Its {@link NamespaceContext#getNamespaceURI(String)} is used
     *      to resolve prefixes in the SCD to the namespace URI.
     */
public static SCD create(String path, NamespaceContext nsContext) throws java.text.ParseException {
    try {
        SCDParser p = new SCDParser(path, nsContext);
        List<?> list = p.RelativeSchemaComponentPath();
        return new SCDImpl(path, list.toArray(new Step[list.size()]));
    } catch (TokenMgrError e) {
        throw setCause(new java.text.ParseException(e.getMessage(), -1), e);
    } catch (ParseException e) {
        throw setCause(new java.text.ParseException(e.getMessage(), e.currentToken.beginColumn), e);
    }
}
Example 45
Project: mobile-campus-assistant-master  File: JenaModelKmlProviderTest.java View source code
@Test
public void test() throws IOException, XPathExpressionException {
    // ---------- create a model with some data
    Model m = ModelFactory.createDefaultModel();
    Resource point1 = m.createResource("http://www.openstreetmap.org/api/0.6/node/943619199");
    point1.addProperty(WGS84.latitude, "51.4541024", XSDDatatype.XSDdouble);
    point1.addProperty(WGS84.longitude, "-2.6021703", XSDDatatype.XSDdouble);
    point1.addProperty(RDF.type, WGS84.Point);
    point1.addProperty(RDFS.label, "Bristol Ram");
    Resource point2 = m.createResource("http://www.openstreetmap.org/api/0.6/node/26122195");
    point2.addProperty(WGS84.latitude, "51.4542722", XSDDatatype.XSDdouble);
    point2.addProperty(WGS84.longitude, "-2.6022771", XSDDatatype.XSDdouble);
    point2.addProperty(RDF.type, WGS84.Point);
    point2.addProperty(RDFS.label, "Folk House");
    // we are going to test this object...
    JenaModelKmlProvider provider = new JenaModelKmlProvider();
    // we can't use a string
    assertFalse("Can write the object", provider.isWriteable((String.class), null, null, null));
    // we should be able to use a Model
    assertTrue("Cannot write the object", provider.isWriteable(m.getClass(), null, null, null));
    // ---------- get a stream and send it to the provider to convert to kml
    ByteOutputStream bos = new ByteOutputStream();
    provider.writeTo(m, null, null, null, null, null, bos);
    // ----------- create an xpath with namespace support
    String output = bos.toString();
    XPath engine = XPathFactory.newInstance().newXPath();
    NamespaceContext ctx = new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            return "http://www.opengis.net/kml/2.2";
        }

        @Override
        public String getPrefix(String s) {
            return null;
        }

        @Override
        public Iterator getPrefixes(String s) {
            return null;
        }
    };
    engine.setNamespaceContext(ctx);
    // ---------- run some tests
    assertEquals("Unexpected name", "Bristol Ram", engine.evaluate("//ns1:kml/ns1:Document/" + "ns1:Placemark[1]/ns1:name/text()", new InputSource(new StringReader(output))));
    assertEquals("Unexpected name", "Folk House", engine.evaluate("//ns1:kml/ns1:Document/" + "ns1:Placemark[2]/ns1:name/text()", new InputSource(new StringReader(output))));
}
Example 46
Project: mp4parser-master  File: ExportTTMLTrack.java View source code
public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    //Movie m = MovieCreator.build("C:\\dev\\mp4parser-github\\ttml-example\\subs.uvu");
    Movie m = MovieCreator.build("C:\\dev\\mp4parser-github\\output.mp4");
    for (Track track : m.getTracks()) {
        if (track.getHandler().endsWith("vide")) {
            Movie vide = new Movie(Collections.singletonList(track));
            DefaultMp4Builder builder = new DefaultMp4Builder();
            builder.build(vide).writeContainer(new RandomAccessFile("vide_" + track.getTrackMetaData().getTrackId() + ".mp4", "rw").getChannel());
        }
        if (track.getHandler().endsWith("soun")) {
            Movie vide = new Movie(Collections.singletonList(track));
            DefaultMp4Builder builder = new DefaultMp4Builder();
            builder.build(vide).writeContainer(new RandomAccessFile("soun_" + track.getTrackMetaData().getTrackId() + ".mp4", "rw").getChannel());
        }
        if (track.getHandler().endsWith("subt")) {
            for (int i = 0; i < track.getSamples().size(); i++) {
                File f = new File("subtitle_" + track.getTrackMetaData().getTrackId() + "_" + i + ".xml");
                f.delete();
                RandomAccessFile raf = new RandomAccessFile(f, "rw");
                SubSampleInformationBox subs = track.getSubsampleInformationBox();
                int j = 0;
                ByteBuffer xmlSamplePart = null;
                for (SubSampleInformationBox.SubSampleEntry subSampleEntry : subs.getEntries()) {
                    j += subSampleEntry.getSampleDelta();
                    if (j == (i + 1)) {
                        // found sample entry
                        Iterator<SubSampleInformationBox.SubSampleEntry.SubsampleEntry> subsampleIter = subSampleEntry.getSubsampleEntries().iterator();
                        if (subsampleIter.hasNext()) {
                            SubSampleInformationBox.SubSampleEntry.SubsampleEntry xmlSubSampleEntry = subsampleIter.next();
                            ByteBuffer sample = track.getSamples().get(i).asByteBuffer();
                            xmlSamplePart = (ByteBuffer) sample.slice().limit(l2i(xmlSubSampleEntry.getSubsampleSize()));
                            raf.getChannel().write(xmlSamplePart);
                            raf.close();
                            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                            factory.setNamespaceAware(true);
                            DocumentBuilder builder = factory.newDocumentBuilder();
                            Document document = builder.parse(f);
                            XPathFactory xPathfactory = XPathFactory.newInstance();
                            NamespaceContext ctx = new NamespaceContext() {

                                public String getNamespaceURI(String prefix) {
                                    if (prefix.equals("ttml")) {
                                        return "http://www.w3.org/ns/ttml";
                                    }
                                    if (prefix.equals("smpte")) {
                                        return "http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt";
                                    }
                                    return null;
                                }

                                public Iterator getPrefixes(String val) {
                                    return Arrays.asList("ttml", "smpte").iterator();
                                }

                                public String getPrefix(String uri) {
                                    if (uri.equals("http://www.w3.org/ns/ttml")) {
                                        return "ttml";
                                    }
                                    if (uri.equals("http://www.smpte-ra.org/schemas/2052-1/2010/smpte-tt")) {
                                        return "smpte";
                                    }
                                    return null;
                                }
                            };
                            XPath xpath = xPathfactory.newXPath();
                            xpath.setNamespaceContext(ctx);
                            XPathExpression expr = xpath.compile("/ttml:tt/ttml:body/ttml:div/@smpte:backgroundImage");
                            NodeList nl = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
                            HashSet<String> names = new HashSet<String>();
                            for (int n = 0; n < nl.getLength(); n++) {
                                names.add(nl.item(n).getNodeValue());
                            }
                            List<String> imageNames = new ArrayList<String>(names);
                            Collections.sort(imageNames);
                            System.out.println(nl);
                            System.out.println(document.getFirstChild().getTextContent());
                            sample = ((ByteBuffer) sample.position(l2i(xmlSubSampleEntry.getSubsampleSize()))).slice();
                            int p = 0;
                            while (subsampleIter.hasNext()) {
                                SubSampleInformationBox.SubSampleEntry.SubsampleEntry picSubSampleEntry = subsampleIter.next();
                                ByteBuffer pic = (ByteBuffer) sample.slice().limit(l2i(picSubSampleEntry.getSubsampleSize()));
                                sample = ((ByteBuffer) sample.position(l2i(picSubSampleEntry.getSubsampleSize()))).slice();
                                FileOutputStream fosPic = new FileOutputStream("subtitle_" + track.getTrackMetaData().getTrackId() + "_" + i + "_" + imageNames.get(p++).replace(":", "_"));
                                fosPic.getChannel().write(pic);
                            }
                            String content = IOUtils.toString(new FileInputStream(f));
                            for (String imageName : imageNames) {
                                content = content.replaceAll(imageName, "subtitle_" + track.getTrackMetaData().getTrackId() + "_" + i + "_" + imageName.replace(":", "_"));
                            }
                            IOUtils.write(content, new FileOutputStream(f));
                        }
                    }
                }
                if (xmlSamplePart == null) {
                    xmlSamplePart = track.getSamples().get(i).asByteBuffer();
                    raf.getChannel().write(xmlSamplePart);
                }
            }
        }
    }
}
Example 47
Project: mylyn.docs-master  File: XmlStreamWriterAdapter.java View source code
@Override
public NamespaceContext getNamespaceContext() {
    return new NamespaceContext() {

        @Override
        public Iterator<String> getPrefixes(String namespaceUri) {
            String prefix = getPrefix(namespaceUri);
            if (prefix == null) {
                return ImmutableSet.<String>of().iterator();
            }
            return Collections.singletonList(prefix).iterator();
        }

        @Override
        public String getPrefix(String namespaceUri) {
            return delegate.getPrefix(namespaceUri);
        }

        @Override
        public String getNamespaceURI(String prefix) {
            return delegate.getNamespaceURI(prefix);
        }
    };
}
Example 48
Project: ODE-X-master  File: CompilerTest.java View source code
@Test
public void testCompileHelloWorld() throws Exception {
/*	repo.importArtifact(new ArtifactId("{http://ode/bpel/unit-test.wsdl}HelloService", null, null), "HelloWorld.wsdl", true, true, readStream(Thread
				.currentThread().getContextClassLoader().getResourceAsStream("HelloWorld/HelloWorld.wsdl")));
		repo.importArtifact(new ArtifactId("{http://ode/bpel/unit-test}HelloWorld", null, null), "HelloWorld.bpel", true, true, readStream(Thread
				.currentThread().getContextClassLoader().getResourceAsStream("HelloWorld/HelloWorld.bpel")));
		buildSystem.build(readStream(Thread.currentThread().getContextClassLoader().getResourceAsStream("HelloWorld/HelloWorld.build")));
		byte[] content = repo.exportArtifact(new ArtifactId("{http://ode/bpel/unit-test}HelloWorld", "application/ode-executable", "1.0"));
		assertNotNull(content);
		System.out.println(new String(content));
		Document doc = ParserUtils.contentToDom(content);
		XPathFactory xpFactory = XPathFactory.newInstance();
		XPath xPath = xpFactory.newXPath();
		Map<String,String> ns = new HashMap<String,String>();
		ns.put("e", Platform.EXEC_NAMESPACE);
		ns.put("b", BPELComponent.BPEL_INSTRUCTION_SET_NS);
		NamespaceContext ctx = ParserUtils.buildNSContext(ns);
		xPath.setNamespaceContext(ctx);
		assertNotNull(xPath.evaluate("/e:executable/e:block[1]/b:process[1]", doc,XPathConstants.NODE));
		assertNotNull(xPath.evaluate("/e:executable/e:block[1]/b:process[2]", doc,XPathConstants.NODE));
	*/
}
Example 49
Project: openaz-master  File: XPathExpressionWrapper.java View source code
public synchronized XPathExpression getXpathExpressionWrapped() {
    if (this.xpathExpressionWrapped == null && (this.getStatus() == null || this.getStatus().isOk())) {
        String thisPath = this.getPath();
        if (thisPath != null) {
            XPath xPath = XPathFactory.newInstance().newXPath();
            NamespaceContext namespaceContextThis = this.getNamespaceContext();
            if (namespaceContextThis != null) {
                xPath.setNamespaceContext(namespaceContextThis);
            }
            try {
                this.xpathExpressionWrapped = xPath.compile(thisPath);
            } catch (XPathExpressionException ex) {
                this.status = new StdStatus(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, "Error compiling XPath " + thisPath + ": " + ex.getMessage());
            }
        }
    }
    return this.xpathExpressionWrapped;
}
Example 50
Project: opencirm-master  File: PartBuiltIn.java View source code
private NamespaceContext defaultContext(final String namespace) {
    return new NamespaceContext() {

        @Override
        public String getNamespaceURI(String prefix) {
            return namespace;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            return "";
        }

        @Override
        public Iterator<String> getPrefixes(String namespaceURI) {
            return Arrays.asList(new String[] { "" }).iterator();
        }
    };
}
Example 51
Project: openjump-core-rels-master  File: XPathUtils.java View source code
/**
     * @param xpath
     * @param e
     * @param nscontext
     * @return a double, possibly converted from an integer value
     * @throws XPathExpressionException
     */
public static double getDouble(String xpath, Element e, NamespaceContext nscontext) throws XPathExpressionException {
    XPATH.setNamespaceContext(nscontext);
    Object res = XPATH.evaluate(xpath, e, NUMBER);
    if (LOG.isDebugEnabled()) {
        LOG.debug("XPath expression " + xpath + " yielded " + res);
    }
    if (res instanceof Double) {
        return (Double) res;
    }
    return (Integer) res;
}
Example 52
Project: org.eclipse.mylyn.docs-master  File: XmlStreamWriterAdapter.java View source code
@Override
public NamespaceContext getNamespaceContext() {
    return new NamespaceContext() {

        @Override
        public Iterator<String> getPrefixes(String namespaceUri) {
            String prefix = getPrefix(namespaceUri);
            if (prefix == null) {
                return Iterators.emptyIterator();
            }
            return Collections.singletonList(prefix).iterator();
        }

        @Override
        public String getPrefix(String namespaceUri) {
            return delegate.getPrefix(namespaceUri);
        }

        @Override
        public String getNamespaceURI(String prefix) {
            return delegate.getNamespaceURI(prefix);
        }
    };
}
Example 53
Project: quercus-master  File: XMLEventFactoryImpl.java View source code
private StartElement createStartElement(QName name, Iterator attributes, Iterator namespaces, NamespaceContext context) {
    HashMap<QName, Attribute> attributeMap = new HashMap<QName, Attribute>();
    HashMap<String, Namespace> namespaceMap = new HashMap<String, Namespace>();
    if (attributes != null) {
        while (attributes.hasNext()) {
            Attribute attribute = (Attribute) attributes.next();
            attributeMap.put(attribute.getName(), attribute);
        }
    }
    if (namespaces != null) {
        while (namespaces.hasNext()) {
            Namespace namespace = (Namespace) namespaces.next();
            namespaceMap.put(namespace.getPrefix(), namespace);
        }
    }
    return new StartElementImpl(name, attributeMap, namespaceMap, context);
}
Example 54
Project: resin-master  File: QNameProperty.java View source code
// XXX default namespace?
private QName resolveQName(String text, NamespaceContext context) throws JAXBException {
    int colon = text.indexOf(':');
    if (colon < 0)
        return new QName(text);
    else {
        String prefix = text.substring(0, colon);
        // NOTE!!! The Xerces StAX requires the prefixes to be interned for
        // some reason...
        String namespace = context.getNamespaceURI(prefix.intern());
        if (namespace == null)
            throw new JAXBException(L.l("No known namespace for prefix '{0}'", prefix));
        String localName = text.substring(colon + 1);
        if ("".equals(localName))
            throw new JAXBException(L.l("Malformed QName: empty localName"));
        return new QName(namespace, localName, prefix);
    }
}
Example 55
Project: snowdrop-master  File: NamedXmlApplicationContext.java View source code
private void initializeNames(Resource resource) {
    try {
        XPath xPath = XPathFactory.newInstance().newXPath();
        xPath.setNamespaceContext(new NamespaceContext() {

            @Override
            public String getNamespaceURI(String prefix) {
                return "http://www.springframework.org/schema/beans";
            }

            @Override
            public String getPrefix(String namespaceURI) {
                return "beans";
            }

            @Override
            public Iterator<String> getPrefixes(String namespaceURI) {
                return Collections.singleton("beans").iterator();
            }
        });
        String expression = "/beans:beans/beans:description";
        InputSource inputSource = new InputSource(resource.getInputStream());
        String description = xPath.evaluate(expression, inputSource);
        if (description != null) {
            Matcher bfm = Pattern.compile(Constants.BEAN_FACTORY_ELEMENT).matcher(description);
            if (bfm.find()) {
                this.name = bfm.group(1);
            }
            Matcher pbfm = Pattern.compile(Constants.PARENT_BEAN_FACTORY_ELEMENT).matcher(description);
            if (pbfm.find()) {
                String parentName = pbfm.group(1);
                try {
                    this.getBeanFactory().setParentBeanFactory((BeanFactory) Util.lookup(parentName, BeanFactory.class));
                } catch (Exception e) {
                    throw new BeanDefinitionStoreException("Failure during parent bean factory JNDI lookup: " + parentName, e);
                }
            }
        }
        if (this.name == null || "".equals(StringUtils.trimAllWhitespace(this.name))) {
            this.name = this.defaultName;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 56
Project: SOCIETIES-Platform-master  File: StAXConnector.java View source code
protected final void handleStartDocument(NamespaceContext nsc) throws SAXException {
    visitor.startDocument(new LocatorEx() {

        public ValidationEventLocator getLocation() {
            return new ValidationEventLocatorImpl(this);
        }

        public int getColumnNumber() {
            return getCurrentLocation().getColumnNumber();
        }

        public int getLineNumber() {
            return getCurrentLocation().getLineNumber();
        }

        public String getPublicId() {
            return getCurrentLocation().getPublicId();
        }

        public String getSystemId() {
            return getCurrentLocation().getSystemId();
        }
    }, nsc);
}
Example 57
Project: Tundra-master  File: xml.java View source code
public static final void parse(IData pipeline) throws ServiceException {
    // --- <<IS-START(parse)>> ---
    // @subtype unknown
    // @sigtype java 3.5
    // [i] object:0:optional $content
    // [i] field:0:optional $encoding
    // [i] record:0:optional $namespace
    // [i] - field:0:optional default
    // [o] record:0:optional $document
    IDataCursor cursor = pipeline.getCursor();
    try {
        Object content = IDataHelper.get(cursor, "$content");
        Charset charset = IDataHelper.get(cursor, "$encoding", Charset.class);
        NamespaceContext namespace = IDataHelper.get(cursor, "$namespace", IDataNamespaceContext.class);
        Node node = null;
        if (content instanceof Node) {
            node = (Node) content;
        } else if (content instanceof InputSource) {
            node = DocumentHelper.parse((InputSource) content, namespace);
        } else if (content != null) {
            node = DocumentHelper.parse(InputStreamHelper.normalize(content, charset), charset, true, namespace);
        }
        if (node != null)
            IDataHelper.put(cursor, "$document", NodeHelper.parse(node, namespace, true));
    } finally {
        cursor.destroy();
    }
// --- <<IS-END>> ---
}
Example 58
Project: tuscany-sca-2.x-master  File: ExternalAttachmentProcessor.java View source code
private void readAttachTo(ExternalAttachment attachment, XMLStreamReader reader, ProcessorContext context) {
    Monitor monitor = context.getMonitor();
    String attachTo = reader.getAttributeValue(null, ATTACH_TO);
    if (attachTo != null) {
        try {
            XPath path = xpathHelper.newXPath();
            NamespaceContext nsContext = xpathHelper.getNamespaceContext(attachTo, reader.getNamespaceContext());
            path.setXPathFunctionResolver(new PolicyXPathFunctionResolver(nsContext));
            attachTo = PolicyXPathFunction.normalize(attachTo, getSCAPrefix(nsContext));
            XPathExpression expression = xpathHelper.compile(path, nsContext, attachTo);
            attachment.setAttachTo(attachTo);
            attachment.setAttachToXPathExpression(expression);
        } catch (XPathExpressionException e) {
            ContributionReadException ce = new ContributionReadException(e);
            error(monitor, "ContributionReadException", attachment, ce);
        }
    }
}
Example 59
Project: webtools.sourceediting.xpath-master  File: StaticContextBuilder.java View source code
public NamespaceContext getNamespaceContext() {
    return new NamespaceContext() {

        public Iterator getPrefixes(String ns) {
            List prefixes = /*<String>*/
            new LinkedList();
            for (Iterator it = _namespaces.entrySet().iterator(); it.hasNext(); ) {
                Map.Entry entry = (Map.Entry) it.next();
                if (entry.getValue().equals(ns))
                    prefixes.add(entry.getKey());
            }
            return prefixes.iterator();
        }

        public String getPrefix(String ns) {
            for (Iterator it = _namespaces.entrySet().iterator(); it.hasNext(); ) {
                Map.Entry entry = (Map.Entry) it.next();
                if (entry.getValue().equals(ns)) {
                    return (String) entry.getKey();
                }
            }
            return null;
        }

        public String getNamespaceURI(String prefix) {
            String ns = (String) _namespaces.get(prefix);
            if (ns == null)
                ns = XMLConstants.NULL_NS_URI;
            return ns;
        }
    };
}
Example 60
Project: wikitext-master  File: SaxonWomXPath.java View source code
public static String womToWmXPath(NamespaceContext nsContext, Wom3Node doc) {
    NodeList nodes;
    try {
        nodes = evalXPath(doc, nsContext, "" + "//wom:text[not(ancestor::wom:repl)]|" + "//wom:rtd[not(ancestor::wom:repl)]");
    } catch (XPathFactoryConfigurationException e) {
        throw new WrappedException(e);
    } catch (XPathExpressionException e) {
        throw new WrappedException(e);
    }
    StringBuilder sb = new StringBuilder();
    for (int j = 0; j < nodes.getLength(); ++j) sb.append(((Element) nodes.item(j)).getTextContent());
    return sb.toString();
}
Example 61
Project: xcurator-master  File: NsContextTest.java View source code
@Test
public void getNamespaceURITest() throws SAXException, IOException, ParserConfigurationException {
    Document dataDoc = (new XmlParser()).parse(NsContextTest.class.getResourceAsStream("/secxbrls/data/fb-20121231.xml"), -1);
    NamespaceContext nscontext = new NsContext(dataDoc.getDocumentElement());
    assertTrue("Namespace for prefix xbrli is incorrect or empty", nscontext.getNamespaceURI("xbrli").equals("http://www.xbrl.org/2003/instance"));
    assertTrue("Namespace for prefix country is incorrect or empty", nscontext.getNamespaceURI("country").equals("http://xbrl.sec.gov/country/2012-01-31"));
    assertTrue("Namespace for prefix dei is incorrect or empty", nscontext.getNamespaceURI("dei").equals("http://xbrl.sec.gov/dei/2012-01-31"));
    assertTrue("Namespace for prefix iso4217 is incorrect or empty", nscontext.getNamespaceURI("iso4217").equals("http://www.xbrl.org/2003/iso4217"));
    assertTrue("Namespace for prefix us-gaap is incorrect or empty", nscontext.getNamespaceURI("us-gaap").equals("http://fasb.org/us-gaap/2012-01-31"));
    assertTrue("Namespace for prefix fb is incorrect or empty", nscontext.getNamespaceURI("fb").equals("http://www.facebook.com/20121231"));
}
Example 62
Project: xmlsh-master  File: xdelattribute.java View source code
@SuppressWarnings("unchecked")
@Override
public int run(List<XValue> args) throws Exception {
    Options opts = new Options("a=attribute:+,v,e=element:+", SerializeOpts.getOptionDefs());
    opts.parse(args);
    args = opts.getRemainingArgs();
    List<QName> attrs = getQNames(opts.getOptValuesRequired("a"));
    boolean bExcept = opts.hasOpt("v");
    List<QName> elements = getQNames(opts.getOptValues("e"));
    XMLEventFactory mFactory = XMLEventFactory.newInstance();
    InputPort stdin = null;
    if (args.size() > 0)
        stdin = getInput(args.get(0));
    else
        stdin = getStdin();
    if (stdin == null)
        throw new InvalidArgumentException("Cannot open input");
    SerializeOpts sopts = getSerializeOpts(opts);
    XMLEventReader reader = stdin.asXMLEventReader(sopts);
    OutputPort stdout = getStdout();
    XMLEventWriter writer = stdout.asXMLEventWriter(sopts);
    stdout.setSystemId(stdin.getSystemId());
    XMLEvent e;
    while (reader.hasNext()) {
        e = (XMLEvent) reader.next();
        if (e.isStartElement()) {
            StartElement se = e.asStartElement();
            // Only look at elements in list, or all elements if null
            if (elements == null || matches(se.getName(), elements, false)) {
                // If matching (or excluding) attributes delete them
                Iterator<Attribute> iter = se.getAttributes();
                boolean bMatches = false;
                while (iter.hasNext()) {
                    Attribute attr = iter.next();
                    if (matches(attr.getName(), attrs, bExcept)) {
                        bMatches = true;
                        break;
                    }
                }
                // If any match then synthesize a new start element
                if (bMatches) {
                    Iterator namespaces = se.getNamespaces();
                    List<Attribute> newAttrs = new ArrayList<Attribute>();
                    iter = se.getAttributes();
                    while (iter.hasNext()) {
                        Attribute attr = iter.next();
                        if (!matches(attr.getName(), attrs, bExcept))
                            newAttrs.add(attr);
                    }
                    NamespaceContext nsc = se.getNamespaceContext();
                    e = mFactory.createStartElement(se.getName().getPrefix(), se.getName().getNamespaceURI(), se.getName().getLocalPart(), newAttrs.iterator(), namespaces, nsc);
                }
            }
        }
        writer.add(e);
    }
    // writer.add(reader);
    Util.safeClose(reader);
    Util.safeClose(writer);
    return 0;
}
Example 63
Project: balana-master  File: XPathFunction.java View source code
/**
     * Gets Xpath results
     *
     * @param contextNode
     * @param xpathValue
     * @return
     * @throws XPathExpressionException
     */
private NodeList getXPathResults(Node contextNode, String xpathValue) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    //see if the request root is in a namespace
    String namespace = contextNode.getNamespaceURI();
    // name spaces are used, so we need to lookup the correct
    // prefix to use in the search string
    NamedNodeMap namedNodeMap = contextNode.getAttributes();
    Map<String, String> nsMap = new HashMap<String, String>();
    for (int i = 0; i < namedNodeMap.getLength(); i++) {
        Node n = namedNodeMap.item(i);
        // we found the matching namespace, so get the prefix
        // and then break out
        String prefix = DOMHelper.getLocalName(n);
        String nodeValue = n.getNodeValue();
        nsMap.put(prefix, nodeValue);
    }
    //  name space would be there.
    if (XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace) || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)) {
        nsMap.put("xacml", namespace);
    }
    NamespaceContext namespaceContext = new DefaultNamespaceContext(nsMap);
    xpath.setNamespaceContext(namespaceContext);
    XPathExpression expression = xpath.compile(xpathValue);
    return (NodeList) expression.evaluate(contextNode, XPathConstants.NODESET);
}
Example 64
Project: boilerpipe-android-master  File: StAXStreamResultBuilder.java View source code
public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException {
    try {
        if (element.prefix.length() > 0) {
            fStreamWriter.writeStartElement(element.prefix, element.localpart, element.uri != null ? element.uri : "");
        } else if (element.uri != null) {
            fStreamWriter.writeStartElement(element.uri, element.localpart);
        } else {
            fStreamWriter.writeStartElement(element.localpart);
        }
        int size = fNamespaceContext.getDeclaredPrefixCount();
        final mf.javax.xml.namespace.NamespaceContext nc = fNamespaceContext.getNamespaceContext();
        for (int i = 0; i < size; ++i) {
            String prefix = fNamespaceContext.getDeclaredPrefixAt(i);
            String uri = nc.getNamespaceURI(prefix);
            if (prefix.length() == 0) {
                fStreamWriter.writeDefaultNamespace(uri != null ? uri : "");
            } else {
                fStreamWriter.writeNamespace(prefix, uri != null ? uri : "");
            }
        }
        size = attributes.getLength();
        for (int i = 0; i < size; ++i) {
            attributes.getName(i, fAttrName);
            if (fAttrName.prefix.length() > 0) {
                fStreamWriter.writeAttribute(fAttrName.prefix, fAttrName.uri != null ? fAttrName.uri : "", fAttrName.localpart, attributes.getValue(i));
            } else if (fAttrName.uri != null) {
                fStreamWriter.writeAttribute(fAttrName.uri, fAttrName.localpart, attributes.getValue(i));
            } else {
                fStreamWriter.writeAttribute(fAttrName.localpart, attributes.getValue(i));
            }
        }
    } catch (XMLStreamException e) {
        throw new XNIException(e);
    }
}
Example 65
Project: bpmn-miwg-tools-master  File: XPathUtil.java View source code
/**
	 * Builds an absolute XPath string from the given node.
	 * 
	 * @param node
	 * @param context namespace context used to determine correct namespace prefixes, see
	 *            {@link SignavioNamespaceContext}
	 * @return an XPath string or null (if no node was given)
	 */
public static String getXPathString(Node node, NamespaceContext context) {
    if (node == null) {
        return null;
    }
    LinkedList<String> xpathSteps = new LinkedList<String>();
    String string = getNodeString(node, context);
    xpathSteps.add(string);
    Node current;
    if (node instanceof Attr)
        current = ((Attr) node).getOwnerElement();
    else
        current = node.getParentNode();
    while (current != node.getOwnerDocument()) {
        xpathSteps.add(getNodeString(current, context));
        current = current.getParentNode();
    }
    StringBuffer buff = new StringBuffer();
    Iterator<String> it = xpathSteps.descendingIterator();
    while (it.hasNext()) {
        buff.append("/" + it.next());
    }
    return buff.toString();
}
Example 66
Project: checkstyle-xml-ext-master  File: XPathCheck.java View source code
/** {@inheritDoc} */
@Override
public void init() {
    super.init();
    //création du XPath 
    XPathFactory fabrique = null;
    try {
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl");
        fabrique = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
        ((XPathFactoryImpl) fabrique).getConfiguration().setLineNumbering(true);
    } catch (XPathFactoryConfigurationException ex) {
        log(0, "XPath engine error" + ex.getMessage());
        ex.printStackTrace();
        return;
    }
    XPath xpath = fabrique.newXPath();
    if (namespaces != null) {
        final Map<String, String> ns = new HashMap<String, String>();
        for (int index = 0; index < namespaces.length; index += 2) {
            ns.put(namespaces[index], namespaces[index + 1]);
        }
        xpath.setNamespaceContext(new NamespaceContext() {

            private Map<String, String> namespaceMap = ns;

            @Override
            public Iterator getPrefixes(String arg0) {
                //not used
                return null;
            }

            @Override
            public String getPrefix(String arg0) {
                //not used
                return null;
            }

            @Override
            public String getNamespaceURI(String prefix) {
                return namespaceMap.get(prefix);
            }
        });
    }
    try {
        itemExpression = xpath.compile(item);
        xPathExpression = xpath.compile(expression);
    } catch (XPathExpressionException ex) {
        log(0, "Invalid XPath expression: " + expression);
        ex.printStackTrace();
    }
}
Example 67
Project: ComplexEventProcessingPlatform-master  File: FileSystemUtil.java View source code
public static String readXmlNodeChildFromFile(String xPath, String path, NamespaceContext nsContext) {
    synchronized (path.intern()) {
        File f = new File(path);
        DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
        xmlFact.setNamespaceAware(nsContext != null);
        try {
            DocumentBuilder builder = xmlFact.newDocumentBuilder();
            Document doc = builder.parse(f);
            XPath xpath = XPathFactory.newInstance().newXPath();
            if (nsContext != null) {
                xpath.setNamespaceContext(nsContext);
            }
            String s = xpath.evaluate(xPath, doc);
            return s.trim();
        } catch (XPathExpressionException e) {
            return "";
        } catch (FileNotFoundException e) {
            return "";
        } catch (ParserConfigurationException e) {
            return "";
        } catch (SAXException e) {
            return "";
        } catch (IOException e) {
            return "";
        }
    }
}
Example 68
Project: eclipselink.runtime-master  File: XMLStreamWriterRecord.java View source code
public void openStartElement(XPathFragment xPathFragment, NamespaceResolver namespaceResolver) {
    super.openStartElement(xPathFragment, namespaceResolver);
    try {
        String namespaceURI = xPathFragment.getNamespaceURI();
        if (namespaceURI == null) {
            NamespaceContext namespaceContext = xmlStreamWriter.getNamespaceContext();
            if (null == namespaceContext) {
                xmlStreamWriter.writeStartElement(xPathFragment.getLocalName());
            } else {
                String defaultNamespace = namespaceContext.getNamespaceURI(Constants.EMPTY_STRING);
                xmlStreamWriter.writeStartElement(Constants.EMPTY_STRING, xPathFragment.getLocalName(), Constants.EMPTY_STRING);
                if (defaultNamespace != null && defaultNamespace.length() > 0) {
                    xmlStreamWriter.writeDefaultNamespace(Constants.EMPTY_STRING);
                }
            }
        } else {
            String prefix = getPrefixForFragment(xPathFragment);
            if (prefix == null) {
                prefix = Constants.EMPTY_STRING;
            }
            xmlStreamWriter.writeStartElement(prefix, xPathFragment.getLocalName(), namespaceURI);
            if (xPathFragment.isGeneratedPrefix()) {
                namespaceDeclaration(xPathFragment.getPrefix(), xPathFragment.getNamespaceURI());
            }
        }
        writePrefixMappings();
    } catch (XMLStreamException e) {
        throw XMLMarshalException.marshalException(e);
    }
}
Example 69
Project: fcrepo-master  File: TestMETSFedoraExtDOSerializer.java View source code
@Test
public void testTwoDataStreamsVersion() throws TransformerException, XpathException, XPathExpressionException {
    DigitalObject obj = createTestObject(FEDORA_OBJECT_3_0);
    final String dsID1 = "DS1";
    final String dsID2 = "DS2";
    // hugely randomly generated test data 
    DatastreamManagedContent ds1 = createMDatastream(dsID1, "aölksdiudshfljdsfnalj mdscmjlfjaö nsaölkjfsölkjfsöldkjfaöslfjasödflaöl".getBytes());
    DatastreamManagedContent ds2 = createMDatastream(dsID2, "älkfddöslfjsölkfjäaoiam,yjöoicncäaskcäaäöl kf,jvdhfkjh".getBytes());
    obj.addDatastreamVersion(ds1, true);
    obj.addDatastreamVersion(ds2, true);
    Document xml = doSerializeOrFail(obj);
    // was unable to do this with assertXpathsNotEqual() method
    // therefore do the assertions by xpath manually
    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new javax.xml.namespace.NamespaceContext() {

        @Override
        public Iterator<String> getPrefixes(String namespaceURI) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            return "METS";
        }

        @Override
        public String getNamespaceURI(String prefix) {
            return "http://www.loc.gov/METS/";
        }
    });
    XPathExpression expr = xp.compile("//METS:fileGrp[@ID='DS1']/METS:file");
    NodeList list = (NodeList) expr.evaluate(xml, XPathConstants.NODESET);
    String checksum1 = list.item(0).getAttributes().getNamedItem("CHECKSUM").toString();
    expr = xp.compile("//METS:fileGrp[@ID='DS2']/METS:file");
    list = (NodeList) expr.evaluate(xml, XPathConstants.NODESET);
    String checkSum2 = list.item(0).getAttributes().getNamedItem("CHECKSUM").toString();
    assertFalse(checksum1.equals(checkSum2));
}
Example 70
Project: federation-master  File: SamlRstHandlerUnitTestCase.java View source code
@Test
public void testIn() throws Exception {
    DelegatingHandler handler = new DelegatingHandler();
    MsgHandlerUnitTestCaseMessageContext msgContext = new MsgHandlerUnitTestCaseMessageContext();
    SOAPMessage soapMessage = get();
    msgContext.setMessage(soapMessage);
    handler.handleInbound(msgContext);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            if (prefix == null)
                throw new NullPointerException("Null prefix");
            if (prefix.equals(WSTrustConstants.PREFIX)) {
                return WSTrustConstants.BASE_NAMESPACE;
            } else if (prefix.equals(Constants.WSSE_PREFIX)) {
                return Constants.WSSE_NS;
            } else if (prefix.equals("wsu")) {
                return WSTrustConstants.WSU_NS;
            } else if (prefix.equals("wsa")) {
                return WSTrustConstants.WSA_NS;
            } else if (prefix.equals(SOAPConstants.SOAP_ENV_PREFIX)) {
                return SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE;
            }
            return null;
        }

        public Iterator getPrefixes(String namespaceURI) {
            // not necessary for XPath
            return null;
        }

        public String getPrefix(String namespaceURI) {
            return null;
        }
    });
    XPathExpression expr = xpath.compile("//env:Envelope/env:Body/wst:RequestSecurityToken/wsse:UsernameToken/wsse:Username/text()");
    NodeList nl = (NodeList) expr.evaluate(soapMessage.getSOAPPart().getDocumentElement(), XPathConstants.NODESET);
    String result = (nl.getLength() == 1 ? nl.item(0).getTextContent() : null);
    assertEquals("Admin user has to be added", ADMIN, result);
}
Example 71
Project: FiWare-Template-Handler-master  File: FileSystemUtil.java View source code
public static String readXmlNodeChildFromFile(String xPath, String path, NamespaceContext nsContext) {
    synchronized (path.intern()) {
        File f = new File(path);
        DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
        xmlFact.setNamespaceAware(nsContext != null);
        try {
            DocumentBuilder builder = xmlFact.newDocumentBuilder();
            Document doc = builder.parse(f);
            XPath xpath = XPathFactory.newInstance().newXPath();
            if (nsContext != null) {
                xpath.setNamespaceContext(nsContext);
            }
            String s = xpath.evaluate(xPath, doc);
            return s.trim();
        } catch (XPathExpressionException e) {
            return "";
        } catch (FileNotFoundException e) {
            return "";
        } catch (ParserConfigurationException e) {
            return "";
        } catch (SAXException e) {
            return "";
        } catch (IOException e) {
            return "";
        }
    }
}
Example 72
Project: flex-falcon-master  File: GenerateManifestsMojo.java View source code
private Map<String, Map<String, String>> getNamespacesFromLibrary(File library) {
    Map<String, Map<String, String>> namespaces = new HashMap<String, Map<String, String>>();
    try {
        // Open the file as a zip
        byte[] catalogBytes = null;
        FileInputStream fin = new FileInputStream(library);
        BufferedInputStream bin = new BufferedInputStream(fin);
        ZipInputStream zin = new ZipInputStream(bin);
        ZipEntry ze;
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.getName().equals("catalog.xml")) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                int len;
                while ((len = zin.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                out.close();
                catalogBytes = out.toByteArray();
                break;
            }
        }
        // Read the catalog.xml file inside.
        if (catalogBytes != null) {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document catalog = builder.parse(new ByteArrayInputStream(catalogBytes));
                XPath xpath = XPathFactory.newInstance().newXPath();
                xpath.setNamespaceContext(new NamespaceContext() {

                    public String getNamespaceURI(String prefix) {
                        return prefix.equals("cat") ? "http://www.adobe.com/flash/swccatalog/9" : null;
                    }

                    public Iterator getPrefixes(String val) {
                        return null;
                    }

                    public String getPrefix(String uri) {
                        return null;
                    }
                });
                XPathExpression expr = xpath.compile("/cat:swc/cat:components/cat:component");
                Object result = expr.evaluate(catalog, XPathConstants.NODESET);
                NodeList nodes = (NodeList) result;
                for (int i = 0; i < nodes.getLength(); i++) {
                    Element componentElement = (Element) nodes.item(i);
                    String className = componentElement.getAttribute("className");
                    String name = componentElement.getAttribute("name");
                    String uri = componentElement.getAttribute("uri");
                    if (!namespaces.containsKey(uri)) {
                        namespaces.put(uri, new HashMap<String, String>());
                    }
                    namespaces.get(uri).put(name, className);
                }
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (XPathExpressionException e) {
                e.printStackTrace();
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return namespaces;
}
Example 73
Project: gda-common-master  File: SchemaReader.java View source code
private NamespaceContext getXSDContext() {
    return new NamespaceContext() {

        @Override
        public String getNamespaceURI(String prefix) {
            if ("xsd".equals(prefix)) {
                return nameSpaceURI;
            }
            return null;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            // TODO Auto-generated method stub
            return null;
        }

        @SuppressWarnings("rawtypes")
        @Override
        public Iterator getPrefixes(String namespaceURI) {
            // TODO Auto-generated method stub
            return null;
        }
    };
}
Example 74
Project: geotools-2.7.x-master  File: DatatypeConverterImpl.java View source code
public QName parseQName(String arg0, NamespaceContext arg1) {
    int offset = arg0.indexOf(':');
    String uri;
    String localName;
    switch(offset) {
        case -1:
            localName = arg0;
            uri = arg1.getNamespaceURI("");
            if (uri == null) {
                // Should not happen, indicates an error in the NamespaceContext implementation
                throw new IllegalArgumentException("The default prefix is not bound.");
            }
            break;
        case 0:
            throw new IllegalArgumentException("Default prefix must be indicated by not using a colon: " + arg0);
        default:
            String prefix = arg0.substring(0, offset);
            localName = arg0.substring(offset + 1);
            uri = arg1.getNamespaceURI(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("The prefix " + prefix + " is not bound.");
            }
    }
    return new QName(uri, localName);
}
Example 75
Project: geotools-master  File: DatatypeConverterImpl.java View source code
public QName parseQName(String arg0, NamespaceContext arg1) {
    int offset = arg0.indexOf(':');
    String uri;
    String localName;
    switch(offset) {
        case -1:
            localName = arg0;
            uri = arg1.getNamespaceURI("");
            if (uri == null) {
                // Should not happen, indicates an error in the NamespaceContext implementation
                throw new IllegalArgumentException("The default prefix is not bound.");
            }
            break;
        case 0:
            throw new IllegalArgumentException("Default prefix must be indicated by not using a colon: " + arg0);
        default:
            String prefix = arg0.substring(0, offset);
            localName = arg0.substring(offset + 1);
            uri = arg1.getNamespaceURI(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("The prefix " + prefix + " is not bound.");
            }
    }
    return new QName(uri, localName);
}
Example 76
Project: geotools-old-master  File: DatatypeConverterImpl.java View source code
public QName parseQName(String arg0, NamespaceContext arg1) {
    int offset = arg0.indexOf(':');
    String uri;
    String localName;
    switch(offset) {
        case -1:
            localName = arg0;
            uri = arg1.getNamespaceURI("");
            if (uri == null) {
                // Should not happen, indicates an error in the NamespaceContext implementation
                throw new IllegalArgumentException("The default prefix is not bound.");
            }
            break;
        case 0:
            throw new IllegalArgumentException("Default prefix must be indicated by not using a colon: " + arg0);
        default:
            String prefix = arg0.substring(0, offset);
            localName = arg0.substring(offset + 1);
            uri = arg1.getNamespaceURI(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("The prefix " + prefix + " is not bound.");
            }
    }
    return new QName(uri, localName);
}
Example 77
Project: geotools-tike-master  File: DatatypeConverterImpl.java View source code
public QName parseQName(String arg0, NamespaceContext arg1) {
    int offset = arg0.indexOf(':');
    String uri;
    String localName;
    switch(offset) {
        case -1:
            localName = arg0;
            uri = arg1.getNamespaceURI("");
            if (uri == null) {
                // Should not happen, indicates an error in the NamespaceContext implementation
                throw new IllegalArgumentException("The default prefix is not bound.");
            }
            break;
        case 0:
            throw new IllegalArgumentException("Default prefix must be indicated by not using a colon: " + arg0);
        default:
            String prefix = arg0.substring(0, offset);
            localName = arg0.substring(offset + 1);
            uri = arg1.getNamespaceURI(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("The prefix " + prefix + " is not bound.");
            }
    }
    return new QName(uri, localName);
}
Example 78
Project: geotools_trunk-master  File: DatatypeConverterImpl.java View source code
public QName parseQName(String arg0, NamespaceContext arg1) {
    int offset = arg0.indexOf(':');
    String uri;
    String localName;
    switch(offset) {
        case -1:
            localName = arg0;
            uri = arg1.getNamespaceURI("");
            if (uri == null) {
                // Should not happen, indicates an error in the NamespaceContext implementation
                throw new IllegalArgumentException("The default prefix is not bound.");
            }
            break;
        case 0:
            throw new IllegalArgumentException("Default prefix must be indicated by not using a colon: " + arg0);
        default:
            String prefix = arg0.substring(0, offset);
            localName = arg0.substring(offset + 1);
            uri = arg1.getNamespaceURI(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("The prefix " + prefix + " is not bound.");
            }
    }
    return new QName(uri, localName);
}
Example 79
Project: JamVM-PH-master  File: FunctionAvailableFunction.java View source code
public Expr clone(Object context) {
    NamespaceContext n = nsctx;
    if (context instanceof NamespaceContext)
        n = (NamespaceContext) context;
    FunctionAvailableFunction f = new FunctionAvailableFunction(n);
    int len = args.size();
    List args2 = new ArrayList(len);
    for (int i = 0; i < len; i++) args2.add(((Expr) args.get(i)).clone(context));
    f.setArguments(args2);
    return f;
}
Example 80
Project: JavaHamcrest-master  File: HasXPath.java View source code
private static XPathExpression compiledXPath(String xPathExpression, NamespaceContext namespaceContext) {
    try {
        final XPath xPath = XPathFactory.newInstance().newXPath();
        if (namespaceContext != null) {
            xPath.setNamespaceContext(namespaceContext);
        }
        return xPath.compile(xPathExpression);
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException("Invalid XPath : " + xPathExpression, e);
    }
}
Example 81
Project: JBossAS51-master  File: JavaBeanSchemaInitializer.java View source code
public void attributes(Object o, QName elementName, ElementBinding element, Attributes attrs, NamespaceContext nsCtx) {
    Holder holder = (Holder) o;
    String className = null;
    Properties properties = holder.getProperties();
    for (int i = 0; i < attrs.getLength(); ++i) {
        String localName = attrs.getLocalName(i);
        String value = attrs.getValue(i);
        if ("class".equals(localName)) {
            className = value;
            holder.setType(className);
            continue;
        }
        properties.put(localName, value);
    }
    if (className == null)
        throw new IllegalArgumentException("No class attribute for " + elementName);
}
Example 82
Project: JBossAS_5_1_EDG-master  File: JavaBeanSchemaInitializer.java View source code
public void attributes(Object o, QName elementName, ElementBinding element, Attributes attrs, NamespaceContext nsCtx) {
    Holder holder = (Holder) o;
    String className = null;
    Properties properties = holder.getProperties();
    for (int i = 0; i < attrs.getLength(); ++i) {
        String localName = attrs.getLocalName(i);
        String value = attrs.getValue(i);
        if ("class".equals(localName)) {
            className = value;
            holder.setType(className);
            continue;
        }
        properties.put(localName, value);
    }
    if (className == null)
        throw new IllegalArgumentException("No class attribute for " + elementName);
}
Example 83
Project: jdom-master  File: JDOMNamespaceContext.java View source code
@Override
public String getNamespaceURI(final String prefix) {
    if (prefix == null) {
        throw new IllegalArgumentException("NamespaceContext requires a non-null prefix");
    }
    if (JDOMConstants.NS_PREFIX_XML.equals(prefix)) {
        return JDOMConstants.NS_URI_XML;
    }
    if (JDOMConstants.NS_PREFIX_XMLNS.equals(prefix)) {
        return JDOMConstants.NS_URI_XMLNS;
    }
    for (final Namespace n : namespacearray) {
        if (n.getPrefix().equals(prefix)) {
            return n.getURI();
        }
    }
    return "";
}
Example 84
Project: jruby-cxf-master  File: ElementReader.java View source code
private void extractXsiType() {
    /*
         * We're making a conscious choice here -- garbage in == garbage out.
         */
    String xsiTypeQname = root.getAttributeValue(SOAPConstants.XSI_NS, "type");
    if (xsiTypeQname != null) {
        Matcher m = QNAME_PATTERN.matcher(xsiTypeQname);
        if (m.matches()) {
            NamespaceContext nc = root.getNamespaceContext();
            this.xsiType = new QName(nc.getNamespaceURI(m.group(1)), m.group(2), m.group(1));
        } else {
            this.xsiType = new QName(this.namespace, xsiTypeQname, "");
        }
    }
}
Example 85
Project: jvarkit-master  File: VcfFilterXPath.java View source code
@Override
public int doWork(List<String> args) {
    if (this.infoTag == null || this.infoTag.isEmpty()) {
        LOG.error("Info Tag is undefined");
        return -1;
    }
    if (this.xpathExpression == null || this.xpathExpression.isEmpty()) {
        LOG.error("XPath Expression is undefined");
        return -1;
    }
    for (final String s : __prefix2uri) {
        int eq = s.indexOf('=');
        if (eq <= 0) {
            LOG.error("'=' missing in " + s);
            return -1;
        }
        this.prefix2uri.put(s.substring(0, eq), s.substring(eq + 1));
    }
    try {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        xpath.setXPathVariableResolver(new XPathVariableResolver() {

            @Override
            public Object resolveVariable(QName qname) {
                return xpathVariableMap.get(qname);
            }
        });
        xpath.setNamespaceContext(new NamespaceContext() {

            @Override
            public Iterator<? extends Object> getPrefixes(String namespaceURI) {
                List<String> L = new ArrayList<>();
                for (String pfx : prefix2uri.keySet()) {
                    if (prefix2uri.get(pfx).equals(namespaceURI)) {
                        L.add(pfx);
                    }
                }
                return L.iterator();
            }

            @Override
            public String getPrefix(String namespaceURI) {
                for (String pfx : prefix2uri.keySet()) {
                    if (prefix2uri.get(pfx).equals(namespaceURI)) {
                        return pfx;
                    }
                }
                return null;
            }

            @Override
            public String getNamespaceURI(String prefix) {
                return prefix2uri.get(prefix);
            }
        });
        this.xpathExpr = xpath.compile(this.xpathExpression);
        return doVcfToVcf(args, outputFile);
    } catch (Exception er) {
        LOG.error(er);
        return -1;
    }
}
Example 86
Project: logback-master  File: XMLLayoutTest.java View source code
/**
    * Create a XPath instance with xmlns:log4j="http://jakarta.apache.org/log4j/"
    * 
    * @return XPath instance with log4 namespace
    */
private XPath newXPath() {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {

        @SuppressWarnings("rawtypes")
        public Iterator getPrefixes(String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        public String getPrefix(String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        public String getNamespaceURI(String prefix) {
            if ("log4j".equals(prefix)) {
                return NAMESPACE;
            } else {
                return XMLConstants.NULL_NS_URI;
            }
        }
    });
    return xpath;
}
Example 87
Project: picketlink-bindings-master  File: SamlRstHandlerUnitTestCase.java View source code
@Test
public void testIn() throws Exception {
    DelegatingHandler handler = new DelegatingHandler();
    MsgHandlerUnitTestCaseMessageContext msgContext = new MsgHandlerUnitTestCaseMessageContext();
    SOAPMessage soapMessage = get();
    msgContext.setMessage(soapMessage);
    handler.handleInbound(msgContext);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            if (prefix == null)
                throw new NullPointerException("Null prefix");
            if (prefix.equals(WSTrustConstants.PREFIX)) {
                return WSTrustConstants.BASE_NAMESPACE;
            } else if (prefix.equals(Constants.WSSE_PREFIX)) {
                return Constants.WSSE_NS;
            } else if (prefix.equals("wsu")) {
                return WSTrustConstants.WSU_NS;
            } else if (prefix.equals("wsa")) {
                return WSTrustConstants.WSA_NS;
            } else if (prefix.equals(SOAPConstants.SOAP_ENV_PREFIX)) {
                return SOAPConstants.URI_NS_SOAP_1_1_ENVELOPE;
            }
            return null;
        }

        public Iterator getPrefixes(String namespaceURI) {
            // not necessary for XPath
            return null;
        }

        public String getPrefix(String namespaceURI) {
            return null;
        }
    });
    XPathExpression expr = xpath.compile("//env:Envelope/env:Body/wst:RequestSecurityToken/wsse:UsernameToken/wsse:Username/text()");
    NodeList nl = (NodeList) expr.evaluate(soapMessage.getSOAPPart().getDocumentElement(), XPathConstants.NODESET);
    String result = (nl.getLength() == 1 ? nl.item(0).getTextContent() : null);
    assertEquals("Admin user has to be added", ADMIN, result);
}
Example 88
Project: pig-master  File: XPath.java View source code
/**
     * input should contain: 1) xml 2) xpath 
     *                       3) optional cache xml doc flag 
     *                       4) optional ignore namespace flag
     * 
     * Usage:
     * 1) XPath(xml, xpath)
     * 2) XPath(xml, xpath, false) 
     * 3) XPath(xml, xpath, false, false)
     * 
     * @param input
     * 		  1st element should to be the xml
     *        2nd element should be the xpath
     *        3rd optional boolean cache flag (default true)
     *        4th optional boolean ignore namespace flag (default true)
     *        
     * 
      *        This UDF will cache the last xml document. This is helpful when
     *        multiple consecutive xpathAll calls are made for the same xml
     *        document. Caching can be turned off to ensure that the UDF's
     *        recreates the internal javax.xml.xpath.XPathAll for every call
     *        
     *        This UDF will also support ignoring the namespace in the xml tags.
     *        This will help to search xpath items by ignoring its namespace.
     *        Ignoring of the namespace can be turned off for special cases using
     *        a fourth argument in the UDF. 
     * 
     * @return chararrary result or null if no match
     */
@Override
public String exec(final Tuple input) throws IOException {
    if (!isArgsValid(input)) {
        // Validate arguments
        return null;
    }
    try {
        final String xml = (String) input.get(0);
        if (xml == null) {
            return null;
        }
        if (input.size() > 2) {
            cache = (Boolean) input.get(2);
        }
        if (input.size() > 3) {
            ignoreNamespace = (Boolean) input.get(3);
        }
        if (!cache || xpath == null || !xml.equals(this.xml)) {
            final InputSource source = new InputSource(new StringReader(xml));
            // track the xml for subsequent calls to this udf
            this.xml = xml;
            final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(!ignoreNamespace);
            final DocumentBuilder db = dbf.newDocumentBuilder();
            this.document = db.parse(source);
            final XPathFactory xpathFactory = XPathFactory.newInstance();
            this.xpath = xpathFactory.newXPath();
            if (!ignoreNamespace) {
                xpath.setNamespaceContext(new NamespaceContext() {

                    @Override
                    public String getNamespaceURI(String prefix) {
                        if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
                            return document.lookupNamespaceURI(null);
                        } else {
                            return document.lookupNamespaceURI(prefix);
                        }
                    }

                    @Override
                    public String getPrefix(String namespaceURI) {
                        return document.lookupPrefix(namespaceURI);
                    }

                    @Override
                    public Iterator getPrefixes(String namespaceURI) {
                        return null;
                    }
                });
            }
        }
        String xpathString = (String) input.get(1);
        final String value = xpath.evaluate(xpathString, document);
        return value;
    } catch (Exception e) {
        warn("Error processing input " + input.getType(0), PigWarning.UDF_WARNING_1);
        return null;
    }
}
Example 89
Project: ProcessPuzzleFramework-master  File: PropertyContextTest.java View source code
private void determineExpectedValues() {
    String customConfigurationPath = CONFIGURATION_DESCRIPTOR_PATH.substring(0, CONFIGURATION_DESCRIPTOR_PATH.indexOf("configuration_descriptor.xml")) + "custom_configuration.xml";
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    ResourceLoader loader = null;
    Resource resource = null;
    NamespaceContext context = new ProcessPuzzleContextNamespace();
    xPath.setNamespaceContext(context);
    loader = (ResourceLoader) new DefaultResourceLoader();
    resource = loader.getResource(customConfigurationPath);
    determineConnectionUrl(xPath, resource);
    determineExpectedWorkingDirectory(xPath, resource);
}
Example 90
Project: RoboBuggy-master  File: HasXPath.java View source code
private static XPathExpression compiledXPath(String xPathExpression, NamespaceContext namespaceContext) {
    try {
        final XPath xPath = XPathFactory.newInstance().newXPath();
        if (namespaceContext != null) {
            xPath.setNamespaceContext(namespaceContext);
        }
        return xPath.compile(xPathExpression);
    } catch (XPathExpressionException e) {
        throw new IllegalArgumentException("Invalid XPath : " + xPathExpression, e);
    }
}
Example 91
Project: signavio-core-mirror-master  File: FileSystemUtil.java View source code
public static String readXmlNodeChildFromFile(String xPath, String path, NamespaceContext nsContext) {
    synchronized (path.intern()) {
        File f = new File(path);
        DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance();
        xmlFact.setNamespaceAware(nsContext != null);
        try {
            DocumentBuilder builder = xmlFact.newDocumentBuilder();
            Document doc = builder.parse(f);
            XPath xpath = XPathFactory.newInstance().newXPath();
            if (nsContext != null) {
                xpath.setNamespaceContext(nsContext);
            }
            String s = xpath.evaluate(xPath, doc);
            return s.trim();
        } catch (XPathExpressionException e) {
            return "";
        } catch (FileNotFoundException e) {
            return "";
        } catch (ParserConfigurationException e) {
            return "";
        } catch (SAXException e) {
            return "";
        } catch (IOException e) {
            return "";
        }
    }
}
Example 92
Project: sonar-plugins-master  File: StyleCopGenerator.java View source code
/**
   * Generates the msbuild configuration for a project.
   * 
   * @param stream
   */
public void generate(OutputStream stream) {
    Project project = new Project();
    // Properties used
    PropertyGroup propGroup = new PropertyGroup();
    propGroup.setProjectRoot(toWindowsPath(projectRoot));
    propGroup.setStyleCopRoot(toWindowsPath(styleCopRoot));
    // StyleCop task definition
    UsingTask usingTask = new UsingTask();
    usingTask.setAssemblyFile("$(StyleCopRoot)\\Microsoft.StyleCop.dll");
    usingTask.setTaskName("StyleCopTask");
    // StyleCop execution target
    Target target = new Target();
    target.setName("CheckStyle");
    StyleCopTask task = new StyleCopTask();
    task.setFullPath(toWindowsPath(visualSolution));
    task.setOutputFile(toWindowsPath(output));
    task.setSettingsFile(toWindowsPath(settings));
    task.setSourceFiles("@(SourceAnalysisFiles);@(CSFile)");
    // Builds the creation item
    CreateItem createItem = new CreateItem();
    createItem.setInclude("%(Project.RootDir)%(Project.Directory)**\\*.cs");
    ItemOutput itemOutput = new ItemOutput();
    itemOutput.setTaskParameter("Include");
    itemOutput.setItemName("SourceAnalysisFiles");
    createItem.setOutput(itemOutput);
    //
    ItemGroup group = new ItemGroup();
    // Adds all the projects files
    for (File visualProject : visualProjects) {
        if (visualProject.isDirectory()) {
            group.addCsFiles(visualProject + "\\**\\*.cs");
        } else {
            group.addProject(toWindowsPath(visualProject));
        }
    }
    // Populates the task
    target.setItem(createItem);
    target.setStyleCopTask(task);
    // Finishes the project
    project.setUsingTask(usingTask);
    project.setPropertyGroup(propGroup);
    project.setDefaultTargets("CheckStyle");
    project.setToolsVersion("3.5");
    project.addItem(group);
    project.addTarget(target);
    XMLOutputFactory xof = XMLOutputFactory.newInstance();
    StringWriter writer = new StringWriter();
    XMLStreamWriter xtw = null;
    try {
        // Gets control of the generated namespaces
        xtw = xof.createXMLStreamWriter(writer);
        xtw.setNamespaceContext(new NamespaceContext() {

            @Override
            public Iterator getPrefixes(String arg0) {
                return null;
            }

            @Override
            public String getPrefix(String arg0) {
                if (STYLE_COP_NAMESPACE.equals(arg0)) {
                    return "stylecop";
                }
                return null;
            }

            @Override
            public String getNamespaceURI(String arg0) {
                return null;
            }
        });
        // Establish a jaxb context
        JAXBContext jc = JAXBContext.newInstance(Project.class);
        // Get a marshaller
        Marshaller m = jc.createMarshaller();
        // Enable formatted xml output
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        // Marshal to system output: java to xml
        m.marshal(project, xtw);
    } catch (Exception e) {
        log.debug("Generation error", e);
    }
    String xmlContent = writer.toString();
    // Due to a bug of missing feature in JAXB, I could not generate an XML file
    // having the default XML namespace
    // of stylecop (it defines the objects in a namespace that is not the
    // default).
    // The problem is that MSBuild is non fully XML compliant and requires the
    // stylecop namespace as being explicitely
    // the default one for the file. This is achived by hand-made replacement in
    // hte generated file, hoping for something
    // more robust later.
    String temp = StringUtils.replace(xmlContent, "xmlns=\"\"", "xmlns=\"" + STYLE_COP_NAMESPACE + "\"");
    String result = StringUtils.replace(temp, "stylecop:Project", "Project");
    PrintWriter outputWriter = new PrintWriter(stream);
    outputWriter.print(result);
    outputWriter.flush();
}
Example 93
Project: topic-modeling-master  File: StAXStreamResultBuilder.java View source code
public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException {
    try {
        if (element.prefix.length() > 0) {
            fStreamWriter.writeStartElement(element.prefix, element.localpart, element.uri != null ? element.uri : "");
        } else if (element.uri != null) {
            fStreamWriter.writeStartElement(element.uri, element.localpart);
        } else {
            fStreamWriter.writeStartElement(element.localpart);
        }
        int size = fNamespaceContext.getDeclaredPrefixCount();
        final javax.xml.namespace.NamespaceContext nc = fNamespaceContext.getNamespaceContext();
        for (int i = 0; i < size; ++i) {
            String prefix = fNamespaceContext.getDeclaredPrefixAt(i);
            String uri = nc.getNamespaceURI(prefix);
            if (prefix.length() == 0) {
                fStreamWriter.writeDefaultNamespace(uri != null ? uri : "");
            } else {
                fStreamWriter.writeNamespace(prefix, uri != null ? uri : "");
            }
        }
        size = attributes.getLength();
        for (int i = 0; i < size; ++i) {
            attributes.getName(i, fAttrName);
            if (fAttrName.prefix.length() > 0) {
                fStreamWriter.writeAttribute(fAttrName.prefix, fAttrName.uri != null ? fAttrName.uri : "", fAttrName.localpart, attributes.getValue(i));
            } else if (fAttrName.uri != null) {
                fStreamWriter.writeAttribute(fAttrName.uri, fAttrName.localpart, attributes.getValue(i));
            } else {
                fStreamWriter.writeAttribute(fAttrName.localpart, attributes.getValue(i));
            }
        }
    } catch (XMLStreamException e) {
        throw new XNIException(e);
    }
}
Example 94
Project: Tundra.java-master  File: DocumentHelper.java View source code
/**
     * Parses the given content to an XML document.
     *
     * @param content           The XML content to parse.
     * @param namespaceContext  Any namespace declarations used in the XML content.
     * @return                  The parsed XML document.
     * @throws ServiceException If a parsing or I/O error occurs.
     */
public static Document parse(InputSource content, NamespaceContext namespaceContext) throws ServiceException {
    if (content == null)
        return null;
    Document document = null;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(namespaceContext != null);
        factory.setExpandEntityReferences(true);
        factory.setIgnoringElementContentWhitespace(true);
        factory.setIgnoringComments(true);
        DocumentBuilder parser = factory.newDocumentBuilder();
        document = parser.parse(content);
    } catch (ParserConfigurationException ex) {
        ExceptionHelper.raise(ex);
    } catch (SAXException ex) {
        ExceptionHelper.raise(ex);
    } catch (IOException ex) {
        ExceptionHelper.raise(ex);
    }
    return document;
}
Example 95
Project: web-feature-service-master  File: FeatureTypeHandler.java View source code
public Set<QName> getFeatureTypeNames(Collection<String> featureTypeNames, NamespaceContext namespaceContext, boolean canBeEmpty, String handle) throws WFSException {
    Set<QName> result = new HashSet<QName>();
    for (String featureTypeName : featureTypeNames) {
        String candidate = featureTypeName;
        boolean isSchemaElementFunction = false;
        // implemented, the function itself is not supported in the following.
        if (featureTypeName.startsWith("schema-element")) {
            Pattern pattern = Pattern.compile("schema-element\\((.+)\\)$");
            Matcher matcher = pattern.matcher(featureTypeName);
            if (matcher.matches()) {
                candidate = matcher.group(1);
                isSchemaElementFunction = true;
            } else
                throw new WFSException(WFSExceptionCode.INVALID_PARAMETER_VALUE, "Invalid schema-element() function: '" + featureTypeName + "'.", handle);
        }
        String namespacePrefix = null;
        String namespaceURI = null;
        String localPart = null;
        String[] parts = candidate.split(":");
        if (parts.length == 1) {
            namespacePrefix = XMLConstants.DEFAULT_NS_PREFIX;
            localPart = parts[0];
        } else if (parts.length == 2) {
            namespacePrefix = parts[0];
            localPart = parts[1];
        } else
            throw new WFSException(WFSExceptionCode.INVALID_PARAMETER_VALUE, "Invalid feature type name: '" + candidate + "'.", handle);
        namespaceURI = namespaceContext.getNamespaceURI(namespacePrefix);
        if (namespaceURI == null)
            throw new WFSException(WFSExceptionCode.INVALID_PARAMETER_VALUE, "The feature type name '" + candidate + "' lacks a namespace declaration.", handle);
        QName qName = new QName(namespaceURI, localPart);
        if (!isSchemaElementFunction)
            result.add(qName);
        else
            result.addAll(resolveSchemaElementFunction(qName, handle));
    }
    return getFeatureTypeNames(result, canBeEmpty, handle);
}
Example 96
Project: weblounge-master  File: SiteAdminImpl.java View source code
/**
   * Initializes this admin object by reading all information from the
   * <code>XML</code> configuration node.
   * 
   * @param userNode
   *          the <code>XML</code> node containing the admin configuration
   * @param site
   *          the associated site
   */
public static SiteAdminImpl fromXml(Node userNode, Site site) throws IllegalStateException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    // Define the xml namespace
    xpath.setNamespaceContext(new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            return "ns".equals(prefix) ? SiteImpl.SITE_XMLNS : null;
        }

        public String getPrefix(String namespaceURI) {
            return null;
        }

        public Iterator<?> getPrefixes(String namespaceURI) {
            return null;
        }
    });
    return fromXml(userNode, site, xpath);
}
Example 97
Project: XFlat-master  File: JDOMNamespaceContext.java View source code
@Override
public String getNamespaceURI(final String prefix) {
    if (prefix == null) {
        throw new IllegalArgumentException("NamespaceContext requires a non-null prefix");
    }
    if (JDOMConstants.NS_PREFIX_XML.equals(prefix)) {
        return JDOMConstants.NS_URI_XML;
    }
    if (JDOMConstants.NS_PREFIX_XMLNS.equals(prefix)) {
        return JDOMConstants.NS_URI_XMLNS;
    }
    for (final Namespace n : namespacearray) {
        if (n.getPrefix().equals(prefix)) {
            return n.getURI();
        }
    }
    return "";
}
Example 98
Project: JFugue-for-Android-master  File: XPathImpl.java View source code
/**
     * <p>Establishes a namespace context.</p>
     *
     * @param nsContext Namespace context to use
     */
public void setNamespaceContext(NamespaceContext nsContext) {
    if (nsContext == null) {
        String fmsg = XSLMessages.createXPATHMessage(XPATHErrorResources.ER_ARG_CANNOT_BE_NULL, new Object[] { "NamespaceContext" });
        throw new NullPointerException(fmsg);
    }
    this.namespaceContext = nsContext;
    this.prefixResolver = new JAXPPrefixResolver(nsContext);
}
Example 99
Project: AGIA-master  File: SimpleNodeFactory.java View source code
private String getPathElement(String sName, String sDefaultPrefix, NamespaceContext sContext) {
    StringBuilder aPathElement = new StringBuilder();
    QName aQName = new QName(sName, sContext);
    aPathElement.append(((aQName.getPrefix() != null) && (aQName.getPrefix().length() > 0)) ? aQName.getPrefix() : sDefaultPrefix);
    aPathElement.append(":");
    aPathElement.append(((aQName.getNamespaceURI() != null) && (aQName.getNamespaceURI().length() > 0)) ? aQName.getLocalName() : ISO9075.encode(aQName.getLocalName()));
    return aPathElement.toString();
}
Example 100
Project: ambra-master  File: XPathUtil.java View source code
/**
   * Set the namespace context to be used by this instance of Xpath.  This enables the selection of namespaced
   * attributes and nodes (i.e. nodes and attributes with a colon in them)
   *
   * @param pairs - a String array where each entry is of the form prefix=namespaceURI.  In an XML document, the
   *                   prefix is the part that comes just after the xmlns part, and the namespaceURI is the value of
   *                   that attribute. E.g. to use the namespaces from the document below
   *                   <pre>
   *                     <rootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
   *                     ...
   *                     </rootNode>
   *                   </pre>
   *                   you would pass in an array like <pre>{"xsi=http://www.w3.org/2001/XMLSchema-instance","web:http=//java.sun.com/xml/ns/javaee/web-app_2_5.xsd"}</pre>
   */
public void setNamespaceContext(final String[] pairs) {
    xPath.setNamespaceContext(new NamespaceContext() {

        @Override
        public String getNamespaceURI(String prefix) {
            for (String namespace : pairs) {
                if (namespace.startsWith(prefix + "=")) {
                    return namespace.substring(namespace.indexOf("=") + 1);
                }
            }
            return null;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            for (String namespace : pairs) {
                if (namespace.endsWith(namespaceURI)) {
                    return namespace.substring(0, namespace.indexOf("="));
                }
            }
            return null;
        }

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            return null;
        }
    });
}
Example 101
Project: atricore-idbus-master  File: SamlR2MetadataDefinitionIntrospector.java View source code
protected NamespaceContext getNamespaceContext() {
    return new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            if (prefix.equals(SAMLR2_MD_LOCAL_NS))
                return SAMLR2Constants.SAML_METADATA_NS;
            return null;
        }

        // Dummy implementation - not used!
        public Iterator getPrefixes(String val) {
            return null;
        }

        // Dummy implemenation - not used!
        public String getPrefix(String uri) {
            if (uri.equals(SAMLR2Constants.SAML_METADATA_NS))
                return SAMLR2_MD_LOCAL_NS;
            return null;
        }
    };
}