Example usage for javax.xml.soap SOAPBody addChildElement

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

Introduction

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

Prototype

public SOAPElement addChildElement(Name name) throws SOAPException;

Source Link

Document

Creates a new SOAPElement object initialized with the given Name object and adds the new element to this SOAPElement object.

Usage

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java

/**
 * Invokes an operation using SAAJ//from  w ww.j  a  v  a  2s  .  co  m
 *
 * @param operation The operation to invoke
 */
public static void main(String[] args) {
    try {
        /*OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("HelloWorld_sayHello");
        operation.setInputMessageText("<urn:sayHello xmlns:urn='urn:jbosstest'><arg0>Markus</arg0></urn:sayHello>");
        operation.setNamespaceURI("urn:jbosstest");
        operation.setOutputMessageName("HelloWorld_sayHelloResponse");
        operation.setOutputMessageText("<sayHello><return>0</return></sayHello>");
        operation.setSoapActionURI("");
        operation.setStyle("document");
        operation.setTargetMethodName("sayHello");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://localhost:8080/HelloWorld/HelloWorld");*/

        OperationInfo operation = new OperationInfo();
        operation.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
        operation.setInputMessageName("ConversionRateSoapIn");
        operation.setInputMessageText(
                "<ns5:ConversionRate xmlns:ns5='http://www.webserviceX.NET/'><ns5:FromCurrency>EUR</ns5:FromCurrency><ns5:ToCurrency>SKK</ns5:ToCurrency></ns5:ConversionRate>");
        operation.setNamespaceURI("http://www.webserviceX.NET/");
        operation.setOutputMessageName("ConversionRateSoapOut");
        operation.setOutputMessageText(
                "<ConversionRate><ConversionRateResult>0</ConversionRateResult></ConversionRate>");
        operation.setSoapActionURI("http://www.webserviceX.NET/ConversionRate");
        operation.setStyle("document");
        operation.setTargetMethodName("ConversionRate");
        operation.setTargetObjectURI(null);
        operation.setTargetURL("http://www.webservicex.net/CurrencyConvertor.asmx");

        // Determine if the operation style is RPC
        boolean isRPC = operation.getStyle().equalsIgnoreCase("rpc");

        // All connections are created by using a connection factory
        SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();

        // Now we can create a SOAPConnection object using the connection factory
        SOAPConnection connection = conFactory.createConnection();

        // All SOAP messages are created by using a message factory
        MessageFactory msgFactory = MessageFactory.newInstance();

        // Now we can create the SOAP message object
        SOAPMessage msg = msgFactory.createMessage();

        // Get the SOAP part from the SOAP message object
        SOAPPart soapPart = msg.getSOAPPart();

        // The SOAP part object will automatically contain the SOAP envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        //envelope.addNamespaceDeclaration("", operation.getNamespaceURI());

        if (isRPC) {
            // Add namespace declarations to the envelope, usually only required for RPC/encoded
            envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI);
            envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI);
        }

        // Get the SOAP header from the envelope
        SOAPHeader header = envelope.getHeader();

        // The client does not yet support SOAP headers
        header.detachNode();

        // Get the SOAP body from the envelope and populate it
        SOAPBody body = envelope.getBody();

        // Create the default namespace for the SOAP body
        //body.addNamespaceDeclaration("", operation.getNamespaceURI());

        // Add the service information
        String targetObjectURI = operation.getTargetObjectURI();

        if (targetObjectURI == null) {
            // The target object URI should not be null
            targetObjectURI = "";
        }

        // Add the service information
        //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI);
        Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns2", operation.getNamespaceURI());
        SOAPElement svcElem = body.addChildElement(svcInfo);

        if (isRPC) {
            // Set the encoding style of the service element
            svcElem.setEncodingStyle(operation.getEncodingStyle());
        }

        // Add the message contents to the SOAP body
        Document doc = XMLSupport.readXML(operation.getInputMessageText());

        if (doc.hasRootElement()) {
            // Begin building content
            buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC);
        }

        //svcElem.addTextNode(operation.getInputMessageText());
        //svcElem.

        // Check for a SOAPAction
        String soapActionURI = operation.getSoapActionURI();

        if (soapActionURI != null && soapActionURI.length() > 0) {
            // Add the SOAPAction value as a MIME header
            MimeHeaders mimeHeaders = msg.getMimeHeaders();
            mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\"");
        }

        // Save changes to the message we just populated
        msg.saveChanges();

        // Get ready for the invocation
        URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL());

        // Show the URL endpoint message in the log
        ByteArrayOutputStream msgStream = new ByteArrayOutputStream();
        msg.writeTo(msgStream);

        log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL());
        log.debug("SOAP Request: " + msgStream.toString());

        // Make the call
        SOAPMessage response = connection.call(msg, endpoint);

        // Close the connection, we are done with it
        connection.close();

        // Get the content of the SOAP response
        Source responseContent = response.getSOAPPart().getContent();

        // Convert the SOAP response into a JDOM
        TransformerFactory tFact = TransformerFactory.newInstance();
        Transformer transformer = tFact.newTransformer();

        JDOMResult jdomResult = new JDOMResult();
        transformer.transform(responseContent, jdomResult);

        // Get the document created by the transform operation
        Document responseDoc = jdomResult.getDocument();

        // Send the response to the Log
        String strResponse = XMLSupport.outputString(responseDoc);
        log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse);

        // Set the response as the output message
        operation.setOutputMessageText(strResponse);

        // Return the response generated
        //return strResponse;
    }

    catch (Throwable ex) {
        log.error("Error invoking operation:");
        log.error(ex.getMessage());
    }

    //return "";
}

