Project

General

Profile

1 2094 jones
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2004 University of New Mexico and the
4
 *                  Regents of the University of California
5 2063 costa
 *
6 2094 jones
 *   '$Author$'
7
 *     '$Date$'
8
 * '$Revision$'
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 2063 costa
 */
24
25
package edu.ucsb.nceas.metacat.harvesterClient;
26
27
import com.oreilly.servlet.ParameterParser;
28
import java.io.IOException;
29
import java.io.PrintWriter;
30
import java.sql.Connection;
31
import java.sql.DriverManager;
32
import java.sql.ResultSet;
33
import java.sql.SQLException;
34
import java.sql.SQLWarning;
35
import java.sql.Statement;
36
import java.text.ParseException;
37
import java.text.SimpleDateFormat;
38
import java.util.Date;
39 2155 costa
import javax.servlet.ServletConfig;
40 2063 costa
import javax.servlet.ServletContext;
41
import javax.servlet.ServletException;
42
import javax.servlet.http.HttpServlet;
43
import javax.servlet.http.HttpServletRequest;
44
import javax.servlet.http.HttpServletResponse;
45
import javax.servlet.http.HttpSession;
46
47 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
48 5015 daigle
import edu.ucsb.nceas.metacat.shared.ServiceException;
49 4125 daigle
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
50
51 2063 costa
/**
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 2367 costa
 * by either inserting, updating, or removing a record in the
56 2063 costa
 * HARVEST_SITE_SCHEDULE table.
57
 *
58
 * @author    costa
59
 *
60
 */
