Example usage for javax.xml.soap SOAPEnvelope createName

List of usage examples for javax.xml.soap SOAPEnvelope createName

Introduction

In this page you can find the example usage for javax.xml.soap SOAPEnvelope createName.

Prototype

public abstract Name createName(String localName, String prefix, String uri) throws SOAPException;

Source Link

Document

Creates a new Name object initialized with the given local name, namespace prefix, and namespace URI.

Usage

From source file:com.googlecode.ddom.frontend.saaj.SOAPElementTest.java

@Validated
@Test/*from w w w.j  a v a  2 s.  c  o m*/
public void testRemoveAttributeByName() throws Exception {
    SOAPEnvelope envelope = saajUtil.createSOAP11Envelope();
    SOAPBody body = envelope.addBody();
    SOAPElement element = body.addChildElement(new QName("urn:test", "test"));
    element.setAttributeNS("urn:ns1", "ns1:attr1", "value");
    element.setAttributeNS("urn:ns1", "ns1:attr2", "value");
    assertTrue(element.removeAttribute(envelope.createName("attr2", "p", "urn:ns1")));
    NamedNodeMap attributes = element.getAttributes();
    assertNull(attributes.getNamedItemNS("urn:ns1", "attr2"));
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

private Document createSOAPFaultDocument(String faultString) throws SOAPException {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart sp = message.getSOAPPart();
    SOAPEnvelope se = sp.getEnvelope();
    se.setPrefix(SOAP_PREFIX);//from   w  w w.  ja  v a 2  s. c  o  m
    se.getHeader().detachNode();
    se.addHeader();
    se.getBody().detachNode();
    SOAPBody body = se.addBody();
    SOAPFault fault = body.addFault();
    Name faultCode = se.createName("Client", null, SOAPConstants.URI_NS_SOAP_ENVELOPE);
    fault.setFaultCode(faultCode);
    fault.setFaultString(faultString);
    return se.getOwnerDocument();
}

From source file:net.sf.jasperreports.olap.xmla.JRXmlaQueryExecuter.java

/**
 * Parses the result-Message into this class's structure
 * /*from w w  w  .j  a  v a  2s . c  o  m*/
 * @param reply
 *            The reply-Message from the Server
 */
protected void parseResult(SOAPMessage reply) throws SOAPException {
    SOAPPart soapPart = reply.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
    SOAPBody soapBody = soapEnvelope.getBody();
    SOAPElement eElement = null;

    if (log.isDebugEnabled()) {
        log.debug("XML/A result envelope: " + prettyPrintSOAP(soapEnvelope));
    }

    SOAPFault fault = soapBody.getFault();
    if (fault != null) {
        handleResultFault(fault);
    }

    Name eName = soapEnvelope.createName("ExecuteResponse", "", XMLA_URI);

    // Get the ExecuteResponse-Node
    Iterator<?> responseElements = soapBody.getChildElements(eName);
    if (responseElements.hasNext()) {
        Object eObj = responseElements.next();
        if (eObj == null) {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT,
                    new Object[] { "ExecuteResponse" });
        }
        eElement = (SOAPElement) eObj;
    } else {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT,
                new Object[] { "ExecuteResponse" });
    }

    // Get the return-Node
    Name rName = soapEnvelope.createName("return", "", XMLA_URI);
    Iterator<?> returnElements = eElement.getChildElements(rName);
    SOAPElement returnElement = null;
    if (returnElements.hasNext()) {
        Object eObj = returnElements.next();
        if (eObj == null) {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[] { "return" });
        }
        returnElement = (SOAPElement) eObj;
    } else {
        // Should be old-Microsoft XMLA-SDK. Try without m-prefix
        Name rName2 = soapEnvelope.createName("return", "", "");
        returnElements = eElement.getChildElements(rName2);
        if (returnElements.hasNext()) {
            Object eObj = returnElements.next();
            if (eObj == null) {
                throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT,
                        new Object[] { "return" });
            }
            returnElement = (SOAPElement) eObj;
        } else {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT,
                    new Object[] { "return" });
        }
    }

    // Get the root-Node
    Name rootName = soapEnvelope.createName("root", "", MDD_URI);
    SOAPElement rootElement = null;
    Iterator<?> rootElements = returnElement.getChildElements(rootName);
    if (rootElements.hasNext()) {
        Object eObj = rootElements.next();
        if (eObj == null) {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[] { "root" });
        }
        rootElement = (SOAPElement) eObj;
    } else {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT,
                new Object[] { "root" });
    }
    // Get the OlapInfo-Node
    Name olapInfoName = soapEnvelope.createName("OlapInfo", "", MDD_URI);
    SOAPElement olapInfoElement = null;
    Iterator<?> olapInfoElements = rootElement.getChildElements(olapInfoName);
    if (olapInfoElements.hasNext()) {
        Object eObj = olapInfoElements.next();
        if (eObj == null) {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[] { "OlapInfo" });
        }
        olapInfoElement = (SOAPElement) eObj;
    } else {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT,
                new Object[] { "OlapInfo" });
    }

    parseOLAPInfoElement(olapInfoElement);

    // Get the Axes Element
    Name axesName = soapEnvelope.createName("Axes", "", MDD_URI);
    SOAPElement axesElement = null;
    Iterator<?> axesElements = rootElement.getChildElements(axesName);
    if (axesElements.hasNext()) {
        Object eObj = axesElements.next();
        if (eObj == null) {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[] { "Axes" });
        }
        axesElement = (SOAPElement) eObj;
    } else {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT,
                new Object[] { "Axes" });
    }

    parseAxesElement(axesElement);

    // Get the CellData Element
    Name cellDataName = soapEnvelope.createName("CellData", "", MDD_URI);
    SOAPElement cellDataElement = null;
    Iterator<?> cellDataElements = rootElement.getChildElements(cellDataName);
    if (cellDataElements.hasNext()) {
        Object eObj = cellDataElements.next();
        if (eObj == null) {
            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_NULL_ELEMENT, new Object[] { "CellData" });
        }
        cellDataElement = (SOAPElement) eObj;
    } else {
        throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_XMLA_CANNOT_RETRIEVE_ELEMENT,
                new Object[] { "CellData" });
    }
    parseCellDataElement(cellDataElement);
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.olap.OLAPQueryExecuter.java

