aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAnton Tananaev <anton.tananaev@gmail.com>2013-01-12 00:56:03 +1300
committerAnton Tananaev <anton.tananaev@gmail.com>2013-01-12 00:56:03 +1300
commit900cbdd8b23cf0e9266523b21f2251510fcc1468 (patch)
treeffe824e491bd01a2df1e144a820ec175834d07f8
parentf10f359d0531417b11a2a0fa1862efd6eae742b9 (diff)
downloadtraccar-server-900cbdd8b23cf0e9266523b21f2251510fcc1468.tar.gz
traccar-server-900cbdd8b23cf0e9266523b21f2251510fcc1468.tar.bz2
traccar-server-900cbdd8b23cf0e9266523b21f2251510fcc1468.zip
Integrate new web interface
-rw-r--r--default.cfg68
-rw-r--r--src/org/traccar/Server.java20
-rw-r--r--src/org/traccar/TrackerEventHandler.java11
-rw-r--r--src/org/traccar/helper/NamedParameterStatement.java6
-rw-r--r--src/org/traccar/http/WebServer.java194
-rw-r--r--src/org/traccar/model/DataManager.java9
-rw-r--r--src/org/traccar/model/DatabaseDataManager.java130
-rw-r--r--test/org/traccar/protocol/TestDataManager.java21
8 files changed, 104 insertions, 355 deletions
diff --git a/default.cfg b/default.cfg
index 6409637bb..8d4df93c7 100644
--- a/default.cfg
+++ b/default.cfg
@@ -14,59 +14,17 @@
<!-- Database refresh delay in seconds -->
<entry key="database.refreshDelay">300</entry>
- <!-- Create database schema -->
- <entry key="database.initialize">
- CREATE TABLE IF NOT EXISTS devices (id INT IDENTITY, imei VARCHAR(16));
- CREATE TABLE IF NOT EXISTS positions (device_id INT, time TIMESTAMP, valid BOOLEAN, latitude DOUBLE, longitude DOUBLE, speed DOUBLE, course DOUBLE, power DOUBLE);
- </entry>
-
<!-->
- id - Integer
+ id - Long
imei - String
<-->
<entry key="database.selectDevice">
- SELECT id, imei
+ SELECT id, uniqueId as imei
FROM devices;
</entry>
<!-->
- imei - String
- <-->
- <entry key="database.insertDevice">
- INSERT INTO devices (imei)
- VALUES (:imei);
- </entry>
-
- <!-->
- id - Integer
- imei - String
- <-->
- <entry key="database.updateDevice">
- UPDATE devices
- SET imei = :imei
- WHERE id = :id;
- </entry>
-
- <!-->
- id - Integer
- <-->
- <entry key="database.deleteDevice">
- DELETE FROM devices
- WHERE id = :id;
- </entry>
-
- <!-->
- device_id - Integer
- <-->
- <entry key="database.selectPosition">
- SELECT *
- FROM positions
- WHERE device_id = :device_id
- ORDER by time DESC;
- </entry>
-
- <!-->
- device_id - Integer
+ device_id - Long
time - Date
valid - Boolean
latitude - Double
@@ -76,16 +34,28 @@
power - Double (NULL for some protocols)
extended_info - String (XML)
<-->
+ <!-->
+ H2 - SCOPE_IDENTITY()
+ MySQL - LAST_INSERT_ID()
+ <-->
<entry key="database.insertPosition">
- INSERT INTO positions (device_id, time, valid, latitude, longitude, speed, course, power)
- VALUES (:device_id, :time, :valid, :latitude, :longitude, :speed, :course, :power);
+ INSERT INTO positions (device_id, time, valid, latitude, longitude, altitude, speed, course, power)
+ VALUES (:device_id, :time, :valid, :latitude, :longitude, :altitude, :speed, :course, :power);
+ </entry>
+
+ <!-->
+ device_id - Long
+ id - Long
+ <-->
+ <entry key="database.updateLatestPosition">
+ UPDATE devices SET latestPosition_id = :id WHERE id = :device_id;
</entry>
<!-- Web interface -->
<entry key="http.enable">true</entry>
<!--<entry key="http.address"></entry>-->
<entry key="http.port">8082</entry>
- <entry key="http.application">/home/user/Documents/traccar-web/target/traccar-web-1.0-SNAPSHOT.war</entry>
+ <entry key="http.application">/home/user/Documents/traccar-web/traccar-web.war</entry>
<!-- Geocoder options -->
<entry key="geocoder.enable">false</entry>
@@ -190,5 +160,5 @@
<!-- GT06 server configuration -->
<entry key="gt06.enable">true</entry>
<entry key="gt06.port">5023</entry>
-
+
</properties>
diff --git a/src/org/traccar/Server.java b/src/org/traccar/Server.java
index d4e4a94cb..e1d9efa3d 100644
--- a/src/org/traccar/Server.java
+++ b/src/org/traccar/Server.java
@@ -111,17 +111,11 @@ public class Server {
initMeitrackServer(properties);
initSkypatrolServer(properties);
initGt02Server(properties);
- initGt06Server(properties);
+ initGt06Server(properties);
// Initialize web server
if (Boolean.valueOf(properties.getProperty("http.enable"))) {
- Integer port = Integer.valueOf(properties.getProperty("http.port", "8082"));
- String address = properties.getProperty("http.address");
- if (address != null) {
- webServer = new WebServer(address, port, dataManager);
- } else {
- webServer = new WebServer(port, dataManager);
- }
+ webServer = new WebServer(properties);
}
}
@@ -144,11 +138,11 @@ public class Server {
for (Object server: serverList) {
((TrackerServer) server).stop();
}
-
+
// Release resources
GlobalChannelFactory.release();
GlobalTimer.release();
-
+
if (webServer != null) {
webServer.stop();
}
@@ -638,7 +632,7 @@ public class Server {
serverList.add(server);
}
}
-
+
/**
* Init EV603 server
*/
@@ -666,7 +660,7 @@ public class Server {
serverList.add(server);
}
}
-
+
/**
* Init V680 server
*/
@@ -694,7 +688,7 @@ public class Server {
serverList.add(server);
}
}
-
+
/**
* Init PT502 server
*/
diff --git a/src/org/traccar/TrackerEventHandler.java b/src/org/traccar/TrackerEventHandler.java
index 11cf41fad..538e71cdf 100644
--- a/src/org/traccar/TrackerEventHandler.java
+++ b/src/org/traccar/TrackerEventHandler.java
@@ -38,7 +38,7 @@ public class TrackerEventHandler extends IdleStateAwareChannelHandler {
super();
dataManager = newDataManager;
}
-
+
private void processSinglePosition(Position position) {
if (position == null) {
Log.info("null message");
@@ -58,7 +58,10 @@ public class TrackerEventHandler extends IdleStateAwareChannelHandler {
// Write position to database
try {
- dataManager.addPosition(position);
+ Long id = dataManager.addPosition(position);
+ if (id != null) {
+ dataManager.updateLatestPosition(position.getDeviceId(), id);
+ }
} catch (Exception error) {
Log.info("Exception during query execution");
Log.warning(error.getMessage());
@@ -82,7 +85,7 @@ public class TrackerEventHandler extends IdleStateAwareChannelHandler {
Log.info("Closing connection by disconnect");
e.getChannel().close();
}
-
+
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
Log.info("Closing connection by exception");
@@ -94,5 +97,5 @@ public class TrackerEventHandler extends IdleStateAwareChannelHandler {
Log.info("Closing connection by timeout");
e.getChannel().close();
}
-
+
}
diff --git a/src/org/traccar/helper/NamedParameterStatement.java b/src/org/traccar/helper/NamedParameterStatement.java
index cbbc187da..500fbe4b3 100644
--- a/src/org/traccar/helper/NamedParameterStatement.java
+++ b/src/org/traccar/helper/NamedParameterStatement.java
@@ -16,8 +16,8 @@
package org.traccar.helper;
import java.sql.*;
-import java.util.Date;
import java.util.*;
+import java.util.Date;
public class NamedParameterStatement {
@@ -40,7 +40,7 @@ public class NamedParameterStatement {
* Database connection
*/
private AdvancedConnection connection;
-
+
private int autoGeneratedKeys;
/**
@@ -108,7 +108,7 @@ public class NamedParameterStatement {
return parsedQuery.toString();
}
-
+
public void reset(boolean resetConnection) throws SQLException {
if (statement != null) {
statement.close();
diff --git a/src/org/traccar/http/WebServer.java b/src/org/traccar/http/WebServer.java
index aac334cc6..59c212d01 100644
--- a/src/org/traccar/http/WebServer.java
+++ b/src/org/traccar/http/WebServer.java
@@ -21,14 +21,19 @@ import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.util.Iterator;
+import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import javax.naming.Context;
+import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import javax.sql.DataSource;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
+import org.eclipse.jetty.webapp.WebAppContext;
import org.traccar.helper.Log;
import org.traccar.model.DataManager;
import org.traccar.model.Device;
@@ -41,183 +46,40 @@ public class WebServer {
private Server server;
- public class WebHandler extends AbstractHandler {
-
- private DataManager dataManager;
-
- public static final int BUFFER_SIZE = 1024;
-
- public WebHandler(DataManager dataManager) {
- this.dataManager = dataManager;
- }
-
- public void handleIndex(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)
- throws IOException, ServletException {
-
- response.setContentType("text/html");
-
- InputStream in = this.getClass().getClassLoader().getResourceAsStream("web/index.html");
- OutputStream out = response.getOutputStream();
-
- byte[] buffer = new byte[BUFFER_SIZE];
- int count;
- while ((count = in.read(buffer)) != -1) {
- out.write(buffer, 0, count);
- }
- out.flush();
- }
-
- public void handleIcon(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)
- throws IOException, ServletException {
-
- response.setContentType("image/x-icon");
-
- InputStream in = this.getClass().getClassLoader().getResourceAsStream("web/favicon.ico");
- OutputStream out = response.getOutputStream();
-
- byte[] buffer = new byte[BUFFER_SIZE];
- int count;
- while ((count = in.read(buffer)) != -1) {
- out.write(buffer, 0, count);
- }
- out.flush();
- }
-
- private Device parseDevice(String json) {
-
- Pattern pattern = Pattern.compile("\\{\"id\":(\\d+),\"imei\":\"(.*)\"\\}");
- Matcher parser = pattern.matcher(json);
- if (parser.matches()) {
- Device device = new Device();
- device.setId(Long.valueOf(parser.group(1)));
- device.setImei(parser.group(2));
- return device;
- }
-
- return null;
- }
-
- // TODO: separate method into small parts
- public void handleData(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)
- throws IOException, ServletException {
-
- response.setContentType("application/json");
-
- PrintWriter out = response.getWriter();
-
- try {
- if (target.equals("/devices.json")) {
-
- String action = request.getParameter("action");
- if (action == null) {
- Iterator<Device> i = dataManager.getDevices().iterator();
- out.print("{'success':true,'results':[");
- while (i.hasNext()) {
- Device device = i.next();
- out.format("{'id':%d,'imei':'%s'}",
- device.getId(),
- device.getImei());
- if (i.hasNext()) out.print(",");
- }
- } else if (action.equals("create")) {
- Device device = parseDevice(request.getReader().readLine());
- dataManager.addDevice(device);
- out.print("{'success':true,'results':[");
- out.format("{'id':%d,'imei':'%s'}",
- device.getId(),
- device.getImei());
- } else if (action.equals("update")) {
- Device device = parseDevice(request.getReader().readLine());
- dataManager.updateDevice(device);
- out.print("{'success':true,'results':[");
- out.format("{'id':%d,'imei':'%s'}",
- device.getId(),
- device.getImei());
- } else if (action.equals("destroy")) {
- Device device = parseDevice(request.getReader().readLine());
- dataManager.removeDevice(device);
- out.print("{'success':true,'results':[");
- }
-
- } else if (target.equals("/positions.json")) {
-
- out.print("{'success':true,'results':[");
- String deviceId = request.getParameter("deviceId");
- if (deviceId != null) {
- Iterator<Position> i = dataManager.getPositions(Long.valueOf(deviceId)).iterator();
- while (i.hasNext()) {
- Position position = i.next();
- out.format("{'device_id':%d,'time':'%tF %tT','valid':%b,'latitude':%f,'longitude':%f,'speed':%f,'course':%f}",
- position.getDeviceId(),
- position.getTime(), position.getTime(),
- position.getValid(),
- position.getLatitude(),
- position.getLongitude(),
- position.getSpeed(),
- position.getCourse());
- if (i.hasNext()) out.print(",");
- }
- }
-
- }
- } catch (Exception error) {
- out.print("{'success':false,'results':[");
- Log.warning(error.getMessage());
- }
-
- out.print("]}");
- out.flush();
- }
-
- public void handleOther(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)
- throws IOException, ServletException {
- response.sendRedirect(response.encodeRedirectURL("/"));
- }
+ private void initDataSource(Properties properties) {
+ try {
- @Override
- public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)
- throws IOException, ServletException
- {
- if (target.equals("/") || target.equals("/index.html")) {
- handleIndex(target, baseRequest, request, response);
- } else if (target.equals("/favicon.ico")) {
- handleIcon(target, baseRequest, request, response);
- } else if (target.matches("/.+\\.json")) {
- handleData(target, baseRequest, request, response);
- } else {
- handleOther(target, baseRequest, request, response);
- }
- }
- }
+ Context context = new InitialContext();
- public WebServer(Integer port, DataManager dataManager) {
- server = new Server(port);
- server.setHandler(new WebHandler(dataManager));
+ Class clazz = Class.forName(properties.getProperty("database.dataSource"));
- /*WebAppContext webapp = new WebAppContext();
- webapp.setContextPath("/");
- webapp.setWar("/home/user/Documents/traccar-web/target/traccar-web-1.0-SNAPSHOT.war");
- try {
-
- Context context = new InitialContext();
-
- Class clazz = Class.forName("org.h2.jdbcx.JdbcDataSource");
-
DataSource ds = (DataSource) clazz.newInstance();
- clazz.getMethod("setURL", String.class).invoke(ds, "jdbc:h2:/home/user/Documents/traccar/target/database2");
- clazz.getMethod("setUser", String.class).invoke(ds, "sa");
- //clazz.getMethod("setPassword", String.class).invoke(ds, "");
+ clazz.getMethod("setURL", String.class).invoke(ds, properties.getProperty("database.url"));
+ clazz.getMethod("setUser", String.class).invoke(ds, properties.getProperty("database.user"));
+ clazz.getMethod("setPassword", String.class).invoke(ds, properties.getProperty("database.password"));
context.bind("java:/DefaultDS", ds);
} catch (Exception error) {
+ Log.warning(error.getMessage());
}
- server.setHandler(webapp);*/
}
- public WebServer(String address, Integer port, DataManager dataManager) {
- server = new Server(new InetSocketAddress(address, port));
- server.setHandler(new WebHandler(dataManager));
+ public WebServer(Properties properties) {
+ String address = properties.getProperty("http.address");
+ Integer port = Integer.valueOf(properties.getProperty("http.port", "8082"));
+ if (address == null) {
+ server = new Server(port);
+ } else {
+ server = new Server(new InetSocketAddress(address, port));
+ }
+
+ initDataSource(properties);
+
+ WebAppContext webapp = new WebAppContext();
+ webapp.setContextPath("/");
+ webapp.setWar(properties.getProperty("http.application"));
+ server.setHandler(webapp);
}
public void start() {
diff --git a/src/org/traccar/model/DataManager.java b/src/org/traccar/model/DataManager.java
index 423c540da..4a5aaa348 100644
--- a/src/org/traccar/model/DataManager.java
+++ b/src/org/traccar/model/DataManager.java
@@ -26,17 +26,12 @@ public interface DataManager {
* Manage devices
*/
public List<Device> getDevices() throws Exception;
- public void addDevice(Device device) throws Exception;
- public void updateDevice(Device device) throws Exception;
- public void removeDevice(Device device) throws Exception;
public Device getDeviceByImei(String imei) throws Exception;
- public Device getDeviceByPhoneNumber(String phoneNumber) throws Exception;
- public Device getDeviceByUniqueId(String uniqueId) throws Exception;
/**
* Manage positions
*/
- public void addPosition(Position position) throws Exception;
- public List<Position> getPositions(Long deviceId) throws Exception;
+ public Long addPosition(Position position) throws Exception;
+ public void updateLatestPosition(Long deviceId, Long positionId) throws Exception;
}
diff --git a/src/org/traccar/model/DatabaseDataManager.java b/src/org/traccar/model/DatabaseDataManager.java
index 073d6ef71..ee86e6370 100644
--- a/src/org/traccar/model/DatabaseDataManager.java
+++ b/src/org/traccar/model/DatabaseDataManager.java
@@ -18,7 +18,6 @@ package org.traccar.model;
import java.sql.*;
import java.util.*;
import org.traccar.helper.AdvancedConnection;
-import org.traccar.helper.Log;
import org.traccar.helper.NamedParameterStatement;
/**
@@ -35,11 +34,8 @@ public class DatabaseDataManager implements DataManager {
* Database statements
*/
private NamedParameterStatement queryGetDevices;
- private NamedParameterStatement queryAddDevice;
- private NamedParameterStatement queryUpdateDevice;
- private NamedParameterStatement queryRemoveDevice;
- private NamedParameterStatement queryGetPositions;
private NamedParameterStatement queryAddPosition;
+ private NamedParameterStatement queryUpdateLatestPosition;
/**
* Initialize database
@@ -75,42 +71,18 @@ public class DatabaseDataManager implements DataManager {
queryGetDevices = new NamedParameterStatement(connection, query);
}
- query = properties.getProperty("database.insertDevice");
- if (query != null) {
- queryAddDevice = new NamedParameterStatement(connection, query);
- }
-
- query = properties.getProperty("database.updateDevice");
- if (query != null) {
- queryUpdateDevice = new NamedParameterStatement(connection, query);
- }
-
- query = properties.getProperty("database.deleteDevice");
- if (query != null) {
- queryRemoveDevice = new NamedParameterStatement(connection, query);
- }
-
- query = properties.getProperty("database.selectPosition");
- if (query != null) {
- queryGetPositions = new NamedParameterStatement(connection, query);
- }
-
query = properties.getProperty("database.insertPosition");
if (query != null) {
queryAddPosition = new NamedParameterStatement(connection, query);
}
- // Create database schema
- query = properties.getProperty("database.initialize");
- if (query != null) try {
- NamedParameterStatement initializeQuery = new NamedParameterStatement(connection, query);
- initializeQuery.prepare();
- initializeQuery.executeUpdate();
- } catch (Exception error) {
- Log.warning(error.getMessage());
+ query = properties.getProperty("database.updateLatestPosition");
+ if (query != null) {
+ queryUpdateLatestPosition = new NamedParameterStatement(connection, query);
}
}
+ @Override
public synchronized List<Device> getDevices() throws SQLException {
List<Device> deviceList = new LinkedList<Device>();
@@ -127,40 +99,6 @@ public class DatabaseDataManager implements DataManager {
return deviceList;
}
- public synchronized void addDevice(Device device) throws SQLException {
-
- queryAddDevice.prepare(Statement.RETURN_GENERATED_KEYS);
- queryAddDevice.setString("imei", device.getImei());
- queryAddDevice.executeUpdate();
-
- // Find generated id
- ResultSet result = queryAddDevice.getGeneratedKeys();
- if (result.next()) {
- device.setId(result.getLong(1));
- }
-
- devices = null;
- }
-
- public synchronized void updateDevice(Device device) throws SQLException {
-
- queryUpdateDevice.prepare();
- queryUpdateDevice.setLong("id", device.getId());
- queryUpdateDevice.setString("imei", device.getImei());
- queryUpdateDevice.executeUpdate();
-
- devices = null;
- }
-
- public synchronized void removeDevice(Device device) throws SQLException {
-
- queryRemoveDevice.prepare();
- queryRemoveDevice.setLong("id", device.getId());
- queryRemoveDevice.executeUpdate();
-
- devices = null;
- }
-
/**
* Devices cache
*/
@@ -168,6 +106,7 @@ public class DatabaseDataManager implements DataManager {
private Calendar devicesLastUpdate;
private Long devicesRefreshDelay;
+ @Override
public Device getDeviceByImei(String imei) throws SQLException {
if ((devices == null) || (Calendar.getInstance().getTimeInMillis() - devicesLastUpdate.getTimeInMillis() > devicesRefreshDelay)) {
@@ -182,43 +121,10 @@ public class DatabaseDataManager implements DataManager {
return devices.get(imei);
}
- public Device getDeviceByPhoneNumber(String phoneNumber) {
- // TODO: implement getDeviceByPhoneNumber
- return null;
- }
-
- public Device getDeviceByUniqueId(String uniqueId) {
- // TODO: implement getDeviceByUniqueId
- return null;
- }
-
- public synchronized List<Position> getPositions(Long deviceId) throws SQLException {
-
- List<Position> positionList = new LinkedList<Position>();
-
- queryGetPositions.prepare();
- queryGetPositions.setLong("device_id", deviceId);
- ResultSet result = queryGetPositions.executeQuery();
- while (result.next()) {
- // TODO: include other parameters
- Position position = new Position();
- position.setDeviceId(result.getLong("device_id"));
- position.setTime(result.getTimestamp("time"));
- position.setValid(result.getBoolean("valid"));
- position.setLatitude(result.getDouble("latitude"));
- position.setLongitude(result.getDouble("longitude"));
- position.setSpeed(result.getDouble("speed"));
- position.setCourse(result.getDouble("course"));
- position.setPower(result.getDouble("power"));
- positionList.add(position);
- }
-
- return positionList;
- }
-
- public synchronized void addPosition(Position position) throws SQLException {
+ @Override
+ public synchronized Long addPosition(Position position) throws SQLException {
- queryAddPosition.prepare();
+ queryAddPosition.prepare(Statement.RETURN_GENERATED_KEYS);
queryAddPosition.setLong("id", position.getId());
queryAddPosition.setLong("device_id", position.getDeviceId());
@@ -235,7 +141,23 @@ public class DatabaseDataManager implements DataManager {
queryAddPosition.executeUpdate();
- // TODO: probably return row id
+ ResultSet result = queryAddPosition.getGeneratedKeys();
+ if (result != null && result.next()) {
+ return result.getLong(1);
+ }
+
+ return null;
+ }
+
+ @Override
+ public void updateLatestPosition(Long deviceId, Long positionId) throws SQLException {
+
+ queryUpdateLatestPosition.prepare();
+
+ queryUpdateLatestPosition.setLong("device_id", deviceId);
+ queryUpdateLatestPosition.setLong("id", positionId);
+
+ queryUpdateLatestPosition.executeUpdate();
}
}
diff --git a/test/org/traccar/protocol/TestDataManager.java b/test/org/traccar/protocol/TestDataManager.java
index c6865a078..7466f5ace 100644
--- a/test/org/traccar/protocol/TestDataManager.java
+++ b/test/org/traccar/protocol/TestDataManager.java
@@ -7,19 +7,22 @@ import org.traccar.model.Position;
public class TestDataManager implements DataManager {
- public List getDevices() { return null; }
- public void addDevice(Device device) {}
- public void updateDevice(Device device) {}
- public void removeDevice(Device device) {}
+ @Override
+ public List getDevices() {
+ return null;
+ }
+ @Override
public Device getDeviceByImei(String imei) {
Device device = new Device();
device.setId(new Long(1));
device.setImei("123456789012345");
return device;
}
- public Device getDeviceByPhoneNumber(String phoneNumber) { return null; }
- public Device getDeviceByUniqueId(String uniqueId) { return null; }
- public List getPositions(Long deviceId) { return null; }
- public void addPosition(Position position) {}
-
+ @Override
+ public Long addPosition(Position position) {
+ return null;
+ }
+ @Override
+ public void updateLatestPosition(Long deviceId, Long positionId) throws Exception {
+ }
}