Example usage for org.w3c.dom Document importNode

List of usage examples for org.w3c.dom Document importNode

Introduction

In this page you can find the example usage for org.w3c.dom Document importNode.

Prototype

public Node importNode(Node importedNode, boolean deep) throws DOMException;

Source Link

Document

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.

Usage

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Inserts the type fragment into the given wsdl document and ensures
 * that definitions from each embedded schema are allowed to reference
 * schema components from the other sibling schemas.
 * @param doc/*from   ww  w . j  a  v a  2s .c  om*/
 */
public void insertTypesFragment(Document doc) {

    updateNamespaces();

    if (wsdlTypesElem == null)
        return;

    // Make sure that definitions from each embedded schema are allowed
    // to reference schema components from the other sibling schemas.
    Element schemaElem = null;
    String tns = null;
    NodeList nl = wsdlTypesElem.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++) {
        NamedNodeMap attrs = nl.item(i).getAttributes();
        if (attrs == null)
            continue; // Should never happen.
        for (int n = 0; n < attrs.getLength(); n++) {
            Attr a = (Attr) attrs.item(n);
            if (a.getName().equals("targetNamespace")) {
                tns = a.getValue();
                schemaElem = (Element) nl.item(i);
                break;
            }
        }

        // Ignore what appears to be a not namespace-qualified
        // schema definition.
        if (tns != null && !"".equals(tns.trim())) {
            // By now we know that an import element might be necessary
            // for some sibling schemas. However, in the absence of
            // a symbol table proper, the best we can do is add one
            // for each sibling schema.
            Iterator it = schemaTypes.keySet().iterator();
            String otherTns;
            Element importElem;
            while (it.hasNext()) {
                if (!tns.equals(otherTns = (String) it.next())) {
                    importElem = docHolder.createElement("import");
                    importElem.setAttribute("namespace", otherTns);
                    schemaElem.insertBefore(importElem, schemaElem.getFirstChild());
                }
            }
        }
        schemaElem = null;
        tns = null;
    }

    // Import the wsdlTypesElement into the doc.
    org.w3c.dom.Node node = doc.importNode(wsdlTypesElem, true);
    // Insert the imported element at the beginning of the document
    doc.getDocumentElement().insertBefore(node, doc.getDocumentElement().getFirstChild());
}

From source file:org.apache.axis2.description.WSDL11ToAxisServiceBuilder.java

private void addElementToAnExistingSchema(Element schemaElement, Element newElement, Map namespacePrefixMap,
        Map namespaceImportsMap, String targetNamespace) {

    Document ownerDocument = schemaElement.getOwnerDocument();

    String newElementName = newElement.getAttribute(XSD_NAME);

    // check whether this element already exists.
    NodeList nodeList = schemaElement.getChildNodes();
    Element nodeElement = null;//from  w  ww. j ava2  s . com
    for (int i = 1; i < nodeList.getLength(); i++) {
        if (nodeList.item(i) instanceof Element) {
            nodeElement = (Element) nodeList.item(i);
            if (nodeElement.getLocalName().equals(XML_SCHEMA_ELEMENT_LOCAL_NAME)) {
                if (nodeElement.getAttribute(XSD_NAME).equals(newElementName)) {
                    // if the element already exists we do not add this element
                    // and just return.
                    return;
                }
            }
        }

    }

    // loop through the namespace declarations first and add them
    String[] nameSpaceDeclarationArray = (String[]) namespacePrefixMap.keySet()
            .toArray(new String[namespacePrefixMap.size()]);
    for (int i = 0; i < nameSpaceDeclarationArray.length; i++) {
        String s = nameSpaceDeclarationArray[i];
        checkAndAddNamespaceDeclarations(s, namespacePrefixMap, schemaElement);
    }

    // add imports - check whether it is the targetnamespace before
    // adding
    Element[] namespaceImports = (Element[]) namespaceImportsMap.values()
            .toArray(new Element[namespaceImportsMap.size()]);
    for (int i = 0; i < namespaceImports.length; i++) {
        if (!targetNamespace.equals(namespaceImports[i].getAttribute(NAMESPACE_URI))) {
            schemaElement.appendChild(ownerDocument.importNode(namespaceImports[i], true));
        }
    }

    schemaElement.appendChild(ownerDocument.importNode(newElement, true));

}

