Java Code Examples for org.w3c.dom.Element#getLocalName()

The following examples show how to use org.w3c.dom.Element#getLocalName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ElementCheckerImpl.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void guaranteeThatElementInCorrectSpace(
    ElementProxy expected, Element actual
) throws XMLSecurityException {

    String expectedLocalname = expected.getBaseLocalName();
    String expectedNamespace = expected.getBaseNamespace();

    String localnameIS = actual.getLocalName();
    String namespaceIS = actual.getNamespaceURI();
    if ((expectedNamespace != namespaceIS) ||
        !expectedLocalname.equals(localnameIS)) {
        Object exArgs[] = { namespaceIS + ":" + localnameIS,
                            expectedNamespace + ":" + expectedLocalname};
        throw new XMLSecurityException("xml.WrongElement", exArgs);
    }
}
 
Example 2
Source File: KeyInfoReferenceResolver.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Validate the Element referred to by the KeyInfoReference.
 *
 * @param referentElement
 *
 * @throws XMLSecurityException
 */
private void validateReference(Element referentElement) throws XMLSecurityException {
    if (!XMLUtils.elementIsInSignatureSpace(referentElement, Constants._TAG_KEYINFO)) {
        Object exArgs[] = { new QName(referentElement.getNamespaceURI(), referentElement.getLocalName()) };
        throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.WrongType", exArgs);
    }

    KeyInfo referent = new KeyInfo(referentElement, "");
    if (referent.containsKeyInfoReference()) {
        if (secureValidation) {
            throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithSecure");
        } else {
            // Don't support chains of references at this time. If do support in the future, this is where the code
            // would go to validate that don't have a cycle, resulting in an infinite loop. This may be unrealistic
            // to implement, and/or very expensive given remote URI references.
            throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithoutSecure");
        }
    }

}
 
Example 3
Source File: XMLHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String getLocalNameOrTagName (@Nonnull final Element aElement)
{
  String ret = aElement.getLocalName ();
  if (ret == null)
    ret = aElement.getTagName ();
  return ret;
}
 
Example 4
Source File: DOMX509Data.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a <code>DOMX509Data</code> from an element.
 *
 * @param xdElem an X509Data element
 * @throws MarshalException if there is an error while unmarshalling
 */
public DOMX509Data(Element xdElem) throws MarshalException {
    // get all children nodes
    NodeList nl = xdElem.getChildNodes();
    int length = nl.getLength();
    List<Object> content = new ArrayList<Object>(length);
    for (int i = 0; i < length; i++) {
        Node child = nl.item(i);
        // ignore all non-Element nodes
        if (child.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }

        Element childElem = (Element)child;
        String localName = childElem.getLocalName();
        if (localName.equals("X509Certificate")) {
            content.add(unmarshalX509Certificate(childElem));
        } else if (localName.equals("X509IssuerSerial")) {
            content.add(new DOMX509IssuerSerial(childElem));
        } else if (localName.equals("X509SubjectName")) {
            content.add(childElem.getFirstChild().getNodeValue());
        } else if (localName.equals("X509SKI")) {
            try {
                content.add(Base64.decode(childElem));
            } catch (Base64DecodingException bde) {
                throw new MarshalException("cannot decode X509SKI", bde);
            }
        } else if (localName.equals("X509CRL")) {
            content.add(unmarshalX509CRL(childElem));
        } else {
            content.add(new javax.xml.crypto.dom.DOMStructure(childElem));
        }
    }
    this.content = Collections.unmodifiableList(content);
}
 
Example 5
Source File: DOMUtils.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static Element verifyElement(Element elem, String localName)
    throws MarshalException
{
    if (elem == null) {
        throw new MarshalException("Missing " + localName + " element");
    }
    String name = elem.getLocalName();
    if (!name.equals(localName)) {
        throw new MarshalException("Invalid element name: " +
                                   name + ", expected " + localName);
    }
    return elem;
}
 
