Example usage for javax.xml.soap SOAPBody addBodyElement

List of usage examples for javax.xml.soap SOAPBody addBodyElement

Introduction

In this page you can find the example usage for javax.xml.soap SOAPBody addBodyElement.

Prototype

public SOAPBodyElement addBodyElement(QName qname) throws SOAPException;

Source Link

Document

Creates a new SOAPBodyElement object with the specified QName and adds it to this SOAPBody object.

Usage

From source file:org.jboss.jaxr.juddi.transport.SaajTransport.java

private SOAPMessage createSOAPMessage(Element elem) throws Exception {
    String prefix = "uddi";
    MessageFactory msgFactory = MessageFactory.newInstance();
    SOAPFactory factory = SOAPFactory.newInstance();

    SOAPMessage message = msgFactory.createMessage();
    message.getSOAPHeader().detachNode();
    SOAPPart soapPart = message.getSOAPPart();
    SOAPBody soapBody = soapPart.getEnvelope().getBody();
    //Create the outer body element
    String uddins = IRegistry.UDDI_V2_NAMESPACE;
    Name bodyName = factory.createName(elem.getNodeName(), prefix, uddins);
    SOAPBodyElement bodyElement = soapBody.addBodyElement(bodyName);
    bodyElement.addNamespaceDeclaration(prefix, uddins);
    appendAttributes(bodyElement, elem.getAttributes(), factory);
    appendElements(bodyElement, elem.getChildNodes(), factory);
    return message;
}

From source file:org.jbpm.bpel.integration.soap.SoapUtil.java

public static void copyChildElement(SOAPElement parent, Element source) throws SOAPException {
    String localName = source.getLocalName();
    String prefix = source.getPrefix();
    String namespaceURI = source.getNamespaceURI();

    Name targetName;/*from   w  w w .j  a  va2s  . c  o m*/
    SOAPEnvelope envelope = findEnvelope(parent);

    if (prefix == null || prefix.length() == 0) {
        // source has no prefix, distinguish between no namespace and default namespace
        if (namespaceURI == null || namespaceURI.length() == 0) {
            // no namespace
            targetName = envelope.createName(localName);
            if (traceEnabled)
                log.trace("appended element: " + localName);
        } else {
            // default namespace, look for existing prefix at target
            prefix = getPrefix(namespaceURI, parent);

            // no prefix for that namespace?
            if (prefix == null) {
                prefix = XmlUtil.generatePrefix(DEFAULT_NAMESPACE_PREFIX, source);
            }
            // BPEL-195 source maps prefix to another URI?
            else if (!namespaceURI.equals(source.getAttributeNS(BpelConstants.NS_XMLNS, prefix))) {
                prefix = XmlUtil.generatePrefix(prefix, source);
            }

            targetName = envelope.createName(localName, prefix, namespaceURI);
            if (traceEnabled)
                log.trace("added child element: {" + namespaceURI + '}' + prefix + ':' + localName);
        }
    } else {
        // source has prefix
        targetName = envelope.createName(localName, prefix, namespaceURI);
        if (traceEnabled)
            log.trace("added child element: {" + namespaceURI + '}' + prefix + ':' + localName);
    }

    SOAPElement target;
    if (parent instanceof SOAPBody) {
        /*
         * jboss-ws4ee throws ClassCastException upon calling the remote endpoint if child elements
         * other than SOAPBodyElements are added to SOAPBody
         */
        SOAPBody body = (SOAPBody) parent;
        target = body.addBodyElement(targetName);
    } else
        target = parent.addChildElement(targetName);

    // namespaces
    copyNamespaces(target, source);
    ensureOwnNamespaceDeclared(target);
    // attributes
    copyAttributes(target, source);
    // child nodes
    copyChildNodes(target, source);
}

From source file:org.jbpm.bpel.integration.soap.SoapUtilTest.java

public void testCopyChildElement_domSoap() throws Exception {
    // <soap:Envelope xmlns:soap='${SOAPConstants.URI_NS_SOAP_ENVELOPE}'>
    // <soap:Body xmlns:fish='urn:example:fish'>
    // <meal:lunch xmlns:produce='urn:example:produce'
    // xmlns:meal='urn:example:meal'>
    // <padding />
    // </meal:lunch>
    // </soap:Body>
    // </soap:Envelope>
    SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
    SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();

    SOAPBody body = envelope.getBody();
    body.addNamespaceDeclaration("fish", "urn:example:fish");

    Name lunchName = envelope.createName("lunch", "meal", "urn:example:meal");
    SOAPElement lunch = body.addBodyElement(lunchName);
    lunch.addNamespaceDeclaration("produce", "urn:example:produce");
    lunch.addNamespaceDeclaration("meal", "urn:example:meal");

    SOAPElement source = SoapUtil.addChildElement(lunch, "padding");
    Element parent = XmlUtil.createElement("urn:example:meal", "lunch");

    // perform the copy
    SoapUtil.copyChildElement(parent, source);
    Element padding = XmlUtil.getElement(parent, "padding");

    // unqualified element
    assertNull(padding.getPrefix());//from ww w . j  a  v  a2  s.  c  om

    // reload
    // parent = writeAndRead(parent);
    padding = XmlUtil.getElement(parent, "padding");

    // unqualified element
    assertNull(padding.getPrefix());
}