From source file:org.apache.axis2.wsdl.codegen.emitter.AxisServiceBasedMultiLanguageEmitter.java

/**
 * Creates the DOM tree for implementations.
 */// ww  w  . ja  va  2  s.c  om
protected Document createDOMDocumentForInterfaceImplementation() throws Exception {

    String packageName = codeGenConfiguration.getPackageName();
    String localPart = makeJavaClassName(axisService.getName());
    String stubName = makeJavaClassName(axisService.getName() + axisService.getEndpointName()) + STUB_SUFFIX;
    Document doc = getEmptyDocument();
    Element rootElement = doc.createElement("class");

    addAttribute(doc, "package", packageName, rootElement);

    addAttribute(doc, "servicename", localPart, rootElement);
    //The target nemespace is added as the namespace for this service
    addAttribute(doc, "namespace", axisService.getTargetNamespace(), rootElement);
    if (this.codeGenConfiguration.isBackwordCompatibilityMode()) {
        addAttribute(doc, "interfaceName",
                makeJavaClassName(axisService.getEndpointName()) + STUB_INTERFACE_SUFFIX_BACK, rootElement);
        addAttribute(doc, "name", makeJavaClassName(axisService.getBindingName()) + STUB_SUFFIX, rootElement);
    } else {
        if (this.axisService.getEndpoints().size() > 1) {
            addAttribute(doc, "interfaceName",
                    makeJavaClassName(axisService.getName() + axisService.getEndpointName()), rootElement);
            addAttribute(doc, "name", stubName, rootElement);
        } else {
            addAttribute(doc, "interfaceName", makeJavaClassName(axisService.getName()), rootElement);
            addAttribute(doc, "name", makeJavaClassName(axisService.getName()) + STUB_SUFFIX, rootElement);
        }

    }

    if (codeGenConfiguration.isPackClasses()) {
        if (this.axisService.getEndpoints().size() > 1) {
            addAttribute(doc, "callbackname",
                    makeJavaClassName(axisService.getName() + axisService.getEndpointName())
                            + CALL_BACK_HANDLER_SUFFIX,
                    rootElement);
        } else {
            addAttribute(doc, "callbackname",
                    makeJavaClassName(axisService.getName()) + CALL_BACK_HANDLER_SUFFIX, rootElement);
        }

    } else {
        addAttribute(doc, "callbackname", localPart + CALL_BACK_HANDLER_SUFFIX, rootElement);
    }
    //add backwordcompatibility attribute
    addAttribute(doc, "isbackcompatible", String.valueOf(codeGenConfiguration.isBackwordCompatibilityMode()),
            rootElement);

    // add the wrap classes flag
    if (codeGenConfiguration.isPackClasses()) {
        addAttribute(doc, "wrapped", "yes", rootElement);
    }

    // add SOAP version
    addSoapVersion(doc, rootElement);

    // add the end point
    addEndpoint(doc, rootElement);

    // set the sync/async attributes
    fillSyncAttributes(doc, rootElement);

    // ###########################################################################################
    // this block of code specifically applies to the integration of databinding code into the
    // generated classes tightly (probably as inner classes)
    // ###########################################################################################
    // check for the special models in the mapper and if they are present process them
    if (mapper.isObjectMappingPresent()) {

        // add an attribute to the root element showing that the writing has been skipped
        addAttribute(doc, "skip-write", "yes", rootElement);

        // process the mapper objects
        processModelObjects(mapper.getAllMappedObjects(), rootElement, doc);
    }

    // #############################################################################################

    // load the operations
    loadOperations(doc, rootElement, null);

    // add the databind supporters. Now the databind supporters are completly contained inside
    // the stubs implementation and not visible outside
    rootElement.appendChild(createDOMElementforDatabinders(doc, false));

    Object moduleCodegenPolicyExtensionElement;

    //if some extension has added the stub methods property, add them to the
    //main document
    if ((moduleCodegenPolicyExtensionElement = codeGenConfiguration
            .getProperty("module-codegen-policy-extensions")) != null) {
        rootElement.appendChild(doc.importNode((Element) moduleCodegenPolicyExtensionElement, true));
    }

    //add another element to have the unique list of faults
    rootElement.appendChild(getUniqueListofFaults(doc));

    doc.appendChild(rootElement);

    //////////////////////////////////////////////////////////
    //        System.out.println(DOM2Writer.nodeToString(rootElement));
    ////////////////////////////////////////////////
    return doc;
}