/**
 * Parses the result-Message into this class's structure
 *
 * @param reply//from w  w  w.  j  a  v a  2 s.c o m
 *            The reply-Message from the Server
 */
protected void parseResult(SOAPMessage reply) throws SOAPException, JRRuntimeException {
    SOAPPart soapPart = reply.getSOAPPart();
    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
    SOAPBody soapBody = soapEnvelope.getBody();
    SOAPElement eElement = null;

    if (log.isDebugEnabled()) {
        log.debug("XML/A result envelope: " + soapEnvelope.toString());
    }

    SOAPFault fault = soapBody.getFault();
    if (fault != null) {
        handleResultFault(fault);
    }

    Name eName = soapEnvelope.createName("ExecuteResponse", "", XMLA_URI);

    // Get the ExecuteResponse-Node
    Iterator responseElements = soapBody.getChildElements(eName);
    if (responseElements.hasNext()) {
        Object eObj = responseElements.next();
        if (eObj == null) {
            log.error("ExecuteResponse Element is null.");
            throw new JRRuntimeException("ExecuteResponse Element is null.");
        }
        eElement = (SOAPElement) eObj;
    } else {
        log.error("Could not retrieve ExecuteResponse Element.");
        throw new JRRuntimeException("Could not retrieve ExecuteResponse Element.");
    }

    // Get the return-Node
    Name rName = soapEnvelope.createName("return", "", XMLA_URI);
    Iterator returnElements = eElement.getChildElements(rName);
    SOAPElement returnElement = null;
    if (returnElements.hasNext()) {
        Object eObj = returnElements.next();
        if (eObj == null) {
            log.error("return Element is null.");
            throw new JRRuntimeException("return Element is null.");
        }
        returnElement = (SOAPElement) eObj;
    } else {
        // Should be old-Microsoft XMLA-SDK. Try without m-prefix
        Name rName2 = soapEnvelope.createName("return", "", "");
        returnElements = eElement.getChildElements(rName2);
        if (returnElements.hasNext()) {
            Object eObj = returnElements.next();
            if (eObj == null) {
                log.error("return Element is null.");
                throw new JRRuntimeException("return Element is null.");
            }
            returnElement = (SOAPElement) eObj;
        } else {
            log.error("Could not retrieve return Element.");
            throw new JRRuntimeException("Could not retrieve return Element.");
        }
    }

    // Get the root-Node
    Name rootName = soapEnvelope.createName("root", "", MDD_URI);
    SOAPElement rootElement = null;
    Iterator rootElements = returnElement.getChildElements(rootName);
    if (rootElements.hasNext()) {
        Object eObj = rootElements.next();
        if (eObj == null) {
            log.error("root Element is null.");
            throw new JRRuntimeException("root Element is null.");
        }
        rootElement = (SOAPElement) eObj;
    } else {
        log.error("Could not retrieve root Element.");
        throw new JRRuntimeException("Could not retrieve root Element.");
    }
    // Get the OlapInfo-Node
    Name olapInfoName = soapEnvelope.createName("OlapInfo", "", MDD_URI);
    SOAPElement olapInfoElement = null;
    Iterator olapInfoElements = rootElement.getChildElements(olapInfoName);
    if (olapInfoElements.hasNext()) {
        Object eObj = olapInfoElements.next();
        if (eObj == null) {
            log.error("OlapInfo Element is null.");
            throw new JRRuntimeException("OlapInfo Element is null.");
        }
        olapInfoElement = (SOAPElement) eObj;
    } else {
        log.error("Could not retrieve OlapInfo Element.");
        throw new JRRuntimeException("Could not retrieve OlapInfo Element.");
    }

    parseOLAPInfoElement(olapInfoElement);

    // Get the Axes Element
    Name axesName = soapEnvelope.createName("Axes", "", MDD_URI);
    SOAPElement axesElement = null;
    Iterator axesElements = rootElement.getChildElements(axesName);
    if (axesElements.hasNext()) {
        Object eObj = axesElements.next();
        if (eObj == null) {
            log.error("Axes Element is null");
            throw new JRRuntimeException("Axes Element is null");
        }
        axesElement = (SOAPElement) eObj;
    } else {
        log.error("Could not retrieve Axes Element.");
        throw new JRRuntimeException("Could not retrieve Axes Element.");
    }

    parseAxesElement(axesElement);

    // Get the CellData Element
    Name cellDataName = soapEnvelope.createName("CellData", "", MDD_URI);
    SOAPElement cellDataElement = null;
    Iterator cellDataElements = rootElement.getChildElements(cellDataName);
    if (cellDataElements.hasNext()) {
        Object eObj = cellDataElements.next();
        if (eObj == null) {
            log.error("CellData element is null");
            throw new JRRuntimeException("CellData element is null");
        }
        cellDataElement = (SOAPElement) eObj;
    } else {
        log.error("Could not retrieve CellData Element.");
        throw new JRRuntimeException("Could not retrieve CellData Element.");
    }
    parseCellDataElement(cellDataElement);
}