From source file:net.bpelunit.framework.control.deploy.ode.ODERequestEntityFactory.java

private void prepareUndeploySOAP(String packageId) throws SOAPException, IOException {
    MessageFactory mFactory = MessageFactory.newInstance();
    SOAPMessage message = mFactory.createMessage();
    SOAPBody body = message.getSOAPBody();

    SOAPElement xmlUndeploy = body.addChildElement(ODE_ELEMENT_UNDEPLOY);
    SOAPElement xmlPackageName = xmlUndeploy.addChildElement(ODE_ELEMENT_PACKAGENAME);
    xmlPackageName.setTextContent(packageId);

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    message.writeTo(b);// w  w  w. j ava2 s.c o  m
    fContent = b.toString();
}

From source file:net.bpelunit.framework.control.deploy.ode.ODERequestEntityFactory.java

private void prepareDeploySOAP(File file) throws IOException, SOAPException {
    MessageFactory mFactory = MessageFactory.newInstance();
    SOAPMessage message = mFactory.createMessage();
    SOAPBody body = message.getSOAPBody();

    SOAPElement xmlDeploy = body.addChildElement(ODE_ELEMENT_DEPLOY);
    SOAPElement xmlZipFilename = xmlDeploy.addChildElement(ODE_ELEMENT_ZIPNAME);
    xmlZipFilename.setTextContent(FilenameUtils.getName(file.toString()).split("\\.")[0]);

    SOAPElement xmlZipContent = xmlDeploy.addChildElement(ODE_ELEMENT_PACKAGE);
    SOAPElement xmlBase64ZipFile = xmlZipContent.addChildElement(ODE_ELEMENT_ZIP, "dep", NS_DEPLOY_SERVICE);

    xmlBase64ZipFile.addAttribute(new QName(NS_XML_MIME, CONTENT_TYPE_STRING), ZIP_CONTENT_TYPE);

    StringBuilder content = new StringBuilder();
    byte[] arr = FileUtils.readFileToByteArray(file);
    byte[] encoded = Base64.encodeBase64Chunked(arr);
    for (int i = 0; i < encoded.length; i++) {
        content.append((char) encoded[i]);
    }/*from   w  ww.ja  va  2s . co  m*/

    xmlBase64ZipFile.setTextContent(content.toString());

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    message.writeTo(b);
    fContent = b.toString();
}

From source file:eu.planets_project.tb.gui.backing.admin.wsclient.util.WSClient.java

/**
 * Invokes an operation using SAAJ//  w  w  w .j  a v  a  2 s. c  o  m
 *
 * @param operation The operation to invoke
 */
