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: 2004-05-17 16:36:27 -0700 (Mon, 17 May 2004) $'
8
 * '$Revision: 2171 $'
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 writeFormat = new SimpleDateFormat("dd-MMM-yyyy");
280
		Statement stmt;
281
    long timeLastHarvest;
282
    long timeNextHarvest;
283
    long timeNow = now.getTime();
284
    
285
    // Calculate the value of delta, the number of milliseconds between the
286
    // last harvest date and the next harvest date.
287
    delta = updateFrequency * millisecondsPerDay;
288
    
289
    if (unit.equals("weeks")) {
290
      delta *= 7;
291
    }
292
    else if (unit.equals("months")) {
293
      delta *= 30;
294
    }
295

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

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

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

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

    
383
    siteScheduleID = getSiteScheduleID(conn, ldapDN);
384

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

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

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

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

    
484

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

    
516
    httpSession = req.getSession(false);
517
    
518
    if (httpSession == null) {
519
      System.out.println("User did not log in.");
520
      return;
521
    }
522

    
523
    // The user name and password are stored as session attributes by the
524
    // HarvesterRegistrationLogin servlet
525
    ldapDN = (String) httpSession.getAttribute("username");
526
    ldapPwd = (String) httpSession.getAttribute("password");
527

    
528
    contactEmail = parameterParser.getStringParameter("contactEmail", "None");
529
    documentListURL = parameterParser.getStringParameter("documentListURL", "");
530
    unit = parameterParser.getStringParameter("unit", "days");
531
    updateFrequency = parameterParser.getIntParameter("updateFrequency", 1);
532
    register = parameterParser.getStringParameter("register", "");
533
    unregister = parameterParser.getStringParameter("unregister", "");
534
    remove = (unregister.equalsIgnoreCase("Unregister"));
535
    siteScheduleID = getSiteScheduleID(conn, ldapDN);
536
    dateLastHarvest = getDateLastHarvest(conn, siteScheduleID);
537

    
538
    res.setContentType("text/plain");
539
    out = res.getWriter();
540

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

    
581
  /**
582
   * Gets a database connection.
583
   * 
584
   * @return  conn, the Connection object
585
   */
586
  private Connection getConnection() {
587
    Connection conn = null;
588
    SQLWarning warn;
589

    
590
    // Make the database connection
591
    try {
592
      System.out.println("Getting connection to Harvester tables");
593
      conn = DriverManager.getConnection(defaultDB, user, password);
594

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

    
616

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

    
643
			stmt.close();	
644
		}
645
    catch (SQLException ex) {
646
			System.out.println("SQLException: " + ex.getMessage());
647
		}
648
    
649
    return dateLastHarvest;
650
  }
651
  
652

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

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

    
712
			stmt.close();	
713
		}
714
    catch (SQLException ex) {
715
			System.out.println("SQLException: " + ex.getMessage());
716
		}
717
    
718
    return siteScheduleID;
719
  }
720
  
721

    
722
  /**
723
   * Initializes the servlet. Reads properties and initializes object fields.
724
   * 
725
   * @throws ServletException
726
   */
727
  public void init(ServletConfig config) throws ServletException {
728
    String database;
729
    String dbDriver = "";
730
    String dirPath;
731
    Options options = null;
732

    
733
    super.init(config);
734
    this.config = config;
735
    this.context = config.getServletContext();
736
    dirPath = context.getRealPath(CONFIG_DIR);
737
    File propertyFile = new File(dirPath, CONFIG_NAME);
738
    
739
    try {
740
      options = Options.initialize(propertyFile);
741
    }
742
    catch (IOException e) {
743
      System.out.println("Error in loading options: " + e.getMessage());
744
    }
745
    
746
    dbDriver = options.getOption("dbDriver");
747
    defaultDB = options.getOption("defaultDB");
748
    password = options.getOption("password");
749
    user = options.getOption("user");
750

    
751
    // Load the jdbc driver
752
    try {
753
      Class.forName(dbDriver);
754
    }
755
    catch (ClassNotFoundException e) {
756
      System.out.println("Can't load driver " + e);
757
    } 
758
  }
759

    
760

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