From source file:it.cnr.icar.eric.common.SOAPMessenger.java

/** Send a SOAP request to the registry server. Main entry point for
 * this class. If credentials have been set on the registry connection,
 * they will be used to sign the request.
 *
 * @param requestString//from   w  ww .j  a  va  2  s.com
 *     String that will be placed in the body of the
 *     SOAP message to be sent to the server
 *
 * @param attachments
 *     HashMap consisting of entries each of which
 *     corresponds to an attachment where the entry key is the ContentId
 *     and the entry value is a javax.activation.DataHandler of the
 *     attachment. A parameter value of null means no attachments.
 *
 * @return
 *     RegistryResponseHolder that represents the response from the
 *     server
 */
@SuppressWarnings("unchecked")
public RegistryResponseHolder sendSoapRequest(String requestString, Map<?, ?> attachments)
        throws JAXRException {
    boolean logRequests = Boolean.valueOf(
            CommonProperties.getInstance().getProperty("eric.common.soapMessenger.logRequests", "false"))
            .booleanValue();

    if (logRequests) {
        PrintStream requestLogPS = null;
        try {
            requestLogPS = new PrintStream(
                    new FileOutputStream(java.io.File.createTempFile("SOAPMessenger_requestLog", ".xml")));
            requestLogPS.println(requestString);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (requestLogPS != null) {
                requestLogPS.close();
            }
        }
    }

    // =================================================================

    //        // Remove the XML Declaration, if any
    //        if (requestString.startsWith("<?xml")) {
    //            requestString = requestString.substring(requestString.indexOf("?>")+2).trim();
    //        }
    //
    //        StringBuffer soapText = new StringBuffer(
    //                "<soap-env:Envelope xmlns:soap-env=\"http://schemas.xmlsoap.org/soap/envelope/\">");
    //
    //      soapText.append("<soap-env:Header>\n");
    //      // tell server about our superior SOAP Fault capabilities
    //      soapText.append("<");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(" xmlns='");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
    //      soapText.append("'>");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);
    //      soapText.append("</");
    //      soapText.append(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName);
    //      soapText.append(">\n");
    //      soapText.append("</soap-env:Header>\n");

    //      soapText.append("<soap-env:Body>\n");
    //        soapText.append(requestString);
    //        soapText.append("</soap-env:Body>");
    //        soapText.append("</soap-env:Envelope>");

    MessageFactory messageFactory;
    SOAPMessage message = null;
    SOAPPart sp = null;
    SOAPEnvelope se = null;
    SOAPBody sb = null;
    SOAPHeader sh = null;

    if (log.isTraceEnabled()) {
        log.trace("requestString=\"" + requestString + "\"");
    }
    try {

        messageFactory = MessageFactory.newInstance();
        message = messageFactory.createMessage();

        sp = message.getSOAPPart();
        se = sp.getEnvelope();
        sb = se.getBody();
        sh = se.getHeader();

        /*
         * <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
         *       <soap-env:Header>
         *          <capabilities xmlns="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</capabilities>
         *
         * change with explicit namespace
         *          <ns1:capabilities xmlns:ns1="urn:freebxml:registry:soap">urn:freebxml:registry:soap:modernFaultCodes</ns1:capabilities>
                
         */
        SOAPHeaderElement capabilityElement = sh
                .addHeaderElement(se.createName(BindingUtility.SOAP_CAPABILITY_HEADER_LocalName, "ns1",
                        BindingUtility.SOAP_CAPABILITY_HEADER_Namespace));
        //           capabilityElement.addAttribute(
        //                 se.createName("xmlns"), 
        //                 BindingUtility.SOAP_CAPABILITY_HEADER_Namespace);
        capabilityElement.setTextContent(BindingUtility.SOAP_CAPABILITY_ModernFaultCodes);

        /*
         * body
         */

        // Remove the XML Declaration, if any
        if (requestString.startsWith("<?xml")) {
            requestString = requestString.substring(requestString.indexOf("?>") + 2).trim();
        }

        // Generate DOM Document from request xml string
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        builderFactory.setNamespaceAware(true);
        InputStream stream = new ByteArrayInputStream(requestString.getBytes("UTF-8"));

        // Inject request into body
        sb.addDocument(builderFactory.newDocumentBuilder().parse(stream));

        // Is it never the case that there attachments but no credentials
        if ((attachments != null) && !attachments.isEmpty()) {
            addAttachments(message, attachments);
        }

        if (credentialInfo == null) {
            throw new JAXRException(resourceBundle.getString("message.credentialInfo"));
        }

        WSS4JSecurityUtilSAML.signSOAPEnvelopeOnClientSAML(se, credentialInfo);

        SOAPMessage response = send(message);

        // Check to see if the session has expired
        // by checking for an error response code
        // TODO: what error code to we look for?
        if (isSessionExpired(response)) {
            credentialInfo.sessionId = null;
            // sign the SOAPMessage this time
            // TODO: session - add method to do the signing
            // signSOAPMessage(msg);
            // send signed message
            // SOAPMessage response = send(msg);
        }

        // Process the main SOAPPart of the response
        //check for soapfault and throw RegistryException
        SOAPFault fault = response.getSOAPBody().getFault();
        if (fault != null) {
            throw createRegistryException(fault);
        }

        Reader reader = processResponseBody(response, "Response");

        RegistryResponseType ebResponse = null;

        try {
            Object obj = BindingUtility.getInstance().getJAXBContext().createUnmarshaller()
                    .unmarshal(new InputSource(reader));

            if (obj instanceof JAXBElement<?>)
                // if Element: take ComplexType from Element
                obj = ((JAXBElement<RegistryResponseType>) obj).getValue();

            ebResponse = (RegistryResponseType) obj;
        } catch (Exception x) {
            log.error(CommonResourceBundle.getInstance().getString("message.FailedToUnmarshalServerResponse"),
                    x);
            throw new JAXRException(resourceBundle.getString("message.invalidServerResponse"));
        }

        // Process the attachments of the response if any
        HashMap<String, Object> responseAttachments = processResponseAttachments(response);

        return new RegistryResponseHolder(ebResponse, responseAttachments);

    } catch (SAXException e) {
        throw new JAXRException(e);

    } catch (ParserConfigurationException e) {
        throw new JAXRException(e);

    } catch (UnsupportedEncodingException x) {
        throw new JAXRException(x);

    } catch (MessagingException x) {
        throw new JAXRException(x);

    } catch (FileNotFoundException x) {
        throw new JAXRException(x);

    } catch (IOException e) {
        throw new JAXRException(e);

    } catch (SOAPException x) {
        x.printStackTrace();
        throw new JAXRException(resourceBundle.getString("message.cannotConnect"), x);

    } catch (TransformerConfigurationException x) {
        throw new JAXRException(x);

    } catch (TransformerException x) {
        throw new JAXRException(x);
    }
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

public Object __buildOutputData(Context context, Object convertigoResponse) throws Exception {
    Engine.logBeans.debug("[WebServiceTranslator] Encoding the SOAP response...");

    SOAPMessage responseMessage = null;
    String sResponseMessage = "";
    String encodingCharSet = "UTF-8";
    if (context.requestedObject != null)
        encodingCharSet = context.requestedObject.getEncodingCharSet();

    if (convertigoResponse instanceof Document) {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is a XML document.");
        Document document = (Document) convertigoResponse;

        //MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
        MessageFactory messageFactory = MessageFactory.newInstance();
        responseMessage = messageFactory.createMessage();

        responseMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, encodingCharSet);

        SOAPPart sp = responseMessage.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();

        sb.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

        String targetNamespace = context.project.getTargetNamespace();
        String prefix = getPrefix(context.projectName, targetNamespace);

        //se.addNamespaceDeclaration(prefix, targetNameSpace);
        se.addNamespaceDeclaration("soapenc", "http://schemas.xmlsoap.org/soap/encoding/");
        se.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        se.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");

        // Remove header as it not used. Seems that empty headers causes the WS client of Flex 4 to fail 
        se.getHeader().detachNode();//from w ww.j  av a2  s . co m

        // Add the method response element
        SOAPElement soapMethodResponseElement = null;
        String soapElementName = context.sequenceName != null ? context.sequenceName
                : context.connectorName + "__" + context.transactionName;
        soapElementName += "Response";

        soapMethodResponseElement = sb.addChildElement(se.createName(soapElementName, prefix, targetNamespace));

        if (XsdForm.qualified == context.project.getSchemaElementForm()) {
            soapMethodResponseElement.addAttribute(se.createName("xmlns"), targetNamespace);
        }

        // Add a 'response' root child element or not
        SOAPElement soapResponseElement;
        if (context.sequenceName != null) {
            Sequence sequence = (Sequence) context.requestedObject;
            if (sequence.isIncludeResponseElement()) {
                soapResponseElement = soapMethodResponseElement.addChildElement("response");
            } else {
                soapResponseElement = soapMethodResponseElement;
            }
        } else {
            soapResponseElement = soapMethodResponseElement.addChildElement("response");
        }

        if (soapResponseElement.getLocalName().equals("response")) {
            if (document.getDocumentElement().hasAttributes()) {
                addAttributes(responseMessage, se, context, document.getDocumentElement().getAttributes(),
                        soapResponseElement);
            }
        }

        NodeList childNodes = document.getDocumentElement().getChildNodes();
        int len = childNodes.getLength();
        org.w3c.dom.Node node;
        for (int i = 0; i < len; i++) {
            node = childNodes.item(i);
            if (node instanceof Element) {
                addElement(responseMessage, se, context, (Element) node, soapResponseElement);
            }
        }

        sResponseMessage = SOAPUtils.toString(responseMessage, encodingCharSet);

        // Correct missing "xmlns" (Bug AXA POC client .NET)
        //sResponseMessage = sResponseMessage.replaceAll("<soapenv:Envelope", "<soapenv:Envelope xmlns=\""+targetNameSpace+"\"");
    } else {
        Engine.logBeans.debug("[WebServiceTranslator] The Convertigo response is not a XML document.");
        sResponseMessage = convertigoResponse.toString();
    }

    if (Engine.logBeans.isDebugEnabled()) {
        Engine.logBeans.debug("[WebServiceTranslator] SOAP response:\n" + sResponseMessage);
    }

    return responseMessage == null ? sResponseMessage.getBytes(encodingCharSet) : responseMessage;
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private void addAttributes(SOAPMessage responseMessage, SOAPEnvelope soapEnvelope, Context context,
        NamedNodeMap attributes, SOAPElement soapElement) throws SOAPException {
    SOAPElement soapMethodResponseElement = (SOAPElement) soapEnvelope.getBody().getFirstChild();
    String targetNamespace = soapMethodResponseElement.getNamespaceURI();
    String prefix = soapMethodResponseElement.getPrefix();

    int len = attributes.getLength();
    Attr attribute;//from  www  .j a  v a 2  s.  c  o m
    for (int i = 0; i < len; i++) {
        attribute = (Attr) attributes.item(i);
        String attributeName = attribute.getName();
        String attributeValue = attribute.getNodeValue();
        String attributeNsUri = attribute.getNamespaceURI();
        String attributePrefix = getPrefix(context.projectName, attributeNsUri);

        XmlSchemaAttribute xmlSchemaAttribute = getXmlSchemaAttributeByName(context.projectName, attributeName);
        boolean isGlobal = xmlSchemaAttribute != null;
        if (isGlobal) {
            attributeNsUri = xmlSchemaAttribute.getQName().getNamespaceURI();
            attributePrefix = getPrefix(context.projectName, attributeNsUri);
        }

        if (XsdForm.qualified == context.project.getSchemaElementForm() || isGlobal) {
            if (attributePrefix == null) {
                soapElement.addAttribute(soapEnvelope.createName(attributeName, prefix, targetNamespace),
                        attributeValue);
            } else {
                soapElement.addAttribute(
                        soapEnvelope.createName(attributeName, attributePrefix, attributeNsUri),
                        attributeValue);
            }
        } else {
            soapElement.addAttribute(soapEnvelope.createName(attributeName), attributeValue);
        }
    }
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private SOAPElement addSoapElement(Context context, SOAPEnvelope se, SOAPElement soapParent, Node node)
        throws Exception {
    String prefix = node.getPrefix();
    String namespace = node.getNamespaceURI();
    String nodeName = node.getNodeName();
    String localName = node.getLocalName();
    String value = node.getNodeValue();

    boolean includeResponseElement = true;
    if (context.sequenceName != null) {
        includeResponseElement = ((Sequence) context.requestedObject).isIncludeResponseElement();
    }/*from w w  w . jav  a2  s. co  m*/

    SOAPElement soapElement = null;
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;

        boolean toAdd = true;
        if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
            toAdd = false;
        }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(element.getParentNode().getNamespaceURI())
                || "http://schemas.xmlsoap.org/soap/envelope/".equals(namespace)
                || nodeName.toLowerCase().endsWith(":envelope") || nodeName.toLowerCase().endsWith(":body")
        //element.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1 ||
        //nodeName.toUpperCase().indexOf("NS0:") != -1
        ) {
            toAdd = false;
        }

        if (toAdd) {
            if (prefix == null || prefix.equals("")) {
                soapElement = soapParent.addChildElement(nodeName);
            } else {
                soapElement = soapParent.addChildElement(se.createName(localName, prefix, namespace));
            }
        } else {
            soapElement = soapParent;
        }

        if (soapElement != null) {
            if (soapParent.equals(se.getBody()) && !soapParent.equals(soapElement)) {
                if (XsdForm.qualified == context.project.getSchemaElementForm()) {
                    if (soapElement.getAttribute("xmlns") == null) {
                        soapElement.addAttribute(se.createName("xmlns"), context.project.getTargetNamespace());
                    }
                }
            }

            if (element.hasAttributes()) {
                String attrType = element.getAttribute("type");
                if (("attachment").equals(attrType)) {
                    if (context.requestedObject instanceof AbstractHttpTransaction) {
                        AttachmentDetails attachment = AttachmentManager.getAttachment(element);
                        if (attachment != null) {
                            byte[] raw = attachment.getData();
                            if (raw != null)
                                soapElement.addTextNode(Base64.encodeBase64String(raw));
                        }

                        /* DON'T WORK YET *\
                        AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), element.getAttribute("content-type"));
                        ap.setContentId(key);
                        ap.setContentLocation(element.getAttribute("url"));
                        responseMessage.addAttachmentPart(ap);
                        \* DON'T WORK YET */
                    }
                }

                if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
                    // do not add attributes
                } else {
                    NamedNodeMap attributes = element.getAttributes();
                    int len = attributes.getLength();
                    for (int i = 0; i < len; i++) {
                        Node item = attributes.item(i);
                        addSoapElement(context, se, soapElement, item);
                    }
                }
            }

            if (element.hasChildNodes()) {
                NodeList childNodes = element.getChildNodes();
                int len = childNodes.getLength();
                for (int i = 0; i < len; i++) {
                    Node item = childNodes.item(i);
                    switch (item.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        addSoapElement(context, se, soapElement, item);
                        break;
                    case Node.CDATA_SECTION_NODE:
                    case Node.TEXT_NODE:
                        String text = item.getNodeValue();
                        text = (text == null) ? "" : text;
                        soapElement.addTextNode(text);
                        break;
                    default:
                        break;
                    }
                }
            }
        }
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        if (prefix == null || prefix.equals("")) {
            soapElement = soapParent.addAttribute(se.createName(nodeName), value);
        } else {
            soapElement = soapParent.addAttribute(se.createName(localName, prefix, namespace), value);
        }
    }
    return soapElement;
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private void addElement(SOAPMessage responseMessage, SOAPEnvelope soapEnvelope, Context context,
        Element elementToAdd, SOAPElement soapElement) throws SOAPException {
    SOAPElement soapMethodResponseElement = (SOAPElement) soapEnvelope.getBody().getFirstChild();
    String targetNamespace = soapMethodResponseElement.getNamespaceURI();
    String prefix = soapMethodResponseElement.getPrefix();

    String nodeType = elementToAdd.getAttribute("type");
    SOAPElement childSoapElement = soapElement;

    boolean elementAdded = true;
    boolean bTable = false;

    if (nodeType.equals("table")) {
        bTable = true;/*from  ww w .ja  va2s  . c  o m*/
        /*childSoapElement = soapElement.addChildElement("ArrayOf" + context.transactionName + "_" + tableName + "_Row", "");
                
           if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
              childSoapElement.addAttribute(soapEnvelope.createName("xsi:type"), "soapenc:Array");
           }*/
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
    } else if (nodeType.equals("row")) {
        /*String elementType = context.transactionName + "_" + tableName + "_Row";
        childSoapElement = soapElement.addChildElement(elementType, "");*/
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());
    } else if (nodeType.equals("attachment")) {
        childSoapElement = soapElement.addChildElement(elementToAdd.getNodeName());

        if (context.requestedObject instanceof AbstractHttpTransaction) {
            AttachmentDetails attachment = AttachmentManager.getAttachment(elementToAdd);
            if (attachment != null) {
                byte[] raw = attachment.getData();
                if (raw != null)
                    childSoapElement.addTextNode(Base64.encodeBase64String(raw));
            }

            /* DON'T WORK YET *\
            AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), elementToAdd.getAttribute("content-type"));
            ap.setContentId(key);
            ap.setContentLocation(elementToAdd.getAttribute("url"));
            responseMessage.addAttachmentPart(ap);
            \* DON'T WORK YET */
        }
    } else {
        String elementNodeName = elementToAdd.getNodeName();
        String elementNodeNsUri = elementToAdd.getNamespaceURI();
        String elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);

        XmlSchemaElement xmlSchemaElement = getXmlSchemaElementByName(context.projectName, elementNodeName);
        boolean isGlobal = xmlSchemaElement != null;
        if (isGlobal) {
            elementNodeNsUri = xmlSchemaElement.getQName().getNamespaceURI();
            elementNodePrefix = getPrefix(context.projectName, elementNodeNsUri);
        }

        // ignore original SOAP message response elements
        //         if ((elementNodeName.toUpperCase().indexOf("SOAP-ENV:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("SOAP-ENV:") != -1)) ||
        //            (elementNodeName.toUpperCase().indexOf("SOAPENV:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("SOAPENV:") != -1)) ||
        //            (elementNodeName.toUpperCase().indexOf("NS0:") != -1) || ((elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1))) {
        //            elementAdded = false;
        //         }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(elementToAdd.getNamespaceURI())
                || "http://schemas.xmlsoap.org/soap/envelope/"
                        .equals(elementToAdd.getParentNode().getNamespaceURI())
                || elementToAdd.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1
                || elementNodeName.toUpperCase().indexOf("NS0:") != -1) {
            elementAdded = false;
        } else {
            if (XsdForm.qualified == context.project.getSchemaElementForm() || isGlobal) {
                if (elementNodePrefix == null) {
                    childSoapElement = soapElement
                            .addChildElement(soapEnvelope.createName(elementNodeName, prefix, targetNamespace));
                } else {
                    childSoapElement = soapElement.addChildElement(
                            soapEnvelope.createName(elementNodeName, elementNodePrefix, elementNodeNsUri));
                }
            } else {
                childSoapElement = soapElement.addChildElement(elementNodeName);
            }
        }
    }

    if (elementAdded && elementToAdd.hasAttributes()) {
        addAttributes(responseMessage, soapEnvelope, context, elementToAdd.getAttributes(), childSoapElement);
    }

    if (elementToAdd.hasChildNodes()) {
        NodeList childNodes = elementToAdd.getChildNodes();
        int len = childNodes.getLength();

        if (bTable) {
            /*if (!context.httpServletRequest.getServletPath().endsWith(".wsl")) {
               childSoapElement.addAttribute(soapEnvelope.createName("soapenc:arrayType"), context.projectName+"_ns:" + context.transactionName + "_" + tableName + "_Row[" + (len - 1) + "]");
            }*/
        }

        org.w3c.dom.Node node;
        Element childElement;
        for (int i = 0; i < len; i++) {
            node = childNodes.item(i);
            switch (node.getNodeType()) {
            case org.w3c.dom.Node.ELEMENT_NODE:
                childElement = (Element) node;
                addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
                break;
            case org.w3c.dom.Node.CDATA_SECTION_NODE:
            case org.w3c.dom.Node.TEXT_NODE:
                String text = node.getNodeValue();
                text = (text == null) ? "" : text;
                childSoapElement.addTextNode(text);
                break;
            default:
                break;
            }
        }

        /*org.w3c.dom.Node node;
        Element childElement;
        for (int i = 0 ; i < len ; i++) {
           node = childNodes.item(i);
           if (node instanceof Element) {
              childElement = (Element) node;
              addElement(responseMessage, soapEnvelope, context, childElement, childSoapElement);
           }
           else if (node instanceof CDATASection) {
              Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.CDATA_SECTION_NODE);
              String text = textNode.getNodeValue();
              if (text == null) {
          text = "";
              }
              childSoapElement.addTextNode(text);
           }
           else {
              Node textNode = XMLUtils.findChildNode(elementToAdd, org.w3c.dom.Node.TEXT_NODE);
              if (textNode != null) {
          String text = textNode.getNodeValue();
          if (text == null) {
             text = "";
          }
          childSoapElement.addTextNode(text);
              }
           }
        }*/
    }
}