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-04-14 13:48:46 -0700 (Wed, 14 Apr 2004) $'
8
 * '$Revision: 2127 $'
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 java.io.File;
29
import java.io.InputStream;
30
import java.io.IOException;
31
import java.io.PrintWriter;
32
import java.sql.Connection;
33
import java.sql.DriverManager;
34
import java.sql.ResultSet;
35
import java.sql.SQLException;
36
import java.sql.SQLWarning;
37
import java.sql.Statement;
38
import java.text.ParseException;
39
import java.text.SimpleDateFormat;
40
import java.util.Date;
41
import java.util.Enumeration;
42
import java.util.Properties;
43
import javax.servlet.ServletContext;
44
import javax.servlet.ServletException;
45
import javax.servlet.http.HttpServlet;
46
import javax.servlet.http.HttpServletRequest;
47
import javax.servlet.http.HttpServletResponse;
48
import javax.servlet.http.HttpSession;
49

    
50
/**
51
 * HarvesterRegistration is a servlet that implements harvester registration.
52
 * The servlet reads parameters that were entered in a harvester registration
53
 * form, checks the validity of the values, stores the values in the database
54
 * by either inserting, updating, or removing a record in the 
55
 * HARVEST_SITE_SCHEDULE table.
56
 * 
57
 * @author    costa
58
 * 
59
 */
