Example usage for org.w3c.dom Element hasAttribute

List of usage examples for org.w3c.dom Element hasAttribute

Introduction

In this page you can find the example usage for org.w3c.dom Element hasAttribute.

Prototype

public boolean hasAttribute(String name);

Source Link

Document

Returns true when an attribute with a given name is specified on this element or has a default value, false otherwise.

Usage

From source file:com.example.soaplegacy.SchemaUtils.java

/**
 * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the
 * specified wsdlUrl//from w  w  w .j  a v  a  2s .c o  m
 */
public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader,
        String tns) {
    if (existing.containsKey(wsdlUrl)) {
        return;
    }

    log.debug("Getting schema " + wsdlUrl);

    ArrayList<?> errorList = new ArrayList<Object>();

    Map<String, XmlObject> result = new HashMap<String, XmlObject>();

    boolean common = false;

    try {
        XmlOptions options = new XmlOptions();
        options.setCompileNoValidation();
        options.setSaveUseOpenFrag();
        options.setErrorListener(errorList);
        options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema"));

        XmlObject xmlObject = loader.loadXmlObject(wsdlUrl, options);
        if (xmlObject == null)
            throw new Exception("Failed to load schema from [" + wsdlUrl + "]");

        Document dom = (Document) xmlObject.getDomNode();
        Node domNode = dom.getDocumentElement();

        // is this an xml schema?
        if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) {
            // set targetNamespace (this happens if we are following an include
            // statement)
            if (tns != null) {
                Element elm = ((Element) domNode);
                if (!elm.hasAttribute("targetNamespace")) {
                    common = true;
                    elm.setAttribute("targetNamespace", tns);
                }

                // check for namespace prefix for targetNamespace
                NamedNodeMap attributes = elm.getAttributes();
                int c = 0;
                for (; c < attributes.getLength(); c++) {
                    Node item = attributes.item(c);
                    if (item.getNodeName().equals("xmlns"))
                        break;

                    if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns"))
                        break;
                }

                if (c == attributes.getLength())
                    elm.setAttribute("xmlns", tns);
            }

            if (common && !existing.containsKey(wsdlUrl + "@" + tns))
                result.put(wsdlUrl + "@" + tns, xmlObject);
            else
                result.put(wsdlUrl, xmlObject);
        } else {
            existing.put(wsdlUrl, null);

            XmlObject[] schemas = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema");

            for (int i = 0; i < schemas.length; i++) {
                XmlCursor xmlCursor = schemas[i].newCursor();
                String xmlText = xmlCursor.getObject().xmlText(options);
                // schemas[i] = XmlObject.Factory.parse( xmlText, options );
                schemas[i] = XmlUtils.createXmlObject(xmlText, options);
                schemas[i].documentProperties().setSourceName(wsdlUrl);

                result.put(wsdlUrl + "@" + (i + 1), schemas[i]);
            }

            XmlObject[] wsdlImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location");
            for (int i = 0; i < wsdlImports.length; i++) {
                String location = ((SimpleValue) wsdlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadl10Imports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadl10Imports.length; i++) {
                String location = ((SimpleValue) wadl10Imports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadlImports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadlImports.length; i++) {
                String location = ((SimpleValue) wadlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

        }

        existing.putAll(result);

        XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]);

        for (int c = 0; c < schemas.length; c++) {
            xmlObject = schemas[c];

            XmlObject[] schemaImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation");
            for (int i = 0; i < schemaImports.length; i++) {
                String location = ((SimpleValue) schemaImports[i]).getStringValue();
                Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement();

                if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] schemaIncludes = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation");
            for (int i = 0; i < schemaIncludes.length; i++) {
                String location = ((SimpleValue) schemaIncludes[i]).getStringValue();
                if (location != null) {
                    String targetNS = getTargetNamespace(xmlObject);

                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, targetNS);
                }
            }
        }
    } catch (Exception e) {
        throw new SoapBuilderException(e);
    }
}

From source file:Main.java

