Example usage for org.w3c.dom Document createElementNS

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

Introduction

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

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java

/**
 * Create the element to be associated with this part into the {@link org.apache.ode.bpel.iapi.Message}.
 * <p/>If the part has a non-null element name, the bodyElement is simply appended.
 * Else if the bodyElement has a text content, the value is set to the message.
 * Else append all nodes of bodyElement to the returned element. Attributes are ignored.
 * <p/>//from ww w  .  j a  v  a  2  s  . c  om
 * The name of the returned element is the part name.
 *
 * @param part
 * @param receivedElement
 * @return the element to insert "as is" to ODE message
 */
public Element createPartElement(Part part, Element receivedElement) {
    Document doc = DOMUtils.newDocument();
    Element partElement = doc.createElementNS(null, part.getName());
    if (part.getElementName() != null) {
        partElement.appendChild(doc.importNode(receivedElement, true));
    } else {
        if (DOMUtils.isEmptyElement(receivedElement)) {
            // Append an empty text node.
            // Warning! setting an empty string with setTextContent has not effect. See javadoc.
            partElement.appendChild(doc.createTextNode(""));
        } else {
            // No need to make the distinction between simple and complex types, importNode will handle it
            // !!! Attributes are ignored
            for (int m = 0; m < receivedElement.getChildNodes().getLength(); m++) {
                Node child = receivedElement.getChildNodes().item(m);
                partElement.appendChild(doc.importNode(child, true));
            }
        }
    }
    return partElement;
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverterTest.java

public void testGetTag() throws Exception {
    String uri = ((HTTPAddress) deliciousPort.getExtensibilityElements().get(0)).getLocationURI();
    String expectedUri = uri + "/tag/java";
    Element msgEl;/*from   ww w.  j ava2s  . com*/
    {
        Document odeMsg = DOMUtils.newDocument();
        msgEl = odeMsg.createElementNS(null, "message");
        Element partEl = odeMsg.createElementNS(null, "TagPart");
        partEl.setTextContent("java");
        odeMsg.appendChild(msgEl);
        msgEl.appendChild(partEl);
    }

    MockMessageExchange odeMex = new MockMessageExchange();
    odeMex.op = deliciousBinding.getBindingOperation("getTag", null, null).getOperation();
    odeMex.req = new MockMessage(msgEl);
    odeMex.epr = new MockEPR(uri);
    HttpMethod httpMethod = deliciousBuilder.createHttpRequest(odeMex, new DefaultHttpParams());

    assertTrue("GET".equalsIgnoreCase(httpMethod.getName()));
    assertTrue(expectedUri.equalsIgnoreCase(httpMethod.getURI().toString()));
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverterTest.java

public void testGetTagWithNoPart() throws Exception {
    String uri = ((HTTPAddress) deliciousPort.getExtensibilityElements().get(0)).getLocationURI();
    Element msgEl;/*from   www.  j  a  v a 2s.  c o m*/
    {
        Document odeMsg = DOMUtils.newDocument();
        msgEl = odeMsg.createElementNS(null, "message");
        odeMsg.appendChild(msgEl);
    }

    MockMessageExchange odeMex = new MockMessageExchange();
    odeMex.op = deliciousBinding.getBindingOperation("getTag", null, null).getOperation();
    odeMex.req = new MockMessage(msgEl);
    odeMex.epr = new MockEPR(uri);
    try {
        HttpMethod httpMethod = deliciousBuilder.createHttpRequest(odeMex, new DefaultHttpParams());
        fail("IllegalArgumentException expected because message element is empty.");
    } catch (IllegalArgumentException e) {
        // expected behavior
    }
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverterTest.java

public void testHello() throws Exception {
    String uri = ((HTTPAddress) dummyPort.getExtensibilityElements().get(0)).getLocationURI();
    String expectedUri = uri + "/" + "DummyService/hello";
    Element msgEl, helloEl;//from  w ww.  ja  v  a 2 s .  c  o  m
    {
        Document odeMsg = DOMUtils.newDocument();
        msgEl = odeMsg.createElementNS(null, "message");
        Element partEl = odeMsg.createElementNS(null, "parameters");
        odeMsg.appendChild(msgEl);
        msgEl.appendChild(partEl);
        helloEl = odeMsg.createElementNS(null, "hello");
        helloEl.setTextContent("This is a test. How is it going so far?");
        partEl.appendChild(helloEl);
    }

    MockMessageExchange odeMex = new MockMessageExchange();
    odeMex.op = dummyBinding.getBindingOperation("hello", null, null).getOperation();
    odeMex.req = new MockMessage(msgEl);
    odeMex.epr = new MockEPR(uri);
    HttpMethod httpMethod = dummyBuilder.createHttpRequest(odeMex, new DefaultHttpParams());
    assertTrue("POST".equalsIgnoreCase(httpMethod.getName()));
    assertEquals("Generated URI does not match", expectedUri, httpMethod.getURI().toString());

    String b = ((StringRequestEntity) ((PostMethod) httpMethod).getRequestEntity()).getContent();
    assertEquals("Invalid body in generated http query", DOMUtils.domToString(helloEl), b);
}

From source file:org.apache.ode.axis2.ODEService.java

/**
 * Get the EPR of this service from the WSDL.
 *
 * @param name     service name//ww w .j a  va  2 s  .c  o m
 * @param portName port name
 * @return XML representation of the EPR
 */
public static Element genEPRfromWSDL(Definition wsdlDef, QName name, String portName) {
    Service serviceDef = wsdlDef.getService(name);
    if (serviceDef != null) {
        Port portDef = serviceDef.getPort(portName);
        if (portDef != null) {
            Document doc = DOMUtils.newDocument();
            Element service = doc.createElementNS(Namespaces.WSDL_11, "service");
            service.setAttribute("name", serviceDef.getQName().getLocalPart());
            service.setAttribute("targetNamespace", serviceDef.getQName().getNamespaceURI());
            Element port = doc.createElementNS(Namespaces.WSDL_11, "port");
            service.appendChild(port);
            port.setAttribute("name", portDef.getName());
            port.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:bindns",
                    portDef.getBinding().getQName().getNamespaceURI());
            port.setAttribute("bindns:binding", portDef.getName());
            for (Object extElmt : portDef.getExtensibilityElements()) {
                if (extElmt instanceof SOAPAddress) {
                    Element soapAddr = doc.createElementNS(Namespaces.SOAP_NS, "address");
                    port.appendChild(soapAddr);
                    soapAddr.setAttribute("location", ((SOAPAddress) extElmt).getLocationURI());
                } else if (extElmt instanceof HTTPAddress) {
                    Element httpAddr = doc.createElementNS(Namespaces.HTTP_NS, "address");
                    port.appendChild(httpAddr);
                    httpAddr.setAttribute("location", ((HTTPAddress) extElmt).getLocationURI());
                } else {
                    port.appendChild(
                            doc.importNode(((UnknownExtensibilityElement) extElmt).getElement(), true));
                }
            }
            return service;
        }
    }
    return null;
}

From source file:org.apache.ode.axis2.ODEService.java

/**
 * Create-and-copy a service-ref element.
 *
 * @param elmt//from  w w  w  .ja  v  a2  s.  c o  m
 * @return wrapped element
 */
public static MutableEndpoint createServiceRef(Element elmt) {
    Document doc = DOMUtils.newDocument();
    QName elQName = new QName(elmt.getNamespaceURI(), elmt.getLocalName());
    // If we get a service-ref, just copy it, otherwise make a service-ref
    // wrapper
    if (!EndpointReference.SERVICE_REF_QNAME.equals(elQName)) {
        Element serviceref = doc.createElementNS(EndpointReference.SERVICE_REF_QNAME.getNamespaceURI(),
                EndpointReference.SERVICE_REF_QNAME.getLocalPart());
        serviceref.appendChild(doc.importNode(elmt, true));
        doc.appendChild(serviceref);
    } else {
        doc.appendChild(doc.importNode(elmt, true));
    }

    return EndpointFactory.createEndpoint(doc.getDocumentElement());
}

From source file:org.apache.ode.axis2.soapbinding.SoapExternalService.java

private void reply(final PartnerRoleMessageExchange odeMex, final Operation operation,
        final MessageContext reply, final boolean isFault) {
    try {//from  w w  w .  j a  v a 2  s .  c  om
        if (__log.isDebugEnabled())
            __log.debug("Received response for MEX " + odeMex);
        if (isFault) {
            Document odeMsg = DOMUtils.newDocument();
            Element odeMsgEl = odeMsg.createElementNS(null, "message");
            odeMsg.appendChild(odeMsgEl);
            Fault fault = _converter.parseSoapFault(odeMsgEl, reply.getEnvelope(), operation);

            if (fault != null) {
                if (__log.isWarnEnabled())
                    __log.warn("Fault response: faultName=" + fault.getName() + " faultType="
                            + fault.getMessage().getQName() + "\n" + DOMUtils.domToString(odeMsgEl));

                QName faultType = fault.getMessage().getQName();
                QName faultName = new QName(_definition.getTargetNamespace(), fault.getName());
                Message response = odeMex.createMessage(faultType);
                response.setMessage(odeMsgEl);

                odeMex.replyWithFault(faultName, response);
            } else {
                if (__log.isWarnEnabled())
                    __log.warn("Fault response: faultType=(unkown)\n" + reply.getEnvelope().toString());
                odeMex.replyWithFailure(FailureType.OTHER, reply.getEnvelope().getBody().getFault().getText(),
                        OMUtils.toDOM(reply.getEnvelope().getBody()));
            }
        } else {
            Message response = odeMex.createMessage(odeMex.getOperation().getOutput().getMessage().getQName());
            _converter.parseSoapResponse(response, reply.getEnvelope(), operation);
            if (__log.isInfoEnabled())
                __log.info("Response:\n"
                        + (response.getMessage() != null ? DOMUtils.domToString(response.getMessage())
                                : "empty"));
            odeMex.reply(response);
        }
    } catch (Exception ex) {
        String errmsg = "Unable to process response: " + ex.getMessage();
        __log.error(errmsg, ex);
        odeMex.replyWithFailure(FailureType.OTHER, errmsg, null);
    }

}

From source file:org.apache.ode.axis2.soapbinding.SoapMessageConverter.java

@SuppressWarnings("unchecked")
public void extractSoapBodyParts(org.apache.ode.bpel.iapi.Message message,
        org.apache.axiom.soap.SOAPBody soapBody, SOAPBody bodyDef, Message msg, String rpcWrapper)
        throws AxisFault {

    List<Part> bodyParts = msg.getOrderedParts(bodyDef.getParts());

    if (_isRPC) {
        QName rpcWrapQName = new QName(bodyDef.getNamespaceURI(), rpcWrapper);
        OMElement partWrapper = soapBody.getFirstChildWithName(rpcWrapQName);
        if (partWrapper == null)
            throw new OdeFault(
                    __msgs.msgSoapBodyDoesNotContainExpectedPartWrapper(_serviceName, _portName, rpcWrapQName));
        // In RPC the body element is the operation name, wrapping parts. Order doesn't really matter as far as
        // we're concerned. All we need to do is copy the soap:body children, since doc-lit rpc looks the same
        // in ode and soap.
        for (Part pdef : bodyParts) {
            OMElement srcPart = partWrapper.getFirstChildWithName(new QName(null, pdef.getName()));
            if (srcPart == null)
                throw new OdeFault(__msgs.msgSOAPBodyDoesNotContainRequiredPart(pdef.getName()));
            message.setPart(srcPart.getLocalName(), OMUtils.toDOM(srcPart));
        }//from  ww  w .  j a va 2  s.  co  m

    } else {
        // In doc-literal style, we expect the elements in the body to correspond (in order) to the
        // parts defined in the binding. All the parts should be element-typed, otherwise it is a mess.
        Iterator<OMElement> srcParts = soapBody.getChildElements();
        for (Part partDef : bodyParts) {
            if (!srcParts.hasNext())
                throw new OdeFault(__msgs.msgSOAPBodyDoesNotContainRequiredPart(partDef.getName()));

            OMElement srcPart = srcParts.next();
            if (partDef.getElementName() == null)
                throw new OdeFault(__msgs.msgBindingDefinesNonElementDocListParts());
            if (!srcPart.getQName().equals(partDef.getElementName()))
                throw new OdeFault(
                        __msgs.msgUnexpectedElementInSOAPBody(srcPart.getQName(), partDef.getElementName()));
            Document doc = DOMUtils.newDocument();
            Element destPart = doc.createElementNS(null, partDef.getName());
            destPart.appendChild(doc.importNode(OMUtils.toDOM(srcPart), true));
            message.setPart(partDef.getName(), destPart);
        }
    }
}

From source file:org.apache.ode.axis2.SoapExternalService.java

private void reply(final String odeMexId, final Operation operation, final MessageContext reply,
        final boolean isFault) {
    // ODE MEX needs to be invoked in a TX.
    try {/*www  . j  ava  2 s  .co  m*/
        _sched.execTransaction(new Callable<Void>() {
            public Void call() throws Exception {
                PartnerRoleMessageExchange odeMex = (PartnerRoleMessageExchange) _server.getEngine()
                        .getMessageExchange(odeMexId);
                // Setting the response
                try {
                    if (__log.isDebugEnabled())
                        __log.debug("Received response for MEX " + odeMex);
                    if (isFault) {
                        Document odeMsg = DOMUtils.newDocument();
                        Element odeMsgEl = odeMsg.createElementNS(null, "message");
                        odeMsg.appendChild(odeMsgEl);
                        Fault fault = _converter.parseSoapFault(odeMsgEl, reply.getEnvelope(), operation);

                        if (fault != null) {
                            if (__log.isWarnEnabled())
                                __log.warn("Fault response: faultName=" + fault.getName() + " faultType="
                                        + fault.getMessage().getQName() + "\n"
                                        + DOMUtils.domToString(odeMsgEl));

                            QName faultType = fault.getMessage().getQName();
                            QName faultName = new QName(_definition.getTargetNamespace(), fault.getName());
                            Message response = odeMex.createMessage(faultType);
                            response.setMessage(odeMsgEl);

                            odeMex.replyWithFault(faultName, response);
                        } else {
                            if (__log.isWarnEnabled())
                                __log.warn("Fault response: faultType=(unkown)\n"
                                        + reply.getEnvelope().toString());
                            odeMex.replyWithFailure(FailureType.OTHER,
                                    reply.getEnvelope().getBody().getFault().getText(),
                                    OMUtils.toDOM(reply.getEnvelope().getBody()));
                        }
                    } else {
                        Message response = odeMex
                                .createMessage(odeMex.getOperation().getOutput().getMessage().getQName());
                        _converter.parseSoapResponse(response, reply.getEnvelope(), operation);
                        if (__log.isInfoEnabled())
                            __log.info("Response:\n" + (response.getMessage() != null
                                    ? DOMUtils.domToString(response.getMessage())
                                    : "empty"));
                        odeMex.reply(response);
                    }
                } catch (Exception ex) {
                    String errmsg = "Unable to process response: " + ex.getMessage();
                    __log.error(errmsg, ex);
                    odeMex.replyWithFailure(FailureType.OTHER, errmsg, null);
                }
                return null;
            }
        });

    } catch (Exception e) {
        String errmsg = "Error executing reply transaction; reply will be lost.";
        __log.error(errmsg, e);
    }
}

From source file:org.apache.ode.bpel.engine.BpelEngineImpl.java

public void sendMyRoleFault(BpelProcess process, JobDetails we, int causeCode) {
    MessageExchange mex = (MessageExchange) getMessageExchange(we.getMexId());
    if (!(mex instanceof MyRoleMessageExchange)) {
        return;/*w w w.  jav  a  2 s . c o  m*/
    }
    QName faultQName = null;
    OConstants constants = process.getOProcess().constants;
    if (constants != null) {
        Document document = DOMUtils.newDocument();
        Element faultElement = document.createElementNS(Namespaces.SOAP_ENV_NS, "Fault");
        Element faultDetail = document.createElementNS(Namespaces.ODE_EXTENSION_NS, "fault");
        faultElement.appendChild(faultDetail);
        switch (causeCode) {
        case InvalidProcessException.TOO_MANY_PROCESSES_CAUSE_CODE:
            faultQName = constants.qnTooManyProcesses;
            faultDetail.setTextContent("The total number of processes in use is over the limit.");
            break;
        case InvalidProcessException.TOO_HUGE_PROCESSES_CAUSE_CODE:
            faultQName = constants.qnTooHugeProcesses;
            faultDetail.setTextContent("The total size of processes in use is over the limit");
            break;
        case InvalidProcessException.TOO_MANY_INSTANCES_CAUSE_CODE:
            faultQName = constants.qnTooManyInstances;
            faultDetail.setTextContent("No more instances of the process allowed at start at this time.");
            break;
        case InvalidProcessException.RETIRED_CAUSE_CODE:
            // we're invoking a target process, trying to see if we can retarget the message
            // to the current version (only applies when it's a new process creation)
            for (BpelProcess activeProcess : _activeProcesses.values()) {
                if (activeProcess.getConf().getState().equals(org.apache.ode.bpel.iapi.ProcessState.ACTIVE)
                        && activeProcess.getConf().getType().equals(process.getConf().getType())) {
                    we.setProcessId(activeProcess._pid);
                    ((MyRoleMessageExchangeImpl) mex)._process = activeProcess;
                    process.handleJobDetails(we);
                    return;
                }
            }
            faultQName = constants.qnRetiredProcess;
            faultDetail.setTextContent("The process you're trying to instantiate has been retired.");
            break;
        case InvalidProcessException.DEFAULT_CAUSE_CODE:
        default:
            faultQName = constants.qnUnknownFault;
            break;
        }
        MexDaoUtil.setFaulted((MessageExchangeImpl) mex, faultQName, faultElement);
    }
}