");
out.println("
");
}
private void printComments(PrintWriter out, Locale loc) throws IOException {
Connection conn = null;
try {
DateFormat fmt = DateFormat.getDateInstance(DateFormat.FULL, loc);
ResultSet results;
Statement stmt;
int rows, count;
conn = DriverManager.getConnection(jdbcURL, connectionProperties);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
results = stmt.executeQuery("SELECT NAME, EMAIL, CMT_DATE, "
+ "COMMENT, COMMENT_ID " + "FROM COMMENT "
+ "ORDER BY CMT_DATE");
out.println("
");
results.last();
results.next();
rows = results.getRow();
// pick a random row
rows = random.nextInt() % rows;
if (rows < 4) {
// if the random row is less than 4, print the first 4 rows
results.afterLast();
} else {
// otherwise go to the specified row, print the prior 5 rows
results.absolute(rows);
}
count = 0;
// print up to 5 rows going backwards from the randomly
// selected row
while (results.previous() && (count < 5)) {
String name, email, cmt;
Date date;
count++;
name = results.getString(1);
if (results.wasNull()) {
name = "Unknown User";
}
email = results.getString(2);
if (results.wasNull()) {
email = "user@host";
}
date = results.getDate(3);
if (results.wasNull()) {
date = new Date((new java.util.Date()).getTime());
}
cmt = results.getString(4);
if (results.wasNull()) {
cmt = "No comment.";
}
out.println("- " + name + " (" + email + ") on "
+ fmt.format(date) + "
");
cmt = noXML(cmt);
out.println("- " + cmt + "
");
}
out.println("
");
} catch (SQLException e) {
out.println("A database error occurred: " + e.getMessage());
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
/**
* Removes any XML-sensitive characters from a comment and replaces them
* with their character entities.
*
* @param cmt
* the raw comment
* @return the XML-safe comment
*/
private String noXML(String cmt) {
StringBuffer buff = new StringBuffer();
for (int i = 0; i < cmt.length(); i++) {
char c = cmt.charAt(i);
switch (c) {
case '<':
buff.append("<");
break;
case '>':
buff.append(">");
break;
case '&':
buff.append("&");
break;
case '"':
buff.append(""");
break;
default:
buff.append(c);
break;
}
}
return buff.toString();
}
/**
* This method escapes single quotes so that database statements are not
* messed up.
*
* @param comment
* the raw comment
* @return a comment with any quotes escaped
*/
private String fixComment(String comment) {
if (comment.indexOf("'") != -1) {
String tmp = "";
for (int i = 0; i < comment.length(); i++) {
char c = comment.charAt(i);
if (c == '\'') {
tmp = tmp + "\\'";
} else {
tmp = tmp + c;
}
}
comment = tmp;
}
return comment;
}
}