Example 6
Source File: XMLSignatureUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Given a dsig:DSAKeyValue element, return {@link DSAKeyValueType}
 *
 * @param element
 *
 * @return
 *
 * @throws ProcessingException
 */
public static DSAKeyValueType getDSAKeyValue(Element element) throws ParsingException {
    DSAKeyValueType dsa = new DSAKeyValueType();
    NodeList nl = element.getChildNodes();
    int length = nl.getLength();

    for (int i = 0; i < length; i++) {
        Node node = nl.item(i);
        if (node instanceof Element) {
            Element childElement = (Element) node;
            String tag = childElement.getLocalName();

            byte[] text = childElement.getTextContent().getBytes(GeneralConstants.SAML_CHARSET);

            if (WSTrustConstants.XMLDSig.P.equals(tag)) {
                dsa.setP(text);
            } else if (WSTrustConstants.XMLDSig.Q.equals(tag)) {
                dsa.setQ(text);
            } else if (WSTrustConstants.XMLDSig.G.equals(tag)) {
                dsa.setG(text);
            } else if (WSTrustConstants.XMLDSig.Y.equals(tag)) {
                dsa.setY(text);
            } else if (WSTrustConstants.XMLDSig.SEED.equals(tag)) {
                dsa.setSeed(text);
            } else if (WSTrustConstants.XMLDSig.PGEN_COUNTER.equals(tag)) {
                dsa.setPgenCounter(text);
            }
        }
    }

    return dsa;
}
 
Example 7
Source File: RMBPHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Metadata parse(Element element, ParserContext context) {
    String s = element.getLocalName();
    if ("reliableMessaging".equals(s)) {
        return new RMBPBeanDefinitionParser(RMFeature.class).parse(element, context);
    } else if ("rmManager".equals(s)) {
        return new RMBPBeanDefinitionParser(RMManager.class).parse(element, context);
    } else if ("jdbcStore".equals(s)) {
        return new RMBPTxStoreBeanDefinitionParser().parse(element, context);
    }

    return null;
}
 
Example 8
Source File: DOMUtils.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static Element verifyElement(Element elem, String localName)
    throws MarshalException
{
    if (elem == null) {
        throw new MarshalException("Missing " + localName + " element");
    }
    String name = elem.getLocalName();
    if (!name.equals(localName)) {
        throw new MarshalException("Invalid element name: " +
                                   name + ", expected " + localName);
    }
    return elem;
}
 
Example 9
Source File: TestingUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static String compareElements(String path, Element e1, Element e2) {
	if (!e1.getNamespaceURI().equals(e2.getNamespaceURI())) 
		return "Namespaces differ at "+path+": "+e1.getNamespaceURI()+"/"+e2.getNamespaceURI();
	if (!e1.getLocalName().equals(e2.getLocalName())) 
		return "Names differ at "+path+": "+e1.getLocalName()+"/"+e2.getLocalName();
	path = path + "/"+e1.getLocalName();
	String s = compareAttributes(path, e1.getAttributes(), e2.getAttributes());
	if (!Utilities.noString(s))
		return s;
	s = compareAttributes(path, e2.getAttributes(), e1.getAttributes());
	if (!Utilities.noString(s))
		return s;

	Node c1 = e1.getFirstChild();
	Node c2 = e2.getFirstChild();
	c1 = skipBlankText(c1);
	c2 = skipBlankText(c2);
	while (c1 != null && c2 != null) {
		if (c1.getNodeType() != c2.getNodeType()) 
			return "node type mismatch in children of "+path+": "+Integer.toString(e1.getNodeType())+"/"+Integer.toString(e2.getNodeType());
		if (c1.getNodeType() == Node.TEXT_NODE) {    
			if (!normalise(c1.getTextContent()).equals(normalise(c2.getTextContent())))
				return "Text differs at "+path+": "+normalise(c1.getTextContent()) +"/"+ normalise(c2.getTextContent());
		}
		else if (c1.getNodeType() == Node.ELEMENT_NODE) {
			s = compareElements(path, (Element) c1, (Element) c2);
			if (!Utilities.noString(s))
				return s;
		}

		c1 = skipBlankText(c1.getNextSibling());
		c2 = skipBlankText(c2.getNextSibling());
	}
	if (c1 != null)
		return "node mismatch - more nodes in source in children of "+path;
	if (c2 != null)
		return "node mismatch - more nodes in target in children of "+path;
	return null;
}
 
