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("getActiveStationsV2", "", "urn:ActiveStations");
            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/ActiveStations");
            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******************************************************");
                        System.out.println("Station Name\t ID\t\t Latitude\t Longitude\t State\t Date\t SHEF ID\t Deployment Designation");
                        if(tagName!=null && tagName.equals("stationV2")){
                            //attributes for a station
                            attributeName = soapFactory.createName("name");
                            System.out.print(se.getAttributeValue(attributeName));//Station Name  
                            attributeName = soapFactory.createName("ID");
                            System.out.print("\t" + se.getAttributeValue(attributeName));//Station ID 
                            
                            iterator3 = se.getChildElements();
                            se = (SOAPElement)iterator3.next();//Metadata Tag
                            iterator4 = se.getChildElements();
                            se = (SOAPElement)iterator4.next();//Location Tag 
                            iterator5 = se.getChildElements();                            
                            
                            while (iterator5.hasNext()){
                                se = (SOAPElement)iterator5.next(); 
                                tagName = se.getElementName().getLocalName();
                                if(tagName!=null){
                                    //The name of the tag in this case is 'lat'
                                    if(tagName.equals("lat")){
                                        System.out.print("\t\t" + se.getValue());//Latitude
                                    }else if(tagName.equals("long")){
                                        System.out.print("\t" + se.getValue()); //longitude
                                    }else if(tagName.equals("state")){
                                        System.out.print("\t" + se.getValue()); //State
                                    }                                   
                                }                            
                            }

                            while (iterator4.hasNext()){
                                se = (SOAPElement)iterator4.next(); 
                                tagName = se.getElementName().getLocalName();
                                if(tagName!=null){
                                    if(tagName.equals("date_established")){
                                        System.out.print("\t\t" + se.getValue());//Established Date
                                    }else if(tagName.equals("shef_id")){
                                        System.out.print("\t" + se.getValue()); //SHEF ID
                                    }else if(tagName.equals("deployment_designation")){
                                        System.out.print("\t" + se.getValue()); //Deployment Designation
                                    }                                   
                                }                            
                            }

                            System.out.println("\n\nParameters\t DCP\t SensorId\t Status");
                            while (iterator3.hasNext()){
                                se = (SOAPElement)iterator3.next();
                                attributeName = soapFactory.createName("name");
                                System.out.print(se.getAttributeValue(attributeName));
                                attributeName = soapFactory.createName("DCP");
                                System.out.print("\t" + se.getAttributeValue(attributeName));
                                attributeName = soapFactory.createName("sensorID");
                                System.out.print("\t" + se.getAttributeValue(attributeName));
                                attributeName = soapFactory.createName("status");
                                System.out.println("\t" + se.getAttributeValue(attributeName));  
                            }  
                        }               
                    }                 
                }        
            }  
        } catch (SOAPException e) {
            System.err.println("ERROR: ******* " + e.toString());
        } catch (IOException io) {
            System.err.println("ERROR: ******* " + io.toString());
        }
    }
}
/****************************************************
        SAMPLE RUN

>java Client

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

******************************************************
Station Name       ID              Latitude        Longitude       State     Date	 SHEF ID	 Deployment Designation
Nikiski            9455760         60.6833	  -151.3980	 AK	  1971-05-21   	NKTA2	       NWLON, NWLORTS

Parameters       DCP     SensorId    Status
Winds            1       C1          1
Air Temp         1       D1          1
Water Temp       1       E1          1
Air Pressure     1       F1          1
Water Level      1       N1          1


******************************************************
Station Name     ID              Latitude           Longitude       State      Date	 SHEF ID	 Deployment Designation
Anchorage	9455920		61.2383	          -149.8900	    AK	   1964-04-24   ANTA2	      NWLORTS

Parameters       DCP     SensorId    Status
Winds            1       C1          1
Air Temp         1       D1          1
Water Temp       1       E1          1
Air Pressure     1       F1          1
Water Level      1       N1          1

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