Example usage for javax.xml.soap SOAPMessage getSOAPBody

List of usage examples for javax.xml.soap SOAPMessage getSOAPBody

Introduction

In this page you can find the example usage for javax.xml.soap SOAPMessage getSOAPBody.

Prototype

public SOAPBody getSOAPBody() throws SOAPException 

Source Link

Document

Gets the SOAP Body contained in this SOAPMessage object.

Usage

From source file:ee.ria.xroad.common.message.SoapUtils.java

/**
 * Converts a SOAP request to SOAP response, by adding "Response" suffix
 * to the service name in the body.//from   w ww.j  a  v a  2  s.  co m
 * @param request SOAP request message to be converted
 * @param callback function to call when the response SOAP object has been created
 * @return the response SoapMessageImpl
 * @throws Exception if errors occur during response message creation
 */
public static SoapMessageImpl toResponse(SoapMessageImpl request, SOAPCallback callback) throws Exception {
    String charset = request.getCharset();

    SOAPMessage soap = createSOAPMessage(new ByteArrayInputStream(request.getBytes()), charset);

    List<SOAPElement> bodyChildren = getChildElements(soap.getSOAPBody());
    if (bodyChildren.size() == 0) {
        return null;
    }

    QName requestElementQName = bodyChildren.get(0).getElementQName();
    String serviceCode = getServiceCode(soap, requestElementQName);

    QName newName = new QName(requestElementQName.getNamespaceURI(), serviceCode + SOAP_SUFFIX_RESPONSE,
            requestElementQName.getPrefix());
    bodyChildren.get(0).setElementQName(newName);

    if (callback != null) {
        callback.call(soap);
    }

    byte[] xml = getBytes(soap);
    return (SoapMessageImpl) new SoapParserImpl().parseMessage(xml, soap, charset, request.getContentType());
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.WsStream.java

/**
 * Performs JAX-WS service call using SOAP API.
 *
 * @param url//  w ww . j  a  v  a 2 s  .  com
 *            JAX-WS service URL
 * @param soapRequestData
 *            JAX-WS service request data: headers and body XML string
 * @return service response string
 * @throws Exception
 *             if exception occurs while performing JAX-WS service call
 */
protected static String callWebService(String url, String soapRequestData) throws Exception {
    if (StringUtils.isEmpty(url)) {
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME,
                "WsStream.cant.execute.request"), url);
        return null;
    }

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    Map<String, String> headers = new HashMap<>();
    // separate SOAP message header values from request body XML
    BufferedReader br = new BufferedReader(new StringReader(soapRequestData));
    StringBuilder sb = new StringBuilder();
    try {
        String line;
        while ((line = br.readLine()) != null) {
            if (line.trim().startsWith("<")) { // NON-NLS
                sb.append(line).append(Utils.NEW_LINE);
            } else {
                int bi = line.indexOf(':'); // NON-NLS
                if (bi >= 0) {
                    String hKey = line.substring(0, bi).trim();
                    String hValue = line.substring(bi + 1).trim();
                    headers.put(hKey, hValue);
                } else {
                    sb.append(line).append(Utils.NEW_LINE);
                }
            }
        }
    } finally {
        Utils.close(br);
    }

    soapRequestData = sb.toString();

    LOGGER.log(OpLevel.DEBUG,
            StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME, "WsStream.invoking.request"),
            url, soapRequestData);

    // Create Request body XML document
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(soapRequestData)));

    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Create SOAP message and set request XML as body
    SOAPMessage soapRequest = MessageFactory.newInstance().createMessage();

    // SOAPPart part = soapRequest.getSOAPPart();
    // SOAPEnvelope envelope = part.getEnvelope();
    // envelope.addNamespaceDeclaration();

    if (!headers.isEmpty()) {
        MimeHeaders mimeHeaders = soapRequest.getMimeHeaders();

        for (Map.Entry<String, String> e : headers.entrySet()) {
            mimeHeaders.addHeader(e.getKey(), e.getValue());
        }
    }

    SOAPBody body = soapRequest.getSOAPBody();
    body.addDocument(doc);
    soapRequest.saveChanges();

    // Send SOAP Message to SOAP Server
    SOAPMessage soapResponse = soapConnection.call(soapRequest, url);

    ByteArrayOutputStream soapResponseBaos = new ByteArrayOutputStream();
    soapResponse.writeTo(soapResponseBaos);
    String soapResponseXml = soapResponseBaos.toString();

    return soapResponseXml;
}

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);//from  ww w .  ja va2 s  . co m
    fContent = b.toString();
}

From source file:test.integ.be.fedict.hsm.ws.WSS4JTest.java

@Test
public void testSecurity() throws Exception {
    QName serviceName = new QName("http://www.example.com/test", "TestService");
    Service service = Service.create(serviceName);
    QName portName = new QName("http://www.example.com/test", "TestPort");
    String endpointAddress = this.baseURL + "test";
    LOG.debug("endpoint address: " + endpointAddress);
    service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
    Dispatch<SOAPMessage> dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE);
    BindingProvider bindingProvider = (BindingProvider) dispatch;
    SOAPBinding soapBinding = (SOAPBinding) bindingProvider.getBinding();
    List handlerChain = soapBinding.getHandlerChain();
    handlerChain.add(new WSS4JTestSOAPHandler());
    soapBinding.setHandlerChain(handlerChain);
    MessageFactory messageFactory = soapBinding.getMessageFactory();
    SOAPMessage soapMessage = messageFactory.createMessage();
    SOAPBody soapBody = soapMessage.getSOAPBody();
    QName payloadName = new QName("http://www.example.com/test", "Payload", "prefix");
    SOAPBodyElement soapBodyElement = soapBody.addBodyElement(payloadName);
    soapBodyElement.addTextNode("hello world");

    SOAPMessage replyMessage = dispatch.invoke(soapMessage);
}

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  ww w.  ja  v  a2  s . co  m

    xmlBase64ZipFile.setTextContent(content.toString());

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