From source file:org.apache.axis2.wsdl.codegen.emitter.AxisServiceBasedMultiLanguageEmitter.java

/**
 * create a dom element for databinders. This is called by other
 *
 * @param doc//from  w  ww .  j  a  v  a  2 s  . c o  m
 */
protected Element createDOMElementforDatabinders(Document doc, boolean isServerside) {

    // First Iterate through the operations and find the relevant fromOM and toOM methods to be generated
    ArrayList parameters = new ArrayList();

    AxisOperation axisOperation = null;
    AxisBindingOperation axisBindingOperation = null;
    for (Iterator bindingOperationsIter = this.axisBinding.getChildren(); bindingOperationsIter.hasNext();) {
        axisBindingOperation = (AxisBindingOperation) bindingOperationsIter.next();
        axisOperation = axisBindingOperation.getAxisOperation();

        // Add the parameters to a map with their type as the key
        // this step is needed to remove repetitions

        // process the input parameters
        String MEP = axisOperation.getMessageExchangePattern();
        if (WSDLUtil.isInputPresentForMEP(MEP)) {
            Element[] inputParamElement = getInputParamElement(doc, axisOperation);
            for (int i = 0; i < inputParamElement.length; i++) {
                //add an attribute to the parameter saying that this is an
                //input
                addAttribute(doc, "direction", "in", inputParamElement[i]);
                //add the short type name
                parameters.add(inputParamElement[i]);

            }
        }
        // process output parameters
        if (WSDLUtil.isOutputPresentForMEP(MEP)) {
            Element outputParamElement = getOutputParamElement(doc, axisOperation);
            if (outputParamElement != null) {
                //set the direction as out
                addAttribute(doc, "direction", "out", outputParamElement);
                parameters.add(outputParamElement);
            }
        }

        //process faults
        Element[] faultParamElements = getFaultParamElements(doc, axisOperation);
        for (int i = 0; i < faultParamElements.length; i++) {
            //set the direction as out - all faults are out messages ?
            addAttribute(doc, "direction", "out", faultParamElements[i]);
            parameters.add(faultParamElements[i]);
        }

        // process the header parameters
        Element newChild;
        List headerParameterQNameList = new ArrayList();
        addHeaderOperations(headerParameterQNameList, axisBindingOperation, true);
        List parameterElementList = getParameterElementList(doc, headerParameterQNameList,
                WSDLConstants.SOAP_HEADER);

        for (int i = 0; i < parameterElementList.size(); i++) {
            newChild = (Element) parameterElementList.get(i);
            parameters.add(newChild);
        }

        headerParameterQNameList.clear();
        parameterElementList.clear();
        addHeaderOperations(headerParameterQNameList, axisBindingOperation, false);
        parameterElementList = getParameterElementList(doc, headerParameterQNameList,
                WSDLConstants.SOAP_HEADER);

        for (int i = 0; i < parameterElementList.size(); i++) {
            newChild = (Element) parameterElementList.get(i);
            parameters.add(newChild);
        }
    }

    Element rootElement = doc.createElement("databinders");
    //add the db type attribute  - the name of the databinding type
    //this will be used to select the correct template
    addAttribute(doc, "dbtype", codeGenConfiguration.getDatabindingType(), rootElement);
    //add the wrapped flag state - this is used by JiBX, but may be useful
    //for other frameworks in the future
    String wrapflag = Boolean.toString(codeGenConfiguration.isParametersWrapped());
    addAttribute(doc, "wrapped", wrapflag, rootElement);

    //at this point we may need to capture the extra parameters passes to the
    //particular databinding framework
    //these parameters showup in the property map with String keys, and we
    //can just copy these items as attributes of the <extra> element.
    Element extraElement = addElement(doc, "extra", null, rootElement);
    Map propertiesMap = codeGenConfiguration.getProperties();
    for (Iterator it = propertiesMap.keySet().iterator(); it.hasNext();) {
        Object key = it.next();
        if (key instanceof String) {
            Object value = propertiesMap.get(key);
            //if the value is null set it to empty string
            if (value == null)
                value = "";
            //add key="value" attribute to element iff value a string
            if (value instanceof String) {
                addAttribute(doc, (String) key, (String) value, extraElement);
            }
        }
    }

    //add the server side attribute. this helps the databinding template
    //to determine the methods to generate
    if (isServerside) {
        addAttribute(doc, "isserverside", "yes", rootElement);
    }
    // add the names of the elements that have base 64 content
    // if the base64 name list is missing then this whole step is skipped
    rootElement.appendChild(getBase64Elements(doc));

    //add the method names
    rootElement.appendChild(getOpNames(doc));

    for (Iterator iterator = parameters.iterator(); iterator.hasNext();) {
        rootElement.appendChild((Element) iterator.next());
    }

    // finish with any extra information from service and operations
    Parameter details = axisService.getParameter(Constants.DATABINDING_SERVICE_DETAILS);
    if (details != null) {
        Object value = details.getValue();
        if (value instanceof Element) {
            rootElement.appendChild(doc.importNode((Element) value, true));
        } else if (value instanceof List) {
            for (Iterator iter = ((List) value).iterator(); iter.hasNext();) {
                rootElement.appendChild(doc.importNode((Element) iter.next(), true));
            }
        }
    }

    axisOperation = null;
    for (Iterator operationsIterator = axisService.getOperations(); operationsIterator.hasNext();) {
        axisOperation = (AxisOperation) operationsIterator.next();
        details = axisOperation.getParameter(Constants.DATABINDING_OPERATION_DETAILS);
        if (details != null) {
            rootElement.appendChild(doc.importNode((Element) details.getValue(), true));
        }
    }

    ///////////////////////////////////////////////
    //        System.out.println("databinding root element " + DOM2Writer.nodeToString(rootElement));
    ////////////////////////////////////////////////

    return rootElement;
}