61
public class HarvesterRegistration extends HttpServlet {
62 2155 costa
63
  /*
64
   * Class fields
65
   */
66
  private static final String CONFIG_DIR = "WEB-INF";
67 2063 costa
68 4125 daigle
  private static final long serialVersionUID = 7390084694699704362L;
69
70 2063 costa
  /*
71
   * Object fields
72
   */
73 2155 costa
  private ServletConfig config = null;
74
  private ServletContext context = null;
75 2114 costa
  private String defaultDB;     // database connection, from properties file
76 2063 costa
  final private long millisecondsPerDay = (1000 * 60 * 60 * 24);
77
  private String password;      // database password, from properties file
78
  private String user;          // database user, from properties file
79
80
81
  /*
82
   * Object methods
83
   */
84 2085 costa
85
86
  /**
87
   * Checks validity of user input values.
88
   *
89
   * @param out             the PrintWriter output object
90 2170 costa
   * @param documentListURL the Harvest List URL specified by the user
91 2085 costa
   * @param updateFrequency the Harvest Frequency specified by the user
92
   * @return validValues    true if all values are valid, else false
93
   */
94
  private boolean checkValues(PrintWriter out,
95
                              String documentListURL,
96
                              int updateFrequency
97
                             ) {
98
    boolean validValues = true;
99 2063 costa
100 2170 costa
    // Check validity of the Harvest List URL field
101 2085 costa
    if (documentListURL.equals("")) {
102 2385 costa
      out.println("A value must be specified in the Harvest List URL field");
103 2085 costa
      validValues = false;
104
    }
105
106
    // Check validity of the Harvest Frequency field
107 2127 costa
    if ((updateFrequency < 0) || (updateFrequency > 99)) {
108 2085 costa
      out.println("Harvest Frequency should be in the range 1 to 99");
109
      validValues = false;
110
    }
111
112
    return validValues;
113
  }
114
115
116 2063 costa
  /**
117
   * Closes the database connection.
118
   *
119
   * @param conn  The connection.
120
   */
121
  private void closeConnection(Connection conn) {
122
    try {
123
      if (conn != null) {
124
        conn.close();
125
      }
126
    }
127
    catch (SQLException e) {
128
      // ignored
129
    }
130
  }
131
132
133
  /**
134
   * Inserts a record to the HARVEST_SITE_SCHEDULE table.
135
   *
136
   * @param out             the PrintWriter output object
137
   * @param conn            the Connection
138
   * @param siteScheduleID  the primary key for the table
139
   * @param contactEmail    contact email address of the site user
140 2170 costa
   * @param documentListURL the URL of the harvest list at the site
141 2063 costa
   * @param ldapDN          the site user's LDAP DN
142
   * @param ldapPwd         the site user's LDAP password
143
   * @param unit            the update frequency unit, e.g. "days", "weeks"
144
   * @param updateFrequency the update frequency, an integer in range 1-99
145
   */
146
  private void dbInsert(PrintWriter out,
147
                        Connection conn,
148
                        int siteScheduleID,
149
                        String contactEmail,
150
                        String documentListURL,
151
                        String ldapDN,
152
                        String ldapPwd,
153
                        String unit,
154
                        int updateFrequency
155
                       ) {
156
    String dateNextHarvest;
157
    long delta;
158
    Date dnh;                          // Date of next harvest
159
    Date now;                          // Today's date
160
    String query;
161 2385 costa
    Statement stmt;
162 2063 costa
    long timeNextHarvest;
163
    SimpleDateFormat writeFormat = new SimpleDateFormat("dd-MMM-yyyy");
164
165
    // Calculate the value of delta, the number of milliseconds between the
166
    // last harvest date and the next harvest date.
167
    delta = updateFrequency * millisecondsPerDay;
168
169
    if (unit.equals("weeks")) {
170
      delta *= 7;
171
    }
172
    else if (unit.equals("months")) {
173
      delta *= 30;
174
    }
175
176
    now = new Date();
177
    timeNextHarvest = now.getTime();
178
    dnh = new Date(timeNextHarvest);
179
    dateNextHarvest = writeFormat.format(dnh);
180
181 2385 costa
    try {
182
      stmt = conn.createStatement();
183
      query = "insert into HARVEST_SITE_SCHEDULE " +
184
        "(SITE_SCHEDULE_ID, CONTACT_EMAIL, DOCUMENTLISTURL, LDAPDN, LDAPPWD, " +
185
        "UNIT, UPDATEFREQUENCY, DATENEXTHARVEST) " +
186
        "values(" + siteScheduleID + "," +
187
        quoteString(contactEmail) + "," +
188
        quoteString(documentListURL) + "," +
189
        quoteString(ldapDN) + "," +
190
        quoteString(ldapPwd) + "," +
191
        quoteString(unit) + "," +
192
        updateFrequency + "," +
193
        quoteString(dateNextHarvest) + ")";
194 2063 costa
195
      System.out.println(query);
196
      stmt.executeUpdate(query);
197 2385 costa
      stmt.close();
198 2063 costa
      reportResults(out, ldapDN, contactEmail, documentListURL, updateFrequency,
199
                    unit, dateNextHarvest);
200 2385 costa
    }
201 2063 costa
    catch(SQLException e) {
202 2385 costa
      System.out.println("SQLException: " + e.getMessage());
203
	}
204
  }
205 2063 costa
206
207
  /**
208
   * Removes a record from the HARVEST_SITE_SCHEDULE table.
209
   *
210
   * @param out            the PrintWriter output object
211
   * @param conn           the Connection
212
   * @param siteScheduleID the primary key for the table
213
   * @param ldapDN          the site user's LDAP DN
214
   */
215
  private void dbRemove(PrintWriter out,
216
                        Connection conn,
217
                        int siteScheduleID,
218
                        String ldapDN
219
                       ) {
220
    String query = "DELETE FROM HARVEST_SITE_SCHEDULE WHERE " +
221
                   "SITE_SCHEDULE_ID=" + siteScheduleID;
222
    int nRecords = 0;
223 2385 costa
	Statement stmt;
224 2063 costa
225 2385 costa
	try {
226
      stmt = conn.createStatement();
227 2063 costa
      System.out.println(query);
228
      nRecords = stmt.executeUpdate(query);
229
      stmt.close();
230
      System.out.println(nRecords + " record(s) removed.");
231
232
      if (nRecords > 0) {
233
        out.println("Harvester registration removed for user " + ldapDN);
234
      }
235
      else {
236
        out.println("A problem was encountered removing registration for user "
237
                    + ldapDN);
238
      }
239 2385 costa
    }
240 2063 costa
    catch(SQLException e) {
241 2385 costa
      System.out.println("SQLException: " + e.getMessage());
242
    }
243
  }
244 2063 costa
245
246
  /**
247
   * Updates a record in the HARVEST_SITE_SCHEDULE table.
248
   *
249
   * @param out             the PrintWriter output object
250
   * @param conn            the Connection
251
   * @param siteScheduleID  the primary key for the table
252
   * @param contactEmail    contact email address of the site user
253 2170 costa
   * @param documentListURL the URL of the harvest list at the site
254 2063 costa
   * @param ldapDN          the site user's LDAP DN
255
   * @param ldapPwd         the site user's LDAP password
256
   * @param unit            the update frequency unit, e.g. "days", "weeks"
257
   * @param updateFrequency the update frequency, an integer in range 1-99
258
   * @param dateLastHarvest the date of last harvest,
259
   *                        e.g. "2004-04-30 00:00:00.0" or ""
260
   */
261
   private void dbUpdate(PrintWriter out,
262
                         Connection conn,
263
                         int siteScheduleID,
264
                         String contactEmail,
265
                         String documentListURL,
266
                         String ldapDN,
267
                         String ldapPwd,
268
                         String unit,
269
                         int updateFrequency,
270
                         String dateLastHarvest
271
                        ) {
272
    String dateNextHarvest;
273
    long delta;
274
    Date dlh;                          // Date of last harvest
275
    Date dnh;                          // Date of next harvest
276
    Date now = new Date();             // Today's date
277 2385 costa
//  SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
278 2303 costa
    SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd");
279 2063 costa
    SimpleDateFormat writeFormat = new SimpleDateFormat("dd-MMM-yyyy");
280 2385 costa
    Statement stmt;
281 2063 costa
    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 2385 costa
    try {
317
      stmt = conn.createStatement();
318
      stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET CONTACT_EMAIL=" +
319 2063 costa
                         quoteString(contactEmail) +
320
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
321 2385 costa
      stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET DOCUMENTLISTURL=" +
322 2063 costa
                         quoteString(documentListURL) +
323
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
324 2385 costa
      stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET LDAPPWD=" +
325 2063 costa
                         quoteString(ldapPwd) +
326
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
327 2385 costa
      stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET UNIT=" +
328 2063 costa
                         quoteString(unit) +
329
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
330 2385 costa
      stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET UPDATEFREQUENCY=" +
331 2063 costa
                         updateFrequency +
332
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
333 2385 costa
      stmt.executeUpdate("UPDATE HARVEST_SITE_SCHEDULE SET DATENEXTHARVEST=" +
334 2063 costa
                         quoteString(dateNextHarvest) +
335
                         " WHERE SITE_SCHEDULE_ID = " + siteScheduleID);
336 2385 costa
      stmt.close();
337 2063 costa
      reportResults(out, ldapDN, contactEmail, documentListURL, updateFrequency,
338
                    unit, dateNextHarvest);
339 2385 costa
    }
340 2063 costa
    catch(SQLException e) {
341 2385 costa
      System.out.println("SQLException: " + e.getMessage());
342
    }
343
344 2063 costa
  }
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 2385 costa
    Statement stmt;
368 2063 costa
    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 2171 costa
    ldapDN = (String) httpSession.getAttribute("username");
381
    ldapPwd = (String) httpSession.getAttribute("password");
382 2063 costa
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 2385 costa
      try {
392
        stmt = conn.createStatement();
393
        ResultSet rs = stmt.executeQuery(query);
394
395
        while (rs.next()) {
396 2063 costa
          contactEmail = rs.getString("CONTACT_EMAIL");
397
          documentListURL = rs.getString("DOCUMENTLISTURL");
398
          updateFrequency = rs.getInt("UPDATEFREQUENCY");
399
          unit = rs.getString("UNIT");
400
        }
401 2385 costa
402
        stmt.close();
403
      }
404 2063 costa
      catch (SQLException ex) {
405 2385 costa
        System.out.println("SQLException: " + ex.getMessage());
406
      }
407 2063 costa
    }
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 2170 costa
    out.println("Fill out the form below to schedule regular harvests of EML ");