Example 10
Source File: GenericDOMDataVerifier.java    From xades4j with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public QualifyingProperty verify(
        GenericDOMData propData,
        QualifyingPropertyVerificationContext ctx) throws InvalidPropertyException
{
    final Element propElem = propData.getPropertyElement();
    QName propElemQName = new QName(propElem.getNamespaceURI(), propElem.getLocalName());

    QualifyingPropertyVerifier propVerifier = customElemVerifiers.get(propElemQName);
    if (null == propVerifier)
        throw new InvalidPropertyException()
        {
            @Override
            protected String getVerificationMessage()
            {
                return "Verifier not available for " + getPropertyName();
            }

            @Override
            public String getPropertyName()
            {
                return propElem.getLocalName();
            }
        };

    return propVerifier.verify(propData, ctx);
}
 
Example 11
Source File: AbstractBeanDefinitionParser.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void setFirstChildAsProperty(Element element, ParserContext ctx,
                                     BeanDefinitionBuilder bean, String propertyName) {

    Element first = getFirstChild(element);

    if (first == null) {
        throw new IllegalStateException(propertyName + " property must have child elements!");
    }

    String id;
    BeanDefinition child;
    if (first.getNamespaceURI().equals(BeanDefinitionParserDelegate.BEANS_NAMESPACE_URI)) {
        String name = first.getLocalName();
        if ("ref".equals(name)) {
            id = first.getAttribute("bean");
            if (id == null) {
                throw new IllegalStateException("<ref> elements must have a \"bean\" attribute!");
            }
            bean.addPropertyReference(propertyName, id);
            return;
        } else if ("bean".equals(name)) {
            BeanDefinitionHolder bdh = ctx.getDelegate().parseBeanDefinitionElement(first);
            child = bdh.getBeanDefinition();
            bean.addPropertyValue(propertyName, child);
            return;
        } else {
            throw new UnsupportedOperationException("Elements with the name " + name
                                                    + " are not currently "
                                                    + "supported as sub elements of "
                                                    + element.getLocalName());
        }
    }
    child = ctx.getDelegate().parseCustomElement(first, bean.getBeanDefinition());
    bean.addPropertyValue(propertyName, child);
}
 
Example 12
Source File: MetadataFinder.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Identifies WSDL documents from the {@link DOMForest}. Also identifies the root wsdl document.
 */
private void identifyRootWsdls(){
    for(String location: rootDocuments){
        Document doc = get(location);
        if(doc!=null){
            Element definition = doc.getDocumentElement();
            if(definition == null || definition.getLocalName() == null || definition.getNamespaceURI() == null)
                continue;
            if(definition.getNamespaceURI().equals(WSDLConstants.NS_WSDL) && definition.getLocalName().equals("definitions")){
                rootWsdls.add(location);
                //set the root wsdl at this point. Root wsdl is one which has wsdl:service in it
                NodeList nl = definition.getElementsByTagNameNS(WSDLConstants.NS_WSDL, "service");

                //TODO:what if there are more than one wsdl with wsdl:service element. Probably such cases
                //are rare and we will take any one of them, this logic should still work
                if(nl.getLength() > 0)
                    rootWSDL = location;
            }
        }
    }
    //no wsdl with wsdl:service found, throw error
    if(rootWSDL == null){
        StringBuilder strbuf = new StringBuilder();
        for(String str : rootWsdls){
            strbuf.append(str);
            strbuf.append('\n');
        }
        errorReceiver.error(null, WsdlMessages.FAILED_NOSERVICE(strbuf.toString()));
    }
}
 
Example 13
Source File: Internalizer.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Moves JAXB customizations under their respective target nodes.
 */