From source file:org.apache.axis2.wsdl.codegen.emitter.AxisServiceBasedMultiLanguageEmitter.java

/**
 * @param objectMappings/*from  w  w w  . java  2 s. c  o m*/
 * @param root
 * @param doc
 */
protected void processModelObjects(Map objectMappings, Element root, Document doc) {
    Iterator objectIterator = objectMappings.values().iterator();

    while (objectIterator.hasNext()) {
        Object o = objectIterator.next();

        if (o instanceof Document) {
            //we cannot have an empty document
            root.appendChild(doc.importNode(((Document) o).getDocumentElement(), true));
        } else {

            // oops we have no idea how to do this, if the model provided is not a DOM document
            // we are done. we might as well skip  it here
        }
    }
}

From source file:org.apache.cocoon.components.source.impl.XModuleSource.java

public void notify(Document insertDoc) throws SAXException {

    // handle xpaths, we are only handling inserts, i.e. if there is no
    // attribute of the given name and type the operation will fail
    if (!(this.xPath.length() == 0 || this.xPath.equals("/"))) {

        Object value = getInputAttribute(this.attributeType, this.attributeName);
        if (value == null)
            throw new SAXException(" The attribute: " + this.attributeName + " is empty");

        JXPathContext context = JXPathContext.newContext(value);

        if (value instanceof Document) {
            // If the attribute contains a dom document we
            // create the elements in the given xpath if
            // necesary, import the input document and put it
            // in the place described by the xpath.
            Document doc = (Document) value;

            Node importedNode = doc.importNode(insertDoc.getDocumentElement(), true);

            context.setLenient(true);/* w  ww  .  j a  va2 s  .co m*/
            context.setFactory(new DOMFactory());
            context.createPathAndSetValue(this.xPath, importedNode);
        } else {
            // Otherwise just try to put a the input document in
            // the place pointed to by the xpath
            context.setValue(this.xPath, insertDoc);
        }

    } else {
        setOutputAttribute(this.attributeType, this.attributeName, insertDoc);
    }
}

