package dk.thoerup.traininfoservice; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dk.thoerup.traininfoservice.DBConnection; /** * Servlet implementation class LocateStations */ public class LocateStations extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LocateStations() { super(); // TODO Auto-generated constructor stub } protected String getStations(Connection conn, double latitude, double longitude) throws SQLException { //inner select is workaround from not being able to use a calculated column directly in where clause final String SQL = "SELECT * FROM ( "+ " SELECT id,name,latitude,longitude,stationcode_fjrn,stationcode_stog, " + " earth_distance( ll_to_earth(latitude,longitude), ll_to_earth(?,?))::int AS calcdist " + " FROM trainstations " + " WHERE latitude IS NOT NULL AND longitude IS NOT NULL " + " ) AS trainstations2 " + "ORDER BY calcdist ASC " + "LIMIT 4 "; System.out.println(SQL); PreparedStatement stmt = null; ResultSet res = null; StringBuffer buff = new StringBuffer(); buff.append("\n"); buff.append("\n"); try { stmt = conn.prepareStatement(SQL); stmt.setDouble(1, latitude); stmt.setDouble(2, longitude); res = stmt.executeQuery(); while (res.next()) { buff.append("\n"); buff.append("").append( res.getInt(1) ).append("\n"); buff.append("").append( res.getString(2) ) .append("\n"); buff.append("").append( res.getDouble(3) ) .append("\n"); buff.append("").append( res.getDouble(4) ) .append("\n"); res.getString(5); buff.append("").append( !res.wasNull() ) .append("\n"); res.getString(6); buff.append("").append( !res.wasNull() ) .append("\n"); buff.append("").append( res.getInt(7) ) .append("\n"); buff.append("\n"); } } finally { if (res != null && !res.isClosed()) res.close(); if (stmt != null && !stmt.isClosed()) stmt.close(); } buff.append("\n"); return buff.toString(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { double latitude = Double.parseDouble( request.getParameter("latitude") ); double longitude = Double.parseDouble( request.getParameter("longitude") ); Connection conn = null; try { conn = DBConnection.getConnection(); String xml = getStations(conn, latitude, longitude); response.setContentType("text/xml"); response.getWriter().print(xml); conn.close(); conn = null; } catch (Exception e) { throw new ServletException(e); } finally { try { if (conn != null) conn.close(); } catch (Throwable t) {} } } }