List of usage examples for org.w3c.dom Element getNamespaceURI
public String getNamespaceURI();
null
if it is unspecified (see ). From source file:org.apache.axis2.saaj.SOAPFactoryTest.java
@Validated @Test//from w ww.j a v a 2s.c o m public void testCreateElement2() { try { SOAPFactory sf = SOAPFactory.newInstance(); //SOAPFactory sf = SOAPFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL); if (sf == null) { fail("could not create SOAPFactory object"); } log.info("Create a DOMElement"); DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbfactory.newDocumentBuilder(); Document document = builder.newDocument(); Element de = document.createElementNS("http://MyNamespace.org/", "MyTag"); //Calling SOAPFactory.createElement(org.w3c.dom.Element) SOAPElement se = sf.createElement(de); if (!de.getNodeName().equals(se.getNodeName()) || !de.getNamespaceURI().equals(se.getNamespaceURI())) { //Node names are not equal fail("Got: <URI=" + se.getNamespaceURI() + ", PREFIX=" + se.getPrefix() + ", NAME=" + se.getNodeName() + ">" + "Expected: <URI=" + de.getNamespaceURI() + ", PREFIX=" + de.getPrefix() + ", NAME=" + de.getNodeName() + ">"); } } catch (Exception e) { fail("Exception: " + e); } }
From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java
protected Element createChildFromXmlFragmentOrText(Document doc, Input input, String localElementName, String errorMessage, String elementOrText) throws IOException, ParserConfigurationException, XmlSignatureException { String ending = localElementName + ">"; Element child; if (elementOrText.startsWith("<") && elementOrText.endsWith(ending)) { try {//from w w w.j av a 2 s . com // assume xml InputSource source = new InputSource(new StringReader(elementOrText)); source.setEncoding("UTF-8"); Document parsedDoc = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).parse(source); replacePrefixes(parsedDoc, input); child = (Element) doc.adoptNode(parsedDoc.getDocumentElement()); // check for correct namespace String ns = findNamespace(input.getMessage()); if (!ns.equals(child.getNamespaceURI())) { throw new XmlSignatureException(String.format( "The XAdES confguration is invalid. The root element '%s' of the provided XML fragment '%s' has the invalid namespace '%s'. The correct namespace is '%s'.", child.getLocalName(), elementOrText, child.getNamespaceURI(), ns)); } } catch (SAXException e) { throw new XmlSignatureException( String.format(errorMessage, elementOrText, localElementName, namespace), e); } } else { child = createElement(localElementName, doc, input); child.setTextContent(elementOrText); } return child; }
From source file:org.apache.cocoon.forms.binding.JXPathBindingManager.java
public Binding createBinding(Source source) throws BindingException { Binding binding = (Binding) this.cacheManager.get(source, PREFIX); if (binding != null && !binding.isValid()) binding = null; //invalidate if (binding == null) { try {//from w ww. j a v a 2 s . co m InputSource is = new InputSource(source.getInputStream()); is.setSystemId(source.getURI()); Document doc = DomHelper.parse(is, this.manager); Element rootElm = doc.getDocumentElement(); if (BindingManager.NAMESPACE.equals(rootElm.getNamespaceURI())) { binding = getBuilderAssistant().getBindingForConfigurationElement(rootElm); ((JXPathBindingBase) binding).enableLogging(getLogger()); if (getLogger().isDebugEnabled()) { getLogger().debug("Creation of new binding finished. " + binding); } } else { if (getLogger().isDebugEnabled()) { getLogger().debug("Root Element of said binding file is in wrong namespace."); } } this.cacheManager.set(binding, source, PREFIX); } catch (BindingException e) { throw e; } catch (Exception e) { throw new BindingException("Error creating binding from " + source.getURI(), e); } } return binding; }
From source file:org.apache.cocoon.util.jxpath.DOMFactory.java
public String getNamespaceURI(Element element, String prefix) { Node tmp = element;// www . j av a 2 s.c om String nsAttr = prefix == null ? "xmlns" : "xmlns:" + prefix; while (tmp != null && tmp.getNodeType() == Node.ELEMENT_NODE) { element = (Element) tmp; // First test element prefixes if (prefix == null) { if (element.getPrefix() == null) { return element.getNamespaceURI(); } } else if (prefix.equals(element.getPrefix())) { return element.getNamespaceURI(); } // Note: stupid DOM api returns "" when an attribute doesn't exist, so we use the Attr node. Attr nsAttrNode = ((Element) tmp).getAttributeNode(nsAttr); if (nsAttrNode != null) { return nsAttrNode.getValue(); } tmp = tmp.getParentNode(); } return null; }
From source file:org.apache.cxf.fediz.service.idp.beans.STSClientAction.java
/** * @param context/*from www. ja v a2 s . c o m*/ * the webflow request context * @return a serialized RP security token * @throws Exception */ public String submit(RequestContext context) throws Exception { String wtrealm = (String) WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_TREALM); SecurityToken idpToken = getSecurityToken(context); Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, IDP_CONFIG); Bus cxfBus = getBus(); IdpSTSClient sts = new IdpSTSClient(cxfBus); sts.setAddressingNamespace(HTTP_WWW_W3_ORG_2005_08_ADDRESSING); Application serviceConfig = idpConfig.findApplication(wtrealm); if (serviceConfig == null) { LOG.warn("No service config found for " + wtrealm); throw new ProcessingException(TYPE.BAD_REQUEST); } // Parse wreq parameter - we only support parsing TokenType and KeyType for now String wreq = (String) WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_REQUEST); String stsTokenType = null; String stsKeyType = keyType; if (wreq != null) { try { Document wreqDoc = DOMUtils.readXml(new StringReader(wreq)); Element wreqElement = wreqDoc.getDocumentElement(); if (wreqElement != null && "RequestSecurityToken".equals(wreqElement.getLocalName()) && (STSUtils.WST_NS_05_12.equals(wreqElement.getNamespaceURI()) || HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST .equals(wreqElement.getNamespaceURI()))) { Element tokenTypeElement = DOMUtils.getFirstChildWithName(wreqElement, wreqElement.getNamespaceURI(), "TokenType"); if (tokenTypeElement != null) { stsTokenType = tokenTypeElement.getTextContent(); } Element keyTypeElement = DOMUtils.getFirstChildWithName(wreqElement, wreqElement.getNamespaceURI(), "KeyType"); if (keyTypeElement != null) { stsKeyType = keyTypeElement.getTextContent(); } } } catch (Exception e) { LOG.warn("Error parsing 'wreq' parameter: " + e.getMessage()); throw new ProcessingException(TYPE.BAD_REQUEST); } } if (stsTokenType != null) { sts.setTokenType(stsTokenType); } else if (serviceConfig.getTokenType() != null && serviceConfig.getTokenType().length() > 0) { sts.setTokenType(serviceConfig.getTokenType()); } else { sts.setTokenType(getTokenType()); } if (serviceConfig.getPolicyNamespace() != null && serviceConfig.getPolicyNamespace().length() > 0) { sts.setWspNamespace(serviceConfig.getPolicyNamespace()); } LOG.debug("TokenType {} set for realm {}", sts.getTokenType(), wtrealm); sts.setKeyType(stsKeyType); if (HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_PUBLICKEY.equals(stsKeyType)) { HttpServletRequest servletRequest = WebUtils.getHttpServletRequest(context); if (servletRequest != null) { X509Certificate certs[] = (X509Certificate[]) servletRequest .getAttribute("javax.servlet.request.X509Certificate"); if (certs != null && certs.length > 0) { sts.setUseCertificateForConfirmationKeyInfo(true); sts.setUseKeyCertificate(certs[0]); } else { LOG.info("Can't send a PublicKey KeyType as no client certs are available"); sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER); } } } processWsdlLocation(context); sts.setWsdlLocation(wsdlLocation); sts.setServiceQName(new QName(namespace, wsdlService)); sts.setEndpointQName(new QName(namespace, wsdlEndpoint)); if (use200502Namespace) { sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST); } if (serviceConfig.getRequestedClaims() != null && serviceConfig.getRequestedClaims().size() > 0) { addClaims(sts, serviceConfig.getRequestedClaims()); LOG.debug("Requested claims set for {}", wtrealm); } sts.setEnableLifetime(true); if (serviceConfig.getLifeTime() > 0) { try { int lifetime = serviceConfig.getLifeTime(); sts.setTtl(lifetime); sts.setEnableLifetime(lifetime > 0); LOG.debug("Lifetime set to {} seconds for realm {}", serviceConfig.getLifeTime(), wtrealm); } catch (NumberFormatException ex) { LOG.warn("Invalid lifetime configured for service provider " + wtrealm); sts.setTtl(this.ttl); sts.setEnableLifetime(this.ttl > 0); } } else { sts.setTtl(this.ttl); sts.setEnableLifetime(this.ttl > 0); if (LOG.isDebugEnabled()) { LOG.debug("Lifetime set to {} seconds for realm {}", this.ttl, wtrealm); } } sts.setOnBehalfOf(idpToken.getToken()); if (!(serviceConfig.getProtocol() == null || FederationConstants.WS_FEDERATION_NS.equals(serviceConfig.getProtocol()))) { LOG.error("Protocol {} not supported for realm {} ", serviceConfig.getProtocol(), wtrealm); throw new ProcessingException(TYPE.BAD_REQUEST); } String rpToken = sts.requestSecurityTokenResponse(wtrealm); InputStream is = new ByteArrayInputStream(rpToken.getBytes()); Document doc = StaxUtils.read(is); NodeList nd = doc.getElementsByTagName("saml2:Assertion"); if (nd.getLength() == 0) { nd = doc.getElementsByTagName("saml1:Assertion"); } Element e = (Element) nd.item(0); SamlAssertionWrapper aw = new SamlAssertionWrapper(e); String id = aw.getId(); LOG.info("[RP_TOKEN={}] successfully created for realm [{}] on behalf of [IDP_TOKEN={}]", id, wtrealm, idpToken.getId()); return StringEscapeUtils.escapeXml(rpToken); }
From source file:org.apache.fop.plan.PreloaderPlan.java
private ImageInfo getImage(String uri, Source src, ImageContext context) throws IOException { InputStream in = new UnclosableInputStream(ImageUtil.needInputStream(src)); try {/* www.j a va 2s . c om*/ Document planDoc = getDocument(in); Element rootEl = planDoc.getDocumentElement(); if (!PlanElementMapping.NAMESPACE.equals(rootEl.getNamespaceURI())) { in.reset(); return null; } //Have to render the plan to know its size PlanRenderer pr = new PlanRenderer(); Document svgDoc = pr.createSVGDocument(planDoc); float width = pr.getWidth(); float height = pr.getHeight(); //Return converted SVG image ImageInfo info = new ImageInfo(uri, "image/svg+xml"); final ImageSize size = new ImageSize(); size.setSizeInMillipoints(Math.round(width * 1000), Math.round(height * 1000)); //Set the resolution to that of the FOUserAgent size.setResolution(context.getSourceResolution()); size.calcPixelsFromSize(); info.setSize(size); //The whole image had to be loaded for this, so keep it Image image = new ImageXMLDOM(info, svgDoc, svgDoc.getDocumentElement().getNamespaceURI()); info.getCustomObjects().put(ImageInfo.ORIGINAL_IMAGE, image); return info; } catch (TransformerException e) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } log.debug("Error while trying to parsing a Plan file: " + e.getMessage()); return null; } }
From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java
/***** * Adds a new node or replaces an existing node in the Document * //from ww w .jav a 2s .c om * @param doc Target document where the node will added * @param xmlEntity contains definition of the xml entity * @throws IOException * @throws ParserConfigurationException * @throws SAXException * @throws XPathExpressionException */ public static void addNewNode(final Document doc, final XmlEntity xmlEntity) throws IOException, XPathExpressionException, SAXException, ParserConfigurationException { // Build up map per call to avoid issues with caching wrong version of the map. final LinkedHashMap<String, CacheElement> elementOrderMap = CacheElement.buildElementMap(doc); final Node newNode = createNode(doc, xmlEntity.getXmlDefinition()); final Node root = doc.getDocumentElement(); final int incomingElementOrder = getElementOrder(elementOrderMap, xmlEntity.getNamespace(), xmlEntity.getType()); boolean nodeAdded = false; NodeList nodes = root.getChildNodes(); final int length = nodes.getLength(); for (int i = 0; i < length; i++) { final Node node = nodes.item(i); if (node instanceof Element) { final Element childElement = (Element) node; final String type = childElement.getLocalName(); final String namespace = childElement.getNamespaceURI(); if (namespace.equals(xmlEntity.getNamespace()) && type.equals(xmlEntity.getType())) { // First check if the element has a name String nameOrId = getAttribute(childElement, "name"); // If not then check if the element has an Id if (nameOrId == null) { nameOrId = getAttribute(childElement, "id"); } if (nameOrId != null) { // If there is a match , then replace the existing node with the incoming node if (nameOrId.equals(xmlEntity.getNameOrId())) { root.replaceChild(newNode, node); nodeAdded = true; break; } } else { // This element does not have any name or id identifier for e.g PDX and gateway-receiver // If there is only one element of that type then replace it with the incoming node if (!isMultiple(elementOrderMap, namespace, type)) { root.replaceChild(newNode, node); nodeAdded = true; break; } } } else { if (incomingElementOrder < getElementOrder(elementOrderMap, namespace, type)) { root.insertBefore(newNode, node); nodeAdded = true; break; } } } } if (!nodeAdded) { root.appendChild(newNode); } }
From source file:org.apache.geode.management.internal.configuration.utils.XmlUtilsJUnitTest.java
/** * Test method for {@link XmlUtils#changeNamespace(Node, String, String)}. *//*from w w w. j a va 2 s . c o m*/ @Test public void testChangeNamespace() throws Exception { Document doc = XmlUtils.getDocumentBuilder().newDocument(); Element root = doc.createElement("root"); root = (Element) doc.appendChild(root); final Element child = doc.createElement("child"); root.appendChild(child); final String ns2 = "urn:namespace2"; final Element childWithNamespace = doc.createElementNS(ns2, "childWithNamespace"); root.appendChild(childWithNamespace); root.appendChild(doc.createTextNode("some text")); assertEquals(null, root.getNamespaceURI()); assertEquals(null, child.getNamespaceURI()); assertEquals(ns2, childWithNamespace.getNamespaceURI()); final String ns1 = "urn:namespace1"; root = (Element) XmlUtils.changeNamespace(root, XMLConstants.NULL_NS_URI, ns1); assertEquals(ns1, root.getNamespaceURI()); assertEquals(ns1, root.getElementsByTagName("child").item(0).getNamespaceURI()); assertEquals(ns2, root.getElementsByTagName("childWithNamespace").item(0).getNamespaceURI()); }
From source file:org.apache.hise.utils.DOMUtils.java
public static Element findElement(QName elementName, List<Object> content) { for (Object o : content) { if (o instanceof Element) { Element u = (Element) o; QName n = new QName(u.getNamespaceURI(), u.getLocalName()); if (n.equals(elementName)) { return u; }/*www . j av a2 s .c o m*/ } } return null; }
From source file:org.apache.ode.axis2.AuthenticationHelper.java
public static void setHttpAuthentication(PartnerRoleMessageExchange odeMex, Options options) { Element msg = odeMex.getRequest().getMessage(); if (msg != null) { Element part = DOMUtils.getFirstChildElement(msg); while (part != null) { Element content = DOMUtils.getFirstChildElement(part); if (content != null) { if (AUTHENTICATION_NS.equals(content.getNamespaceURI()) && AUTHENTICATE_ELEMENT.equals(content.getLocalName())) { setOptions(options, content); msg.removeChild(part); break; }//from w w w . j a va 2 s. c o m } part = DOMUtils.getNextSiblingElement(part); } } }