421
    out.println("documents from your site.<BR>");
422 2063 costa
    out.println("To register or changes values, enter all values ");
423 2170 costa
    out.println("below and click <B>Register</B>. ");
424 2063 costa
    out.println("To unregister, simply click <B>Unregister</B>.<BR>");
425 2170 costa
    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 2221 costa
    out.println("<INPUT TYPE=TEXT NAME=contactEmail SIZE=30 VALUE=");
432 2063 costa
    out.println(contactEmail + ">");
433 2170 costa
    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 2221 costa
    out.println("<INPUT TYPE=TEXT NAME=documentListURL SIZE=50 VALUE=");
441 2063 costa
    out.println(documentListURL + ">");
442 2170 costa
    out.println("</td>");
443
    out.println("</tr>");
444
    out.println("<tr>");
445
    out.println("<td>");
446 2221 costa
    out.println("Harvest Frequency");
447 2170 costa
    out.println("</td>");
448
    out.println("<td>");
449 2221 costa
    out.println("</td>");
450
    out.println("</tr>");
451
    out.println("<tr>");
452
    out.println("<td>");
453
    out.println("  Once every (1-99):");
454
    out.println("</td>");
455
    out.println("<td>");
456 2063 costa
    out.println("<INPUT TYPE=TEXT NAME=updateFrequency ");
