/[projects]/android/TrainInfoService/src/dk/thoerup/traininfoservice/LocateStations.java
ViewVC logotype

Diff of /android/TrainInfoService/src/dk/thoerup/traininfoservice/LocateStations.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 301 by torben, Mon Sep 7 12:23:35 2009 UTC revision 858 by torben, Wed Jun 16 08:11:33 2010 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice;  package dk.thoerup.traininfoservice;
2    
3  import java.io.IOException;  import java.io.IOException;
 import java.sql.Connection;  
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
4  import java.sql.SQLException;  import java.sql.SQLException;
5    import java.util.List;
6    import java.util.logging.Level;
7    import java.util.logging.Logger;
8    
9  import javax.servlet.ServletException;  import javax.servlet.ServletException;
10  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServlet;
11  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletRequest;
12  import javax.servlet.http.HttpServletResponse;  import javax.servlet.http.HttpServletResponse;
13    
 import dk.thoerup.traininfoservice.DBConnection;  
   
14  /**  /**
15   * Servlet implementation class LocateStations   * Servlet implementation class LocateStations
16   */   */
17  public class LocateStations extends HttpServlet {  public class LocateStations extends HttpServlet {
18          private static final long serialVersionUID = 1L;          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 name,latitude,longitude,stationcode, " +  
                                                    "                     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("<?xml version=\"1.0\" ?>\n");  
                 buff.append("<stations>\n");  
                 try  
                 {  
                         stmt = conn.prepareStatement(SQL);  
                         stmt.setDouble(1, latitude);  
                         stmt.setDouble(2, longitude);  
                           
                         res = stmt.executeQuery();  
                           
                         while (res.next()) {  
                                 buff.append("<station>\n");  
19    
20                                  buff.append("<name>").append( res.getString(1) ) .append("</name>\n");          Logger logger = Logger.getLogger( LocateStations.class.toString() );
21                                  buff.append("<latitude>").append( res.getDouble(2) ) .append("</latitude>\n");  
22                                  buff.append("<longitude>").append( res.getDouble(3) ) .append("</longitude>\n");                                                  StationDAO stationDao = new StationDAO();
23                                  buff.append("<stationcode>").append( res.getString(4) ) .append("</stationcode>\n");  
24                                  buff.append("<calcdist>").append( res.getInt(5) ) .append("</calcdist>\n");  
25                                            protected String transformToIntList(String input) {            
26                                  buff.append("</station>\n");                                              String strings[] = input.split(",");
27    
28                    StringBuffer sb = new StringBuffer();
29                    sb.append("(");
30                    for (int i = 0; i<strings.length; i++) {
31                            if (i>0) {
32                                    sb.append(",");
33                          }                          }
34                  } finally {                          sb.append( Integer.parseInt(strings[i])); //by doing the integer conversion we ensure that it really is a integer
35                          if (res != null && !res.isClosed())                  }
36                                  res.close();                  sb.append(")");
37                          if (stmt != null && !stmt.isClosed())                  return sb.toString();          
38                                  stmt.close();          }
39    
40    
41            protected List<StationBean> getStations(HttpServletRequest req) throws SQLException {
42                    List<StationBean> stations = null;
43                    if (req.getParameter("latitude") != null && req.getParameter("latitude") != null) {
44                            
45                            Statistics.getInstance().incrementStationLookupsLocation();
46                            
47                            double latitude = Double.parseDouble( req.getParameter("latitude") );
48                            double longitude = Double.parseDouble( req.getParameter("longitude") );
49                            stations = stationDao.getByLocation(latitude, longitude);
50    
51                    } else if (req.getParameter("name") != null) {
52                            Statistics.getInstance().incrementStationLookupsName();
53                            String name = req.getParameter("name").trim();
54                            stations = stationDao.getByName(name);
55    
56                    } else if (req.getParameter("list") != null) {
57                            Statistics.getInstance().incrementStationLookupsFavorites();
58                            String list = transformToIntList( req.getParameter("list"));
59                            stations = stationDao.getByList(list);
60                  }                  }
61                    return stations;
62            }
63    
64    
65            protected String formatStations(List<StationBean> stations)  {
66    
67                    StringBuffer buff = new StringBuffer();
68    
69                    buff.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
70                    buff.append("<stations>\n");    
71    
72    
73                    for (int i=0; i<stations.size(); i++) {                
74                            StationBean station = stations.get(i);
75    
76                            buff.append("<station>\n");
77    
78                            buff.append("<id>").append( station.getId() ).append("</id>\n");
79                            buff.append("<name>").append( station.getName() ) .append("</name>\n");
80                            buff.append("<latitude>").append( station.getLatitude() ) .append("</latitude>\n");
81                            buff.append("<longitude>").append( station.getLongitude() ) .append("</longitude>\n");                  
82                            buff.append("<regional>").append( station.getRegional() != null ) .append("</regional>\n");
83                            buff.append("<strain>").append( station.getStrain() != null ) .append("</strain>\n");
84                            buff.append("<metro>").append( station.getMetro() != null ).append("</metro>\n");
85                            buff.append("<address>").append( station.getAddress() != null ?  station.getAddress() : "").append("</address>");                              
86                            buff.append("<calcdist>").append( station.getCalcdist() ) .append("</calcdist>\n");
87    
88                            buff.append("</station>\n");                            
89                    }
90                  buff.append("</stations>\n");                  buff.append("</stations>\n");
91                  return buff.toString();                  return buff.toString();
92          }          }
93    
94            @Override
95          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
96                    
97                  double latitude = Double.parseDouble( request.getParameter("latitude") );  
                 double longitude = Double.parseDouble( request.getParameter("longitude") );  
                                   
                 Connection conn = null;  
98                  try {                  try {
99                          conn = DBConnection.getConnection();                          List<StationBean> stations = getStations(request);
100                            
101                          String xml = getStations(conn, latitude, longitude);  
102                                                    if (stations != null){
103                          response.setContentType("text/xml");                                  String xml = formatStations(stations);
104                          response.getWriter().print(xml);  
105                                                            response.setContentType("text/xml");
106                          conn.close();                                  response.getWriter().print(xml);
107                          conn = null;                          } else {
108                                                            response.sendError(400, "not enough parameters");              
109                  } catch (Exception e) {                          }
110                          throw new ServletException(e);  
111                  } finally {  
112                          try {                  } catch (Exception e) {                        
113                                  if (conn != null)                          logger.log(Level.SEVERE, "Exception while finding stations", e);
114                                          conn.close();                          response.sendError(500);                                                
115                          } catch (Throwable t) {}                  }
                 }  
116          }          }
117    
118  }  }

Legend:
Removed from v.301  
changed lines
  Added in v.858

  ViewVC Help
Powered by ViewVC 1.1.20