FileDocCategorySizeDatePackage
EmptyMessageClient.javaAPI DocExample2619Fri Jul 19 22:26:34 BST 2002ora.jwsnut.chapter3.client

EmptyMessageClient.java

package ora.jwsnut.chapter3.client;

import java.io.IOException;
import java.util.Iterator;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

/**
 * Client that sends an empty SOAP message
 * to a service and prints the reply that it receives.
 */
public class EmptyMessageClient {
    
    public static void main(String[] args) {
        
        if (args.length != 1) {
            usage();
        }

        try {
            // Build the message
            MessageFactory messageFactory = MessageFactory.newInstance();
            SOAPMessage message = messageFactory.createMessage();

            // Print the message.
            printMessage(message);
           
            // Get a SOAPConnection        
            SOAPConnectionFactory connFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection conn = connFactory.createConnection();
            
            // Send the message
            SOAPMessage reply = conn.call(message, args[0]);
            
            // Display the reply
            printMessage(reply);
            
            // Close the connection
            conn.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
    
    public static void usage() {
        System.err.println("Usage: java EmptyMessageClient address");
        System.exit(1);
    }
    
    private static void printMessage(SOAPMessage message) throws IOException, SOAPException {
        if (message != null) {
            // Get the MIME headers and print them
            System.out.println("Headers:");
            if (message.saveRequired()) {
                message.saveChanges();
            }
            MimeHeaders headers = message.getMimeHeaders();
            printHeaders(headers);
            
            // Print the message itself
            System.out.println("\nMessage:");
            message.writeTo(System.out);
            System.out.println();
        }
    }
    
    private static void printHeaders(MimeHeaders headers) {
        printHeaders(headers.getAllHeaders());
    }
    
    private static void printHeaders(Iterator iter) {
        while (iter.hasNext()) {
            MimeHeader header = (MimeHeader)iter.next();
            System.out.println("\t" + header.getName() + ": " + header.getValue());
        }
    }
}