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.client.net;
21  
22  import static triptracker.core.ConnectionState.*;
23  import static triptracker.core.Protocol.*;
24  
25  import java.io.IOException;
26  import java.util.ArrayList;
27  import java.util.Date;
28  import java.util.List;
29  
30  import triptracker.core.Coordinate;
31  import triptracker.core.Route;
32  import triptracker.core.Utils;
33  
34  public class GPSSocket extends SocketConnection<GPSSocketListener> {
35  	/***
36  	 * Logon a user of the type {@link triptracker.core.Protocol#SENDCLIENT}.
37  	 * 
38  	 * @param user username
39  	 * @param pass password
40  	 * @throws IOException on connection failure
41  	 */
42  	public void logon(String user, String pass) throws IOException {
43  		logon(SENDCLIENT, user, pass);
44  	}
45  
46  	/***
47  	 * Sends coordinates to server.
48  	 * 
49  	 * @param coord coordinate to send to server
50  	 */
51  	public void sendCoord(Coordinate coord){
52  		sendMessage(COORD_ADD, coord.getY(), coord.getX(),
53  				coord.getDateString());
54  	}
55     
56     /***
57      * Sends buffered coordinates to server.
58      * 
59      * @param coordBuffer string buffer of all coordinates
60      * @return true if send successful, false if send failed
61      */
62     public boolean sendTmpCoords(StringBuilder coordBuffer){
63  		// TODO It might be enough to check isClosed() because it might
64  		// work to send a message while the socket is still connecting.
65  		// Then it might send it right after successfully connecting.
66  		// This needs to be tested.
67  	   	// Same this as with sendMessage(...) except that this method uses
68  	    // sendMessage so it might not be needed here.
69  		if(isConnected()) {
70  //			GZIPOutputStream zipOutStream;
71  			int size = coordBuffer.toString().getBytes().length;
72  			sendMessage(COORD_BUFFER_ADD, size);
73  //			try {
74  //			System.out.println("Sending zipped coordBuffer: "
75  //					+ coordBuffer.toString());
76  			sendMessage(coordBuffer);
77  				
78  //		        FileOutputStream fout = new FileOutputStream("test.gz");
79  //		        GZIPOutputStream out = new GZIPOutputStream(fout);
80  	
81  //				ZipOutputStream zipOutStream = new ZipOutputStream(outStream);
82  //				DeflaterOutputStream zipOutStream =
83  //						new DeflaterOutputStream(outStream); 
84  //				GZIPOutputStream zipOutStream =
85  //						new GZIPOutputStream(outStream, size);
86  
87  //				.toString().getBytes(),0,size);
88  //				send(zipOutStream, true, coordBuffer,0,size);
89  				
90  //				send(zipOutStream, true, coordBuffer);
91  //				zipOutStream.write(coordBuffer.toString().getBytes(),0,size);
92  //				zipOutStream.write(coordBuffer.toString().getBytes());
93  				
94  /*				byte[] x = new byte[2];
95  				x[0] = 1;
96  				x[1] = 2;
97  */
98  //				zipOutStream.write(x);//coordBuffer.toString().getBytes());
99  
100 //				zipOutStream.flush();
101 //				zipOutStream.finish();
102 //				zipOutStream = null;				
103 			
104 /*			} catch (IOException e) {
105 				System.out.println("Problem sending buffered coords: " + e);
106 				e.printStackTrace();
107 				return false;
108 			}
109 */	//		System.out.println("Zipped buffer is sent");
110 			return true;
111 		}
112 //		System.out.println("Zipping gjekk gale!");
113 		return false;
114    }
115    
116    /***
117     * Generates new route
118     * @param description
119     */
120    public void makeRoute(String description){
121 	   sendMessage(MAKE_ROUTE, description);
122    }
123    
124    /*** For locking route when it is finnished. */
125    public void lockRoute(int route){
126 	   sendMessage(ROUTE_LOCK, route);
127    }
128    
129    protected void routesReceived(List<Route> routes) {
130 	   for (GPSSocketListener listener : listeners) {
131 		   try {
132 			   listener.routeList(routes);
133 		   } catch (RuntimeException e) {
134 			   brokenListener(listener, e);
135 		   }
136 	   }
137    }
138    
139 	/***
140 	 * {@inheritDoc}
141 	 */
142 	@Override
143 	public void addListener(GPSSocketListener listener) {
144 		listeners.add(listener);
145 	}
146 	
147    	/***
148 	 * {@inheritDoc}
149 	 */
150 	@Override
151 	public void removeListener(GPSSocketListener listener) {
152 		listeners.remove(listener);
153 	}
154 	
155    	/***
156 	 * {@inheritDoc}
157 	 */
158 	@Override
159 	protected boolean messageHandler(String message){
160 		String[] msg = message.split(DELIMITER, -1);
161 //		System.out.println("Message: " + Arrays.toString(msg));
162 
163 		try {
164 			// Handle message based on first field (msg[0]).
165 			switch (Integer.parseInt(msg[0])) {
166 			case AUTH_FAIL: //=-1
167 				connectionUpdate(AUTH_FAILED);
168 				break;
169 			case AUTH_OK: //=0
170 				connectionUpdate(AUTH_SUCCESS);
171 				break;
172 			case VIEW_ROUTES:
173 				List<Route> routes = new ArrayList<Route>();
174 
175 				for (int i = 1; i < msg.length; i += 6) {
176 					int routeId = Integer.parseInt(msg[i]);
177 					int userId = Integer.parseInt(msg[i + 1]);
178 					String description = msg[i + 2];
179 					boolean active = Utils.strToBool(msg[i + 3]);
180 					Date date = Utils.parseDate(msg[i + 4]);
181 					boolean visible = Utils.strToBool(msg[i + 5]);
182 					Route route = new Route(routeId, userId, description,
183 							active, visible, date);
184 					routes.add(route);
185 				}
186 				routesReceived(routes);
187 				break;
188 			case MAKE_ROUTE:
189 				routeCreated(Integer.parseInt(msg[1]));
190 				break;
191 			default:
192 				invalidMessage(message);
193 				break;
194 			}
195 		} catch (NumberFormatException num) {
196 			System.out.println("NumberFormatException: " + num);
197 			num.printStackTrace();
198 			invalidMessage(message);
199 		}
200 		
201 		return true;
202 	}
203 
204 	/***
205 	 * Publish a route created message event to all listeners. This signals that
206 	 * a previous request to create a route has been accepted.
207 	 * 
208 	 * @param routeId route ID of the new route
209 	 */
210 	protected void routeCreated(int routeId) {
211 	   for (GPSSocketListener listener : listeners) {
212 		   try {
213 			   listener.routeCreated(routeId);
214 		   } catch (RuntimeException e) {
215 			   brokenListener(listener, e);
216 		   }
217 	   }
218 	}
219 }