private void move(Element bindings, Map<Element, List<Node>> targetNodes) {
    List<Node> nodelist = targetNodes.get(bindings);

    if(nodelist == null) {
            return; // abort
    }

    for (Node target : nodelist) {
        if (target == null) // this must be the result of an error on the external binding.
        // recover from the error by ignoring this node
        {
            return;
        }

        for (Element item : DOMUtils.getChildElements(bindings)) {
            String localName = item.getLocalName();

            if ("bindings".equals(localName)) {
                // process child <jaxb:bindings> recursively
                move(item, targetNodes);
            } else if ("globalBindings".equals(localName)) {
                    // <jaxb:globalBindings> always go to the root of document.
                Element root = forest.getOneDocument().getDocumentElement();
                if (root.getNamespaceURI().equals(WSDL_NS)) {
                    NodeList elements = root.getElementsByTagNameNS(XMLConstants.W3C_XML_SCHEMA_NS_URI, "schema");
                    if ((elements == null) || (elements.getLength() < 1)) {
                        reportError(item, Messages.format(Messages.ORPHANED_CUSTOMIZATION, item.getNodeName()));
                        return;
                    } else {
                        moveUnder(item, (Element)elements.item(0));
                    }
                } else {
                    moveUnder(item, root);
                }
            } else {
                if (!(target instanceof Element)) {
                    reportError(item,
                            Messages.format(Messages.CONTEXT_NODE_IS_NOT_ELEMENT));
                    return; // abort
                }

                if (!forest.logic.checkIfValidTargetNode(forest, item, (Element) target)) {
                    reportError(item,
                            Messages.format(Messages.ORPHANED_CUSTOMIZATION, item.getNodeName()));
                    return; // abort
                }

                // move this node under the target
                moveUnder(item, (Element) target);
            }
        }
    }
}
 
Example 14
Source File: DOMRetrievalMethod.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a <code>DOMRetrievalMethod</code> from an element.
 *
 * @param rmElem a RetrievalMethod element
 */
public DOMRetrievalMethod(Element rmElem, XMLCryptoContext context,
                          Provider provider)
    throws MarshalException
{
    // get URI and Type attributes
    uri = DOMUtils.getAttributeValue(rmElem, "URI");
    type = DOMUtils.getAttributeValue(rmElem, "Type");

    // get here node
    here = rmElem.getAttributeNodeNS(null, "URI");

    boolean secVal = Utils.secureValidation(context);

    // get Transforms, if specified
    List<Transform> transforms = new ArrayList<Transform>();
    Element transformsElem = DOMUtils.getFirstChildElement(rmElem);

    if (transformsElem != null) {
        String localName = transformsElem.getLocalName();
        if (!localName.equals("Transforms")) {
            throw new MarshalException("Invalid element name: " +
                                       localName + ", expected Transforms");
        }
        Element transformElem =
            DOMUtils.getFirstChildElement(transformsElem, "Transform");
        transforms.add(new DOMTransform(transformElem, context, provider));
        transformElem = DOMUtils.getNextSiblingElement(transformElem);
        while (transformElem != null) {
            String name = transformElem.getLocalName();
            if (!name.equals("Transform")) {
                throw new MarshalException("Invalid element name: " +
                                           name + ", expected Transform");
            }
            transforms.add
                (new DOMTransform(transformElem, context, provider));
            if (secVal && (transforms.size() > DOMReference.MAXIMUM_TRANSFORM_COUNT)) {
                String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " "
                    + "transforms per Reference are allowed with secure validation";
                throw new MarshalException(error);
            }
            transformElem = DOMUtils.getNextSiblingElement(transformElem);
        }
    }
    if (transforms.isEmpty()) {
        this.transforms = Collections.emptyList();
    } else {
        this.transforms = Collections.unmodifiableList(transforms);
    }
}
 
Example 15
Source File: DOMRetrievalMethod.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a <code>DOMRetrievalMethod</code> from an element.
 *
 * @param rmElem a RetrievalMethod element
 */