457
    out.println("MAXLENGTH=2 SIZE=2 VALUE=");
458
    out.println(updateFrequency + ">");
459 2170 costa
    out.println("</td>");
460
    out.println("</tr>");
461
    out.println("<tr>");
462
    out.println("<td>");
463 2221 costa
    //out.println("Unit:");
464 2170 costa
    out.println("</td>");
465
    out.println("<td>");
466 2063 costa
    out.println("<INPUT TYPE=RADIO ");
467
    if (unit.equals("days")) out.println("CHECKED ");
468
    out.println("NAME=unit VALUE=days>day(s)");
469
    out.println("<INPUT TYPE=RADIO ");
470
    if (unit.equals("weeks")) out.println("CHECKED ");
471
    out.println("NAME=unit VALUE=weeks>week(s)");
472
    out.println("<INPUT TYPE=RADIO ");
473
    if (unit.equals("months")) out.println("CHECKED ");
474
    out.println("NAME=unit VALUE=months>month(s)");
475 2170 costa
    out.println("</td>");
476
    out.println("</tr>");
477
    out.println("<tr></tr>");
478
    out.println("<tr>");
479
    out.println("<td>");
480 2063 costa
    out.println("<INPUT TYPE=SUBMIT NAME=register VALUE=Register>");
481
    out.println("<INPUT TYPE=SUBMIT NAME=unregister VALUE=Unregister>");
482 2170 costa
    out.println("</td>");
483
    out.println("<td>");
484
    out.println("</td>");
485
    out.println("</tr>");
486
    out.println("</table>");
487 2063 costa
    out.println("</BODY>");
488
    out.println("</HTML>");
489
  }