public static String getXPath(Node node) {
    if (null == node)
        return null;

    // declarations
    Node parent = null;//w w w .  j  a  v  a2 s . c  o m
    Stack<Node> hierarchy = new Stack<Node>();
    StringBuilder buffer = new StringBuilder();

    // push element on stack
    hierarchy.push(node);

    parent = node.getParentNode();
    while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) {
        // push on stack
        hierarchy.push(parent);

        // get parent of parent
        parent = parent.getParentNode();
    }

    // construct xpath
    Object obj = null;
    while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) {
        Node n = (Node) obj;
        boolean handled = false;

        // only consider elements
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            Element e = (Element) n;

            // is this the root element?
            if (buffer.length() == 0) {
                // root element - simply append element name
                buffer.append(n.getNodeName());
            } else {
                // child element - append slash and element name
                buffer.append("/");
                buffer.append(n.getNodeName());

                if (n.hasAttributes()) {
                    // see if the element has a name or id attribute
                    if (e.hasAttribute("id")) {
                        // id attribute found - use that
                        buffer.append("[@id='" + e.getAttribute("id") + "']");
                        handled = true;
                    } else if (e.hasAttribute("name")) {
                        // name attribute found - use that
                        buffer.append("[@name='" + e.getAttribute("name") + "']");
                        handled = true;
                    }
                }

                if (!handled) {
                    // no known attribute we could use - get sibling index
                    int prev_siblings = 1;
                    Node prev_sibling = n.getPreviousSibling();
                    while (null != prev_sibling) {
                        if (prev_sibling.getNodeType() == n.getNodeType()) {
                            if (prev_sibling.getNodeName().equalsIgnoreCase(n.getNodeName())) {
                                prev_siblings++;
                            }
                        }
                        prev_sibling = prev_sibling.getPreviousSibling();
                    }
                    buffer.append("[" + prev_siblings + "]");
                }
            }
        }
    }

    // return buffer
    return buffer.toString();
}

From source file:com.ibm.soatf.component.soap.builder.SchemaUtils.java

/**
 * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the
 * specified wsdlUrl//from w w  w  .j av a  2 s. c  om
 */
public static void getSchemas(final String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader,
        String tns) {
    if (existing.containsKey(wsdlUrl)) {
        return;
    }

    log.debug("Getting schema " + wsdlUrl);

    ArrayList<?> errorList = new ArrayList<>();

    Map<String, XmlObject> result = new HashMap<>();

    boolean common = false;

    try {
        XmlOptions options = new XmlOptions();
        options.setCompileNoValidation();
        options.setSaveUseOpenFrag();
        options.setErrorListener(errorList);
        options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema"));

        XmlObject xmlObject = loader.loadXmlObject(wsdlUrl, options);
        if (xmlObject == null)
            throw new Exception("Failed to load schema from [" + wsdlUrl + "]");

        Document dom = (Document) xmlObject.getDomNode();
        Node domNode = dom.getDocumentElement();

        // is this an xml schema?
        if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) {
            // set targetNamespace (this happens if we are following an include
            // statement)
            if (tns != null) {
                Element elm = ((Element) domNode);
                if (!elm.hasAttribute("targetNamespace")) {
                    common = true;
                    elm.setAttribute("targetNamespace", tns);
                }

                // check for namespace prefix for targetNamespace
                NamedNodeMap attributes = elm.getAttributes();
                int c = 0;
                for (; c < attributes.getLength(); c++) {
                    Node item = attributes.item(c);
                    if (item.getNodeName().equals("xmlns"))
                        break;

                    if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns"))
                        break;
                }

                if (c == attributes.getLength())
                    elm.setAttribute("xmlns", tns);
            }

            if (common && !existing.containsKey(wsdlUrl + "@" + tns))
                result.put(wsdlUrl + "@" + tns, xmlObject);
            else
                result.put(wsdlUrl, xmlObject);
        } else {
            existing.put(wsdlUrl, null);

            XmlObject[] schemas = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema");

            for (int i = 0; i < schemas.length; i++) {
                XmlCursor xmlCursor = schemas[i].newCursor();
                String xmlText = xmlCursor.getObject().xmlText(options);
                // schemas[i] = XmlObject.Factory.parse( xmlText, options );
                schemas[i] = XmlUtils.createXmlObject(xmlText, options);
                schemas[i].documentProperties().setSourceName(wsdlUrl);

                result.put(wsdlUrl + "@" + (i + 1), schemas[i]);
            }

            XmlObject[] wsdlImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location");
            for (int i = 0; i < wsdlImports.length; i++) {
                String location = ((SimpleValue) wsdlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadl10Imports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadl10Imports.length; i++) {
                String location = ((SimpleValue) wadl10Imports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadlImports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadlImports.length; i++) {
                String location = ((SimpleValue) wadlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }
        }

        existing.putAll(result);

        XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]);
        for (int c = 0; c < schemas.length; c++) {
            xmlObject = schemas[c];

            XmlObject[] schemaImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation");
            for (int i = 0; i < schemaImports.length; i++) {
                String location = ((SimpleValue) schemaImports[i]).getStringValue();
                Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement();

                if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] schemaIncludes = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation");
            for (int i = 0; i < schemaIncludes.length; i++) {
                String location = ((SimpleValue) schemaIncludes[i]).getStringValue();
                if (location != null) {
                    String targetNS = getTargetNamespace(xmlObject);

                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, targetNS);
                }
            }
        }
    } catch (Exception e) {
        throw new SoapBuilderException(e);
    }
}

From source file:com.centeractive.ws.legacy.SchemaUtils.java

/**
 * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the specified wsdlUrl
 *//*w ww. j a  v  a2 s  .  c om*/
public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader,
        String tns) {
    if (existing.containsKey(wsdlUrl)) {
        return;
    }

    log.debug("Getting schema " + wsdlUrl);

    ArrayList<?> errorList = new ArrayList<Object>();

    Map<String, XmlObject> result = new HashMap<String, XmlObject>();

    boolean common = false;

    try {
        XmlOptions options = new XmlOptions();
        options.setCompileNoValidation();
        options.setSaveUseOpenFrag();
        options.setErrorListener(errorList);
        options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema"));

        XmlObject xmlObject = loader.loadXmlObject(wsdlUrl, options);
        if (xmlObject == null) {
            throw new Exception("Failed to load schema from [" + wsdlUrl + "]");
        }

        Document dom = (Document) xmlObject.getDomNode();
        Node domNode = dom.getDocumentElement();

        // is this an xml schema?
        if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) {
            // set targetNamespace (this happens if we are following an include
            // statement)
            if (tns != null) {
                Element elm = ((Element) domNode);
                if (!elm.hasAttribute("targetNamespace")) {
                    common = true;
                    elm.setAttribute("targetNamespace", tns);
                }

                // check for namespace prefix for targetNamespace
                NamedNodeMap attributes = elm.getAttributes();
                int c = 0;
                for (; c < attributes.getLength(); c++) {
                    Node item = attributes.item(c);
                    if (item.getNodeName().equals("xmlns")) {
                        break;
                    }

                    if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns")) {
                        break;
                    }
                }

                if (c == attributes.getLength()) {
                    elm.setAttribute("xmlns", tns);
                }
            }

            if (common && !existing.containsKey(wsdlUrl + "@" + tns)) {
                result.put(wsdlUrl + "@" + tns, xmlObject);
            } else {
                result.put(wsdlUrl, xmlObject);
            }
        } else {
            existing.put(wsdlUrl, null);

            XmlObject[] schemas = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema");

            for (int i = 0; i < schemas.length; i++) {

                XmlCursor xmlCursor = schemas[i].newCursor();
                String xmlText = xmlCursor.getObject().xmlText(options);
                // schemas[i] = XmlObject.Factory.parse( xmlText, options );
                schemas[i] = XmlUtils.createXmlObject(xmlText, options);
                schemas[i].documentProperties().setSourceName(wsdlUrl);

                result.put(wsdlUrl + "@" + (i + 1), schemas[i]);
            }

            XmlObject[] wsdlImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location");
            for (int i = 0; i < wsdlImports.length; i++) {

                String location = ((SimpleValue) wsdlImports[i]).getStringValue();

                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1) {
                        location = joinRelativeUrl(wsdlUrl, location);
                    }

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadl10Imports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadl10Imports.length; i++) {
                String location = ((SimpleValue) wadl10Imports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1) {
                        location = joinRelativeUrl(wsdlUrl, location);
                    }

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadlImports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadlImports.length; i++) {
                String location = ((SimpleValue) wadlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1) {
                        location = joinRelativeUrl(wsdlUrl, location);
                    }

                    getSchemas(location, existing, loader, null);
                }
            }

        }

        existing.putAll(result);

        XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]);

        for (int c = 0; c < schemas.length; c++) {
            xmlObject = schemas[c];

            XmlObject[] schemaImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation");
            for (int i = 0; i < schemaImports.length; i++) {
                String location = ((SimpleValue) schemaImports[i]).getStringValue();
                Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement();

                if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1) {
                        location = joinRelativeUrl(wsdlUrl, location);
                    }

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] schemaIncludes = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation");
            for (int i = 0; i < schemaIncludes.length; i++) {
                String location = ((SimpleValue) schemaIncludes[i]).getStringValue();
                if (location != null) {
                    String targetNS = getTargetNamespace(xmlObject);

                    if (!location.startsWith("file:") && location.indexOf("://") == -1) {
                        location = joinRelativeUrl(wsdlUrl, location);
                    }

                    getSchemas(location, existing, loader, targetNS);
                }
            }
        }
    } catch (Exception e) {
        throw new SoapBuilderException(e);
    }
}

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