public DOMRetrievalMethod(Element rmElem, XMLCryptoContext context,
                          Provider provider)
    throws MarshalException
{
    // get URI and Type attributes
    uri = DOMUtils.getAttributeValue(rmElem, "URI");
    type = DOMUtils.getAttributeValue(rmElem, "Type");

    // get here node
    here = rmElem.getAttributeNodeNS(null, "URI");

    boolean secVal = Utils.secureValidation(context);

    // get Transforms, if specified
    List<Transform> transforms = new ArrayList<Transform>();
    Element transformsElem = DOMUtils.getFirstChildElement(rmElem);

    if (transformsElem != null) {
        String localName = transformsElem.getLocalName();
        if (!localName.equals("Transforms")) {
            throw new MarshalException("Invalid element name: " +
                                       localName + ", expected Transforms");
        }
        Element transformElem =
            DOMUtils.getFirstChildElement(transformsElem, "Transform");
        transforms.add(new DOMTransform(transformElem, context, provider));
        transformElem = DOMUtils.getNextSiblingElement(transformElem);
        while (transformElem != null) {
            String name = transformElem.getLocalName();
            if (!name.equals("Transform")) {
                throw new MarshalException("Invalid element name: " +
                                           name + ", expected Transform");
            }
            transforms.add
                (new DOMTransform(transformElem, context, provider));
            if (secVal && (transforms.size() > DOMReference.MAXIMUM_TRANSFORM_COUNT)) {
                String error = "A maxiumum of " + DOMReference.MAXIMUM_TRANSFORM_COUNT + " "
                    + "transforms per Reference are allowed with secure validation";
                throw new MarshalException(error);
            }
            transformElem = DOMUtils.getNextSiblingElement(transformElem);
        }
    }
    if (transforms.isEmpty()) {
        this.transforms = Collections.emptyList();
    } else {
        this.transforms = Collections.unmodifiableList(transforms);
    }
}
 
Example 16
Source File: DOMKeyInfo.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a <code>DOMKeyInfo</code> from XML.
 *
 * @param kiElem KeyInfo element
 */
public DOMKeyInfo(Element kiElem, XMLCryptoContext context,
                  Provider provider)
    throws MarshalException
{
    // get Id attribute, if specified
    Attr attr = kiElem.getAttributeNodeNS(null, "Id");
    if (attr != null) {
        id = attr.getValue();
        kiElem.setIdAttributeNode(attr, true);
    } else {
        id = null;
    }

    // get all children nodes
    NodeList nl = kiElem.getChildNodes();
    int length = nl.getLength();
    if (length < 1) {
        throw new MarshalException
            ("KeyInfo must contain at least one type");
    }
    List<XMLStructure> content = new ArrayList<XMLStructure>(length);
    for (int i = 0; i < length; i++) {
        Node child = nl.item(i);
        // ignore all non-Element nodes
        if (child.getNodeType() != Node.ELEMENT_NODE) {
            continue;
        }
        Element childElem = (Element)child;
        String localName = childElem.getLocalName();
        if (localName.equals("X509Data")) {
            content.add(new DOMX509Data(childElem));
        } else if (localName.equals("KeyName")) {
            content.add(new DOMKeyName(childElem));
        } else if (localName.equals("KeyValue")) {
            content.add(DOMKeyValue.unmarshal(childElem));
        } else if (localName.equals("RetrievalMethod")) {
            content.add(new DOMRetrievalMethod(childElem,
                                               context, provider));
        } else if (localName.equals("PGPData")) {
            content.add(new DOMPGPData(childElem));
        } else { //may be MgmtData, SPKIData or element from other namespace
            content.add(new javax.xml.crypto.dom.DOMStructure((childElem)));
        }
    }
    keyInfoTypes = Collections.unmodifiableList(content);
}
 
Example 17
Source File: SOAPFaultBuilder.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private static @NotNull QName getFirstDetailEntryName(@NotNull Element entry) {
    return new QName(entry.getNamespaceURI(), entry.getLocalName());
}
 
