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:gov.nij.bundles.intermediaries.ers.EntityResolutionServiceIntermediaryTest.java

@Before
public void setUp() throws Exception {

    final NamespaceContext baseEntityResolutionNamespaceContext = new EntityResolutionNamespaceContext();
    testNamespaceContext = new NamespaceContext() {

        @Override/*from  w  ww  . ja  va  2 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);
        }

    };

    // Advise the person search results endpoint and replace it with a mock endpoint.
    // We then will test this mock endpoint to see if it gets the proper payload.
    context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            // weave the vehicle search results in the route
            // and replace it with the following mock route path
            weaveByToString("To[EntityResolutionResponseEndpoint]").replace()
                    .to("mock:EntityResolutionResponseEndpoint");
            replaceFromWith("direct:entityResolutionRequestServiceEndpoint");
        }
    });

    context.start();

    // We should get one message
    entityResolutionResponseMock.expectedMessageCount(1);

    // Create a new exchange
    senderExchange = new DefaultExchange(context);

    Document doc = createDocument();
    List<SoapHeader> soapHeaders = new ArrayList<SoapHeader>();
    soapHeaders.add(makeSoapHeader(doc, "http://www.w3.org/2005/08/addressing", "MessageID", "12345"));
    soapHeaders.add(makeSoapHeader(doc, "http://www.w3.org/2005/08/addressing", "ReplyTo", "https://reply.to"));
    senderExchange.getIn().setHeader(Header.HEADER_LIST, soapHeaders);

    senderExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, CXF_OPERATION_NAME);
    senderExchange.getIn().setHeader(CxfConstants.OPERATION_NAMESPACE, CXF_OPERATION_NAMESPACE);
}

From source file:org.dataconservancy.dcs.integration.main.ManualDepositIT.java

/**
 * Ensure that the <code>href</code> attribute values for &lt;collection&gt;s are valid URLs.
 *///  w  ww.ja  v  a2s .  c  om
@Test
public void testServiceDocCollectionUrls() throws IOException, XPathExpressionException {
    final HttpGet req = new HttpGet(serviceDocUrl);
    final HttpResponse resp = client.execute(req);
    assertEquals("Unable to retrieve atompub service document " + serviceDocUrl, 200,
            resp.getStatusLine().getStatusCode());

    final XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            if ("app".equals(prefix) || prefix == null || "".equals(prefix)) {
                return ATOM_NS;
            }
            throw new RuntimeException("Unknown xmlns prefix: '" + prefix + "'");
        }

        @Override
        public String getPrefix(String nsUri) {
            if (ATOM_NS.equals(nsUri)) {
                return "app";
            }
            throw new RuntimeException("Unknown xmlns uri '" + nsUri + "'");
        }

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

    final String xpathExpression = "//app:collection/@href";
    final NodeList collectionHrefs = (NodeList) xpath.evaluate(xpathExpression,
            new InputSource(resp.getEntity().getContent()), XPathConstants.NODESET);

    assertTrue(
            "No atompub collections found in service document " + serviceDocUrl + " (xpath search '"
                    + xpathExpression + "' yielded no results.",
            collectionHrefs != null && collectionHrefs.getLength() > 0);

    for (int i = 0; i < collectionHrefs.getLength(); i++) {
        final String collectionUrl = collectionHrefs.item(i).getNodeValue();
        assertNotNull("atompub collection url was null.", collectionUrl);
        assertTrue("atompub collection url was the empty string.", collectionUrl.trim().length() > 0);
        new URL(collectionUrl);
        assertTrue("Expected atompub collection url to start with " + serviceDocUrl + " (collection url was: "
                + collectionUrl, collectionUrl.startsWith(serviceDocUrl));
    }
}

From source file:ch.entwine.weblounge.common.impl.content.page.PageTemplateImpl.java

/**
 * Initializes this page template from an XML node that was generated using
 * {@link #toXml()}./*from  www. ja  va2 s  .  co  m*/
 * <p>
 * To speed things up, you might consider using the second signature that uses
 * an existing <code>XPath</code> instance instead of creating a new one.
 * 
 * @param node
 *          the page template node
 * @throws IllegalStateException
 *           if the page template cannot be parsed
 * @see #fromXml(Node, XPath)
 * @see #toXml()
 */
public static PageTemplate fromXml(Node node) 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(node, xpath);
}

From source file:de.pangaea.fixo3.xml.ProcessXmlFiles.java