From source file:org.mule.transport.soap.axis.style.DefaultMessageService.java

public void soapRequestResponse(SOAPEnvelope req, SOAPEnvelope resp) throws SOAPException {
    // Echo back//w w w.  j av a  2  s . co m
    logger.debug("envelopeTest Called");
    SOAPBody body = resp.getBody();
    Name ns0 = resp.createName("TestNS0", "ns0", "http://example.com");
    Name ns1 = resp.createName("TestNS1", "ns1", "http://example.com");
    SOAPElement bodyElmnt = body.addBodyElement(ns0);
    SOAPElement el = bodyElmnt.addChildElement(ns1);
    el.addTextNode("TEST RESPONSE");
}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Fetches the values for the given item configurations from the FritzBox. Calls
 * the FritzBox SOAP services delivering the values for the item configurations.
 * The resulting map contains the values of all item configurations returned by
 * the invoked services. This can be more items than were given as parameter.
 *
 * @param request//from w w w . ja v a  2s. c o  m
 *            string from config including the command and optional parameters
 * @return Parsed values for all item configurations returned by the invoked
 *         services.
 */
public Map<ItemConfiguration, String> getTr064Values(Collection<ItemConfiguration> itemConfigurations) {
    Map<ItemConfiguration, String> values = new HashMap<>();

    for (ItemConfiguration itemConfiguration : itemConfigurations) {

        String itemCommand = itemConfiguration.getItemCommand();

        if (values.containsKey(itemCommand)) {
            // item value already read by earlier MultiItemMap
            continue;
        }

        // search for proper item Mapping
        ItemMap itemMap = determineItemMappingByItemCommand(itemCommand);

        if (itemMap == null) {
            logger.warn("No item mapping found for {}. Function not implemented by your FritzBox (?)",
                    itemConfiguration);
            continue;
        }

        // determine which url etc. to connect to for accessing required value
        Tr064Service tr064service = determineServiceByItemMapping(itemMap);

        // construct soap Body which is added to soap msg later
        SOAPBodyElement bodyData = null; // holds data to be sent to fbox
        try {
            MessageFactory mf = MessageFactory.newInstance();
            SOAPMessage msg = mf.createMessage(); // empty message
            SOAPBody body = msg.getSOAPBody(); // std. SAOP body
            QName bodyName = new QName(tr064service.getServiceType(), itemMap.getReadServiceCommand(), "u"); // header
                                                                                                             // for
                                                                                                             // body
                                                                                                             // element
            bodyData = body.addBodyElement(bodyName);
            // only if input parameter is present
            if (itemMap instanceof ParametrizedItemMap) {
                for (InputArgument inputArgument : ((ParametrizedItemMap) itemMap)
                        .getConfigInputArguments(itemConfiguration)) {
                    String dataInName = inputArgument.getName();
                    String dataInValue = inputArgument.getValue();
                    QName dataNode = new QName(dataInName);
                    SOAPElement beDataNode = bodyData.addChildElement(dataNode);
                    // if input is mac address, replace "-" with ":" as fbox wants
                    if (itemConfiguration.getItemCommand().equals("maconline")) {
                        dataInValue = dataInValue.replaceAll("-", ":");
                    }
                    beDataNode.addTextNode(dataInValue); // add data which should be requested from fbox for this
                                                         // service
                }

            }
            logger.trace("Raw SOAP Request to be sent to FritzBox: {}", soapToString(msg));

        } catch (Exception e) {
            logger.warn("Error constructing request SOAP msg for getting parameter. {}", e.getMessage());
            logger.debug("Request was: {}", itemConfiguration);
        }

        if (bodyData == null) {
            logger.warn("Could not determine data to be sent to FritzBox!");
            return null;
        }

        SOAPMessage smTr064Request = constructTr064Msg(bodyData); // construct entire msg with body element
        String soapActionHeader = tr064service.getServiceType() + "#" + itemMap.getReadServiceCommand(); // needed
                                                                                                         // to be
                                                                                                         // sent
                                                                                                         // with
                                                                                                         // request
                                                                                                         // (not
                                                                                                         // in body
                                                                                                         // ->
                                                                                                         // header)
        SOAPMessage response = readSoapResponse(soapActionHeader, smTr064Request,
                _url + tr064service.getControlUrl());
        logger.trace("Raw SOAP Response from FritzBox: {}", soapToString(response));
        if (response == null) {
            logger.warn("Error retrieving SOAP response from FritzBox");
            continue;
        }

        values.putAll(
                itemMap.getSoapValueParser().parseValuesFromSoapMessage(response, itemMap, itemConfiguration));
    }

    return values;
}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Sets a parameter in fbox. Called from event bus.
 *
 * @param request/* w  w w. j  a va 2s .  c o m*/
 *            config string from itemconfig
 * @param cmd
 *            command to set
 */