Example 18
Source File: ODataAtomParser.java    From odata with Apache License 2.0 4 votes vote down vote up
private void setStructProperty(Object instance, StructuredType structType, Element propertyElement)
        throws ODataException {
    String propertyName = propertyElement.getLocalName();
    LOG.debug("Found property element: {}", propertyName);

    PropertyType propertyTypeFromXML = getPropertyTypeFromXML(propertyElement);
    if (propertyTypeFromXML == null) {
        LOG.debug("Skip rendering for {} property", propertyName);
        return;
    }

    LOG.debug("Property type from XML: {}", propertyTypeFromXML);

    StructuralProperty property = getStructuralProperty(getEntityDataModel(), structType, propertyName);
    if (property == null) {
        if (!structType.isOpen()) {
            LOG.debug("{} property is not found in the following {} type. Ignoring",
                    propertyName, structType.toString());
            return;
        } else {
            throw new ODataNotImplementedException("Open types are not supported, cannot set property value " +
                    "for property '" + propertyName + "' in instance of type: " + structType);
        }
    }


    if (propertyTypeFromXML.isCollection()) {
        if (!property.isCollection()) {
            throw new ODataUnmarshallingException("The type of the property '" + propertyName + "' is a " +
                    "collection type: " + propertyTypeFromXML + ", but according to the entity data model it " +
                    "is not a collection: " + property.getTypeName());
        }
    } else {
        if (property.isCollection()) {
            throw new ODataUnmarshallingException("The type of the property '" + propertyName + "' is not a " +
                    "collection type: " + propertyTypeFromXML + ", but according to the entity data model it " +
                    "is a collection: " + property.getTypeName());
        }
    }

    Object propertyValue;
    if (propertyTypeFromXML.isCollection()) {
        foundCollectionProperties.add(propertyName);
        Class<?> fieldType = property.getJavaField().getType();
        propertyValue = parsePropertyValueCollection(propertyElement, propertyTypeFromXML.getType(), fieldType);
    } else {
        propertyValue = parsePropertyValueSingle(propertyElement, propertyTypeFromXML.getType());
    }

    boolean notNullableProperty = propertyValue != null;

    LOG.debug("Property value: {} ({})", propertyValue,
            notNullableProperty ? propertyValue.getClass().getName() : "<null>");

    try {
        Field field = property.getJavaField();
        field.setAccessible(true);
        field.set(instance, propertyValue);
    } catch (IllegalAccessException e) {
        throw new ODataUnmarshallingException("Error while setting property value for property '" +
                propertyName + "': " + propertyValue, e);
    }
}
 
Example 19
Source File: ElementFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Create element wrapper for existing DOM element.
 *
 * @param ownerDocument SOAP document wrapper not null
 * @param element DOM element not null
 * @return SOAP wrapper for DOM element
 */
