From aeb9dace63d4c9ae02af80824fe157fa43129595 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 11 Jul 2017 16:32:39 +0500 Subject: Implement Driver models, schema and database --- src/org/traccar/database/DataManager.java | 84 +++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) (limited to 'src/org/traccar/database') diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index dd65289e4..1c2a66bcf 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -44,11 +44,15 @@ import org.traccar.model.CalendarPermission; import org.traccar.model.Attribute; import org.traccar.model.Device; import org.traccar.model.DeviceAttribute; +import org.traccar.model.DeviceDriver; import org.traccar.model.DevicePermission; +import org.traccar.model.Driver; +import org.traccar.model.DriverPermission; import org.traccar.model.Event; import org.traccar.model.Geofence; import org.traccar.model.Group; import org.traccar.model.GroupAttribute; +import org.traccar.model.GroupDriver; import org.traccar.model.GroupGeofence; import org.traccar.model.GroupPermission; import org.traccar.model.Notification; @@ -638,4 +642,84 @@ public class DataManager { .executeUpdate(); } + public Collection getDrivers() throws SQLException { + return QueryBuilder.create(dataSource, getQuery("database.selectDrivers")) + .executeQuery(Driver.class); + } + + public void addDriver(Driver driver) throws SQLException { + driver.setId(QueryBuilder.create(dataSource, getQuery("database.insertDriver"), true) + .setObject(driver) + .executeUpdate()); + } + + public void updateDriver(Driver driver) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.updateDriver")) + .setObject(driver) + .executeUpdate(); + } + + public void removeDriver(long driverId) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.deleteDriver")) + .setLong("id", driverId) + .executeUpdate(); + } + + public Collection getDriverPermissions() throws SQLException { + return QueryBuilder.create(dataSource, getQuery("database.selectDriverPermissions")) + .executeQuery(DriverPermission.class); + } + + public void linkDriver(long userId, long driverId) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.linkDriver")) + .setLong("userId", userId) + .setLong("driverId", driverId) + .executeUpdate(); + } + + public void unlinkDriver(long userId, long driverId) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.unlinkDriver")) + .setLong("userId", userId) + .setLong("driverId", driverId) + .executeUpdate(); + } + + public Collection getGroupDrivers() throws SQLException { + return QueryBuilder.create(dataSource, getQuery("database.selectGroupDrivers")) + .executeQuery(GroupDriver.class); + } + + public void linkGroupDriver(long groupId, long driverId) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.linkGroupDriver")) + .setLong("groupId", groupId) + .setLong("driverId", driverId) + .executeUpdate(); + } + + public void unlinkGroupDriver(long groupId, long driverId) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.unlinkGroupDriver")) + .setLong("groupId", groupId) + .setLong("driverId", driverId) + .executeUpdate(); + } + + public Collection getDeviceDrivers() throws SQLException { + return QueryBuilder.create(dataSource, getQuery("database.selectDeviceDrivers")) + .executeQuery(DeviceDriver.class); + } + + public void linkDeviceDriver(long deviceId, long driverId) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.linkDeviceDriver")) + .setLong("deviceId", deviceId) + .setLong("driverId", driverId) + .executeUpdate(); + } + + public void unlinkDeviceDriver(long deviceId, long driverId) throws SQLException { + QueryBuilder.create(dataSource, getQuery("database.unlinkDeviceDriver")) + .setLong("deviceId", deviceId) + .setLong("driverId", driverId) + .executeUpdate(); + } + } -- cgit v1.2.3 From 7863a5ca3358cef028b77188538a0893a737ddbf Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 11 Jul 2017 17:15:06 +0500 Subject: Implement base Drivers Manager --- src/org/traccar/database/DriversManager.java | 213 +++++++++++++++++++++++++++ 1 file changed, 213 insertions(+) create mode 100644 src/org/traccar/database/DriversManager.java (limited to 'src/org/traccar/database') diff --git a/src/org/traccar/database/DriversManager.java b/src/org/traccar/database/DriversManager.java new file mode 100644 index 000000000..8df06d972 --- /dev/null +++ b/src/org/traccar/database/DriversManager.java @@ -0,0 +1,213 @@ +/* + * Copyright 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2017 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.database; + +import java.sql.SQLException; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.traccar.Context; +import org.traccar.helper.Log; +import org.traccar.model.Device; +import org.traccar.model.DeviceDriver; +import org.traccar.model.Driver; +import org.traccar.model.DriverPermission; +import org.traccar.model.GroupDriver; + +public class DriversManager { + + private final DataManager dataManager; + + private final Map drivers = new ConcurrentHashMap<>(); + private final Map driversByUniqueId = new ConcurrentHashMap<>(); + private final Map> deviceDrivers = new ConcurrentHashMap<>(); + private final Map> deviceDriversWithGroups = new ConcurrentHashMap<>(); + private final Map> groupDrivers = new ConcurrentHashMap<>(); + private final Map> userDrivers = new ConcurrentHashMap<>(); + + public DriversManager(DataManager dataManager) { + this.dataManager = dataManager; + refreshDrivers(); + } + + public Set getUserDrivers(long userId) { + if (!userDrivers.containsKey(userId)) { + userDrivers.put(userId, new HashSet()); + } + return userDrivers.get(userId); + } + + public Set getGroupDrivers(long groupId) { + if (!groupDrivers.containsKey(groupId)) { + groupDrivers.put(groupId, new HashSet()); + } + return groupDrivers.get(groupId); + } + + public Set getDeviceDrivers(long deviceId) { + return getDeviceDrivers(deviceDrivers, deviceId); + } + + public Set getAllDeviceDrivers(long deviceId) { + return getDeviceDrivers(deviceDriversWithGroups, deviceId); + } + + private Set getDeviceDrivers(Map> deviceDrivers, long deviceId) { + if (!deviceDrivers.containsKey(deviceId)) { + deviceDrivers.put(deviceId, new HashSet()); + } + return deviceDrivers.get(deviceId); + } + + public final void refreshDrivers() { + if (dataManager != null) { + try { + drivers.clear(); + driversByUniqueId.clear(); + for (Driver driver : dataManager.getDrivers()) { + drivers.put(driver.getId(), driver); + driversByUniqueId.put(driver.getUniqueId(), driver); + } + } catch (SQLException error) { + Log.warning(error); + } + } + refreshUserDrivers(); + refresh(); + } + + public final void refreshUserDrivers() { + if (dataManager != null) { + try { + userDrivers.clear(); + for (DriverPermission driverPermission : dataManager.getDriverPermissions()) { + getUserDrivers(driverPermission.getUserId()).add(driverPermission.getDriverId()); + } + } catch (SQLException error) { + Log.warning(error); + } + } + } + + public final void refresh() { + if (dataManager != null) { + try { + + Collection databaseGroupDrivers = dataManager.getGroupDrivers(); + + groupDrivers.clear(); + for (GroupDriver groupDriver : databaseGroupDrivers) { + getGroupDrivers(groupDriver.getGroupId()).add(groupDriver.getDriverId()); + } + + Collection databaseDeviceDrivers = dataManager.getDeviceDrivers(); + Collection allDevices = Context.getDeviceManager().getAllDevices(); + + deviceDrivers.clear(); + deviceDriversWithGroups.clear(); + + for (DeviceDriver deviceAttribute : databaseDeviceDrivers) { + getDeviceDrivers(deviceAttribute.getDeviceId()) + .add(deviceAttribute.getDriverId()); + getAllDeviceDrivers(deviceAttribute.getDeviceId()) + .add(deviceAttribute.getDriverId()); + } + + for (Device device : allDevices) { + long groupId = device.getGroupId(); + while (groupId != 0) { + getAllDeviceDrivers(device.getId()).addAll(getGroupDrivers(groupId)); + if (Context.getDeviceManager().getGroupById(groupId) != null) { + groupId = Context.getDeviceManager().getGroupById(groupId).getGroupId(); + } else { + groupId = 0; + } + } + } + + } catch (SQLException error) { + Log.warning(error); + } + } + } + + public void addDriver(Driver driver) throws SQLException { + dataManager.addDriver(driver); + drivers.put(driver.getId(), driver); + driversByUniqueId.put(driver.getUniqueId(), driver); + } + + public void updateDriver(Driver driver) throws SQLException { + dataManager.updateDriver(driver); + Driver cachedDriver = drivers.get(driver.getId()); + cachedDriver.setName(driver.getName()); + if (!driver.getUniqueId().equals(cachedDriver.getUniqueId())) { + driversByUniqueId.remove(cachedDriver.getUniqueId()); + cachedDriver.setUniqueId(driver.getUniqueId()); + driversByUniqueId.put(cachedDriver.getUniqueId(), cachedDriver); + } + cachedDriver.setAttributes(driver.getAttributes()); + } + + public void removeDriver(long driverId) throws SQLException { + dataManager.removeAttribute(driverId); + if (drivers.containsKey(driverId)) { + String driverUniqueId = drivers.get(driverId).getUniqueId(); + drivers.remove(driverId); + driversByUniqueId.remove(driverUniqueId); + } + refreshUserDrivers(); + refresh(); + } + + public boolean checkDriver(long userId, long driverId) { + return getUserDrivers(userId).contains(driverId); + } + + public Driver getDriver(long id) { + return drivers.get(id); + } + + public Driver getDriverByUniqueId(String uniqueId) { + return driversByUniqueId.get(uniqueId); + } + + public final Collection getDrivers(Set driverIds) { + Collection result = new LinkedList<>(); + for (long driverId : driverIds) { + result.add(getDriver(driverId)); + } + return result; + } + + public final Set getAllDrivers() { + return drivers.keySet(); + } + + public final Set getManagedDrivers(long userId) { + Set drivers = new HashSet<>(); + drivers.addAll(getUserDrivers(userId)); + for (long managedUserId : Context.getPermissionsManager().getUserPermissions(userId)) { + drivers.addAll(getUserDrivers(managedUserId)); + } + return drivers; + } +} -- cgit v1.2.3 From 0588389bee46910392d4bb0f017b5bae61581e78 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 11 Jul 2017 17:33:33 +0500 Subject: Implement DriverResource --- src/org/traccar/Context.java | 9 ++ src/org/traccar/api/resource/DriverResource.java | 112 +++++++++++++++++++++++ src/org/traccar/database/PermissionsManager.java | 13 +++ 3 files changed, 134 insertions(+) create mode 100644 src/org/traccar/api/resource/DriverResource.java (limited to 'src/org/traccar/database') diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 9626d949c..a4fc5b679 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -31,6 +31,7 @@ import org.traccar.database.AttributesManager; import org.traccar.database.ConnectionManager; import org.traccar.database.DataManager; import org.traccar.database.DeviceManager; +import org.traccar.database.DriversManager; import org.traccar.database.IdentityManager; import org.traccar.database.MediaManager; import org.traccar.database.NotificationManager; @@ -187,6 +188,12 @@ public final class Context { return attributesManager; } + private static DriversManager driversManager; + + public static DriversManager getDriversManager() { + return driversManager; + } + private static StatisticsManager statisticsManager; public static StatisticsManager getStatisticsManager() { @@ -330,6 +337,8 @@ public final class Context { attributesManager = new AttributesManager(dataManager); + driversManager = new DriversManager(dataManager); + statisticsManager = new StatisticsManager(); if (config.getBoolean("sms.smpp.enable")) { diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java new file mode 100644 index 000000000..4ccd11182 --- /dev/null +++ b/src/org/traccar/api/resource/DriverResource.java @@ -0,0 +1,112 @@ +/* + * Copyright 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2017 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.api.resource; + +import java.sql.SQLException; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.traccar.Context; +import org.traccar.api.BaseResource; +import org.traccar.database.DriversManager; +import org.traccar.model.Driver; + +@Path("drivers") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class DriverResource extends BaseResource { + + @GET + public Collection get( + @QueryParam("all") boolean all, @QueryParam("userId") long userId, @QueryParam("groupId") long groupId, + @QueryParam("deviceId") long deviceId, @QueryParam("refresh") boolean refresh) throws SQLException { + + DriversManager driversManager = Context.getDriversManager(); + if (refresh) { + driversManager.refreshDrivers(); + } + + Set result = new HashSet<>(); + if (all) { + if (Context.getPermissionsManager().isAdmin(getUserId())) { + result.addAll(driversManager.getAllDrivers()); + } else { + Context.getPermissionsManager().checkManager(getUserId()); + result.addAll(driversManager.getManagedDrivers(getUserId())); + } + } else { + if (userId == 0) { + userId = getUserId(); + } + Context.getPermissionsManager().checkUser(getUserId(), userId); + result.addAll(driversManager.getUserDrivers(userId)); + } + + if (groupId != 0) { + Context.getPermissionsManager().checkGroup(getUserId(), groupId); + result.retainAll(driversManager.getGroupDrivers(groupId)); + } + + if (deviceId != 0) { + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + result.retainAll(driversManager.getDeviceDrivers(deviceId)); + } + return driversManager.getDrivers(result); + + } + + @POST + public Response add(Driver entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getDriversManager().addDriver(entity); + Context.getDataManager().linkAttribute(getUserId(), entity.getId()); + Context.getAttributesManager().refreshUserAttributes(); + return Response.ok(entity).build(); + } + + @Path("{id}") + @PUT + public Response update(Driver entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getPermissionsManager().checkDriver(getUserId(), entity.getId()); + Context.getDriversManager().updateDriver(entity); + return Response.ok(entity).build(); + } + + @Path("{id}") + @DELETE + public Response remove(@PathParam("id") long id) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getPermissionsManager().checkDriver(getUserId(), id); + Context.getDriversManager().removeDriver(id); + return Response.noContent().build(); + } + +} diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 9a82efd48..82ca6af49 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -322,6 +322,19 @@ public class PermissionsManager { } } + public void checkDriver(long userId, long driverId) throws SecurityException { + if (!Context.getDriversManager().checkDriver(userId, driverId) && !isAdmin(userId)) { + checkManager(userId); + for (long managedUserId : getUserPermissions(userId)) { + if (Context.getDriversManager().checkDriver(managedUserId, driverId)) { + return; + } + } + throw new SecurityException("Driver access denied"); + } + } + + public void checkCalendar(long userId, long calendarId) throws SecurityException { if (!Context.getCalendarManager().checkCalendar(userId, calendarId) && !isAdmin(userId)) { checkManager(userId); -- cgit v1.2.3 From 4f3830d844dd0542e9e7b09e7a6c17ffbb796264 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 12 Jul 2017 12:21:35 +0500 Subject: Fix copy/past issues --- setup/default.xml | 4 ++-- src/org/traccar/api/resource/DriverResource.java | 4 ++-- src/org/traccar/database/DriversManager.java | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src/org/traccar/database') diff --git a/setup/default.xml b/setup/default.xml index 9533c3a9b..4a408bf30 100644 --- a/setup/default.xml +++ b/setup/default.xml @@ -443,7 +443,7 @@ UPDATE drivers SET name = :name, - uniqueId = :uniqueId + uniqueId = :uniqueId, attributes = :attributes WHERE id = :id @@ -461,7 +461,7 @@ - DELETE FROM user_attribute WHERE userId = :userId AND driverId = :driverId + DELETE FROM user_driver WHERE userId = :userId AND driverId = :driverId diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index 4ccd11182..7fe0af473 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -86,8 +86,8 @@ public class DriverResource extends BaseResource { public Response add(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDriversManager().addDriver(entity); - Context.getDataManager().linkAttribute(getUserId(), entity.getId()); - Context.getAttributesManager().refreshUserAttributes(); + Context.getDataManager().linkDriver(getUserId(), entity.getId()); + Context.getDriversManager().refreshUserDrivers(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/database/DriversManager.java b/src/org/traccar/database/DriversManager.java index 8df06d972..e89d59311 100644 --- a/src/org/traccar/database/DriversManager.java +++ b/src/org/traccar/database/DriversManager.java @@ -168,7 +168,7 @@ public class DriversManager { } public void removeDriver(long driverId) throws SQLException { - dataManager.removeAttribute(driverId); + dataManager.removeDriver(driverId); if (drivers.containsKey(driverId)) { String driverUniqueId = drivers.get(driverId).getUniqueId(); drivers.remove(driverId); -- cgit v1.2.3 From b19f1a505f7088ff48f467b32b5f1c207aa3be01 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 12 Jul 2017 14:22:03 +0500 Subject: - Handle rfid attributes and populate driverUniqueId - Add Driver Name to Trip report --- src/org/traccar/BasePipelineFactory.java | 8 ++++ src/org/traccar/database/DriversManager.java | 12 ++++++ src/org/traccar/model/Position.java | 2 + .../traccar/processing/PopulateDriverHandler.java | 45 ++++++++++++++++++++++ .../traccar/protocol/AplicomProtocolDecoder.java | 3 +- .../traccar/protocol/MeiligaoProtocolDecoder.java | 2 +- .../traccar/protocol/OsmAndProtocolDecoder.java | 3 ++ .../traccar/protocol/TeltonikaProtocolDecoder.java | 2 +- src/org/traccar/reports/ReportUtils.java | 16 ++++++++ src/org/traccar/reports/model/TripReport.java | 10 +++++ test/org/traccar/ProtocolTest.java | 4 ++ .../org/traccar/processing/PopulateDriverTest.java | 21 ++++++++++ tools/test-generator.py | 8 +++- 13 files changed, 131 insertions(+), 5 deletions(-) create mode 100644 src/org/traccar/processing/PopulateDriverHandler.java create mode 100644 test/org/traccar/processing/PopulateDriverTest.java (limited to 'src/org/traccar/database') diff --git a/src/org/traccar/BasePipelineFactory.java b/src/org/traccar/BasePipelineFactory.java index a6446dbaa..9f0824b6c 100644 --- a/src/org/traccar/BasePipelineFactory.java +++ b/src/org/traccar/BasePipelineFactory.java @@ -40,6 +40,7 @@ import org.traccar.events.AlertEventHandler; import org.traccar.helper.Log; import org.traccar.processing.ComputedAttributesHandler; import org.traccar.processing.CopyAttributesHandler; +import org.traccar.processing.PopulateDriverHandler; import java.net.InetSocketAddress; @@ -54,6 +55,7 @@ public abstract class BasePipelineFactory implements ChannelPipelineFactory { private GeocoderHandler geocoderHandler; private GeolocationHandler geolocationHandler; private HemisphereHandler hemisphereHandler; + private PopulateDriverHandler populateDriverHandler; private CopyAttributesHandler copyAttributesHandler; private ComputedAttributesHandler computedAttributesHandler; @@ -152,6 +154,8 @@ public abstract class BasePipelineFactory implements ChannelPipelineFactory { hemisphereHandler = new HemisphereHandler(); } + populateDriverHandler = new PopulateDriverHandler(); + if (Context.getConfig().getBoolean("processing.copyAttributes.enable")) { copyAttributesHandler = new CopyAttributesHandler(); } @@ -214,6 +218,10 @@ public abstract class BasePipelineFactory implements ChannelPipelineFactory { pipeline.addLast("motion", motionHandler); } + if (populateDriverHandler != null) { + pipeline.addLast("populateDriver", populateDriverHandler); + } + if (copyAttributesHandler != null) { pipeline.addLast("copyAttributes", copyAttributesHandler); } diff --git a/src/org/traccar/database/DriversManager.java b/src/org/traccar/database/DriversManager.java index e89d59311..1744936e3 100644 --- a/src/org/traccar/database/DriversManager.java +++ b/src/org/traccar/database/DriversManager.java @@ -210,4 +210,16 @@ public class DriversManager { } return drivers; } + + public final boolean authorizeDriverByUniqueId(String driverUniqueId, long deviceId) { + if (driversByUniqueId.containsKey(driverUniqueId)) { + long chekingDriverId = getDriverByUniqueId(driverUniqueId).getId(); + for (long driverId : getAllDeviceDrivers(deviceId)) { + if (chekingDriverId == driverId) { + return true; + } + } + } + return false; + } } diff --git a/src/org/traccar/model/Position.java b/src/org/traccar/model/Position.java index 5835310ae..97b3f365f 100644 --- a/src/org/traccar/model/Position.java +++ b/src/org/traccar/model/Position.java @@ -81,6 +81,8 @@ public class Position extends Message { public static final String KEY_RESULT = "result"; + public static final String KEY_DRIVER_UNIQUE_ID = "driverUniqueId"; + // Start with 1 not 0 public static final String PREFIX_TEMP = "temp"; public static final String PREFIX_ADC = "adc"; diff --git a/src/org/traccar/processing/PopulateDriverHandler.java b/src/org/traccar/processing/PopulateDriverHandler.java new file mode 100644 index 000000000..339cc5548 --- /dev/null +++ b/src/org/traccar/processing/PopulateDriverHandler.java @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2017 Andrey Kunitsyn (andrey@traccar.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.traccar.processing; + +import org.traccar.BaseDataHandler; +import org.traccar.Context; +import org.traccar.model.Position; + +public class PopulateDriverHandler extends BaseDataHandler { + + private Position getLastPosition(long deviceId) { + if (Context.getIdentityManager() != null) { + return Context.getIdentityManager().getLastPosition(deviceId); + } + return null; + } + + @Override + protected Position handlePosition(Position position) { + if (position.getAttributes().containsKey(Position.KEY_RFID)) { + position.set(Position.KEY_DRIVER_UNIQUE_ID, position.getString(Position.KEY_RFID)); + } else { + Position last = getLastPosition(position.getDeviceId()); + if (last != null && last.getAttributes().containsKey(Position.KEY_DRIVER_UNIQUE_ID)) { + position.set(Position.KEY_DRIVER_UNIQUE_ID, last.getString(Position.KEY_DRIVER_UNIQUE_ID)); + } + } + return position; + } + +} diff --git a/src/org/traccar/protocol/AplicomProtocolDecoder.java b/src/org/traccar/protocol/AplicomProtocolDecoder.java index eb8d77011..448cd94fc 100644 --- a/src/org/traccar/protocol/AplicomProtocolDecoder.java +++ b/src/org/traccar/protocol/AplicomProtocolDecoder.java @@ -263,7 +263,8 @@ public class AplicomProtocolDecoder extends BaseProtocolDecoder { } if ((selector & 0x0200) != 0) { - position.set(Position.KEY_RFID, (((long) buf.readUnsignedShort()) << 32) + buf.readUnsignedInt()); + position.set(Position.KEY_RFID, + String.valueOf(((long) buf.readUnsignedShort()) << 32) + buf.readUnsignedInt()); } if ((selector & 0x0400) != 0) { diff --git a/src/org/traccar/protocol/MeiligaoProtocolDecoder.java b/src/org/traccar/protocol/MeiligaoProtocolDecoder.java index 44e01d5e0..77e117262 100644 --- a/src/org/traccar/protocol/MeiligaoProtocolDecoder.java +++ b/src/org/traccar/protocol/MeiligaoProtocolDecoder.java @@ -253,7 +253,7 @@ public class MeiligaoProtocolDecoder extends BaseProtocolDecoder { } if (parser.hasNext()) { - position.set(Position.KEY_RFID, parser.nextHexInt(0)); + position.set(Position.KEY_RFID, String.valueOf(parser.nextHexInt(0))); } return position; diff --git a/src/org/traccar/protocol/OsmAndProtocolDecoder.java b/src/org/traccar/protocol/OsmAndProtocolDecoder.java index 15f6f40b8..20cd54b2f 100644 --- a/src/org/traccar/protocol/OsmAndProtocolDecoder.java +++ b/src/org/traccar/protocol/OsmAndProtocolDecoder.java @@ -128,6 +128,9 @@ public class OsmAndProtocolDecoder extends BaseProtocolDecoder { case "batt": position.set(Position.KEY_BATTERY_LEVEL, Double.parseDouble(value)); break; + case "rfid": + position.set(Position.KEY_RFID, value); + break; default: try { position.set(entry.getKey(), Double.parseDouble(value)); diff --git a/src/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/org/traccar/protocol/TeltonikaProtocolDecoder.java index 3f5b68f67..f1fd55d98 100644 --- a/src/org/traccar/protocol/TeltonikaProtocolDecoder.java +++ b/src/org/traccar/protocol/TeltonikaProtocolDecoder.java @@ -114,7 +114,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { position.set(Position.PREFIX_TEMP + 3, readValue(buf, length, true) * 0.1); break; case 78: - position.set(Position.KEY_RFID, readValue(buf, length, false)); + position.set(Position.KEY_RFID, String.valueOf(readValue(buf, length, false))); break; case 182: position.set(Position.KEY_HDOP, readValue(buf, length, false) * 0.1); diff --git a/src/org/traccar/reports/ReportUtils.java b/src/org/traccar/reports/ReportUtils.java index 71c567c29..92918b861 100644 --- a/src/org/traccar/reports/ReportUtils.java +++ b/src/org/traccar/reports/ReportUtils.java @@ -26,6 +26,7 @@ import org.jxls.transform.Transformer; import org.jxls.transform.poi.PoiTransformer; import org.jxls.util.TransformerFactory; import org.traccar.Context; +import org.traccar.model.Driver; import org.traccar.model.Position; import org.traccar.reports.model.BaseReport; import org.traccar.reports.model.StopReport; @@ -101,6 +102,20 @@ public final class ReportUtils { return 0; } + public static String findDriverName(Position firstPosition, Position lastPosition) { + String driverUniqueId = null; + if (firstPosition.getAttributes().containsKey(Position.KEY_DRIVER_UNIQUE_ID)) { + driverUniqueId = firstPosition.getString(Position.KEY_DRIVER_UNIQUE_ID); + } else if (lastPosition.getAttributes().containsKey(Position.KEY_DRIVER_UNIQUE_ID)) { + driverUniqueId = lastPosition.getString(Position.KEY_DRIVER_UNIQUE_ID); + } + if (driverUniqueId != null && Context.getDriversManager() != null) { + Driver driver = Context.getDriversManager().getDriverByUniqueId(driverUniqueId); + return driver != null ? driver.getName() : null; + } + return null; + } + public static org.jxls.common.Context initializeContext(long userId) { org.jxls.common.Context jxlsContext = PoiTransformer.createInitialContext(); jxlsContext.putVar("distanceUnit", getDistanceUnit(userId)); @@ -175,6 +190,7 @@ public final class ReportUtils { trip.setAverageSpeed(speedSum / (endIndex - startIndex)); trip.setMaxSpeed(speedMax); trip.setSpentFuel(calculateFuel(startTrip, endTrip)); + trip.setDriverName(findDriverName(startTrip, endTrip)); return trip; } diff --git a/src/org/traccar/reports/model/TripReport.java b/src/org/traccar/reports/model/TripReport.java index efe556f79..0f23581b2 100644 --- a/src/org/traccar/reports/model/TripReport.java +++ b/src/org/traccar/reports/model/TripReport.java @@ -145,4 +145,14 @@ public class TripReport extends BaseReport { public void setDuration(long duration) { this.duration = duration; } + + private String driverName; + + public String getDriverName() { + return driverName; + } + + public void setDriverName(String driverName) { + this.driverName = driverName; + } } diff --git a/test/org/traccar/ProtocolTest.java b/test/org/traccar/ProtocolTest.java index 3b801c6eb..dc4f70981 100644 --- a/test/org/traccar/ProtocolTest.java +++ b/test/org/traccar/ProtocolTest.java @@ -245,6 +245,10 @@ public class ProtocolTest extends BaseTest { Assert.assertTrue(attributes.get(Position.KEY_ARCHIVE) instanceof Boolean); } + if (attributes.containsKey(Position.KEY_RFID)) { + Assert.assertTrue(attributes.get(Position.KEY_RFID) instanceof String); + } + if (position.getNetwork() != null && position.getNetwork().getCellTowers() != null) { for (CellTower cellTower : position.getNetwork().getCellTowers()) { checkInteger(cellTower.getMobileCountryCode(), 0, 999); diff --git a/test/org/traccar/processing/PopulateDriverTest.java b/test/org/traccar/processing/PopulateDriverTest.java new file mode 100644 index 000000000..7c6ee9f06 --- /dev/null +++ b/test/org/traccar/processing/PopulateDriverTest.java @@ -0,0 +1,21 @@ +package org.traccar.processing; + +import org.junit.Assert; +import org.junit.Test; +import org.traccar.model.Position; + +public class PopulateDriverTest { + + @Test + public void testPopulateDriver() { + Position position = new Position(); + PopulateDriverHandler populateDriverHandler = new PopulateDriverHandler(); + Assert.assertNull(populateDriverHandler.handlePosition(position).getString(Position.KEY_DRIVER_UNIQUE_ID)); + position.set(Position.KEY_DRIVER_UNIQUE_ID, "123"); + Assert.assertEquals("123", + populateDriverHandler.handlePosition(position).getString(Position.KEY_DRIVER_UNIQUE_ID)); + position.set(Position.KEY_RFID, "321"); + Assert.assertEquals("321", + populateDriverHandler.handlePosition(position).getString(Position.KEY_DRIVER_UNIQUE_ID)); + } +} diff --git a/tools/test-generator.py b/tools/test-generator.py index 9e9cf892e..47c1c478f 100755 --- a/tools/test-generator.py +++ b/tools/test-generator.py @@ -12,6 +12,7 @@ server = 'localhost:5055' period = 1 step = 0.001 device_speed = 40 +driver_id = '123456' waypoints = [ (40.722412, -74.006288), @@ -34,7 +35,7 @@ for i in range(0, len(waypoints)): lon = lon1 + (lon2 - lon1) * j / count points.append((lat, lon)) -def send(conn, lat, lon, course, speed, alarm, ignition, accuracy, rpm, fuel): +def send(conn, lat, lon, course, speed, alarm, ignition, accuracy, rpm, fuel, rfid): params = (('id', id), ('timestamp', int(time.time())), ('lat', lat), ('lon', lon), ('bearing', course), ('speed', speed)) if alarm: params = params + (('alarm', 'sos'),) @@ -46,6 +47,8 @@ def send(conn, lat, lon, course, speed, alarm, ignition, accuracy, rpm, fuel): params = params + (('rpm', rpm),) if fuel: params = params + (('fuel', fuel),) + if rfid: + params = params + (('rfid', rfid),) conn.request('GET', '?' + urllib.urlencode(params)) conn.getresponse().read() @@ -71,6 +74,7 @@ while True: accuracy = 100 if (index % 10) == 0 else 0 rpm = random.randint(500, 4000) fuel = random.randint(0, 80) - send(conn, lat1, lon1, course(lat1, lon1, lat2, lon2), speed, alarm, ignition, accuracy, rpm, fuel) + rfid = driver_id if (index % len(points)) == 0 else False + send(conn, lat1, lon1, course(lat1, lon1, lat2, lon2), speed, alarm, ignition, accuracy, rpm, fuel, rfid) time.sleep(period) index += 1 -- cgit v1.2.3 From 74471c1fbbb7e8a09a6958fa88930a2905b4a3eb Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 12 Jul 2017 17:15:31 +0500 Subject: Do not generate unathorized events if no one driver linked to device --- src/org/traccar/database/DriversManager.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src/org/traccar/database') diff --git a/src/org/traccar/database/DriversManager.java b/src/org/traccar/database/DriversManager.java index 1744936e3..cba2e14c1 100644 --- a/src/org/traccar/database/DriversManager.java +++ b/src/org/traccar/database/DriversManager.java @@ -214,7 +214,11 @@ public class DriversManager { public final boolean authorizeDriverByUniqueId(String driverUniqueId, long deviceId) { if (driversByUniqueId.containsKey(driverUniqueId)) { long chekingDriverId = getDriverByUniqueId(driverUniqueId).getId(); - for (long driverId : getAllDeviceDrivers(deviceId)) { + Set deviceDrivers = getAllDeviceDrivers(deviceId); + if (deviceDrivers.isEmpty()) { + return true; + } + for (long driverId : deviceDrivers) { if (chekingDriverId == driverId) { return true; } -- cgit v1.2.3 From c0cbde51aa75a5b2df58b11e76527ee703289541 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Fri, 14 Jul 2017 11:59:31 +0500 Subject: Implement driverChanged event instead of driverUnauthorized --- setup/default.xml | 2 +- src/org/traccar/database/DriversManager.java | 16 ---------------- src/org/traccar/events/DriverEventHandler.java | 19 +++++-------------- src/org/traccar/model/Event.java | 2 +- templates/mail/driverChanged.vm | 10 ++++++++++ templates/mail/driverUnauthorized.vm | 10 ---------- templates/sms/driverChanged.vm | 6 ++++++ templates/sms/driverUnauthorized.vm | 6 ------ 8 files changed, 23 insertions(+), 48 deletions(-) create mode 100644 templates/mail/driverChanged.vm delete mode 100644 templates/mail/driverUnauthorized.vm create mode 100644 templates/sms/driverChanged.vm delete mode 100644 templates/sms/driverUnauthorized.vm (limited to 'src/org/traccar/database') diff --git a/setup/default.xml b/setup/default.xml index 4a408bf30..04530104a 100644 --- a/setup/default.xml +++ b/setup/default.xml @@ -452,7 +452,7 @@ DELETE FROM drivers WHERE id = :id - + SELECT userId, driverId FROM user_driver diff --git a/src/org/traccar/database/DriversManager.java b/src/org/traccar/database/DriversManager.java index cba2e14c1..e89d59311 100644 --- a/src/org/traccar/database/DriversManager.java +++ b/src/org/traccar/database/DriversManager.java @@ -210,20 +210,4 @@ public class DriversManager { } return drivers; } - - public final boolean authorizeDriverByUniqueId(String driverUniqueId, long deviceId) { - if (driversByUniqueId.containsKey(driverUniqueId)) { - long chekingDriverId = getDriverByUniqueId(driverUniqueId).getId(); - Set deviceDrivers = getAllDeviceDrivers(deviceId); - if (deviceDrivers.isEmpty()) { - return true; - } - for (long driverId : deviceDrivers) { - if (chekingDriverId == driverId) { - return true; - } - } - } - return false; - } } diff --git a/src/org/traccar/events/DriverEventHandler.java b/src/org/traccar/events/DriverEventHandler.java index 9109373c7..eb5f2a301 100644 --- a/src/org/traccar/events/DriverEventHandler.java +++ b/src/org/traccar/events/DriverEventHandler.java @@ -26,12 +26,6 @@ import org.traccar.model.Position; public class DriverEventHandler extends BaseEventHandler { - private boolean notRepeat; - - public DriverEventHandler() { - notRepeat = Context.getConfig().getBoolean("event.driver.notRepeat"); - } - @Override protected Collection analyzePosition(Position position) { if (!Context.getIdentityManager().isLatestPosition(position)) { @@ -40,15 +34,12 @@ public class DriverEventHandler extends BaseEventHandler { String driverUniqueId = position.getString(Position.KEY_DRIVER_UNIQUE_ID); if (driverUniqueId != null) { String oldDriverUniqueId = null; - if (notRepeat) { - Position lastPosition = Context.getIdentityManager().getLastPosition(position.getDeviceId()); - if (lastPosition != null) { - oldDriverUniqueId = lastPosition.getString(Position.KEY_DRIVER_UNIQUE_ID); - } + Position lastPosition = Context.getIdentityManager().getLastPosition(position.getDeviceId()); + if (lastPosition != null) { + oldDriverUniqueId = lastPosition.getString(Position.KEY_DRIVER_UNIQUE_ID); } - if (!driverUniqueId.equals(oldDriverUniqueId) - && !Context.getDriversManager().authorizeDriverByUniqueId(driverUniqueId, position.getDeviceId())) { - Event event = new Event(Event.TYPE_DRIVER_UNAUTHORIZED, position.getDeviceId(), position.getId()); + if (!driverUniqueId.equals(oldDriverUniqueId)) { + Event event = new Event(Event.TYPE_DRIVER_CHANGED, position.getDeviceId(), position.getId()); event.set(Position.KEY_DRIVER_UNIQUE_ID, driverUniqueId); return Collections.singleton(event); } diff --git a/src/org/traccar/model/Event.java b/src/org/traccar/model/Event.java index dd5358f75..2d836abeb 100644 --- a/src/org/traccar/model/Event.java +++ b/src/org/traccar/model/Event.java @@ -61,7 +61,7 @@ public class Event extends Message { public static final String TYPE_TEXT_MESSAGE = "textMessage"; - public static final String TYPE_DRIVER_UNAUTHORIZED = "driverUnauthorized"; + public static final String TYPE_DRIVER_CHANGED = "driverChanged"; private Date serverTime; diff --git a/templates/mail/driverChanged.vm b/templates/mail/driverChanged.vm new file mode 100644 index 000000000..ba1e68661 --- /dev/null +++ b/templates/mail/driverChanged.vm @@ -0,0 +1,10 @@ +#set($subject = "$device.name: driver has changed") + + + +Device: $device.name
+Time: $dateTool.format("YYYY-MM-dd HH:mm:ss", $event.serverTime, $locale, $timezone)
+Point: #{if}($position.address)$position.address#{else}$position.latitude°, $position.longitude°#{end}
+Driver: #{if}($driver)$driver.name#{else}$event.getString("driverUniqueId")#{end} + + diff --git a/templates/mail/driverUnauthorized.vm b/templates/mail/driverUnauthorized.vm deleted file mode 100644 index 3d28266cd..000000000 --- a/templates/mail/driverUnauthorized.vm +++ /dev/null @@ -1,10 +0,0 @@ -#set($subject = "$device.name: driver unauthorized") - - - -Device: $device.name
-Time: $dateTool.format("YYYY-MM-dd HH:mm:ss", $event.serverTime, $locale, $timezone)
-Point: #{if}($position.address)$position.address#{else}$position.latitude°, $position.longitude°#{end}
-Driver: #{if}($driver)$driver.name#{else}$event.getString("driverUniqueId")#{end} - - diff --git a/templates/sms/driverChanged.vm b/templates/sms/driverChanged.vm new file mode 100644 index 000000000..50849df7c --- /dev/null +++ b/templates/sms/driverChanged.vm @@ -0,0 +1,6 @@ +#if($driver) +#set($driverName = $driver.name) +#else +#set($driverName = $event.getString("driverUniqueId")) +#end +Driver $driverName has changed in $device.name at $dateTool.format("YYYY-MM-dd HH:mm:ss", $event.serverTime, $locale, $timezone) diff --git a/templates/sms/driverUnauthorized.vm b/templates/sms/driverUnauthorized.vm deleted file mode 100644 index 52c819eb8..000000000 --- a/templates/sms/driverUnauthorized.vm +++ /dev/null @@ -1,6 +0,0 @@ -#if($driver) -#set($driverName = $driver.name) -#else -#set($driverName = $event.getString("driverUniqueId")) -#end -$driverName is unauthorized for $device.name at $dateTool.format("YYYY-MM-dd HH:mm:ss", $event.serverTime, $locale, $timezone) -- cgit v1.2.3