Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2004 University of New Mexico and the 
4
 *                  Regents of the University of California
5
 *
6
 *   '$Author: costa $'
7
 *     '$Date: 2005-01-13 16:49:36 -0800 (Thu, 13 Jan 2005) $'
8
 * '$Revision: 2367 $'
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 2 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program; if not, write to the Free Software
22
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23
 */
24

    
25
package edu.ucsb.nceas.metacat.harvesterClient;
26

    
27
import com.oreilly.servlet.ParameterParser;
28
import edu.ucsb.nceas.utilities.Options;
29
import java.io.File;
30
import java.io.InputStream;
31
import java.io.IOException;
32
import java.io.PrintWriter;
33
import java.sql.Connection;
34
import java.sql.DriverManager;
35
import java.sql.ResultSet;
36
import java.sql.SQLException;
37
import java.sql.SQLWarning;
38
import java.sql.Statement;
39
import java.text.ParseException;
40
import java.text.SimpleDateFormat;
41
import java.util.Date;
42
import java.util.Enumeration;
43
import javax.servlet.ServletConfig;
44
import javax.servlet.ServletContext;
45
import javax.servlet.ServletException;
46
import javax.servlet.http.HttpServlet;
47
import javax.servlet.http.HttpServletRequest;
48
import javax.servlet.http.HttpServletResponse;
49
import javax.servlet.http.HttpSession;
50

    
51
/**
52
 * HarvesterRegistration is a servlet that implements harvester registration.
53
 * The servlet reads parameters that were entered in a harvester registration
54
 * form, checks the validity of the values, stores the values in the database
55
 * by either inserting, updating, or removing a record in the
56
 * HARVEST_SITE_SCHEDULE table.
57
 * 
58
 * @author    costa
59
 * 
60
 */