public static SOAPElement createElement(SOAPDocumentImpl ownerDocument, Element element) {
    Objects.requireNonNull(ownerDocument);
    Objects.requireNonNull(element);

    String localName = element.getLocalName();
    String namespaceUri = element.getNamespaceURI();
    String prefix = element.getPrefix();

    if ("Envelope".equalsIgnoreCase(localName)) {
        if (NameImpl.SOAP11_NAMESPACE.equals(namespaceUri)) {
            return new Envelope1_1Impl(ownerDocument, element);
        } else if (NameImpl.SOAP12_NAMESPACE.equals(namespaceUri)) {
            return new Envelope1_2Impl(ownerDocument, element);
        }
    }
    if ("Body".equalsIgnoreCase(localName)) {
        if (NameImpl.SOAP11_NAMESPACE.equals(namespaceUri)) {
            return new Body1_1Impl(ownerDocument, element);
        } else if (NameImpl.SOAP12_NAMESPACE.equals(namespaceUri)) {
            return new Body1_2Impl(ownerDocument, element);
        }
    }
    if ("Header".equalsIgnoreCase(localName)) {
        if (NameImpl.SOAP11_NAMESPACE.equals(namespaceUri)) {
            return new Header1_1Impl(ownerDocument, element);
        } else if (NameImpl.SOAP12_NAMESPACE.equals(namespaceUri)) {
            return new Header1_2Impl(ownerDocument, element);
        }
    }
    if ("Fault".equalsIgnoreCase(localName)) {
        if (NameImpl.SOAP11_NAMESPACE.equals(namespaceUri)) {
            return new Fault1_1Impl(ownerDocument, element);
        } else if (NameImpl.SOAP12_NAMESPACE.equals(namespaceUri)) {
            return new Fault1_2Impl(ownerDocument, element);
        }

    }
    if ("Detail".equalsIgnoreCase(localName)) {
        if (NameImpl.SOAP11_NAMESPACE.equals(namespaceUri)) {
            return new Detail1_1Impl(ownerDocument, element);
        } else if (NameImpl.SOAP12_NAMESPACE.equals(namespaceUri)) {
            return new Detail1_2Impl(ownerDocument, element);
        }
    }
    if ("faultcode".equalsIgnoreCase(localName)
            || "faultstring".equalsIgnoreCase(localName)
            || "faultactor".equalsIgnoreCase(localName)) {
        // SOAP 1.2 does not have fault(code/string/actor)
        // So there is no else case required
        if (NameImpl.SOAP11_NAMESPACE.equals(namespaceUri)) {
            return new FaultElement1_1Impl(ownerDocument,
                    localName,
                    prefix);
        }
    }

    return new ElementImpl(ownerDocument, element);
}
 
Example 20
Source File: EwsServiceXmlWriter.java    From ews-java-api with MIT License 4 votes vote down vote up
/**
 * @param element DOM element
 * @param writer XML stream writer
 * @throws XMLStreamException the XML stream exception
 */
public static void addElement(Element element, XMLStreamWriter writer)
    throws XMLStreamException {
  String nameSpace = element.getNamespaceURI();
  String prefix = element.getPrefix();
  String localName = element.getLocalName();
  if (prefix == null) {
    prefix = "";
  }
  if (localName == null) {
    localName = element.getNodeName();

    if (localName == null) {
      throw new IllegalStateException(
          "Element's local name cannot be null!");
    }
  }

  String decUri = writer.getNamespaceContext().getNamespaceURI(prefix);
  boolean declareNamespace = decUri == null || !decUri.equals(nameSpace);

  if (nameSpace == null || nameSpace.length() == 0) {
    writer.writeStartElement(localName);
  } else {
    writer.writeStartElement(prefix, localName, nameSpace);
  }

  NamedNodeMap attrs = element.getAttributes();
  for (int i = 0; i < attrs.getLength(); i++) {
    Node attr = attrs.item(i);

    String name = attr.getNodeName();
    String attrPrefix = "";
    int prefixIndex = name.indexOf(':');
    if (prefixIndex != -1) {
      attrPrefix = name.substring(0, prefixIndex);
      name = name.substring(prefixIndex + 1);
    }

    if ("xmlns".equals(attrPrefix)) {
      writer.writeNamespace(name, attr.getNodeValue());
      if (name.equals(prefix)
          && attr.getNodeValue().equals(nameSpace)) {
        declareNamespace = false;
      }
    } else {
      if ("xmlns".equals(name) && "".equals(attrPrefix)) {
        writer.writeNamespace("", attr.getNodeValue());
        if (attr.getNodeValue().equals(nameSpace)) {
          declareNamespace = false;
        }
      } else {
        writer.writeAttribute(attrPrefix, attr.getNamespaceURI(),
            name, attr.getNodeValue());
      }
    }
  }

  if (declareNamespace) {
    if (nameSpace == null) {
      writer.writeNamespace(prefix, "");
    } else {
      writer.writeNamespace(prefix, nameSpace);
    }
  }

  NodeList nodes = element.getChildNodes();
  for (int i = 0; i < nodes.getLength(); i++) {
    Node n = nodes.item(i);
    writeNode(n, writer);
  }


  writer.writeEndElement();

}