Adapter method used to convert any type of Source to a String for SOAP - Java javax.xml.soap

Java examples for javax.xml.soap:SOAPMessage

Description

Adapter method used to convert any type of Source to a String for SOAP

Demo Code

/*/*from   ww w  .j  av  a2s. co  m*/
 * 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.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;

import java.io.StringWriter;

public class Main {
    /**
     * Adapter method used to convert any type of Source to a String
     * 
     * @param input
     * @return
     */
    public static String toString(Source input) {

        if (input == null)
            return null;

        StringWriter writer = new StringWriter();
        Transformer trasformer;
        try {
            trasformer = TransformerFactory.newInstance().newTransformer();
            Result result = new StreamResult(writer);
            trasformer.transform(input, result);
        } catch (Exception e) {
            return null;
        }

        return writer.getBuffer().toString();
    }

    /**
     * Adapter method used to convert any type of SOAPMessage to a String
     * 
     * @param input
     * @return
     */
    public static String toString(SOAPMessage input) {

        if (input == null)
            return null;

        Source result = null;
        try {
            result = input.getSOAPPart().getContent();
        } catch (SOAPException e) {
            e.printStackTrace();
        }

        return toString(result);
    }
}

Related Tutorials