/**
 * For the given element, return the value of the given attribute if it exists,
 * or null if it doesn't exist. Note that this is different from calling
 * e.getAttribute(), which will return the empty string both if the attribute
 * doesn't exist and if it exists and has the empty value. 
 * @param e/*from w  ww  .  j av  a2 s  . co  m*/
 * @param attributeName
 * @return the String value of the attribute if it exists, or null
 */
public static String getAttributeIfAvailable(Element e, String attributeName) {
    if (!e.hasAttribute(attributeName)) {
        return null;
    }
    return e.getAttribute(attributeName);
}

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

/**
 * For the given element, return the value of the given attribute if it exists,
 * or complain with a MessageFormatException if it doesn't exist.
 * @param e the element whose attribute to return
 * @param attributeName the name of the attribute to look up.
 * @return the String value of the attribute if it exists
 * @throws MessageFormatException if the attribute doesn't exist.
 *//*from  ww  w .j  a  v  a 2s . com*/
public static String needAttribute(Element e, String attributeName) throws MessageFormatException {
    if (!e.hasAttribute(attributeName)) {
        throw new MessageFormatException("Element '" + e.getTagName() + "' in namespace '" + e.getNamespaceURI()
                + "' needs an attribute '" + attributeName + "'");
    }
    return e.getAttribute(attributeName);
}

From source file:de.betterform.xml.xforms.ui.state.UIElementStateUtil.java

private static Map<String, Object> getAlertInfo(BindingElement bindingElement, ModelItem modelItem,
        RefreshView refreshView) {/*  w w w  .j  av  a 2  s.  co m*/
    Element alertElem = (Element) DOMUtil.getFirstChildByTagNameNS(bindingElement.getElement(),
            NamespaceConstants.XFORMS_NS, "alert");
    Map<String, Object> context = new HashMap<String, Object>();
    ;
    if (alertElem != null) {
        if (alertElem.hasAttribute("srcBind")) {
            buildConstraintContextInfo(context, modelItem, refreshView);
        } else {
            //                Element e = XFormsUtil.getFirstXFormsElement(bindingElement.getElement(), XFormsConstants.ALERT);
            String alertMsg = DOMUtil.getTextNodeAsString(alertElem);
            //use standard alert element from UI
            List invalidConstraints = new ArrayList(1);
            invalidConstraints.add(alertMsg);
            context.put("alerts", invalidConstraints);
        }

    }
    return context;
}

From source file:net.exclaimindustries.geohashdroid.wiki.WikiUtils.java

/**
 * Returns whether or not a given wiki page or file exists.
 * /* www  .ja  v  a  2 s  .  c om*/
 * @param  httpclient an active HTTP session 
 * @param  pagename   the name of the wiki page
 * @return            true if the page exists, false if not
 * @throws WikiException problem with the wiki, translate the ID
 * @throws Exception     anything else happened, use getMessage
 */
public static boolean doesWikiPageExist(HttpClient httpclient, String pagename) throws Exception {
    // It's GET time!  This is basically the same as the content request, but
    // we really don't need ANY data other than whether or not the page
    // exists, so we won't call for anything.
    HttpGet httpget = new HttpGet(
            WIKI_API_URL + "?action=query&format=xml&titles=" + URLEncoder.encode(pagename, "UTF-8"));

    Document response = getHttpDocument(httpclient, httpget);

    // Now for some of the usual checking that should look familiar...
    Element root = response.getDocumentElement();

    // Error check!
    if (doesResponseHaveError(root)) {
        throw new WikiException(getErrorTextId(findErrorCode(root)));
    }

    Element pageElem;
    try {
        pageElem = DOMUtil.getFirstElement(root, "page");
    } catch (Exception e) {
        throw new WikiException(R.string.wiki_error_xml);
    }

    // "invalid" or "missing" both resolve to the same answer: No.  Anything
    // else means yes.
    if (pageElem.hasAttribute("invalid") || pageElem.hasAttribute("missing"))
        return false;
    else
        return true;
}

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

