improved logging and error handling

This commit is contained in:
Steve Waterworth
2019-01-25 12:33:49 +00:00
parent d08e90c589
commit e874b66672

View File

@@ -21,7 +21,7 @@ import com.google.gson.Gson;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.sql.Connection; import java.sql.Connection;
import java.sql.Statement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import java.sql.ResultSetMetaData;
import java.sql.Types; import java.sql.Types;
@@ -130,8 +130,8 @@ public class Main {
Spark.get("/calc/:uuid", (req, res) -> { Spark.get("/calc/:uuid", (req, res) -> {
double homeLat = 51.164896; double homeLat = 51.164896;
double homeLong = 7.068792; double homeLong = 7.068792;
String data;
res.header("Content-Type", "application/json");
Location location = getLocation(req.params(":uuid")); Location location = getLocation(req.params(":uuid"));
Ship ship = new Ship(); Ship ship = new Ship();
if(location != null) { if(location != null) {
@@ -141,11 +141,15 @@ public class Main {
double cost = Math.rint(distance * 5) / 100.0; double cost = Math.rint(distance * 5) / 100.0;
ship.setDistance(distance); ship.setDistance(distance);
ship.setCost(cost); ship.setCost(cost);
res.header("Content-Type", "application/json");
data = new Gson().toJson(ship);
} else { } else {
res.status(500); data = "no location";
logger.warn(data);
res.status(400);
} }
return new Gson().toJson(ship); return data;
}); });
Spark.post("/confirm/:id", (req, res) -> { Spark.post("/confirm/:id", (req, res) -> {
@@ -188,20 +192,21 @@ public class Main {
private static Location getLocation(String uuid) { private static Location getLocation(String uuid) {
Location location = null; Location location = null;
Connection conn = null; Connection conn = null;
Statement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
String query = "select latitude, longitude from cities where uuid = " + uuid; String query = "select latitude, longitude from cities where uuid = ?";
try { try {
conn = cpds.getConnection(); conn = cpds.getConnection();
stmt = conn.createStatement(); stmt = conn.prepareStatement(query);
rs = stmt.executeQuery(query); stmt.setInt(1, Integer.parseInt(uuid));
rs = stmt.executeQuery();
while(rs.next()) { while(rs.next()) {
location = new Location(rs.getDouble(1), rs.getDouble(2)); location = new Location(rs.getDouble(1), rs.getDouble(2));
break; break;
} }
} catch(Exception e) { } catch(Exception e) {
logger.error("Query exception", e); logger.error("Location exception", e);
} finally { } finally {
DbUtils.closeQuietly(conn, stmt, rs); DbUtils.closeQuietly(conn, stmt, rs);
} }