From source file:org.apache.cocoon.forms.binding.InsertNodeJXPathBinding.java

/**
 * Registers a JXPath Factory on the JXPath Context.
 * <p>/*from www.ja va2  s. com*/
 * The factory will inserts a clone of the 'template' DocumentFragment
 * inside this object into the target objectmodel.
 */
public void doSave(Widget frmModel, JXPathContext jxpc) {

    Node parentNode = (Node) jxpc.getContextBean();
    Document targetDoc = parentNode.getOwnerDocument();
    Node toInsert = targetDoc.importNode(this.template, true);
    parentNode.appendChild(toInsert);

    if (getLogger().isDebugEnabled())
        getLogger().debug("InsertNode executed.");

    // jxpc.setFactory(new AbstractFactory() {
    //     public boolean createObject(JXPathContext context, Pointer pointer,
    //         Object parent, String name, int index) {
    //
    //         Node parentNode = (Node) parent;
    //         Document targetDoc = parentNode.getOwnerDocument();
    //         Node toInsert = targetDoc.importNode(InsertNodeJXPathBinding.this.template, true);
    //         parentNode.appendChild(toInsert);
    //
    //         if (getLogger().isDebugEnabled())
    //             getLogger().debug("InsertNode jxpath factory executed for index." + index);
    //         return true;
    //     }
    // });
    //
    // if (getLogger().isDebugEnabled())
    //     getLogger().debug("done registered factory for inserting node -- " + toString());
}

From source file:org.apache.cocoon.webapps.session.context.RequestSessionContext.java

/**
 * Build parameter XML//from w w  w  . j  a  v  a2 s  .  co  m
 */
private void buildParameterXML(Element root, SAXParser parser) {
    Document doc = root.getOwnerDocument();
    // include all parameters
    // process "/parameter" and "/parametervalues" at the same time
    Element parameterElement = doc.createElementNS(null, "parameter");
    Element parameterValuesElement = doc.createElementNS(null, "parametervalues");
    root.appendChild(parameterElement);
    root.appendChild(parameterValuesElement);
    String parameterName = null;
    Enumeration pars = this.request.getParameterNames();
    Element parameter;
    Element element;
    Node valueNode;
    String[] values;
    String parValue;

    element = doc.createElementNS(CIncludeTransformer.CINCLUDE_NAMESPACE_URI, PARAMETERS_ELEMENT);
    element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:cinclude",
            CIncludeTransformer.CINCLUDE_NAMESPACE_URI);
    parameterValuesElement.appendChild(element);
    parameterValuesElement = element;

    while (pars.hasMoreElements() == true) {
        parameterName = (String) pars.nextElement();
        values = this.request.getParameterValues(parameterName);

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

            // this is a fast test, if the parameter value contains xml!
            parValue = values[i].trim();
            if (parValue.length() > 0 && parValue.charAt(0) == '<') {
                try {
                    valueNode = DOMUtil.getDocumentFragment(parser, new StringReader(parValue));
                    valueNode = doc.importNode(valueNode, true);
                } catch (Exception noXMLException) {
                    valueNode = doc.createTextNode(parValue);
                }
            } else {
                valueNode = doc.createTextNode(parValue);
            }
            // create "/parameter" entry for first value
            if (i == 0) {
                try {
                    parameter = doc.createElementNS(null, parameterName);
                    parameter.appendChild(valueNode);
                    parameterElement.appendChild(parameter);
                } catch (Exception local) {
                    // the exception is ignored and only this parameters is ignored
                }
            }

            try {
                // create "/parametervalues" entry
                element = doc.createElementNS(CIncludeTransformer.CINCLUDE_NAMESPACE_URI, PARAMETER_ELEMENT);
                parameterValuesElement.appendChild(element);
                parameter = element;
                element = doc.createElementNS(CIncludeTransformer.CINCLUDE_NAMESPACE_URI, NAME_ELEMENT);
                parameter.appendChild(element);
                element.appendChild(doc.createTextNode(parameterName));
                element = doc.createElementNS(CIncludeTransformer.CINCLUDE_NAMESPACE_URI, VALUE_ELEMENT);
                parameter.appendChild(element);
                element.appendChild(valueNode.cloneNode(true));
            } catch (Exception local) {
                // the exception is ignored and only this parameters is ignored
            }
        }
    }
    // and now the query string
    element = doc.createElementNS(null, "querystring");
    root.appendChild(element);
    String value = request.getQueryString();
    if (value != null) {
        element.appendChild(doc.createTextNode('?' + value));
    }
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java

