Commit 7817a7cc authored by iwakeh's avatar iwakeh
Browse files

Prevent NPE and unclosed connections.

parent 02c9c5fb
......@@ -13,6 +13,7 @@ import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
......@@ -245,19 +246,21 @@ public class QueryServlet extends HttpServlet {
SortedSet<Long> allValidAfters = new TreeSet<>();
List<QueryResponse.Match> matches = new ArrayList<>();
SortedSet<String> allAddresses = new TreeSet<>();
try {
final long requestedConnection = System.currentTimeMillis();
Connection conn = this.ds.getConnection();
CallableStatement cs = conn.prepareCall(String.format(
Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
try (Connection conn = this.ds.getConnection()) {
try (CallableStatement cs = conn.prepareCall(String.format(
"{call search_by_address%s_date(?, ?)}",
relayIp.contains(":") ? 48 : 24));
relayIp.contains(":") ? 48 : 24))) {
cs.setString(1, address24Or48Hex);
Calendar utcCalendar = Calendar.getInstance(
TimeZone.getTimeZone("UTC"));
cs.setDate(2, new java.sql.Date(timestamp), utcCalendar);
ResultSet rs = cs.executeQuery();
try (ResultSet rs = cs.executeQuery()) {
while (rs.next()) {
long validafter = rs.getTimestamp(2, utcCalendar).getTime();
Timestamp ts = rs.getTimestamp(2, utcCalendar);
if (null == ts) {
continue;
}
long validafter = ts.getTime();
allValidAfters.add(validafter);
byte[] rawstatusentry = rs.getBytes(1);
if (null == rawstatusentry) {
......@@ -304,18 +307,21 @@ public class QueryServlet extends HttpServlet {
match.exit = exit;
matches.add(match);
}
rs.close();
cs.close();
conn.close();
} catch (SQLException e) {
this.logger.warn("Result set error. Returning 'null'.", e);
return null;
}
this.logger.info("Returned a database connection to the pool after {}"
+ " millis.", System.currentTimeMillis() - requestedConnection);
} catch (SQLException e) {
/* Nothing found. */
this.logger.warn("Callable statement error. Returning 'null'.", e);
return null;
}
} catch (Throwable e) { // Catch all problems left.
this.logger.warn("Database error. Returning 'null'.", e);
return null;
}
/* Create a query response object. */
QueryResponse response = new QueryResponse();
response.queryAddress = relayIp;
response.queryDate = dateFormat.format(timestamp);
......@@ -352,7 +358,6 @@ public class QueryServlet extends HttpServlet {
}
}
/* Return the query response. */
return response;
}
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment