001    import java.io.BufferedWriter;
002    import java.io.File;
003    import java.io.FileWriter;
004    import java.io.IOException;
005    import java.io.PrintWriter;
006    import java.sql.Connection;
007    import java.sql.DriverManager;
008    import java.sql.ResultSet;
009    import java.sql.Statement;
010    import java.util.*;
011    
012    import javax.swing.JComboBox;
013    
014    /** 
015     * <h2>DBUpdt15</h2>
016     *
017     * @author Matthew Hough
018     * @version .01, 6/2/07
019     * @assignment.number A19015
020     * @prgm.usage This program contains functions to handle the weather data 
021     *
022     */
023    
024    public class DBUpdt15 implements DBUpdt {
025    
026            // Variables below 
027    
028            /** Describes WHERE the DB is and what TYPE it is */
029            Connection dbBMAC;
030    
031            /** Contains the SQL commands for the database manager */
032            Statement dbCmdText;
033    
034            /** Used to temporarily hold the SQL command */
035            String strSQL;
036    
037            /** Contains the records from the database manager */
038            ResultSet dbRecordset;
039    
040            /** Contains the operating system ODBC name */
041            String dbName = "BMAC";
042    
043            // Methods below 
044    
045            /** 
046             Look for strKey in the field called for by the default key field (strKeyField); 
047             If the record is not found, add a record to the database; 
048             If it is found, just ignore the request. 
049             */
050            public void add(String strKey) throws Exception {
051                    // Check to see if the entries exist 
052                    dbCmdText = dbBMAC.createStatement();
053                    strSQL = "SELECT * FROM station WHERE stationID = '" + strKey + "'";
054                    dbRecordset = dbCmdText.executeQuery(strSQL);
055    
056                    // If they don't exist, update the database with the new records 
057                    if (!dbRecordset.next()) {
058                            // Insert the fields 
059                            strSQL = "INSERT INTO station (stationID) VALUES ('" + strKey
060                            + "')";
061                            dbCmdText.executeUpdate(strSQL);
062                    }// end of if block 
063            }
064    
065            /** 
066             Close the database connection. 
067             */
068            public void close() throws Exception {
069                    dbBMAC.close();
070                    dbCmdText = null;
071            }
072    
073            /** 
074             Returns the contents of the field using a position number 
075             @return String null
076             @see <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSet.html">Java java.sql.ResultSet class</a> 
077             */
078            public String getField(int intFieldNum) throws Exception {
079                    return null;
080            }
081    
082            /** 
083             Returns the contents of the field specified by strFldName. 
084             @see <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSet.html">Java java.sql.ResultSet class</a> 
085             @param strFieldname the 3 digit station ID
086             @return dbRecordset the ResultSet from the database query
087             */
088            public ResultSet getField(String strFieldName) throws Exception {
089                    dbCmdText = dbBMAC.createStatement();
090                    strSQL = "SELECT " + strFieldName + " FROM station ORDER BY stationName";
091                    dbRecordset = dbCmdText.executeQuery(strSQL);
092                    return dbRecordset;
093            }
094    
095            /** 
096             Returns the number of fields in this recordset.  
097             @see <br><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSetMetaData.html">Java java.sql.ResultSetMetaData class</a> 
098             @return intNumOfRecords The number of records
099             */
100            public int getFieldCount() throws Exception {
101                    int intNumOfRecords;
102                    strSQL = "SELECT count(*) AS NumberOfRows FROM station"; 
103                    dbRecordset = dbCmdText.executeQuery(strSQL);
104                    dbRecordset.next();
105                    intNumOfRecords = dbRecordset.getInt(1);
106                    return intNumOfRecords;
107            }
108    
109            /** 
110             Returns the name of the field at position intFldNum.   
111             @see <br><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSetMetaData.html">Java java.sql.ResultSetMetaData class</a> 
112             */
113            public String getFieldName(int intFieldNum) throws Exception {
114                    return null;
115            }
116    
117            /** 
118             Check to see if there are any more records to  
119             be processed in the recordset.  This should only take  
120             one line of code. 
121             @see <br><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/sql/ResultSetMetaData.html">Java java.sql.ResultSetMetaData class</a> 
122             */
123            public boolean moreRecords() throws Exception {
124                    return false;
125            }
126    
127            /**  
128             Accept an ODBC name (that was set up on your computer) along with 
129             the name of the table and the default field name of the key.   
130             <ul> 
131             <li>Store the name of the table in strTable</li> 
132             <li>Store the name of the key field in strKeyField</li> 
133             <li>Create an ODBC Database connection, Return true if successful, false if not</li> 
134             </ul> 
135             */
136            public boolean open(String strConn, String strTable, String strKeyField)
137            throws Exception {
138                    // Generic SUN driver for databases 
139                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
140                    dbBMAC = DriverManager.getConnection("jdbc:odbc:" + strConn);
141    
142                    // if the connection was successfull return true, else return false 
143                    if (dbBMAC == null) {
144                            return true;
145                    } else {
146                            return false;
147                    }
148            }
149    
150            /** 
151             Executes an SQL query on the database.
152             @param strSql A string containing a sql query statement
153             @return dbRecordSet The ResultSet of the database query 
154             */
155            public ResultSet query(String strSQL) throws Exception {
156                    dbCmdText = dbBMAC.createStatement();
157                    dbRecordset = dbCmdText.executeQuery(strSQL);
158                    return dbRecordset;
159            }
160    
161            /** 
162             Using strKey, look up the record, and once found,  
163             update strFieldName field with strContent.  
164             <br> 
165             Note: 
166             <br>  
167             You should only update one field at a time. 
168             If you have multiple fields to update in a  
169             record, you need to call this function  
170             multiple times. 
171             */
172            public void setField(String strContent, String strFieldName, String strKey)
173            throws Exception {
174                    strSQL = "UPDATE station SET " + strFieldName + "='" + strContent
175                    + "'WHERE stationID='" + strKey + "'";
176                    dbCmdText.executeUpdate(strSQL);
177            }
178    
179            /** 
180             This method deletes all of the fields in the database
181             @param strTableName The name of the table 
182             */
183            public void deleteAll(String strTableName) throws Exception {
184    
185                    /* Execute the SQL delete statements */
186                    dbCmdText = dbBMAC.createStatement();
187                    strSQL = "DELETE * FROM " + strTableName + ";";
188                    dbCmdText.executeUpdate(strSQL);
189            }
190    
191            /** This method downloads all of the data from the website and saves it in a text file */
192            public void loadWindsAloft(){
193    
194                    /* Declare a new Inet object */
195                    Inet windsAloft = new Inet();
196    
197                    /* Download the data and save it to a string */
198                    String strWindsData = windsAloft.getData(windsAloft.getURL("http://aviationweather.gov/products/nws/winds/?area=all&fint=06&lvl=lo")+ " ");
199    
200                    /* Save the string to a text file */
201                    windsAloft.saveData("FBIN.txt", strWindsData);
202    
203                    /* Declare a scanner object so that you can open a text file. */
204                    Scanner fileScan;
205    
206                    /* Instantiate a new DNUpdt15 object and open the database connection */
207                    DBUpdt15 loadWinds = new DBUpdt15(); // Instatiate new DBUpdt object
208                    try {
209                            loadWinds.open("BMAC", "", ""); //open the database connection
210                    } // end of try block
211                    catch (Exception e) {
212                            System.out.println("Problem opening the database.");
213                    } // end of catch block
214    
215                    /* Open the file and read the first record. */
216                    try {
217                            fileScan = new Scanner(new File("FBIN.txt"));
218                            /* Read a couple of lines off the top of the file and discard them. */
219                            fileScan.nextLine();  // 000
220                            fileScan.nextLine();  // FDUW02 KWBC 231410
221                            fileScan.nextLine();  // DATA BASED ON 231200Z
222                            fileScan.nextLine();  // VALID 231800Z 
223                            fileScan.nextLine();  // FT  3000    6000
224                            fileScan.nextLine();
225                            fileScan.nextLine();
226                            fileScan.nextLine();
227    
228                            /* Using a while loop, read each line. */
229                            while (fileScan.hasNext()){
230    
231                                    /* Save each line in a variable */
232                                    String strStaWeather = fileScan.nextLine();
233    
234                                    /* Instatiate a new NWSFB06 object to extract the station ID */
235                                    NWSFB06 strGetStaID = new NWSFB06(strStaWeather);
236    
237                                    /* Using the NWSFB06 object, extract the station ID from each line */
238                                    String strStaID = strGetStaID.getStationID();
239    
240                                    /* Save the string to the WINDSALOFT database field */
241                                    try {
242                                            loadWinds.add(strStaID);
243                                            loadWinds.setField(strStaWeather, "windsaloft", strStaID);
244                                    }
245                                    catch (Exception e) {
246                                            System.out.println("Problem saving to the database.");
247                                    }
248    
249                            } //end of while block
250    
251                            /* Close the database */
252                            try {
253                                    loadWinds.close();
254                            } // end of try block
255                            catch (Exception e) {
256                                    System.out.println("Problem closing the database.");
257                            } // end of catch block
258    
259                    } //end of try block
260                    catch (IOException ex){
261                            System.out.println("Problem looping through the text file.");
262                    } //end of catch block
263    
264            }
265    
266            /**
267             * This method reads the text file and loads the weather data
268             */
269            public void getStationDetails() {
270                    /* Declare a scanner object so that you can open a text file. */
271                    Scanner fileScan;
272    
273                    /* Open the file and read the first record. */
274                    try {
275                            fileScan = new Scanner(new File("FBIN.txt"));
276                            /* Read a couple of lines off the top of the file and discard them. */
277                            fileScan.nextLine();  // 000
278                            fileScan.nextLine();  // FDUW02 KWBC 231410
279                            fileScan.nextLine();  // DATA BASED ON 231200Z
280                            fileScan.nextLine();  // VALID 231800Z 
281                            fileScan.nextLine();  // FT  3000    6000
282                            fileScan.nextLine();
283                            fileScan.nextLine();
284                            fileScan.nextLine();
285    
286                            /* Using a while loop, read each line. */
287                            while (fileScan.hasNext()){
288    
289                                    /* Save each line in a variable */
290                                    String strStaWeather = fileScan.nextLine();
291    
292                                    /* Instatiate a new NWSFB06 object */
293                                    NWSFB06 strGetStaID = new NWSFB06(strStaWeather);
294    
295                                    /* Using the NWSFB06 object, extract the station ID from each line */
296                                    String strStaID = strGetStaID.getStationID();
297    
298                                    /* Get the surface weather data */
299                                    String strSurWea = strGetStaID.getAltWea("03");
300    
301                                    /* Start a loop to check to see if the stations have surface weather */
302                                    if (strSurWea.equals("    ")) {
303                                            //Do nothing if the surface weather is blank
304                                    }
305                                    else {
306                                            /* Using the station ID, format an XML URL */
307                                            String strXMLURL = "http://www.nws.noaa.gov/data/current_obs/K" + strStaID + ".xml";
308    
309                                            /* Instantiate the XMLRead object */
310                                            XMLRead xmlSta = new XMLRead();
311    
312                                            try
313                                            {
314                                                    /* Load the XML page */
315                                                    xmlSta.loadPage(strXMLURL);
316    
317                                                    /* Instantiate a new DBUpdt15 object to open the database */
318                                                    DBUpdt15 XMLDB = new DBUpdt15();
319    
320                                                    try {
321                                                            XMLDB.open("BMAC", "", ""); //open the database connection
322                                                            XMLDB.query("SELECT * FROM station"); //query the database
323    
324                                                            /* extract the XML page data and enter into the database */
325                                                            XMLDB.setField((xmlSta.getField("location")), "stationName", strStaID);
326                                                            XMLDB.setField((xmlSta.getField("latitude")), "latitude", strStaID);
327                                                            XMLDB.setField((xmlSta.getField("longitude")), "longitude", strStaID);
328                                                            XMLDB.setField((xmlSta.getField("temp_f")), "temperature", strStaID);
329                                                            XMLDB.setField((xmlSta.getField("relative_humidity")), "humidity", strStaID);
330                                                            XMLDB.setField((xmlSta.getField("wind_dir")), "windspeed", strStaID);
331                                                            XMLDB.setField((xmlSta.getField("wind_mph")), "winddirection", strStaID);
332                                                            XMLDB.setField((xmlSta.getField("pressure_in")), "pressure", strStaID);
333                                                            XMLDB.setField((xmlSta.getField("dewpoint_f")), "dewpoint", strStaID); 
334    
335                                                            /* Close the database */
336                                                            XMLDB.close();
337                                                    } //end of try block
338                                                    catch (Exception e) {
339                                                            System.out.println(e);
340                                                    } //end of catch block
341                                            }//end of try loop
342                                            catch(Exception e)
343                                            {
344                                                    System.out.println("XML Page not found");
345                                            } //end of catch loop
346                                    } //end of if-else loop
347                            } //end of while loop
348                    } //end of try block
349                    catch (Exception e) {
350                            System.out.println(e);
351                    } //end of catch block
352    
353            }
354    
355            
356    
357            /** 
358             Send a string to the console (System.out.print)- this should be used throughtout  
359             your program to indicate progress and display variable contents - see DemoMain11 for code. 
360             */
361            public void status(String strVar) {
362                    System.out.println("Main: " + strVar);
363            }
364    
365    }