/****
 * Creates a node from the String xml definition
 * /*w w w.  j  a va2 s  .  co m*/
 * @param owner
 * @param xmlDefinition
 * @return Node representing the xml definition
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
private static Node createNode(Document owner, String xmlDefinition)
        throws SAXException, IOException, ParserConfigurationException {
    InputSource inputSource = new InputSource(new StringReader(xmlDefinition));
    Document document = getDocumentBuilder().parse(inputSource);
    Node newNode = document.getDocumentElement();
    return owner.importNode(newNode, true);
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtils.java

/**
 * Upgrade the schema of a given Config XMl <code>document</code> to the given
 * <code>namespace</code>, <code>schemaLocation</code> and <code>version</code>.
 * //from w  ww . j  a va  2 s  .co m
 * @param document Config XML {@link Document} to upgrade.
 * @param namespaceUri Namespace URI to upgrade to.
 * @param schemaLocation Schema location to upgrade to.
 * @throws XPathExpressionException
 * @throws ParserConfigurationException
 * @since GemFire 8.1
 */
public static Document upgradeSchema(Document document, final String namespaceUri, final String schemaLocation,
        String schemaVersion) throws XPathExpressionException, ParserConfigurationException {
    if (StringUtils.isBlank(namespaceUri)) {
        throw new IllegalArgumentException("namespaceUri");
    }
    if (StringUtils.isBlank(schemaLocation)) {
        throw new IllegalArgumentException("schemaLocation");
    }
    if (StringUtils.isBlank(schemaVersion)) {
        throw new IllegalArgumentException("schemaVersion");
    }

    if (null != document.getDoctype()) {
        Node root = document.getDocumentElement();
        Document copiedDocument = getDocumentBuilder().newDocument();
        Node copiedRoot = copiedDocument.importNode(root, true);
        copiedDocument.appendChild(copiedRoot);
        document = copiedDocument;
    }

    final Element root = document.getDocumentElement();
    // since root is the cache element, then this oldNamespace will be the cache's namespaceURI
    String oldNamespaceUri = root.getNamespaceURI();

    // update the namespace
    if (!namespaceUri.equals(oldNamespaceUri)) {
        changeNamespace(root, oldNamespaceUri, namespaceUri);
    }

    // update the version
    root.setAttribute("version", schemaVersion);

    // update the schemaLocation attribute
    Node schemaLocationAttr = root.getAttributeNodeNS(W3C_XML_SCHEMA_INSTANCE_NS_URI,
            W3C_XML_SCHEMA_INSTANCE_ATTRIBUTE_SCHEMA_LOCATION);
    String xsiPrefix = findPrefix(root, W3C_XML_SCHEMA_INSTANCE_NS_URI);
    ;
    Map<String, String> uriToLocation = new HashMap<>();
    if (schemaLocationAttr != null) {
        uriToLocation = buildSchemaLocationMap(schemaLocationAttr.getNodeValue());
    } else if (xsiPrefix == null) {
        // this namespace is not defined yet, define it
        xsiPrefix = W3C_XML_SCHEMA_INSTANCE_PREFIX;
        root.setAttribute("xmlns:" + xsiPrefix, W3C_XML_SCHEMA_INSTANCE_NS_URI);
    }

    uriToLocation.remove(oldNamespaceUri);
    uriToLocation.put(namespaceUri, schemaLocation);

    root.setAttributeNS(W3C_XML_SCHEMA_INSTANCE_NS_URI,
            xsiPrefix + ":" + W3C_XML_SCHEMA_INSTANCE_ATTRIBUTE_SCHEMA_LOCATION,
            getSchemaLocationValue(uriToLocation));

    return document;
}