Example usage for javax.xml.namespace NamespaceContext NamespaceContext

List of usage examples for javax.xml.namespace NamespaceContext NamespaceContext

Introduction

In this page you can find the example usage for javax.xml.namespace NamespaceContext NamespaceContext.

Prototype

NamespaceContext

Source Link

Usage

From source file:Main.java

public static NamespaceContext getNamespaceContext(final String prefix, final String uri) {
    return new NamespaceContext() {
        @Override/*from  w  w w .j  a v a  2 s  .  c  om*/
        public String getNamespaceURI(String prefix) {
            return uri;
        }

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

        @Override
        public Iterator<String> getPrefixes(String uri) {
            ArrayList<String> prefixes = new ArrayList<String>();
            prefixes.add(prefix);
            return prefixes.iterator();
        }
    };
}

From source file:Main.java

/**
 * @return/*from   w  w w  . ja  v a  2 s  . co  m*/
 */
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;
}

From source file:Main.java

public static String getProcessIdFromBpmn(final String bpmn) {
    String processId = null;/*ww w  .j a  v a  2 s  . c o m*/
    try {
        final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        final Document doc = domFactory.newDocumentBuilder()
                .parse(new ByteArrayInputStream(bpmn.getBytes("UTF-8")));
        final XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(new NamespaceContext() {
            @Override
            public Iterator<?> getPrefixes(final String namespaceURI) {
                // Not used in this context.
                return null;
            }

            @Override
            public String getPrefix(final String namespaceURI) {
                // Not used in this context.
                return null;
            }

            @Override
            public String getNamespaceURI(final String prefix) {
                // Only require the URI for the bpmn2 NS.
                return BPMN2_NAMESPACE_URI;
            }
        });
        final XPathExpression expr = xpath.compile(BPMN_PROCESS_ID_XPATH_EXPR);

        final Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
        processId = node.getAttributes().getNamedItem(BPMN_PROCESS_ID_ATTR).getNodeValue();
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return processId;
}

From source file:eu.smartfp7.terrier.sensor.ParserUtility.java

public static EdgeNodeSnapShot parse(InputStream is) throws Exception {
    DocumentBuilderFactory xmlfact = DocumentBuilderFactory.newInstance();
    xmlfact.setNamespaceAware(true);//  w ww  .  j  ava 2  s  .c  o m
    Document document = xmlfact.newDocumentBuilder().parse(is);

    NamespaceContext ctx = new NamespaceContext() {

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

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

        @Override
        public String getNamespaceURI(String prefix) {

            String uri = null;

            /*
             *    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
            xmlns:smart="http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#"
            xmlns:dc="http://purl.org/dc/elements/1.1/"
            xmlns:contact="http://www.w3.org/2000/10/swap/pim/contact#"
            xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
            xmlns:time="http://www.w3.org/2006/time#"
            xml:base="http://www.ait.gr/ait_web_site/faculty/apne/report.xml"
                    
            *
            */

            if (prefix.equals("rdf")) {
                uri = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
            }
            if (prefix.equals("smart")) {
                uri = "http://www.ait.gr/ait_web_site/faculty/apne/schema.xml#";
            }
            if (prefix.equals("dc")) {
                uri = "http://purl.org/dc/elements/1.1/#";
            }
            if (prefix.equals("geo")) {
                uri = "http://www.w3.org/2003/01/geo/wgs84_pos#";
            }
            if (prefix.equals("time")) {
                uri = "http://www.w3.org/2006/time#";
            }
            return uri;

        }
    };

    // find the node data

    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(ctx);

    String id = (String) xpath.compile("//smart:Node/@rdf:ID").evaluate(document, XPathConstants.STRING);
    String lat = (String) xpath.compile("//smart:Node/geo:lat/text()").evaluate(document,
            XPathConstants.STRING);
    String lon = (String) xpath.compile("//smart:Node/geo:long/text()").evaluate(document,
            XPathConstants.STRING);
    String fullName = (String) xpath.compile("//smart:Node/dc:fullName/text()").evaluate(document,
            XPathConstants.STRING);
    Node node = new Node(new Double(lat), new Double(lon), id, fullName);

    String time = (String) xpath.compile("//smart:Report/time:inXSDDateTime/text()").evaluate(document,
            XPathConstants.STRING);
    String reportId = (String) xpath.compile("//smart:Report/@rdf:ID").evaluate(document,
            XPathConstants.STRING);

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Calendar c = Calendar.getInstance();
    ;
    c.setTime(df.parse(time));

    String density = (String) xpath.compile("//smart:Crowd/smart:density/text()").evaluate(document,
            XPathConstants.STRING);
    String cameraGain = (String) xpath.compile("//smart:Crowd/smart:cameraGain/text()").evaluate(document,
            XPathConstants.STRING);

    NodeList list = (NodeList) xpath.compile("//smart:Crowd/smart:colour").evaluate(document,
            XPathConstants.NODESET);
    double[] colors = new double[list.getLength()];
    for (int i = 0; i < list.getLength(); i++) {
        org.w3c.dom.Node colorNode = list.item(i);
        String v = colorNode.getFirstChild().getTextContent();
        colors[i] = new Double(v);
    }

    CrowdReport crowdReport = new CrowdReport(reportId, new Double(density), new Double(cameraGain), colors);

    EdgeNodeSnapShot snapShot = new EdgeNodeSnapShot(node, id, c, crowdReport);

    return snapShot;
}

From source file:Main.java

public static final String[] executeXPathExpression(InputSource inputSource, String xpathExpression,
        String namespace) throws XPathExpressionException, SAXException, IOException,
        ParserConfigurationException, TransformerException {

    // optional namespace spec: xmlns:prefix:URI
    String nsPrefix = null;/*  w w w.  j a va2  s . co  m*/
    String nsUri = null;
    if (namespace != null && namespace.startsWith("xmlns:")) {
        String[] nsDef = namespace.substring("xmlns:".length()).split("=");
        if (nsDef.length == 2) {
            nsPrefix = nsDef[0];
            nsUri = nsDef[1];
        }
    }

    // Parse XML to DOM
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    Document doc = dbFactory.newDocumentBuilder().parse(inputSource);

    // Find nodes by XPATH
    XPathFactory xpFactory = XPathFactory.newInstance();
    XPath xpath = xpFactory.newXPath();

    // namespace?
    if (nsPrefix != null) {
        final String myPrefix = nsPrefix;
        final String myUri = nsUri;
        xpath.setNamespaceContext(new NamespaceContext() {
            public String getNamespaceURI(String prefix) {
                return myPrefix.equals(prefix) ? myUri : null;
            }

            public String getPrefix(String namespaceURI) {
                return null; // we are not using this.
            }

            public Iterator<?> getPrefixes(String namespaceURI) {
                return null; // we are not using this.
            }
        });
    }

    XPathExpression expr = xpath.compile(xpathExpression);
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

    List<String> lines = new ArrayList<>();

    for (int i = 0; i < nodes.getLength(); i++) {
        lines.add((indenting(nodes.item(i))));
    }

    return lines.toArray(new String[lines.size()]);

}

From source file:Main.java

private static XPathExpression createXPathExpression(String xpathString) {
    /* XPath *///from www.  ja v a 2 s  .  co m
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {

        @Override
        public Iterator<?> getPrefixes(String namespaceURI) {
            throw new RuntimeException();
        }

        @Override
        public String getPrefix(String namespaceURI) {
            throw new RuntimeException();
        }

        @Override
        public String getNamespaceURI(String prefix) {
            if ("ds".equals(prefix)) {
                return XMLSignature.XMLNS;
            } else if ("xades".equals(prefix)) {
                return "http://uri.etsi.org/01903/v1.3.2#";
            } else if ("xades141".equals(prefix)) {
                return "http://uri.etsi.org/01903/v1.4.1#";
            } else if ("xades111".equals(prefix)) {
                return "http://uri.etsi.org/01903/v1.1.1#";
            }
            throw new RuntimeException("Prefix not recognized : " + prefix);
        }
    });
    try {
        XPathExpression expr = xpath.compile(xpathString);
        return expr;
    } catch (XPathExpressionException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:org.jboss.spring.factory.NamedXmlBeanFactory.java

private void initializeNames(Resource resource) {
    try {//from w  w  w  .java2s.com
        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 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.setParentBeanFactory((BeanFactory) Util.lookup(parentName, BeanFactory.class));
                } catch (Exception e) {
                    throw new BeanDefinitionStoreException(
                            "Failure during parent bean factory JNDI lookup: " + parentName, e);
                }
            }
            Matcher inst = Pattern.compile(Constants.INSTANTIATION_ELEMENT).matcher(description);
            if (inst.find()) {
                instantiate = Boolean.parseBoolean(inst.group(1));
            }
        }
        if (this.name == null || "".equals(StringUtils.trimAllWhitespace(this.name))) {
            this.name = this.defaultName;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.radium226.github.maven.MetaDataDownloader.java

public static String evaluateXPath(InputStream pomInputStream, String expression)
        throws XPathExpressionException {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    xPath.setNamespaceContext(new NamespaceContext() {

        @Override/*from   www .  j av a 2  s .co m*/
        public String getNamespaceURI(String prefix) {
            if (prefix.equals("ns")) {
                return "http://maven.apache.org/POM/4.0.0";
            }

            return null;
        }

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

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            return null;
        }
    });
    XPathExpression xPathExpression = xPath.compile(expression);
    String version = (String) xPathExpression.evaluate(new InputSource(pomInputStream), XPathConstants.STRING);
    return version;
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Before
public void setUp() throws Exception {
    final NamespaceContext baseEntityResolutionNamespaceContext = new EntityResolutionNamespaceContext();
    testNamespaceContext = new NamespaceContext() {

        @Override// ww w. j av  a2 s  . c  om
        public String getNamespaceURI(String prefix) {
            if ("ext".equals(prefix)) {
                return "http://local.org/IEPD/Extensions/PersonSearchResults/1.0";
            }
            return baseEntityResolutionNamespaceContext.getNamespaceURI(prefix);
        }

        @Override
        public String getPrefix(String arg0) {
            return baseEntityResolutionNamespaceContext.getPrefix(arg0);
        }

        @SuppressWarnings("rawtypes")
        @Override
        public Iterator getPrefixes(String arg0) {
            return baseEntityResolutionNamespaceContext.getPrefixes(arg0);
        }

    };
    entityResolutionMessageHandler = new EntityResolutionMessageHandler();
    testAttributeParametersMessageInputStream = getClass()
            .getResourceAsStream("/xml/TestAttributeParameters.xml");
    assertNotNull(testAttributeParametersMessageInputStream);
    entityResolutionMessageHandler.setAttributeParametersStream(testAttributeParametersMessageInputStream);
    testRequestMessageInputStream = getClass().getResourceAsStream("/xml/EntityMergeRequestMessage.xml");
    assertNotNull(testRequestMessageInputStream);
}

From source file:org.jboss.spring.factory.NamedXmlApplicationContext.java

private void initializeNames(Resource resource) {
    try {//  www  . j  a v a 2 s  .  c o  m
        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 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);
    }
}