private void run() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException,
        XPathExpressionException {
    // src/test/resources/, src/main/resources/files
    File folder = new File("src/main/resources/files");
    File[] files = folder.listFiles(new FileFilter() {

        @Override/*  ww  w  . j a v a2 s .c o m*/
        public boolean accept(File pathname) {
            if (pathname.getName().endsWith(".xml"))
                return true;

            return false;
        }
    });

    JsonArrayBuilder json = Json.createArrayBuilder();

    Document doc;
    String deviceLabel, deviceComment, deviceImage;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    final Map<String, String> prefixToNS = new HashMap<>();
    prefixToNS.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    prefixToNS.put(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
    prefixToNS.put("sml", "http://www.opengis.net/sensorml/2.0");
    prefixToNS.put("gml", "http://www.opengis.net/gml/3.2");
    prefixToNS.put("gmd", "http://www.isotc211.org/2005/gmd");

    XPath x = XPathFactory.newInstance().newXPath();
    x.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            Objects.requireNonNull(prefix, "Namespace prefix cannot be null");
            final String uri = prefixToNS.get(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("Undeclared namespace prefix: " + prefix);
            }
            return uri;
        }

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

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

    XPathExpression exGmlName = x.compile("/sml:PhysicalSystem/gml:name");
    XPathExpression exGmlDescription = x.compile("/sml:PhysicalSystem/gml:description");
    XPathExpression exGmdUrl = x.compile(
            "/sml:PhysicalSystem/sml:documentation/sml:DocumentList/sml:document/gmd:CI_OnlineResource/gmd:linkage/gmd:URL");
    XPathExpression exTerm = x
            .compile("/sml:PhysicalSystem/sml:classification/sml:ClassifierList/sml:classifier/sml:Term");

    int m = 0;
    int n = 0;

    for (File file : files) {
        log.info(file.getName());
        doc = dbf.newDocumentBuilder().parse(new FileInputStream(file));

        deviceLabel = exGmlName.evaluate(doc).trim();
        deviceComment = exGmlDescription.evaluate(doc).trim();
        deviceImage = exGmdUrl.evaluate(doc).trim();
        NodeList terms = (NodeList) exTerm.evaluate(doc, XPathConstants.NODESET);

        JsonObjectBuilder jobDevice = Json.createObjectBuilder();

        jobDevice.add("name", toUri(deviceLabel));
        jobDevice.add("label", deviceLabel);
        jobDevice.add("comment", toAscii(deviceComment));
        jobDevice.add("image", deviceImage);

        JsonArrayBuilder jabSubClasses = Json.createArrayBuilder();

        for (int i = 0; i < terms.getLength(); i++) {
            Node term = terms.item(i);
            NodeList attributes = term.getChildNodes();

            String attributeLabel = null;
            String attributeValue = null;

            for (int j = 0; j < attributes.getLength(); j++) {
                Node attribute = attributes.item(j);
                String attributeName = attribute.getNodeName();

                if (attributeName.equals("sml:label")) {
                    attributeLabel = attribute.getTextContent();
                } else if (attributeName.equals("sml:value")) {
                    attributeValue = attribute.getTextContent();
                }
            }

            if (attributeLabel == null || attributeValue == null) {
                throw new RuntimeException("Attribute label or value cannot be null [attributeLabel = "
                        + attributeLabel + "; attributeValue = " + attributeValue + "]");
            }

            if (attributeLabel.equals("model")) {
                continue;
            }

            if (attributeLabel.equals("manufacturer")) {
                jobDevice.add("manufacturer", attributeValue);
                continue;
            }

            n++;

            Quantity quantity = getQuantity(attributeValue);

            if (quantity == null) {
                continue;
            }

            m++;

            JsonObjectBuilder jobSubClass = Json.createObjectBuilder();
            JsonObjectBuilder jobCapability = Json.createObjectBuilder();
            JsonObjectBuilder jobQuantity = Json.createObjectBuilder();

            String quantityLabel = getQuantityLabel(attributeLabel);
            String capabilityLabel = deviceLabel + " " + quantityLabel;

            jobCapability.add("label", capabilityLabel);

            jobQuantity.add("label", quantity.getLabel());

            if (quantity.getValue() != null) {
                jobQuantity.add("value", quantity.getValue());
            } else if (quantity.getMinValue() != null && quantity.getMaxValue() != null) {
                jobQuantity.add("minValue", quantity.getMinValue());
                jobQuantity.add("maxValue", quantity.getMaxValue());
            } else {
                throw new RuntimeException(
                        "Failed to determine quantity value [attributeValue = " + attributeValue + "]");
            }

            jobQuantity.add("unitCode", quantity.getUnitCode());
            jobQuantity.add("type", toUri(quantityLabel));

            jobCapability.add("quantity", jobQuantity);
            jobSubClass.add("capability", jobCapability);

            jabSubClasses.add(jobSubClass);
        }

        jobDevice.add("subClasses", jabSubClasses);

        json.add(jobDevice);
    }

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);

    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(properties);
    JsonWriter jsonWriter = jsonWriterFactory.createWriter(new FileWriter(new File(jsonFileName)));
    jsonWriter.write(json.build());
    jsonWriter.close();

    System.out.println("Fraction of characteristics included: " + m + "/" + n);
}

From source file:com.amalto.core.util.Util.java