public static String invokeOperation(OperationInfo operation) throws Exception {
    try {
        // Determine if the operation style is RPC
        boolean isRPC = false;
        if (operation.getStyle() != null)
            isRPC = operation.getStyle().equalsIgnoreCase("rpc");
        else
            ;

        // All connections are created by using a connection factory
        SOAPConnectionFactory conFactory = SOAPConnectionFactory.newInstance();

        // Now we can create a SOAPConnection object using the connection factory
        SOAPConnection connection = conFactory.createConnection();

        // All SOAP messages are created by using a message factory
        MessageFactory msgFactory = MessageFactory.newInstance();

        // Now we can create the SOAP message object
        SOAPMessage msg = msgFactory.createMessage();

        // Get the SOAP part from the SOAP message object
        SOAPPart soapPart = msg.getSOAPPart();

        // The SOAP part object will automatically contain the SOAP envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        //my extension - START
        //envelope.addNamespaceDeclaration("_ns1", operation.getNamespaceURI());
        //my extension - END

        if (isRPC) {
            // Add namespace declarations to the envelope, usually only required for RPC/encoded
            envelope.addNamespaceDeclaration(XSI_NAMESPACE_PREFIX, XSI_NAMESPACE_URI);
            envelope.addNamespaceDeclaration(XSD_NAMESPACE_PREFIX, XSD_NAMESPACE_URI);
        }

        // Get the SOAP header from the envelope
        SOAPHeader header = envelope.getHeader();

        // The client does not yet support SOAP headers
        header.detachNode();

        // Get the SOAP body from the envelope and populate it
        SOAPBody body = envelope.getBody();

        // Create the default namespace for the SOAP body
        //body.addNamespaceDeclaration("", operation.getNamespaceURI());

        // Add the service information
        String targetObjectURI = operation.getTargetObjectURI();

        if (targetObjectURI == null) {
            // The target object URI should not be null
            targetObjectURI = "";
        }

        // Add the service information         
        //Name svcInfo = envelope.createName(operation.getTargetMethodName(), "", targetObjectURI);
        Name svcInfo = envelope.createName(operation.getTargetMethodName(), "ns1", operation.getNamespaceURI());
        SOAPElement svcElem = body.addChildElement(svcInfo);

        if (isRPC) {
            // Set the encoding style of the service element
            svcElem.setEncodingStyle(operation.getEncodingStyle());
        }

        // Add the message contents to the SOAP body
        Document doc = XMLSupport.readXML(operation.getInputMessageText());

        if (doc.hasRootElement()) {
            // Begin building content
            buildSoapElement(envelope, svcElem, doc.getRootElement(), isRPC);
        }

        //svcElem.addTextNode(operation.getInputMessageText());
        //svcElem.

        // Check for a SOAPAction
        String soapActionURI = operation.getSoapActionURI();

        if (soapActionURI != null && soapActionURI.length() > 0) {
            // Add the SOAPAction value as a MIME header
            MimeHeaders mimeHeaders = msg.getMimeHeaders();
            mimeHeaders.setHeader("SOAPAction", "\"" + operation.getSoapActionURI() + "\"");
        }

        // Save changes to the message we just populated
        msg.saveChanges();

        // Get ready for the invocation
        URLEndpoint endpoint = new URLEndpoint(operation.getTargetURL());

        // Show the URL endpoint message in the log
        ByteArrayOutputStream msgStream = new ByteArrayOutputStream();
        msg.writeTo(msgStream);

        log.debug("SOAP Message MeasurementTarget URL: " + endpoint.getURL());
        log.debug("SOAP Request: " + msgStream.toString());

        // Make the call
        SOAPMessage response = connection.call(msg, endpoint);

        // Close the connection, we are done with it
        connection.close();

        // Get the content of the SOAP response
        Source responseContent = response.getSOAPPart().getContent();

        // Convert the SOAP response into a JDOM
        TransformerFactory tFact = TransformerFactory.newInstance();
        Transformer transformer = tFact.newTransformer();

        JDOMResult jdomResult = new JDOMResult();
        transformer.transform(responseContent, jdomResult);

        // Get the document created by the transform operation
        Document responseDoc = jdomResult.getDocument();

        // Send the response to the Log
        String strResponse = XMLSupport.outputString(responseDoc);
        log.debug("SOAP Response from: " + operation.getTargetMethodName() + ": " + strResponse);

        // Set the response as the output message
        operation.setOutputMessageText(strResponse);

        // Return the response generated
        return strResponse;
    }

    catch (Throwable ex) {
        throw new Exception("Error invoking operation", ex);
    }

}

From source file:backend.Weather.java

private SOAPMessage createSOAPRequest() throws Exception {
    MessageFactory messageFactory = MessageFactory.newInstance();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    String serverURI = "http://ws.cdyne.com/";
    SOAPEnvelope envelope = soapPart.getEnvelope();

    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("GetCityWeatherByZIP");
    QName attributeName = new QName("xmlns");
    soapBodyElem.addAttribute(attributeName, "http://ws.cdyne.com/WeatherWS/");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("ZIP");
    soapBodyElem1.addTextNode("02215");
    soapMessage.saveChanges();//ww w.ja  v  a2s .  com
    return soapMessage;

}

From source file:SendSOAPMessage.java

/**
 * send a simple soap message with JAXM API.
 *//*www . j  a  v a2  s.c  o m*/