61
public class HarvesterRegistration extends HttpServlet {
62

    
63
  /*
64
   * Class fields
65
   */
66
  private static final String CONFIG_DIR = "WEB-INF";
67
  private static final String CONFIG_NAME = "metacat.properties";
68
   
69
  /*
70
   * Object fields
71
   */
72
  private ServletConfig config = null;
73
  private ServletContext context = null;
74
  private String defaultDB;     // database connection, from properties file
75
  final private long millisecondsPerDay = (1000 * 60 * 60 * 24);
76
  private String password;      // database password, from properties file
77
  private String user;          // database user, from properties file
78
   
79

    
80
  /*
81
   * Object methods
82
   */
83
   
84
   
85
  /**
86
   * Checks validity of user input values.
87
   * 
88
   * @param out             the PrintWriter output object
89
   * @param documentListURL the Harvest List URL specified by the user
90
   * @param updateFrequency the Harvest Frequency specified by the user
91
   * @return validValues    true if all values are valid, else false
92
   */
93
  private boolean checkValues(PrintWriter out,
94
                              String documentListURL,
95
                              int updateFrequency
96
                             ) {
97
    boolean validValues = true;
98

    
99
    // Check validity of the Harvest List URL field    
100
    if (documentListURL.equals("")) {
101
      out.println(
102
              "A value must be specified in the Harvest List URL field"
103
                 );
104
      validValues = false;
105
    }
106

    
107
    // Check validity of the Harvest Frequency field    
108
    if ((updateFrequency < 0) || (updateFrequency > 99)) {
109
      out.println("Harvest Frequency should be in the range 1 to 99");
110
      validValues = false;
111
    }
112
    
113
    return validValues;
114
  }
115
  
116
  
117
  /**
118
   * Closes the database connection.
119
   * 
120
   * @param conn  The connection.
121
   */
122
  private void closeConnection(Connection conn) {
123
    try {
124
      if (conn != null) {
125
        conn.close();
126
      }
127
    }
128
    catch (SQLException e) {
129
      // ignored
130
    }
131
  }
132

    
133

    
134
  /**
135
   * Inserts a record to the HARVEST_SITE_SCHEDULE table.
136
   * 
137
   * @param out             the PrintWriter output object
138
   * @param conn            the Connection
139
   * @param siteScheduleID  the primary key for the table
140
   * @param contactEmail    contact email address of the site user
141
   * @param documentListURL the URL of the harvest list at the site
142
   * @param ldapDN          the site user's LDAP DN
143
   * @param ldapPwd         the site user's LDAP password
144
   * @param unit            the update frequency unit, e.g. "days", "weeks"
145
   * @param updateFrequency the update frequency, an integer in range 1-99
146
   */
147
  private void dbInsert(PrintWriter out,
148
                        Connection conn,
149
                        int siteScheduleID,
150
                        String contactEmail,
151
                        String documentListURL,
152
                        String ldapDN,
153
                        String ldapPwd,
154
                        String unit,
155
                        int updateFrequency
156
                       ) {
157
    String dateNextHarvest;
158
    long delta;
159
    Date dnh;                          // Date of next harvest
160
    Date now;                          // Today's date
161
    String query;
162
		Statement stmt;
163
    long timeNextHarvest;
164
    SimpleDateFormat writeFormat = new SimpleDateFormat("dd-MMM-yyyy");
165
    
166
    // Calculate the value of delta, the number of milliseconds between the
167
    // last harvest date and the next harvest date.
168
    delta = updateFrequency * millisecondsPerDay;
169
    
170
    if (unit.equals("weeks")) {
171
      delta *= 7;
172
    }
173
    else if (unit.equals("months")) {
174
      delta *= 30;
175
    }
176

    
177
    now = new Date();
178
    timeNextHarvest = now.getTime();
179
    dnh = new Date(timeNextHarvest);
180
    dateNextHarvest = writeFormat.format(dnh);
181
	
182
		try {
183
			stmt = conn.createStatement();							
184
			query = "insert into HARVEST_SITE_SCHEDULE " +
185
      "(SITE_SCHEDULE_ID, CONTACT_EMAIL, DOCUMENTLISTURL, LDAPDN, LDAPPWD, " +
186
      "UNIT, UPDATEFREQUENCY, DATENEXTHARVEST) " +
187
      "values(" + siteScheduleID + "," +
188
                  quoteString(contactEmail) + "," +
189
                  quoteString(documentListURL) + "," +
190
                  quoteString(ldapDN) + "," +
191
                  quoteString(ldapPwd) + "," +
192
                  quoteString(unit) + "," +
193
                  updateFrequency + "," +
194
                  quoteString(dateNextHarvest) + ")";
195
                  
196
      System.out.println(query);
197
      stmt.executeUpdate(query);
198
			stmt.close();
199
      reportResults(out, ldapDN, contactEmail, documentListURL, updateFrequency,
200
                    unit, dateNextHarvest);
201
		}
202
    catch(SQLException e) {
203
			System.out.println("SQLException: " + e.getMessage());
204
		}
205
   }
206
   
207

    
208
  /**
209
   * Removes a record from the HARVEST_SITE_SCHEDULE table.
210
   * 
211
   * @param out            the PrintWriter output object
212
   * @param conn           the Connection
213
   * @param siteScheduleID the primary key for the table
214
   * @param ldapDN          the site user's LDAP DN
215
   */
216
  private void dbRemove(PrintWriter out,
217
                        Connection conn,
218
                        int siteScheduleID,
219
                        String ldapDN
220
                       ) {
221
    String query = "DELETE FROM HARVEST_SITE_SCHEDULE WHERE " +
222
                   "SITE_SCHEDULE_ID=" + siteScheduleID;
223
    int nRecords = 0;
224
		Statement stmt;
225
     
226
		try {
227
			stmt = conn.createStatement();
228
      System.out.println(query);
229
      nRecords = stmt.executeUpdate(query);
230
      stmt.close();
231
      System.out.println(nRecords + " record(s) removed.");
232
      
233
      if (nRecords > 0) {
234
        out.println("Harvester registration removed for user " + ldapDN);
235
      }
236
      else {
237
        out.println("A problem was encountered removing registration for user " 
238
                    + ldapDN);
239
      }
240
		}
241
    catch(SQLException e) {
242
			System.out.println("SQLException: " + e.getMessage());
243
		}
244
   }
245
   
246

    
247
  /**
248
   * Updates a record in the HARVEST_SITE_SCHEDULE table.
249
   * 
250
   * @param out             the PrintWriter output object
251
   * @param conn            the Connection
252
   * @param siteScheduleID  the primary key for the table
253
   * @param contactEmail    contact email address of the site user
254
   * @param documentListURL the URL of the harvest list at the site
255
   * @param ldapDN          the site user's LDAP DN
256
   * @param ldapPwd         the site user's LDAP password
257
   * @param unit            the update frequency unit, e.g. "days", "weeks"
258
   * @param updateFrequency the update frequency, an integer in range 1-99
259
   * @param dateLastHarvest the date of last harvest, 
260
   *                        e.g. "2004-04-30 00:00:00.0" or ""
261
   */
262
   private void dbUpdate(PrintWriter out,
263
                         Connection conn,
264
                         int siteScheduleID,
265
                         String contactEmail,
266
                         String documentListURL,
267
                         String ldapDN,
268
                         String ldapPwd,
269
                         String unit,
270
                         int updateFrequency,
271
                         String dateLastHarvest
272
                        ) {
273
    String dateNextHarvest;
274
    long delta;
275
    Date dlh;                          // Date of last harvest
276
    Date dnh;                          // Date of next harvest
277
    Date now = new Date();             // Today's date
278
//    SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
279
    SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd");
280
    SimpleDateFormat writeFormat = new SimpleDateFormat("dd-MMM-yyyy");
281
		Statement stmt;
282
    long timeLastHarvest;
283
    long timeNextHarvest;
284
    long timeNow = now.getTime();
285
    
286
    // Calculate the value of delta, the number of milliseconds between the
287
    // last harvest date and the next harvest date.
288
    delta = updateFrequency * millisecondsPerDay;
289
    
290
    if (unit.equals("weeks")) {
291
      delta *= 7;
292
    }
293
    else if (unit.equals("months")) {
294
      delta *= 30;
295
    }
296

    
297
    if (dateLastHarvest.equals("")) {
298
      timeNextHarvest = timeNow;
299
    }
300
    else {
301
      try {
302
        dlh = readFormat.parse(dateLastHarvest);
303
        timeLastHarvest = dlh.getTime();
304
        timeNextHarvest = timeLastHarvest + delta;
305
        timeNextHarvest = Math.max(timeNextHarvest, timeNow);
306
      }
307
      catch (ParseException e) {
308
        System.out.println("Error parsing date: " + dateLastHarvest +
309
                           " " + e.getMessage());
310
        timeNextHarvest = timeNow;
311
      }
312
    }
313
    
314
    dnh = new Date(timeNextHarvest);
315
    dateNextHarvest = writeFormat.format(dnh);
316
	
317
		try {
318
			stmt = conn.createStatement();							
319
			stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET CONTACT_EMAIL=" +
320
                         quoteString(contactEmail) +
321
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
322
			stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET DOCUMENTLISTURL=" +
323
                         quoteString(documentListURL) +
324
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
325
			stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET LDAPPWD=" +
326
                         quoteString(ldapPwd) +
327
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
328
			stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET UNIT=" +
329
                         quoteString(unit) +
330
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
331
			stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET UPDATEFREQUENCY=" +
332
                         updateFrequency +
333
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
334
			stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET DATENEXTHARVEST=" +
335
                         quoteString(dateNextHarvest) +
336
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
337
			stmt.close();
338
      reportResults(out, ldapDN, contactEmail, documentListURL, updateFrequency,
339
                    unit, dateNextHarvest);
340
		}
341
    catch(SQLException e) {
342
			System.out.println("SQLException: " + e.getMessage());
343
		}
344
     
345
  }
346
   
347

    
348
  /**
349
   * Handles GET method requests. Displays the current registration info for
350
   * this user (if any), then allows the user to make changes and register or
351
   * unregister.
352
   * 
353
   * @param req                the request
354
   * @param res                the response
355
   * @throws ServletException
356
   * @throws IOException
357
   */
358
  public void doGet(HttpServletRequest req, HttpServletResponse res)
359
                               throws ServletException, IOException {
360
    Connection conn = getConnection();
361
    String contactEmail = "";
362
    String documentListURL = "http://";
363
    HttpSession httpSession;
364
    String ldapDN;
365
    String ldapPwd;
366
    String query;
367
    int siteScheduleID;
368
		Statement stmt;
369
    String unit = "days";
370
    int updateFrequency = 1;
371

    
372
    httpSession = req.getSession(false);
373
    
374
    if (httpSession == null) {
375
      System.out.println("User did not log in.");
376
      return;
377
    }
378

    
379
    // The user name and password are stored as session attributes by the
380
    // HarvesterRegistrationLogin servlet.
381
    ldapDN = (String) httpSession.getAttribute("username");
382
    ldapPwd = (String) httpSession.getAttribute("password");
383

    
384
    siteScheduleID = getSiteScheduleID(conn, ldapDN);
385

    
386
    // If the user is already registered, query the existing values and
387
    // initialize the form with them.
388
    if (siteScheduleID != 0) {
389
      query = "SELECT * FROM HARVEST_SITE_SCHEDULE WHERE SITE_SCHEDULE_ID=" +
390
              siteScheduleID;
391
      
392
		  try {
393
			  stmt = conn.createStatement();							
394
			  ResultSet rs = stmt.executeQuery(query);
395
	
396
			  while (rs.next()) {
397
          contactEmail = rs.getString("CONTACT_EMAIL");
398
          documentListURL = rs.getString("DOCUMENTLISTURL");
399
          updateFrequency = rs.getInt("UPDATEFREQUENCY");
400
          unit = rs.getString("UNIT");
401
        }
402

    
403
			  stmt.close();	
404
		  }
405
      catch (SQLException ex) {
406
			  System.out.println("SQLException: " + ex.getMessage());
407
		  }
408
    }
409

    
410
    res.setContentType("text/html");
411
    PrintWriter out = res.getWriter();
412

    
413
    // Print the registration form    
414
    out.println("<HTML>");
415
    out.println("<HEAD>");
416
    out.println("<TITLE>Metacat Harvester Registration</TITLE>");
417
    out.println("</HEAD>");
418
    out.println("<BODY>");
419
    out.println("<H2><B>Metacat Harvester Registration</B></H2>");
420
    out.println("<FORM METHOD=POST>");   // posts to itself
421
    out.println("Fill out the form below to schedule regular harvests of EML ");
422
    out.println("documents from your site.<BR>");
423
    out.println("To register or changes values, enter all values ");
424
    out.println("below and click <B>Register</B>. ");
425
    out.println("To unregister, simply click <B>Unregister</B>.<BR>");
426
    out.println("<table>");
427
    out.println("<tr>");
428
    out.println("<td>");
429
    out.println("Email address:");
430
    out.println("</td>");
431
    out.println("<td>");
432
    out.println("<INPUT TYPE=TEXT NAME=contactEmail SIZE=30 VALUE=");
433
    out.println(contactEmail + ">");
434
    out.println("</td>");
435
    out.println("</tr>");
436
    out.println("<tr>");
437
    out.println("<td>");
438
    out.println("Harvest List URL:");
439
    out.println("</td>");
440
    out.println("<td>");
441
    out.println("<INPUT TYPE=TEXT NAME=documentListURL SIZE=50 VALUE=");
442
    out.println(documentListURL + ">");
443
    out.println("</td>");
444
    out.println("</tr>");
445
    out.println("<tr>");
446
    out.println("<td>");
447
    out.println("Harvest Frequency");
448
    out.println("</td>");
449
    out.println("<td>");
450
    out.println("</td>");
451
    out.println("</tr>");
452
    out.println("<tr>");
453
    out.println("<td>");
454
    out.println("  Once every (1-99):");
455
    out.println("</td>");
456
    out.println("<td>");
457
    out.println("<INPUT TYPE=TEXT NAME=updateFrequency ");
458
    out.println("MAXLENGTH=2 SIZE=2 VALUE=");
459
    out.println(updateFrequency + ">");
460
    out.println("</td>");
461
    out.println("</tr>");
462
    out.println("<tr>");
463
    out.println("<td>");
464
    //out.println("Unit:");
465
    out.println("</td>");
466
    out.println("<td>");
467
    out.println("<INPUT TYPE=RADIO ");
468
    if (unit.equals("days")) out.println("CHECKED ");
469
    out.println("NAME=unit VALUE=days>day(s)");
470
    out.println("<INPUT TYPE=RADIO ");
471
    if (unit.equals("weeks")) out.println("CHECKED ");
472
    out.println("NAME=unit VALUE=weeks>week(s)");
473
    out.println("<INPUT TYPE=RADIO ");
474
    if (unit.equals("months")) out.println("CHECKED ");
475
    out.println("NAME=unit VALUE=months>month(s)");
476
    out.println("</td>");
477
    out.println("</tr>");
478
    out.println("<tr></tr>");
479
    out.println("<tr>");
480
    out.println("<td>");
481
    out.println("<INPUT TYPE=SUBMIT NAME=register VALUE=Register>");
482
    out.println("<INPUT TYPE=SUBMIT NAME=unregister VALUE=Unregister>");
483
    out.println("</td>");
484
    out.println("<td>");
485
    out.println("</td>");
486
    out.println("</tr>");
487
    out.println("</table>");
488
    out.println("</BODY>");
489
    out.println("</HTML>");
490
  }
491

    
492

    
493
  /**
494
   * Handles POST method requests. Reads values as entered by the user in the
495
   * harvester registration form and checks them for validity. Then either 
496
   * inserts, updates, or removes a record in the HARVEST_SITE_SCHEDULE table.
497
   * 
498
   * @param req                the request
499
   * @param res                the response
500
   * @throws ServletException
501
   * @throws IOException
502
   */
503
  public void doPost(HttpServletRequest req, HttpServletResponse res)
504
                               throws ServletException, IOException {
505
    Connection conn = getConnection();
506
    int maxValue;
507
    boolean remove = false;        // if true, remove record
508
    int siteScheduleID;
509
    String contactEmail;
510
    String dateLastHarvest;
511
    String dateNextHarvest;
512
    String documentListURL;
513
    HttpSession httpSession;
514
    String ldapDN;
515
    String ldapPwd;
516
    PrintWriter out;
517
    ParameterParser parameterParser = new ParameterParser(req);
518
    String register;
519
    String unit;
520
    String unregister;
521
    int updateFrequency;
522
    boolean validValues;
523

    
524
    httpSession = req.getSession(false);
525
    
526
    if (httpSession == null) {
527
      System.out.println("User did not log in.");
528
      return;
529
    }
530

    
531
    // The user name and password are stored as session attributes by the
532
    // HarvesterRegistrationLogin servlet
533
    ldapDN = (String) httpSession.getAttribute("username");
534
    ldapPwd = (String) httpSession.getAttribute("password");
535

    
536
    contactEmail = parameterParser.getStringParameter("contactEmail", "None");
537
    documentListURL = parameterParser.getStringParameter("documentListURL", "");
538
    unit = parameterParser.getStringParameter("unit", "days");
539
    updateFrequency = parameterParser.getIntParameter("updateFrequency", 1);
540
    register = parameterParser.getStringParameter("register", "");
541
    unregister = parameterParser.getStringParameter("unregister", "");
542
    remove = (unregister.equalsIgnoreCase("Unregister"));
543
    siteScheduleID = getSiteScheduleID(conn, ldapDN);
544
    dateLastHarvest = getDateLastHarvest(conn, siteScheduleID);
545

    
546
    res.setContentType("text/plain");
547
    out = res.getWriter();
548

    
549
    if (!remove) {    
550
      validValues = checkValues(out, documentListURL, updateFrequency);
551
      
552
      if (!validValues) {
553
        return;
554
      }
555
    }
556
    
557
    if (siteScheduleID == 0) {
558
      if (remove) {
559
        // The user clicked Unregister, but no existing record was found
560
        System.out.println("Unable to remove record for user " + ldapDN);
561
        System.out.println("No matching record found in HARVEST_SITE_SCHEDULE");
562
        out.println("No record found for user " + ldapDN + ".");
563
        out.println("Since you were not registered, no action was taken.");
564
      }
565
      else {
566
        maxValue = getMaxValue(conn,
567
                               "HARVEST_SITE_SCHEDULE",
568
                               "SITE_SCHEDULE_ID");
569
        siteScheduleID = maxValue + 1;
570
        dbInsert(out, conn, siteScheduleID, contactEmail, documentListURL,
571
                 ldapDN, ldapPwd, unit, updateFrequency);
572
      }
573
    }
574
    else {
575
      // Either update or remove an existing record
576
      if (remove) {
577
        dbRemove(out, conn, siteScheduleID, ldapDN);
578
      }
579
      else {
580
        dbUpdate(out, conn, siteScheduleID, contactEmail, documentListURL,
581
                 ldapDN, ldapPwd, unit, updateFrequency, dateLastHarvest);
582
      }
583
    }
584
    
585
    closeConnection(conn);
586
  }
587
  
588

    
589
  /**
590
   * Gets a database connection.
591
   * 
592
   * @return  conn, the Connection object
593
   */
594
  private Connection getConnection() {
595
    Connection conn = null;
596
    SQLWarning warn;
597

    
598
    // Make the database connection
599
    try {
600
      System.out.println("Getting connection to Harvester tables");
601
      conn = DriverManager.getConnection(defaultDB, user, password);
602

    
603
      // If a SQLWarning object is available, print its warning(s).
604
      // There may be multiple warnings chained.
605
      warn = conn.getWarnings();
606
      
607
      if (warn != null) {
608
        while (warn != null) {
609
          System.out.println("SQLState: " + warn.getSQLState());
610
          System.out.println("Message:  " + warn.getMessage());
611
          System.out.println("Vendor: " + warn.getErrorCode());
612
          System.out.println("");
613
          warn = warn.getNextWarning();
614
        }
615
      }
616
    }
617
    catch (SQLException e) {
618
      System.out.println("Database access failed " + e);
619
    }
620
    
621
    return conn;
622
  }
623

    
624

    
625
  /**
626
   * Gets the date of last harvest value from the HARVEST_SITE_SCHEDULE table,
627
   * given a siteScheduleID value (the primary key).
628
   * 
629
   * @param  conn            the connection
630
   * @param  siteScheduleID  the primary key
631
   * @return dateLastHarvest the string stored in the table, e.g.
632
   *                         "2004-04-30 00:00:00.0" or ""
633
   */
634
  private String getDateLastHarvest(Connection conn, int siteScheduleID) {
635
    String dateLastHarvest = "";
636
    String query = "SELECT DATELASTHARVEST FROM HARVEST_SITE_SCHEDULE " +
637
                   "WHERE SITE_SCHEDULE_ID=" + siteScheduleID;
638
		Statement stmt;
639
    
640
		try {
641
			stmt = conn.createStatement();							
642
			ResultSet rs = stmt.executeQuery(query);
643
	
644
			while (rs.next()) {
645
        dateLastHarvest = rs.getString("DATELASTHARVEST");
646
        if (rs.wasNull()) {
647
          dateLastHarvest = "";  // Convert null value to empty string
648
        }
649
			}
650

    
651
			stmt.close();	
652
		}
653
    catch (SQLException ex) {
654
			System.out.println("SQLException: " + ex.getMessage());
655
		}
656
    
657
    return dateLastHarvest;
658
  }
659
  
660

    
661
  /** 
662
   * Gets the maximum value of an integer field from a table, given the table
663
   * name and the field name.
664
   * 
665
   * @param tableName  the database table name
666
   * @param fieldName  the field name of the integer field in the table
667
   * @return  the maximum integer stored in the fieldName field of tableName
668
   */
669
  private int getMaxValue(Connection conn, String tableName, String fieldName) {
670
    int maxValue = 0;
671
    int fieldValue;
672
		String query = "SELECT " + fieldName + " FROM " + tableName;
673
		Statement stmt;
674
    
675
		try {
676
			stmt = conn.createStatement();							
677
			ResultSet rs = stmt.executeQuery(query);
678
	
679
			while (rs.next()) {
680
				fieldValue = rs.getInt(fieldName);
681
        maxValue = Math.max(maxValue, fieldValue);
682
			}
683
	
684
			stmt.close();	
685
		} 
686
    catch (SQLException ex) {
687
			System.out.println("SQLException: " + ex.getMessage());
688
		}
689
    
690
    return maxValue;
691
  }
692
  
693

    
694
  /**
695
   * Gets the siteScheduleID value from the HARVEST_SITE_SCHEDULE table, given
696
   * the value of the ldapDN field.
697
   * 
698
   * @param conn   the database connection
699
   * @param ldapDN the ldap DN string
700
   * @return  siteScheduleID, an integer, the primary key
701
   */
702
  private int getSiteScheduleID(Connection conn, String ldapDN) {
703
    String ldapDNValue;                       // value of LDAPDN field
704
    String query = "SELECT * FROM HARVEST_SITE_SCHEDULE";
705
    int siteScheduleID = 0;
706
		Statement stmt;
707
    
708
		try {
709
			stmt = conn.createStatement();							
710
			ResultSet rs = stmt.executeQuery(query);
711
	
712
			while (rs.next()) {
713
        ldapDNValue = rs.getString("LDAPDN");
714
        
715
        if (ldapDNValue.equalsIgnoreCase(ldapDN)) {
716
				  siteScheduleID = rs.getInt("SITE_SCHEDULE_ID");
717
        }
718
			}
719

    
720
			stmt.close();	
721
		}
722
    catch (SQLException ex) {
723
			System.out.println("SQLException: " + ex.getMessage());
724
		}
725
    
726
    return siteScheduleID;
727
  }
728
  
729

    
730
  /**
731
   * Initializes the servlet. Reads properties and initializes object fields.
732
   * 
733
   * @throws ServletException
734
   */
735
  public void init(ServletConfig config) throws ServletException {
736
    String database;
737
    String dbDriver = "";
738
    String dirPath;
739
    Options options = null;
740

    
741
    super.init(config);
742
    this.config = config;
743
    this.context = config.getServletContext();
744
    dirPath = context.getRealPath(CONFIG_DIR);
745
    File propertyFile = new File(dirPath, CONFIG_NAME);
746
    
747
    try {
748
      options = Options.initialize(propertyFile);
749
    }
750
    catch (IOException e) {
751
      System.out.println("Error in loading options: " + e.getMessage());
752
    }
753
    
754
    dbDriver = options.getOption("dbDriver");
755
    defaultDB = options.getOption("defaultDB");
756
    password = options.getOption("password");
757
    user = options.getOption("user");
758

    
759
    // Load the jdbc driver
760
    try {
761
      Class.forName(dbDriver);
762
    }
763
    catch (ClassNotFoundException e) {
764
      System.out.println("Can't load driver " + e);
765
    } 
766
  }
767

    
768

    
769
  /**
770
   * Surrounds a string with single quotes.
771
   * @param str  the original string
772
   * @return     the quoted string
773
   */
774
  private String quoteString(String str) {
775
    return "'" + str + "'";
776
  }
777
  
778
  
779
  /**
780
   * Reports the results of an insert or update to the client.
781
   * 
782
   * @param out               the PrintWriter
783
   * @param ldapDN            the LDAP DN string
784
   * @param contactEmail      the email address of the site contact
785
   * @param documentListURL   the URL of the harvester document list at the site
786
   * @param updateFrequency   the harvest update frequency
787
   * @param unit              the unit (e.g. "days", "weeks", "months"
788
   * @param dateNextHarvest   the date of the next scheduled harvest
789
   */
790
  private void reportResults(PrintWriter out,
791
                             String ldapDN,
792
                             String contactEmail,
793
                             String documentListURL,
794
                             int updateFrequency,
795
                             String unit,
796
                             String dateNextHarvest
797
                            ) {
798
    out.println("Harvester registration updated for " + ldapDN);
799
    out.println("  Email Address:             " + contactEmail);
800
    out.println("  Harvest List URL:          " + documentListURL);
801
    out.println("  Harvest Frequency:         " + updateFrequency);
802
    out.println("  Unit:                      " + unit);
803
    out.println("");
804
    out.println("Next scheduled harvest date: " + dateNextHarvest);
805
  }
806
  
807
}
(7-7/11)