private static String[] getTextNodes(Node contextNode, String xPath, final Node namespaceNode)
        throws TransformerException {
    String[] results;//  w  w  w.  ja  v  a2  s.co  m
    // test for hard-coded values
    if (xPath.startsWith("\"") && xPath.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
        return new String[] { xPath.substring(1, xPath.length() - 1) };
    }
    // test for incomplete path (elements missing /text())
    if (!xPath.matches(".*@[^/\\]]+")) { // attribute
        if (!xPath.endsWith(")")) { // function
            xPath += "/text()";
        }
    }
    try {
        XPath path = XPathFactory.newInstance().newXPath();
        path.setNamespaceContext(new NamespaceContext() {

            @Override
            public String getNamespaceURI(String s) {
                return namespaceNode.getNamespaceURI();
            }

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

            @Override
            public Iterator getPrefixes(String s) {
                return Collections.singleton(namespaceNode.getPrefix()).iterator();
            }
        });
        NodeList xo = (NodeList) path.evaluate(xPath, contextNode, XPathConstants.NODESET);
        results = new String[xo.getLength()];
        for (int i = 0; i < xo.getLength(); i++) {
            results[i] = xo.item(i).getTextContent();
        }
    } catch (Exception e) {
        String err = "Unable to get the text node(s) of " + xPath + ": " + e.getClass().getName() + ": "
                + e.getLocalizedMessage();
        throw new TransformerException(err);
    }
    return results;

}

From source file:com.amalto.core.util.Util.java

/**
 * Get a node list from an xPath/*from w w w  .  ja v  a2s  .  c o  m*/
 * 
 * @throws XtentisException
 */
public static NodeList getNodeList(Node contextNode, String xPath) throws XtentisException {
    try {
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPathParser = xPathFactory.newXPath();
        xPathParser.setNamespaceContext(new NamespaceContext() {

            @Override
            public String getNamespaceURI(String s) {
                if ("xsd".equals(s)) { //$NON-NLS-1$
                    return XMLConstants.W3C_XML_SCHEMA_NS_URI;
                }
                return null;
            }

            @Override
            public String getPrefix(String s) {
                if (XMLConstants.W3C_XML_SCHEMA_NS_URI.equals(s)) {
                    return "xsd"; //$NON-NLS-1$
                }
                return null;
            }

            @Override
            public Iterator getPrefixes(String s) {
                return Collections.singletonList(s).iterator();
            }
        });
        return (NodeList) xPathParser.evaluate(xPath, contextNode, XPathConstants.NODESET);
    } catch (Exception e) {
        String err = "Unable to get the Nodes List for xpath '" + xPath + "'"
                + ((contextNode == null) ? "" : " for Node " + contextNode.getLocalName()) + ": "
                + e.getLocalizedMessage();
        throw new XtentisException(err, e);
    }
}

From source file:com.fluidops.iwb.provider.XMLProvider.java

/**
 * @return a namespace context build according to the config
 *///from  w w  w. jav a 2  s.  co m
protected NamespaceContext getNamespaceContextFromConfig() {
    final HashMap<String, String> namespaceMapping = new HashMap<String, String>();
    if (!StringUtil.isNullOrEmpty(config.namespaceAbbreviations)) {
        String[] mappings = config.namespaceAbbreviations.split(",");
        for (String mapping : mappings) {
            mapping = mapping.trim();
            String[] inner = mapping.split("=", -1);
            if (inner.length == 2)
                namespaceMapping.put(inner[0], inner[1]);
        }
    }

    return new NamespaceContext() {
        public String getNamespaceURI(String prefix) {
            return namespaceMapping.get(prefix);
        }

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

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

From source file:eu.semaine.util.XMLTool.java

/**
 * Create a namespace context from the given mapping bewteen prefixes and namespace uris.
 * @param prefixes2NamespaceURIs//from w  w w .  ja va 2s  . co  m
 * @return a namespace context
 */
public static NamespaceContext createNamespaceContext(final Map<String, String> prefixes2NamespaceURIs) {
    return new NamespaceContext() {
        public String getNamespaceURI(String prefix) {
            if (prefix == null)
                throw new NullPointerException("Null prefix");
            else if (prefixes2NamespaceURIs.containsKey(prefix))
                return prefixes2NamespaceURIs.get(prefix);
            else if ("xml".equals(prefix))
                return XMLConstants.XML_NS_URI;
            return XMLConstants.NULL_NS_URI;
        }

        // 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<Object> getPrefixes(String uri) {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:org.apache.maven.dotnet.stylecop.StyleCopGenerator.java

/**
 * Generates the msbuild configuration for a project.
 * /*w w w  .  j  a v a 2  s. c o m*/
 * @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();
}

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

protected NamespaceContext getNamespaceContext() {

    return new NamespaceContext() {

        public String getNamespaceURI(String prefix) {
            if (prefix.equals("ds"))
                return org.apache.xml.security.utils.Constants.SignatureSpecNS;
            if (prefix.equals("p"))
                return SAMLR2Constants.SAML_PROTOCOL_NS;
            if (prefix.equals("a"))
                return SAMLR2Constants.SAML_ASSERTION_NS;

            return null;
        }/*  ww  w . ja  v a  2  s  . c o  m*/

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

        // Dummy implemenation - not used!
        public String getPrefix(String uri) {
            if (uri.equals(org.apache.xml.security.utils.Constants.SignatureSpecNS))
                return "ds";
            if (uri.equals(SAMLR2Constants.SAML_PROTOCOL_NS))
                return "p";
            if (uri.equals(SAMLR2Constants.SAML_ASSERTION_NS))
                return "a";

            return null;
        }

    };

}