490
491
492
  /**
493
   * Handles POST method requests. Reads values as entered by the user in the
494
   * harvester registration form and checks them for validity. Then either
495
   * inserts, updates, or removes a record in the HARVEST_SITE_SCHEDULE table.
496
   *
497
   * @param req                the request
498
   * @param res                the response
499
   * @throws ServletException
500
   * @throws IOException
501
   */
502
  public void doPost(HttpServletRequest req, HttpServletResponse res)
503
                               throws ServletException, IOException {
504
    Connection conn = getConnection();
505
    int maxValue;
506
    boolean remove = false;        // if true, remove record
507
    int siteScheduleID;
508
    String contactEmail;
509
    String dateLastHarvest;
510
    String dateNextHarvest;
511
    String documentListURL;
512
    HttpSession httpSession;
513
    String ldapDN;
514
    String ldapPwd;
515 2085 costa
    PrintWriter out;
516 2063 costa
    ParameterParser parameterParser = new ParameterParser(req);
517
    String register;
518
    String unit;
519
    String unregister;
520
    int updateFrequency;
521 2085 costa
    boolean validValues;
522 2063 costa
523 2085 costa
    httpSession = req.getSession(false);
524 2063 costa
525
    if (httpSession == null) {
526
      System.out.println("User did not log in.");
527
      return;
528
    }
529
530
    // The user name and password are stored as session attributes by the
531
    // HarvesterRegistrationLogin servlet
532 2171 costa
    ldapDN = (String) httpSession.getAttribute("username");
533
    ldapPwd = (String) httpSession.getAttribute("password");
534 2063 costa
535
    contactEmail = parameterParser.getStringParameter("contactEmail", "None");
536
    documentListURL = parameterParser.getStringParameter("documentListURL", "");
537
    unit = parameterParser.getStringParameter("unit", "days");
538
    updateFrequency = parameterParser.getIntParameter("updateFrequency", 1);
539
    register = parameterParser.getStringParameter("register", "");
540
    unregister = parameterParser.getStringParameter("unregister", "");
541
    remove = (unregister.equalsIgnoreCase("Unregister"));
542
    siteScheduleID = getSiteScheduleID(conn, ldapDN);
543
    dateLastHarvest = getDateLastHarvest(conn, siteScheduleID);
544 2085 costa
545 2063 costa
    res.setContentType("text/plain");
546 2085 costa
    out = res.getWriter();
547 2063 costa
548 2085 costa
    if (!remove) {
549
      validValues = checkValues(out, documentListURL, updateFrequency);
550
551
      if (!validValues) {
552
        return;
553
      }
554
    }
555
556 2063 costa
    if (siteScheduleID == 0) {
557
      if (remove) {
558
        // The user clicked Unregister, but no existing record was found
559
        System.out.println("Unable to remove record for user " + ldapDN);
560
        System.out.println("No matching record found in HARVEST_SITE_SCHEDULE");
561
        out.println("No record found for user " + ldapDN + ".");
562
        out.println("Since you were not registered, no action was taken.");
563
      }
564
      else {
565
        maxValue = getMaxValue(conn,
566
                               "HARVEST_SITE_SCHEDULE",
567
                               "SITE_SCHEDULE_ID");
568
        siteScheduleID = maxValue + 1;
569
        dbInsert(out, conn, siteScheduleID, contactEmail, documentListURL,
570
                 ldapDN, ldapPwd, unit, updateFrequency);
571
      }
572
    }
573
    else {
574
      // Either update or remove an existing record
575
      if (remove) {
576
        dbRemove(out, conn, siteScheduleID, ldapDN);
577
      }
578
      else {
579
        dbUpdate(out, conn, siteScheduleID, contactEmail, documentListURL,
580
                 ldapDN, ldapPwd, unit, updateFrequency, dateLastHarvest);
581
      }
582
    }
583
584
    closeConnection(conn);
585
  }
586
587
588
  /**
589
   * Gets a database connection.
590
   *
591
   * @return  conn, the Connection object
592
   */
