View Javadoc

1   /*
2    * Trip Tracker, a real-time position tracking system for the Internet.
3    * Copyright (C) 2006  Team Trip Tracker
4    *
5    * This program is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU General Public License as published by the
7    * Free Software Foundation; either version 2 of the License, or (at your
8    * option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful, but
11   * WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13   * General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License along
16   * with this program; if not, write to the Free Software Foundation, Inc.,
17   * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18   */
19  
20  package triptracker.server;
21  
22  import static triptracker.core.Protocol.*;
23  
24  import java.io.IOException;
25  import java.net.Socket;
26  import java.util.List;
27  import java.util.zip.GZIPOutputStream;
28  
29  import triptracker.core.Coordinate;
30  import triptracker.core.Route;
31  import triptracker.core.User;
32  
33  /***
34   * Handler for map clients. 
35   */
36  public class MapHandler extends ClientHandler implements CoordListener {
37  	GPSHandler handler = null;
38  	/***
39  	 * Sets up socket streams for communication with a map client and creates
40  	 * the message reader thread for message processing. 
41  	 * 
42  	 * @param server main server instance
43  	 * @param socket client communication socket
44  	 * @param user client user data
45  	 * @throws IOException on connection failure
46  	 */
47  	public MapHandler(Server server, Socket socket, User user) throws IOException {
48  		super(server, socket, user);
49  	}
50  
51  	/***
52  	 * TODO (harald) Not finished yet!!! The method making sure everything is
53  	 * being shutdown before the handler deletes itself.
54  	 */	
55  	@Override
56  	protected void stopHandler() {
57  //		System.out.println("Removing mapHandler from gpsHandler. " + handler);
58  		if (handler != null)
59  			handler.removeCoordListener(this);
60  		server.removeMapHandler(this);
61  	}
62  
63  	/***
64  	 * {@inheritDoc}
65  	 */
66  	@Override
67  	protected boolean messageHandler(String message) {
68  		String[] msg = message.split(DELIMITER,-1);
69  
70  		try {
71  			switch (Integer.parseInt(msg[0])) {
72  			case QUIT:
73  				log("Exiting thread and closing connection.");
74  				stopHandler();
75  				return false;
76  			case USERS_GET:
77  				 // For getting all users in database.
78  				getUsers();
79  				break;
80  			case USER_GET:
81  				User user = db.getUser(Integer.parseInt(msg[1]));
82  				sendMessage(out, USER_GET, user.getUserId(),
83  						user.getUsername());
84  				log("Sent user: " + user.getUserId() + " to client");
85  				
86  //				out.println(USER_GET + ";" + user.getUserId() + ";" + user.getUsername());
87  				break;
88  			case VIEW_ROUTES:
89  				viewRoutes((msg[1]));
90  				break;
91  			case ROUTE_GET:
92  				// For getting complete route.
93  				getRoute(Integer.parseInt(msg[1]));
94  				break;
95  			case REALTIME:
96  				StringBuilder routeString = new StringBuilder();
97  
98  				for (GPSHandler gpsHandler : server.getGPSHandlers()) {
99  					Route route = gpsHandler.getActiveRoute();
100 					if (route != null) {
101 						makeMsg(DELIMITER, routeString, route.getRouteId(),
102 								route.getUserId(), route.getDescription(),
103 								route.isActive(), route.getLastUpdateString(), route.getVisible());
104 					} else { 
105 						log("Realtime routes = null");
106 					}
107 				}
108 				log("Sending realtime routes.");
109 				sendMessage(out, VIEW_ROUTES, routeString);
110 				break;
111 			default:
112 				// Invalid/unsupported message.
113 				log("Invalid message: " + message);
114 				server.invalidMessage(this, message);
115 				break;
116 			}
117 		} catch (NumberFormatException num) {
118 			log("Invalid indata from client: " + num);
119 			server.invalidMessage(this, message);
120 		} 
121 		return true;
122 	}
123 	
124 	/***
125 	 * Sends newly recieved coordinate to mapClient.
126 	 */
127 	public void coordinateUpdate(Coordinate coord) {
128 		sendMessage(out, COORD_ADD, route.getRouteId(), coord.getY(),
129 				coord.getX(), coord.getDateString());
130 		log("New coordinate sent to client");
131 	}
132 	
133 	public void coordinateBufferUpdate(String[] coords) {
134 		StringBuilder bufferString = new StringBuilder();
135 		
136 		makeMsg(DELIMITER, bufferString, route.getRouteId());
137 		
138 		for (int i = 0; i < coords.length; i += 3) {
139 			double latitude = Double.parseDouble(coords[i]);
140 			double longitude = Double.parseDouble(coords[i + 1]);
141 			String time = coords[i + 2];
142 			
143 			makeMsg(DELIMITER, bufferString, latitude, longitude,
144 					time);
145 //			coordinateUpdate(coord);
146 		}
147 		
148 		sendMessage(out, COORD_BUFFER_ADD, bufferString);
149 		log("Sent buffered coordinates to client, size: " + coords.length);
150 	}
151 	
152 	/***
153 	 * Will stop the logging of a tracker.
154 	 */
155 	public void stopLogging(GPSHandler gpsHandler) {
156 		sendMessage(out, REALTIME, false);// gpsHandler.getRoute().");
157 //		if (handler != null)
158 //			handler.removeCoordListener(this);
159 		// TODO Implement method
160 	}
161 	
162 	/***
163 	 * Signals that tracking will start
164 	 */
165 	public void startLogging(GPSHandler gpsHandler) {
166 		sendMessage(out, REALTIME, true);// gpsHandler.getRoute().");
167 //		if (handler != null)
168 //			handler.removeCoordListener(this);
169 		// TODO Implement method
170 	}
171 	
172 	/***
173 	 * Sends a list of users to client.
174 	 */
175 	protected void getUsers() {
176 		List<User> users = db.getUserList();
177 		StringBuilder userString = new StringBuilder();
178 		
179 		for (User user : users) {
180 			makeMsg(DELIMITER, userString, user.getUserId(),
181 					user.getUsername());
182 		}
183 		log("Sending user list: " + userString.toString());
184 		sendMessage(out, USERS_GET, userString.toString());
185 	}
186 	
187 	/***
188 	 * For recieving a complete route from database.
189 	 * Will allso check if route is beeing plotted realtime, and start listening to route
190 	 */
191 	protected void getRoute(int routeId) {
192 
193 //		BufferedWriter gzipOutBuffer = new BufferedWriter(
194 //				new OutputStreamWriter(new GZIPOutputStream(output)));
195 		
196 		route = new Route(routeId);
197 		
198 		handler = server.getGPSHandler(route);
199 		if (handler != null)
200 			handler.addCoordListener(this);
201 //		else {
202 //			sendMessage(out, SET_ROUTE, "Route not beeing tracked");
203 //		}
204 		log("Is tracking route: " + route.getRouteId());
205 		
206 		List<Coordinate> coords = db.getCoordinates(routeId);
207 		
208 		StringBuilder routeString = new StringBuilder();
209 		for (Coordinate coord : coords) {
210 			makeMsg(DELIMITER, routeString, coord.getY(), coord.getX(),
211 					coord.getDateString());
212 		}
213 		
214 		// TODO Legg til siste koordinat, aktiv
215 		if (routeString.toString().trim().length() == 0)
216 			sendMessage(ROUTE_GET, routeId);
217 		else
218 			sendMessage(ROUTE_GET, routeId, routeString);
219 		
220 //		sendMessage(out, ROUTE_GET, routeId);
221 //		GZIPOutputStream zipout;
222 //		try {
223 //			zipout = new GZIPOutputStream(out);
224 //			zipout.write(routeString.toString().getBytes());
225 //		} catch (IOException e) {
226 //			// TODO Auto-generated catch block
227 //			e.printStackTrace();
228 //		}
229 
230 //		System.out.println("Sent zipped route");
231 		
232 		log("Sent route " + routeId + " to " + user);
233 	}
234 }