Method used to convert Strings to SOAPMessages - Java javax.xml.soap

Java examples for javax.xml.soap:SOAPMessage

Description

Method used to convert Strings to SOAPMessages

Demo Code

/*/*from  w  w w  . j  av a2  s  .com*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
//package com.java2s;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPConstants;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

import javax.xml.transform.Source;

import javax.xml.transform.stream.StreamSource;

import java.io.StringReader;

public class Main {

    public static final String SOAP11_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope";

    /**
     * Method used to convert Strings to SOAPMessages
     * 
     * @param msgString
     * @return
     */
    public static SOAPMessage toSOAPMessage(String msgString) {

        if (msgString == null)
            return null;

        SOAPMessage message = null;
        try {
            MessageFactory factory = null;

            // Force the usage of specific MesasgeFactories
            if (msgString.indexOf(SOAP11_NAMESPACE) >= 0) {
                factory = MessageFactory
                        .newInstance(SOAPConstants.SOAP_1_1_PROTOCOL);
            } else {
                factory = MessageFactory
                        .newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
            }
            message = factory.createMessage();
            message.getSOAPPart().setContent(
                    (Source) new StreamSource(new StringReader(msgString)));
            message.saveChanges();
        } catch (SOAPException e) {
            System.out.println("toSOAPMessage Exception encountered: " + e);
            e.printStackTrace();
        }
        return message;
    }
}

Related Tutorials