From source file:com.hiperium.integration.access.control.SoapSessionHandler.java

/**
 * /*from  w  w  w .  j  av  a2  s  .  c o  m*/
 * @param msg
 * @param reason
 */
private void generateFault(SOAPMessage msg, String reason) {
    try {
        SOAPBody body = msg.getSOAPBody();
        SOAPFault fault = body.addFault();
        fault.setFaultString(reason);
        throw new SOAPFaultException(fault);
    } catch (SOAPException e) {
        LOGGER.error(e.getMessage(), e);
    }
}

From source file:com.polivoto.networking.SoapClient.java

public String start() throws SOAPException, IOException {
    String resp = "NaN";
    // Create SOAP Connection
    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    // Send SOAP Message to SOAP Server
    String url = "http://" + host
            + "/FistVotingServiceBank/services/ServAvailableVoteProcesses.ServAvailableVoteProcessesHttpSoap11Endpoint/";
    SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

    SOAPBody body = soapResponse.getSOAPBody();
    java.util.Iterator updates = body.getChildElements();
    // El siguiente ciclo funciona slo porque el cuerpo contiene 
    // un elemento y ste a suvez nicamente contiene un elemento.
    while (updates.hasNext()) {
        System.out.println();//from w  ww  .  j a  v a 2s  . com
        // The listing and its ID
        SOAPElement update = (SOAPElement) updates.next();
        java.util.Iterator i = update.getChildElements();
        while (i.hasNext()) {
            SOAPElement e = (SOAPElement) i.next();
            String name = e.getLocalName();
            String value = e.getValue();
            resp = value; // Am I getting last response?
            System.out.println(name + ": " + value);
        }
    }
    soapConnection.close();
    return resp;
}

From source file:com.github.thesmartenergy.cnr.SmartChargingProvider.java

private SOAPMessage createSoapMessage(GetChargingPlans value) throws PEPException {
    try {// w w w.  j  a va  2 s .  co  m
        JAXBContext jaxbContext = JAXBContext.newInstance(GetChargingPlans.class);
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        jaxbContext.createMarshaller().marshal(value, document);

        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        soapMessage.getSOAPBody().addDocument(document);
        Name headername = soapMessage.getSOAPPart().getEnvelope().createName("Action", "",
                "http://schemas.microsoft.com/ws/2005/05/addressing/none/");
        SOAPHeaderElement soapAction = soapMessage.getSOAPHeader().addHeaderElement(headername);
        soapAction.setMustUnderstand(true);
        soapAction.setTextContent("http://tempuri.org/ISmartCharging/GetChargingPlans");
        return soapMessage;
    } catch (DOMException | JAXBException | ParserConfigurationException | SOAPException ex) {
        throw new PEPException(ex);
    }
}

From source file:de.drv.dsrv.spoc.web.webservice.spring.SpocMessageDispatcherServlet.java

private void createExtraErrorAndWriteResponse(final HttpServletResponse httpServletResponse,
        final String errorText)
        throws SOAPException, JAXBException, DatatypeConfigurationException, IOException {

    final MessageFactory factory = MessageFactory.newInstance();
    final SOAPMessage message = factory.createMessage();
    final SOAPBody body = message.getSOAPBody();

    final SOAPFault fault = body.addFault();
    final QName faultName = new QName(SOAPConstants.URI_NS_SOAP_ENVELOPE, FaultCode.CLIENT.toString());
    fault.setFaultCode(faultName);//ww w . java2 s . c  o m
    fault.setFaultString(this.soapFaultString);

    final Detail detail = fault.addDetail();

    final ExtraJaxbMarshaller extraJaxbMarshaller = new ExtraJaxbMarshaller();
    final ExtraErrorReasonType reason = ExtraErrorReasonType.INVALID_REQUEST;
    final ExtraErrorType extraError = ExtraHelper.generateError(reason, this.extraErrorCode, errorText);
    extraJaxbMarshaller.marshalExtraError(extraError, detail);

    // Schreibt die SOAPMessage in einen String.
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    message.writeTo(out);
    // Das Encoding, in dem sich die Message rausschreibt, kann man als
    // Property abfragen.
    final Object encodingProperty = message.getProperty(SOAPMessage.CHARACTER_SET_ENCODING);
    String soapMessageEncoding = "UTF-8";
    if (encodingProperty != null) {
        soapMessageEncoding = encodingProperty.toString();
    }
    final String errorXml = out.toString(soapMessageEncoding);

    httpServletResponse.setStatus(HttpServletResponse.SC_OK);
    httpServletResponse.setContentType("text/xml");
    httpServletResponse.getWriter().write(errorXml);
    httpServletResponse.getWriter().flush();
    httpServletResponse.getWriter().close();
}

From source file:de.drv.dsrv.spoc.web.webservice.jax.ExtraSchemaValidationHandler.java

private SOAPBody getSoapBody(final SOAPMessageContext context) {
    SOAPBody soapBody = null;//w w  w . j a v  a  2  s .co  m
    try {
        final SOAPMessage soapMessage = context.getMessage();
        soapBody = soapMessage.getSOAPBody();
    } catch (final Exception e) {
        LOG.error("Exception beim Auslesen des SOAP-Bodys.", e);
    }
    return soapBody;
}