/[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 344 by torben, Thu Sep 24 21:04:34 2009 UTC revision 1557 by torben, Fri Jul 8 12:47:02 2011 UTC
# Line 1  Line 1 
1  package dk.thoerup.traininfoservice;  package dk.thoerup.traininfoservice;
2    
3    
4  import java.io.IOException;  import java.io.IOException;
5  import java.sql.Connection;  import java.io.StringWriter;
 import java.sql.PreparedStatement;  
 import java.sql.ResultSet;  
6  import java.sql.SQLException;  import java.sql.SQLException;
7    import java.util.logging.Level;
8    import java.util.logging.Logger;
9    
10  import javax.servlet.ServletException;  import javax.servlet.ServletException;
11    import javax.servlet.annotation.WebServlet;
12  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServlet;
13  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletRequest;
14  import javax.servlet.http.HttpServletResponse;  import javax.servlet.http.HttpServletResponse;
15    
16  import dk.thoerup.traininfoservice.DBConnection;  import org.simpleframework.xml.Serializer;
17    import org.simpleframework.xml.core.Persister;
18    
19    import dk.thoerup.android.traininfo.common.StationBean;
20    import dk.thoerup.traininfoservice.db.StationDAO;
21    
22  /**  /**
23   * Servlet implementation class LocateStations   * Servlet implementation class LocateStations
24   */   */
25    @WebServlet(urlPatterns={"/LocateStations"})
26  public class LocateStations extends HttpServlet {  public class LocateStations extends HttpServlet {
27          private static final long serialVersionUID = 1L;          private static final long serialVersionUID = 1L;
         
     /**  
      * @see HttpServlet#HttpServlet()  
      */  
     public LocateStations() {  
         super();  
         // TODO Auto-generated constructor stub  
     }  
       
28    
29            Logger logger = Logger.getLogger( LocateStations.class.toString() );
30    
31          protected String getStations(Connection conn, double latitude, double longitude, String name) throws SQLException {          StationDAO stationDao = new StationDAO();
                 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");  
                   
                   
                 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");  
32    
33                                  buff.append("<id>").append( res.getInt(1) ).append("</id>\n");  
34                                  buff.append("<name>").append( res.getString(2) ) .append("</name>\n");          protected String transformToIntList(String input) {            
35                                  buff.append("<latitude>").append( res.getDouble(3) ) .append("</latitude>\n");                  String strings[] = input.split(",");
36                                  buff.append("<longitude>").append( res.getDouble(4) ) .append("</longitude>\n");  
37                                  res.getString(5);                  StringBuffer sb = new StringBuffer();
38                                  buff.append("<fjerntog>").append( !res.wasNull() ) .append("</fjerntog>\n");                  sb.append("(");
39                                  res.getString(6);                  for (int i = 0; i<strings.length; i++) {
40                                  buff.append("<stog>").append( !res.wasNull() ) .append("</stog>\n");                          if (i>0) {
41                                  buff.append("<calcdist>").append( res.getInt(7) ) .append("</calcdist>\n");                                  sb.append(",");
                                   
                                 buff.append("</station>\n");                              
42                          }                          }
43                  } 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();  
44                  }                  }
45                  buff.append("</stations>\n");                  sb.append(")");
46                  return buff.toString();                  return sb.toString();          
47          }          }
48    
49          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
50                            protected StationBean getStations(HttpServletRequest req) throws SQLException {
51                  double latitude = -1.0;                  StationBean stations = null;
                 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") );  
52                                    
53                  String name = request.getParameter("name");                  boolean dummy = req.getParameter("dummy") != null;
54                                                    if (dummy == true)
55                  Connection conn = null;                          stations = new StationBean();
56                    
57                    if (req.getParameter("latitude") != null && req.getParameter("latitude") != null) {
58                            
59                            Statistics.getInstance().incrementStationLookupsLocation();
60                            
61                            double latitude = Double.parseDouble( req.getParameter("latitude") );
62                            double longitude = Double.parseDouble( req.getParameter("longitude") );
63                            if (dummy == false)
64                                    stations = stationDao.getByLocation(latitude, longitude);
65    
66                    } else if (req.getParameter("name") != null) {
67                            Statistics.getInstance().incrementStationLookupsName();
68                            String name = req.getParameter("name").trim();
69                            if (dummy == false)
70                                    stations = stationDao.getByName(name);
71    
72                    } else if (req.getParameter("list") != null) {
73                            Statistics.getInstance().incrementStationLookupsFavorites();
74                            String list = transformToIntList( req.getParameter("list"));
75                            if (dummy == false)
76                                    stations = stationDao.getByList(list);
77                    } else if (req.getParameter("dump") != null) {
78                            stations = stationDao.dumpAll();
79                    }
80                    return stations;
81            }
82    
83    
84            protected String formatStations(StationBean stations) throws ServletException {
85    
86                    Serializer serializer = new Persister();
87    
88                    StringWriter out = new StringWriter();
89    
90                  try {                  try {
91                          conn = DBConnection.getConnection();                          serializer.write(stations, out);
                           
                         String xml = getStations(conn, latitude, longitude, name);  
                           
                         response.setContentType("text/xml");  
                         response.getWriter().print(xml);  
                           
                         conn.close();  
                         conn = null;  
                           
92                  } catch (Exception e) {                  } catch (Exception e) {
93                          throw new ServletException(e);                          throw new ServletException(e);
                 } finally {  
                         try {  
                                 if (conn != null)  
                                         conn.close();  
                         } catch (Throwable t) {}  
94                  }                  }
95                    
96                    return out.toString();
97            }
98    
99            @Override
100            protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
101    
102    
103                    try {
104                            StationBean stations = getStations(request);
105    
106    
107                            if (stations != null){
108                                    String xml = formatStations(stations);
109    
110                                    response.setContentType("text/xml");
111                                    response.getWriter().print(xml);
112                            } else {
113                                    response.sendError(400, "not enough parameters");              
114                            }
115    
116    
117                    } catch (Exception e) {                        
118                            logger.log(Level.SEVERE, "Exception while finding stations", e);
119                            response.sendError(500);                                                
120                    }
121          }          }
122    
123  }  }

Legend:
Removed from v.344  
changed lines
  Added in v.1557

  ViewVC Help
Powered by ViewVC 1.1.20