public void setTr064Value(ItemConfiguration request, Command cmd) {
    String itemCommand = request.getItemCommand();

    // search for proper item Mapping
    ItemMap itemMapForCommand = determineItemMappingByItemCommand(itemCommand);

    if (!(itemMapForCommand instanceof WritableItemMap)) {
        logger.warn("Item command {} does not support setting values", itemCommand);
        return;
    }
    WritableItemMap itemMap = (WritableItemMap) itemMapForCommand;

    Tr064Service tr064service = determineServiceByItemMapping(itemMap);

    // determine which url etc. to connect to for accessing required value
    // construct soap Body which is added to soap msg later
    SOAPBodyElement bodyData = null; // holds data to be sent to fbox
    try {
        MessageFactory mf = MessageFactory.newInstance();
        SOAPMessage msg = mf.createMessage(); // empty message
        SOAPBody body = msg.getSOAPBody(); // std. SAOP body
        QName bodyName = new QName(tr064service.getServiceType(), itemMap.getWriteServiceCommand(), "u"); // header
                                                                                                          // for
                                                                                                          // body
                                                                                                          // element
        bodyData = body.addBodyElement(bodyName);

        List<InputArgument> writeInputArguments = new ArrayList<>();
        writeInputArguments.add(itemMap.getWriteInputArgument(cmd));
        if (itemMap instanceof ParametrizedItemMap) {
            writeInputArguments.addAll(((ParametrizedItemMap) itemMap).getConfigInputArguments(request));
        }

        for (InputArgument inputArgument : writeInputArguments) {
            QName dataNode = new QName(inputArgument.getName());
            SOAPElement beDataNode = bodyData.addChildElement(dataNode);
            beDataNode.addTextNode(inputArgument.getValue());
        }

        logger.debug("SOAP Msg to send to FritzBox for setting data: {}", soapToString(msg));

    } catch (Exception e) {
        logger.error("Error constructing request SOAP msg for setting parameter. {}", e.getMessage());
        logger.debug("Request was: {}. Command was: {}.", request, cmd.toString());
    }

    if (bodyData == null) {
        logger.error("Could not determine data to be sent to FritzBox!");
        return;
    }

    SOAPMessage smTr064Request = constructTr064Msg(bodyData); // construct entire msg with body element
    String soapActionHeader = tr064service.getServiceType() + "#" + itemMap.getWriteServiceCommand(); // needed to
                                                                                                      // be sent
                                                                                                      // with
                                                                                                      // request
                                                                                                      // (not in
                                                                                                      // body ->
                                                                                                      // header)
    SOAPMessage response = readSoapResponse(soapActionHeader, smTr064Request,
            _url + tr064service.getControlUrl());
    if (response == null) {
        logger.error("Error retrieving SOAP response from FritzBox");
        return;
    }
    logger.debug("SOAP response from FritzBox: {}", soapToString(response));

    // Check if error received
    try {
        if (response.getSOAPBody().getFault() != null) {
            logger.error("Error received from FritzBox while trying to set parameter");
            logger.debug("Soap Response was: {}", soapToString(response));
        }
    } catch (SOAPException e) {
        logger.error("Could not parse soap response from FritzBox while setting parameter. {}", e.getMessage());
        logger.debug("Soap Response was: {}", soapToString(response));
    }

}

From source file:test.functional.TestJAXMSamples.java

