import javax.xml.soap.*;
import java.util.Iterator;
import java.net.URL;
import java.io.*;
      
public class Client {
    
    public static void main(String [] args) {
        try {
            SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
            SOAPConnection connection = soapConnectionFactory.createConnection();
            SOAPFactory soapFactory = SOAPFactory.newInstance();
            
            MessageFactory factory = MessageFactory.newInstance();
            SOAPMessage message = factory.createMessage();
            
            SOAPBody body = message.getSOAPBody();
            Name bodyName = soapFactory.createName("getSurveyCurrentStations", "", "urn:ActiveCurrentStations");
            body.addBodyElement(bodyName);
            
            System.out.print("\nPrinting the message that is being sent: \n\n");
            message.writeTo(System.out);
            System.out.println("\n\n");
            
	    URL endpoint = new URL ("https://opendap.co-ops.nos.noaa.gov/axis/services/SurveyCurrentStations");
            SOAPMessage response = connection.call(message, endpoint);
            connection.close();
            
            /*
            System.out.println("\nPrinting the respone that was recieved: \n\n" );
            response.writeTo(System.out);
            */  
    
            //Uncoment this part if you want the response to be saved locally in an XML file
            /*
            FileOutputStream fout = new FileOutputStream ("SoapResponse.xml");
            response.writeTo(fout);
            fout.close();
            */
       
            //You can also stores the response as a String
            /*
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.writeTo( out );
            String str = out.toString();  
            */
            
            System.out.println("\n\nIterating through the response object to get the values:\n\n");
            SOAPBody responseBody = response.getSOAPBody();
            
            //Checking for errors
            if (responseBody.hasFault()) {
                SOAPFault newFault = responseBody.getFault();
                System.out.println("SAOP FAULT:\n");
                System.out.println("code = " + newFault.getFaultCodeAsName());
                System.out.println("message = " + newFault.getFaultString());
                System.out.println("actor = " + newFault.getFaultActor());
            }else{
                Iterator iterator = responseBody.getChildElements();
                Iterator iterator2, iterator3, iterator4, iterator5;
                
                String tagName = null;
                SOAPElement se = null;
                Name attributeName = null;
                
                if (iterator.hasNext()){
                    se = (SOAPElement)iterator.next();//Stations Tag
                    iterator2 = se.getChildElements();
                    se = (SOAPElement)iterator2.next();//Station Tag
                    iterator2 = se.getChildElements();
                    while (iterator2.hasNext()){
                        se = (SOAPElement)iterator2.next();
                        tagName = se.getElementName().getLocalName();
                        System.out.println("\n\n******************************************************");
                        if(tagName!=null && tagName.equals("station")){
                            //attributes for a station                            
                            attributeName = soapFactory.createName("ID");
                            System.out.println("Station ID:\t" + se.getAttributeValue(attributeName));//Station ID 
                            attributeName = soapFactory.createName("name");
                            System.out.println("Station Name:\t" + se.getAttributeValue(attributeName));//Station Name  
                        
                            // metadata element
                            iterator3 = se.getChildElements();
                            while (iterator3.hasNext()){
                                se = (SOAPElement)iterator3.next();
                                iterator4 = se.getChildElements(); 

                                // Get project
                                se = (SOAPElement)iterator4.next();
                                tagName = se.getElementName().getLocalName();
                                if(tagName!=null && tagName.equals("project")){
                                   System.out.println("Project:\t" + se.getValue());
                                }    
 
                                // Get deployment history info
                                se = (SOAPElement)iterator4.next();
                                tagName = se.getElementName().getLocalName();
                                if(tagName!=null && tagName.equals("deploymentHistory")){
                                   iterator4 = se.getChildElements(); 
				   System.out.println("\n   Latitude\tLongitude\tDeployed\tRecovered");
                                   while (iterator4.hasNext()){
                                      se = (SOAPElement)iterator4.next();
                                      tagName = se.getElementName().getLocalName();
                                      attributeName = soapFactory.createName("lat");
                                      System.out.print("   " + se.getAttributeValue(attributeName)); 
                                      attributeName = soapFactory.createName("long");
                                      System.out.print("\t" + se.getAttributeValue(attributeName)); 
                                      attributeName = soapFactory.createName("deployed");
                                      System.out.print("\t" + formatDate(se.getAttributeValue(attributeName))); 
                                      attributeName = soapFactory.createName("recovered");
                                      System.out.println("\t" + formatDate(se.getAttributeValue(attributeName)));
                                   } 
                                }                                
                            }

                        }               
                    }                 
                }        
            }  
        } catch (SOAPException e) {
            System.err.println("ERROR: ******* " + e.toString());
        } catch (IOException io) {
            System.err.println("ERROR: ******* " + io.toString());
        }
    }


    public static String formatDate(String dateTime){
	String date = "";
        if(dateTime!=null){
	    String s[] = dateTime.split(" ");
            if(s.length>0){
		date = s[0];
            }
        }
        return date; 
    } 
}
/****************************************************
        SAMPLE RUN

>java Client

Sample Output (The entire output is omitted for it is too long)


******************************************************
Station ID:     COI0418
Station Name:   Kennedy Entrance
Project:        Cook Inlet 2004 Current Survey

   Latitude     Longitude       Deployed        Recovered
   59.0658      -151.9823       2004-06-22      2004-08-03


******************************************************
Station ID:     COI0502
Station Name:   The Forelands
Project:        Cook Inlet 2005 Current Survey

   Latitude     Longitude       Deployed        Recovered
   60.7207      -151.5573       2005-05-18      2005-08-16


******************************************************/