public void sendMessage(String url) {

    try {
        /**
         * Construct a default SOAP message factory.
         */
        MessageFactory mf = MessageFactory.newInstance();
        /**
         * Create a SOAP message object.
         */
        SOAPMessage soapMessage = mf.createMessage();
        /**
         * Get SOAP part.
         */
        SOAPPart soapPart = soapMessage.getSOAPPart();
        /**
         * Get SOAP envelope.
         */
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        /**
         * Get SOAP body.
         */
        SOAPBody soapBody = soapEnvelope.getBody();

        /**
         * Add child element with the specified name.
         */
        SOAPElement element = soapBody.addChildElement("HelloWorld");

        /**
         * Add text message
         */
        element.addTextNode("Welcome to SunOne Web Services!");

        soapMessage.saveChanges();

        /**
         * Construct a default SOAP connection factory.
         */
        SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();

        /**
         * Get SOAP connection.
         */
        SOAPConnection soapConnection = connectionFactory.createConnection();

        /**
         * Construct endpoint object.
         */
        URLEndpoint endpoint = new URLEndpoint(url);

        /**
         * Send SOAP message.
         */
        SOAPMessage resp = soapConnection.call(soapMessage, endpoint);

        /**
         * Print response to the std output.
         */
        resp.writeTo(System.out);

        /**
         * close the connection
         */
        soapConnection.close();

    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (SOAPException soape) {
        soape.printStackTrace();
    }
}

From source file:com.fortify.bugtracker.tgt.archer.connection.ArcherAuthenticatingRestConnection.java

public Long addValueToValuesList(Long valueListId, String value) {
    LOG.info("[Archer] Adding value '" + value + "' to value list id " + valueListId);
    // Adding items to value lists is not supported via REST API, so we need to revert to SOAP API
    // TODO Simplify this method?
    // TODO Make this method more fail-safe (like checking for the correct response element)?
    Long result = null;/*w w  w.  j a  v  a2  s  . co  m*/
    try {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage message = messageFactory.createMessage();
        SOAPPart soapPart = message.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        SOAPBody body = envelope.getBody();
        SOAPElement bodyElement = body.addChildElement(
                envelope.createName("CreateValuesListValue", "", "http://archer-tech.com/webservices/"));
        bodyElement.addChildElement("sessionToken").addTextNode(tokenProviderRest.getToken());
        bodyElement.addChildElement("valuesListId").addTextNode(valueListId + "");
        bodyElement.addChildElement("valuesListValueName").addTextNode(value);
        message.saveChanges();

        SOAPMessage response = executeRequest(HttpMethod.POST,
                getBaseResource().path("/ws/field.asmx").request()
                        .header("SOAPAction", "\"http://archer-tech.com/webservices/CreateValuesListValue\"")
                        .accept("text/xml"),
                Entity.entity(message, "text/xml"), SOAPMessage.class);
        @SuppressWarnings("unchecked")
        Iterator<Object> it = response.getSOAPBody().getChildElements();
        while (it.hasNext()) {
            Object o = it.next();
            if (o instanceof SOAPElement) {
                result = new Long(((SOAPElement) o).getTextContent());
            }
        }
        System.out.println(response);
    } catch (SOAPException e) {
        throw new RuntimeException("Error executing SOAP request", e);
    }
    return result;
}

From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java

/**
 * Creates the import study response./* ww w  . j ava  2s . co  m*/
 *
 * @return the sOAP message
 * @throws SOAPException the sOAP exception
 */
private SOAPMessage createImportStudyResponse() throws SOAPException {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage response = mf.createMessage();
    SOAPBody body = response.getSOAPBody();
    body.addChildElement(new QName(SERVICE_NS, "ImportStudyResponse"));
    response.saveChanges();
    return response;
}

From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java

/**
 * Creates the export study response.//from  www.  ja  va 2  s .  c o  m
 *
 * @param study the study
 * @return the sOAP message
 * @throws SOAPException the sOAP exception
 * @throws XMLUtilityException the xML utility exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws SAXException the sAX exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
private SOAPMessage createExportStudyResponse(Study study)
        throws SOAPException, XMLUtilityException, ParserConfigurationException, SAXException, IOException {
    MessageFactory mf = MessageFactory.newInstance();
    SOAPMessage response = mf.createMessage();
    SOAPBody body = response.getSOAPBody();
    SOAPElement exportStudyResponse = body.addChildElement(new QName(SERVICE_NS, "ExportStudyResponse"));
    String xml = marshaller.toXML(study);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(XmlMarshaller.class.getResource(C3PR_DOMAIN_XSD_URL)));
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml));
    Element studyEl = (Element) doc.getFirstChild();
    exportStudyResponse.appendChild(body.getOwnerDocument().importNode(studyEl, true));
    response.saveChanges();
    return response;
}

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

@Validated
@Test//  w  w w. j  av  a 2s  .  c  om
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"));
}