/**
 * Create an XML document from the given XPath expression.
 * The given string is interpreted as a limited subset of XPath expressions and split into parts.
 * Each part except the last one is expected to follow precisely the following form:
 * <code>"/" ( prefix ":" ) ? localname ( "[" "@" attName "=" "'" attValue "'" "]" ) ?</code>
 * The last part must be either/*from   w ww  .  ja v a  2s  . c o  m*/
 * <code> "/" "text()"</code>
 * or
 * </code> "/" "@" attributeName </code>.
 * @param xpathExpression an xpath expression from which the given document can be created. must not be null.
 * @param value the value to insert at the location identified by the xpath expression. if this is null, the empty string is added.
 * @param namespaceContext the namespace context to use for resolving namespace prefixes.
 *  If this is null, the namespace context returned by {@link #getDefaultNamespaceContext()} will be used.
 * @param document if not null, the xpath expression + value pair will be added to the document. 
 * If null, a new document will be created from the xpathExpression and value pair.
 * @return a document containing the given information
 * @throws NullPointerException if xpathExpression is null.
 * @throws IllegalArgumentException if the xpath expression is not valid, or if the xpath expression is incompatible with the given document (e.g., different root node) 
 */
public static Document xpath2doc(String xpathExpression, String value, NamespaceContext namespaceContext,
        Document document) throws NullPointerException, IllegalArgumentException {
    if (xpathExpression == null) {
        throw new NullPointerException("null argument");
    }
    if (value == null) {
        value = "";
    }
    if (namespaceContext == null) {
        namespaceContext = getDefaultNamespaceContext();
    }
    String[][] parts = splitXPathIntoParts(xpathExpression);
    Element currentElt = null;

    for (int i = 0; i < parts.length - 1; i++) {
        String[] part = parts[i];
        assert part != null;
        assert part.length == 4;
        String prefix = part[0];
        String localName = part[1];
        String attName = part[2];
        String attValue = part[3];
        String namespaceURI = prefix != null ? namespaceContext.getNamespaceURI(prefix) : null;
        if (prefix != null && namespaceURI.equals("")) {
            throw new IllegalArgumentException("Unknown prefix: " + prefix);
        }
        // Now traverse to or create element defined by prefix, localName and namespaceURI
        if (currentElt == null) { // at top level
            if (document == null) { // create a new document
                try {
                    document = XMLTool.newDocument(localName, namespaceURI);
                } catch (DOMException de) {
                    throw new IllegalArgumentException("Cannot create document for localname '" + localName
                            + "' and namespaceURI '" + namespaceURI + "'", de);
                }
                currentElt = document.getDocumentElement();
                currentElt.setPrefix(prefix);
            } else {
                currentElt = document.getDocumentElement();
                if (!currentElt.getLocalName().equals(localName)) {
                    throw new IllegalArgumentException(
                            "Incompatible root node specification: expression requests '" + localName
                                    + "', but document already has '" + currentElt.getLocalName() + "'!");
                }
                String currentNamespaceURI = currentElt.getNamespaceURI();
                if (!(currentNamespaceURI == null && namespaceURI == null
                        || currentNamespaceURI != null && currentNamespaceURI.equals(namespaceURI))) {
                    throw new IllegalArgumentException(
                            "Incompatible root namespace specification: expression requests '" + namespaceURI
                                    + "', but document already has '" + currentNamespaceURI + "'!");
                }
            }
        } else { // somewhere in the tree
            // First check if the requested child already exists
            List<Element> sameNameChildren = XMLTool.getChildrenByLocalNameNS(currentElt, localName,
                    namespaceURI);
            boolean found = false;
            if (attName == null) {
                if (sameNameChildren.size() > 0) {
                    currentElt = sameNameChildren.get(0);
                    found = true;
                }
            } else {
                for (Element c : sameNameChildren) {
                    if (c.hasAttribute(attName)) {
                        if (attValue == null || attValue.equals(c.getAttribute(attName))) {
                            currentElt = c;
                            found = true;
                            break;
                        }
                    }
                }
            }
            if (!found) { // need to create it
                currentElt = XMLTool.appendChildElement(currentElt, localName, namespaceURI);
                if (prefix != null)
                    currentElt.setPrefix(prefix);
                if (attName != null) {
                    currentElt.setAttribute(attName, attValue != null ? attValue : "");
                }
            }
        }

    }
    if (currentElt == null) {
        throw new IllegalArgumentException(
                "No elements or no final part created from XPath expression '" + xpathExpression + "'");
    }
    String[] lastPart = parts[parts.length - 1];
    assert lastPart.length <= 1;
    if (lastPart.length == 0) { // text content of the given node
        currentElt.setTextContent(value);
    } else {
        String attName = lastPart[0];
        currentElt.setAttribute(attName, value);
    }
    return document;
}

From source file:com.centeractive.ws.builder.soap.SchemaUtils.java

/**
 * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the
 * specified wsdlUrl//from w w w  .j a  va 2 s  . c om
 */

public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader,
        String tns) {
    if (existing.containsKey(wsdlUrl)) {
        return;
    }

    // if( add )
    // existing.put( wsdlUrl, null );

    log.info("Getting schema " + wsdlUrl);

    ArrayList<?> errorList = new ArrayList<Object>();

    Map<String, XmlObject> result = new HashMap<String, XmlObject>();

    boolean common = false;

    try {
        XmlOptions options = new XmlOptions();
        options.setCompileNoValidation();
        options.setSaveUseOpenFrag();
        options.setErrorListener(errorList);
        options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema"));

        XmlObject xmlObject = loader.loadXmlObject(wsdlUrl, options);
        if (xmlObject == null)
            throw new Exception("Failed to load schema from [" + wsdlUrl + "]");

        Document dom = (Document) xmlObject.getDomNode();
        Node domNode = dom.getDocumentElement();

        // is this an xml schema?
        if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) {
            // set targetNamespace (this happens if we are following an include
            // statement)
            if (tns != null) {
                Element elm = ((Element) domNode);
                if (!elm.hasAttribute("targetNamespace")) {
                    common = true;
                    elm.setAttribute("targetNamespace", tns);
                }

                // check for namespace prefix for targetNamespace
                NamedNodeMap attributes = elm.getAttributes();
                int c = 0;
                for (; c < attributes.getLength(); c++) {
                    Node item = attributes.item(c);
                    if (item.getNodeName().equals("xmlns"))
                        break;

                    if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns"))
                        break;
                }

                if (c == attributes.getLength())
                    elm.setAttribute("xmlns", tns);
            }

            if (common && !existing.containsKey(wsdlUrl + "@" + tns))
                result.put(wsdlUrl + "@" + tns, xmlObject);
            else
                result.put(wsdlUrl, xmlObject);
        } else {
            existing.put(wsdlUrl, null);

            XmlObject[] schemas = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema");

            for (int i = 0; i < schemas.length; i++) {
                XmlCursor xmlCursor = schemas[i].newCursor();
                String xmlText = xmlCursor.getObject().xmlText(options);
                // schemas[i] = XmlObject.Factory.parse( xmlText, options );
                schemas[i] = XmlUtils.createXmlObject(xmlText, options);
                schemas[i].documentProperties().setSourceName(wsdlUrl);

                result.put(wsdlUrl + "@" + (i + 1), schemas[i]);
            }

            XmlObject[] wsdlImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location");
            for (int i = 0; i < wsdlImports.length; i++) {
                String location = ((SimpleValue) wsdlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadl10Imports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadl10Imports.length; i++) {
                String location = ((SimpleValue) wadl10Imports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] wadlImports = xmlObject.selectPath(
                    "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href");
            for (int i = 0; i < wadlImports.length; i++) {
                String location = ((SimpleValue) wadlImports[i]).getStringValue();
                if (location != null) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

        }

        existing.putAll(result);

        XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]);

        for (int c = 0; c < schemas.length; c++) {
            xmlObject = schemas[c];

            XmlObject[] schemaImports = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation");
            for (int i = 0; i < schemaImports.length; i++) {
                String location = ((SimpleValue) schemaImports[i]).getStringValue();
                Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement();

                if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) {
                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, null);
                }
            }

            XmlObject[] schemaIncludes = xmlObject
                    .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation");
            for (int i = 0; i < schemaIncludes.length; i++) {
                String location = ((SimpleValue) schemaIncludes[i]).getStringValue();
                if (location != null) {
                    String targetNS = getTargetNamespace(xmlObject);

                    if (!location.startsWith("file:") && location.indexOf("://") == -1)
                        location = joinRelativeUrl(wsdlUrl, location);

                    getSchemas(location, existing, loader, targetNS);
                }
            }
        }
    } catch (Exception e) {
        throw new SoapBuilderException(e);
    }
}