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

Legend:
Removed from v.322  
changed lines
  Added in v.958

  ViewVC Help
Powered by ViewVC 1.1.20