593
  private Connection getConnection() {
594
    Connection conn = null;
595
    SQLWarning warn;
596
597
    // Make the database connection
598
    try {
599
      System.out.println("Getting connection to Harvester tables");
600 2114 costa
      conn = DriverManager.getConnection(defaultDB, user, password);
601 2063 costa
602
      // If a SQLWarning object is available, print its warning(s).
603
      // There may be multiple warnings chained.
604
      warn = conn.getWarnings();
605
606
      if (warn != null) {
607
        while (warn != null) {
608
          System.out.println("SQLState: " + warn.getSQLState());
609
          System.out.println("Message:  " + warn.getMessage());
610
          System.out.println("Vendor: " + warn.getErrorCode());
611
          System.out.println("");
612
          warn = warn.getNextWarning();
613
        }
614
      }
615
    }
616
    catch (SQLException e) {
617
      System.out.println("Database access failed " + e);
618
    }
619
620
    return conn;
621
  }
622
623
624
  /**
625
   * Gets the date of last harvest value from the HARVEST_SITE_SCHEDULE table,
626
   * given a siteScheduleID value (the primary key).
627
   *
628
   * @param  conn            the connection
629
   * @param  siteScheduleID  the primary key
630
   * @return dateLastHarvest the string stored in the table, e.g.
631
   *                         "2004-04-30 00:00:00.0" or ""
632
   */
633
  private String getDateLastHarvest(Connection conn, int siteScheduleID) {
634
    String dateLastHarvest = "";
635
    String query = "SELECT DATELASTHARVEST FROM HARVEST_SITE_SCHEDULE " +
636
                   "WHERE SITE_SCHEDULE_ID=" + siteScheduleID;
637 2385 costa
	Statement stmt;
638 2063 costa
639 2385 costa
	try {
640
      stmt = conn.createStatement();
641
      ResultSet rs = stmt.executeQuery(query);
642 2063 costa
643 2385 costa
      while (rs.next()) {
644 2063 costa
        dateLastHarvest = rs.getString("DATELASTHARVEST");
645
        if (rs.wasNull()) {
646
          dateLastHarvest = "";  // Convert null value to empty string
647
        }
648 2385 costa
      }
649
650
      stmt.close();
651
    }
652 2063 costa
    catch (SQLException ex) {
653 2385 costa
      System.out.println("SQLException: " + ex.getMessage());
654
    }
655 2063 costa
656
    return dateLastHarvest;
657
  }
658
659
660
  /**
661
   * Gets the maximum value of an integer field from a table, given the table
662
   * name and the field name.
663
   *
664
   * @param tableName  the database table name
665
   * @param fieldName  the field name of the integer field in the table
666
   * @return  the maximum integer stored in the fieldName field of tableName
667
   */
668
  private int getMaxValue(Connection conn, String tableName, String fieldName) {
669
    int maxValue = 0;
670
    int fieldValue;
671 2385 costa
    String query = "SELECT " + fieldName + " FROM " + tableName;
672
    Statement stmt;
673 2063 costa
674 2385 costa
    try {
675
      stmt = conn.createStatement();
676
      ResultSet rs = stmt.executeQuery(query);
677
678
      while (rs.next()) {
679
        fieldValue = rs.getInt(fieldName);
680 2063 costa
        maxValue = Math.max(maxValue, fieldValue);
681 2385 costa
      }
682
683
      stmt.close();
684
    }
685 2063 costa
    catch (SQLException ex) {
686 2385 costa
      System.out.println("SQLException: " + ex.getMessage());
687
    }
688 2063 costa
689
    return maxValue;
690
  }
691
692
693
  /**
694
   * Gets the siteScheduleID value from the HARVEST_SITE_SCHEDULE table, given
695
   * the value of the ldapDN field.
696
   *
697
   * @param conn   the database connection
698
   * @param ldapDN the ldap DN string
699
   * @return  siteScheduleID, an integer, the primary key
700
   */