public void testJWSFault() throws Exception {
    try {//from  w  w  w  .  ja va  2s  .  c om
        SOAPConnectionFactory scFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection con = scFactory.createConnection();

        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage message = factory.createMessage();

        SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
        SOAPBody body = envelope.getBody();

        Name bodyName = envelope.createName("echo");
        SOAPBodyElement bodyElement = body.addBodyElement(bodyName);

        Name name = envelope.createName("arg0");
        SOAPElement symbol = bodyElement.addChildElement(name);
        symbol.addTextNode("Hello");

        URLEndpoint endpoint = new URLEndpoint("http://localhost:8080/jws/FaultTest.jws");
        SOAPMessage response = con.call(message, endpoint);
        SOAPBody respBody = response.getSOAPPart().getEnvelope().getBody();
        assertTrue(respBody.hasFault());
    } catch (javax.xml.soap.SOAPException e) {
        Throwable t = e.getCause();
        if (t != null) {
            t.printStackTrace();
            if (t instanceof AxisFault) {
                AxisFault af = (AxisFault) t;
                if ((af.detail instanceof SocketException)
                        || (af.getFaultCode().getLocalPart().equals("HTTP"))) {
                    System.out.println("Connect failure caused testJWSFault to be skipped.");
                    return;
                }
            }
            throw new Exception("Fault returned from test: " + t);
        } else {
            e.printStackTrace();
            throw new Exception("Exception returned from test: " + e);
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new Exception("Fault returned from test: " + t);
    }
}

From source file:test.saaj.TestAttachmentSerialization.java

public int saveMsgWithAttachments(OutputStream os) throws Exception {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage msg = mf.createMessage();

    SOAPPart sp = msg.getSOAPPart();
    SOAPEnvelope envelope = sp.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPBody body = envelope.getBody();

    SOAPElement el = header.addHeaderElement(envelope.createName("field4", NS_PREFIX, NS_URI));
    SOAPElement el2 = el.addChildElement("field4b", NS_PREFIX);
    SOAPElement el3 = el2.addTextNode("field4value");

    el = body.addBodyElement(envelope.createName("bodyfield3", NS_PREFIX, NS_URI));
    el2 = el.addChildElement("bodyfield3a", NS_PREFIX);
    el2.addTextNode("bodyvalue3a");
    el2 = el.addChildElement("bodyfield3b", NS_PREFIX);
    el2.addTextNode("bodyvalue3b");
    el2 = el.addChildElement("datefield", NS_PREFIX);

    AttachmentPart ap = msg.createAttachmentPart();
    ap.setContent("some attachment text...", "text/plain");
    msg.addAttachmentPart(ap);// w w  w  .ja  va2s  .  c  o  m

    String jpgfilename = "docs/images/axis.jpg";
    File myfile = new File(jpgfilename);
    FileDataSource fds = new FileDataSource(myfile);
    DataHandler dh = new DataHandler(fds);
    AttachmentPart ap2 = msg.createAttachmentPart(dh);
    ap2.setContentType("image/jpg");
    msg.addAttachmentPart(ap2);

    // Test for Bug #17664
    if (msg.saveRequired()) {
        msg.saveChanges();
    }
    MimeHeaders headers = msg.getMimeHeaders();
    assertTrue(headers != null);
    String[] contentType = headers.getHeader("Content-Type");
    assertTrue(contentType != null);

    msg.writeTo(os);
    os.flush();
    return msg.countAttachments();
}

From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java

@Test
public void testVerifyTimestamp() throws Exception {
    // setup/*w w  w . j  av  a  2  s  . com*/
    SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class);

    EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.FALSE);

    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage();

    SOAPBody soapBody = soapMessage.getSOAPBody();
    soapBody.addBodyElement(new QName("test"));

    SOAPPart soapPart = soapMessage.getSOAPPart();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(soapPart);
    WSSecTimestamp timestamp = new WSSecTimestamp();
    timestamp.build(soapPart, secHeader);

    LOG.debug("SOAP message: " + toString(soapMessage.getSOAPPart()));
    EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage);

    // prepare
    EasyMock.replay(mockContext);

    // operate
    boolean result = this.testedInstance.handleMessage(mockContext);

    // verify
    EasyMock.verify(mockContext);
    assertTrue(result);
}

From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java

@Test
public void testVerifyTimestampMissing() throws Exception {
    // setup//from w w  w. j  a v  a 2  s.c o m
    SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class);

    EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.FALSE);

    SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage();

    SOAPBody soapBody = soapMessage.getSOAPBody();
    soapBody.addBodyElement(new QName("test"));

    LOG.debug("SOAP message: " + toString(soapMessage.getSOAPPart()));
    EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage);

    // prepare
    EasyMock.replay(mockContext);

    // operate
    try {
        this.testedInstance.handleMessage(mockContext);
        fail();
    } catch (ProtocolException e) {
        // verify
        EasyMock.verify(mockContext);
    }
}