60
public class HarvesterRegistration extends HttpServlet {
61
   
62
  /*
63
   * Object fields
64
   */
65
  private String defaultDB;     // database connection, from properties file
66
  final private long millisecondsPerDay = (1000 * 60 * 60 * 24);
67
  private String password;      // database password, from properties file
68
  private String user;          // database user, from properties file
69
   
70

    
71
  /*
72
   * Object methods
73
   */
74
   
75
   
76
  /**
77
   * Checks validity of user input values.
78
   * 
79
   * @param out             the PrintWriter output object
80
   * @param documentListURL the Harvest Document List URL specified by the user
81
   * @param updateFrequency the Harvest Frequency specified by the user
82
   * @return validValues    true if all values are valid, else false
83
   */
84
  private boolean checkValues(PrintWriter out,
85
                              String documentListURL,
86
                              int updateFrequency
87
                             ) {
88
    boolean validValues = true;
89

    
90
    // Check validity of the Harvest Document List URL field    
91
    if (documentListURL.equals("")) {
92
      out.println(
93
              "A value must be specified in the Harvest Document List URL field"
94
                 );
95
      validValues = false;
96
    }
97

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

    
124

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

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

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

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

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

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

    
362
    httpSession = req.getSession(false);
363
    
364
    if (httpSession == null) {
365
      System.out.println("User did not log in.");
366
      return;
367
    }
368

    
369
    // The user name and password are stored as session attributes by the
370
    // HarvesterRegistrationLogin servlet.
371
    ldapDN = (String) httpSession.getAttribute("ldapDN");
372
    ldapPwd = (String) httpSession.getAttribute("ldapPwd");
373

    
374
    siteScheduleID = getSiteScheduleID(conn, ldapDN);
375

    
376
    // If the user is already registered, query the existing values and
377
    // initialize the form with them.
378
    if (siteScheduleID != 0) {
379
      query = "SELECT * FROM HARVEST_SITE_SCHEDULE WHERE SITE_SCHEDULE_ID=" +
380
              siteScheduleID;
381
      
382
		  try {
383
			  stmt = conn.createStatement();							
384
			  ResultSet rs = stmt.executeQuery(query);
385
	
386
			  while (rs.next()) {
387
          contactEmail = rs.getString("CONTACT_EMAIL");
388
          documentListURL = rs.getString("DOCUMENTLISTURL");
389
          updateFrequency = rs.getInt("UPDATEFREQUENCY");
390
          unit = rs.getString("UNIT");
391
        }
392

    
393
			  stmt.close();	
394
		  }
395
      catch (SQLException ex) {
396
			  System.out.println("SQLException: " + ex.getMessage());
397
		  }
398
    }
399

    
400
    res.setContentType("text/html");
401
    PrintWriter out = res.getWriter();
402

    
403
    // Print the registration form    
404
    out.println("<HTML>");
405
    out.println("<HEAD>");
406
    out.println("<TITLE>Metacat Harvester Registration</TITLE>");
407
    out.println("</HEAD>");
408
    out.println("<BODY>");
409
    out.println("<H2><B>Metacat Harvester Registration</B></H2>");
410
    out.println("<FORM METHOD=POST>");   // posts to itself
411
    out.println("To register or changes values, enter all values ");
412
    out.println("below and click <B>Register</B>.<BR>");
413
    out.println("To unregister, simply click <B>Unregister</B>.<BR>");
414
    out.println("<BR><BR>");
415
    out.println("<pre>Email address:             </pre>");
416
    out.println("<INPUT TYPE=TEXT NAME=contactEmail VALUE=");
417
    out.println(contactEmail + ">");
418
    out.println("<BR><BR>");
419
    out.println("<pre>Harvest Document List URL: </pre>");
420
    out.println("<INPUT TYPE=TEXT NAME=documentListURL VALUE=");
421
    out.println(documentListURL + ">");
422
    out.println("<BR><BR>");
423
    out.println("<pre>Harvest Frequency (1-99):  </pre>");
424
    out.println("<INPUT TYPE=TEXT NAME=updateFrequency ");
425
    out.println("MAXLENGTH=2 SIZE=2 VALUE=");
426
    out.println(updateFrequency + ">");
427
    out.println("<BR><BR>");
428
    out.println("<pre>Unit:                      </pre>");
429
    out.println("<INPUT TYPE=RADIO ");
430
    if (unit.equals("days")) out.println("CHECKED ");
431
    out.println("NAME=unit VALUE=days>day(s)");
432
    out.println("<INPUT TYPE=RADIO ");
433
    if (unit.equals("weeks")) out.println("CHECKED ");
434
    out.println("NAME=unit VALUE=weeks>week(s)");
435
    out.println("<INPUT TYPE=RADIO ");
436
    if (unit.equals("months")) out.println("CHECKED ");
437
    out.println("NAME=unit VALUE=months>month(s)");
438
    out.println("<BR><BR><BR>");
439
    out.println("<INPUT TYPE=SUBMIT NAME=register VALUE=Register>");
440
    out.println("<INPUT TYPE=SUBMIT NAME=unregister VALUE=Unregister>");
441
    out.println("</BODY>");
442
    out.println("</HTML>");
443
  }
444

    
445

    
446
  /**
447
   * Handles POST method requests. Reads values as entered by the user in the
448
   * harvester registration form and checks them for validity. Then either 
449
   * inserts, updates, or removes a record in the HARVEST_SITE_SCHEDULE table.
450
   * 
451
   * @param req                the request
452
   * @param res                the response
453
   * @throws ServletException
454
   * @throws IOException
455
   */
456
  public void doPost(HttpServletRequest req, HttpServletResponse res)
457
                               throws ServletException, IOException {
458
    Connection conn = getConnection();
459
    int maxValue;
460
    boolean remove = false;        // if true, remove record
461
    int siteScheduleID;
462
    String contactEmail;
463
    String dateLastHarvest;
464
    String dateNextHarvest;
465
    String documentListURL;
466
    HttpSession httpSession;
467
    String ldapDN;
468
    String ldapPwd;
469
    PrintWriter out;
470
    ParameterParser parameterParser = new ParameterParser(req);
471
    String register;
472
    String unit;
473
    String unregister;
474
    int updateFrequency;
475
    boolean validValues;
476

    
477
    httpSession = req.getSession(false);
478
    
479
    if (httpSession == null) {
480
      System.out.println("User did not log in.");
481
      return;
482
    }
483

    
484
    // The user name and password are stored as session attributes by the
485
    // HarvesterRegistrationLogin servlet
486
    ldapDN = (String) httpSession.getAttribute("ldapDN");
487
    ldapPwd = (String) httpSession.getAttribute("ldapPwd");
488

    
489
    contactEmail = parameterParser.getStringParameter("contactEmail", "None");
490
    documentListURL = parameterParser.getStringParameter("documentListURL", "");
491
    unit = parameterParser.getStringParameter("unit", "days");
492
    updateFrequency = parameterParser.getIntParameter("updateFrequency", 1);
493
    register = parameterParser.getStringParameter("register", "");
494
    unregister = parameterParser.getStringParameter("unregister", "");
495
    remove = (unregister.equalsIgnoreCase("Unregister"));
496
    siteScheduleID = getSiteScheduleID(conn, ldapDN);
497
    dateLastHarvest = getDateLastHarvest(conn, siteScheduleID);
498

    
499
    res.setContentType("text/plain");
500
    out = res.getWriter();
501

    
502
    if (!remove) {    
503
      validValues = checkValues(out, documentListURL, updateFrequency);
504
      
505
      if (!validValues) {
506
        return;
507
      }
508
    }
509
    
510
    if (siteScheduleID == 0) {
511
      if (remove) {
512
        // The user clicked Unregister, but no existing record was found
513
        System.out.println("Unable to remove record for user " + ldapDN);
514
        System.out.println("No matching record found in HARVEST_SITE_SCHEDULE");
515
        out.println("No record found for user " + ldapDN + ".");
516
        out.println("Since you were not registered, no action was taken.");
517
      }
518
      else {
519
        maxValue = getMaxValue(conn,
520
                               "HARVEST_SITE_SCHEDULE",
521
                               "SITE_SCHEDULE_ID");
522
        siteScheduleID = maxValue + 1;
523
        dbInsert(out, conn, siteScheduleID, contactEmail, documentListURL,
524
                 ldapDN, ldapPwd, unit, updateFrequency);
525
      }
526
    }
527
    else {
528
      // Either update or remove an existing record
529
      if (remove) {
530
        dbRemove(out, conn, siteScheduleID, ldapDN);
531
      }
532
      else {
533
        dbUpdate(out, conn, siteScheduleID, contactEmail, documentListURL,
534
                 ldapDN, ldapPwd, unit, updateFrequency, dateLastHarvest);
535
      }
536
    }
537
    
538
    closeConnection(conn);
539
  }
540
  
541

    
542
  /**
543
   * Gets a database connection.
544
   * 
545
   * @return  conn, the Connection object
546
   */
547
  private Connection getConnection() {
548
    Connection conn = null;
549
    SQLWarning warn;
550

    
551
    // Make the database connection
552
    try {
553
      System.out.println("Getting connection to Harvester tables");
554
      conn = DriverManager.getConnection(defaultDB, user, password);
555

    
556
      // If a SQLWarning object is available, print its warning(s).
557
      // There may be multiple warnings chained.
558
      warn = conn.getWarnings();
559
      
560
      if (warn != null) {
561
        while (warn != null) {
562
          System.out.println("SQLState: " + warn.getSQLState());
563
          System.out.println("Message:  " + warn.getMessage());
564
          System.out.println("Vendor: " + warn.getErrorCode());
565
          System.out.println("");
566
          warn = warn.getNextWarning();
567
        }
568
      }
569
    }
570
    catch (SQLException e) {
571
      System.out.println("Database access failed " + e);
572
    }
573
    
574
    return conn;
575
  }
576

    
577

    
578
  /**
579
   * Gets the date of last harvest value from the HARVEST_SITE_SCHEDULE table,
580
   * given a siteScheduleID value (the primary key).
581
   * 
582
   * @param  conn            the connection
583
   * @param  siteScheduleID  the primary key
584
   * @return dateLastHarvest the string stored in the table, e.g.
585
   *                         "2004-04-30 00:00:00.0" or ""
586
   */
587
  private String getDateLastHarvest(Connection conn, int siteScheduleID) {
588
    String dateLastHarvest = "";
589
    String query = "SELECT DATELASTHARVEST FROM HARVEST_SITE_SCHEDULE " +
590
                   "WHERE SITE_SCHEDULE_ID=" + siteScheduleID;
591
		Statement stmt;
592
    
593
		try {
594
			stmt = conn.createStatement();							
595
			ResultSet rs = stmt.executeQuery(query);
596
	
597
			while (rs.next()) {
598
        dateLastHarvest = rs.getString("DATELASTHARVEST");
599
        if (rs.wasNull()) {
600
          dateLastHarvest = "";  // Convert null value to empty string
601
        }
602
			}
603

    
604
			stmt.close();	
605
		}
606
    catch (SQLException ex) {
607
			System.out.println("SQLException: " + ex.getMessage());
608
		}
609
    
610
    return dateLastHarvest;
611
  }
612
  
613

    
614
  /** 
615
   * Gets the maximum value of an integer field from a table, given the table
616
   * name and the field name.
617
   * 
618
   * @param tableName  the database table name
619
   * @param fieldName  the field name of the integer field in the table
620
   * @return  the maximum integer stored in the fieldName field of tableName
621
   */
622
  private int getMaxValue(Connection conn, String tableName, String fieldName) {
623
    int maxValue = 0;
624
    int fieldValue;
625
		String query = "SELECT " + fieldName + " FROM " + tableName;
626
		Statement stmt;
627
    
628
		try {
629
			stmt = conn.createStatement();							
630
			ResultSet rs = stmt.executeQuery(query);
631
	
632
			while (rs.next()) {
633
				fieldValue = rs.getInt(fieldName);
634
        maxValue = Math.max(maxValue, fieldValue);
635
			}
636
	
637
			stmt.close();	
638
		} 
639
    catch (SQLException ex) {
640
			System.out.println("SQLException: " + ex.getMessage());
641
		}
642
    
643
    return maxValue;
644
  }
645
  
646

    
647
  /**
648
   * Gets the siteScheduleID value from the HARVEST_SITE_SCHEDULE table, given
649
   * the value of the ldapDN field.
650
   * 
651
   * @param conn   the database connection
652
   * @param ldapDN the ldap DN string
653
   * @return  siteScheduleID, an integer, the primary key
654
   */
655
  private int getSiteScheduleID(Connection conn, String ldapDN) {
656
    String ldapDNValue;                       // value of LDAPDN field
657
    String query = "SELECT * FROM HARVEST_SITE_SCHEDULE";
658
    int siteScheduleID = 0;
659
		Statement stmt;
660
    
661
		try {
662
			stmt = conn.createStatement();							
663
			ResultSet rs = stmt.executeQuery(query);
664
	
665
			while (rs.next()) {
666
        ldapDNValue = rs.getString("LDAPDN");
667

    
668
        if (ldapDNValue.equalsIgnoreCase(ldapDN)) {
669
				  siteScheduleID = rs.getInt("SITE_SCHEDULE_ID");
670
        }
671
			}
672

    
673
			stmt.close();	
674
		}
675
    catch (SQLException ex) {
676
			System.out.println("SQLException: " + ex.getMessage());
677
		}
678
    
679
    return siteScheduleID;
680
  }
681
  
682

    
683
  /**
684
   * Initializes the servlet. Reads properties and initializes object fields.
685
   * 
686
   * @throws ServletException
687
   */
688
  public void init() throws ServletException {
689
    String dbDriver;
690
    Properties properties = loadProperties();
691

    
692
    dbDriver = properties.getProperty("dbDriver");
693
    defaultDB = properties.getProperty("defaultDB");
694
    password = properties.getProperty("password");
695
    user = properties.getProperty("user");
696

    
697
    // Load the jdbc driver
698
    try {
699
      Class.forName(dbDriver);
700
    }
701
    catch (ClassNotFoundException e) {
702
      System.out.println("Can't load driver " + e);
703
    } 
704
  }
705

    
706

    
707
  /**
708
   * Loads Harvester properties from a configuration file.
709
   */
710
  private Properties loadProperties() {
711
    InputStream inputStream;
712
    String path = "/harvester/harvester.properties";
713
    Properties properties = new Properties();
714
    ServletContext servletContext = getServletContext();
715

    
716
    try {
717
      inputStream = servletContext.getResourceAsStream(path);
718
      properties.load(inputStream);
719
      properties.list(System.out);
720
    }
721
    catch (IOException e) {
722
      System.out.println("IOException: " + e.getMessage());
723
    }
724
    
725
    return properties;
726
  }
727
  
728

    
729
  /**
730
   * Surrounds a string with single quotes.
731
   * @param str  the original string
732
   * @return     the quoted string
733
   */
734
  private String quoteString(String str) {
735
    return "'" + str + "'";
736
  }
737
  
738
  
739
  /**
740
   * Reports the results of an insert or update to the client.
741
   * 
742
   * @param out               the PrintWriter
743
   * @param ldapDN            the LDAP DN string
744
   * @param contactEmail      the email address of the site contact
745
   * @param documentListURL   the URL of the harvester document list at the site
746
   * @param updateFrequency   the harvest update frequency
747
   * @param unit              the unit (e.g. "days", "weeks", "months"
748
   * @param dateNextHarvest   the date of the next scheduled harvest
749
   */
750
  private void reportResults(PrintWriter out,
751
                             String ldapDN,
752
                             String contactEmail,
753
                             String documentListURL,
754
                             int updateFrequency,
755
                             String unit,
756
                             String dateNextHarvest
757
                            ) {
758
    out.println("Harvester registration updated for " + ldapDN);
759
    out.println("  Email Address:             " + contactEmail);
760
    out.println("  Harvest Document List URL: " + documentListURL);
761
    out.println("  Harvest Frequency:         " + updateFrequency);
762
    out.println("  Unit:                      " + unit);
763
    out.println("");
764
    out.println("Next scheduled harvest date: " + dateNextHarvest);
765
  }
766
  
767
}
(6-6/9)