701
  private int getSiteScheduleID(Connection conn, String ldapDN) {
702
    String ldapDNValue;                       // value of LDAPDN field
703
    String query = "SELECT * FROM HARVEST_SITE_SCHEDULE";
704
    int siteScheduleID = 0;
705 2385 costa
    Statement stmt;
706 2063 costa
707 2385 costa
708
    try {
709
      stmt = conn.createStatement();
710
      ResultSet rs = stmt.executeQuery(query);
711
712
      while (rs.next()) {
713 2063 costa
        ldapDNValue = rs.getString("LDAPDN");
714 2171 costa
715 2063 costa
        if (ldapDNValue.equalsIgnoreCase(ldapDN)) {
716 2385 costa
          siteScheduleID = rs.getInt("SITE_SCHEDULE_ID");
717 2063 costa
        }
718 2385 costa
      }
719
720
      stmt.close();
721
    }
722 2063 costa
    catch (SQLException ex) {
723 2385 costa
      System.out.println("SQLException: " + ex.getMessage());
724
    }
725 2063 costa
726
    return siteScheduleID;
727
  }
728
729
730 4125 daigle
    /**
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 2063 costa
740 4125 daigle
		super.init(config);
741
		this.config = config;
742
		this.context = config.getServletContext();
743
		dirPath = context.getRealPath(CONFIG_DIR);
744 2063 costa
745 4125 daigle
		try {
746 6901 jones
		    ServletContext context = config.getServletContext();
747
			PropertyService.getInstance(context);
748 2063 costa
749 4125 daigle
			dbDriver = PropertyService.getProperty("database.driver");
750
			defaultDB = PropertyService.getProperty("database.connectionURI");
751
			password = PropertyService.getProperty("database.password");
752
			user = PropertyService.getProperty("database.user");
753
		} catch (ServiceException se) {
754
			System.out.println("Error initializing PropertyService: " + se.getMessage());
755
		} catch (PropertyNotFoundException pnfe) {
756
			System.out.println("Error reading property: " + pnfe.getMessage());
757
		}
758 2063 costa
759 4125 daigle
		// Load the jdbc driver
760
		try {
761
			Class.forName(dbDriver);
762
		} catch (ClassNotFoundException e) {
763
			System.out.println("Can't load driver " + e);
764
		}
765
	}
766
767
768 2063 costa
  /**
769 4125 daigle
	 * Surrounds a string with single quotes.
770
	 *
771
	 * @param str
772
	 *            the original string
773
	 * @return the quoted string
774
	 */
775 2063 costa
  private String quoteString(String str) {
776
    return "'" + str + "'";
777
  }
778
779
780
  /**
781
   * Reports the results of an insert or update to the client.
782
   *
783
   * @param out               the PrintWriter
784
   * @param ldapDN            the LDAP DN string
785
   * @param contactEmail      the email address of the site contact
786
   * @param documentListURL   the URL of the harvester document list at the site
787
   * @param updateFrequency   the harvest update frequency
788
   * @param unit              the unit (e.g. "days", "weeks", "months"
789
   * @param dateNextHarvest   the date of the next scheduled harvest
790
   */
791
  private void reportResults(PrintWriter out,
792
                             String ldapDN,
793
                             String contactEmail,
794
                             String documentListURL,
795
                             int updateFrequency,
796
                             String unit,
797
                             String dateNextHarvest
798
                            ) {
799
    out.println("Harvester registration updated for " + ldapDN);
800
    out.println("  Email Address:             " + contactEmail);
801 2170 costa
    out.println("  Harvest List URL:          " + documentListURL);
802 2063 costa
    out.println("  Harvest Frequency:         " + updateFrequency);
803
    out.println("  Unit:                      " + unit);
804
    out.println("");
805
    out.println("Next scheduled harvest date: " + dateNextHarvest);
806
  }
807
808
}