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/api/resource/DriverResource.java | 112 +++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 src/org/traccar/api/resource/DriverResource.java (limited to 'src/org/traccar/api') 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(); + } + +} -- cgit v1.2.3 From 6a2efbf78f7012e893079a1c086c12ab14e92cd6 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 11 Jul 2017 17:47:17 +0500 Subject: Implement Drivers permissions resources --- .../traccar/api/resource/DeviceDriverResource.java | 58 +++++++++++++++++++++ .../api/resource/DriverPermissionResource.java | 59 ++++++++++++++++++++++ .../traccar/api/resource/GroupDriverResource.java | 58 +++++++++++++++++++++ 3 files changed, 175 insertions(+) create mode 100644 src/org/traccar/api/resource/DeviceDriverResource.java create mode 100644 src/org/traccar/api/resource/DriverPermissionResource.java create mode 100644 src/org/traccar/api/resource/GroupDriverResource.java (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/DeviceDriverResource.java b/src/org/traccar/api/resource/DeviceDriverResource.java new file mode 100644 index 000000000..341c50909 --- /dev/null +++ b/src/org/traccar/api/resource/DeviceDriverResource.java @@ -0,0 +1,58 @@ +/* + * 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 javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.traccar.Context; +import org.traccar.api.BaseResource; +import org.traccar.model.DeviceDriver; + +@Path("devices/drivers") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class DeviceDriverResource extends BaseResource { + + @POST + public Response add(DeviceDriver entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); + Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getDataManager().linkDeviceDriver(entity.getDeviceId(), entity.getDriverId()); + Context.getDriversManager().refresh(); + return Response.ok(entity).build(); + } + + @DELETE + public Response remove(DeviceDriver entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); + Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getDataManager().unlinkDeviceDriver(entity.getDeviceId(), entity.getDriverId()); + Context.getDriversManager().refresh(); + return Response.noContent().build(); + } + +} diff --git a/src/org/traccar/api/resource/DriverPermissionResource.java b/src/org/traccar/api/resource/DriverPermissionResource.java new file mode 100644 index 000000000..fd1ca7c6d --- /dev/null +++ b/src/org/traccar/api/resource/DriverPermissionResource.java @@ -0,0 +1,59 @@ +/* + * 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 javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.traccar.Context; +import org.traccar.api.BaseResource; + +import org.traccar.model.DriverPermission; + +@Path("permissions/drivers") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class DriverPermissionResource extends BaseResource { + + @POST + public Response add(DriverPermission entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); + Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getDataManager().linkDriver(entity.getUserId(), entity.getDriverId()); + Context.getDriversManager().refreshUserDrivers(); + return Response.ok(entity).build(); + } + + @DELETE + public Response remove(DriverPermission entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); + Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getDataManager().unlinkDriver(entity.getUserId(), entity.getDriverId()); + Context.getDriversManager().refreshUserDrivers(); + return Response.noContent().build(); + } + +} diff --git a/src/org/traccar/api/resource/GroupDriverResource.java b/src/org/traccar/api/resource/GroupDriverResource.java new file mode 100644 index 000000000..76fc2892c --- /dev/null +++ b/src/org/traccar/api/resource/GroupDriverResource.java @@ -0,0 +1,58 @@ +/* + * 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 javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.traccar.Context; +import org.traccar.api.BaseResource; +import org.traccar.model.GroupDriver; + +@Path("groups/drivers") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class GroupDriverResource extends BaseResource { + + @POST + public Response add(GroupDriver entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); + Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getDataManager().linkGroupDriver(entity.getGroupId(), entity.getDriverId()); + Context.getDriversManager().refresh(); + return Response.ok(entity).build(); + } + + @DELETE + public Response remove(GroupDriver entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); + Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getDataManager().unlinkGroupDriver(entity.getGroupId(), entity.getDriverId()); + Context.getDriversManager().refresh(); + return Response.noContent().build(); + } + +} -- cgit v1.2.3 From 24a0a43d58088eb569ba0d7c32bc8a2d31a13d53 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 11 Jul 2017 17:49:19 +0500 Subject: Fix Device and Group Computed Attribute unlinking --- src/org/traccar/api/resource/DeviceAttributeResource.java | 2 +- src/org/traccar/api/resource/GroupAttributeResource.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/DeviceAttributeResource.java b/src/org/traccar/api/resource/DeviceAttributeResource.java index 8d80c9235..82d17bcc6 100644 --- a/src/org/traccar/api/resource/DeviceAttributeResource.java +++ b/src/org/traccar/api/resource/DeviceAttributeResource.java @@ -49,7 +49,7 @@ public class DeviceAttributeResource extends BaseResource { public Response remove(DeviceAttribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkGeofence(getUserId(), entity.getAttributeId()); + Context.getPermissionsManager().checkAttribute(getUserId(), entity.getAttributeId()); Context.getDataManager().unlinkDeviceAttribute(entity.getDeviceId(), entity.getAttributeId()); Context.getAttributesManager().refresh(); return Response.noContent().build(); diff --git a/src/org/traccar/api/resource/GroupAttributeResource.java b/src/org/traccar/api/resource/GroupAttributeResource.java index 84b876d34..d8b8b58c9 100644 --- a/src/org/traccar/api/resource/GroupAttributeResource.java +++ b/src/org/traccar/api/resource/GroupAttributeResource.java @@ -49,7 +49,7 @@ public class GroupAttributeResource extends BaseResource { public Response remove(GroupAttribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkGeofence(getUserId(), entity.getAttributeId()); + Context.getPermissionsManager().checkAttribute(getUserId(), entity.getAttributeId()); Context.getDataManager().unlinkGroupAttribute(entity.getGroupId(), entity.getAttributeId()); Context.getAttributesManager().refresh(); return Response.noContent().build(); -- 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/api') 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 2aaa4a5e00e801b9b310e42f538113dd83e60188 Mon Sep 17 00:00:00 2001 From: Jan-Piet Mens Date: Wed, 19 Jul 2017 09:38:51 +0200 Subject: [NEW] add GET with list of uniqueId --- src/org/traccar/api/resource/DeviceResource.java | 41 +++++++++++++++--------- swagger.json | 8 +++++ 2 files changed, 33 insertions(+), 16 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index ce46b4e29..0bf0aa45f 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -45,30 +45,39 @@ public class DeviceResource extends BaseResource { @GET public Collection get( @QueryParam("all") boolean all, @QueryParam("userId") long userId, + @QueryParam("uniqueId") List uniqueIds, @QueryParam("id") List deviceIds) throws SQLException { - if (deviceIds.isEmpty()) { - if (all) { - if (Context.getPermissionsManager().isAdmin(getUserId())) { - return Context.getDeviceManager().getAllDevices(); - } else { - Context.getPermissionsManager().checkManager(getUserId()); - return Context.getDeviceManager().getManagedDevices(getUserId()); - } + if (all) { + if (Context.getPermissionsManager().isAdmin(getUserId())) { + return Context.getDeviceManager().getAllDevices(); } else { - if (userId == 0) { - userId = getUserId(); - } - Context.getPermissionsManager().checkUser(getUserId(), userId); - return Context.getDeviceManager().getDevices(userId); + Context.getPermissionsManager().checkManager(getUserId()); + return Context.getDeviceManager().getManagedDevices(getUserId()); } - } else { - ArrayList devices = new ArrayList<>(); + } + if (uniqueIds.isEmpty() && deviceIds.isEmpty()) { + if (userId == 0) { + userId = getUserId(); + } + Context.getPermissionsManager().checkUser(getUserId(), userId); + return Context.getDeviceManager().getDevices(userId); + } + + ArrayList devices = new ArrayList<>(); + if (!uniqueIds.isEmpty()) { + for (String uniqueId : uniqueIds) { + Device device = Context.getDeviceManager().getDeviceByUniqueId(uniqueId); + Context.getPermissionsManager().checkDevice(getUserId(), device.getId()); + devices.add(device); + } + } + if (!deviceIds.isEmpty()) { for (Long deviceId : deviceIds) { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); devices.add(Context.getDeviceManager().getDeviceById(deviceId)); } - return devices; } + return devices; } @POST diff --git a/swagger.json b/swagger.json index 734e42eab..a82232f02 100644 --- a/swagger.json +++ b/swagger.json @@ -65,6 +65,14 @@ "required" : false, "type" : "integer", "collectionFormat" : "multi" + }, + { + "name" : "uniqueId", + "in" : "query", + "description" : "To fetch one or more devices. Multiple params can be passed like `uniqueId=333331&uniqieId=44442`", + "required" : false, + "type" : "string", + "collectionFormat" : "multi" } ], "responses": { -- cgit v1.2.3 From 97d57828301ef04ccd4a3c58ca9ce5a23038345e Mon Sep 17 00:00:00 2001 From: Jan-Piet Mens Date: Wed, 19 Jul 2017 12:02:27 +0200 Subject: remove redundant checks --- src/org/traccar/api/resource/DeviceResource.java | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index 0bf0aa45f..2957d623c 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -64,18 +64,15 @@ public class DeviceResource extends BaseResource { } ArrayList devices = new ArrayList<>(); - if (!uniqueIds.isEmpty()) { - for (String uniqueId : uniqueIds) { - Device device = Context.getDeviceManager().getDeviceByUniqueId(uniqueId); - Context.getPermissionsManager().checkDevice(getUserId(), device.getId()); - devices.add(device); - } + + for (String uniqueId : uniqueIds) { + Device device = Context.getDeviceManager().getDeviceByUniqueId(uniqueId); + Context.getPermissionsManager().checkDevice(getUserId(), device.getId()); + devices.add(device); } - if (!deviceIds.isEmpty()) { - for (Long deviceId : deviceIds) { - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - devices.add(Context.getDeviceManager().getDeviceById(deviceId)); - } + for (Long deviceId : deviceIds) { + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + devices.add(Context.getDeviceManager().getDeviceById(deviceId)); } return devices; } -- cgit v1.2.3 From a9478ded48de140d47d17def1ee5329267fe6088 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 19 Jul 2017 15:24:55 +0500 Subject: Refactored four managers --- setup/default.xml | 4 +- .../api/resource/AttributePermissionResource.java | 8 +- .../traccar/api/resource/AttributeResource.java | 26 +- .../api/resource/CalendarPermissionResource.java | 8 +- src/org/traccar/api/resource/CalendarResource.java | 20 +- .../api/resource/DeviceAttributeResource.java | 4 +- .../traccar/api/resource/DeviceDriverResource.java | 4 +- .../api/resource/DeviceGeofenceResource.java | 4 +- .../api/resource/DriverPermissionResource.java | 8 +- src/org/traccar/api/resource/DriverResource.java | 26 +- src/org/traccar/api/resource/EventResource.java | 2 +- .../api/resource/GeofencePermissionResource.java | 8 +- src/org/traccar/api/resource/GeofenceResource.java | 27 +- .../api/resource/GroupAttributeResource.java | 4 +- .../traccar/api/resource/GroupDriverResource.java | 4 +- .../api/resource/GroupGeofenceResource.java | 4 +- src/org/traccar/api/resource/UserResource.java | 2 +- src/org/traccar/database/AttributesManager.java | 171 +------------ src/org/traccar/database/CalendarManager.java | 99 +------ src/org/traccar/database/DataManager.java | 183 ++----------- src/org/traccar/database/DriversManager.java | 179 +++---------- .../traccar/database/ExtendedObjectManager.java | 129 ++++++++++ src/org/traccar/database/GeofenceManager.java | 284 ++------------------- src/org/traccar/database/NotificationManager.java | 2 +- src/org/traccar/database/PermissionsManager.java | 73 +++--- src/org/traccar/database/SimpleObjectManager.java | 164 ++++++++++++ src/org/traccar/events/GeofenceEventHandler.java | 16 +- src/org/traccar/model/Attribute.java | 12 +- src/org/traccar/model/AttributeAlias.java | 12 +- src/org/traccar/model/AttributePermission.java | 17 +- src/org/traccar/model/BaseDevicePermission.java | 31 +++ src/org/traccar/model/BaseGroupPermission.java | 31 +++ src/org/traccar/model/BasePermission.java | 23 ++ src/org/traccar/model/BaseUserPermission.java | 31 +++ src/org/traccar/model/CalendarPermission.java | 17 +- src/org/traccar/model/DeviceAttribute.java | 17 +- src/org/traccar/model/DeviceDriver.java | 17 +- src/org/traccar/model/DeviceGeofence.java | 17 +- src/org/traccar/model/DriverPermission.java | 17 +- src/org/traccar/model/Extensible.java | 12 +- src/org/traccar/model/GeofencePermission.java | 17 +- src/org/traccar/model/GroupAttribute.java | 17 +- src/org/traccar/model/GroupDriver.java | 17 +- src/org/traccar/model/GroupGeofence.java | 17 +- src/org/traccar/model/Identifiable.java | 31 +++ src/org/traccar/notification/EventForwarder.java | 2 +- .../notification/NotificationFormatter.java | 2 +- .../processing/ComputedAttributesHandler.java | 4 +- src/org/traccar/reports/Events.java | 6 +- 49 files changed, 725 insertions(+), 1105 deletions(-) create mode 100644 src/org/traccar/database/ExtendedObjectManager.java create mode 100644 src/org/traccar/database/SimpleObjectManager.java create mode 100644 src/org/traccar/model/BaseDevicePermission.java create mode 100644 src/org/traccar/model/BaseGroupPermission.java create mode 100644 src/org/traccar/model/BasePermission.java create mode 100644 src/org/traccar/model/BaseUserPermission.java create mode 100644 src/org/traccar/model/Identifiable.java (limited to 'src/org/traccar/api') diff --git a/setup/default.xml b/setup/default.xml index 04530104a..d3651b9f0 100644 --- a/setup/default.xml +++ b/setup/default.xml @@ -207,7 +207,7 @@ SELECT * FROM events WHERE deviceId = :deviceId AND serverTime BETWEEN :from AND :to ORDER BY serverTime - + SELECT * FROM geofences @@ -328,7 +328,7 @@ VALUES (:captureTime, :activeUsers, :activeDevices, :requests, :messagesReceived, :messagesStored, :mailSent, :smsSent, :geocoderRequests, :geolocationRequests, :attributes) - + SELECT * FROM calendars diff --git a/src/org/traccar/api/resource/AttributePermissionResource.java b/src/org/traccar/api/resource/AttributePermissionResource.java index 1924bcdf1..37e50e371 100644 --- a/src/org/traccar/api/resource/AttributePermissionResource.java +++ b/src/org/traccar/api/resource/AttributePermissionResource.java @@ -39,9 +39,9 @@ public class AttributePermissionResource extends BaseResource { public Response add(AttributePermission entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkAttribute(getUserId(), entity.getAttributeId()); + Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); Context.getDataManager().linkAttribute(entity.getUserId(), entity.getAttributeId()); - Context.getAttributesManager().refreshUserAttributes(); + Context.getAttributesManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -49,9 +49,9 @@ public class AttributePermissionResource extends BaseResource { public Response remove(AttributePermission entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkAttribute(getUserId(), entity.getAttributeId()); + Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); Context.getDataManager().unlinkAttribute(entity.getUserId(), entity.getAttributeId()); - Context.getAttributesManager().refreshUserAttributes(); + Context.getAttributesManager().refreshUserItems(); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/AttributeResource.java b/src/org/traccar/api/resource/AttributeResource.java index 4d326779b..c67d9cafe 100644 --- a/src/org/traccar/api/resource/AttributeResource.java +++ b/src/org/traccar/api/resource/AttributeResource.java @@ -52,42 +52,42 @@ public class AttributeResource extends BaseResource { AttributesManager attributesManager = Context.getAttributesManager(); if (refresh) { - attributesManager.refreshAttributes(); + attributesManager.refreshItems(); } Set result = new HashSet<>(); if (all) { if (Context.getPermissionsManager().isAdmin(getUserId())) { - result.addAll(attributesManager.getAllAttributes()); + result.addAll(attributesManager.getAllItems()); } else { Context.getPermissionsManager().checkManager(getUserId()); - result.addAll(attributesManager.getManagedAttributes(getUserId())); + result.addAll(attributesManager.getManagedItems(getUserId())); } } else { if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); - result.addAll(attributesManager.getUserAttributes(userId)); + result.addAll(attributesManager.getUserItems(userId)); } if (groupId != 0) { Context.getPermissionsManager().checkGroup(getUserId(), groupId); - result.retainAll(attributesManager.getGroupAttributes(groupId)); + result.retainAll(attributesManager.getGroupItems(groupId)); } if (deviceId != 0) { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - result.retainAll(attributesManager.getDeviceAttributes(deviceId)); + result.retainAll(attributesManager.getDeviceItems(deviceId)); } - return attributesManager.getAttributes(result); + return attributesManager.getItems(Attribute.class, result); } private Response add(Attribute entity) throws SQLException { - Context.getAttributesManager().addAttribute(entity); + Context.getAttributesManager().addItem(entity); Context.getDataManager().linkAttribute(getUserId(), entity.getId()); - Context.getAttributesManager().refreshUserAttributes(); + Context.getAttributesManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -127,8 +127,8 @@ public class AttributeResource extends BaseResource { @PUT public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkAttribute(getUserId(), entity.getId()); - Context.getAttributesManager().updateAttribute(entity); + Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getId()); + Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); } @@ -136,8 +136,8 @@ public class AttributeResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkAttribute(getUserId(), id); - Context.getAttributesManager().removeAttribute(id); + Context.getPermissionsManager().checkPermission("attribute", getUserId(), id); + Context.getAttributesManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/CalendarPermissionResource.java b/src/org/traccar/api/resource/CalendarPermissionResource.java index a49254b6b..3936bcaf3 100644 --- a/src/org/traccar/api/resource/CalendarPermissionResource.java +++ b/src/org/traccar/api/resource/CalendarPermissionResource.java @@ -39,9 +39,9 @@ public class CalendarPermissionResource extends BaseResource { public Response add(CalendarPermission entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkCalendar(getUserId(), entity.getCalendarId()); + Context.getPermissionsManager().checkPermission("calendar", getUserId(), entity.getCalendarId()); Context.getDataManager().linkCalendar(entity.getUserId(), entity.getCalendarId()); - Context.getCalendarManager().refreshUserCalendars(); + Context.getCalendarManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -49,9 +49,9 @@ public class CalendarPermissionResource extends BaseResource { public Response remove(CalendarPermission entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkCalendar(getUserId(), entity.getCalendarId()); + Context.getPermissionsManager().checkPermission("calendar", getUserId(), entity.getCalendarId()); Context.getDataManager().unlinkCalendar(entity.getUserId(), entity.getCalendarId()); - Context.getCalendarManager().refreshUserCalendars(); + Context.getCalendarManager().refreshUserItems(); return Response.noContent().build(); } } diff --git a/src/org/traccar/api/resource/CalendarResource.java b/src/org/traccar/api/resource/CalendarResource.java index 641d3b4b5..be675fc79 100644 --- a/src/org/traccar/api/resource/CalendarResource.java +++ b/src/org/traccar/api/resource/CalendarResource.java @@ -33,6 +33,7 @@ import javax.ws.rs.core.Response; import org.traccar.Context; import org.traccar.api.BaseResource; +import org.traccar.database.CalendarManager; import org.traccar.model.Calendar; @Path("calendars") @@ -44,28 +45,29 @@ public class CalendarResource extends BaseResource { public Collection get( @QueryParam("all") boolean all, @QueryParam("userId") long userId) throws SQLException { + CalendarManager calendarManager = Context.getCalendarManager(); if (all) { if (Context.getPermissionsManager().isAdmin(getUserId())) { - return Context.getCalendarManager().getAllCalendars(); + return calendarManager.getItems(Calendar.class, calendarManager.getAllItems()); } else { Context.getPermissionsManager().checkManager(getUserId()); - return Context.getCalendarManager().getManagedCalendars(getUserId()); + return calendarManager.getItems(Calendar.class, calendarManager.getManagedItems(getUserId())); } } else { if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); - return Context.getCalendarManager().getUserCalendars(userId); + return calendarManager.getItems(Calendar.class, calendarManager.getUserItems(userId)); } } @POST public Response add(Calendar entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getCalendarManager().addCalendar(entity); + Context.getCalendarManager().addItem(entity); Context.getDataManager().linkCalendar(getUserId(), entity.getId()); - Context.getCalendarManager().refreshUserCalendars(); + Context.getCalendarManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -73,8 +75,8 @@ public class CalendarResource extends BaseResource { @PUT public Response update(Calendar entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkCalendar(getUserId(), entity.getId()); - Context.getCalendarManager().updateCalendar(entity); + Context.getPermissionsManager().checkPermission("calendar", getUserId(), entity.getId()); + Context.getCalendarManager().updateItem(entity); return Response.ok(entity).build(); } @@ -82,8 +84,8 @@ public class CalendarResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkCalendar(getUserId(), id); - Context.getCalendarManager().removeCalendar(id); + Context.getPermissionsManager().checkPermission("calendar", getUserId(), id); + Context.getCalendarManager().removeItem(id); return Response.noContent().build(); } } diff --git a/src/org/traccar/api/resource/DeviceAttributeResource.java b/src/org/traccar/api/resource/DeviceAttributeResource.java index 82d17bcc6..bb833d4db 100644 --- a/src/org/traccar/api/resource/DeviceAttributeResource.java +++ b/src/org/traccar/api/resource/DeviceAttributeResource.java @@ -39,7 +39,7 @@ public class DeviceAttributeResource extends BaseResource { public Response add(DeviceAttribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkAttribute(getUserId(), entity.getAttributeId()); + Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); Context.getDataManager().linkDeviceAttribute(entity.getDeviceId(), entity.getAttributeId()); Context.getAttributesManager().refresh(); return Response.ok(entity).build(); @@ -49,7 +49,7 @@ public class DeviceAttributeResource extends BaseResource { public Response remove(DeviceAttribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkAttribute(getUserId(), entity.getAttributeId()); + Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); Context.getDataManager().unlinkDeviceAttribute(entity.getDeviceId(), entity.getAttributeId()); Context.getAttributesManager().refresh(); return Response.noContent().build(); diff --git a/src/org/traccar/api/resource/DeviceDriverResource.java b/src/org/traccar/api/resource/DeviceDriverResource.java index 341c50909..286f2223f 100644 --- a/src/org/traccar/api/resource/DeviceDriverResource.java +++ b/src/org/traccar/api/resource/DeviceDriverResource.java @@ -39,7 +39,7 @@ public class DeviceDriverResource extends BaseResource { public Response add(DeviceDriver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); Context.getDataManager().linkDeviceDriver(entity.getDeviceId(), entity.getDriverId()); Context.getDriversManager().refresh(); return Response.ok(entity).build(); @@ -49,7 +49,7 @@ public class DeviceDriverResource extends BaseResource { public Response remove(DeviceDriver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); Context.getDataManager().unlinkDeviceDriver(entity.getDeviceId(), entity.getDriverId()); Context.getDriversManager().refresh(); return Response.noContent().build(); diff --git a/src/org/traccar/api/resource/DeviceGeofenceResource.java b/src/org/traccar/api/resource/DeviceGeofenceResource.java index 6254fe3cf..8034e2168 100644 --- a/src/org/traccar/api/resource/DeviceGeofenceResource.java +++ b/src/org/traccar/api/resource/DeviceGeofenceResource.java @@ -38,7 +38,7 @@ public class DeviceGeofenceResource extends BaseResource { public Response add(DeviceGeofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkGeofence(getUserId(), entity.getGeofenceId()); + Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); Context.getDataManager().linkDeviceGeofence(entity.getDeviceId(), entity.getGeofenceId()); Context.getGeofenceManager().refresh(); return Response.ok(entity).build(); @@ -48,7 +48,7 @@ public class DeviceGeofenceResource extends BaseResource { public Response remove(DeviceGeofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkGeofence(getUserId(), entity.getGeofenceId()); + Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); Context.getDataManager().unlinkDeviceGeofence(entity.getDeviceId(), entity.getGeofenceId()); Context.getGeofenceManager().refresh(); return Response.noContent().build(); diff --git a/src/org/traccar/api/resource/DriverPermissionResource.java b/src/org/traccar/api/resource/DriverPermissionResource.java index fd1ca7c6d..4d890cae9 100644 --- a/src/org/traccar/api/resource/DriverPermissionResource.java +++ b/src/org/traccar/api/resource/DriverPermissionResource.java @@ -40,9 +40,9 @@ public class DriverPermissionResource extends BaseResource { public Response add(DriverPermission entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); Context.getDataManager().linkDriver(entity.getUserId(), entity.getDriverId()); - Context.getDriversManager().refreshUserDrivers(); + Context.getDriversManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -50,9 +50,9 @@ public class DriverPermissionResource extends BaseResource { public Response remove(DriverPermission entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); Context.getDataManager().unlinkDriver(entity.getUserId(), entity.getDriverId()); - Context.getDriversManager().refreshUserDrivers(); + Context.getDriversManager().refreshUserItems(); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index 7fe0af473..3d6a12795 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -50,44 +50,44 @@ public class DriverResource extends BaseResource { DriversManager driversManager = Context.getDriversManager(); if (refresh) { - driversManager.refreshDrivers(); + driversManager.refreshItems(); } Set result = new HashSet<>(); if (all) { if (Context.getPermissionsManager().isAdmin(getUserId())) { - result.addAll(driversManager.getAllDrivers()); + result.addAll(driversManager.getAllItems()); } else { Context.getPermissionsManager().checkManager(getUserId()); - result.addAll(driversManager.getManagedDrivers(getUserId())); + result.addAll(driversManager.getManagedItems(getUserId())); } } else { if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); - result.addAll(driversManager.getUserDrivers(userId)); + result.addAll(driversManager.getUserItems(userId)); } if (groupId != 0) { Context.getPermissionsManager().checkGroup(getUserId(), groupId); - result.retainAll(driversManager.getGroupDrivers(groupId)); + result.retainAll(driversManager.getGroupItems(groupId)); } if (deviceId != 0) { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - result.retainAll(driversManager.getDeviceDrivers(deviceId)); + result.retainAll(driversManager.getDeviceItems(deviceId)); } - return driversManager.getDrivers(result); + return driversManager.getItems(Driver.class, result); } @POST public Response add(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getDriversManager().addDriver(entity); + Context.getDriversManager().addItem(entity); Context.getDataManager().linkDriver(getUserId(), entity.getId()); - Context.getDriversManager().refreshUserDrivers(); + Context.getDriversManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -95,8 +95,8 @@ public class DriverResource extends BaseResource { @PUT public Response update(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDriver(getUserId(), entity.getId()); - Context.getDriversManager().updateDriver(entity); + Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getId()); + Context.getDriversManager().updateItem(entity); return Response.ok(entity).build(); } @@ -104,8 +104,8 @@ public class DriverResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDriver(getUserId(), id); - Context.getDriversManager().removeDriver(id); + Context.getPermissionsManager().checkPermission("driver", getUserId(), id); + Context.getDriversManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/EventResource.java b/src/org/traccar/api/resource/EventResource.java index 0ef5456af..9b43bf4b0 100644 --- a/src/org/traccar/api/resource/EventResource.java +++ b/src/org/traccar/api/resource/EventResource.java @@ -25,7 +25,7 @@ public class EventResource extends BaseResource { Event event = Context.getDataManager().getEvent(id); Context.getPermissionsManager().checkDevice(getUserId(), event.getDeviceId()); if (event.getGeofenceId() != 0) { - Context.getPermissionsManager().checkGeofence(getUserId(), event.getGeofenceId()); + Context.getPermissionsManager().checkPermission("geofence", getUserId(), event.getGeofenceId()); } return event; } diff --git a/src/org/traccar/api/resource/GeofencePermissionResource.java b/src/org/traccar/api/resource/GeofencePermissionResource.java index 8faa63d85..a569e56fd 100644 --- a/src/org/traccar/api/resource/GeofencePermissionResource.java +++ b/src/org/traccar/api/resource/GeofencePermissionResource.java @@ -37,9 +37,9 @@ public class GeofencePermissionResource extends BaseResource { public Response add(GeofencePermission entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkGeofence(getUserId(), entity.getGeofenceId()); + Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); Context.getDataManager().linkGeofence(entity.getUserId(), entity.getGeofenceId()); - Context.getGeofenceManager().refreshUserGeofences(); + Context.getGeofenceManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -47,9 +47,9 @@ public class GeofencePermissionResource extends BaseResource { public Response remove(GeofencePermission entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkGeofence(getUserId(), entity.getGeofenceId()); + Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); Context.getDataManager().unlinkGeofence(entity.getUserId(), entity.getGeofenceId()); - Context.getGeofenceManager().refreshUserGeofences(); + Context.getGeofenceManager().refreshUserItems(); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/GeofenceResource.java b/src/org/traccar/api/resource/GeofenceResource.java index d5acf106a..4a52822cc 100644 --- a/src/org/traccar/api/resource/GeofenceResource.java +++ b/src/org/traccar/api/resource/GeofenceResource.java @@ -49,44 +49,44 @@ public class GeofenceResource extends BaseResource { GeofenceManager geofenceManager = Context.getGeofenceManager(); if (refresh) { - geofenceManager.refreshGeofences(); + geofenceManager.refreshItems(); } Set result = new HashSet<>(); if (all) { if (Context.getPermissionsManager().isAdmin(getUserId())) { - result.addAll(geofenceManager.getAllGeofencesIds()); + result.addAll(geofenceManager.getAllItems()); } else { Context.getPermissionsManager().checkManager(getUserId()); - result.addAll(geofenceManager.getManagedGeofencesIds(getUserId())); + result.addAll(geofenceManager.getManagedItems(getUserId())); } } else { if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); - result.addAll(geofenceManager.getUserGeofencesIds(userId)); + result.addAll(geofenceManager.getUserItems(userId)); } if (groupId != 0) { Context.getPermissionsManager().checkGroup(getUserId(), groupId); - result.retainAll(geofenceManager.getGroupGeofencesIds(groupId)); + result.retainAll(geofenceManager.getGroupItems(groupId)); } if (deviceId != 0) { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - result.retainAll(geofenceManager.getDeviceGeofencesIds(deviceId)); + result.retainAll(geofenceManager.getDeviceItems(deviceId)); } - return geofenceManager.getGeofences(result); + return geofenceManager.getItems(Geofence.class, result); } @POST public Response add(Geofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getDataManager().addGeofence(entity); + Context.getGeofenceManager().addItem(entity); Context.getDataManager().linkGeofence(getUserId(), entity.getId()); - Context.getGeofenceManager().refreshGeofences(); + Context.getGeofenceManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -94,8 +94,8 @@ public class GeofenceResource extends BaseResource { @PUT public Response update(Geofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGeofence(getUserId(), entity.getId()); - Context.getGeofenceManager().updateGeofence(entity); + Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getId()); + Context.getGeofenceManager().updateItem(entity); return Response.ok(entity).build(); } @@ -103,9 +103,8 @@ public class GeofenceResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGeofence(getUserId(), id); - Context.getDataManager().removeGeofence(id); - Context.getGeofenceManager().refreshGeofences(); + Context.getPermissionsManager().checkPermission("geofence", getUserId(), id); + Context.getGeofenceManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/GroupAttributeResource.java b/src/org/traccar/api/resource/GroupAttributeResource.java index d8b8b58c9..5df63194e 100644 --- a/src/org/traccar/api/resource/GroupAttributeResource.java +++ b/src/org/traccar/api/resource/GroupAttributeResource.java @@ -39,7 +39,7 @@ public class GroupAttributeResource extends BaseResource { public Response add(GroupAttribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkAttribute(getUserId(), entity.getAttributeId()); + Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); Context.getDataManager().linkGroupAttribute(entity.getGroupId(), entity.getAttributeId()); Context.getAttributesManager().refresh(); return Response.ok(entity).build(); @@ -49,7 +49,7 @@ public class GroupAttributeResource extends BaseResource { public Response remove(GroupAttribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkAttribute(getUserId(), entity.getAttributeId()); + Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); Context.getDataManager().unlinkGroupAttribute(entity.getGroupId(), entity.getAttributeId()); Context.getAttributesManager().refresh(); return Response.noContent().build(); diff --git a/src/org/traccar/api/resource/GroupDriverResource.java b/src/org/traccar/api/resource/GroupDriverResource.java index 76fc2892c..71c1aca29 100644 --- a/src/org/traccar/api/resource/GroupDriverResource.java +++ b/src/org/traccar/api/resource/GroupDriverResource.java @@ -39,7 +39,7 @@ public class GroupDriverResource extends BaseResource { public Response add(GroupDriver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); Context.getDataManager().linkGroupDriver(entity.getGroupId(), entity.getDriverId()); Context.getDriversManager().refresh(); return Response.ok(entity).build(); @@ -49,7 +49,7 @@ public class GroupDriverResource extends BaseResource { public Response remove(GroupDriver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkDriver(getUserId(), entity.getDriverId()); + Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); Context.getDataManager().unlinkGroupDriver(entity.getGroupId(), entity.getDriverId()); Context.getDriversManager().refresh(); return Response.noContent().build(); diff --git a/src/org/traccar/api/resource/GroupGeofenceResource.java b/src/org/traccar/api/resource/GroupGeofenceResource.java index 81fd4e45f..14000c4b5 100644 --- a/src/org/traccar/api/resource/GroupGeofenceResource.java +++ b/src/org/traccar/api/resource/GroupGeofenceResource.java @@ -37,7 +37,7 @@ public class GroupGeofenceResource extends BaseResource { public Response add(GroupGeofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkGeofence(getUserId(), entity.getGeofenceId()); + Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); Context.getDataManager().linkGroupGeofence(entity.getGroupId(), entity.getGeofenceId()); Context.getGeofenceManager().refresh(); return Response.ok(entity).build(); @@ -47,7 +47,7 @@ public class GroupGeofenceResource extends BaseResource { public Response remove(GroupGeofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkGeofence(getUserId(), entity.getGeofenceId()); + Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); Context.getDataManager().unlinkGroupGeofence(entity.getGroupId(), entity.getGeofenceId()); Context.getGeofenceManager().refresh(); return Response.noContent().build(); diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index 4d8a8b3a4..b9187fdbb 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -104,7 +104,7 @@ public class UserResource extends BaseResource { Context.getPermissionsManager().checkUser(getUserId(), id); Context.getPermissionsManager().removeUser(id); if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refreshUserGeofences(); + Context.getGeofenceManager().refreshUserItems(); } if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); diff --git a/src/org/traccar/database/AttributesManager.java b/src/org/traccar/database/AttributesManager.java index 362d6130f..88bedfba4 100644 --- a/src/org/traccar/database/AttributesManager.java +++ b/src/org/traccar/database/AttributesManager.java @@ -17,183 +17,30 @@ 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.AttributePermission; import org.traccar.model.Attribute; -import org.traccar.model.Device; import org.traccar.model.DeviceAttribute; import org.traccar.model.GroupAttribute; +import org.traccar.model.Identifiable; -public class AttributesManager { - - private final DataManager dataManager; - - private final Map attributes = new ConcurrentHashMap<>(); - private final Map> deviceAttributes = new ConcurrentHashMap<>(); - private final Map> deviceAttributesWithGroups = new ConcurrentHashMap<>(); - private final Map> groupAttributes = new ConcurrentHashMap<>(); - private final Map> userAttributes = new ConcurrentHashMap<>(); +public class AttributesManager extends ExtendedObjectManager { public AttributesManager(DataManager dataManager) { - this.dataManager = dataManager; - refreshAttributes(); - } - - public Set getUserAttributes(long userId) { - if (!userAttributes.containsKey(userId)) { - userAttributes.put(userId, new HashSet()); - } - return userAttributes.get(userId); - } - - public Set getGroupAttributes(long groupId) { - if (!groupAttributes.containsKey(groupId)) { - groupAttributes.put(groupId, new HashSet()); - } - return groupAttributes.get(groupId); - } - - public Set getDeviceAttributes(long deviceId) { - return getDeviceAttributes(deviceAttributes, deviceId); - } - - public Set getAllDeviceAttributes(long deviceId) { - return getDeviceAttributes(deviceAttributesWithGroups, deviceId); - } - - private Set getDeviceAttributes(Map> deviceAttributes, long deviceId) { - if (!deviceAttributes.containsKey(deviceId)) { - deviceAttributes.put(deviceId, new HashSet()); - } - return deviceAttributes.get(deviceId); - } - - public final void refreshAttributes() { - if (dataManager != null) { - try { - attributes.clear(); - for (Attribute attribute : dataManager.getAttributes()) { - attributes.put(attribute.getId(), attribute); - } - } catch (SQLException error) { - Log.warning(error); - } - } - refreshUserAttributes(); + super(dataManager, Attribute.class, AttributePermission.class, DeviceAttribute.class, GroupAttribute.class); + refreshItems(); refresh(); } - public final void refreshUserAttributes() { - if (dataManager != null) { - try { - userAttributes.clear(); - for (AttributePermission attributePermission : dataManager.getAttributePermissions()) { - getUserAttributes(attributePermission.getUserId()).add(attributePermission.getAttributeId()); - } - } catch (SQLException error) { - Log.warning(error); - } - } - } - - public final void refresh() { - if (dataManager != null) { - try { - - Collection databaseGroupAttributes = dataManager.getGroupAttributes(); - - groupAttributes.clear(); - for (GroupAttribute groupAttribute : databaseGroupAttributes) { - getGroupAttributes(groupAttribute.getGroupId()).add(groupAttribute.getAttributeId()); - } - - Collection databaseDeviceAttributes = dataManager.getDeviceAttributes(); - Collection allDevices = Context.getDeviceManager().getAllDevices(); - - deviceAttributes.clear(); - deviceAttributesWithGroups.clear(); - - for (DeviceAttribute deviceAttribute : databaseDeviceAttributes) { - getDeviceAttributes(deviceAttribute.getDeviceId()) - .add(deviceAttribute.getAttributeId()); - getAllDeviceAttributes(deviceAttribute.getDeviceId()) - .add(deviceAttribute.getAttributeId()); - } - - for (Device device : allDevices) { - long groupId = device.getGroupId(); - while (groupId != 0) { - getAllDeviceAttributes(device.getId()).addAll(getGroupAttributes(groupId)); - if (Context.getDeviceManager().getGroupById(groupId) != null) { - groupId = Context.getDeviceManager().getGroupById(groupId).getGroupId(); - } else { - groupId = 0; - } - } - } - - } catch (SQLException error) { - Log.warning(error); - } - } - } - - public void addAttribute(Attribute attribute) throws SQLException { - dataManager.addAttribute(attribute); - attributes.put(attribute.getId(), attribute); - } - - public void updateAttribute(Attribute attribute) throws SQLException { - dataManager.updateAttribute(attribute); - Attribute cachedAttribute = attributes.get(attribute.getId()); + @Override + public void updateItem(Identifiable item) throws SQLException { + Attribute attribute = (Attribute) item; + getDataManager().updateObject(attribute); + Attribute cachedAttribute = (Attribute) getById(item.getId()); cachedAttribute.setDescription(attribute.getDescription()); cachedAttribute.setAttribute(attribute.getAttribute()); cachedAttribute.setExpression(attribute.getExpression()); cachedAttribute.setType(attribute.getType()); } - public void removeAttribute(long computedAttributeId) throws SQLException { - dataManager.removeAttribute(computedAttributeId); - attributes.remove(computedAttributeId); - refreshUserAttributes(); - refresh(); - } - - public boolean checkAttribute(long userId, long attributeId) { - return getUserAttributes(userId).contains(attributeId); - } - - public Attribute getAttribute(long id) { - return attributes.get(id); - } - - public final Collection getAttributes(Set attributeIds) { - Collection result = new LinkedList<>(); - for (long attributeId : attributeIds) { - result.add(getAttribute(attributeId)); - } - return result; - } - - public final Set getAllAttributes() { - return attributes.keySet(); - } - - public final Set getManagedAttributes(long userId) { - Set attributes = new HashSet<>(); - attributes.addAll(getUserAttributes(userId)); - for (long managedUserId : Context.getPermissionsManager().getUserPermissions(userId)) { - attributes.addAll(getUserAttributes(managedUserId)); - } - return attributes; - } - } diff --git a/src/org/traccar/database/CalendarManager.java b/src/org/traccar/database/CalendarManager.java index 31d484327..e00b4faa6 100644 --- a/src/org/traccar/database/CalendarManager.java +++ b/src/org/traccar/database/CalendarManager.java @@ -16,107 +16,14 @@ */ package org.traccar.database; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -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.Calendar; import org.traccar.model.CalendarPermission; -public class CalendarManager { - - private final DataManager dataManager; - - private final Map calendars = new ConcurrentHashMap<>(); - private final Map> userCalendars = new ConcurrentHashMap<>(); +public class CalendarManager extends SimpleObjectManager { public CalendarManager(DataManager dataManager) { - this.dataManager = dataManager; - refreshCalendars(); - } - - public final void refreshCalendars() { - if (dataManager != null) { - try { - calendars.clear(); - for (Calendar calendar : dataManager.getCalendars()) { - calendars.put(calendar.getId(), calendar); - } - } catch (SQLException error) { - Log.warning(error); - } - } - refreshUserCalendars(); - } - - private Set getUserCalendarIds(long userId) { - if (!userCalendars.containsKey(userId)) { - userCalendars.put(userId, new HashSet()); - } - return userCalendars.get(userId); - } - - public Collection getUserCalendars(long userId) { - ArrayList result = new ArrayList<>(); - for (long calendarId : getUserCalendarIds(userId)) { - result.add(calendars.get(calendarId)); - } - return result; - } - - public Collection getManagedCalendars(long userId) { - ArrayList result = new ArrayList<>(); - result.addAll(getUserCalendars(userId)); - for (long managedUserId : Context.getPermissionsManager().getUserPermissions(userId)) { - result.addAll(getUserCalendars(managedUserId)); - } - return result; - } - - public final void refreshUserCalendars() { - if (dataManager != null) { - try { - userCalendars.clear(); - for (CalendarPermission calendarsPermission : dataManager.getCalendarPermissions()) { - getUserCalendarIds(calendarsPermission.getUserId()).add(calendarsPermission.getCalendarId()); - } - } catch (SQLException error) { - Log.warning(error); - } - } - } - - public Calendar getCalendar(long calendarId) { - return calendars.get(calendarId); - } - - public final void addCalendar(Calendar calendar) throws SQLException { - dataManager.addCalendar(calendar); - calendars.put(calendar.getId(), calendar); - } - - public final void updateCalendar(Calendar calendar) throws SQLException { - dataManager.updateCalendar(calendar); - calendars.put(calendar.getId(), calendar); - } - - public final void removeCalendar(long calendarId) throws SQLException { - dataManager.removeCalendar(calendarId); - calendars.remove(calendarId); - refreshUserCalendars(); + super(dataManager, Calendar.class, CalendarPermission.class); + refreshItems(); } - public Collection getAllCalendars() { - return calendars.values(); - } - - public boolean checkCalendar(long userId, long calendarId) { - return getUserCalendarIds(userId).contains(calendarId); - } } diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 1c2a66bcf..4bf4b1b9a 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -38,31 +38,18 @@ import liquibase.resource.ResourceAccessor; import org.traccar.Config; import org.traccar.helper.Log; import org.traccar.model.AttributeAlias; -import org.traccar.model.AttributePermission; -import org.traccar.model.Calendar; -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.Identifiable; import org.traccar.model.Notification; import org.traccar.model.Position; import org.traccar.model.Server; import org.traccar.model.Statistics; import org.traccar.model.User; import org.traccar.model.UserPermission; -import org.traccar.model.DeviceGeofence; -import org.traccar.model.GeofencePermission; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; @@ -362,34 +349,6 @@ public class DataManager { .executeQuery(Event.class); } - public Collection getGeofences() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectGeofencesAll")) - .executeQuery(Geofence.class); - } - - public void addGeofence(Geofence geofence) throws SQLException { - geofence.setId(QueryBuilder.create(dataSource, getQuery("database.insertGeofence"), true) - .setObject(geofence) - .executeUpdate()); - } - - public void updateGeofence(Geofence geofence) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateGeofence")) - .setObject(geofence) - .executeUpdate(); - } - - public void removeGeofence(long geofenceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.deleteGeofence")) - .setLong("id", geofenceId) - .executeUpdate(); - } - - public Collection getGeofencePermissions() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectGeofencePermissions")) - .executeQuery(GeofencePermission.class); - } - public void linkGeofence(long userId, long geofenceId) throws SQLException { QueryBuilder.create(dataSource, getQuery("database.linkGeofence")) .setLong("userId", userId) @@ -404,11 +363,6 @@ public class DataManager { .executeUpdate(); } - public Collection getGroupGeofences() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectGroupGeofences")) - .executeQuery(GroupGeofence.class); - } - public void linkGroupGeofence(long groupId, long geofenceId) throws SQLException { QueryBuilder.create(dataSource, getQuery("database.linkGroupGeofence")) .setLong("groupId", groupId) @@ -423,11 +377,6 @@ public class DataManager { .executeUpdate(); } - public Collection getDeviceGeofences() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectDeviceGeofences")) - .executeQuery(DeviceGeofence.class); - } - public void linkDeviceGeofence(long deviceId, long geofenceId) throws SQLException { QueryBuilder.create(dataSource, getQuery("database.linkDeviceGeofence")) .setLong("deviceId", deviceId) @@ -501,34 +450,6 @@ public class DataManager { .executeUpdate()); } - public Collection getCalendars() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectCalendarsAll")) - .executeQuery(Calendar.class); - } - - public void addCalendar(Calendar calendar) throws SQLException { - calendar.setId(QueryBuilder.create(dataSource, getQuery("database.insertCalendar"), true) - .setObject(calendar) - .executeUpdate()); - } - - public void updateCalendar(Calendar calendar) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateCalendar")) - .setObject(calendar) - .executeUpdate(); - } - - public void removeCalendar(long calendarId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.deleteCalendar")) - .setLong("id", calendarId) - .executeUpdate(); - } - - public Collection getCalendarPermissions() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectCalendarPermissions")) - .executeQuery(CalendarPermission.class); - } - public void linkCalendar(long userId, long calendarId) throws SQLException { QueryBuilder.create(dataSource, getQuery("database.linkCalendar")) .setLong("userId", userId) @@ -562,34 +483,6 @@ public class DataManager { .executeUpdate(); } - public Collection getAttributes() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectAttributes")) - .executeQuery(Attribute.class); - } - - public void addAttribute(Attribute attribute) throws SQLException { - attribute.setId(QueryBuilder.create(dataSource, getQuery("database.insertAttribute"), true) - .setObject(attribute) - .executeUpdate()); - } - - public void updateAttribute(Attribute attribute) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateAttribute")) - .setObject(attribute) - .executeUpdate(); - } - - public void removeAttribute(long computedAttributeId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.deleteAttribute")) - .setLong("id", computedAttributeId) - .executeUpdate(); - } - - public Collection getAttributePermissions() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectAttributePermissions")) - .executeQuery(AttributePermission.class); - } - public void linkAttribute(long userId, long attributeId) throws SQLException { QueryBuilder.create(dataSource, getQuery("database.linkAttribute")) .setLong("userId", userId) @@ -604,11 +497,6 @@ public class DataManager { .executeUpdate(); } - public Collection getGroupAttributes() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectGroupAttributes")) - .executeQuery(GroupAttribute.class); - } - public void linkGroupAttribute(long groupId, long attributeId) throws SQLException { QueryBuilder.create(dataSource, getQuery("database.linkGroupAttribute")) .setLong("groupId", groupId) @@ -623,11 +511,6 @@ public class DataManager { .executeUpdate(); } - public Collection getDeviceAttributes() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectDeviceAttributes")) - .executeQuery(DeviceAttribute.class); - } - public void linkDeviceAttribute(long deviceId, long attributeId) throws SQLException { QueryBuilder.create(dataSource, getQuery("database.linkDeviceAttribute")) .setLong("deviceId", deviceId) @@ -642,34 +525,6 @@ 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) @@ -684,11 +539,6 @@ public class DataManager { .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) @@ -703,11 +553,6 @@ public class DataManager { .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) @@ -722,4 +567,30 @@ public class DataManager { .executeUpdate(); } + public Collection getObjects(Class clazz) throws SQLException { + String query = "database.select" + clazz.getSimpleName() + "s"; + return QueryBuilder.create(dataSource, getQuery(query)).executeQuery(clazz); + } + + public void addObject(Identifiable entity) throws SQLException { + String query = "database.insert" + entity.getClass().getSimpleName(); + entity.setId(QueryBuilder.create(dataSource, getQuery(query), true) + .setObject(entity) + .executeUpdate()); + } + + public void updateObject(Identifiable entity) throws SQLException { + String query = "database.update" + entity.getClass().getSimpleName(); + QueryBuilder.create(dataSource, getQuery(query)) + .setObject(entity) + .executeUpdate(); + } + + public void removeObject(Class clazz, long entityId) throws SQLException { + String query = "database.delete" + clazz.getSimpleName(); + QueryBuilder.create(dataSource, getQuery(query)) + .setLong("id", entityId) + .executeUpdate(); + } + } diff --git a/src/org/traccar/database/DriversManager.java b/src/org/traccar/database/DriversManager.java index e89d59311..391708f64 100644 --- a/src/org/traccar/database/DriversManager.java +++ b/src/org/traccar/database/DriversManager.java @@ -17,147 +17,53 @@ 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; +import org.traccar.model.Identifiable; -public class DriversManager { +public class DriversManager extends ExtendedObjectManager { - 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(); + super(dataManager, Driver.class, DriverPermission.class, DeviceDriver.class, GroupDriver.class); + refreshItems(); refresh(); } - public final void refreshUserDrivers() { - if (dataManager != null) { + @Override + public void refreshItems() { + if (getDataManager() != null) { try { - userDrivers.clear(); - for (DriverPermission driverPermission : dataManager.getDriverPermissions()) { - getUserDrivers(driverPermission.getUserId()).add(driverPermission.getDriverId()); + clearItems(); + for (Identifiable item : getDataManager().getObjects(getBaseClass())) { + putItem(item.getId(), item); + driversByUniqueId.put(((Driver) item).getUniqueId(), (Driver) item); } } catch (SQLException error) { Log.warning(error); } } + refreshUserItems(); } - 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); + @Override + public void addItem(Identifiable item) throws SQLException { + super.addItem(item); + driversByUniqueId.put(((Driver) item).getUniqueId(), (Driver) item); } - public void updateDriver(Driver driver) throws SQLException { - dataManager.updateDriver(driver); - Driver cachedDriver = drivers.get(driver.getId()); + @Override + public void updateItem(Identifiable item) throws SQLException { + Driver driver = (Driver) item; + getDataManager().updateObject(driver); + Driver cachedDriver = (Driver) getById(driver.getId()); cachedDriver.setName(driver.getName()); if (!driver.getUniqueId().equals(cachedDriver.getUniqueId())) { driversByUniqueId.remove(cachedDriver.getUniqueId()); @@ -167,47 +73,20 @@ public class DriversManager { cachedDriver.setAttributes(driver.getAttributes()); } - public void removeDriver(long driverId) throws SQLException { - dataManager.removeDriver(driverId); - if (drivers.containsKey(driverId)) { - String driverUniqueId = drivers.get(driverId).getUniqueId(); - drivers.remove(driverId); + @Override + public void removeItem(long driverId) throws SQLException { + Driver cachedDriver = (Driver) getById(driverId); + getDataManager().removeObject(cachedDriver.getClass(), driverId); + if (cachedDriver != null) { + String driverUniqueId = cachedDriver.getUniqueId(); + removeCachedItem(driverId); driversByUniqueId.remove(driverUniqueId); } - refreshUserDrivers(); + refreshUserItems(); 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; - } } diff --git a/src/org/traccar/database/ExtendedObjectManager.java b/src/org/traccar/database/ExtendedObjectManager.java new file mode 100644 index 000000000..5147b9f9f --- /dev/null +++ b/src/org/traccar/database/ExtendedObjectManager.java @@ -0,0 +1,129 @@ +/* + * 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.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.traccar.Context; +import org.traccar.helper.Log; +import org.traccar.model.BaseDevicePermission; +import org.traccar.model.BaseGroupPermission; +import org.traccar.model.BaseUserPermission; +import org.traccar.model.Device; +import org.traccar.model.Identifiable; + +public abstract class ExtendedObjectManager extends SimpleObjectManager { + + private final Map> deviceItems = new ConcurrentHashMap<>(); + private final Map> deviceItemsWithGroups = new ConcurrentHashMap<>(); + private final Map> groupItems = new ConcurrentHashMap<>(); + + private Class devicePermissionClass; + private Class groupPermissionClass; + + protected ExtendedObjectManager(DataManager dataManager, + Class baseClass, + Class permissionClass, + Class devicePermissionClass, + Class groupPermissionClass) { + super(dataManager, baseClass, permissionClass); + this.devicePermissionClass = devicePermissionClass; + this.groupPermissionClass = groupPermissionClass; + } + + public final Set getGroupItems(long groupId) { + if (!groupItems.containsKey(groupId)) { + groupItems.put(groupId, new HashSet()); + } + return groupItems.get(groupId); + } + + protected final void clearGroupItems() { + groupItems.clear(); + } + + public final Set getDeviceItems(long deviceId) { + if (!deviceItems.containsKey(deviceId)) { + deviceItems.put(deviceId, new HashSet()); + } + return deviceItems.get(deviceId); + } + + protected final void clearDeviceItems() { + deviceItems.clear(); + } + + public Set getAllDeviceItems(long deviceId) { + if (!deviceItemsWithGroups.containsKey(deviceId)) { + deviceItemsWithGroups.put(deviceId, new HashSet()); + } + return deviceItemsWithGroups.get(deviceId); + } + + @Override + public void removeItem(long itemId) throws SQLException { + super.removeItem(itemId); + refresh(); + } + + public void refresh() { + if (getDataManager() != null) { + try { + + Collection databaseGroupPermissions = + getDataManager().getObjects(groupPermissionClass); + + clearGroupItems(); + for (BaseGroupPermission groupPermission : databaseGroupPermissions) { + getGroupItems(groupPermission.getGroupId()).add(groupPermission.getSlaveId()); + } + + Collection databaseDevicePermissions = + getDataManager().getObjects(devicePermissionClass); + Collection allDevices = Context.getDeviceManager().getAllDevices(); + + clearDeviceItems(); + deviceItemsWithGroups.clear(); + + for (BaseDevicePermission devicePermission : databaseDevicePermissions) { + getDeviceItems(devicePermission.getDeviceId()).add(devicePermission.getSlaveId()); + getAllDeviceItems(devicePermission.getDeviceId()).add(devicePermission.getSlaveId()); + } + + for (Device device : allDevices) { + long groupId = device.getGroupId(); + while (groupId != 0) { + getAllDeviceItems(device.getId()).addAll(getGroupItems(groupId)); + if (Context.getDeviceManager().getGroupById(groupId) != null) { + groupId = Context.getDeviceManager().getGroupById(groupId).getGroupId(); + } else { + groupId = 0; + } + } + } + + } catch (SQLException error) { + Log.warning(error); + } + } + } +} diff --git a/src/org/traccar/database/GeofenceManager.java b/src/org/traccar/database/GeofenceManager.java index b8e6a5d73..868804d8f 100644 --- a/src/org/traccar/database/GeofenceManager.java +++ b/src/org/traccar/database/GeofenceManager.java @@ -15,20 +15,10 @@ */ package org.traccar.database; -import java.sql.SQLException; import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; import org.traccar.Context; -import org.traccar.helper.Log; import org.traccar.model.Device; import org.traccar.model.DeviceGeofence; import org.traccar.model.Geofence; @@ -36,269 +26,45 @@ import org.traccar.model.GeofencePermission; import org.traccar.model.GroupGeofence; import org.traccar.model.Position; -public class GeofenceManager { - - private final DataManager dataManager; - - private final Map geofences = new HashMap<>(); - private final Map> userGeofences = new HashMap<>(); - private final Map> groupGeofences = new HashMap<>(); - - private final Map> deviceGeofencesWithGroups = new HashMap<>(); - private final Map> deviceGeofences = new HashMap<>(); - - private final ReadWriteLock deviceGeofencesLock = new ReentrantReadWriteLock(); - private final ReadWriteLock geofencesLock = new ReentrantReadWriteLock(); - private final ReadWriteLock groupGeofencesLock = new ReentrantReadWriteLock(); - private final ReadWriteLock userGeofencesLock = new ReentrantReadWriteLock(); +public class GeofenceManager extends ExtendedObjectManager { public GeofenceManager(DataManager dataManager) { - this.dataManager = dataManager; - refreshGeofences(); - } - - private Set getUserGeofences(long userId) { - if (!userGeofences.containsKey(userId)) { - userGeofences.put(userId, new HashSet()); - } - return userGeofences.get(userId); - } - - public Set getUserGeofencesIds(long userId) { - userGeofencesLock.readLock().lock(); - try { - return getUserGeofences(userId); - } finally { - userGeofencesLock.readLock().unlock(); - } - } - - private Set getGroupGeofences(long groupId) { - if (!groupGeofences.containsKey(groupId)) { - groupGeofences.put(groupId, new HashSet()); - } - return groupGeofences.get(groupId); - } - - public Set getGroupGeofencesIds(long groupId) { - groupGeofencesLock.readLock().lock(); - try { - return getGroupGeofences(groupId); - } finally { - groupGeofencesLock.readLock().unlock(); - } - } - - public Set getAllDeviceGeofences(long deviceId) { - deviceGeofencesLock.readLock().lock(); - try { - return getDeviceGeofences(deviceGeofencesWithGroups, deviceId); - } finally { - deviceGeofencesLock.readLock().unlock(); - } - } - - public Set getDeviceGeofencesIds(long deviceId) { - deviceGeofencesLock.readLock().lock(); - try { - return getDeviceGeofences(deviceGeofences, deviceId); - } finally { - deviceGeofencesLock.readLock().unlock(); - } - } - - private Set getDeviceGeofences(Map> deviceGeofences, long deviceId) { - if (!deviceGeofences.containsKey(deviceId)) { - deviceGeofences.put(deviceId, new HashSet()); - } - return deviceGeofences.get(deviceId); - } - - public final void refreshGeofences() { - if (dataManager != null) { - try { - geofencesLock.writeLock().lock(); - try { - geofences.clear(); - for (Geofence geofence : dataManager.getGeofences()) { - geofences.put(geofence.getId(), geofence); - } - } finally { - geofencesLock.writeLock().unlock(); - } - } catch (SQLException error) { - Log.warning(error); - } - } - refreshUserGeofences(); + super(dataManager, Geofence.class, GeofencePermission.class, DeviceGeofence.class, GroupGeofence.class); + refreshItems(); refresh(); } - public final void refreshUserGeofences() { - if (dataManager != null) { - try { - userGeofencesLock.writeLock().lock(); - try { - userGeofences.clear(); - for (GeofencePermission geofencePermission : dataManager.getGeofencePermissions()) { - getUserGeofences(geofencePermission.getUserId()).add(geofencePermission.getGeofenceId()); - } - } finally { - userGeofencesLock.writeLock().unlock(); - } - } catch (SQLException error) { - Log.warning(error); - } - } - } - public final void refresh() { - if (dataManager != null) { - try { - - Collection databaseGroupGeofences = dataManager.getGroupGeofences(); - groupGeofencesLock.writeLock().lock(); - try { - groupGeofences.clear(); - for (GroupGeofence groupGeofence : databaseGroupGeofences) { - getGroupGeofences(groupGeofence.getGroupId()).add(groupGeofence.getGeofenceId()); - } - } finally { - groupGeofencesLock.writeLock().unlock(); - } - - Collection databaseDeviceGeofences = dataManager.getDeviceGeofences(); - Collection allDevices = Context.getDeviceManager().getAllDevices(); - - groupGeofencesLock.readLock().lock(); - deviceGeofencesLock.writeLock().lock(); - try { - deviceGeofences.clear(); - deviceGeofencesWithGroups.clear(); - - for (DeviceGeofence deviceGeofence : databaseDeviceGeofences) { - getDeviceGeofences(deviceGeofences, deviceGeofence.getDeviceId()) - .add(deviceGeofence.getGeofenceId()); - getDeviceGeofences(deviceGeofencesWithGroups, deviceGeofence.getDeviceId()) - .add(deviceGeofence.getGeofenceId()); - } - - for (Device device : allDevices) { - long groupId = device.getGroupId(); - while (groupId != 0) { - getDeviceGeofences(deviceGeofencesWithGroups, - device.getId()).addAll(getGroupGeofences(groupId)); - if (Context.getDeviceManager().getGroupById(groupId) != null) { - groupId = Context.getDeviceManager().getGroupById(groupId).getGroupId(); - } else { - groupId = 0; - } - } - List deviceGeofenceIds = device.getGeofenceIds(); - if (deviceGeofenceIds == null) { - deviceGeofenceIds = new ArrayList<>(); - } else { - deviceGeofenceIds.clear(); - } - Position lastPosition = Context.getIdentityManager().getLastPosition(device.getId()); - if (lastPosition != null && deviceGeofencesWithGroups.containsKey(device.getId())) { - for (long geofenceId : deviceGeofencesWithGroups.get(device.getId())) { - Geofence geofence = getGeofence(geofenceId); - if (geofence != null && geofence.getGeometry() - .containsPoint(lastPosition.getLatitude(), lastPosition.getLongitude())) { - deviceGeofenceIds.add(geofenceId); - } - } - } - device.setGeofenceIds(deviceGeofenceIds); - } - - } finally { - deviceGeofencesLock.writeLock().unlock(); - groupGeofencesLock.readLock().unlock(); - } - - } catch (SQLException error) { - Log.warning(error); - } - } - } - - public final Collection getAllGeofences() { - geofencesLock.readLock().lock(); - try { - return geofences.values(); - } finally { - geofencesLock.readLock().unlock(); - } - } - - public final Set getAllGeofencesIds() { - geofencesLock.readLock().lock(); - try { - return geofences.keySet(); - } finally { - geofencesLock.readLock().unlock(); - } - } - - public final Set getManagedGeofencesIds(long userId) { - Set geofences = new HashSet<>(); - geofences.addAll(getUserGeofencesIds(userId)); - for (long managedUserId : Context.getPermissionsManager().getUserPermissions(userId)) { - geofences.addAll(getUserGeofencesIds(managedUserId)); - } - return geofences; - } - - public final Collection getGeofences(Set geofencesIds) { - geofencesLock.readLock().lock(); - try { - Collection result = new LinkedList<>(); - for (long geofenceId : geofencesIds) { - result.add(getGeofence(geofenceId)); - } - return result; - } finally { - geofencesLock.readLock().unlock(); - } - } - - public final Geofence getGeofence(long geofenceId) { - geofencesLock.readLock().lock(); - try { - return geofences.get(geofenceId); - } finally { - geofencesLock.readLock().unlock(); - } - } - - public final void updateGeofence(Geofence geofence) { - geofencesLock.writeLock().lock(); - try { - geofences.put(geofence.getId(), geofence); - } finally { - geofencesLock.writeLock().unlock(); - } - try { - dataManager.updateGeofence(geofence); - } catch (SQLException error) { - Log.warning(error); - } - } - - public boolean checkGeofence(long userId, long geofenceId) { - return getUserGeofencesIds(userId).contains(geofenceId); + super.refresh(); + recalculateDevicesGeofences(); } public List getCurrentDeviceGeofences(Position position) { List result = new ArrayList<>(); - for (long geofenceId : getAllDeviceGeofences(position.getDeviceId())) { - if (getGeofence(geofenceId).getGeometry().containsPoint(position.getLatitude(), position.getLongitude())) { + for (long geofenceId : getAllDeviceItems(position.getDeviceId())) { + Geofence geofence = (Geofence) getById(geofenceId); + if (geofence != null && geofence.getGeometry() + .containsPoint(position.getLatitude(), position.getLongitude())) { result.add(geofenceId); } } return result; } + public void recalculateDevicesGeofences() { + for (Device device : Context.getDeviceManager().getAllDevices()) { + List deviceGeofenceIds = device.getGeofenceIds(); + if (deviceGeofenceIds == null) { + deviceGeofenceIds = new ArrayList<>(); + } else { + deviceGeofenceIds.clear(); + } + Position lastPosition = Context.getIdentityManager().getLastPosition(device.getId()); + if (lastPosition != null && getAllDeviceItems(device.getId()) != null) { + deviceGeofenceIds.addAll(getCurrentDeviceGeofences(lastPosition)); + } + device.setGeofenceIds(deviceGeofenceIds); + } + } + } diff --git a/src/org/traccar/database/NotificationManager.java b/src/org/traccar/database/NotificationManager.java index 48caa615c..11d5a9aca 100644 --- a/src/org/traccar/database/NotificationManager.java +++ b/src/org/traccar/database/NotificationManager.java @@ -57,7 +57,7 @@ public class NotificationManager { Set users = Context.getPermissionsManager().getDeviceUsers(event.getDeviceId()); for (long userId : users) { if (event.getGeofenceId() == 0 || Context.getGeofenceManager() != null - && Context.getGeofenceManager().checkGeofence(userId, event.getGeofenceId())) { + && Context.getGeofenceManager().checkItemPermission(userId, event.getGeofenceId())) { Notification notification = getUserNotificationByType(userId, event.getType()); if (notification != null) { if (notification.getWeb()) { diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 82ca6af49..f88e14bfe 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -298,52 +298,37 @@ public class PermissionsManager { } } - public void checkGeofence(long userId, long geofenceId) throws SecurityException { - if (!Context.getGeofenceManager().checkGeofence(userId, geofenceId) && !isAdmin(userId)) { - checkManager(userId); - for (long managedUserId : getUserPermissions(userId)) { - if (Context.getGeofenceManager().checkGeofence(managedUserId, geofenceId)) { - return; - } - } - throw new SecurityException("Geofence access denied"); - } - } - - public void checkAttribute(long userId, long attributeId) throws SecurityException { - if (!Context.getAttributesManager().checkAttribute(userId, attributeId) && !isAdmin(userId)) { - checkManager(userId); - for (long managedUserId : getUserPermissions(userId)) { - if (Context.getAttributesManager().checkAttribute(managedUserId, attributeId)) { - return; - } - } - throw new SecurityException("Attribute access denied"); - } - } - - 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); - for (long managedUserId : getUserPermissions(userId)) { - if (Context.getCalendarManager().checkCalendar(managedUserId, calendarId)) { - return; + public void checkPermission(String object, long userId, long objectId) throws SecurityException { + SimpleObjectManager manager = null; + + switch (object) { + case "geofence": + manager = Context.getGeofenceManager(); + break; + case "attribute": + manager = Context.getAttributesManager(); + break; + case "driver": + manager = Context.getDriversManager(); + break; + case "calendar": + manager = Context.getCalendarManager(); + break; + default: + throw new IllegalArgumentException("Unknown object type"); + } + + if (manager != null) { + if (manager.checkItemPermission(userId, objectId) && !isAdmin(userId)) { + checkManager(userId); + for (long managedUserId : getUserPermissions(userId)) { + if (manager.checkItemPermission(managedUserId, objectId)) { + return; + } } + throw new SecurityException(object.substring(0, 1).toUpperCase() + object.substring(1) + + " access denied"); } - throw new SecurityException("Calendar access denied"); } } diff --git a/src/org/traccar/database/SimpleObjectManager.java b/src/org/traccar/database/SimpleObjectManager.java new file mode 100644 index 000000000..84d41a84f --- /dev/null +++ b/src/org/traccar/database/SimpleObjectManager.java @@ -0,0 +1,164 @@ +/* + * 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.BaseUserPermission; +import org.traccar.model.Identifiable; + +public abstract class SimpleObjectManager { + + private final DataManager dataManager; + + private final Map items = new ConcurrentHashMap<>(); + private final Map> userItems = new ConcurrentHashMap<>(); + + private Class baseClass; + private Class permissionClass; + + protected SimpleObjectManager(DataManager dataManager, + Class baseClass, + Class permissionClass) { + this.dataManager = dataManager; + this.baseClass = baseClass; + this.permissionClass = permissionClass; + } + + protected final DataManager getDataManager() { + return dataManager; + } + + protected final Class getBaseClass() { + return baseClass; + } + + public final Identifiable getById(long itemId) { + return items.get(itemId); + } + + protected final void clearItems() { + items.clear(); + } + + protected final void putItem(long itemId, Identifiable item) { + items.put(itemId, item); + } + + protected final void removeCachedItem(long itemId) { + items.remove(itemId); + } + + public final Set getUserItems(long userId) { + if (!userItems.containsKey(userId)) { + userItems.put(userId, new HashSet()); + } + return userItems.get(userId); + } + + protected final void clearUserItems() { + userItems.clear(); + } + + public final boolean checkItemPermission(long userId, long itemId) { + return getUserItems(userId).contains(itemId); + } + + public void refreshItems() { + if (dataManager != null) { + try { + clearItems(); + for (Identifiable item : dataManager.getObjects(this.baseClass)) { + putItem(item.getId(), item); + } + } catch (SQLException error) { + Log.warning(error); + } + } + refreshUserItems(); + } + + public final void refreshUserItems() { + if (dataManager != null) { + try { + clearUserItems(); + for (BaseUserPermission permission : dataManager.getObjects(this.permissionClass)) { + getUserItems(permission.getUserId()).add(permission.getSlaveId()); + } + } catch (SQLException error) { + Log.warning(error); + } + } + } + + public void addItem(Identifiable item) throws SQLException { + dataManager.addObject(item); + putItem(item.getId(), item); + } + + public void updateItem(Identifiable item) throws SQLException { + dataManager.updateObject(item); + putItem(item.getId(), item); + } + + public void removeItem(long itemId) throws SQLException { + Identifiable item = getById(itemId); + if (item != null) { + dataManager.removeObject(item.getClass(), itemId); + removeCachedItem(itemId); + } + refreshUserItems(); + } + +// public final Collection getItems(Set itemIds) { +// Collection result = new LinkedList<>(); +// for (long itemId : itemIds) { +// result.add(getById(itemId)); +// } +// return result; +// } + + public final Collection getItems(Class clazz, Set itemIds) { + Collection result = new LinkedList<>(); + for (long itemId : itemIds) { + result.add((T) getById(itemId)); + } + return result; + } + + public final Set getAllItems() { + return items.keySet(); + } + + public final Set getManagedItems(long userId) { + Set result = new HashSet<>(); + result.addAll(getUserItems(userId)); + for (long managedUserId : Context.getPermissionsManager().getUserPermissions(userId)) { + result.addAll(getUserItems(managedUserId)); + } + return result; + } + +} diff --git a/src/org/traccar/events/GeofenceEventHandler.java b/src/org/traccar/events/GeofenceEventHandler.java index fbec932b1..cdac7993f 100644 --- a/src/org/traccar/events/GeofenceEventHandler.java +++ b/src/org/traccar/events/GeofenceEventHandler.java @@ -22,8 +22,10 @@ import java.util.List; import org.traccar.BaseEventHandler; import org.traccar.Context; import org.traccar.database.GeofenceManager; +import org.traccar.model.Calendar; import org.traccar.model.Device; import org.traccar.model.Event; +import org.traccar.model.Geofence; import org.traccar.model.Position; public class GeofenceEventHandler extends BaseEventHandler { @@ -57,18 +59,20 @@ public class GeofenceEventHandler extends BaseEventHandler { Collection events = new ArrayList<>(); for (long geofenceId : newGeofences) { - long calendarId = geofenceManager.getGeofence(geofenceId).getCalendarId(); - if (calendarId == 0 || Context.getCalendarManager().getCalendar(calendarId) == null - || Context.getCalendarManager().getCalendar(calendarId).checkMoment(position.getFixTime())) { + long calendarId = ((Geofence) geofenceManager.getById(geofenceId)).getCalendarId(); + if (calendarId == 0 || Context.getCalendarManager().getById(calendarId) == null + || ((Calendar) Context.getCalendarManager().getById(calendarId)) + .checkMoment(position.getFixTime())) { Event event = new Event(Event.TYPE_GEOFENCE_ENTER, position.getDeviceId(), position.getId()); event.setGeofenceId(geofenceId); events.add(event); } } for (long geofenceId : oldGeofences) { - long calendarId = geofenceManager.getGeofence(geofenceId).getCalendarId(); - if (calendarId == 0 || Context.getCalendarManager().getCalendar(calendarId) == null - || Context.getCalendarManager().getCalendar(calendarId).checkMoment(position.getFixTime())) { + long calendarId = ((Geofence) geofenceManager.getById(geofenceId)).getCalendarId(); + if (calendarId == 0 || Context.getCalendarManager().getById(calendarId) == null + || ((Calendar) Context.getCalendarManager().getById(calendarId)) + .checkMoment(position.getFixTime())) { Event event = new Event(Event.TYPE_GEOFENCE_EXIT, position.getDeviceId(), position.getId()); event.setGeofenceId(geofenceId); events.add(event); diff --git a/src/org/traccar/model/Attribute.java b/src/org/traccar/model/Attribute.java index 9c3b5e43b..ab12cd2c4 100644 --- a/src/org/traccar/model/Attribute.java +++ b/src/org/traccar/model/Attribute.java @@ -16,17 +16,7 @@ */ package org.traccar.model; -public class Attribute { - - private long id; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } +public class Attribute extends Identifiable { private String description; diff --git a/src/org/traccar/model/AttributeAlias.java b/src/org/traccar/model/AttributeAlias.java index 2835c0558..5aa8a5122 100644 --- a/src/org/traccar/model/AttributeAlias.java +++ b/src/org/traccar/model/AttributeAlias.java @@ -16,17 +16,7 @@ */ package org.traccar.model; -public class AttributeAlias { - - private long id; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } +public class AttributeAlias extends Identifiable { private long deviceId; diff --git a/src/org/traccar/model/AttributePermission.java b/src/org/traccar/model/AttributePermission.java index fe2fe7b6e..e6bbb0f91 100644 --- a/src/org/traccar/model/AttributePermission.java +++ b/src/org/traccar/model/AttributePermission.java @@ -16,17 +16,7 @@ */ package org.traccar.model; -public class AttributePermission { - - private long userId; - - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } +public class AttributePermission extends BaseUserPermission { private long attributeId; @@ -38,4 +28,9 @@ public class AttributePermission { this.attributeId = attributeId; } + @Override + public long getSlaveId() { + return attributeId; + } + } diff --git a/src/org/traccar/model/BaseDevicePermission.java b/src/org/traccar/model/BaseDevicePermission.java new file mode 100644 index 000000000..6eda15d0e --- /dev/null +++ b/src/org/traccar/model/BaseDevicePermission.java @@ -0,0 +1,31 @@ +/* + * 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.model; + +public abstract class BaseDevicePermission implements BasePermission { + + private long deviceId; + + public long getDeviceId() { + return deviceId; + } + + public void setDeviceId(long deviceId) { + this.deviceId = deviceId; + } + +} diff --git a/src/org/traccar/model/BaseGroupPermission.java b/src/org/traccar/model/BaseGroupPermission.java new file mode 100644 index 000000000..5a289cad2 --- /dev/null +++ b/src/org/traccar/model/BaseGroupPermission.java @@ -0,0 +1,31 @@ +/* + * 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.model; + +public abstract class BaseGroupPermission implements BasePermission { + + private long groupId; + + public long getGroupId() { + return groupId; + } + + public void setGroupId(long groupId) { + this.groupId = groupId; + } + +} diff --git a/src/org/traccar/model/BasePermission.java b/src/org/traccar/model/BasePermission.java new file mode 100644 index 000000000..6f1baffdc --- /dev/null +++ b/src/org/traccar/model/BasePermission.java @@ -0,0 +1,23 @@ +/* + * 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.model; + +public interface BasePermission { + + long getSlaveId(); + +} diff --git a/src/org/traccar/model/BaseUserPermission.java b/src/org/traccar/model/BaseUserPermission.java new file mode 100644 index 000000000..64a7be82a --- /dev/null +++ b/src/org/traccar/model/BaseUserPermission.java @@ -0,0 +1,31 @@ +/* + * 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.model; + +public abstract class BaseUserPermission implements BasePermission { + + private long userId; + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + +} diff --git a/src/org/traccar/model/CalendarPermission.java b/src/org/traccar/model/CalendarPermission.java index 59f54e07b..d95e51b0e 100644 --- a/src/org/traccar/model/CalendarPermission.java +++ b/src/org/traccar/model/CalendarPermission.java @@ -16,17 +16,7 @@ */ package org.traccar.model; -public class CalendarPermission { - - private long userId; - - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } +public class CalendarPermission extends BaseUserPermission { private long calendarId; @@ -37,4 +27,9 @@ public class CalendarPermission { public void setCalendarId(long calendarId) { this.calendarId = calendarId; } + + @Override + public long getSlaveId() { + return calendarId; + } } diff --git a/src/org/traccar/model/DeviceAttribute.java b/src/org/traccar/model/DeviceAttribute.java index e0ac6dd98..bfcd873fa 100644 --- a/src/org/traccar/model/DeviceAttribute.java +++ b/src/org/traccar/model/DeviceAttribute.java @@ -16,17 +16,7 @@ */ package org.traccar.model; -public class DeviceAttribute { - - private long deviceId; - - public long getDeviceId() { - return deviceId; - } - - public void setDeviceId(long deviceId) { - this.deviceId = deviceId; - } +public class DeviceAttribute extends BaseDevicePermission { private long attributeId; @@ -37,4 +27,9 @@ public class DeviceAttribute { public void setAttributeId(long attributeId) { this.attributeId = attributeId; } + + @Override + public long getSlaveId() { + return attributeId; + } } diff --git a/src/org/traccar/model/DeviceDriver.java b/src/org/traccar/model/DeviceDriver.java index 2008aaddf..f5257531d 100644 --- a/src/org/traccar/model/DeviceDriver.java +++ b/src/org/traccar/model/DeviceDriver.java @@ -16,17 +16,7 @@ */ package org.traccar.model; -public class DeviceDriver { - - private long deviceId; - - public long getDeviceId() { - return deviceId; - } - - public void setDeviceId(long deviceId) { - this.deviceId = deviceId; - } +public class DeviceDriver extends BaseDevicePermission { private long driverId; @@ -38,4 +28,9 @@ public class DeviceDriver { this.driverId = driverId; } + @Override + public long getSlaveId() { + return driverId; + } + } diff --git a/src/org/traccar/model/DeviceGeofence.java b/src/org/traccar/model/DeviceGeofence.java index 00c99add6..7ea4d3bea 100644 --- a/src/org/traccar/model/DeviceGeofence.java +++ b/src/org/traccar/model/DeviceGeofence.java @@ -15,17 +15,7 @@ */ package org.traccar.model; -public class DeviceGeofence { - - private long deviceId; - - public long getDeviceId() { - return deviceId; - } - - public void setDeviceId(long deviceId) { - this.deviceId = deviceId; - } +public class DeviceGeofence extends BaseDevicePermission { private long geofenceId; @@ -37,4 +27,9 @@ public class DeviceGeofence { this.geofenceId = geofenceId; } + @Override + public long getSlaveId() { + return geofenceId; + } + } diff --git a/src/org/traccar/model/DriverPermission.java b/src/org/traccar/model/DriverPermission.java index cdbcc4a50..44f34c8e6 100644 --- a/src/org/traccar/model/DriverPermission.java +++ b/src/org/traccar/model/DriverPermission.java @@ -16,17 +16,7 @@ */ package org.traccar.model; -public class DriverPermission { - - private long userId; - - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } +public class DriverPermission extends BaseUserPermission { private long driverId; @@ -37,4 +27,9 @@ public class DriverPermission { public void setDriverId(long driverId) { this.driverId = driverId; } + + @Override + public long getSlaveId() { + return driverId; + } } diff --git a/src/org/traccar/model/Extensible.java b/src/org/traccar/model/Extensible.java index b7953d8a6..3b382838e 100644 --- a/src/org/traccar/model/Extensible.java +++ b/src/org/traccar/model/Extensible.java @@ -18,17 +18,7 @@ package org.traccar.model; import java.util.LinkedHashMap; import java.util.Map; -public class Extensible { - - private long id; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } +public class Extensible extends Identifiable { private Map attributes = new LinkedHashMap<>(); diff --git a/src/org/traccar/model/GeofencePermission.java b/src/org/traccar/model/GeofencePermission.java index 464f4e9eb..8606cc3e7 100644 --- a/src/org/traccar/model/GeofencePermission.java +++ b/src/org/traccar/model/GeofencePermission.java @@ -15,17 +15,7 @@ */ package org.traccar.model; -public class GeofencePermission { - - private long userId; - - public long getUserId() { - return userId; - } - - public void setUserId(long userId) { - this.userId = userId; - } +public class GeofencePermission extends BaseUserPermission { private long geofenceId; @@ -37,4 +27,9 @@ public class GeofencePermission { this.geofenceId = geofenceId; } + @Override + public long getSlaveId() { + return geofenceId; + } + } diff --git a/src/org/traccar/model/GroupAttribute.java b/src/org/traccar/model/GroupAttribute.java index a7e8a80bc..cfaf9cc2f 100644 --- a/src/org/traccar/model/GroupAttribute.java +++ b/src/org/traccar/model/GroupAttribute.java @@ -16,17 +16,7 @@ */ package org.traccar.model; -public class GroupAttribute { - - private long groupId; - - public long getGroupId() { - return groupId; - } - - public void setGroupId(long groupId) { - this.groupId = groupId; - } +public class GroupAttribute extends BaseGroupPermission { private long attributeId; @@ -37,4 +27,9 @@ public class GroupAttribute { public void setAttributeId(long attributeId) { this.attributeId = attributeId; } + + @Override + public long getSlaveId() { + return attributeId; + } } diff --git a/src/org/traccar/model/GroupDriver.java b/src/org/traccar/model/GroupDriver.java index 91b205923..9bf74c214 100644 --- a/src/org/traccar/model/GroupDriver.java +++ b/src/org/traccar/model/GroupDriver.java @@ -16,17 +16,7 @@ */ package org.traccar.model; -public class GroupDriver { - - private long groupId; - - public long getGroupId() { - return groupId; - } - - public void setGroupId(long groupId) { - this.groupId = groupId; - } +public class GroupDriver extends BaseGroupPermission { private long driverId; @@ -38,4 +28,9 @@ public class GroupDriver { this.driverId = driverId; } + @Override + public long getSlaveId() { + return driverId; + } + } diff --git a/src/org/traccar/model/GroupGeofence.java b/src/org/traccar/model/GroupGeofence.java index 736e6c704..89830324d 100644 --- a/src/org/traccar/model/GroupGeofence.java +++ b/src/org/traccar/model/GroupGeofence.java @@ -15,17 +15,7 @@ */ package org.traccar.model; -public class GroupGeofence { - - private long groupId; - - public long getGroupId() { - return groupId; - } - - public void setGroupId(long groupId) { - this.groupId = groupId; - } +public class GroupGeofence extends BaseGroupPermission { private long geofenceId; @@ -37,4 +27,9 @@ public class GroupGeofence { this.geofenceId = geofenceId; } + @Override + public long getSlaveId() { + return geofenceId; + } + } diff --git a/src/org/traccar/model/Identifiable.java b/src/org/traccar/model/Identifiable.java new file mode 100644 index 000000000..f22cfe800 --- /dev/null +++ b/src/org/traccar/model/Identifiable.java @@ -0,0 +1,31 @@ +/* + * 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.model; + +public class Identifiable { + + private long id; + + public final long getId() { + return id; + } + + public final void setId(long id) { + this.id = id; + } + +} diff --git a/src/org/traccar/notification/EventForwarder.java b/src/org/traccar/notification/EventForwarder.java index bd7cfc0c5..08f55df75 100644 --- a/src/org/traccar/notification/EventForwarder.java +++ b/src/org/traccar/notification/EventForwarder.java @@ -75,7 +75,7 @@ public final class EventForwarder { } } if (event.getGeofenceId() != 0) { - Geofence geofence = Context.getGeofenceManager().getGeofence(event.getGeofenceId()); + Geofence geofence = (Geofence) Context.getGeofenceManager().getById(event.getGeofenceId()); if (geofence != null) { data.put(KEY_GEOFENCE, geofence); } diff --git a/src/org/traccar/notification/NotificationFormatter.java b/src/org/traccar/notification/NotificationFormatter.java index a30023fdc..cd9959671 100644 --- a/src/org/traccar/notification/NotificationFormatter.java +++ b/src/org/traccar/notification/NotificationFormatter.java @@ -51,7 +51,7 @@ public final class NotificationFormatter { velocityContext.put("speedUnits", ReportUtils.getSpeedUnit(userId)); } if (event.getGeofenceId() != 0) { - velocityContext.put("geofence", Context.getGeofenceManager().getGeofence(event.getGeofenceId())); + velocityContext.put("geofence", Context.getGeofenceManager().getById(event.getGeofenceId())); } String driverUniqueId = event.getString(Position.KEY_DRIVER_UNIQUE_ID); if (driverUniqueId != null) { diff --git a/src/org/traccar/processing/ComputedAttributesHandler.java b/src/org/traccar/processing/ComputedAttributesHandler.java index 536e39ec4..d6a762535 100644 --- a/src/org/traccar/processing/ComputedAttributesHandler.java +++ b/src/org/traccar/processing/ComputedAttributesHandler.java @@ -86,8 +86,8 @@ public class ComputedAttributesHandler extends BaseDataHandler { @Override protected Position handlePosition(Position position) { - Collection attributes = Context.getAttributesManager().getAttributes( - Context.getAttributesManager().getAllDeviceAttributes(position.getDeviceId())); + Collection attributes = Context.getAttributesManager().getItems(Attribute.class, + Context.getAttributesManager().getAllDeviceItems(position.getDeviceId())); for (Attribute attribute : attributes) { if (attribute.getAttribute() != null) { Object result = null; diff --git a/src/org/traccar/reports/Events.java b/src/org/traccar/reports/Events.java index 0706f1382..3a111944c 100644 --- a/src/org/traccar/reports/Events.java +++ b/src/org/traccar/reports/Events.java @@ -50,7 +50,7 @@ public final class Events { for (Event event : events) { if (all || types.contains(event.getType())) { long geofenceId = event.getGeofenceId(); - if (geofenceId == 0 || Context.getGeofenceManager().checkGeofence(userId, geofenceId)) { + if (geofenceId == 0 || Context.getGeofenceManager().checkItemPermission(userId, geofenceId)) { result.add(event); } } @@ -74,8 +74,8 @@ public final class Events { if (all || types.contains(event.getType())) { long geofenceId = event.getGeofenceId(); if (geofenceId != 0) { - if (Context.getGeofenceManager().checkGeofence(userId, geofenceId)) { - Geofence geofence = Context.getGeofenceManager().getGeofence(geofenceId); + if (Context.getGeofenceManager().checkItemPermission(userId, geofenceId)) { + Geofence geofence = (Geofence) Context.getGeofenceManager().getById(geofenceId); if (geofence != null) { geofenceNames.put(geofenceId, geofence.getName()); } -- cgit v1.2.3 From afb9a199f57824ec06c993b6028c35b616f64885 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Thu, 20 Jul 2017 08:56:29 +0500 Subject: Combine permission resources and reuse common database functions --- setup/default.xml | 34 +-- src/org/traccar/BaseProtocolDecoder.java | 4 +- .../api/resource/AttributePermissionResource.java | 58 ---- .../traccar/api/resource/AttributeResource.java | 6 +- .../api/resource/CalendarPermissionResource.java | 57 ---- src/org/traccar/api/resource/CalendarResource.java | 6 +- .../api/resource/DeviceAttributeResource.java | 58 ---- .../traccar/api/resource/DeviceDriverResource.java | 58 ---- .../api/resource/DeviceGeofenceResource.java | 57 ---- .../api/resource/DevicePermissionResource.java | 66 ----- src/org/traccar/api/resource/DeviceResource.java | 45 ++- .../api/resource/DriverPermissionResource.java | 59 ---- src/org/traccar/api/resource/DriverResource.java | 6 +- .../api/resource/GeofencePermissionResource.java | 56 ---- src/org/traccar/api/resource/GeofenceResource.java | 6 +- .../api/resource/GroupAttributeResource.java | 58 ---- .../traccar/api/resource/GroupDriverResource.java | 58 ---- .../api/resource/GroupGeofenceResource.java | 56 ---- .../api/resource/GroupPermissionResource.java | 62 ----- src/org/traccar/api/resource/GroupResource.java | 43 ++- .../traccar/api/resource/PermissionsResource.java | 62 +++++ .../api/resource/UserPermissionResource.java | 56 ---- src/org/traccar/api/resource/UserResource.java | 6 +- src/org/traccar/database/AttributesManager.java | 2 +- src/org/traccar/database/DataManager.java | 309 +-------------------- src/org/traccar/database/DeviceManager.java | 16 +- src/org/traccar/database/DriversManager.java | 4 +- .../traccar/database/ExtendedObjectManager.java | 4 +- src/org/traccar/database/GeofenceManager.java | 7 +- src/org/traccar/database/NotificationManager.java | 10 +- src/org/traccar/database/PermissionsManager.java | 62 ++++- src/org/traccar/database/SimpleObjectManager.java | 8 - 32 files changed, 260 insertions(+), 1139 deletions(-) delete mode 100644 src/org/traccar/api/resource/AttributePermissionResource.java delete mode 100644 src/org/traccar/api/resource/CalendarPermissionResource.java delete mode 100644 src/org/traccar/api/resource/DeviceAttributeResource.java delete mode 100644 src/org/traccar/api/resource/DeviceDriverResource.java delete mode 100644 src/org/traccar/api/resource/DeviceGeofenceResource.java delete mode 100644 src/org/traccar/api/resource/DevicePermissionResource.java delete mode 100644 src/org/traccar/api/resource/DriverPermissionResource.java delete mode 100644 src/org/traccar/api/resource/GeofencePermissionResource.java delete mode 100644 src/org/traccar/api/resource/GroupAttributeResource.java delete mode 100644 src/org/traccar/api/resource/GroupDriverResource.java delete mode 100644 src/org/traccar/api/resource/GroupGeofenceResource.java delete mode 100644 src/org/traccar/api/resource/GroupPermissionResource.java create mode 100644 src/org/traccar/api/resource/PermissionsResource.java delete mode 100644 src/org/traccar/api/resource/UserPermissionResource.java (limited to 'src/org/traccar/api') diff --git a/setup/default.xml b/setup/default.xml index d3651b9f0..dcf995af0 100644 --- a/setup/default.xml +++ b/setup/default.xml @@ -60,7 +60,7 @@ WHERE email = :email - + SELECT * FROM users @@ -111,7 +111,7 @@ SELECT userId, groupId FROM user_group - + SELECT * FROM devices @@ -141,15 +141,15 @@ DELETE FROM devices WHERE id = :id - + INSERT INTO user_device (userId, deviceId) VALUES (:userId, :deviceId) - + DELETE FROM user_device WHERE userId = :userId AND deviceId = :deviceId - + SELECT * FROM groups @@ -165,11 +165,11 @@ DELETE FROM groups WHERE id = :id - + INSERT INTO user_group (userId, groupId) VALUES (:userId, :groupId) - + DELETE FROM user_group WHERE userId = :userId AND groupId = :groupId @@ -234,11 +234,11 @@ SELECT userId, geofenceId FROM user_geofence - + INSERT INTO user_geofence (userId, geofenceId) VALUES (:userId, :geofenceId) - + DELETE FROM user_geofence WHERE userId = :userId AND geofenceId = :geofenceId @@ -353,11 +353,11 @@ SELECT userId, calendarId FROM user_calendar - + INSERT INTO user_calendar (userId, calendarId) VALUES (:userId, :calendarId) - + DELETE FROM user_calendar WHERE userId = :userId AND calendarId = :calendarId @@ -365,11 +365,11 @@ SELECT userId, managedUserId FROM user_user - + INSERT INTO user_user (userId, managedUserId) VALUES (:userId, :managedUserId) - + DELETE FROM user_user WHERE userId = :userId AND managedUserId = :managedUserId @@ -399,11 +399,11 @@ SELECT userId, attributeId FROM user_attribute - + INSERT INTO user_attribute (userId, attributeId) VALUES (:userId, :attributeId) - + DELETE FROM user_attribute WHERE userId = :userId AND attributeId = :attributeId @@ -456,11 +456,11 @@ SELECT userId, driverId FROM user_driver - + INSERT INTO user_driver (userId, driverId) VALUES (:userId, :driverId) - + DELETE FROM user_driver WHERE userId = :userId AND driverId = :driverId diff --git a/src/org/traccar/BaseProtocolDecoder.java b/src/org/traccar/BaseProtocolDecoder.java index 54d2bf28f..b8d2b122c 100644 --- a/src/org/traccar/BaseProtocolDecoder.java +++ b/src/org/traccar/BaseProtocolDecoder.java @@ -51,9 +51,7 @@ public abstract class BaseProtocolDecoder extends ExtendedObjectDecoder { if (defaultGroupId != 0) { Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } + Context.getPermissionsManager().refreshAllExtendedPermissions(); } return device.getId(); diff --git a/src/org/traccar/api/resource/AttributePermissionResource.java b/src/org/traccar/api/resource/AttributePermissionResource.java deleted file mode 100644 index 37e50e371..000000000 --- a/src/org/traccar/api/resource/AttributePermissionResource.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.AttributePermission; - -@Path("permissions/attributes") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class AttributePermissionResource extends BaseResource { - - @POST - public Response add(AttributePermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); - Context.getDataManager().linkAttribute(entity.getUserId(), entity.getAttributeId()); - Context.getAttributesManager().refreshUserItems(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(AttributePermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); - Context.getDataManager().unlinkAttribute(entity.getUserId(), entity.getAttributeId()); - Context.getAttributesManager().refreshUserItems(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/AttributeResource.java b/src/org/traccar/api/resource/AttributeResource.java index c67d9cafe..2f731e3a7 100644 --- a/src/org/traccar/api/resource/AttributeResource.java +++ b/src/org/traccar/api/resource/AttributeResource.java @@ -19,6 +19,7 @@ package org.traccar.api.resource; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.Set; import javax.ws.rs.Consumes; @@ -86,7 +87,10 @@ public class AttributeResource extends BaseResource { private Response add(Attribute entity) throws SQLException { Context.getAttributesManager().addItem(entity); - Context.getDataManager().linkAttribute(getUserId(), entity.getId()); + LinkedHashMap link = new LinkedHashMap<>(); + link.put("userId", getUserId()); + link.put("attributeId", entity.getId()); + Context.getDataManager().linkObject(link, true); Context.getAttributesManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/CalendarPermissionResource.java b/src/org/traccar/api/resource/CalendarPermissionResource.java deleted file mode 100644 index 3936bcaf3..000000000 --- a/src/org/traccar/api/resource/CalendarPermissionResource.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 Anton Tananaev (anton@traccar.org) - * Copyright 2016 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 javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.CalendarPermission; - -@Path("permissions/calendars") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class CalendarPermissionResource extends BaseResource { - - @POST - public Response add(CalendarPermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkPermission("calendar", getUserId(), entity.getCalendarId()); - Context.getDataManager().linkCalendar(entity.getUserId(), entity.getCalendarId()); - Context.getCalendarManager().refreshUserItems(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(CalendarPermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkPermission("calendar", getUserId(), entity.getCalendarId()); - Context.getDataManager().unlinkCalendar(entity.getUserId(), entity.getCalendarId()); - Context.getCalendarManager().refreshUserItems(); - return Response.noContent().build(); - } -} diff --git a/src/org/traccar/api/resource/CalendarResource.java b/src/org/traccar/api/resource/CalendarResource.java index be675fc79..f4ff9d4e9 100644 --- a/src/org/traccar/api/resource/CalendarResource.java +++ b/src/org/traccar/api/resource/CalendarResource.java @@ -18,6 +18,7 @@ package org.traccar.api.resource; import java.sql.SQLException; import java.util.Collection; +import java.util.LinkedHashMap; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -66,7 +67,10 @@ public class CalendarResource extends BaseResource { public Response add(Calendar entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getCalendarManager().addItem(entity); - Context.getDataManager().linkCalendar(getUserId(), entity.getId()); + LinkedHashMap link = new LinkedHashMap<>(); + link.put("userId", getUserId()); + link.put("calendarId", entity.getId()); + Context.getDataManager().linkObject(link, true); Context.getCalendarManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/DeviceAttributeResource.java b/src/org/traccar/api/resource/DeviceAttributeResource.java deleted file mode 100644 index bb833d4db..000000000 --- a/src/org/traccar/api/resource/DeviceAttributeResource.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.DeviceAttribute; - -@Path("devices/attributes") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class DeviceAttributeResource extends BaseResource { - - @POST - public Response add(DeviceAttribute entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); - Context.getDataManager().linkDeviceAttribute(entity.getDeviceId(), entity.getAttributeId()); - Context.getAttributesManager().refresh(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(DeviceAttribute entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); - Context.getDataManager().unlinkDeviceAttribute(entity.getDeviceId(), entity.getAttributeId()); - Context.getAttributesManager().refresh(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/DeviceDriverResource.java b/src/org/traccar/api/resource/DeviceDriverResource.java deleted file mode 100644 index 286f2223f..000000000 --- a/src/org/traccar/api/resource/DeviceDriverResource.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.DeviceDriver; - -@Path("devices/drivers") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class DeviceDriverResource extends BaseResource { - - @POST - public Response add(DeviceDriver entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); - Context.getDataManager().linkDeviceDriver(entity.getDeviceId(), entity.getDriverId()); - Context.getDriversManager().refresh(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(DeviceDriver entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); - Context.getDataManager().unlinkDeviceDriver(entity.getDeviceId(), entity.getDriverId()); - Context.getDriversManager().refresh(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/DeviceGeofenceResource.java b/src/org/traccar/api/resource/DeviceGeofenceResource.java deleted file mode 100644 index 8034e2168..000000000 --- a/src/org/traccar/api/resource/DeviceGeofenceResource.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 Anton Tananaev (anton@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 org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.DeviceGeofence; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import java.sql.SQLException; - -@Path("devices/geofences") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class DeviceGeofenceResource extends BaseResource { - - @POST - public Response add(DeviceGeofence entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); - Context.getDataManager().linkDeviceGeofence(entity.getDeviceId(), entity.getGeofenceId()); - Context.getGeofenceManager().refresh(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(DeviceGeofence entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); - Context.getDataManager().unlinkDeviceGeofence(entity.getDeviceId(), entity.getGeofenceId()); - Context.getGeofenceManager().refresh(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/DevicePermissionResource.java b/src/org/traccar/api/resource/DevicePermissionResource.java deleted file mode 100644 index 6e00dc47f..000000000 --- a/src/org/traccar/api/resource/DevicePermissionResource.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2015 - 2017 Anton Tananaev (anton@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 org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.DevicePermission; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.sql.SQLException; - -@Path("permissions/devices") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class DevicePermissionResource extends BaseResource { - - @POST - public Response add(DevicePermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getDataManager().linkDevice(entity.getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(DevicePermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - if (getUserId() != entity.getUserId()) { - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - } else { - Context.getPermissionsManager().checkAdmin(getUserId()); - } - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getDataManager().unlinkDevice(entity.getUserId(), entity.getDeviceId()); - Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index ce46b4e29..41a8970e2 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -35,7 +35,9 @@ import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; @Path("devices") @Produces(MediaType.APPLICATION_JSON) @@ -77,11 +79,12 @@ public class DeviceResource extends BaseResource { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); Context.getPermissionsManager().checkDeviceLimit(getUserId()); Context.getDeviceManager().addDevice(entity); - Context.getDataManager().linkDevice(getUserId(), entity.getId()); + LinkedHashMap link = new LinkedHashMap<>(); + link.put("userId", getUserId()); + link.put("deviceId", entity.getId()); + Context.getDataManager().linkObject(link, true); Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } + Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); } @@ -93,13 +96,11 @@ public class DeviceResource extends BaseResource { Context.getPermissionsManager().checkDevice(getUserId(), entity.getId()); Context.getDeviceManager().updateDevice(entity); Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } + Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); } - @Path("{id}") + @Path("{id : \\d+}") @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); @@ -107,9 +108,7 @@ public class DeviceResource extends BaseResource { Context.getPermissionsManager().checkDevice(getUserId(), id); Context.getDeviceManager().removeDevice(id); Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } + Context.getPermissionsManager().refreshAllExtendedPermissions(); Context.getAliasesManager().removeDevice(id); return Response.noContent().build(); } @@ -122,4 +121,28 @@ public class DeviceResource extends BaseResource { return Response.noContent().build(); } + @Path("/{slave : (geofences|drivers|attributes)}") + @POST + public Response add(Map entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + for (String key : entity.keySet()) { + Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); + } + Context.getDataManager().linkObject(entity, true); + Context.getPermissionsManager().refreshPermissions(entity); + return Response.noContent().build(); + } + + @Path("/{slave : (geofences|drivers|attributes)}") + @DELETE + public Response remove(Map entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + for (String key : entity.keySet()) { + Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); + } + Context.getDataManager().linkObject(entity, false); + Context.getPermissionsManager().refreshPermissions(entity); + return Response.noContent().build(); + } + } diff --git a/src/org/traccar/api/resource/DriverPermissionResource.java b/src/org/traccar/api/resource/DriverPermissionResource.java deleted file mode 100644 index 4d890cae9..000000000 --- a/src/org/traccar/api/resource/DriverPermissionResource.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.traccar.Context; -import org.traccar.api.BaseResource; - -import org.traccar.model.DriverPermission; - -@Path("permissions/drivers") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class DriverPermissionResource extends BaseResource { - - @POST - public Response add(DriverPermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); - Context.getDataManager().linkDriver(entity.getUserId(), entity.getDriverId()); - Context.getDriversManager().refreshUserItems(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(DriverPermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); - Context.getDataManager().unlinkDriver(entity.getUserId(), entity.getDriverId()); - Context.getDriversManager().refreshUserItems(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index 3d6a12795..91a502790 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -19,6 +19,7 @@ package org.traccar.api.resource; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.Set; import javax.ws.rs.Consumes; @@ -86,7 +87,10 @@ public class DriverResource extends BaseResource { public Response add(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDriversManager().addItem(entity); - Context.getDataManager().linkDriver(getUserId(), entity.getId()); + LinkedHashMap link = new LinkedHashMap<>(); + link.put("userId", getUserId()); + link.put("driverId", entity.getId()); + Context.getDataManager().linkObject(link, true); Context.getDriversManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/GeofencePermissionResource.java b/src/org/traccar/api/resource/GeofencePermissionResource.java deleted file mode 100644 index a569e56fd..000000000 --- a/src/org/traccar/api/resource/GeofencePermissionResource.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2016 Anton Tananaev (anton@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 org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.GeofencePermission; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.sql.SQLException; - -@Path("permissions/geofences") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class GeofencePermissionResource extends BaseResource { - - @POST - public Response add(GeofencePermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); - Context.getDataManager().linkGeofence(entity.getUserId(), entity.getGeofenceId()); - Context.getGeofenceManager().refreshUserItems(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(GeofencePermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); - Context.getDataManager().unlinkGeofence(entity.getUserId(), entity.getGeofenceId()); - Context.getGeofenceManager().refreshUserItems(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/GeofenceResource.java b/src/org/traccar/api/resource/GeofenceResource.java index 4a52822cc..c39d882b6 100644 --- a/src/org/traccar/api/resource/GeofenceResource.java +++ b/src/org/traccar/api/resource/GeofenceResource.java @@ -35,6 +35,7 @@ import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.Set; @Path("geofences") @@ -85,7 +86,10 @@ public class GeofenceResource extends BaseResource { public Response add(Geofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getGeofenceManager().addItem(entity); - Context.getDataManager().linkGeofence(getUserId(), entity.getId()); + LinkedHashMap link = new LinkedHashMap<>(); + link.put("userId", getUserId()); + link.put("geofenceId", entity.getId()); + Context.getDataManager().linkObject(link, true); Context.getGeofenceManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/GroupAttributeResource.java b/src/org/traccar/api/resource/GroupAttributeResource.java deleted file mode 100644 index 5df63194e..000000000 --- a/src/org/traccar/api/resource/GroupAttributeResource.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.GroupAttribute; - -@Path("groups/attributes") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class GroupAttributeResource extends BaseResource { - - @POST - public Response add(GroupAttribute entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); - Context.getDataManager().linkGroupAttribute(entity.getGroupId(), entity.getAttributeId()); - Context.getAttributesManager().refresh(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(GroupAttribute entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getAttributeId()); - Context.getDataManager().unlinkGroupAttribute(entity.getGroupId(), entity.getAttributeId()); - Context.getAttributesManager().refresh(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/GroupDriverResource.java b/src/org/traccar/api/resource/GroupDriverResource.java deleted file mode 100644 index 71c1aca29..000000000 --- a/src/org/traccar/api/resource/GroupDriverResource.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.GroupDriver; - -@Path("groups/drivers") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class GroupDriverResource extends BaseResource { - - @POST - public Response add(GroupDriver entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); - Context.getDataManager().linkGroupDriver(entity.getGroupId(), entity.getDriverId()); - Context.getDriversManager().refresh(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(GroupDriver entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getDriverId()); - Context.getDataManager().unlinkGroupDriver(entity.getGroupId(), entity.getDriverId()); - Context.getDriversManager().refresh(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/GroupGeofenceResource.java b/src/org/traccar/api/resource/GroupGeofenceResource.java deleted file mode 100644 index 14000c4b5..000000000 --- a/src/org/traccar/api/resource/GroupGeofenceResource.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2016 Anton Tananaev (anton@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 org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.GroupGeofence; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.sql.SQLException; - -@Path("groups/geofences") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class GroupGeofenceResource extends BaseResource { - - @POST - public Response add(GroupGeofence entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); - Context.getDataManager().linkGroupGeofence(entity.getGroupId(), entity.getGeofenceId()); - Context.getGeofenceManager().refresh(); - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(GroupGeofence entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getGeofenceId()); - Context.getDataManager().unlinkGroupGeofence(entity.getGroupId(), entity.getGeofenceId()); - Context.getGeofenceManager().refresh(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/GroupPermissionResource.java b/src/org/traccar/api/resource/GroupPermissionResource.java deleted file mode 100644 index 61a725222..000000000 --- a/src/org/traccar/api/resource/GroupPermissionResource.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2016 - 2017 Anton Tananaev (anton@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 org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.GroupPermission; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.sql.SQLException; - -@Path("permissions/groups") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class GroupPermissionResource extends BaseResource { - - @POST - public Response add(GroupPermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getDataManager().linkGroup(entity.getUserId(), entity.getGroupId()); - Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(GroupPermission entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), entity.getGroupId()); - Context.getDataManager().unlinkGroup(entity.getUserId(), entity.getGroupId()); - Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index ceba69105..97b6d671d 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -32,6 +32,8 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; @Path("groups") @Produces(MediaType.APPLICATION_JSON) @@ -61,11 +63,12 @@ public class GroupResource extends BaseResource { public Response add(Group entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDeviceManager().addGroup(entity); - Context.getDataManager().linkGroup(getUserId(), entity.getId()); + LinkedHashMap link = new LinkedHashMap<>(); + link.put("userId", getUserId()); + link.put("groupId", entity.getId()); + Context.getDataManager().linkObject(link, true); Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } + Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); } @@ -75,22 +78,42 @@ public class GroupResource extends BaseResource { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), entity.getId()); Context.getDeviceManager().updateGroup(entity); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); - } + Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); } - @Path("{id}") + @Path("{id : \\d+}") @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), id); Context.getDeviceManager().removeGroup(id); Context.getPermissionsManager().refreshPermissions(); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refresh(); + Context.getPermissionsManager().refreshAllExtendedPermissions(); + return Response.noContent().build(); + } + + @Path("/{slave : (geofences|drivers|attributes)}") + @POST + public Response add(Map entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + for (String key : entity.keySet()) { + Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); + } + Context.getDataManager().linkObject(entity, true); + Context.getPermissionsManager().refreshPermissions(entity); + return Response.noContent().build(); + } + + @Path("/{slave : (geofences|drivers|attributes)}") + @DELETE + public Response remove(Map entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + for (String key : entity.keySet()) { + Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); } + Context.getDataManager().linkObject(entity, false); + Context.getPermissionsManager().refreshPermissions(entity); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/PermissionsResource.java b/src/org/traccar/api/resource/PermissionsResource.java new file mode 100644 index 000000000..ac7acb93f --- /dev/null +++ b/src/org/traccar/api/resource/PermissionsResource.java @@ -0,0 +1,62 @@ +/* + * 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.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.traccar.Context; +import org.traccar.api.BaseResource; + +@Path("permissions") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class PermissionsResource extends BaseResource { + + @Path("/{slave : (users|devices|groups|geofences|drivers|attributes|calendars)}") + @POST + public Response add(Map entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + for (String key : entity.keySet()) { + Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); + } + Context.getDataManager().linkObject(entity, true); + Context.getPermissionsManager().refreshPermissions(entity); + return Response.noContent().build(); + } + + @Path("/{slave : (users|devices|groups|geofences|drivers|attributes|calendars)}") + @DELETE + public Response remove(Map entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + for (String key : entity.keySet()) { + Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); + } + Context.getDataManager().linkObject(entity, false); + Context.getPermissionsManager().refreshPermissions(entity); + return Response.noContent().build(); + } + +} diff --git a/src/org/traccar/api/resource/UserPermissionResource.java b/src/org/traccar/api/resource/UserPermissionResource.java deleted file mode 100644 index a97c4a665..000000000 --- a/src/org/traccar/api/resource/UserPermissionResource.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.UserPermission; - -@Path("permissions/users") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class UserPermissionResource extends BaseResource { - - @POST - public Response add(UserPermission entity) throws SQLException { - Context.getPermissionsManager().checkAdmin(getUserId()); - if (entity.getUserId() != entity.getManagedUserId()) { - Context.getDataManager().linkUser(entity.getUserId(), entity.getManagedUserId()); - Context.getPermissionsManager().refreshUserPermissions(); - } - return Response.ok(entity).build(); - } - - @DELETE - public Response remove(UserPermission entity) throws SQLException { - Context.getPermissionsManager().checkAdmin(getUserId()); - Context.getDataManager().unlinkUser(entity.getUserId(), entity.getManagedUserId()); - Context.getPermissionsManager().refreshUserPermissions(); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index b9187fdbb..94cc56b47 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -34,6 +34,7 @@ import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.Collection; import java.util.Date; +import java.util.LinkedHashMap; @Path("users") @Produces(MediaType.APPLICATION_JSON) @@ -74,7 +75,10 @@ public class UserResource extends BaseResource { } Context.getPermissionsManager().addUser(entity); if (Context.getPermissionsManager().isManager(getUserId())) { - Context.getDataManager().linkUser(getUserId(), entity.getId()); + LinkedHashMap link = new LinkedHashMap<>(); + link.put("userId", getUserId()); + link.put("managedUserId", entity.getId()); + Context.getDataManager().linkObject(link, true); } Context.getPermissionsManager().refreshUserPermissions(); if (Context.getNotificationManager() != null) { diff --git a/src/org/traccar/database/AttributesManager.java b/src/org/traccar/database/AttributesManager.java index 88bedfba4..ebfdbc9b4 100644 --- a/src/org/traccar/database/AttributesManager.java +++ b/src/org/traccar/database/AttributesManager.java @@ -29,7 +29,7 @@ public class AttributesManager extends ExtendedObjectManager { public AttributesManager(DataManager dataManager) { super(dataManager, Attribute.class, AttributePermission.class, DeviceAttribute.class, GroupAttribute.class); refreshItems(); - refresh(); + refreshExtendedPermissions(); } @Override diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 4bf4b1b9a..6c9cca86c 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -23,6 +23,7 @@ import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; +import java.util.Map; import javax.naming.InitialContext; import javax.sql.DataSource; @@ -39,17 +40,12 @@ import org.traccar.Config; import org.traccar.helper.Log; import org.traccar.model.AttributeAlias; import org.traccar.model.Device; -import org.traccar.model.DevicePermission; import org.traccar.model.Event; -import org.traccar.model.Group; -import org.traccar.model.GroupPermission; import org.traccar.model.Identifiable; -import org.traccar.model.Notification; import org.traccar.model.Position; import org.traccar.model.Server; import org.traccar.model.Statistics; import org.traccar.model.User; -import org.traccar.model.UserPermission; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; @@ -153,17 +149,6 @@ public class DataManager { } } - public Collection getUsers() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectUsersAll")) - .executeQuery(User.class); - } - - public void addUser(User user) throws SQLException { - user.setId(QueryBuilder.create(dataSource, getQuery("database.insertUser"), true) - .setObject(user) - .executeUpdate()); - } - public void updateUser(User user) throws SQLException { QueryBuilder.create(dataSource, getQuery("database.updateUser")) .setObject(user) @@ -175,102 +160,12 @@ public class DataManager { } } - public void removeUser(long userId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.deleteUser")) - .setLong("id", userId) - .executeUpdate(); - } - - public Collection getDevicePermissions() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectDevicePermissions")) - .executeQuery(DevicePermission.class); - } - - public Collection getGroupPermissions() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectGroupPermissions")) - .executeQuery(GroupPermission.class); - } - - public Collection getAllDevices() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectDevicesAll")) - .executeQuery(Device.class); - } - - public void addDevice(Device device) throws SQLException { - device.setId(QueryBuilder.create(dataSource, getQuery("database.insertDevice"), true) - .setObject(device) - .executeUpdate()); - } - - public void updateDevice(Device device) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateDevice")) - .setObject(device) - .executeUpdate(); - } - public void updateDeviceStatus(Device device) throws SQLException { QueryBuilder.create(dataSource, getQuery("database.updateDeviceStatus")) .setObject(device) .executeUpdate(); } - public void removeDevice(long deviceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.deleteDevice")) - .setLong("id", deviceId) - .executeUpdate(); - } - - public void linkDevice(long userId, long deviceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkDevice")) - .setLong("userId", userId) - .setLong("deviceId", deviceId) - .executeUpdate(); - } - - public void unlinkDevice(long userId, long deviceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkDevice")) - .setLong("userId", userId) - .setLong("deviceId", deviceId) - .executeUpdate(); - } - - public Collection getAllGroups() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectGroupsAll")) - .executeQuery(Group.class); - } - - public void addGroup(Group group) throws SQLException { - group.setId(QueryBuilder.create(dataSource, getQuery("database.insertGroup"), true) - .setObject(group) - .executeUpdate()); - } - - public void updateGroup(Group group) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateGroup")) - .setObject(group) - .executeUpdate(); - } - - public void removeGroup(long groupId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.deleteGroup")) - .setLong("id", groupId) - .executeUpdate(); - } - - public void linkGroup(long userId, long groupId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkGroup")) - .setLong("userId", userId) - .setLong("groupId", groupId) - .executeUpdate(); - } - - public void unlinkGroup(long userId, long groupId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkGroup")) - .setLong("userId", userId) - .setLong("groupId", groupId) - .executeUpdate(); - } - public Collection getPositions(long deviceId, Date from, Date to) throws SQLException { return QueryBuilder.create(dataSource, getQuery("database.selectPositions")) .setLong("deviceId", deviceId) @@ -323,24 +218,12 @@ public class DataManager { .executeQuerySingle(Server.class); } - public void updateServer(Server server) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateServer")) - .setObject(server) - .executeUpdate(); - } - public Event getEvent(long eventId) throws SQLException { return QueryBuilder.create(dataSource, getQuery("database.selectEvent")) .setLong("id", eventId) .executeQuerySingle(Event.class); } - public void addEvent(Event event) throws SQLException { - event.setId(QueryBuilder.create(dataSource, getQuery("database.insertEvent"), true) - .setObject(event) - .executeUpdate()); - } - public Collection getEvents(long deviceId, Date from, Date to) throws SQLException { return QueryBuilder.create(dataSource, getQuery("database.selectEvents")) .setLong("deviceId", deviceId) @@ -349,71 +232,6 @@ public class DataManager { .executeQuery(Event.class); } - public void linkGeofence(long userId, long geofenceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkGeofence")) - .setLong("userId", userId) - .setLong("geofenceId", geofenceId) - .executeUpdate(); - } - - public void unlinkGeofence(long userId, long geofenceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkGeofence")) - .setLong("userId", userId) - .setLong("geofenceId", geofenceId) - .executeUpdate(); - } - - public void linkGroupGeofence(long groupId, long geofenceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkGroupGeofence")) - .setLong("groupId", groupId) - .setLong("geofenceId", geofenceId) - .executeUpdate(); - } - - public void unlinkGroupGeofence(long groupId, long geofenceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkGroupGeofence")) - .setLong("groupId", groupId) - .setLong("geofenceId", geofenceId) - .executeUpdate(); - } - - public void linkDeviceGeofence(long deviceId, long geofenceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkDeviceGeofence")) - .setLong("deviceId", deviceId) - .setLong("geofenceId", geofenceId) - .executeUpdate(); - } - - public void unlinkDeviceGeofence(long deviceId, long geofenceId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkDeviceGeofence")) - .setLong("deviceId", deviceId) - .setLong("geofenceId", geofenceId) - .executeUpdate(); - } - - public Collection getNotifications() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectNotifications")) - .executeQuery(Notification.class); - } - - public void addNotification(Notification notification) throws SQLException { - notification.setId(QueryBuilder.create(dataSource, getQuery("database.insertNotification"), true) - .setObject(notification) - .executeUpdate()); - } - - public void updateNotification(Notification notification) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateNotification")) - .setObject(notification) - .executeUpdate(); - } - - public void removeNotification(Notification notification) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.deleteNotification")) - .setLong("id", notification.getId()) - .executeUpdate(); - } - public Collection getAttributeAliases() throws SQLException { return QueryBuilder.create(dataSource, getQuery("database.selectAttributeAliases")) .executeQuery(AttributeAlias.class); @@ -450,121 +268,16 @@ public class DataManager { .executeUpdate()); } - public void linkCalendar(long userId, long calendarId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkCalendar")) - .setLong("userId", userId) - .setLong("calendarId", calendarId) - .executeUpdate(); - } - - public void unlinkCalendar(long userId, long calendarId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkCalendar")) - .setLong("userId", userId) - .setLong("calendarId", calendarId) - .executeUpdate(); - } - - public Collection getUserPermissions() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectUserPermissions")) - .executeQuery(UserPermission.class); - } - - public void linkUser(long userId, long managedUserId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkUser")) - .setLong("userId", userId) - .setLong("managedUserId", managedUserId) - .executeUpdate(); - } - - public void unlinkUser(long userId, long managedUserId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkUser")) - .setLong("userId", userId) - .setLong("managedUserId", managedUserId) - .executeUpdate(); - } - - public void linkAttribute(long userId, long attributeId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkAttribute")) - .setLong("userId", userId) - .setLong("attributeId", attributeId) - .executeUpdate(); - } - - public void unlinkAttribute(long userId, long attributeId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkAttribute")) - .setLong("userId", userId) - .setLong("attributeId", attributeId) - .executeUpdate(); - } - - public void linkGroupAttribute(long groupId, long attributeId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkGroupAttribute")) - .setLong("groupId", groupId) - .setLong("attributeId", attributeId) - .executeUpdate(); - } - - public void unlinkGroupAttribute(long groupId, long attributeId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkGroupAttribute")) - .setLong("groupId", groupId) - .setLong("attributeId", attributeId) - .executeUpdate(); - } - - public void linkDeviceAttribute(long deviceId, long attributeId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.linkDeviceAttribute")) - .setLong("deviceId", deviceId) - .setLong("attributeId", attributeId) - .executeUpdate(); - } - - public void unlinkDeviceAttribute(long deviceId, long attributeId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.unlinkDeviceAttribute")) - .setLong("deviceId", deviceId) - .setLong("attributeId", attributeId) - .executeUpdate(); - } - - 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 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 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(); + public void linkObject(Map permission, boolean link) throws SQLException { + String query = "database." + (!link ? "un" : "") + "link"; + for (String key : permission.keySet()) { + query += key.substring(0, 1).toUpperCase() + key.replace("Id", "").substring(1); + } + QueryBuilder queryBuilder = QueryBuilder.create(dataSource, getQuery(query)); + for (String key : permission.keySet()) { + queryBuilder.setLong(key, permission.get(key)); + } + queryBuilder.executeUpdate(); } public Collection getObjects(Class clazz) throws SQLException { diff --git a/src/org/traccar/database/DeviceManager.java b/src/org/traccar/database/DeviceManager.java index f2a2dd565..ba360f165 100644 --- a/src/org/traccar/database/DeviceManager.java +++ b/src/org/traccar/database/DeviceManager.java @@ -85,7 +85,7 @@ public class DeviceManager implements IdentityManager { if ((force || System.currentTimeMillis() - lastUpdate > dataRefreshDelay) && devicesLastUpdate.compareAndSet(lastUpdate, System.currentTimeMillis())) { GeofenceManager geofenceManager = Context.getGeofenceManager(); - Collection databaseDevices = dataManager.getAllDevices(); + Collection databaseDevices = dataManager.getObjects(Device.class); if (devicesById == null) { devicesById = new ConcurrentHashMap<>(databaseDevices.size()); } @@ -199,7 +199,7 @@ public class DeviceManager implements IdentityManager { } public void addDevice(Device device) throws SQLException { - dataManager.addDevice(device); + dataManager.addObject(device); devicesById.put(device.getId(), device); devicesByUniqueId.put(device.getUniqueId(), device); @@ -209,7 +209,7 @@ public class DeviceManager implements IdentityManager { } public void updateDevice(Device device) throws SQLException { - dataManager.updateDevice(device); + dataManager.updateObject(device); devicesById.put(device.getId(), device); devicesByUniqueId.put(device.getUniqueId(), device); @@ -227,7 +227,7 @@ public class DeviceManager implements IdentityManager { } public void removeDevice(long deviceId) throws SQLException { - dataManager.removeDevice(deviceId); + dataManager.removeObject(Device.class, deviceId); if (devicesById.containsKey(deviceId)) { String deviceUniqueId = devicesById.get(deviceId).getUniqueId(); @@ -289,7 +289,7 @@ public class DeviceManager implements IdentityManager { long lastUpdate = groupsLastUpdate.get(); if ((force || System.currentTimeMillis() - lastUpdate > dataRefreshDelay) && groupsLastUpdate.compareAndSet(lastUpdate, System.currentTimeMillis())) { - Collection databaseGroups = dataManager.getAllGroups(); + Collection databaseGroups = dataManager.getObjects(Group.class); if (groupsById == null) { groupsById = new ConcurrentHashMap<>(databaseGroups.size()); } @@ -359,18 +359,18 @@ public class DeviceManager implements IdentityManager { public void addGroup(Group group) throws SQLException { checkGroupCycles(group); - dataManager.addGroup(group); + dataManager.addObject(group); groupsById.put(group.getId(), group); } public void updateGroup(Group group) throws SQLException { checkGroupCycles(group); - dataManager.updateGroup(group); + dataManager.updateObject(group); groupsById.put(group.getId(), group); } public void removeGroup(long groupId) throws SQLException { - dataManager.removeGroup(groupId); + dataManager.removeObject(Group.class, groupId); groupsById.remove(groupId); } diff --git a/src/org/traccar/database/DriversManager.java b/src/org/traccar/database/DriversManager.java index 391708f64..9b01f1a70 100644 --- a/src/org/traccar/database/DriversManager.java +++ b/src/org/traccar/database/DriversManager.java @@ -34,7 +34,7 @@ public class DriversManager extends ExtendedObjectManager { public DriversManager(DataManager dataManager) { super(dataManager, Driver.class, DriverPermission.class, DeviceDriver.class, GroupDriver.class); refreshItems(); - refresh(); + refreshExtendedPermissions(); } @Override @@ -83,7 +83,7 @@ public class DriversManager extends ExtendedObjectManager { driversByUniqueId.remove(driverUniqueId); } refreshUserItems(); - refresh(); + refreshExtendedPermissions(); } public Driver getDriverByUniqueId(String uniqueId) { diff --git a/src/org/traccar/database/ExtendedObjectManager.java b/src/org/traccar/database/ExtendedObjectManager.java index 5147b9f9f..a6508f066 100644 --- a/src/org/traccar/database/ExtendedObjectManager.java +++ b/src/org/traccar/database/ExtendedObjectManager.java @@ -82,10 +82,10 @@ public abstract class ExtendedObjectManager extends SimpleObjectManager { @Override public void removeItem(long itemId) throws SQLException { super.removeItem(itemId); - refresh(); + refreshExtendedPermissions(); } - public void refresh() { + public void refreshExtendedPermissions() { if (getDataManager() != null) { try { diff --git a/src/org/traccar/database/GeofenceManager.java b/src/org/traccar/database/GeofenceManager.java index 868804d8f..ed1f26f78 100644 --- a/src/org/traccar/database/GeofenceManager.java +++ b/src/org/traccar/database/GeofenceManager.java @@ -31,11 +31,12 @@ public class GeofenceManager extends ExtendedObjectManager { public GeofenceManager(DataManager dataManager) { super(dataManager, Geofence.class, GeofencePermission.class, DeviceGeofence.class, GroupGeofence.class); refreshItems(); - refresh(); + refreshExtendedPermissions(); } - public final void refresh() { - super.refresh(); + @Override + public final void refreshExtendedPermissions() { + super.refreshExtendedPermissions(); recalculateDevicesGeofences(); } diff --git a/src/org/traccar/database/NotificationManager.java b/src/org/traccar/database/NotificationManager.java index 11d5a9aca..0987f255b 100644 --- a/src/org/traccar/database/NotificationManager.java +++ b/src/org/traccar/database/NotificationManager.java @@ -49,7 +49,7 @@ public class NotificationManager { public void updateEvent(Event event, Position position) { try { - dataManager.addEvent(event); + dataManager.addObject(event); } catch (SQLException error) { Log.warning(error); } @@ -105,7 +105,7 @@ public class NotificationManager { notificationsLock.writeLock().lock(); try { userNotifications.clear(); - for (Notification notification : dataManager.getNotifications()) { + for (Notification notification : dataManager.getObjects(Notification.class)) { getUserNotificationsUnsafe(notification.getUserId()).add(notification); } } finally { @@ -139,7 +139,7 @@ public class NotificationManager { || cachedNotification.getSms() != notification.getSms()) { if (!notification.getWeb() && !notification.getMail() && !notification.getSms()) { try { - dataManager.removeNotification(cachedNotification); + dataManager.removeObject(Notification.class, cachedNotification.getId()); } catch (SQLException error) { Log.warning(error); } @@ -160,7 +160,7 @@ public class NotificationManager { notificationsLock.writeLock().unlock(); } try { - dataManager.updateNotification(cachedNotification); + dataManager.updateObject(cachedNotification); } catch (SQLException error) { Log.warning(error); } @@ -170,7 +170,7 @@ public class NotificationManager { } } else if (notification.getWeb() || notification.getMail() || notification.getSms()) { try { - dataManager.addNotification(notification); + dataManager.addObject(notification); } catch (SQLException error) { Log.warning(error); } diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index f88e14bfe..caae86b84 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -98,7 +98,7 @@ public class PermissionsManager { usersTokens.clear(); try { server = dataManager.getServer(); - for (User user : dataManager.getUsers()) { + for (User user : dataManager.getObjects(User.class)) { users.put(user.getId(), user); if (user.getToken() != null) { usersTokens.put(user.getToken(), user.getId()); @@ -112,7 +112,7 @@ public class PermissionsManager { public final void refreshUserPermissions() { userPermissions.clear(); try { - for (UserPermission permission : dataManager.getUserPermissions()) { + for (UserPermission permission : dataManager.getObjects(UserPermission.class)) { getUserPermissions(permission.getUserId()).add(permission.getManagedUserId()); } } catch (SQLException error) { @@ -126,7 +126,7 @@ public class PermissionsManager { try { GroupTree groupTree = new GroupTree(Context.getDeviceManager().getAllGroups(), Context.getDeviceManager().getAllDevices()); - for (GroupPermission permission : dataManager.getGroupPermissions()) { + for (GroupPermission permission : dataManager.getObjects(GroupPermission.class)) { Set userGroupPermissions = getGroupPermissions(permission.getUserId()); Set userDevicePermissions = getDevicePermissions(permission.getUserId()); userGroupPermissions.add(permission.getGroupId()); @@ -137,7 +137,7 @@ public class PermissionsManager { userDevicePermissions.add(device.getId()); } } - for (DevicePermission permission : dataManager.getDevicePermissions()) { + for (DevicePermission permission : dataManager.getObjects(DevicePermission.class)) { getDevicePermissions(permission.getUserId()).add(permission.getDeviceId()); } @@ -302,6 +302,15 @@ public class PermissionsManager { SimpleObjectManager manager = null; switch (object) { + case "device": + checkDevice(userId, objectId); + break; + case "group": + checkGroup(userId, objectId); + break; + case "user": + checkUser(userId, objectId); + break; case "geofence": manager = Context.getGeofenceManager(); break; @@ -332,12 +341,51 @@ public class PermissionsManager { } } + public void refreshAllExtendedPermissions() { + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refreshExtendedPermissions(); + } + Context.getDriversManager().refreshExtendedPermissions(); + Context.getAttributesManager().refreshExtendedPermissions(); + } + + public void refreshPermissions(Map entity) { + if (entity.containsKey("userId")) { + if (entity.containsKey("deviceId") || entity.containsKey("groupId")) { + refreshPermissions(); + refreshAllExtendedPermissions(); + } else if (entity.containsKey("managedUserId")) { + refreshUserPermissions(); + } else if (entity.containsKey("geofenceId")) { + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refreshUserItems(); + } + } else if (entity.containsKey("driverId")) { + Context.getDriversManager().refreshUserItems(); + } else if (entity.containsKey("attributeId")) { + Context.getAttributesManager().refreshUserItems(); + } else if (entity.containsKey("calendarId")) { + Context.getCalendarManager().refreshUserItems(); + } + } else if (entity.containsKey("deviceId") || entity.containsKey("groupId")) { + if (entity.containsKey("geofenceId")) { + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refreshExtendedPermissions(); + } + } else if (entity.containsKey("driverId")) { + Context.getDriversManager().refreshExtendedPermissions(); + } else if (entity.containsKey("attributeId")) { + Context.getAttributesManager().refreshExtendedPermissions(); + } + } + } + public Server getServer() { return server; } public void updateServer(Server server) throws SQLException { - dataManager.updateServer(server); + dataManager.updateObject(server); this.server = server; } @@ -364,7 +412,7 @@ public class PermissionsManager { } public void addUser(User user) throws SQLException { - dataManager.addUser(user); + dataManager.addObject(user); users.put(user.getId(), user); if (user.getToken() != null) { usersTokens.put(user.getToken(), user.getId()); @@ -386,7 +434,7 @@ public class PermissionsManager { } public void removeUser(long userId) throws SQLException { - dataManager.removeUser(userId); + dataManager.removeObject(User.class, userId); usersTokens.remove(users.get(userId).getToken()); users.remove(userId); refreshPermissions(); diff --git a/src/org/traccar/database/SimpleObjectManager.java b/src/org/traccar/database/SimpleObjectManager.java index 84d41a84f..f5f807850 100644 --- a/src/org/traccar/database/SimpleObjectManager.java +++ b/src/org/traccar/database/SimpleObjectManager.java @@ -132,14 +132,6 @@ public abstract class SimpleObjectManager { refreshUserItems(); } -// public final Collection getItems(Set itemIds) { -// Collection result = new LinkedList<>(); -// for (long itemId : itemIds) { -// result.add(getById(itemId)); -// } -// return result; -// } - public final Collection getItems(Class clazz, Set itemIds) { Collection result = new LinkedList<>(); for (long itemId : itemIds) { -- cgit v1.2.3 From 0d5a1b36c704f3a79eceb2a1f19894f0438eb1b0 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Thu, 20 Jul 2017 10:05:33 +0500 Subject: Make permissions resources more strict --- src/org/traccar/api/resource/DeviceResource.java | 6 ++++++ src/org/traccar/api/resource/GroupResource.java | 6 ++++++ src/org/traccar/api/resource/PermissionsResource.java | 6 ++++++ 3 files changed, 18 insertions(+) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index 41a8970e2..0f7579bae 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -125,6 +125,9 @@ public class DeviceResource extends BaseResource { @POST public Response add(Map entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); + if (entity.size() != 2) { + throw new IllegalArgumentException(); + } for (String key : entity.keySet()) { Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); } @@ -140,6 +143,9 @@ public class DeviceResource extends BaseResource { for (String key : entity.keySet()) { Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); } + if (entity.size() != 2) { + throw new IllegalArgumentException(); + } Context.getDataManager().linkObject(entity, false); Context.getPermissionsManager().refreshPermissions(entity); return Response.noContent().build(); diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index 97b6d671d..0d9572332 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -97,6 +97,9 @@ public class GroupResource extends BaseResource { @POST public Response add(Map entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); + if (entity.size() != 2) { + throw new IllegalArgumentException(); + } for (String key : entity.keySet()) { Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); } @@ -109,6 +112,9 @@ public class GroupResource extends BaseResource { @DELETE public Response remove(Map entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); + if (entity.size() != 2) { + throw new IllegalArgumentException(); + } for (String key : entity.keySet()) { Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); } diff --git a/src/org/traccar/api/resource/PermissionsResource.java b/src/org/traccar/api/resource/PermissionsResource.java index ac7acb93f..e22ffae36 100644 --- a/src/org/traccar/api/resource/PermissionsResource.java +++ b/src/org/traccar/api/resource/PermissionsResource.java @@ -39,6 +39,9 @@ public class PermissionsResource extends BaseResource { @POST public Response add(Map entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); + if (entity.size() != 2) { + throw new IllegalArgumentException(); + } for (String key : entity.keySet()) { Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); } @@ -51,6 +54,9 @@ public class PermissionsResource extends BaseResource { @DELETE public Response remove(Map entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); + if (entity.size() != 2) { + throw new IllegalArgumentException(); + } for (String key : entity.keySet()) { Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); } -- cgit v1.2.3 From f77912f14ed17bfbe533b664b6b82154c80e3b58 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Fri, 21 Jul 2017 11:55:38 +0500 Subject: - Combine all permissions to one resource - Add two helpers to BaseResource --- src/org/traccar/api/BaseResource.java | 36 +++++++++++++++++++++ .../traccar/api/resource/AttributeResource.java | 7 ++-- src/org/traccar/api/resource/CalendarResource.java | 6 +--- src/org/traccar/api/resource/DeviceResource.java | 37 +--------------------- src/org/traccar/api/resource/DriverResource.java | 6 +--- src/org/traccar/api/resource/GeofenceResource.java | 6 +--- src/org/traccar/api/resource/GroupResource.java | 37 +--------------------- .../traccar/api/resource/PermissionsResource.java | 18 ++--------- src/org/traccar/api/resource/UserResource.java | 6 +--- src/org/traccar/database/DataManager.java | 18 ++++++----- 10 files changed, 56 insertions(+), 121 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/BaseResource.java b/src/org/traccar/api/BaseResource.java index 44ef33c53..9ac30f5a7 100644 --- a/src/org/traccar/api/BaseResource.java +++ b/src/org/traccar/api/BaseResource.java @@ -15,8 +15,15 @@ */ package org.traccar.api; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.Map; + import javax.ws.rs.core.SecurityContext; +import org.traccar.Context; +import org.traccar.model.BaseModel; + public class BaseResource { @javax.ws.rs.core.Context @@ -29,4 +36,33 @@ public class BaseResource { } return 0; } + + protected void handlePermission(Map entity, boolean link) throws SQLException { + if (entity.size() != 2) { + throw new IllegalArgumentException(); + } + Iterator iterator = entity.keySet().iterator(); + String owner = iterator.next(); + String property = iterator.next(); + long ownerId = entity.get(owner); + long propertyId = entity.get(property); + + if (!link && owner.equals("userId") && property.equals("deviceId")) { + if (getUserId() != ownerId) { + Context.getPermissionsManager().checkUser(getUserId(), ownerId); + } else { + Context.getPermissionsManager().checkAdmin(getUserId()); + } + } else { + Context.getPermissionsManager().checkPermission(owner.replace("Id", ""), getUserId(), ownerId); + } + Context.getPermissionsManager().checkPermission(property.replace("Id", ""), getUserId(), propertyId); + + Context.getDataManager().linkObject(owner, ownerId, property, propertyId, link); + } + + protected void linkNew(BaseModel entity) throws SQLException { + Context.getDataManager().linkObject("userId", getUserId(), + entity.getClass().getSimpleName(), entity.getId(), true); + } } diff --git a/src/org/traccar/api/resource/AttributeResource.java b/src/org/traccar/api/resource/AttributeResource.java index 2f731e3a7..c6c95e05c 100644 --- a/src/org/traccar/api/resource/AttributeResource.java +++ b/src/org/traccar/api/resource/AttributeResource.java @@ -19,7 +19,6 @@ package org.traccar.api.resource; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.Set; import javax.ws.rs.Consumes; @@ -86,11 +85,9 @@ public class AttributeResource extends BaseResource { } private Response add(Attribute entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); Context.getAttributesManager().addItem(entity); - LinkedHashMap link = new LinkedHashMap<>(); - link.put("userId", getUserId()); - link.put("attributeId", entity.getId()); - Context.getDataManager().linkObject(link, true); + linkNew(entity); Context.getAttributesManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/CalendarResource.java b/src/org/traccar/api/resource/CalendarResource.java index f4ff9d4e9..0666f2fed 100644 --- a/src/org/traccar/api/resource/CalendarResource.java +++ b/src/org/traccar/api/resource/CalendarResource.java @@ -18,7 +18,6 @@ package org.traccar.api.resource; import java.sql.SQLException; import java.util.Collection; -import java.util.LinkedHashMap; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -67,10 +66,7 @@ public class CalendarResource extends BaseResource { public Response add(Calendar entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getCalendarManager().addItem(entity); - LinkedHashMap link = new LinkedHashMap<>(); - link.put("userId", getUserId()); - link.put("calendarId", entity.getId()); - Context.getDataManager().linkObject(link, true); + linkNew(entity); Context.getCalendarManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index 0f7579bae..285ed6a31 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -35,9 +35,7 @@ import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; @Path("devices") @Produces(MediaType.APPLICATION_JSON) @@ -79,10 +77,7 @@ public class DeviceResource extends BaseResource { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); Context.getPermissionsManager().checkDeviceLimit(getUserId()); Context.getDeviceManager().addDevice(entity); - LinkedHashMap link = new LinkedHashMap<>(); - link.put("userId", getUserId()); - link.put("deviceId", entity.getId()); - Context.getDataManager().linkObject(link, true); + linkNew(entity); Context.getPermissionsManager().refreshPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); @@ -121,34 +116,4 @@ public class DeviceResource extends BaseResource { return Response.noContent().build(); } - @Path("/{slave : (geofences|drivers|attributes)}") - @POST - public Response add(Map entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - if (entity.size() != 2) { - throw new IllegalArgumentException(); - } - for (String key : entity.keySet()) { - Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); - } - Context.getDataManager().linkObject(entity, true); - Context.getPermissionsManager().refreshPermissions(entity); - return Response.noContent().build(); - } - - @Path("/{slave : (geofences|drivers|attributes)}") - @DELETE - public Response remove(Map entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - for (String key : entity.keySet()) { - Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); - } - if (entity.size() != 2) { - throw new IllegalArgumentException(); - } - Context.getDataManager().linkObject(entity, false); - Context.getPermissionsManager().refreshPermissions(entity); - return Response.noContent().build(); - } - } diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index 91a502790..749674002 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -19,7 +19,6 @@ package org.traccar.api.resource; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.Set; import javax.ws.rs.Consumes; @@ -87,10 +86,7 @@ public class DriverResource extends BaseResource { public Response add(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDriversManager().addItem(entity); - LinkedHashMap link = new LinkedHashMap<>(); - link.put("userId", getUserId()); - link.put("driverId", entity.getId()); - Context.getDataManager().linkObject(link, true); + linkNew(entity); Context.getDriversManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/GeofenceResource.java b/src/org/traccar/api/resource/GeofenceResource.java index c39d882b6..df4947a1b 100644 --- a/src/org/traccar/api/resource/GeofenceResource.java +++ b/src/org/traccar/api/resource/GeofenceResource.java @@ -35,7 +35,6 @@ import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.Collection; import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.Set; @Path("geofences") @@ -86,10 +85,7 @@ public class GeofenceResource extends BaseResource { public Response add(Geofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getGeofenceManager().addItem(entity); - LinkedHashMap link = new LinkedHashMap<>(); - link.put("userId", getUserId()); - link.put("geofenceId", entity.getId()); - Context.getDataManager().linkObject(link, true); + linkNew(entity); Context.getGeofenceManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index 0d9572332..5d575ebfe 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -32,8 +32,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.Map; @Path("groups") @Produces(MediaType.APPLICATION_JSON) @@ -63,10 +61,7 @@ public class GroupResource extends BaseResource { public Response add(Group entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDeviceManager().addGroup(entity); - LinkedHashMap link = new LinkedHashMap<>(); - link.put("userId", getUserId()); - link.put("groupId", entity.getId()); - Context.getDataManager().linkObject(link, true); + linkNew(entity); Context.getPermissionsManager().refreshPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); @@ -93,34 +88,4 @@ public class GroupResource extends BaseResource { return Response.noContent().build(); } - @Path("/{slave : (geofences|drivers|attributes)}") - @POST - public Response add(Map entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - if (entity.size() != 2) { - throw new IllegalArgumentException(); - } - for (String key : entity.keySet()) { - Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); - } - Context.getDataManager().linkObject(entity, true); - Context.getPermissionsManager().refreshPermissions(entity); - return Response.noContent().build(); - } - - @Path("/{slave : (geofences|drivers|attributes)}") - @DELETE - public Response remove(Map entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - if (entity.size() != 2) { - throw new IllegalArgumentException(); - } - for (String key : entity.keySet()) { - Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); - } - Context.getDataManager().linkObject(entity, false); - Context.getPermissionsManager().refreshPermissions(entity); - return Response.noContent().build(); - } - } diff --git a/src/org/traccar/api/resource/PermissionsResource.java b/src/org/traccar/api/resource/PermissionsResource.java index e22ffae36..707242cf1 100644 --- a/src/org/traccar/api/resource/PermissionsResource.java +++ b/src/org/traccar/api/resource/PermissionsResource.java @@ -35,32 +35,18 @@ import org.traccar.api.BaseResource; @Consumes(MediaType.APPLICATION_JSON) public class PermissionsResource extends BaseResource { - @Path("/{slave : (users|devices|groups|geofences|drivers|attributes|calendars)}") @POST public Response add(Map entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - if (entity.size() != 2) { - throw new IllegalArgumentException(); - } - for (String key : entity.keySet()) { - Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); - } - Context.getDataManager().linkObject(entity, true); + handlePermission(entity, true); Context.getPermissionsManager().refreshPermissions(entity); return Response.noContent().build(); } - @Path("/{slave : (users|devices|groups|geofences|drivers|attributes|calendars)}") @DELETE public Response remove(Map entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - if (entity.size() != 2) { - throw new IllegalArgumentException(); - } - for (String key : entity.keySet()) { - Context.getPermissionsManager().checkPermission(key.replace("Id", ""), getUserId(), entity.get(key)); - } - Context.getDataManager().linkObject(entity, false); + handlePermission(entity, false); Context.getPermissionsManager().refreshPermissions(entity); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index 94cc56b47..e710c940d 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -34,7 +34,6 @@ import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.Collection; import java.util.Date; -import java.util.LinkedHashMap; @Path("users") @Produces(MediaType.APPLICATION_JSON) @@ -75,10 +74,7 @@ public class UserResource extends BaseResource { } Context.getPermissionsManager().addUser(entity); if (Context.getPermissionsManager().isManager(getUserId())) { - LinkedHashMap link = new LinkedHashMap<>(); - link.put("userId", getUserId()); - link.put("managedUserId", entity.getId()); - Context.getDataManager().linkObject(link, true); + Context.getDataManager().linkObject("userId", getUserId(), "managedUserId", entity.getId(), true); } Context.getPermissionsManager().refreshUserPermissions(); if (Context.getNotificationManager() != null) { diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 39a80ee72..9d8167acc 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -272,15 +272,17 @@ public class DataManager { return object.substring(0, 1).toUpperCase() + object.replace("Id", "").substring(1); } - public void linkObject(Map permission, boolean link) throws SQLException { - String query = "database." + (!link ? "un" : "") + "link"; - for (String key : permission.keySet()) { - query += makeName(key); - } + private String makeNameId(String object) { + return object.substring(0, 1).toLowerCase() + object.substring(1) + (object.indexOf("Id") == -1 ? "Id" : ""); + } + + public void linkObject(String owner, long ownerId, String property, long propertyId, + boolean link) throws SQLException { + String query = "database." + (!link ? "un" : "") + "link" + makeName(owner) + makeName(property); QueryBuilder queryBuilder = QueryBuilder.create(dataSource, getQuery(query)); - for (String key : permission.keySet()) { - queryBuilder.setLong(key, permission.get(key)); - } + + queryBuilder.setLong(makeNameId(owner), ownerId); + queryBuilder.setLong(makeNameId(property), propertyId); queryBuilder.executeUpdate(); } -- cgit v1.2.3 From 55d91ec7a86777bb0427422c15c2b8a60aa00071 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Fri, 21 Jul 2017 13:06:18 +0500 Subject: Implement type constants --- src/org/traccar/Context.java | 8 ++++++++ src/org/traccar/api/BaseResource.java | 9 ++++++--- src/org/traccar/api/resource/AttributeResource.java | 4 ++-- src/org/traccar/api/resource/CalendarResource.java | 4 ++-- src/org/traccar/api/resource/DriverResource.java | 4 ++-- src/org/traccar/api/resource/EventResource.java | 2 +- src/org/traccar/api/resource/GeofenceResource.java | 4 ++-- src/org/traccar/database/DataManager.java | 4 ++-- src/org/traccar/database/PermissionsManager.java | 16 ++++++++-------- 9 files changed, 33 insertions(+), 22 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index a4fc5b679..57c6bc908 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -59,6 +59,14 @@ import org.traccar.web.WebServer; public final class Context { + public static final String TYPE_USER = "User"; + public static final String TYPE_DEVICE = "Device"; + public static final String TYPE_GROUP = "Group"; + public static final String TYPE_GEOFENCE = "Geofence"; + public static final String TYPE_CALENDAR = "Calendar"; + public static final String TYPE_ATTRIBUTE = "Attribute"; + public static final String TYPE_DRIVER = "Driver"; + private Context() { } diff --git a/src/org/traccar/api/BaseResource.java b/src/org/traccar/api/BaseResource.java index 9ac30f5a7..4ad1477c2 100644 --- a/src/org/traccar/api/BaseResource.java +++ b/src/org/traccar/api/BaseResource.java @@ -22,6 +22,7 @@ import java.util.Map; import javax.ws.rs.core.SecurityContext; import org.traccar.Context; +import org.traccar.database.DataManager; import org.traccar.model.BaseModel; public class BaseResource { @@ -44,19 +45,21 @@ public class BaseResource { Iterator iterator = entity.keySet().iterator(); String owner = iterator.next(); String property = iterator.next(); + long ownerId = entity.get(owner); long propertyId = entity.get(property); - if (!link && owner.equals("userId") && property.equals("deviceId")) { + if (!link && DataManager.makeName(owner).equals(Context.TYPE_USER) + && DataManager.makeName(property).equals(Context.TYPE_DEVICE)) { if (getUserId() != ownerId) { Context.getPermissionsManager().checkUser(getUserId(), ownerId); } else { Context.getPermissionsManager().checkAdmin(getUserId()); } } else { - Context.getPermissionsManager().checkPermission(owner.replace("Id", ""), getUserId(), ownerId); + Context.getPermissionsManager().checkPermission(owner, getUserId(), ownerId); } - Context.getPermissionsManager().checkPermission(property.replace("Id", ""), getUserId(), propertyId); + Context.getPermissionsManager().checkPermission(property, getUserId(), propertyId); Context.getDataManager().linkObject(owner, ownerId, property, propertyId, link); } diff --git a/src/org/traccar/api/resource/AttributeResource.java b/src/org/traccar/api/resource/AttributeResource.java index c6c95e05c..63cdfb2a7 100644 --- a/src/org/traccar/api/resource/AttributeResource.java +++ b/src/org/traccar/api/resource/AttributeResource.java @@ -128,7 +128,7 @@ public class AttributeResource extends BaseResource { @PUT public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission("attribute", getUserId(), entity.getId()); + Context.getPermissionsManager().checkPermission(Context.TYPE_ATTRIBUTE, getUserId(), entity.getId()); Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); } @@ -137,7 +137,7 @@ public class AttributeResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission("attribute", getUserId(), id); + Context.getPermissionsManager().checkPermission(Context.TYPE_ATTRIBUTE, getUserId(), id); Context.getAttributesManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/CalendarResource.java b/src/org/traccar/api/resource/CalendarResource.java index 0666f2fed..d29080ee2 100644 --- a/src/org/traccar/api/resource/CalendarResource.java +++ b/src/org/traccar/api/resource/CalendarResource.java @@ -75,7 +75,7 @@ public class CalendarResource extends BaseResource { @PUT public Response update(Calendar entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission("calendar", getUserId(), entity.getId()); + Context.getPermissionsManager().checkPermission(Context.TYPE_CALENDAR, getUserId(), entity.getId()); Context.getCalendarManager().updateItem(entity); return Response.ok(entity).build(); } @@ -84,7 +84,7 @@ public class CalendarResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission("calendar", getUserId(), id); + Context.getPermissionsManager().checkPermission(Context.TYPE_CALENDAR, getUserId(), id); Context.getCalendarManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index 749674002..b528a197a 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -95,7 +95,7 @@ public class DriverResource extends BaseResource { @PUT public Response update(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission("driver", getUserId(), entity.getId()); + Context.getPermissionsManager().checkPermission(Context.TYPE_DRIVER, getUserId(), entity.getId()); Context.getDriversManager().updateItem(entity); return Response.ok(entity).build(); } @@ -104,7 +104,7 @@ public class DriverResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission("driver", getUserId(), id); + Context.getPermissionsManager().checkPermission(Context.TYPE_DRIVER, getUserId(), id); Context.getDriversManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/EventResource.java b/src/org/traccar/api/resource/EventResource.java index 9b43bf4b0..85f981514 100644 --- a/src/org/traccar/api/resource/EventResource.java +++ b/src/org/traccar/api/resource/EventResource.java @@ -25,7 +25,7 @@ public class EventResource extends BaseResource { Event event = Context.getDataManager().getEvent(id); Context.getPermissionsManager().checkDevice(getUserId(), event.getDeviceId()); if (event.getGeofenceId() != 0) { - Context.getPermissionsManager().checkPermission("geofence", getUserId(), event.getGeofenceId()); + Context.getPermissionsManager().checkPermission(Context.TYPE_GEOFENCE, getUserId(), event.getGeofenceId()); } return event; } diff --git a/src/org/traccar/api/resource/GeofenceResource.java b/src/org/traccar/api/resource/GeofenceResource.java index df4947a1b..c9cc72bd7 100644 --- a/src/org/traccar/api/resource/GeofenceResource.java +++ b/src/org/traccar/api/resource/GeofenceResource.java @@ -94,7 +94,7 @@ public class GeofenceResource extends BaseResource { @PUT public Response update(Geofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission("geofence", getUserId(), entity.getId()); + Context.getPermissionsManager().checkPermission(Context.TYPE_GEOFENCE, getUserId(), entity.getId()); Context.getGeofenceManager().updateItem(entity); return Response.ok(entity).build(); } @@ -103,7 +103,7 @@ public class GeofenceResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission("geofence", getUserId(), id); + Context.getPermissionsManager().checkPermission(Context.TYPE_GEOFENCE, getUserId(), id); Context.getGeofenceManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 9d8167acc..3bb367ece 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -268,11 +268,11 @@ public class DataManager { .executeUpdate()); } - private String makeName(String object) { + public static String makeName(String object) { return object.substring(0, 1).toUpperCase() + object.replace("Id", "").substring(1); } - private String makeNameId(String object) { + public static String makeNameId(String object) { return object.substring(0, 1).toLowerCase() + object.substring(1) + (object.indexOf("Id") == -1 ? "Id" : ""); } diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 5f83a1274..56a12e941 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -299,26 +299,26 @@ public class PermissionsManager { public void checkPermission(String object, long userId, long objectId) throws SecurityException { SimpleObjectManager manager = null; - switch (object) { - case "device": + switch (DataManager.makeName(object)) { + case Context.TYPE_DEVICE: checkDevice(userId, objectId); break; - case "group": + case Context.TYPE_GROUP: checkGroup(userId, objectId); break; - case "user": + case Context.TYPE_USER: checkUser(userId, objectId); break; - case "geofence": + case Context.TYPE_GEOFENCE: manager = Context.getGeofenceManager(); break; - case "attribute": + case Context.TYPE_ATTRIBUTE: manager = Context.getAttributesManager(); break; - case "driver": + case Context.TYPE_DRIVER: manager = Context.getDriversManager(); break; - case "calendar": + case Context.TYPE_CALENDAR: manager = Context.getCalendarManager(); break; default: -- cgit v1.2.3 From 69c46399ee0f6b3dd2b0589cb412e9e17f040369 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Fri, 21 Jul 2017 18:41:49 +0500 Subject: Use classes instead of constants everywhere --- setup/default.xml | 14 ++-- src/org/traccar/Context.java | 8 -- src/org/traccar/api/BaseResource.java | 29 +++---- .../traccar/api/resource/AttributeResource.java | 6 +- src/org/traccar/api/resource/CalendarResource.java | 6 +- src/org/traccar/api/resource/DeviceResource.java | 2 +- src/org/traccar/api/resource/DriverResource.java | 6 +- src/org/traccar/api/resource/EventResource.java | 3 +- src/org/traccar/api/resource/GeofenceResource.java | 6 +- src/org/traccar/api/resource/GroupResource.java | 2 +- .../traccar/api/resource/PermissionsResource.java | 10 +-- src/org/traccar/api/resource/UserResource.java | 3 +- src/org/traccar/database/DataManager.java | 21 +++-- src/org/traccar/database/DriversManager.java | 2 +- .../traccar/database/ExtendedObjectManager.java | 14 ++-- src/org/traccar/database/PermissionsManager.java | 96 +++++++++++----------- src/org/traccar/database/SimpleObjectManager.java | 16 ++-- src/org/traccar/model/ManagedUser.java | 21 +++++ 18 files changed, 144 insertions(+), 121 deletions(-) create mode 100644 src/org/traccar/model/ManagedUser.java (limited to 'src/org/traccar/api') diff --git a/setup/default.xml b/setup/default.xml index dcf995af0..f0f9ef4a3 100644 --- a/setup/default.xml +++ b/setup/default.xml @@ -103,11 +103,11 @@ DELETE FROM users WHERE id = :id - + SELECT userId, deviceId FROM user_device - + SELECT userId, groupId FROM user_group @@ -230,7 +230,7 @@ DELETE FROM geofences WHERE id = :id - + SELECT userId, geofenceId FROM user_geofence @@ -349,7 +349,7 @@ DELETE FROM calendars WHERE id = :id - + SELECT userId, calendarId FROM user_calendar @@ -361,7 +361,7 @@ DELETE FROM user_calendar WHERE userId = :userId AND calendarId = :calendarId - + SELECT userId, managedUserId FROM user_user @@ -395,7 +395,7 @@ DELETE FROM attributes WHERE id = :id - + SELECT userId, attributeId FROM user_attribute @@ -452,7 +452,7 @@ DELETE FROM drivers WHERE id = :id - + SELECT userId, driverId FROM user_driver diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 57c6bc908..a4fc5b679 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -59,14 +59,6 @@ import org.traccar.web.WebServer; public final class Context { - public static final String TYPE_USER = "User"; - public static final String TYPE_DEVICE = "Device"; - public static final String TYPE_GROUP = "Group"; - public static final String TYPE_GEOFENCE = "Geofence"; - public static final String TYPE_CALENDAR = "Calendar"; - public static final String TYPE_ATTRIBUTE = "Attribute"; - public static final String TYPE_DRIVER = "Driver"; - private Context() { } diff --git a/src/org/traccar/api/BaseResource.java b/src/org/traccar/api/BaseResource.java index 4ad1477c2..920bb3931 100644 --- a/src/org/traccar/api/BaseResource.java +++ b/src/org/traccar/api/BaseResource.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 - 2016 Anton Tananaev (anton@traccar.org) + * Copyright 2015 - 2017 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,15 @@ package org.traccar.api; import java.sql.SQLException; import java.util.Iterator; -import java.util.Map; +import java.util.LinkedHashMap; import javax.ws.rs.core.SecurityContext; import org.traccar.Context; import org.traccar.database.DataManager; import org.traccar.model.BaseModel; +import org.traccar.model.Device; +import org.traccar.model.User; public class BaseResource { @@ -38,34 +40,33 @@ public class BaseResource { return 0; } - protected void handlePermission(Map entity, boolean link) throws SQLException { - if (entity.size() != 2) { - throw new IllegalArgumentException(); - } + protected void checkAndLinkPermission(LinkedHashMap entity, boolean link) + throws SQLException, ClassNotFoundException { Iterator iterator = entity.keySet().iterator(); String owner = iterator.next(); + Class ownerClass = DataManager.getClassByName(owner); String property = iterator.next(); + Class propertyClass = DataManager.getClassByName(property); long ownerId = entity.get(owner); long propertyId = entity.get(property); - if (!link && DataManager.makeName(owner).equals(Context.TYPE_USER) - && DataManager.makeName(property).equals(Context.TYPE_DEVICE)) { + if (!link && ownerClass.equals(User.class) + && propertyClass.equals(Device.class)) { if (getUserId() != ownerId) { Context.getPermissionsManager().checkUser(getUserId(), ownerId); } else { Context.getPermissionsManager().checkAdmin(getUserId()); } } else { - Context.getPermissionsManager().checkPermission(owner, getUserId(), ownerId); + Context.getPermissionsManager().checkPermission(ownerClass, getUserId(), ownerId); } - Context.getPermissionsManager().checkPermission(property, getUserId(), propertyId); + Context.getPermissionsManager().checkPermission(propertyClass, getUserId(), propertyId); - Context.getDataManager().linkObject(owner, ownerId, property, propertyId, link); + Context.getDataManager().linkObject(ownerClass, ownerId, propertyClass, propertyId, link); } - protected void linkNew(BaseModel entity) throws SQLException { - Context.getDataManager().linkObject("userId", getUserId(), - entity.getClass().getSimpleName(), entity.getId(), true); + protected void linkNewEntity(BaseModel entity) throws SQLException { + Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); } } diff --git a/src/org/traccar/api/resource/AttributeResource.java b/src/org/traccar/api/resource/AttributeResource.java index 63cdfb2a7..7e6947d26 100644 --- a/src/org/traccar/api/resource/AttributeResource.java +++ b/src/org/traccar/api/resource/AttributeResource.java @@ -87,7 +87,7 @@ public class AttributeResource extends BaseResource { private Response add(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getAttributesManager().addItem(entity); - linkNew(entity); + linkNewEntity(entity); Context.getAttributesManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -128,7 +128,7 @@ public class AttributeResource extends BaseResource { @PUT public Response update(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Context.TYPE_ATTRIBUTE, getUserId(), entity.getId()); + Context.getPermissionsManager().checkPermission(Attribute.class, getUserId(), entity.getId()); Context.getAttributesManager().updateItem(entity); return Response.ok(entity).build(); } @@ -137,7 +137,7 @@ public class AttributeResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Context.TYPE_ATTRIBUTE, getUserId(), id); + Context.getPermissionsManager().checkPermission(Attribute.class, getUserId(), id); Context.getAttributesManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/CalendarResource.java b/src/org/traccar/api/resource/CalendarResource.java index d29080ee2..30f5df6b8 100644 --- a/src/org/traccar/api/resource/CalendarResource.java +++ b/src/org/traccar/api/resource/CalendarResource.java @@ -66,7 +66,7 @@ public class CalendarResource extends BaseResource { public Response add(Calendar entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getCalendarManager().addItem(entity); - linkNew(entity); + linkNewEntity(entity); Context.getCalendarManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -75,7 +75,7 @@ public class CalendarResource extends BaseResource { @PUT public Response update(Calendar entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Context.TYPE_CALENDAR, getUserId(), entity.getId()); + Context.getPermissionsManager().checkPermission(Calendar.class, getUserId(), entity.getId()); Context.getCalendarManager().updateItem(entity); return Response.ok(entity).build(); } @@ -84,7 +84,7 @@ public class CalendarResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Context.TYPE_CALENDAR, getUserId(), id); + Context.getPermissionsManager().checkPermission(Calendar.class, getUserId(), id); Context.getCalendarManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index 285ed6a31..e1c0fc96d 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -77,7 +77,7 @@ public class DeviceResource extends BaseResource { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); Context.getPermissionsManager().checkDeviceLimit(getUserId()); Context.getDeviceManager().addDevice(entity); - linkNew(entity); + linkNewEntity(entity); Context.getPermissionsManager().refreshPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index b528a197a..cf80bf7df 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -86,7 +86,7 @@ public class DriverResource extends BaseResource { public Response add(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDriversManager().addItem(entity); - linkNew(entity); + linkNewEntity(entity); Context.getDriversManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -95,7 +95,7 @@ public class DriverResource extends BaseResource { @PUT public Response update(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Context.TYPE_DRIVER, getUserId(), entity.getId()); + Context.getPermissionsManager().checkPermission(Driver.class, getUserId(), entity.getId()); Context.getDriversManager().updateItem(entity); return Response.ok(entity).build(); } @@ -104,7 +104,7 @@ public class DriverResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Context.TYPE_DRIVER, getUserId(), id); + Context.getPermissionsManager().checkPermission(Driver.class, getUserId(), id); Context.getDriversManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/EventResource.java b/src/org/traccar/api/resource/EventResource.java index 85f981514..b7fda6f73 100644 --- a/src/org/traccar/api/resource/EventResource.java +++ b/src/org/traccar/api/resource/EventResource.java @@ -12,6 +12,7 @@ import javax.ws.rs.core.MediaType; import org.traccar.Context; import org.traccar.api.BaseResource; import org.traccar.model.Event; +import org.traccar.model.Geofence; @Path("events") @Produces(MediaType.APPLICATION_JSON) @@ -25,7 +26,7 @@ public class EventResource extends BaseResource { Event event = Context.getDataManager().getEvent(id); Context.getPermissionsManager().checkDevice(getUserId(), event.getDeviceId()); if (event.getGeofenceId() != 0) { - Context.getPermissionsManager().checkPermission(Context.TYPE_GEOFENCE, getUserId(), event.getGeofenceId()); + Context.getPermissionsManager().checkPermission(Geofence.class, getUserId(), event.getGeofenceId()); } return event; } diff --git a/src/org/traccar/api/resource/GeofenceResource.java b/src/org/traccar/api/resource/GeofenceResource.java index c9cc72bd7..341180cf8 100644 --- a/src/org/traccar/api/resource/GeofenceResource.java +++ b/src/org/traccar/api/resource/GeofenceResource.java @@ -85,7 +85,7 @@ public class GeofenceResource extends BaseResource { public Response add(Geofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getGeofenceManager().addItem(entity); - linkNew(entity); + linkNewEntity(entity); Context.getGeofenceManager().refreshUserItems(); return Response.ok(entity).build(); } @@ -94,7 +94,7 @@ public class GeofenceResource extends BaseResource { @PUT public Response update(Geofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Context.TYPE_GEOFENCE, getUserId(), entity.getId()); + Context.getPermissionsManager().checkPermission(Geofence.class, getUserId(), entity.getId()); Context.getGeofenceManager().updateItem(entity); return Response.ok(entity).build(); } @@ -103,7 +103,7 @@ public class GeofenceResource extends BaseResource { @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Context.TYPE_GEOFENCE, getUserId(), id); + Context.getPermissionsManager().checkPermission(Geofence.class, getUserId(), id); Context.getGeofenceManager().removeItem(id); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index 5d575ebfe..2ecd11fe5 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -61,7 +61,7 @@ public class GroupResource extends BaseResource { public Response add(Group entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDeviceManager().addGroup(entity); - linkNew(entity); + linkNewEntity(entity); Context.getPermissionsManager().refreshPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); diff --git a/src/org/traccar/api/resource/PermissionsResource.java b/src/org/traccar/api/resource/PermissionsResource.java index 707242cf1..515efbe41 100644 --- a/src/org/traccar/api/resource/PermissionsResource.java +++ b/src/org/traccar/api/resource/PermissionsResource.java @@ -17,7 +17,7 @@ package org.traccar.api.resource; import java.sql.SQLException; -import java.util.Map; +import java.util.LinkedHashMap; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -36,17 +36,17 @@ import org.traccar.api.BaseResource; public class PermissionsResource extends BaseResource { @POST - public Response add(Map entity) throws SQLException { + public Response add(LinkedHashMap entity) throws SQLException, ClassNotFoundException { Context.getPermissionsManager().checkReadonly(getUserId()); - handlePermission(entity, true); + checkAndLinkPermission(entity, true); Context.getPermissionsManager().refreshPermissions(entity); return Response.noContent().build(); } @DELETE - public Response remove(Map entity) throws SQLException { + public Response remove(LinkedHashMap entity) throws SQLException, ClassNotFoundException { Context.getPermissionsManager().checkReadonly(getUserId()); - handlePermission(entity, false); + checkAndLinkPermission(entity, false); Context.getPermissionsManager().refreshPermissions(entity); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index e710c940d..98395e3cc 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -17,6 +17,7 @@ package org.traccar.api.resource; import org.traccar.Context; import org.traccar.api.BaseResource; +import org.traccar.model.ManagedUser; import org.traccar.model.User; import javax.annotation.security.PermitAll; @@ -74,7 +75,7 @@ public class UserResource extends BaseResource { } Context.getPermissionsManager().addUser(entity); if (Context.getPermissionsManager().isManager(getUserId())) { - Context.getDataManager().linkObject("userId", getUserId(), "managedUserId", entity.getId(), true); + Context.getDataManager().linkObject(User.class, getUserId(), ManagedUser.class, entity.getId(), true); } Context.getPermissionsManager().refreshUserPermissions(); if (Context.getNotificationManager() != null) { diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 3bb367ece..80b9f98e9 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -268,17 +268,19 @@ public class DataManager { .executeUpdate()); } - public static String makeName(String object) { - return object.substring(0, 1).toUpperCase() + object.replace("Id", "").substring(1); + public static Class getClassByName(String name) throws ClassNotFoundException { + return Class.forName("org.traccar.model." + + name.substring(0, 1).toUpperCase() + name.replace("Id", "").substring(1)); } - public static String makeNameId(String object) { - return object.substring(0, 1).toLowerCase() + object.substring(1) + (object.indexOf("Id") == -1 ? "Id" : ""); + public static String makeNameId(Class clazz) { + String name = clazz.getSimpleName(); + return name.substring(0, 1).toLowerCase() + name.substring(1) + (name.indexOf("Id") == -1 ? "Id" : ""); } - public void linkObject(String owner, long ownerId, String property, long propertyId, - boolean link) throws SQLException { - String query = "database." + (!link ? "un" : "") + "link" + makeName(owner) + makeName(property); + public void linkObject(Class owner, long ownerId, Class property, long propertyId, boolean link) + throws SQLException { + String query = "database." + (link ? "link" : "unlink") + owner.getSimpleName() + property.getSimpleName(); QueryBuilder queryBuilder = QueryBuilder.create(dataSource, getQuery(query)); queryBuilder.setLong(makeNameId(owner), ownerId); @@ -291,8 +293,9 @@ public class DataManager { return QueryBuilder.create(dataSource, getQuery(query)).executeQuery(clazz); } - public Collection> getPermissions(String owner, String property) throws SQLException { - String query = "database.select" + makeName(owner) + makeName(property) + "s"; + public Collection> getPermissions(Class owner, + Class property) throws SQLException { + String query = "database.select" + owner.getSimpleName() + property.getSimpleName() + "s"; return QueryBuilder.create(dataSource, getQuery(query)).executeMapQuery(Long.class); } diff --git a/src/org/traccar/database/DriversManager.java b/src/org/traccar/database/DriversManager.java index 8c35f3ddf..0dc2b102d 100644 --- a/src/org/traccar/database/DriversManager.java +++ b/src/org/traccar/database/DriversManager.java @@ -73,7 +73,7 @@ public class DriversManager extends ExtendedObjectManager { @Override public void removeItem(long driverId) throws SQLException { Driver cachedDriver = (Driver) getById(driverId); - getDataManager().removeObject(cachedDriver.getClass(), driverId); + getDataManager().removeObject(Driver.class, driverId); if (cachedDriver != null) { String driverUniqueId = cachedDriver.getUniqueId(); removeCachedItem(driverId); diff --git a/src/org/traccar/database/ExtendedObjectManager.java b/src/org/traccar/database/ExtendedObjectManager.java index fce32fb41..8380b9da2 100644 --- a/src/org/traccar/database/ExtendedObjectManager.java +++ b/src/org/traccar/database/ExtendedObjectManager.java @@ -26,6 +26,7 @@ import java.util.concurrent.ConcurrentHashMap; import org.traccar.Context; import org.traccar.helper.Log; import org.traccar.model.Device; +import org.traccar.model.Group; import org.traccar.model.BaseModel; public abstract class ExtendedObjectManager extends SimpleObjectManager { @@ -79,23 +80,26 @@ public abstract class ExtendedObjectManager extends SimpleObjectManager { try { Collection> databaseGroupPermissions = - getDataManager().getPermissions("Group", getBaseClassName()); + getDataManager().getPermissions(Group.class, getBaseClass()); clearGroupItems(); for (Map groupPermission : databaseGroupPermissions) { - getGroupItems(groupPermission.get("groupId")).add(groupPermission.get(getBaseClassIdName())); + getGroupItems(groupPermission.get(DataManager.makeNameId(Group.class))) + .add(groupPermission.get(getBaseClassIdName())); } Collection> databaseDevicePermissions = - getDataManager().getPermissions("Device", getBaseClassName()); + getDataManager().getPermissions(Device.class, getBaseClass()); Collection allDevices = Context.getDeviceManager().getAllDevices(); clearDeviceItems(); deviceItemsWithGroups.clear(); for (Map devicePermission : databaseDevicePermissions) { - getDeviceItems(devicePermission.get("deviceId")).add(devicePermission.get(getBaseClassIdName())); - getAllDeviceItems(devicePermission.get("deviceId")).add(devicePermission.get(getBaseClassIdName())); + getDeviceItems(devicePermission.get(DataManager.makeNameId(Device.class))) + .add(devicePermission.get(getBaseClassIdName())); + getAllDeviceItems(devicePermission.get(DataManager.makeNameId(Device.class))) + .add(devicePermission.get(getBaseClassIdName())); } for (Device device : allDevices) { diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 56a12e941..4008134ec 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -17,8 +17,13 @@ package org.traccar.database; import org.traccar.Context; import org.traccar.helper.Log; +import org.traccar.model.Attribute; +import org.traccar.model.Calendar; import org.traccar.model.Device; +import org.traccar.model.Driver; +import org.traccar.model.Geofence; import org.traccar.model.Group; +import org.traccar.model.ManagedUser; import org.traccar.model.Server; import org.traccar.model.User; @@ -109,8 +114,9 @@ public class PermissionsManager { public final void refreshUserPermissions() { userPermissions.clear(); try { - for (Map permission : dataManager.getPermissions("User", "Permission")) { - getUserPermissions(permission.get("userId")).add(permission.get("managedUserId")); + for (Map permission : dataManager.getPermissions(User.class, User.class)) { + getUserPermissions(permission.get(DataManager.makeNameId(User.class))) + .add(permission.get(DataManager.makeNameId(ManagedUser.class))); } } catch (SQLException error) { Log.warning(error); @@ -123,20 +129,23 @@ public class PermissionsManager { try { GroupTree groupTree = new GroupTree(Context.getDeviceManager().getAllGroups(), Context.getDeviceManager().getAllDevices()); - for (Map groupPermission : dataManager.getPermissions("Group", "Permission")) { - Set userGroupPermissions = getGroupPermissions(groupPermission.get("userId")); - Set userDevicePermissions = getDevicePermissions(groupPermission.get("userId")); - userGroupPermissions.add(groupPermission.get("groupId")); - for (Group group : groupTree.getGroups(groupPermission.get("groupId"))) { + for (Map groupPermission : dataManager.getPermissions(User.class, Group.class)) { + Set userGroupPermissions = getGroupPermissions(groupPermission + .get(DataManager.makeNameId(User.class))); + Set userDevicePermissions = getDevicePermissions(groupPermission + .get(DataManager.makeNameId(User.class))); + userGroupPermissions.add(groupPermission.get(DataManager.makeNameId(Group.class))); + for (Group group : groupTree.getGroups(groupPermission.get(DataManager.makeNameId(Group.class)))) { userGroupPermissions.add(group.getId()); } - for (Device device : groupTree.getDevices(groupPermission.get("groupId"))) { + for (Device device : groupTree.getDevices(groupPermission.get(DataManager.makeNameId(Group.class)))) { userDevicePermissions.add(device.getId()); } } - for (Map devicePermission : dataManager.getPermissions("Device", "Permission")) { - getDevicePermissions(devicePermission.get("userId")).add(devicePermission.get("deviceId")); + for (Map devicePermission : dataManager.getPermissions(User.class, Device.class)) { + getDevicePermissions(devicePermission.get(DataManager.makeNameId(User.class))) + .add(devicePermission.get(DataManager.makeNameId(Device.class))); } groupDevices.clear(); @@ -296,33 +305,26 @@ public class PermissionsManager { } } - public void checkPermission(String object, long userId, long objectId) throws SecurityException { + public void checkPermission(Class object, long userId, long objectId) + throws SecurityException { SimpleObjectManager manager = null; - switch (DataManager.makeName(object)) { - case Context.TYPE_DEVICE: - checkDevice(userId, objectId); - break; - case Context.TYPE_GROUP: - checkGroup(userId, objectId); - break; - case Context.TYPE_USER: - checkUser(userId, objectId); - break; - case Context.TYPE_GEOFENCE: - manager = Context.getGeofenceManager(); - break; - case Context.TYPE_ATTRIBUTE: - manager = Context.getAttributesManager(); - break; - case Context.TYPE_DRIVER: - manager = Context.getDriversManager(); - break; - case Context.TYPE_CALENDAR: - manager = Context.getCalendarManager(); - break; - default: - throw new IllegalArgumentException("Unknown object type"); + if (object.equals(Device.class)) { + checkDevice(userId, objectId); + } else if (object.equals(Group.class)) { + checkGroup(userId, objectId); + } else if (object.equals(User.class) || object.equals(ManagedUser.class)) { + checkUser(userId, objectId); + } else if (object.equals(Geofence.class)) { + manager = Context.getGeofenceManager(); + } else if (object.equals(Attribute.class)) { + manager = Context.getAttributesManager(); + } else if (object.equals(Driver.class)) { + manager = Context.getDriversManager(); + } else if (object.equals(Calendar.class)) { + manager = Context.getCalendarManager(); + } else { + throw new IllegalArgumentException("Unknown object type"); } if (manager != null) { @@ -347,31 +349,33 @@ public class PermissionsManager { } public void refreshPermissions(Map entity) { - if (entity.containsKey("userId")) { - if (entity.containsKey("deviceId") || entity.containsKey("groupId")) { + if (entity.containsKey(DataManager.makeNameId(User.class))) { + if (entity.containsKey(DataManager.makeNameId(Device.class)) + || entity.containsKey(DataManager.makeNameId(Group.class))) { refreshPermissions(); refreshAllExtendedPermissions(); - } else if (entity.containsKey("managedUserId")) { + } else if (entity.containsKey(DataManager.makeNameId(ManagedUser.class))) { refreshUserPermissions(); - } else if (entity.containsKey("geofenceId")) { + } else if (entity.containsKey(DataManager.makeNameId(Geofence.class))) { if (Context.getGeofenceManager() != null) { Context.getGeofenceManager().refreshUserItems(); } - } else if (entity.containsKey("driverId")) { + } else if (entity.containsKey(DataManager.makeNameId(Driver.class))) { Context.getDriversManager().refreshUserItems(); - } else if (entity.containsKey("attributeId")) { + } else if (entity.containsKey(DataManager.makeNameId(Attribute.class))) { Context.getAttributesManager().refreshUserItems(); - } else if (entity.containsKey("calendarId")) { + } else if (entity.containsKey(DataManager.makeNameId(Calendar.class))) { Context.getCalendarManager().refreshUserItems(); } - } else if (entity.containsKey("deviceId") || entity.containsKey("groupId")) { - if (entity.containsKey("geofenceId")) { + } else if (entity.containsKey(DataManager.makeNameId(Device.class)) + || entity.containsKey(DataManager.makeNameId(Group.class))) { + if (entity.containsKey(DataManager.makeNameId(Geofence.class))) { if (Context.getGeofenceManager() != null) { Context.getGeofenceManager().refreshExtendedPermissions(); } - } else if (entity.containsKey("driverId")) { + } else if (entity.containsKey(DataManager.makeNameId(Driver.class))) { Context.getDriversManager().refreshExtendedPermissions(); - } else if (entity.containsKey("attributeId")) { + } else if (entity.containsKey(DataManager.makeNameId(Attribute.class))) { Context.getAttributesManager().refreshExtendedPermissions(); } } diff --git a/src/org/traccar/database/SimpleObjectManager.java b/src/org/traccar/database/SimpleObjectManager.java index c4fc0e97a..0db8af658 100644 --- a/src/org/traccar/database/SimpleObjectManager.java +++ b/src/org/traccar/database/SimpleObjectManager.java @@ -27,6 +27,7 @@ import java.util.concurrent.ConcurrentHashMap; import org.traccar.Context; import org.traccar.helper.Log; import org.traccar.model.BaseModel; +import org.traccar.model.User; public abstract class SimpleObjectManager { @@ -36,14 +37,12 @@ public abstract class SimpleObjectManager { private final Map> userItems = new ConcurrentHashMap<>(); private Class baseClass; - private String baseClassName; private String baseClassIdName; protected SimpleObjectManager(DataManager dataManager, Class baseClass) { this.dataManager = dataManager; this.baseClass = baseClass; - baseClassName = baseClass.getSimpleName(); - baseClassIdName = baseClassName.substring(0, 1).toLowerCase() + baseClassName.substring(1) + "Id"; + baseClassIdName = DataManager.makeNameId(baseClass); } protected final DataManager getDataManager() { @@ -54,10 +53,6 @@ public abstract class SimpleObjectManager { return baseClass; } - protected final String getBaseClassName() { - return baseClassName; - } - protected final String getBaseClassIdName() { return baseClassIdName; } @@ -111,8 +106,9 @@ public abstract class SimpleObjectManager { if (dataManager != null) { try { clearUserItems(); - for (Map permission : dataManager.getPermissions(baseClassName, "Permission")) { - getUserItems(permission.get("userId")).add(permission.get(baseClassIdName)); + for (Map permission : dataManager.getPermissions(User.class, baseClass)) { + getUserItems(permission.get(DataManager.makeNameId(User.class))) + .add(permission.get(baseClassIdName)); } } catch (SQLException error) { Log.warning(error); @@ -133,7 +129,7 @@ public abstract class SimpleObjectManager { public void removeItem(long itemId) throws SQLException { BaseModel item = getById(itemId); if (item != null) { - dataManager.removeObject(item.getClass(), itemId); + dataManager.removeObject(baseClass, itemId); removeCachedItem(itemId); } refreshUserItems(); diff --git a/src/org/traccar/model/ManagedUser.java b/src/org/traccar/model/ManagedUser.java new file mode 100644 index 000000000..03c5ef48d --- /dev/null +++ b/src/org/traccar/model/ManagedUser.java @@ -0,0 +1,21 @@ +/* + * 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.model; + +public class ManagedUser extends User { + +} -- cgit v1.2.3 From 4cb47c38af63696470acdc91d7b7d01512f6b2e7 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Sat, 22 Jul 2017 11:16:14 +0500 Subject: - Add Permission helper Class - Reorganize permission check and link - Optimize calendar retrieving --- src/org/traccar/api/BaseResource.java | 30 ------------ src/org/traccar/api/resource/DeviceResource.java | 2 +- src/org/traccar/api/resource/GroupResource.java | 2 +- .../traccar/api/resource/PermissionsResource.java | 29 ++++++++++- src/org/traccar/events/GeofenceEventHandler.java | 16 +++--- src/org/traccar/model/Permission.java | 57 ++++++++++++++++++++++ 6 files changed, 96 insertions(+), 40 deletions(-) create mode 100644 src/org/traccar/model/Permission.java (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/BaseResource.java b/src/org/traccar/api/BaseResource.java index 920bb3931..502591efe 100644 --- a/src/org/traccar/api/BaseResource.java +++ b/src/org/traccar/api/BaseResource.java @@ -16,15 +16,11 @@ package org.traccar.api; import java.sql.SQLException; -import java.util.Iterator; -import java.util.LinkedHashMap; import javax.ws.rs.core.SecurityContext; import org.traccar.Context; -import org.traccar.database.DataManager; import org.traccar.model.BaseModel; -import org.traccar.model.Device; import org.traccar.model.User; public class BaseResource { @@ -40,32 +36,6 @@ public class BaseResource { return 0; } - protected void checkAndLinkPermission(LinkedHashMap entity, boolean link) - throws SQLException, ClassNotFoundException { - Iterator iterator = entity.keySet().iterator(); - String owner = iterator.next(); - Class ownerClass = DataManager.getClassByName(owner); - String property = iterator.next(); - Class propertyClass = DataManager.getClassByName(property); - - long ownerId = entity.get(owner); - long propertyId = entity.get(property); - - if (!link && ownerClass.equals(User.class) - && propertyClass.equals(Device.class)) { - if (getUserId() != ownerId) { - Context.getPermissionsManager().checkUser(getUserId(), ownerId); - } else { - Context.getPermissionsManager().checkAdmin(getUserId()); - } - } else { - Context.getPermissionsManager().checkPermission(ownerClass, getUserId(), ownerId); - } - Context.getPermissionsManager().checkPermission(propertyClass, getUserId(), propertyId); - - Context.getDataManager().linkObject(ownerClass, ownerId, propertyClass, propertyId, link); - } - protected void linkNewEntity(BaseModel entity) throws SQLException { Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); } diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index e1c0fc96d..0d6e4f09c 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -95,7 +95,7 @@ public class DeviceResource extends BaseResource { return Response.ok(entity).build(); } - @Path("{id : \\d+}") + @Path("{id}") @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index 2ecd11fe5..402e687e6 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -77,7 +77,7 @@ public class GroupResource extends BaseResource { return Response.ok(entity).build(); } - @Path("{id : \\d+}") + @Path("{id}") @DELETE public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); diff --git a/src/org/traccar/api/resource/PermissionsResource.java b/src/org/traccar/api/resource/PermissionsResource.java index 515efbe41..88fd9d092 100644 --- a/src/org/traccar/api/resource/PermissionsResource.java +++ b/src/org/traccar/api/resource/PermissionsResource.java @@ -29,16 +29,38 @@ import javax.ws.rs.core.Response; import org.traccar.Context; import org.traccar.api.BaseResource; +import org.traccar.model.Device; +import org.traccar.model.Permission; +import org.traccar.model.User; @Path("permissions") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class PermissionsResource extends BaseResource { + private void checkPermission(Permission permission, boolean link) { + if (!link && permission.getOwnerClass().equals(User.class) + && permission.getPropertyClass().equals(Device.class)) { + if (getUserId() != permission.getOwnerId()) { + Context.getPermissionsManager().checkUser(getUserId(), permission.getOwnerId()); + } else { + Context.getPermissionsManager().checkAdmin(getUserId()); + } + } else { + Context.getPermissionsManager().checkPermission( + permission.getOwnerClass(), getUserId(), permission.getOwnerId()); + } + Context.getPermissionsManager().checkPermission( + permission.getPropertyClass(), getUserId(), permission.getPropertyId()); + } + @POST public Response add(LinkedHashMap entity) throws SQLException, ClassNotFoundException { Context.getPermissionsManager().checkReadonly(getUserId()); - checkAndLinkPermission(entity, true); + Permission permission = new Permission(entity); + checkPermission(permission, true); + Context.getDataManager().linkObject(permission.getOwnerClass(), permission.getOwnerId(), + permission.getPropertyClass(), permission.getPropertyId(), true); Context.getPermissionsManager().refreshPermissions(entity); return Response.noContent().build(); } @@ -46,7 +68,10 @@ public class PermissionsResource extends BaseResource { @DELETE public Response remove(LinkedHashMap entity) throws SQLException, ClassNotFoundException { Context.getPermissionsManager().checkReadonly(getUserId()); - checkAndLinkPermission(entity, false); + Permission permission = new Permission(entity); + checkPermission(permission, false); + Context.getDataManager().linkObject(permission.getOwnerClass(), permission.getOwnerId(), + permission.getPropertyClass(), permission.getPropertyId(), false); Context.getPermissionsManager().refreshPermissions(entity); return Response.noContent().build(); } diff --git a/src/org/traccar/events/GeofenceEventHandler.java b/src/org/traccar/events/GeofenceEventHandler.java index cdac7993f..089d1e0ef 100644 --- a/src/org/traccar/events/GeofenceEventHandler.java +++ b/src/org/traccar/events/GeofenceEventHandler.java @@ -60,9 +60,11 @@ public class GeofenceEventHandler extends BaseEventHandler { Collection events = new ArrayList<>(); for (long geofenceId : newGeofences) { long calendarId = ((Geofence) geofenceManager.getById(geofenceId)).getCalendarId(); - if (calendarId == 0 || Context.getCalendarManager().getById(calendarId) == null - || ((Calendar) Context.getCalendarManager().getById(calendarId)) - .checkMoment(position.getFixTime())) { + Calendar calendar = null; + if (calendarId != 0) { + calendar = (Calendar) Context.getCalendarManager().getById(calendarId); + } + if (calendar == null || calendar.checkMoment(position.getFixTime())) { Event event = new Event(Event.TYPE_GEOFENCE_ENTER, position.getDeviceId(), position.getId()); event.setGeofenceId(geofenceId); events.add(event); @@ -70,9 +72,11 @@ public class GeofenceEventHandler extends BaseEventHandler { } for (long geofenceId : oldGeofences) { long calendarId = ((Geofence) geofenceManager.getById(geofenceId)).getCalendarId(); - if (calendarId == 0 || Context.getCalendarManager().getById(calendarId) == null - || ((Calendar) Context.getCalendarManager().getById(calendarId)) - .checkMoment(position.getFixTime())) { + Calendar calendar = null; + if (calendarId != 0) { + calendar = (Calendar) Context.getCalendarManager().getById(calendarId); + } + if (calendar == null || calendar.checkMoment(position.getFixTime())) { Event event = new Event(Event.TYPE_GEOFENCE_EXIT, position.getDeviceId(), position.getId()); event.setGeofenceId(geofenceId); events.add(event); diff --git a/src/org/traccar/model/Permission.java b/src/org/traccar/model/Permission.java new file mode 100644 index 000000000..1006b1c47 --- /dev/null +++ b/src/org/traccar/model/Permission.java @@ -0,0 +1,57 @@ +/* + * 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.model; + +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.traccar.database.DataManager; + +public class Permission { + + private Class ownerClass; + private long ownerId; + private Class propertyClass; + private long propertyId; + + public Permission(LinkedHashMap permissionMap) throws ClassNotFoundException { + Iterator> iterator = permissionMap.entrySet().iterator(); + String owner = iterator.next().getKey(); + ownerClass = DataManager.getClassByName(owner); + String property = iterator.next().getKey(); + propertyClass = DataManager.getClassByName(property); + ownerId = permissionMap.get(owner); + propertyId = permissionMap.get(property); + } + + public Class getOwnerClass() { + return ownerClass; + } + + public long getOwnerId() { + return ownerId; + } + + public Class getPropertyClass() { + return propertyClass; + } + + public long getPropertyId() { + return propertyId; + } +} -- cgit v1.2.3 From f92b5cd97a5d2159a890fb4817238f4c1bbb2a12 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Sun, 23 Jul 2017 08:19:48 +0500 Subject: Remove proxy function --- src/org/traccar/api/BaseResource.java | 9 --------- src/org/traccar/api/resource/AttributeResource.java | 3 ++- src/org/traccar/api/resource/CalendarResource.java | 3 ++- src/org/traccar/api/resource/DeviceResource.java | 3 ++- src/org/traccar/api/resource/DriverResource.java | 3 ++- src/org/traccar/api/resource/GeofenceResource.java | 3 ++- src/org/traccar/api/resource/GroupResource.java | 3 ++- 7 files changed, 12 insertions(+), 15 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/BaseResource.java b/src/org/traccar/api/BaseResource.java index 502591efe..4e1db7831 100644 --- a/src/org/traccar/api/BaseResource.java +++ b/src/org/traccar/api/BaseResource.java @@ -15,13 +15,8 @@ */ package org.traccar.api; -import java.sql.SQLException; - import javax.ws.rs.core.SecurityContext; -import org.traccar.Context; -import org.traccar.model.BaseModel; -import org.traccar.model.User; public class BaseResource { @@ -35,8 +30,4 @@ public class BaseResource { } return 0; } - - protected void linkNewEntity(BaseModel entity) throws SQLException { - Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); - } } diff --git a/src/org/traccar/api/resource/AttributeResource.java b/src/org/traccar/api/resource/AttributeResource.java index 7e6947d26..7b81d3ffb 100644 --- a/src/org/traccar/api/resource/AttributeResource.java +++ b/src/org/traccar/api/resource/AttributeResource.java @@ -38,6 +38,7 @@ import org.traccar.api.BaseResource; import org.traccar.database.AttributesManager; import org.traccar.model.Attribute; import org.traccar.model.Position; +import org.traccar.model.User; import org.traccar.processing.ComputedAttributesHandler; @Path("attributes/computed") @@ -87,7 +88,7 @@ public class AttributeResource extends BaseResource { private Response add(Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getAttributesManager().addItem(entity); - linkNewEntity(entity); + Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); Context.getAttributesManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/CalendarResource.java b/src/org/traccar/api/resource/CalendarResource.java index 30f5df6b8..a0f8656af 100644 --- a/src/org/traccar/api/resource/CalendarResource.java +++ b/src/org/traccar/api/resource/CalendarResource.java @@ -35,6 +35,7 @@ import org.traccar.Context; import org.traccar.api.BaseResource; import org.traccar.database.CalendarManager; import org.traccar.model.Calendar; +import org.traccar.model.User; @Path("calendars") @Produces(MediaType.APPLICATION_JSON) @@ -66,7 +67,7 @@ public class CalendarResource extends BaseResource { public Response add(Calendar entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getCalendarManager().addItem(entity); - linkNewEntity(entity); + Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); Context.getCalendarManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index 0d6e4f09c..a6b3ef964 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -19,6 +19,7 @@ import org.traccar.Context; import org.traccar.api.BaseResource; import org.traccar.model.Device; import org.traccar.model.DeviceTotalDistance; +import org.traccar.model.User; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -77,7 +78,7 @@ public class DeviceResource extends BaseResource { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); Context.getPermissionsManager().checkDeviceLimit(getUserId()); Context.getDeviceManager().addDevice(entity); - linkNewEntity(entity); + Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); Context.getPermissionsManager().refreshPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index cf80bf7df..72eadb711 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -37,6 +37,7 @@ import org.traccar.Context; import org.traccar.api.BaseResource; import org.traccar.database.DriversManager; import org.traccar.model.Driver; +import org.traccar.model.User; @Path("drivers") @Produces(MediaType.APPLICATION_JSON) @@ -86,7 +87,7 @@ public class DriverResource extends BaseResource { public Response add(Driver entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDriversManager().addItem(entity); - linkNewEntity(entity); + Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); Context.getDriversManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/GeofenceResource.java b/src/org/traccar/api/resource/GeofenceResource.java index 341180cf8..47f889e9c 100644 --- a/src/org/traccar/api/resource/GeofenceResource.java +++ b/src/org/traccar/api/resource/GeofenceResource.java @@ -19,6 +19,7 @@ import org.traccar.Context; import org.traccar.api.BaseResource; import org.traccar.database.GeofenceManager; import org.traccar.model.Geofence; +import org.traccar.model.User; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -85,7 +86,7 @@ public class GeofenceResource extends BaseResource { public Response add(Geofence entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getGeofenceManager().addItem(entity); - linkNewEntity(entity); + Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); Context.getGeofenceManager().refreshUserItems(); return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index 402e687e6..f20c95327 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -18,6 +18,7 @@ package org.traccar.api.resource; import org.traccar.Context; import org.traccar.api.BaseResource; import org.traccar.model.Group; +import org.traccar.model.User; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -61,7 +62,7 @@ public class GroupResource extends BaseResource { public Response add(Group entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getDeviceManager().addGroup(entity); - linkNewEntity(entity); + Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); Context.getPermissionsManager().refreshPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); -- cgit v1.2.3 From d2a2ce5d05572caadf13627d3e6c3767ad68688f Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Sun, 23 Jul 2017 08:32:55 +0500 Subject: Use Permission object instead of Map --- .../traccar/api/resource/PermissionsResource.java | 4 +-- .../traccar/database/ExtendedObjectManager.java | 3 +-- src/org/traccar/database/PermissionsManager.java | 29 +++++++++++----------- 3 files changed, 18 insertions(+), 18 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/PermissionsResource.java b/src/org/traccar/api/resource/PermissionsResource.java index 88fd9d092..9b9f65ad1 100644 --- a/src/org/traccar/api/resource/PermissionsResource.java +++ b/src/org/traccar/api/resource/PermissionsResource.java @@ -61,7 +61,7 @@ public class PermissionsResource extends BaseResource { checkPermission(permission, true); Context.getDataManager().linkObject(permission.getOwnerClass(), permission.getOwnerId(), permission.getPropertyClass(), permission.getPropertyId(), true); - Context.getPermissionsManager().refreshPermissions(entity); + Context.getPermissionsManager().refreshPermissions(permission); return Response.noContent().build(); } @@ -72,7 +72,7 @@ public class PermissionsResource extends BaseResource { checkPermission(permission, false); Context.getDataManager().linkObject(permission.getOwnerClass(), permission.getOwnerId(), permission.getPropertyClass(), permission.getPropertyId(), false); - Context.getPermissionsManager().refreshPermissions(entity); + Context.getPermissionsManager().refreshPermissions(permission); return Response.noContent().build(); } diff --git a/src/org/traccar/database/ExtendedObjectManager.java b/src/org/traccar/database/ExtendedObjectManager.java index 8380b9da2..483c3a09e 100644 --- a/src/org/traccar/database/ExtendedObjectManager.java +++ b/src/org/traccar/database/ExtendedObjectManager.java @@ -35,8 +35,7 @@ public abstract class ExtendedObjectManager extends SimpleObjectManager { private final Map> deviceItemsWithGroups = new ConcurrentHashMap<>(); private final Map> groupItems = new ConcurrentHashMap<>(); - protected ExtendedObjectManager(DataManager dataManager, - Class baseClass) { + protected ExtendedObjectManager(DataManager dataManager, Class baseClass) { super(dataManager, baseClass); } diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 4008134ec..8aa0dc9d7 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -24,6 +24,7 @@ import org.traccar.model.Driver; import org.traccar.model.Geofence; import org.traccar.model.Group; import org.traccar.model.ManagedUser; +import org.traccar.model.Permission; import org.traccar.model.Server; import org.traccar.model.User; @@ -348,34 +349,34 @@ public class PermissionsManager { Context.getAttributesManager().refreshExtendedPermissions(); } - public void refreshPermissions(Map entity) { - if (entity.containsKey(DataManager.makeNameId(User.class))) { - if (entity.containsKey(DataManager.makeNameId(Device.class)) - || entity.containsKey(DataManager.makeNameId(Group.class))) { + public void refreshPermissions(Permission permission) { + if (permission.getOwnerClass().equals(User.class)) { + if (permission.getPropertyClass().equals(Device.class) + || permission.getPropertyClass().equals(Group.class)) { refreshPermissions(); refreshAllExtendedPermissions(); - } else if (entity.containsKey(DataManager.makeNameId(ManagedUser.class))) { + } else if (permission.getPropertyClass().equals(ManagedUser.class)) { refreshUserPermissions(); - } else if (entity.containsKey(DataManager.makeNameId(Geofence.class))) { + } else if (permission.getPropertyClass().equals(Geofence.class)) { if (Context.getGeofenceManager() != null) { Context.getGeofenceManager().refreshUserItems(); } - } else if (entity.containsKey(DataManager.makeNameId(Driver.class))) { + } else if (permission.getPropertyClass().equals(Driver.class)) { Context.getDriversManager().refreshUserItems(); - } else if (entity.containsKey(DataManager.makeNameId(Attribute.class))) { + } else if (permission.getPropertyClass().equals(Attribute.class)) { Context.getAttributesManager().refreshUserItems(); - } else if (entity.containsKey(DataManager.makeNameId(Calendar.class))) { + } else if (permission.getPropertyClass().equals(Calendar.class)) { Context.getCalendarManager().refreshUserItems(); } - } else if (entity.containsKey(DataManager.makeNameId(Device.class)) - || entity.containsKey(DataManager.makeNameId(Group.class))) { - if (entity.containsKey(DataManager.makeNameId(Geofence.class))) { + } else if (permission.getOwnerClass().equals(Device.class) + || permission.getOwnerClass().equals(Group.class)) { + if (permission.getPropertyClass().equals(Geofence.class)) { if (Context.getGeofenceManager() != null) { Context.getGeofenceManager().refreshExtendedPermissions(); } - } else if (entity.containsKey(DataManager.makeNameId(Driver.class))) { + } else if (permission.getPropertyClass().equals(Driver.class)) { Context.getDriversManager().refreshExtendedPermissions(); - } else if (entity.containsKey(DataManager.makeNameId(Attribute.class))) { + } else if (permission.getPropertyClass().equals(Attribute.class)) { Context.getAttributesManager().refreshExtendedPermissions(); } } -- cgit v1.2.3 From 5a65c0d6be8ffc2db0ffdb0c35ecedfb2b3750c7 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Sun, 23 Jul 2017 09:15:38 +0500 Subject: Remove line --- src/org/traccar/api/BaseResource.java | 1 - 1 file changed, 1 deletion(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/BaseResource.java b/src/org/traccar/api/BaseResource.java index 4e1db7831..cc272df9c 100644 --- a/src/org/traccar/api/BaseResource.java +++ b/src/org/traccar/api/BaseResource.java @@ -17,7 +17,6 @@ package org.traccar.api; import javax.ws.rs.core.SecurityContext; - public class BaseResource { @javax.ws.rs.core.Context -- cgit v1.2.3 From 68af658ea2ff9593e5be7a2b2cfcb75c744fd749 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 25 Jul 2017 10:53:08 +0500 Subject: Move users management to separate manager --- src/org/traccar/Context.java | 13 +- src/org/traccar/api/resource/SessionResource.java | 2 +- src/org/traccar/api/resource/UserResource.java | 20 ++- src/org/traccar/database/DeviceManager.java | 4 +- src/org/traccar/database/PermissionsManager.java | 149 ++++++---------------- src/org/traccar/database/SimpleObjectManager.java | 4 +- src/org/traccar/database/UsersManager.java | 83 ++++++++++++ 7 files changed, 149 insertions(+), 126 deletions(-) create mode 100644 src/org/traccar/database/UsersManager.java (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index a4fc5b679..47472b1d4 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -38,6 +38,7 @@ import org.traccar.database.NotificationManager; import org.traccar.database.PermissionsManager; import org.traccar.database.GeofenceManager; import org.traccar.database.StatisticsManager; +import org.traccar.database.UsersManager; import org.traccar.geocoder.BingMapsGeocoder; import org.traccar.geocoder.FactualGeocoder; import org.traccar.geocoder.GeocodeFarmGeocoder; @@ -98,6 +99,12 @@ public final class Context { return mediaManager; } + private static UsersManager usersManager; + + public static UsersManager getUsersManager() { + return usersManager; + } + private static DeviceManager deviceManager; public static DeviceManager getDeviceManager() { @@ -232,6 +239,10 @@ public final class Context { mediaManager = new MediaManager(config); } + if (dataManager != null) { + usersManager = new UsersManager(dataManager); + } + if (dataManager != null) { deviceManager = new DeviceManager(dataManager); } @@ -298,7 +309,7 @@ public final class Context { webServer = new WebServer(config, dataManager.getDataSource()); } - permissionsManager = new PermissionsManager(dataManager); + permissionsManager = new PermissionsManager(dataManager, usersManager); connectionManager = new ConnectionManager(); diff --git a/src/org/traccar/api/resource/SessionResource.java b/src/org/traccar/api/resource/SessionResource.java index acdbb7c87..fa2a14c6f 100644 --- a/src/org/traccar/api/resource/SessionResource.java +++ b/src/org/traccar/api/resource/SessionResource.java @@ -80,7 +80,7 @@ public class SessionResource extends BaseResource { request.getSession().setAttribute(USER_ID_KEY, userId); } } else if (token != null) { - User user = Context.getPermissionsManager().getUserByToken(token); + User user = Context.getUsersManager().getUserByToken(token); if (user != null) { userId = user.getId(); request.getSession().setAttribute(USER_ID_KEY, userId); diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index 98395e3cc..d3d82f99d 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -17,6 +17,7 @@ package org.traccar.api.resource; import org.traccar.Context; import org.traccar.api.BaseResource; +import org.traccar.database.UsersManager; import org.traccar.model.ManagedUser; import org.traccar.model.User; @@ -35,6 +36,7 @@ import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.Collection; import java.util.Date; +import java.util.Set; @Path("users") @Produces(MediaType.APPLICATION_JSON) @@ -43,17 +45,21 @@ public class UserResource extends BaseResource { @GET public Collection get(@QueryParam("userId") long userId) throws SQLException { + UsersManager usersManager = Context.getUsersManager(); + Set result = null; if (Context.getPermissionsManager().isAdmin(getUserId())) { if (userId != 0) { - return Context.getPermissionsManager().getUsers(userId); + result = usersManager.getManagedItems(userId); } else { - return Context.getPermissionsManager().getAllUsers(); + result = usersManager.getAllItems(); } } else if (Context.getPermissionsManager().isManager(getUserId())) { - return Context.getPermissionsManager().getManagedUsers(getUserId()); + result = usersManager.getManagedItems(getUserId()); + result.add(getUserId()); } else { throw new SecurityException("Admin or manager access required"); } + return usersManager.getItems(User.class, result); } @PermitAll @@ -73,11 +79,11 @@ public class UserResource extends BaseResource { } } } - Context.getPermissionsManager().addUser(entity); + Context.getUsersManager().addItem(entity); if (Context.getPermissionsManager().isManager(getUserId())) { Context.getDataManager().linkObject(User.class, getUserId(), ManagedUser.class, entity.getId(), true); } - Context.getPermissionsManager().refreshUserPermissions(); + Context.getUsersManager().refreshUserItems(); if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } @@ -91,7 +97,7 @@ public class UserResource extends BaseResource { User before = Context.getPermissionsManager().getUser(entity.getId()); Context.getPermissionsManager().checkUser(getUserId(), entity.getId()); Context.getPermissionsManager().checkUserUpdate(getUserId(), before, entity); - Context.getPermissionsManager().updateUser(entity); + Context.getUsersManager().updateItem(entity); if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } @@ -103,7 +109,7 @@ public class UserResource extends BaseResource { public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), id); - Context.getPermissionsManager().removeUser(id); + Context.getUsersManager().removeItem(id); if (Context.getGeofenceManager() != null) { Context.getGeofenceManager().refreshUserItems(); } diff --git a/src/org/traccar/database/DeviceManager.java b/src/org/traccar/database/DeviceManager.java index 6637df91c..995aa8ac3 100644 --- a/src/org/traccar/database/DeviceManager.java +++ b/src/org/traccar/database/DeviceManager.java @@ -192,7 +192,7 @@ public class DeviceManager implements IdentityManager { public Collection getManagedDevices(long userId) throws SQLException { Collection devices = new HashSet<>(); devices.addAll(getDevices(userId)); - for (long managedUserId : Context.getPermissionsManager().getUserPermissions(userId)) { + for (long managedUserId : Context.getUsersManager().getManagedItems(userId)) { devices.addAll(getDevices(managedUserId)); } return devices; @@ -340,7 +340,7 @@ public class DeviceManager implements IdentityManager { public Collection getManagedGroups(long userId) throws SQLException { Collection groups = new ArrayList<>(); groups.addAll(getGroups(userId)); - for (long managedUserId : Context.getPermissionsManager().getUserPermissions(userId)) { + for (long managedUserId : Context.getUsersManager().getManagedItems(userId)) { groups.addAll(getGroups(managedUserId)); } return groups; diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 70969d749..b38ecf9bf 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -30,29 +30,33 @@ import org.traccar.model.User; import java.lang.reflect.Method; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; public class PermissionsManager { private final DataManager dataManager; + private final UsersManager usersManager; private volatile Server server; - private final Map users = new ConcurrentHashMap<>(); - private final Map usersTokens = new HashMap<>(); - private final Map> groupPermissions = new HashMap<>(); private final Map> devicePermissions = new HashMap<>(); private final Map> deviceUsers = new HashMap<>(); private final Map> groupDevices = new HashMap<>(); - private final Map> userPermissions = new HashMap<>(); + public PermissionsManager(DataManager dataManager, UsersManager usersManager) { + this.dataManager = dataManager; + this.usersManager = usersManager; + refreshServer(); + refreshPermissions(); + } + + public User getUser(long userId) { + return (User) usersManager.getById(userId); + } public Set getGroupPermissions(long userId) { if (!groupPermissions.containsKey(userId)) { @@ -82,47 +86,14 @@ public class PermissionsManager { return groupDevices.get(groupId); } - public Set getUserPermissions(long userId) { - if (!userPermissions.containsKey(userId)) { - userPermissions.put(userId, new HashSet()); - } - return userPermissions.get(userId); - } - - public PermissionsManager(DataManager dataManager) { - this.dataManager = dataManager; - refreshUsers(); - refreshPermissions(); - refreshUserPermissions(); - } - - public final void refreshUsers() { - users.clear(); - usersTokens.clear(); + public void refreshServer() { try { server = dataManager.getServer(); - for (User user : dataManager.getObjects(User.class)) { - users.put(user.getId(), user); - if (user.getToken() != null) { - usersTokens.put(user.getToken(), user.getId()); - } - } } catch (SQLException error) { Log.warning(error); } } - public final void refreshUserPermissions() { - userPermissions.clear(); - try { - for (Permission permission : dataManager.getPermissions(User.class, User.class)) { - getUserPermissions(permission.getOwnerId()).add(permission.getPropertyId()); - } - } catch (SQLException | ClassNotFoundException error) { - Log.warning(error); - } - } - public final void refreshPermissions() { groupPermissions.clear(); devicePermissions.clear(); @@ -165,7 +136,8 @@ public class PermissionsManager { } public boolean isAdmin(long userId) { - return users.containsKey(userId) && users.get(userId).getAdmin(); + User user = getUser(userId); + return user != null && user.getAdmin(); } public void checkAdmin(long userId) throws SecurityException { @@ -175,7 +147,8 @@ public class PermissionsManager { } public boolean isManager(long userId) { - return users.containsKey(userId) && users.get(userId).getUserLimit() != 0; + User user = getUser(userId); + return user != null && user.getUserLimit() != 0; } public void checkManager(long userId) throws SecurityException { @@ -186,20 +159,20 @@ public class PermissionsManager { public void checkManager(long userId, long managedUserId) throws SecurityException { checkManager(userId); - if (!getUserPermissions(userId).contains(managedUserId)) { + if (!usersManager.getManagedItems(userId).contains(managedUserId)) { throw new SecurityException("User access denied"); } } public void checkUserLimit(long userId) throws SecurityException { - int userLimit = users.get(userId).getUserLimit(); - if (userLimit != -1 && getUserPermissions(userId).size() >= userLimit) { + int userLimit = getUser(userId).getUserLimit(); + if (userLimit != -1 && usersManager.getManagedItems(userId).size() >= userLimit) { throw new SecurityException("Manager user limit reached"); } } public void checkDeviceLimit(long userId) throws SecurityException, SQLException { - int deviceLimit = users.get(userId).getDeviceLimit(); + int deviceLimit = getUser(userId).getDeviceLimit(); if (deviceLimit != -1) { int deviceCount = 0; if (isManager(userId)) { @@ -214,11 +187,13 @@ public class PermissionsManager { } public boolean isReadonly(long userId) { - return users.containsKey(userId) && users.get(userId).getReadonly(); + User user = getUser(userId); + return user != null && user.getReadonly(); } public boolean isDeviceReadonly(long userId) { - return users.containsKey(userId) && users.get(userId).getDeviceReadonly(); + User user = getUser(userId); + return user != null && user.getDeviceReadonly(); } public void checkReadonly(long userId) throws SecurityException { @@ -235,6 +210,9 @@ public class PermissionsManager { public void checkUserEnabled(long userId) throws SecurityException { User user = getUser(userId); + if (user == null) { + throw new SecurityException("Unknown account"); + } if (user.getDisabled()) { throw new SecurityException("Account is disabled"); } @@ -249,9 +227,10 @@ public class PermissionsManager { || before.getUserLimit() != after.getUserLimit()) { checkAdmin(userId); } - if (users.containsKey(userId) && users.get(userId).getExpirationTime() != null + User user = getUser(userId); + if (user != null && user.getExpirationTime() != null && (after.getExpirationTime() == null - || users.get(userId).getExpirationTime().compareTo(after.getExpirationTime()) < 0)) { + || user.getExpirationTime().compareTo(after.getExpirationTime()) < 0)) { checkAdmin(userId); } if (before.getReadonly() != after.getReadonly() @@ -275,7 +254,7 @@ public class PermissionsManager { public void checkGroup(long userId, long groupId) throws SecurityException { if (!getGroupPermissions(userId).contains(groupId) && !isAdmin(userId)) { checkManager(userId); - for (long managedUserId : getUserPermissions(userId)) { + for (long managedUserId : usersManager.getManagedItems(userId)) { if (getGroupPermissions(managedUserId).contains(groupId)) { return; } @@ -287,7 +266,7 @@ public class PermissionsManager { public void checkDevice(long userId, long deviceId) throws SecurityException { if (!getDevicePermissions(userId).contains(deviceId) && !isAdmin(userId)) { checkManager(userId); - for (long managedUserId : getUserPermissions(userId)) { + for (long managedUserId : usersManager.getManagedItems(userId)) { if (getDevicePermissions(managedUserId).contains(deviceId)) { return; } @@ -326,7 +305,7 @@ public class PermissionsManager { if (manager != null && !manager.checkItemPermission(userId, objectId) && !isAdmin(userId)) { checkManager(userId); - for (long managedUserId : getUserPermissions(userId)) { + for (long managedUserId : usersManager.getManagedItems(userId)) { if (manager.checkItemPermission(managedUserId, objectId)) { return; } @@ -350,7 +329,7 @@ public class PermissionsManager { refreshPermissions(); refreshAllExtendedPermissions(); } else if (permission.getPropertyClass().equals(ManagedUser.class)) { - refreshUserPermissions(); + usersManager.refreshUserItems(); } else if (permission.getPropertyClass().equals(Geofence.class) && Context.getGeofenceManager() != null) { Context.getGeofenceManager().refreshUserItems(); } else if (permission.getPropertyClass().equals(Driver.class)) { @@ -380,71 +359,15 @@ public class PermissionsManager { this.server = server; } - public Collection getAllUsers() { - return users.values(); - } - - public Collection getUsers(long userId) { - Collection result = new ArrayList<>(); - for (long managedUserId : getUserPermissions(userId)) { - result.add(users.get(managedUserId)); - } - return result; - } - - public Collection getManagedUsers(long userId) { - Collection result = getUsers(userId); - result.add(users.get(userId)); - return result; - } - - public User getUser(long userId) { - return users.get(userId); - } - - public void addUser(User user) throws SQLException { - dataManager.addObject(user); - users.put(user.getId(), user); - if (user.getToken() != null) { - usersTokens.put(user.getToken(), user.getId()); - } - refreshPermissions(); - } - - public void updateUser(User user) throws SQLException { - dataManager.updateUser(user); - User old = users.get(user.getId()); - users.put(user.getId(), user); - if (user.getToken() != null) { - usersTokens.put(user.getToken(), user.getId()); - } - if (old.getToken() != null && !old.getToken().equals(user.getToken())) { - usersTokens.remove(old.getToken()); - } - refreshPermissions(); - } - - public void removeUser(long userId) throws SQLException { - dataManager.removeObject(User.class, userId); - usersTokens.remove(users.get(userId).getToken()); - users.remove(userId); - refreshPermissions(); - refreshUserPermissions(); - } - public User login(String email, String password) throws SQLException { User user = dataManager.login(email, password); if (user != null) { checkUserEnabled(user.getId()); - return users.get(user.getId()); + return getUser(user.getId()); } return null; } - public User getUserByToken(String token) { - return users.get(usersTokens.get(token)); - } - public Object lookupPreference(long userId, String key, Object defaultValue) { String methodName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1); Object preference; @@ -454,7 +377,7 @@ public class PermissionsManager { Method method = null; method = User.class.getMethod(methodName, (Class[]) null); if (method != null) { - userPreference = method.invoke(users.get(userId), (Object[]) null); + userPreference = method.invoke(getUser(userId), (Object[]) null); } method = null; method = Server.class.getMethod(methodName, (Class[]) null); diff --git a/src/org/traccar/database/SimpleObjectManager.java b/src/org/traccar/database/SimpleObjectManager.java index 282dea46e..124178a05 100644 --- a/src/org/traccar/database/SimpleObjectManager.java +++ b/src/org/traccar/database/SimpleObjectManager.java @@ -166,10 +166,10 @@ public abstract class SimpleObjectManager { return items.keySet(); } - public final Set getManagedItems(long userId) { + public Set getManagedItems(long userId) { Set result = new HashSet<>(); result.addAll(getUserItems(userId)); - for (long managedUserId : Context.getPermissionsManager().getUserPermissions(userId)) { + for (long managedUserId : Context.getUsersManager().getManagedItems(userId)) { result.addAll(getUserItems(managedUserId)); } return result; diff --git a/src/org/traccar/database/UsersManager.java b/src/org/traccar/database/UsersManager.java new file mode 100644 index 000000000..3c9c8b280 --- /dev/null +++ b/src/org/traccar/database/UsersManager.java @@ -0,0 +1,83 @@ +/* + * 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.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.traccar.model.BaseModel; +import org.traccar.model.User; + +public class UsersManager extends SimpleObjectManager { + + private Map usersTokens; + + public UsersManager(DataManager dataManager) { + super(dataManager, User.class); + } + + private void putToken(User user) { + if (usersTokens == null) { + usersTokens = new ConcurrentHashMap<>(); + } + if (user.getToken() != null) { + usersTokens.put(user.getToken(), user.getId()); + } + } + + @Override + protected void addNewItem(BaseModel item) { + super.addNewItem(item); + putToken((User) item); + } + + @Override + protected void updateCachedItem(BaseModel item) { + User user = (User) item; + User cachedUser = (User) getById(item.getId()); + super.updateCachedItem(item); + if (user.getToken() != null) { + usersTokens.put(user.getToken(), user.getId()); + } + if (cachedUser.getToken() != null && !cachedUser.getToken().equals(user.getToken())) { + usersTokens.remove(cachedUser.getToken()); + } + } + + @Override + protected void removeCachedItem(long userId) { + User cachedUser = (User) getById(userId); + if (cachedUser != null) { + String userToken = cachedUser.getToken(); + super.removeCachedItem(userId); + if (userToken != null) { + usersTokens.remove(userToken); + } + } + } + + @Override + public Set getManagedItems(long userId) { + return getUserItems(userId); + } + + public User getUserByToken(String token) { + return (User) getById(usersTokens.get(token)); + } + +} -- cgit v1.2.3 From bbcca3d65106069018e93a69b85290c075b128db Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 25 Jul 2017 17:33:00 +0500 Subject: Split Drivers and Groups management --- src/org/traccar/BaseProtocolDecoder.java | 2 +- src/org/traccar/Context.java | 11 +- src/org/traccar/api/resource/DeviceResource.java | 52 ++-- src/org/traccar/api/resource/GroupResource.java | 22 +- src/org/traccar/api/resource/UserResource.java | 11 +- src/org/traccar/database/BaseObjectManager.java | 124 ++++++++ src/org/traccar/database/DeviceManager.java | 342 +++++++-------------- .../traccar/database/ExtendedObjectManager.java | 20 +- src/org/traccar/database/GroupsManager.java | 104 +++++++ src/org/traccar/database/ManagableObjects.java | 27 ++ src/org/traccar/database/PermissionsManager.java | 43 ++- src/org/traccar/database/SimpleObjectManager.java | 134 ++------ src/org/traccar/database/UsersManager.java | 6 +- src/org/traccar/reports/Events.java | 2 +- src/org/traccar/reports/Route.java | 2 +- src/org/traccar/reports/Stops.java | 2 +- src/org/traccar/reports/Trips.java | 2 +- 17 files changed, 488 insertions(+), 418 deletions(-) create mode 100644 src/org/traccar/database/BaseObjectManager.java create mode 100644 src/org/traccar/database/GroupsManager.java create mode 100644 src/org/traccar/database/ManagableObjects.java (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/BaseProtocolDecoder.java b/src/org/traccar/BaseProtocolDecoder.java index 436ef9b02..1aff4564f 100644 --- a/src/org/traccar/BaseProtocolDecoder.java +++ b/src/org/traccar/BaseProtocolDecoder.java @@ -46,7 +46,7 @@ public abstract class BaseProtocolDecoder extends ExtendedObjectDecoder { } try { - Context.getDeviceManager().addDevice(device); + Context.getDeviceManager().addItem(device); Log.info("Automatically registered device " + uniqueId); diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 47472b1d4..dfb8c5f47 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -37,6 +37,7 @@ import org.traccar.database.MediaManager; import org.traccar.database.NotificationManager; import org.traccar.database.PermissionsManager; import org.traccar.database.GeofenceManager; +import org.traccar.database.GroupsManager; import org.traccar.database.StatisticsManager; import org.traccar.database.UsersManager; import org.traccar.geocoder.BingMapsGeocoder; @@ -105,6 +106,12 @@ public final class Context { return usersManager; } + private static GroupsManager groupsManager; + + public static GroupsManager getGroupsManager() { + return groupsManager; + } + private static DeviceManager deviceManager; public static DeviceManager getDeviceManager() { @@ -241,9 +248,7 @@ public final class Context { if (dataManager != null) { usersManager = new UsersManager(dataManager); - } - - if (dataManager != null) { + groupsManager = new GroupsManager(dataManager); deviceManager = new DeviceManager(dataManager); } diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index 6cf7a6219..c621d4304 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -17,6 +17,7 @@ package org.traccar.api.resource; import org.traccar.Context; import org.traccar.api.BaseResource; +import org.traccar.database.DeviceManager; import org.traccar.model.Device; import org.traccar.model.DeviceTotalDistance; import org.traccar.model.User; @@ -34,9 +35,10 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.sql.SQLException; -import java.util.ArrayList; import java.util.Collection; +import java.util.HashSet; import java.util.List; +import java.util.Set; @Path("devices") @Produces(MediaType.APPLICATION_JSON) @@ -48,34 +50,34 @@ public class DeviceResource extends BaseResource { @QueryParam("all") boolean all, @QueryParam("userId") long userId, @QueryParam("uniqueId") List uniqueIds, @QueryParam("id") List deviceIds) throws SQLException { + DeviceManager deviceManager = Context.getDeviceManager(); + Set result = null; if (all) { if (Context.getPermissionsManager().isAdmin(getUserId())) { - return Context.getDeviceManager().getAllDevices(); + result = deviceManager.getAllItems(); } else { Context.getPermissionsManager().checkManager(getUserId()); - return Context.getDeviceManager().getManagedDevices(getUserId()); + result = deviceManager.getManagedItems(getUserId()); } - } - if (uniqueIds.isEmpty() && deviceIds.isEmpty()) { + } else if (uniqueIds.isEmpty() && deviceIds.isEmpty()) { if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); - return Context.getDeviceManager().getDevices(userId); - } - - ArrayList devices = new ArrayList<>(); - - for (String uniqueId : uniqueIds) { - Device device = Context.getDeviceManager().getDeviceByUniqueId(uniqueId); - Context.getPermissionsManager().checkDevice(getUserId(), device.getId()); - devices.add(device); - } - for (Long deviceId : deviceIds) { - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - devices.add(Context.getDeviceManager().getDeviceById(deviceId)); + result = deviceManager.getUserItems(userId); + } else { + result = new HashSet(); + for (String uniqueId : uniqueIds) { + Device device = deviceManager.getDeviceByUniqueId(uniqueId); + Context.getPermissionsManager().checkDevice(getUserId(), device.getId()); + result.add(device.getId()); + } + for (Long deviceId : deviceIds) { + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + result.add(deviceId); + } } - return devices; + return deviceManager.getItems(Device.class, result); } @POST @@ -83,9 +85,9 @@ public class DeviceResource extends BaseResource { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDeviceReadonly(getUserId()); Context.getPermissionsManager().checkDeviceLimit(getUserId()); - Context.getDeviceManager().addDevice(entity); + Context.getDeviceManager().addItem(entity); Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); - Context.getPermissionsManager().refreshPermissions(); + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); } @@ -96,8 +98,8 @@ public class DeviceResource extends BaseResource { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDeviceReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), entity.getId()); - Context.getDeviceManager().updateDevice(entity); - Context.getPermissionsManager().refreshPermissions(); + Context.getDeviceManager().updateItem(entity); + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); } @@ -108,8 +110,8 @@ public class DeviceResource extends BaseResource { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkDeviceReadonly(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), id); - Context.getDeviceManager().removeDevice(id); - Context.getPermissionsManager().refreshPermissions(); + Context.getDeviceManager().removeItem(id); + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); Context.getAliasesManager().removeDevice(id); return Response.noContent().build(); diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index f20c95327..f832660b2 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -17,6 +17,7 @@ package org.traccar.api.resource; import org.traccar.Context; import org.traccar.api.BaseResource; +import org.traccar.database.GroupsManager; import org.traccar.model.Group; import org.traccar.model.User; @@ -33,6 +34,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.sql.SQLException; import java.util.Collection; +import java.util.Set; @Path("groups") @Produces(MediaType.APPLICATION_JSON) @@ -42,28 +44,31 @@ public class GroupResource extends BaseResource { @GET public Collection get( @QueryParam("all") boolean all, @QueryParam("userId") long userId) throws SQLException { + GroupsManager groupsManager = Context.getGroupsManager(); + Set result = null; if (all) { if (Context.getPermissionsManager().isAdmin(getUserId())) { - return Context.getDeviceManager().getAllGroups(); + result = groupsManager.getAllItems(); } else { Context.getPermissionsManager().checkManager(getUserId()); - return Context.getDeviceManager().getManagedGroups(getUserId()); + result = groupsManager.getManagedItems(getUserId()); } } else { if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); - return Context.getDeviceManager().getGroups(userId); + result = groupsManager.getUserItems(userId); } + return groupsManager.getItems(Group.class, result); } @POST public Response add(Group entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getDeviceManager().addGroup(entity); + Context.getGroupsManager().addItem(entity); Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); - Context.getPermissionsManager().refreshPermissions(); + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); } @@ -73,7 +78,8 @@ public class GroupResource extends BaseResource { public Response update(Group entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), entity.getId()); - Context.getDeviceManager().updateGroup(entity); + Context.getGroupsManager().updateItem(entity); + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.ok(entity).build(); } @@ -83,8 +89,8 @@ public class GroupResource extends BaseResource { public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkGroup(getUserId(), id); - Context.getDeviceManager().removeGroup(id); - Context.getPermissionsManager().refreshPermissions(); + Context.getGroupsManager().removeItem(id); + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index d3d82f99d..9998ed346 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -49,13 +49,12 @@ public class UserResource extends BaseResource { Set result = null; if (Context.getPermissionsManager().isAdmin(getUserId())) { if (userId != 0) { - result = usersManager.getManagedItems(userId); + result = usersManager.getUserItems(userId); } else { result = usersManager.getAllItems(); } } else if (Context.getPermissionsManager().isManager(getUserId())) { result = usersManager.getManagedItems(getUserId()); - result.add(getUserId()); } else { throw new SecurityException("Admin or manager access required"); } @@ -110,12 +109,8 @@ public class UserResource extends BaseResource { Context.getPermissionsManager().checkReadonly(getUserId()); Context.getPermissionsManager().checkUser(getUserId(), id); Context.getUsersManager().removeItem(id); - if (Context.getGeofenceManager() != null) { - Context.getGeofenceManager().refreshUserItems(); - } - if (Context.getNotificationManager() != null) { - Context.getNotificationManager().refresh(); - } + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); + Context.getPermissionsManager().refreshAllUsersPermissions(); return Response.noContent().build(); } diff --git a/src/org/traccar/database/BaseObjectManager.java b/src/org/traccar/database/BaseObjectManager.java new file mode 100644 index 000000000..d515fc2a9 --- /dev/null +++ b/src/org/traccar/database/BaseObjectManager.java @@ -0,0 +1,124 @@ +/* + * 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.helper.Log; +import org.traccar.model.BaseModel; + +public class BaseObjectManager { + + private final DataManager dataManager; + + private Map items; + private Class baseClass; + + protected BaseObjectManager(DataManager dataManager, Class baseClass) { + this.dataManager = dataManager; + this.baseClass = baseClass; + refreshItems(); + } + + protected final DataManager getDataManager() { + return dataManager; + } + + protected final Class getBaseClass() { + return baseClass; + } + + public final BaseModel getById(long itemId) { + return items.get(itemId); + } + + public void refreshItems() { + if (dataManager != null) { + try { + Collection databaseItems = dataManager.getObjects(baseClass); + if (items == null) { + items = new ConcurrentHashMap<>(databaseItems.size()); + } + Set databaseItemIds = new HashSet<>(); + for (BaseModel item : databaseItems) { + databaseItemIds.add(item.getId()); + if (items.containsKey(item.getId())) { + updateCachedItem(item); + } else { + addNewItem(item); + } + } + for (Long cachedItemId : items.keySet()) { + if (!databaseItemIds.contains(cachedItemId)) { + removeCachedItem(cachedItemId); + } + } + } catch (SQLException error) { + Log.warning(error); + } + } + } + + protected void addNewItem(BaseModel item) { + items.put(item.getId(), item); + } + + public void addItem(BaseModel item) throws SQLException { + dataManager.addObject(item); + addNewItem(item); + } + + protected void updateCachedItem(BaseModel item) { + items.put(item.getId(), item); + } + + public void updateItem(BaseModel item) throws SQLException { + dataManager.updateObject(item); + updateCachedItem(item); + } + + protected void removeCachedItem(long itemId) { + items.remove(itemId); + } + + public void removeItem(long itemId) throws SQLException { + BaseModel item = getById(itemId); + if (item != null) { + dataManager.removeObject(baseClass, itemId); + removeCachedItem(itemId); + } + } + + public final Collection getItems(Class clazz, Set itemIds) { + Collection result = new LinkedList<>(); + for (long itemId : itemIds) { + result.add((T) getById(itemId)); + } + return result; + } + + public Set getAllItems() { + return items.keySet(); + } + +} diff --git a/src/org/traccar/database/DeviceManager.java b/src/org/traccar/database/DeviceManager.java index 995aa8ac3..ac66f1bb8 100644 --- a/src/org/traccar/database/DeviceManager.java +++ b/src/org/traccar/database/DeviceManager.java @@ -19,7 +19,6 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -31,6 +30,7 @@ import org.traccar.BaseProtocol; import org.traccar.Config; import org.traccar.Context; import org.traccar.helper.Log; +import org.traccar.model.BaseModel; import org.traccar.model.Command; import org.traccar.model.CommandType; import org.traccar.model.Device; @@ -39,121 +39,42 @@ import org.traccar.model.Group; import org.traccar.model.Position; import org.traccar.model.Server; -public class DeviceManager implements IdentityManager { +public class DeviceManager extends BaseObjectManager implements IdentityManager, ManagableObjects { public static final long DEFAULT_REFRESH_DELAY = 300; private final Config config; - private final DataManager dataManager; private final long dataRefreshDelay; private boolean lookupGroupsAttribute; - private Map devicesById; private Map devicesByUniqueId; private Map devicesByPhone; private AtomicLong devicesLastUpdate = new AtomicLong(); - private Map groupsById; - private AtomicLong groupsLastUpdate = new AtomicLong(); - private final Map positions = new ConcurrentHashMap<>(); private boolean fallbackToText; public DeviceManager(DataManager dataManager) { - this.dataManager = dataManager; + super(dataManager, Device.class); this.config = Context.getConfig(); dataRefreshDelay = config.getLong("database.refreshDelay", DEFAULT_REFRESH_DELAY) * 1000; lookupGroupsAttribute = config.getBoolean("deviceManager.lookupGroupsAttribute"); fallbackToText = config.getBoolean("command.fallbackToSms"); - if (dataManager != null) { - try { - updateGroupCache(true); - updateDeviceCache(true); - for (Position position : dataManager.getLatestPositions()) { - positions.put(position.getDeviceId(), position); - } - } catch (SQLException error) { - Log.warning(error); - } - } + refreshLastPositions(); } private void updateDeviceCache(boolean force) throws SQLException { - long lastUpdate = devicesLastUpdate.get(); if ((force || System.currentTimeMillis() - lastUpdate > dataRefreshDelay) && devicesLastUpdate.compareAndSet(lastUpdate, System.currentTimeMillis())) { - GeofenceManager geofenceManager = Context.getGeofenceManager(); - Collection databaseDevices = dataManager.getObjects(Device.class); - if (devicesById == null) { - devicesById = new ConcurrentHashMap<>(databaseDevices.size()); - } - if (devicesByUniqueId == null) { - devicesByUniqueId = new ConcurrentHashMap<>(databaseDevices.size()); - } - if (devicesByPhone == null) { - devicesByPhone = new ConcurrentHashMap<>(databaseDevices.size()); - } - Set databaseDevicesIds = new HashSet<>(); - Set databaseDevicesUniqueIds = new HashSet<>(); - Set databaseDevicesPhones = new HashSet<>(); - for (Device device : databaseDevices) { - databaseDevicesIds.add(device.getId()); - databaseDevicesUniqueIds.add(device.getUniqueId()); - databaseDevicesPhones.add(device.getPhone()); - if (devicesById.containsKey(device.getId())) { - Device cachedDevice = devicesById.get(device.getId()); - cachedDevice.setName(device.getName()); - cachedDevice.setGroupId(device.getGroupId()); - cachedDevice.setCategory(device.getCategory()); - cachedDevice.setContact(device.getContact()); - cachedDevice.setModel(device.getModel()); - cachedDevice.setAttributes(device.getAttributes()); - if (!device.getUniqueId().equals(cachedDevice.getUniqueId())) { - devicesByUniqueId.put(device.getUniqueId(), cachedDevice); - } - cachedDevice.setUniqueId(device.getUniqueId()); - if (device.getPhone() != null && !device.getPhone().isEmpty() - && !device.getPhone().equals(cachedDevice.getPhone())) { - devicesByPhone.put(device.getPhone(), cachedDevice); - } - cachedDevice.setPhone(device.getPhone()); - } else { - devicesById.put(device.getId(), device); - devicesByUniqueId.put(device.getUniqueId(), device); - if (device.getPhone() != null && !device.getPhone().isEmpty()) { - devicesByPhone.put(device.getPhone(), device); - } - if (geofenceManager != null) { - Position lastPosition = getLastPosition(device.getId()); - if (lastPosition != null) { - device.setGeofenceIds(geofenceManager.getCurrentDeviceGeofences(lastPosition)); - } - } - } - } - for (Iterator iterator = devicesById.keySet().iterator(); iterator.hasNext();) { - if (!databaseDevicesIds.contains(iterator.next())) { - iterator.remove(); - } - } - for (Iterator iterator = devicesByUniqueId.keySet().iterator(); iterator.hasNext();) { - if (!databaseDevicesUniqueIds.contains(iterator.next())) { - iterator.remove(); - } - } - for (Iterator iterator = devicesByPhone.keySet().iterator(); iterator.hasNext();) { - if (!databaseDevicesPhones.contains(iterator.next())) { - iterator.remove(); - } - } + refreshItems(); } } @Override public Device getDeviceById(long id) { - return devicesById.get(id); + return (Device) getById(id); } @Override @@ -169,76 +90,129 @@ public class DeviceManager implements IdentityManager { return devicesByPhone.get(phone); } + @Override + public Set getAllItems() { + Set result = super.getAllItems(); + if (result.isEmpty()) { + try { + updateDeviceCache(true); + } catch (SQLException e) { + Log.warning(e); + } + result = super.getAllItems(); + } + return result; + } + public Collection getAllDevices() { - boolean forceUpdate = devicesById.isEmpty(); + return getItems(Device.class, getAllItems()); + } - try { - updateDeviceCache(forceUpdate); - } catch (SQLException e) { - Log.warning(e); + @Override + public Set getUserItems(long userId) { + if (Context.getPermissionsManager() != null) { + return Context.getPermissionsManager().getDevicePermissions(userId); + } else { + return new HashSet<>(); } - - return devicesById.values(); } - public Collection getDevices(long userId) throws SQLException { - Collection devices = new ArrayList<>(); - for (long id : Context.getPermissionsManager().getDevicePermissions(userId)) { - devices.add(devicesById.get(id)); + @Override + public Set getManagedItems(long userId) { + Set result = new HashSet<>(); + result.addAll(getUserItems(userId)); + for (long managedUserId : Context.getUsersManager().getUserItems(userId)) { + result.addAll(getUserItems(managedUserId)); } - return devices; + return result; } - public Collection getManagedDevices(long userId) throws SQLException { - Collection devices = new HashSet<>(); - devices.addAll(getDevices(userId)); - for (long managedUserId : Context.getUsersManager().getManagedItems(userId)) { - devices.addAll(getDevices(managedUserId)); + private void putUniqueDeviceId(Device device) { + if (devicesByUniqueId == null) { + devicesByUniqueId = new ConcurrentHashMap<>(getAllItems().size()); } - return devices; + devicesByUniqueId.put(device.getUniqueId(), device); } - public void addDevice(Device device) throws SQLException { - dataManager.addObject(device); + private void putPhone(Device device) { + if (devicesByPhone == null) { + devicesByPhone = new ConcurrentHashMap<>(getAllItems().size()); + } + devicesByPhone.put(device.getPhone(), device); + } - devicesById.put(device.getId(), device); - devicesByUniqueId.put(device.getUniqueId(), device); + @Override + protected void addNewItem(BaseModel item) { + Device device = (Device) item; + super.addNewItem(item); + putUniqueDeviceId(device); if (device.getPhone() != null && !device.getPhone().isEmpty()) { - devicesByPhone.put(device.getPhone(), device); + putPhone(device); + } + if (Context.getGeofenceManager() != null) { + Position lastPosition = getLastPosition(device.getId()); + if (lastPosition != null) { + device.setGeofenceIds(Context.getGeofenceManager().getCurrentDeviceGeofences(lastPosition)); + } } } - public void updateDevice(Device device) throws SQLException { - dataManager.updateObject(device); + @Override + protected void updateCachedItem(BaseModel item) { + Device device = (Device) item; + Device cachedDevice = (Device) getById(device.getId()); + cachedDevice.setName(device.getName()); + cachedDevice.setGroupId(device.getGroupId()); + cachedDevice.setCategory(device.getCategory()); + cachedDevice.setContact(device.getContact()); + cachedDevice.setModel(device.getModel()); + cachedDevice.setAttributes(device.getAttributes()); + if (!device.getUniqueId().equals(cachedDevice.getUniqueId())) { + devicesByUniqueId.remove(cachedDevice.getUniqueId()); + cachedDevice.setUniqueId(device.getUniqueId()); + putUniqueDeviceId(cachedDevice); + } + if (device.getPhone() != null && !device.getPhone().isEmpty() + && !device.getPhone().equals(cachedDevice.getPhone())) { + devicesByPhone.remove(cachedDevice.getPhone()); + cachedDevice.setPhone(device.getPhone()); + putPhone(cachedDevice); + } + } - devicesById.put(device.getId(), device); - devicesByUniqueId.put(device.getUniqueId(), device); - if (device.getPhone() != null && !device.getPhone().isEmpty()) { - devicesByPhone.put(device.getPhone(), device); + @Override + protected void removeCachedItem(long deviceId) { + Device cachedDevice = (Device) getById(deviceId); + if (cachedDevice != null) { + String deviceUniqueId = cachedDevice.getUniqueId(); + String phone = cachedDevice.getPhone(); + super.removeCachedItem(deviceId); + devicesByUniqueId.remove(deviceUniqueId); + if (phone != null && !phone.isEmpty()) { + devicesByPhone.remove(phone); + } } + positions.remove(deviceId); } public void updateDeviceStatus(Device device) throws SQLException { - dataManager.updateDeviceStatus(device); - if (devicesById.containsKey(device.getId())) { - Device cachedDevice = devicesById.get(device.getId()); + getDataManager().updateDeviceStatus(device); + Device cachedDevice = (Device) getById(device.getId()); + if (cachedDevice != null) { cachedDevice.setStatus(device.getStatus()); } } - public void removeDevice(long deviceId) throws SQLException { - dataManager.removeObject(Device.class, deviceId); - - if (devicesById.containsKey(deviceId)) { - String deviceUniqueId = devicesById.get(deviceId).getUniqueId(); - String phone = devicesById.get(deviceId).getPhone(); - devicesById.remove(deviceId); - devicesByUniqueId.remove(deviceUniqueId); - if (phone != null && !phone.isEmpty()) { - devicesByPhone.remove(phone); + private void refreshLastPositions() { + if (getDataManager() != null) { + try { + for (Position position : getDataManager().getLatestPositions()) { + positions.put(position.getDeviceId(), position); + } + } catch (SQLException error) { + Log.warning(error); } } - positions.remove(deviceId); } public boolean isLatestPosition(Position position) { @@ -250,10 +224,11 @@ public class DeviceManager implements IdentityManager { if (isLatestPosition(position)) { - dataManager.updateLatestPosition(position); + getDataManager().updateLatestPosition(position); - if (devicesById.containsKey(position.getDeviceId())) { - devicesById.get(position.getDeviceId()).setPositionId(position.getId()); + Device device = (Device) getById(position.getDeviceId()); + if (device != null) { + device.setPositionId(position.getId()); } positions.put(position.getDeviceId(), position); @@ -274,7 +249,7 @@ public class DeviceManager implements IdentityManager { List result = new LinkedList<>(); if (Context.getPermissionsManager() != null) { - for (long deviceId : Context.getPermissionsManager().getDevicePermissions(userId)) { + for (long deviceId : getUserItems(userId)) { if (positions.containsKey(deviceId)) { result.add(positions.get(deviceId)); } @@ -284,96 +259,6 @@ public class DeviceManager implements IdentityManager { return result; } - private void updateGroupCache(boolean force) throws SQLException { - - long lastUpdate = groupsLastUpdate.get(); - if ((force || System.currentTimeMillis() - lastUpdate > dataRefreshDelay) - && groupsLastUpdate.compareAndSet(lastUpdate, System.currentTimeMillis())) { - Collection databaseGroups = dataManager.getObjects(Group.class); - if (groupsById == null) { - groupsById = new ConcurrentHashMap<>(databaseGroups.size()); - } - Set databaseGroupsIds = new HashSet<>(); - for (Group group : databaseGroups) { - databaseGroupsIds.add(group.getId()); - if (groupsById.containsKey(group.getId())) { - Group cachedGroup = groupsById.get(group.getId()); - cachedGroup.setName(group.getName()); - cachedGroup.setGroupId(group.getGroupId()); - } else { - groupsById.put(group.getId(), group); - } - } - for (Long cachedGroupId : groupsById.keySet()) { - if (!databaseGroupsIds.contains(cachedGroupId)) { - groupsById.remove(cachedGroupId); - } - } - databaseGroupsIds.clear(); - } - } - - public Group getGroupById(long id) { - return groupsById.get(id); - } - - public Collection getAllGroups() { - boolean forceUpdate = groupsById.isEmpty(); - - try { - updateGroupCache(forceUpdate); - } catch (SQLException e) { - Log.warning(e); - } - - return groupsById.values(); - } - - public Collection getGroups(long userId) throws SQLException { - Collection groups = new ArrayList<>(); - for (long id : Context.getPermissionsManager().getGroupPermissions(userId)) { - groups.add(getGroupById(id)); - } - return groups; - } - - public Collection getManagedGroups(long userId) throws SQLException { - Collection groups = new ArrayList<>(); - groups.addAll(getGroups(userId)); - for (long managedUserId : Context.getUsersManager().getManagedItems(userId)) { - groups.addAll(getGroups(managedUserId)); - } - return groups; - } - - private void checkGroupCycles(Group group) { - Set groups = new HashSet<>(); - while (group != null) { - if (groups.contains(group.getId())) { - throw new IllegalArgumentException("Cycle in group hierarchy"); - } - groups.add(group.getId()); - group = groupsById.get(group.getGroupId()); - } - } - - public void addGroup(Group group) throws SQLException { - checkGroupCycles(group); - dataManager.addObject(group); - groupsById.put(group.getId(), group); - } - - public void updateGroup(Group group) throws SQLException { - checkGroupCycles(group); - dataManager.updateObject(group); - groupsById.put(group.getId(), group); - } - - public void removeGroup(long groupId) throws SQLException { - dataManager.removeObject(Group.class, groupId); - groupsById.remove(groupId); - } - public boolean lookupAttributeBoolean( long deviceId, String attributeName, boolean defaultValue, boolean lookupConfig) { String result = lookupAttribute(deviceId, attributeName, lookupConfig); @@ -426,12 +311,13 @@ public class DeviceManager implements IdentityManager { if (result == null && lookupGroupsAttribute) { long groupId = device.getGroupId(); while (groupId != 0) { - if (getGroupById(groupId) != null) { - result = getGroupById(groupId).getString(attributeName); + Group group = (Group) Context.getGroupsManager().getById(groupId); + if (group != null) { + result = group.getString(attributeName); if (result != null) { break; } - groupId = getGroupById(groupId).getGroupId(); + groupId = group.getGroupId(); } else { groupId = 0; } @@ -453,7 +339,7 @@ public class DeviceManager implements IdentityManager { Position last = positions.get(deviceTotalDistance.getDeviceId()); if (last != null) { last.getAttributes().put(Position.KEY_TOTAL_DISTANCE, deviceTotalDistance.getTotalDistance()); - dataManager.addPosition(last); + getDataManager().addPosition(last); updateLatestPosition(last); } else { throw new IllegalArgumentException(); @@ -466,9 +352,9 @@ public class DeviceManager implements IdentityManager { Position lastPosition = getLastPosition(deviceId); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); - protocol.sendTextCommand(devicesById.get(deviceId).getPhone(), command); + protocol.sendTextCommand(((Device) getById(deviceId)).getPhone(), command); } else if (command.getType().equals(Command.TYPE_CUSTOM)) { - Context.getSmppManager().sendMessageSync(devicesById.get(deviceId).getPhone(), + Context.getSmppManager().sendMessageSync(((Device) getById(deviceId)).getPhone(), command.getString(Command.KEY_DATA), true); } else { throw new RuntimeException("Command " + command.getType() + " is not supported"); diff --git a/src/org/traccar/database/ExtendedObjectManager.java b/src/org/traccar/database/ExtendedObjectManager.java index 2833b3bae..19c9ca5b2 100644 --- a/src/org/traccar/database/ExtendedObjectManager.java +++ b/src/org/traccar/database/ExtendedObjectManager.java @@ -48,10 +48,6 @@ public abstract class ExtendedObjectManager extends SimpleObjectManager { return groupItems.get(groupId); } - protected final void clearGroupItems() { - groupItems.clear(); - } - public final Set getDeviceItems(long deviceId) { if (!deviceItems.containsKey(deviceId)) { deviceItems.put(deviceId, new HashSet()); @@ -59,10 +55,6 @@ public abstract class ExtendedObjectManager extends SimpleObjectManager { return deviceItems.get(deviceId); } - protected final void clearDeviceItems() { - deviceItems.clear(); - } - public Set getAllDeviceItems(long deviceId) { if (!deviceItemsWithGroups.containsKey(deviceId)) { deviceItemsWithGroups.put(deviceId, new HashSet()); @@ -83,16 +75,15 @@ public abstract class ExtendedObjectManager extends SimpleObjectManager { Collection databaseGroupPermissions = getDataManager().getPermissions(Group.class, getBaseClass()); - clearGroupItems(); + groupItems.clear(); for (Permission groupPermission : databaseGroupPermissions) { getGroupItems(groupPermission.getOwnerId()).add(groupPermission.getPropertyId()); } Collection databaseDevicePermissions = getDataManager().getPermissions(Device.class, getBaseClass()); - Collection allDevices = Context.getDeviceManager().getAllDevices(); - clearDeviceItems(); + deviceItems.clear(); deviceItemsWithGroups.clear(); for (Permission devicePermission : databaseDevicePermissions) { @@ -100,12 +91,13 @@ public abstract class ExtendedObjectManager extends SimpleObjectManager { getAllDeviceItems(devicePermission.getOwnerId()).add(devicePermission.getPropertyId()); } - for (Device device : allDevices) { + for (Device device : Context.getDeviceManager().getAllDevices()) { long groupId = device.getGroupId(); while (groupId != 0) { getAllDeviceItems(device.getId()).addAll(getGroupItems(groupId)); - if (Context.getDeviceManager().getGroupById(groupId) != null) { - groupId = Context.getDeviceManager().getGroupById(groupId).getGroupId(); + Group group = (Group) Context.getGroupsManager().getById(groupId); + if (group != null) { + groupId = group.getGroupId(); } else { groupId = 0; } diff --git a/src/org/traccar/database/GroupsManager.java b/src/org/traccar/database/GroupsManager.java new file mode 100644 index 000000000..e92158fd6 --- /dev/null +++ b/src/org/traccar/database/GroupsManager.java @@ -0,0 +1,104 @@ +/* + * 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.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; + +import org.traccar.Context; +import org.traccar.helper.Log; +import org.traccar.model.BaseModel; +import org.traccar.model.Group; + +public class GroupsManager extends BaseObjectManager implements ManagableObjects { + + private AtomicLong groupsLastUpdate = new AtomicLong(); + private final long dataRefreshDelay; + + public GroupsManager(DataManager dataManager) { + super(dataManager, Group.class); + dataRefreshDelay = Context.getConfig().getLong("database.refreshDelay", + DeviceManager.DEFAULT_REFRESH_DELAY) * 1000; + } + + private void checkGroupCycles(BaseModel group) { + Set groups = new HashSet<>(); + while (group != null) { + if (groups.contains(group.getId())) { + throw new IllegalArgumentException("Cycle in group hierarchy"); + } + groups.add(group.getId()); + group = getById(((Group) group).getGroupId()); + } + } + + private void updateGroupCache(boolean force) throws SQLException { + long lastUpdate = groupsLastUpdate.get(); + if ((force || System.currentTimeMillis() - lastUpdate > dataRefreshDelay) + && groupsLastUpdate.compareAndSet(lastUpdate, System.currentTimeMillis())) { + refreshItems(); + } + } + + @Override + public Set getAllItems() { + Set result = super.getAllItems(); + if (result.isEmpty()) { + try { + updateGroupCache(true); + } catch (SQLException e) { + Log.warning(e); + } + result = super.getAllItems(); + } + return result; + } + + @Override + protected void addNewItem(BaseModel item) { + checkGroupCycles(item); + super.addNewItem(item); + } + + @Override + protected void updateCachedItem(BaseModel item) { + checkGroupCycles(item); + super.updateCachedItem(item); + } + + @Override + public Set getUserItems(long userId) { + if (Context.getPermissionsManager() != null) { + return Context.getPermissionsManager().getGroupPermissions(userId); + } else { + return new HashSet<>(); + } + } + + @Override + public Set getManagedItems(long userId) { + Set result = new HashSet<>(); + result.addAll(getUserItems(userId)); + for (long managedUserId : Context.getUsersManager().getUserItems(userId)) { + result.addAll(getUserItems(managedUserId)); + } + return result; + } + +} diff --git a/src/org/traccar/database/ManagableObjects.java b/src/org/traccar/database/ManagableObjects.java new file mode 100644 index 000000000..ec9549493 --- /dev/null +++ b/src/org/traccar/database/ManagableObjects.java @@ -0,0 +1,27 @@ +/* + * 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.util.Set; + +public interface ManagableObjects { + + Set getUserItems(long userId); + + Set getManagedItems(long userId); + +} diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index b38ecf9bf..54e5ed979 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -51,7 +51,7 @@ public class PermissionsManager { this.dataManager = dataManager; this.usersManager = usersManager; refreshServer(); - refreshPermissions(); + refreshDeviceAndGroupPermissions(); } public User getUser(long userId) { @@ -94,11 +94,12 @@ public class PermissionsManager { } } - public final void refreshPermissions() { + public final void refreshDeviceAndGroupPermissions() { groupPermissions.clear(); devicePermissions.clear(); try { - GroupTree groupTree = new GroupTree(Context.getDeviceManager().getAllGroups(), + GroupTree groupTree = new GroupTree(Context.getGroupsManager().getItems( + Group.class, Context.getGroupsManager().getAllItems()), Context.getDeviceManager().getAllDevices()); for (Permission groupPermission : dataManager.getPermissions(User.class, Group.class)) { Set userGroupPermissions = getGroupPermissions(groupPermission.getOwnerId()); @@ -117,9 +118,9 @@ public class PermissionsManager { } groupDevices.clear(); - for (Group group : Context.getDeviceManager().getAllGroups()) { - for (Device device : groupTree.getDevices(group.getId())) { - getGroupDevices(group.getId()).add(device.getId()); + for (long groupId : Context.getGroupsManager().getAllItems()) { + for (Device device : groupTree.getDevices(groupId)) { + getGroupDevices(groupId).add(device.getId()); } } @@ -159,14 +160,14 @@ public class PermissionsManager { public void checkManager(long userId, long managedUserId) throws SecurityException { checkManager(userId); - if (!usersManager.getManagedItems(userId).contains(managedUserId)) { + if (!usersManager.getUserItems(userId).contains(managedUserId)) { throw new SecurityException("User access denied"); } } public void checkUserLimit(long userId) throws SecurityException { int userLimit = getUser(userId).getUserLimit(); - if (userLimit != -1 && usersManager.getManagedItems(userId).size() >= userLimit) { + if (userLimit != -1 && usersManager.getUserItems(userId).size() >= userLimit) { throw new SecurityException("Manager user limit reached"); } } @@ -176,9 +177,9 @@ public class PermissionsManager { if (deviceLimit != -1) { int deviceCount = 0; if (isManager(userId)) { - deviceCount = Context.getDeviceManager().getManagedDevices(userId).size(); + deviceCount = Context.getDeviceManager().getManagedItems(userId).size(); } else { - deviceCount = getDevicePermissions(userId).size(); + deviceCount = Context.getDeviceManager().getUserItems(userId).size(); } if (deviceCount >= deviceLimit) { throw new SecurityException("User device limit reached"); @@ -254,7 +255,7 @@ public class PermissionsManager { public void checkGroup(long userId, long groupId) throws SecurityException { if (!getGroupPermissions(userId).contains(groupId) && !isAdmin(userId)) { checkManager(userId); - for (long managedUserId : usersManager.getManagedItems(userId)) { + for (long managedUserId : usersManager.getUserItems(userId)) { if (getGroupPermissions(managedUserId).contains(groupId)) { return; } @@ -264,10 +265,10 @@ public class PermissionsManager { } public void checkDevice(long userId, long deviceId) throws SecurityException { - if (!getDevicePermissions(userId).contains(deviceId) && !isAdmin(userId)) { + if (!Context.getDeviceManager().getUserItems(userId).contains(deviceId) && !isAdmin(userId)) { checkManager(userId); - for (long managedUserId : usersManager.getManagedItems(userId)) { - if (getDevicePermissions(managedUserId).contains(deviceId)) { + for (long managedUserId : usersManager.getUserItems(userId)) { + if (Context.getDeviceManager().getUserItems(managedUserId).contains(deviceId)) { return; } } @@ -314,6 +315,18 @@ public class PermissionsManager { } } + public void refreshAllUsersPermissions() { + if (Context.getGeofenceManager() != null) { + Context.getGeofenceManager().refreshUserItems(); + } + Context.getCalendarManager().refreshUserItems(); + Context.getDriversManager().refreshUserItems(); + Context.getAttributesManager().refreshUserItems(); + if (Context.getNotificationManager() != null) { + Context.getNotificationManager().refresh(); + } + } + public void refreshAllExtendedPermissions() { if (Context.getGeofenceManager() != null) { Context.getGeofenceManager().refreshExtendedPermissions(); @@ -326,7 +339,7 @@ public class PermissionsManager { if (permission.getOwnerClass().equals(User.class)) { if (permission.getPropertyClass().equals(Device.class) || permission.getPropertyClass().equals(Group.class)) { - refreshPermissions(); + refreshDeviceAndGroupPermissions(); refreshAllExtendedPermissions(); } else if (permission.getPropertyClass().equals(ManagedUser.class)) { usersManager.refreshUserItems(); diff --git a/src/org/traccar/database/SimpleObjectManager.java b/src/org/traccar/database/SimpleObjectManager.java index 124178a05..fa41f30b6 100644 --- a/src/org/traccar/database/SimpleObjectManager.java +++ b/src/org/traccar/database/SimpleObjectManager.java @@ -17,9 +17,7 @@ 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; @@ -30,43 +28,15 @@ import org.traccar.model.BaseModel; import org.traccar.model.Permission; import org.traccar.model.User; -public abstract class SimpleObjectManager { +public abstract class SimpleObjectManager extends BaseObjectManager implements ManagableObjects { - private final DataManager dataManager; - - private Map items; - private final Map> userItems = new ConcurrentHashMap<>(); - - private Class baseClass; - private String baseClassIdName; + private Map> userItems; protected SimpleObjectManager(DataManager dataManager, Class baseClass) { - this.dataManager = dataManager; - this.baseClass = baseClass; - baseClassIdName = DataManager.makeNameId(baseClass); - refreshItems(); - } - - protected final DataManager getDataManager() { - return dataManager; - } - - protected final Class getBaseClass() { - return baseClass; - } - - protected final String getBaseClassIdName() { - return baseClassIdName; - } - - public final BaseModel getById(long itemId) { - return items.get(itemId); - } - - protected final void clearItems() { - items.clear(); + super(dataManager, baseClass); } + @Override public final Set getUserItems(long userId) { if (!userItems.containsKey(userId)) { userItems.put(userId, new HashSet()); @@ -74,47 +44,35 @@ public abstract class SimpleObjectManager { return userItems.get(userId); } - protected final void clearUserItems() { - userItems.clear(); + @Override + public Set getManagedItems(long userId) { + Set result = new HashSet<>(); + result.addAll(getUserItems(userId)); + for (long managedUserId : Context.getUsersManager().getUserItems(userId)) { + result.addAll(getUserItems(managedUserId)); + } + return result; } public final boolean checkItemPermission(long userId, long itemId) { return getUserItems(userId).contains(itemId); } + @Override public void refreshItems() { - if (dataManager != null) { - try { - Collection databaseItems = dataManager.getObjects(baseClass); - if (items == null) { - items = new ConcurrentHashMap<>(databaseItems.size()); - } - Set databaseItemIds = new HashSet<>(); - for (BaseModel item : databaseItems) { - databaseItemIds.add(item.getId()); - if (items.containsKey(item.getId())) { - updateCachedItem(item); - } else { - addNewItem(item); - } - } - for (Long cachedItemId : items.keySet()) { - if (!databaseItemIds.contains(cachedItemId)) { - removeCachedItem(cachedItemId); - } - } - } catch (SQLException error) { - Log.warning(error); - } - } + super.refreshItems(); refreshUserItems(); } public final void refreshUserItems() { - if (dataManager != null) { + if (getDataManager() != null) { try { - clearUserItems(); - for (Permission permission : dataManager.getPermissions(User.class, baseClass)) { + if (userItems != null) { + userItems.clear(); + } else { + userItems = new ConcurrentHashMap<>(); + } + for (Permission permission : getDataManager().getPermissions(User.class, getBaseClass())) { getUserItems(permission.getOwnerId()).add(permission.getPropertyId()); } } catch (SQLException | ClassNotFoundException error) { @@ -123,56 +81,10 @@ public abstract class SimpleObjectManager { } } - protected void addNewItem(BaseModel item) { - items.put(item.getId(), item); - } - - public void addItem(BaseModel item) throws SQLException { - dataManager.addObject(item); - addNewItem(item); - } - - protected void updateCachedItem(BaseModel item) { - items.put(item.getId(), item); - } - - public void updateItem(BaseModel item) throws SQLException { - dataManager.updateObject(item); - updateCachedItem(item); - } - - protected void removeCachedItem(long itemId) { - items.remove(itemId); - } - + @Override public void removeItem(long itemId) throws SQLException { - BaseModel item = getById(itemId); - if (item != null) { - dataManager.removeObject(baseClass, itemId); - removeCachedItem(itemId); - } + super.removeItem(itemId); refreshUserItems(); } - public final Collection getItems(Class clazz, Set itemIds) { - Collection result = new LinkedList<>(); - for (long itemId : itemIds) { - result.add((T) getById(itemId)); - } - return result; - } - - public final Set getAllItems() { - return items.keySet(); - } - - public Set getManagedItems(long userId) { - Set result = new HashSet<>(); - result.addAll(getUserItems(userId)); - for (long managedUserId : Context.getUsersManager().getManagedItems(userId)) { - result.addAll(getUserItems(managedUserId)); - } - return result; - } - } diff --git a/src/org/traccar/database/UsersManager.java b/src/org/traccar/database/UsersManager.java index 3c9c8b280..cb4ea623f 100644 --- a/src/org/traccar/database/UsersManager.java +++ b/src/org/traccar/database/UsersManager.java @@ -16,6 +16,7 @@ */ package org.traccar.database; +import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -73,7 +74,10 @@ public class UsersManager extends SimpleObjectManager { @Override public Set getManagedItems(long userId) { - return getUserItems(userId); + Set result = new HashSet<>(); + result.addAll(getUserItems(userId)); + result.add(userId); + return result; } public User getUserByToken(String token) { diff --git a/src/org/traccar/reports/Events.java b/src/org/traccar/reports/Events.java index 3a111944c..9d3acb250 100644 --- a/src/org/traccar/reports/Events.java +++ b/src/org/traccar/reports/Events.java @@ -92,7 +92,7 @@ public final class Events { deviceEvents.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceEvents.getDeviceName())); if (device.getGroupId() != 0) { - Group group = Context.getDeviceManager().getGroupById(device.getGroupId()); + Group group = (Group) Context.getGroupsManager().getById(device.getGroupId()); if (group != null) { deviceEvents.setGroupName(group.getName()); } diff --git a/src/org/traccar/reports/Route.java b/src/org/traccar/reports/Route.java index aa6b7105b..9f0696085 100644 --- a/src/org/traccar/reports/Route.java +++ b/src/org/traccar/reports/Route.java @@ -61,7 +61,7 @@ public final class Route { deviceRoutes.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceRoutes.getDeviceName())); if (device.getGroupId() != 0) { - Group group = Context.getDeviceManager().getGroupById(device.getGroupId()); + Group group = (Group) Context.getGroupsManager().getById(device.getGroupId()); if (group != null) { deviceRoutes.setGroupName(group.getName()); } diff --git a/src/org/traccar/reports/Stops.java b/src/org/traccar/reports/Stops.java index 64e589be1..1c631a0c2 100644 --- a/src/org/traccar/reports/Stops.java +++ b/src/org/traccar/reports/Stops.java @@ -78,7 +78,7 @@ public final class Stops { deviceStops.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceStops.getDeviceName())); if (device.getGroupId() != 0) { - Group group = Context.getDeviceManager().getGroupById(device.getGroupId()); + Group group = (Group) Context.getGroupsManager().getById(device.getGroupId()); if (group != null) { deviceStops.setGroupName(group.getName()); } diff --git a/src/org/traccar/reports/Trips.java b/src/org/traccar/reports/Trips.java index 5c26bea54..51689bfd3 100644 --- a/src/org/traccar/reports/Trips.java +++ b/src/org/traccar/reports/Trips.java @@ -77,7 +77,7 @@ public final class Trips { deviceTrips.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceTrips.getDeviceName())); if (device.getGroupId() != 0) { - Group group = Context.getDeviceManager().getGroupById(device.getGroupId()); + Group group = (Group) Context.getGroupsManager().getById(device.getGroupId()); if (group != null) { deviceTrips.setGroupName(group.getName()); } -- cgit v1.2.3 From d31f68d80a8e3ae75fa0c2f02b9ca258486a3cad Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 26 Jul 2017 17:52:27 +0500 Subject: - Implement base manager classes as generics - Remame getDeviceById and getDeviceByUniqueId functions --- src/org/traccar/BaseProtocolDecoder.java | 2 +- src/org/traccar/BaseProtocolEncoder.java | 4 +-- src/org/traccar/FilterHandler.java | 2 +- src/org/traccar/MainEventHandler.java | 2 +- src/org/traccar/WebDataHandler.java | 2 +- .../traccar/api/resource/AttributeResource.java | 2 +- src/org/traccar/api/resource/CalendarResource.java | 9 ++++-- src/org/traccar/api/resource/DeviceResource.java | 4 +-- src/org/traccar/api/resource/DriverResource.java | 2 +- src/org/traccar/api/resource/GeofenceResource.java | 2 +- src/org/traccar/api/resource/GroupResource.java | 2 +- src/org/traccar/api/resource/PositionResource.java | 2 +- src/org/traccar/api/resource/UserResource.java | 2 +- src/org/traccar/database/AttributesManager.java | 13 ++------- src/org/traccar/database/BaseObjectManager.java | 28 +++++++++--------- src/org/traccar/database/CalendarManager.java | 7 +---- src/org/traccar/database/ConnectionManager.java | 2 +- src/org/traccar/database/DeviceManager.java | 34 +++++++++------------- src/org/traccar/database/DriversManager.java | 25 ++++++---------- .../traccar/database/ExtendedObjectManager.java | 4 +-- src/org/traccar/database/GeofenceManager.java | 7 +---- src/org/traccar/database/GroupsManager.java | 19 +++++------- src/org/traccar/database/IdentityManager.java | 4 +-- src/org/traccar/database/PermissionsManager.java | 5 ++-- src/org/traccar/database/SimpleObjectManager.java | 5 ++-- src/org/traccar/database/UsersManager.java | 21 +++++-------- src/org/traccar/events/FuelDropEventHandler.java | 2 +- src/org/traccar/events/GeofenceEventHandler.java | 11 ++++--- src/org/traccar/events/IgnitionEventHandler.java | 2 +- .../traccar/events/MaintenanceEventHandler.java | 2 +- src/org/traccar/events/MotionEventHandler.java | 2 +- src/org/traccar/events/OverspeedEventHandler.java | 2 +- src/org/traccar/notification/EventForwarder.java | 2 +- .../notification/NotificationFormatter.java | 2 +- .../processing/ComputedAttributesHandler.java | 4 +-- src/org/traccar/protocol/Gt06ProtocolDecoder.java | 2 +- .../traccar/protocol/MeitrackProtocolDecoder.java | 4 +-- src/org/traccar/reports/Events.java | 2 +- src/org/traccar/reports/ReportUtils.java | 4 +-- src/org/traccar/reports/Route.java | 2 +- src/org/traccar/reports/Stops.java | 2 +- src/org/traccar/reports/Summary.java | 2 +- src/org/traccar/reports/Trips.java | 2 +- test/org/traccar/BaseTest.java | 4 +-- 44 files changed, 112 insertions(+), 152 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/BaseProtocolDecoder.java b/src/org/traccar/BaseProtocolDecoder.java index b7ceabb5c..cc16000f4 100644 --- a/src/org/traccar/BaseProtocolDecoder.java +++ b/src/org/traccar/BaseProtocolDecoder.java @@ -75,7 +75,7 @@ public abstract class BaseProtocolDecoder extends ExtendedObjectDecoder { try { for (String uniqueId : uniqueIds) { if (uniqueId != null) { - Device device = Context.getIdentityManager().getDeviceByUniqueId(uniqueId); + Device device = Context.getIdentityManager().getByUniqueId(uniqueId); if (device != null) { deviceId = device.getId(); break; diff --git a/src/org/traccar/BaseProtocolEncoder.java b/src/org/traccar/BaseProtocolEncoder.java index 3c2d08471..2c8a81868 100644 --- a/src/org/traccar/BaseProtocolEncoder.java +++ b/src/org/traccar/BaseProtocolEncoder.java @@ -25,12 +25,12 @@ import org.traccar.model.Device; public abstract class BaseProtocolEncoder extends OneToOneEncoder { protected String getUniqueId(long deviceId) { - return Context.getIdentityManager().getDeviceById(deviceId).getUniqueId(); + return Context.getIdentityManager().getById(deviceId).getUniqueId(); } protected void initDevicePassword(Command command, String defaultPassword) { if (!command.getAttributes().containsKey(Command.KEY_DEVICE_PASSWORD)) { - Device device = Context.getIdentityManager().getDeviceById(command.getDeviceId()); + Device device = Context.getIdentityManager().getById(command.getDeviceId()); String password = device.getString(Command.KEY_DEVICE_PASSWORD); if (password != null) { command.set(Command.KEY_DEVICE_PASSWORD, password); diff --git a/src/org/traccar/FilterHandler.java b/src/org/traccar/FilterHandler.java index 71c0a1cf5..1f5fffc86 100644 --- a/src/org/traccar/FilterHandler.java +++ b/src/org/traccar/FilterHandler.java @@ -184,7 +184,7 @@ public class FilterHandler extends BaseDataHandler { message.append("Position filtered by "); message.append(filterType.toString()); message.append("filters from device: "); - message.append(Context.getIdentityManager().getDeviceById(position.getDeviceId()).getUniqueId()); + message.append(Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId()); message.append(" with id: "); message.append(position.getDeviceId()); diff --git a/src/org/traccar/MainEventHandler.java b/src/org/traccar/MainEventHandler.java index a005ee44b..8e88e15b9 100644 --- a/src/org/traccar/MainEventHandler.java +++ b/src/org/traccar/MainEventHandler.java @@ -55,7 +55,7 @@ public class MainEventHandler extends IdleStateAwareChannelHandler { Log.warning(error); } - String uniqueId = Context.getIdentityManager().getDeviceById(position.getDeviceId()).getUniqueId(); + String uniqueId = Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId(); // Log position StringBuilder s = new StringBuilder(); diff --git a/src/org/traccar/WebDataHandler.java b/src/org/traccar/WebDataHandler.java index eaf0978ef..c64dcc81b 100644 --- a/src/org/traccar/WebDataHandler.java +++ b/src/org/traccar/WebDataHandler.java @@ -75,7 +75,7 @@ public class WebDataHandler extends BaseDataHandler { public String formatRequest(Position position) { - Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); + Device device = Context.getIdentityManager().getById(position.getDeviceId()); String request = url .replace("{name}", device.getName()) diff --git a/src/org/traccar/api/resource/AttributeResource.java b/src/org/traccar/api/resource/AttributeResource.java index 7b81d3ffb..c12fcd9e6 100644 --- a/src/org/traccar/api/resource/AttributeResource.java +++ b/src/org/traccar/api/resource/AttributeResource.java @@ -81,7 +81,7 @@ public class AttributeResource extends BaseResource { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); result.retainAll(attributesManager.getDeviceItems(deviceId)); } - return attributesManager.getItems(Attribute.class, result); + return attributesManager.getItems(result); } diff --git a/src/org/traccar/api/resource/CalendarResource.java b/src/org/traccar/api/resource/CalendarResource.java index a0f8656af..f8d78a847 100644 --- a/src/org/traccar/api/resource/CalendarResource.java +++ b/src/org/traccar/api/resource/CalendarResource.java @@ -18,6 +18,7 @@ package org.traccar.api.resource; import java.sql.SQLException; import java.util.Collection; +import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -47,20 +48,22 @@ public class CalendarResource extends BaseResource { @QueryParam("all") boolean all, @QueryParam("userId") long userId) throws SQLException { CalendarManager calendarManager = Context.getCalendarManager(); + Set result = null; if (all) { if (Context.getPermissionsManager().isAdmin(getUserId())) { - return calendarManager.getItems(Calendar.class, calendarManager.getAllItems()); + result = calendarManager.getAllItems(); } else { Context.getPermissionsManager().checkManager(getUserId()); - return calendarManager.getItems(Calendar.class, calendarManager.getManagedItems(getUserId())); + result = calendarManager.getManagedItems(getUserId()); } } else { if (userId == 0) { userId = getUserId(); } Context.getPermissionsManager().checkUser(getUserId(), userId); - return calendarManager.getItems(Calendar.class, calendarManager.getUserItems(userId)); + result = calendarManager.getUserItems(userId); } + return calendarManager.getItems(result); } @POST diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index c621d4304..a473b7bde 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -68,7 +68,7 @@ public class DeviceResource extends BaseResource { } else { result = new HashSet(); for (String uniqueId : uniqueIds) { - Device device = deviceManager.getDeviceByUniqueId(uniqueId); + Device device = deviceManager.getByUniqueId(uniqueId); Context.getPermissionsManager().checkDevice(getUserId(), device.getId()); result.add(device.getId()); } @@ -77,7 +77,7 @@ public class DeviceResource extends BaseResource { result.add(deviceId); } } - return deviceManager.getItems(Device.class, result); + return deviceManager.getItems(result); } @POST diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index 72eadb711..d44979998 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -79,7 +79,7 @@ public class DriverResource extends BaseResource { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); result.retainAll(driversManager.getDeviceItems(deviceId)); } - return driversManager.getItems(Driver.class, result); + return driversManager.getItems(result); } diff --git a/src/org/traccar/api/resource/GeofenceResource.java b/src/org/traccar/api/resource/GeofenceResource.java index 47f889e9c..9a110fbcf 100644 --- a/src/org/traccar/api/resource/GeofenceResource.java +++ b/src/org/traccar/api/resource/GeofenceResource.java @@ -78,7 +78,7 @@ public class GeofenceResource extends BaseResource { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); result.retainAll(geofenceManager.getDeviceItems(deviceId)); } - return geofenceManager.getItems(Geofence.class, result); + return geofenceManager.getItems(result); } diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index f832660b2..4482f06c0 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -60,7 +60,7 @@ public class GroupResource extends BaseResource { Context.getPermissionsManager().checkUser(getUserId(), userId); result = groupsManager.getUserItems(userId); } - return groupsManager.getItems(Group.class, result); + return groupsManager.getItems(result); } @POST diff --git a/src/org/traccar/api/resource/PositionResource.java b/src/org/traccar/api/resource/PositionResource.java index 9d3cd9ae6..6dab51744 100644 --- a/src/org/traccar/api/resource/PositionResource.java +++ b/src/org/traccar/api/resource/PositionResource.java @@ -87,7 +87,7 @@ public class PositionResource extends BaseResource { @QueryParam("deviceId") long deviceId, @QueryParam("from") String from, @QueryParam("to") String to) throws SQLException { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - GpxBuilder gpx = new GpxBuilder(Context.getIdentityManager().getDeviceById(deviceId).getName()); + GpxBuilder gpx = new GpxBuilder(Context.getIdentityManager().getById(deviceId).getName()); gpx.addPositions(Context.getDataManager().getPositions( deviceId, DateUtil.parseDate(from), DateUtil.parseDate(to))); return Response.ok(gpx.build()).header(HttpHeaders.CONTENT_DISPOSITION, CONTENT_DISPOSITION_VALUE_GPX).build(); diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index 9998ed346..deb2dd2b4 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -58,7 +58,7 @@ public class UserResource extends BaseResource { } else { throw new SecurityException("Admin or manager access required"); } - return usersManager.getItems(User.class, result); + return usersManager.getItems(result); } @PermitAll diff --git a/src/org/traccar/database/AttributesManager.java b/src/org/traccar/database/AttributesManager.java index e80d57c4e..28816645a 100644 --- a/src/org/traccar/database/AttributesManager.java +++ b/src/org/traccar/database/AttributesManager.java @@ -17,23 +17,16 @@ package org.traccar.database; import org.traccar.model.Attribute; -import org.traccar.model.BaseModel; -public class AttributesManager extends ExtendedObjectManager { +public class AttributesManager extends ExtendedObjectManager { public AttributesManager(DataManager dataManager) { super(dataManager, Attribute.class); } @Override - public Attribute getById(long calendarId) { - return (Attribute) super.getById(calendarId); - } - - @Override - public void updateCachedItem(BaseModel item) { - Attribute attribute = (Attribute) item; - Attribute cachedAttribute = getById(item.getId()); + public void updateCachedItem(Attribute attribute) { + Attribute cachedAttribute = getById(attribute.getId()); cachedAttribute.setDescription(attribute.getDescription()); cachedAttribute.setAttribute(attribute.getAttribute()); cachedAttribute.setExpression(attribute.getExpression()); diff --git a/src/org/traccar/database/BaseObjectManager.java b/src/org/traccar/database/BaseObjectManager.java index 92cfd9b6b..cc1dbde5f 100644 --- a/src/org/traccar/database/BaseObjectManager.java +++ b/src/org/traccar/database/BaseObjectManager.java @@ -27,14 +27,14 @@ import java.util.concurrent.ConcurrentHashMap; import org.traccar.helper.Log; import org.traccar.model.BaseModel; -public class BaseObjectManager { +public class BaseObjectManager { private final DataManager dataManager; - private Map items; - private Class baseClass; + private Map items; + private Class baseClass; - protected BaseObjectManager(DataManager dataManager, Class baseClass) { + protected BaseObjectManager(DataManager dataManager, Class baseClass) { this.dataManager = dataManager; this.baseClass = baseClass; refreshItems(); @@ -44,23 +44,23 @@ public class BaseObjectManager { return dataManager; } - protected final Class getBaseClass() { + protected final Class getBaseClass() { return baseClass; } - public BaseModel getById(long itemId) { + public T getById(long itemId) { return items.get(itemId); } public void refreshItems() { if (dataManager != null) { try { - Collection databaseItems = dataManager.getObjects(baseClass); + Collection databaseItems = dataManager.getObjects(baseClass); if (items == null) { items = new ConcurrentHashMap<>(databaseItems.size()); } Set databaseItemIds = new HashSet<>(); - for (BaseModel item : databaseItems) { + for (T item : databaseItems) { databaseItemIds.add(item.getId()); if (items.containsKey(item.getId())) { updateCachedItem(item); @@ -79,20 +79,20 @@ public class BaseObjectManager { } } - protected void addNewItem(BaseModel item) { + protected void addNewItem(T item) { items.put(item.getId(), item); } - public void addItem(BaseModel item) throws SQLException { + public void addItem(T item) throws SQLException { dataManager.addObject(item); addNewItem(item); } - protected void updateCachedItem(BaseModel item) { + protected void updateCachedItem(T item) { items.put(item.getId(), item); } - public void updateItem(BaseModel item) throws SQLException { + public void updateItem(T item) throws SQLException { dataManager.updateObject(item); updateCachedItem(item); } @@ -109,10 +109,10 @@ public class BaseObjectManager { } } - public final Collection getItems(Class clazz, Set itemIds) { + public final Collection getItems(Set itemIds) { Collection result = new LinkedList<>(); for (long itemId : itemIds) { - result.add((T) getById(itemId)); + result.add(getById(itemId)); } return result; } diff --git a/src/org/traccar/database/CalendarManager.java b/src/org/traccar/database/CalendarManager.java index b8d0914ee..44ced1082 100644 --- a/src/org/traccar/database/CalendarManager.java +++ b/src/org/traccar/database/CalendarManager.java @@ -18,15 +18,10 @@ package org.traccar.database; import org.traccar.model.Calendar; -public class CalendarManager extends SimpleObjectManager { +public class CalendarManager extends SimpleObjectManager { public CalendarManager(DataManager dataManager) { super(dataManager, Calendar.class); } - @Override - public Calendar getById(long calendarId) { - return (Calendar) super.getById(calendarId); - } - } diff --git a/src/org/traccar/database/ConnectionManager.java b/src/org/traccar/database/ConnectionManager.java index 0baafb578..1445fb785 100644 --- a/src/org/traccar/database/ConnectionManager.java +++ b/src/org/traccar/database/ConnectionManager.java @@ -70,7 +70,7 @@ public class ConnectionManager { } public void updateDevice(final long deviceId, String status, Date time) { - Device device = Context.getIdentityManager().getDeviceById(deviceId); + Device device = Context.getIdentityManager().getById(deviceId); if (device == null) { return; } diff --git a/src/org/traccar/database/DeviceManager.java b/src/org/traccar/database/DeviceManager.java index 1fe7ddfa5..4aafe6631 100644 --- a/src/org/traccar/database/DeviceManager.java +++ b/src/org/traccar/database/DeviceManager.java @@ -30,7 +30,6 @@ import org.traccar.BaseProtocol; import org.traccar.Config; import org.traccar.Context; import org.traccar.helper.Log; -import org.traccar.model.BaseModel; import org.traccar.model.Command; import org.traccar.model.CommandType; import org.traccar.model.Device; @@ -39,7 +38,7 @@ import org.traccar.model.Group; import org.traccar.model.Position; import org.traccar.model.Server; -public class DeviceManager extends BaseObjectManager implements IdentityManager, ManagableObjects { +public class DeviceManager extends BaseObjectManager implements IdentityManager, ManagableObjects { public static final long DEFAULT_REFRESH_DELAY = 300; @@ -73,12 +72,7 @@ public class DeviceManager extends BaseObjectManager implements IdentityManager, } @Override - public Device getDeviceById(long id) { - return (Device) getById(id); - } - - @Override - public Device getDeviceByUniqueId(String uniqueId) throws SQLException { + public Device getByUniqueId(String uniqueId) throws SQLException { boolean forceUpdate = !devicesByUniqueId.containsKey(uniqueId) && !config.getBoolean("database.ignoreUnknown"); updateDeviceCache(forceUpdate); @@ -105,7 +99,7 @@ public class DeviceManager extends BaseObjectManager implements IdentityManager, } public Collection getAllDevices() { - return getItems(Device.class, getAllItems()); + return getItems(getAllItems()); } @Override @@ -142,9 +136,8 @@ public class DeviceManager extends BaseObjectManager implements IdentityManager, } @Override - protected void addNewItem(BaseModel item) { - super.addNewItem(item); - Device device = (Device) item; + protected void addNewItem(Device device) { + super.addNewItem(device); putUniqueDeviceId(device); if (device.getPhone() != null && !device.getPhone().isEmpty()) { putPhone(device); @@ -158,9 +151,8 @@ public class DeviceManager extends BaseObjectManager implements IdentityManager, } @Override - protected void updateCachedItem(BaseModel item) { - Device device = (Device) item; - Device cachedDevice = getDeviceById(device.getId()); + protected void updateCachedItem(Device device) { + Device cachedDevice = getById(device.getId()); cachedDevice.setName(device.getName()); cachedDevice.setGroupId(device.getGroupId()); cachedDevice.setCategory(device.getCategory()); @@ -182,7 +174,7 @@ public class DeviceManager extends BaseObjectManager implements IdentityManager, @Override protected void removeCachedItem(long deviceId) { - Device cachedDevice = getDeviceById(deviceId); + Device cachedDevice = getById(deviceId); if (cachedDevice != null) { String deviceUniqueId = cachedDevice.getUniqueId(); String phone = cachedDevice.getPhone(); @@ -197,7 +189,7 @@ public class DeviceManager extends BaseObjectManager implements IdentityManager, public void updateDeviceStatus(Device device) throws SQLException { getDataManager().updateDeviceStatus(device); - Device cachedDevice = getDeviceById(device.getId()); + Device cachedDevice = getById(device.getId()); if (cachedDevice != null) { cachedDevice.setStatus(device.getStatus()); } @@ -226,7 +218,7 @@ public class DeviceManager extends BaseObjectManager implements IdentityManager, getDataManager().updateLatestPosition(position); - Device device = getDeviceById(position.getDeviceId()); + Device device = getById(position.getDeviceId()); if (device != null) { device.setPositionId(position.getId()); } @@ -305,7 +297,7 @@ public class DeviceManager extends BaseObjectManager implements IdentityManager, private String lookupAttribute(long deviceId, String attributeName, boolean lookupConfig) { String result = null; - Device device = getDeviceById(deviceId); + Device device = getById(deviceId); if (device != null) { result = device.getString(attributeName); if (result == null && lookupGroupsAttribute) { @@ -352,9 +344,9 @@ public class DeviceManager extends BaseObjectManager implements IdentityManager, Position lastPosition = getLastPosition(deviceId); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); - protocol.sendTextCommand(getDeviceById(deviceId).getPhone(), command); + protocol.sendTextCommand(getById(deviceId).getPhone(), command); } else if (command.getType().equals(Command.TYPE_CUSTOM)) { - Context.getSmppManager().sendMessageSync(((Device) getById(deviceId)).getPhone(), + Context.getSmppManager().sendMessageSync(getById(deviceId).getPhone(), command.getString(Command.KEY_DATA), true); } else { throw new RuntimeException("Command " + command.getType() + " is not supported"); diff --git a/src/org/traccar/database/DriversManager.java b/src/org/traccar/database/DriversManager.java index 420824dbb..d3866a5f0 100644 --- a/src/org/traccar/database/DriversManager.java +++ b/src/org/traccar/database/DriversManager.java @@ -20,37 +20,30 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.traccar.model.Driver; -import org.traccar.model.BaseModel; -public class DriversManager extends ExtendedObjectManager { +public class DriversManager extends ExtendedObjectManager { - private Map driversByUniqueId; + private Map driversByUniqueId; public DriversManager(DataManager dataManager) { super(dataManager, Driver.class); } - @Override - public Driver getById(long driverId) { - return (Driver) super.getById(driverId); - } - private void putUniqueDriverId(Driver driver) { if (driversByUniqueId == null) { - driversByUniqueId = new ConcurrentHashMap<>(); + driversByUniqueId = new ConcurrentHashMap<>(getAllItems().size()); } - driversByUniqueId.put(driver.getUniqueId(), driver); + driversByUniqueId.put(driver.getUniqueId(), driver.getId()); } @Override - protected void addNewItem(BaseModel item) { - super.addNewItem(item); - putUniqueDriverId((Driver) item); + protected void addNewItem(Driver driver) { + super.addNewItem(driver); + putUniqueDriverId(driver); } @Override - protected void updateCachedItem(BaseModel item) { - Driver driver = (Driver) item; + protected void updateCachedItem(Driver driver) { Driver cachedDriver = getById(driver.getId()); cachedDriver.setName(driver.getName()); if (!driver.getUniqueId().equals(cachedDriver.getUniqueId())) { @@ -72,6 +65,6 @@ public class DriversManager extends ExtendedObjectManager { } public Driver getDriverByUniqueId(String uniqueId) { - return driversByUniqueId.get(uniqueId); + return getById(driversByUniqueId.get(uniqueId)); } } diff --git a/src/org/traccar/database/ExtendedObjectManager.java b/src/org/traccar/database/ExtendedObjectManager.java index 19c9ca5b2..16785cb37 100644 --- a/src/org/traccar/database/ExtendedObjectManager.java +++ b/src/org/traccar/database/ExtendedObjectManager.java @@ -30,13 +30,13 @@ import org.traccar.model.Group; import org.traccar.model.Permission; import org.traccar.model.BaseModel; -public abstract class ExtendedObjectManager extends SimpleObjectManager { +public abstract class ExtendedObjectManager extends SimpleObjectManager { private final Map> deviceItems = new ConcurrentHashMap<>(); private final Map> deviceItemsWithGroups = new ConcurrentHashMap<>(); private final Map> groupItems = new ConcurrentHashMap<>(); - protected ExtendedObjectManager(DataManager dataManager, Class baseClass) { + protected ExtendedObjectManager(DataManager dataManager, Class baseClass) { super(dataManager, baseClass); refreshExtendedPermissions(); } diff --git a/src/org/traccar/database/GeofenceManager.java b/src/org/traccar/database/GeofenceManager.java index 4bc3909cd..a32847cf9 100644 --- a/src/org/traccar/database/GeofenceManager.java +++ b/src/org/traccar/database/GeofenceManager.java @@ -23,17 +23,12 @@ import org.traccar.model.Device; import org.traccar.model.Geofence; import org.traccar.model.Position; -public class GeofenceManager extends ExtendedObjectManager { +public class GeofenceManager extends ExtendedObjectManager { public GeofenceManager(DataManager dataManager) { super(dataManager, Geofence.class); } - @Override - public Geofence getById(long geofenceId) { - return (Geofence) super.getById(geofenceId); - } - @Override public final void refreshExtendedPermissions() { super.refreshExtendedPermissions(); diff --git a/src/org/traccar/database/GroupsManager.java b/src/org/traccar/database/GroupsManager.java index 095e7a22c..20b403d55 100644 --- a/src/org/traccar/database/GroupsManager.java +++ b/src/org/traccar/database/GroupsManager.java @@ -26,7 +26,7 @@ import org.traccar.helper.Log; import org.traccar.model.BaseModel; import org.traccar.model.Group; -public class GroupsManager extends BaseObjectManager implements ManagableObjects { +public class GroupsManager extends BaseObjectManager implements ManagableObjects { private AtomicLong groupsLastUpdate = new AtomicLong(); private final long dataRefreshDelay; @@ -37,11 +37,6 @@ public class GroupsManager extends BaseObjectManager implements ManagableObjects DeviceManager.DEFAULT_REFRESH_DELAY) * 1000; } - @Override - public Group getById(long groupId) { - return (Group) super.getById(groupId); - } - private void checkGroupCycles(BaseModel group) { Set groups = new HashSet<>(); while (group != null) { @@ -76,15 +71,15 @@ public class GroupsManager extends BaseObjectManager implements ManagableObjects } @Override - protected void addNewItem(BaseModel item) { - checkGroupCycles(item); - super.addNewItem(item); + protected void addNewItem(Group group) { + checkGroupCycles(group); + super.addNewItem(group); } @Override - protected void updateCachedItem(BaseModel item) { - checkGroupCycles(item); - super.updateCachedItem(item); + protected void updateCachedItem(Group group) { + checkGroupCycles(group); + super.updateCachedItem(group); } @Override diff --git a/src/org/traccar/database/IdentityManager.java b/src/org/traccar/database/IdentityManager.java index c8c593a54..82d905963 100644 --- a/src/org/traccar/database/IdentityManager.java +++ b/src/org/traccar/database/IdentityManager.java @@ -20,9 +20,9 @@ import org.traccar.model.Position; public interface IdentityManager { - Device getDeviceById(long id); + Device getById(long id); - Device getDeviceByUniqueId(String uniqueId) throws Exception; + Device getByUniqueId(String uniqueId) throws Exception; Position getLastPosition(long deviceId); diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 54e5ed979..3b03c1900 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -18,6 +18,7 @@ package org.traccar.database; import org.traccar.Context; import org.traccar.helper.Log; import org.traccar.model.Attribute; +import org.traccar.model.BaseModel; import org.traccar.model.Calendar; import org.traccar.model.Device; import org.traccar.model.Driver; @@ -99,7 +100,7 @@ public class PermissionsManager { devicePermissions.clear(); try { GroupTree groupTree = new GroupTree(Context.getGroupsManager().getItems( - Group.class, Context.getGroupsManager().getAllItems()), + Context.getGroupsManager().getAllItems()), Context.getDeviceManager().getAllDevices()); for (Permission groupPermission : dataManager.getPermissions(User.class, Group.class)) { Set userGroupPermissions = getGroupPermissions(groupPermission.getOwnerId()); @@ -284,7 +285,7 @@ public class PermissionsManager { public void checkPermission(Class object, long userId, long objectId) throws SecurityException { - SimpleObjectManager manager = null; + SimpleObjectManager manager = null; if (object.equals(Device.class)) { checkDevice(userId, objectId); diff --git a/src/org/traccar/database/SimpleObjectManager.java b/src/org/traccar/database/SimpleObjectManager.java index fa41f30b6..0b4d11378 100644 --- a/src/org/traccar/database/SimpleObjectManager.java +++ b/src/org/traccar/database/SimpleObjectManager.java @@ -28,11 +28,12 @@ import org.traccar.model.BaseModel; import org.traccar.model.Permission; import org.traccar.model.User; -public abstract class SimpleObjectManager extends BaseObjectManager implements ManagableObjects { +public abstract class SimpleObjectManager extends BaseObjectManager + implements ManagableObjects { private Map> userItems; - protected SimpleObjectManager(DataManager dataManager, Class baseClass) { + protected SimpleObjectManager(DataManager dataManager, Class baseClass) { super(dataManager, baseClass); } diff --git a/src/org/traccar/database/UsersManager.java b/src/org/traccar/database/UsersManager.java index e53409b4f..28e6a31b2 100644 --- a/src/org/traccar/database/UsersManager.java +++ b/src/org/traccar/database/UsersManager.java @@ -21,10 +21,9 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import org.traccar.model.BaseModel; import org.traccar.model.User; -public class UsersManager extends SimpleObjectManager { +public class UsersManager extends SimpleObjectManager { private Map usersTokens; @@ -32,11 +31,6 @@ public class UsersManager extends SimpleObjectManager { super(dataManager, User.class); } - @Override - public User getById(long userId) { - return (User) super.getById(userId); - } - private void putToken(User user) { if (usersTokens == null) { usersTokens = new ConcurrentHashMap<>(); @@ -47,16 +41,15 @@ public class UsersManager extends SimpleObjectManager { } @Override - protected void addNewItem(BaseModel item) { - super.addNewItem(item); - putToken((User) item); + protected void addNewItem(User user) { + super.addNewItem(user); + putToken(user); } @Override - protected void updateCachedItem(BaseModel item) { - User user = (User) item; - User cachedUser = getById(item.getId()); - super.updateCachedItem(item); + protected void updateCachedItem(User user) { + User cachedUser = getById(user.getId()); + super.updateCachedItem(user); if (user.getToken() != null) { usersTokens.put(user.getToken(), user.getId()); } diff --git a/src/org/traccar/events/FuelDropEventHandler.java b/src/org/traccar/events/FuelDropEventHandler.java index e9a261aea..4e09bd4fa 100644 --- a/src/org/traccar/events/FuelDropEventHandler.java +++ b/src/org/traccar/events/FuelDropEventHandler.java @@ -31,7 +31,7 @@ public class FuelDropEventHandler extends BaseEventHandler { @Override protected Collection analyzePosition(Position position) { - Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); + Device device = Context.getIdentityManager().getById(position.getDeviceId()); if (device == null) { return null; } diff --git a/src/org/traccar/events/GeofenceEventHandler.java b/src/org/traccar/events/GeofenceEventHandler.java index 516df9d69..79e5d0f8e 100644 --- a/src/org/traccar/events/GeofenceEventHandler.java +++ b/src/org/traccar/events/GeofenceEventHandler.java @@ -25,7 +25,6 @@ import org.traccar.database.GeofenceManager; import org.traccar.model.Calendar; import org.traccar.model.Device; import org.traccar.model.Event; -import org.traccar.model.Geofence; import org.traccar.model.Position; public class GeofenceEventHandler extends BaseEventHandler { @@ -38,7 +37,7 @@ public class GeofenceEventHandler extends BaseEventHandler { @Override protected Collection analyzePosition(Position position) { - Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); + Device device = Context.getIdentityManager().getById(position.getDeviceId()); if (device == null) { return null; } @@ -59,8 +58,8 @@ public class GeofenceEventHandler extends BaseEventHandler { Collection events = new ArrayList<>(); for (long geofenceId : newGeofences) { - long calendarId = ((Geofence) geofenceManager.getById(geofenceId)).getCalendarId(); - Calendar calendar = calendarId != 0 ? (Calendar) Context.getCalendarManager().getById(calendarId) : null; + long calendarId = geofenceManager.getById(geofenceId).getCalendarId(); + Calendar calendar = calendarId != 0 ? Context.getCalendarManager().getById(calendarId) : null; if (calendar == null || calendar.checkMoment(position.getFixTime())) { Event event = new Event(Event.TYPE_GEOFENCE_ENTER, position.getDeviceId(), position.getId()); event.setGeofenceId(geofenceId); @@ -68,8 +67,8 @@ public class GeofenceEventHandler extends BaseEventHandler { } } for (long geofenceId : oldGeofences) { - long calendarId = ((Geofence) geofenceManager.getById(geofenceId)).getCalendarId(); - Calendar calendar = calendarId != 0 ? (Calendar) Context.getCalendarManager().getById(calendarId) : null; + long calendarId = geofenceManager.getById(geofenceId).getCalendarId(); + Calendar calendar = calendarId != 0 ? Context.getCalendarManager().getById(calendarId) : null; if (calendar == null || calendar.checkMoment(position.getFixTime())) { Event event = new Event(Event.TYPE_GEOFENCE_EXIT, position.getDeviceId(), position.getId()); event.setGeofenceId(geofenceId); diff --git a/src/org/traccar/events/IgnitionEventHandler.java b/src/org/traccar/events/IgnitionEventHandler.java index c628cc107..5519135bf 100644 --- a/src/org/traccar/events/IgnitionEventHandler.java +++ b/src/org/traccar/events/IgnitionEventHandler.java @@ -29,7 +29,7 @@ public class IgnitionEventHandler extends BaseEventHandler { @Override protected Collection analyzePosition(Position position) { - Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); + Device device = Context.getIdentityManager().getById(position.getDeviceId()); if (device == null || !Context.getIdentityManager().isLatestPosition(position)) { return null; } diff --git a/src/org/traccar/events/MaintenanceEventHandler.java b/src/org/traccar/events/MaintenanceEventHandler.java index 86836f6af..ffeefc8c5 100644 --- a/src/org/traccar/events/MaintenanceEventHandler.java +++ b/src/org/traccar/events/MaintenanceEventHandler.java @@ -32,7 +32,7 @@ public class MaintenanceEventHandler extends BaseEventHandler { @Override protected Collection analyzePosition(Position position) { - Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); + Device device = Context.getIdentityManager().getById(position.getDeviceId()); if (device == null || !Context.getIdentityManager().isLatestPosition(position)) { return null; } diff --git a/src/org/traccar/events/MotionEventHandler.java b/src/org/traccar/events/MotionEventHandler.java index e6fd10f3e..ed81176a8 100644 --- a/src/org/traccar/events/MotionEventHandler.java +++ b/src/org/traccar/events/MotionEventHandler.java @@ -29,7 +29,7 @@ public class MotionEventHandler extends BaseEventHandler { @Override protected Collection analyzePosition(Position position) { - Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); + Device device = Context.getIdentityManager().getById(position.getDeviceId()); if (device == null) { return null; } diff --git a/src/org/traccar/events/OverspeedEventHandler.java b/src/org/traccar/events/OverspeedEventHandler.java index 00c3845d2..795892f40 100644 --- a/src/org/traccar/events/OverspeedEventHandler.java +++ b/src/org/traccar/events/OverspeedEventHandler.java @@ -37,7 +37,7 @@ public class OverspeedEventHandler extends BaseEventHandler { @Override protected Collection analyzePosition(Position position) { - Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); + Device device = Context.getIdentityManager().getById(position.getDeviceId()); if (device == null) { return null; } diff --git a/src/org/traccar/notification/EventForwarder.java b/src/org/traccar/notification/EventForwarder.java index 08f55df75..ac37f980c 100644 --- a/src/org/traccar/notification/EventForwarder.java +++ b/src/org/traccar/notification/EventForwarder.java @@ -69,7 +69,7 @@ public final class EventForwarder { data.put(KEY_POSITION, position); } if (event.getDeviceId() != 0) { - Device device = Context.getIdentityManager().getDeviceById(event.getDeviceId()); + Device device = Context.getIdentityManager().getById(event.getDeviceId()); if (device != null) { data.put(KEY_DEVICE, device); } diff --git a/src/org/traccar/notification/NotificationFormatter.java b/src/org/traccar/notification/NotificationFormatter.java index cd9959671..33fd2cdc7 100644 --- a/src/org/traccar/notification/NotificationFormatter.java +++ b/src/org/traccar/notification/NotificationFormatter.java @@ -40,7 +40,7 @@ public final class NotificationFormatter { public static VelocityContext prepareContext(long userId, Event event, Position position) { User user = Context.getPermissionsManager().getUser(userId); - Device device = Context.getIdentityManager().getDeviceById(event.getDeviceId()); + Device device = Context.getIdentityManager().getById(event.getDeviceId()); VelocityContext velocityContext = new VelocityContext(); velocityContext.put("user", user); diff --git a/src/org/traccar/processing/ComputedAttributesHandler.java b/src/org/traccar/processing/ComputedAttributesHandler.java index d6a762535..f1f371475 100644 --- a/src/org/traccar/processing/ComputedAttributesHandler.java +++ b/src/org/traccar/processing/ComputedAttributesHandler.java @@ -51,7 +51,7 @@ public class ComputedAttributesHandler extends BaseDataHandler { private MapContext prepareContext(Position position) { MapContext result = new MapContext(); if (mapDeviceAttributes) { - Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); + Device device = Context.getIdentityManager().getById(position.getDeviceId()); if (device != null) { for (Object key : device.getAttributes().keySet()) { result.set((String) key, device.getAttributes().get(key)); @@ -86,7 +86,7 @@ public class ComputedAttributesHandler extends BaseDataHandler { @Override protected Position handlePosition(Position position) { - Collection attributes = Context.getAttributesManager().getItems(Attribute.class, + Collection attributes = Context.getAttributesManager().getItems( Context.getAttributesManager().getAllDeviceItems(position.getDeviceId())); for (Attribute attribute : attributes) { if (attribute.getAttribute() != null) { diff --git a/src/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/org/traccar/protocol/Gt06ProtocolDecoder.java index 36358b6e5..186867b9d 100644 --- a/src/org/traccar/protocol/Gt06ProtocolDecoder.java +++ b/src/org/traccar/protocol/Gt06ProtocolDecoder.java @@ -555,7 +555,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { if (photo.writableBytes() > 0) { sendPhotoRequest(channel, pictureId); } else { - Device device = Context.getDeviceManager().getDeviceById(deviceSession.getDeviceId()); + Device device = Context.getDeviceManager().getById(deviceSession.getDeviceId()); Context.getMediaManager().writeFile(device.getUniqueId(), photo, "jpg"); photos.remove(pictureId); } diff --git a/src/org/traccar/protocol/MeitrackProtocolDecoder.java b/src/org/traccar/protocol/MeitrackProtocolDecoder.java index 711697fc4..469ef3f76 100644 --- a/src/org/traccar/protocol/MeitrackProtocolDecoder.java +++ b/src/org/traccar/protocol/MeitrackProtocolDecoder.java @@ -160,7 +160,7 @@ public class MeitrackProtocolDecoder extends BaseProtocolDecoder { } } - String deviceModel = Context.getIdentityManager().getDeviceById(deviceSession.getDeviceId()).getModel(); + String deviceModel = Context.getIdentityManager().getById(deviceSession.getDeviceId()).getModel(); if (deviceModel == null) { deviceModel = ""; } @@ -316,7 +316,7 @@ public class MeitrackProtocolDecoder extends BaseProtocolDecoder { case "D03": if (channel != null) { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); - String imei = Context.getIdentityManager().getDeviceById(deviceSession.getDeviceId()).getUniqueId(); + String imei = Context.getIdentityManager().getById(deviceSession.getDeviceId()).getUniqueId(); channel.write("@@O46," + imei + ",D00,camera_picture.jpg,0*00\r\n"); } return null; diff --git a/src/org/traccar/reports/Events.java b/src/org/traccar/reports/Events.java index 348e6077f..63077de32 100644 --- a/src/org/traccar/reports/Events.java +++ b/src/org/traccar/reports/Events.java @@ -88,7 +88,7 @@ public final class Events { } } DeviceReport deviceEvents = new DeviceReport(); - Device device = Context.getIdentityManager().getDeviceById(deviceId); + Device device = Context.getIdentityManager().getById(deviceId); deviceEvents.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceEvents.getDeviceName())); if (device.getGroupId() != 0) { diff --git a/src/org/traccar/reports/ReportUtils.java b/src/org/traccar/reports/ReportUtils.java index bc58d28df..cf94030ab 100644 --- a/src/org/traccar/reports/ReportUtils.java +++ b/src/org/traccar/reports/ReportUtils.java @@ -176,7 +176,7 @@ public final class ReportUtils { long tripDuration = endTrip.getFixTime().getTime() - startTrip.getFixTime().getTime(); long deviceId = startTrip.getDeviceId(); trip.setDeviceId(deviceId); - trip.setDeviceName(Context.getIdentityManager().getDeviceById(deviceId).getName()); + trip.setDeviceName(Context.getIdentityManager().getById(deviceId).getName()); trip.setStartPositionId(startTrip.getId()); trip.setStartLat(startTrip.getLatitude()); @@ -210,7 +210,7 @@ public final class ReportUtils { long deviceId = startStop.getDeviceId(); stop.setDeviceId(deviceId); - stop.setDeviceName(Context.getIdentityManager().getDeviceById(deviceId).getName()); + stop.setDeviceName(Context.getIdentityManager().getById(deviceId).getName()); stop.setPositionId(startStop.getId()); stop.setLatitude(startStop.getLatitude()); diff --git a/src/org/traccar/reports/Route.java b/src/org/traccar/reports/Route.java index 69be55155..1c53a15cc 100644 --- a/src/org/traccar/reports/Route.java +++ b/src/org/traccar/reports/Route.java @@ -57,7 +57,7 @@ public final class Route { Collection positions = Context.getDataManager() .getPositions(deviceId, from, to); DeviceReport deviceRoutes = new DeviceReport(); - Device device = Context.getIdentityManager().getDeviceById(deviceId); + Device device = Context.getIdentityManager().getById(deviceId); deviceRoutes.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceRoutes.getDeviceName())); if (device.getGroupId() != 0) { diff --git a/src/org/traccar/reports/Stops.java b/src/org/traccar/reports/Stops.java index 20a6c1ce3..886fd7915 100644 --- a/src/org/traccar/reports/Stops.java +++ b/src/org/traccar/reports/Stops.java @@ -74,7 +74,7 @@ public final class Stops { Context.getPermissionsManager().checkDevice(userId, deviceId); Collection stops = detectStops(deviceId, from, to); DeviceReport deviceStops = new DeviceReport(); - Device device = Context.getIdentityManager().getDeviceById(deviceId); + Device device = Context.getIdentityManager().getById(deviceId); deviceStops.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceStops.getDeviceName())); if (device.getGroupId() != 0) { diff --git a/src/org/traccar/reports/Summary.java b/src/org/traccar/reports/Summary.java index 5aaf33fae..dd9877cd7 100644 --- a/src/org/traccar/reports/Summary.java +++ b/src/org/traccar/reports/Summary.java @@ -38,7 +38,7 @@ public final class Summary { private static SummaryReport calculateSummaryResult(long deviceId, Date from, Date to) throws SQLException { SummaryReport result = new SummaryReport(); result.setDeviceId(deviceId); - result.setDeviceName(Context.getIdentityManager().getDeviceById(deviceId).getName()); + result.setDeviceName(Context.getIdentityManager().getById(deviceId).getName()); Collection positions = Context.getDataManager().getPositions(deviceId, from, to); if (positions != null && !positions.isEmpty()) { Position firstPosition = null; diff --git a/src/org/traccar/reports/Trips.java b/src/org/traccar/reports/Trips.java index 7b5df0248..68b03a819 100644 --- a/src/org/traccar/reports/Trips.java +++ b/src/org/traccar/reports/Trips.java @@ -73,7 +73,7 @@ public final class Trips { Context.getPermissionsManager().checkDevice(userId, deviceId); Collection trips = detectTrips(deviceId, from, to); DeviceReport deviceTrips = new DeviceReport(); - Device device = Context.getIdentityManager().getDeviceById(deviceId); + Device device = Context.getIdentityManager().getById(deviceId); deviceTrips.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceTrips.getDeviceName())); if (device.getGroupId() != 0) { diff --git a/test/org/traccar/BaseTest.java b/test/org/traccar/BaseTest.java index 6af8610cd..37956f11d 100644 --- a/test/org/traccar/BaseTest.java +++ b/test/org/traccar/BaseTest.java @@ -18,12 +18,12 @@ public class BaseTest { } @Override - public Device getDeviceById(long id) { + public Device getById(long id) { return createDevice(); } @Override - public Device getDeviceByUniqueId(String uniqueId) { + public Device getByUniqueId(String uniqueId) { return createDevice(); } -- cgit v1.2.3 From e8a758072e9368f6977880e1aa607351d7cf619a Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Thu, 27 Jul 2017 13:16:59 +0500 Subject: Implement BaseObjectResource generic and combine PUT/POST/DELETE functions --- src/org/traccar/Context.java | 28 +++++ src/org/traccar/api/BaseObjectResource.java | 126 +++++++++++++++++++++ .../traccar/api/resource/AttributeResource.java | 53 ++------- src/org/traccar/api/resource/CalendarResource.java | 40 +------ src/org/traccar/api/resource/DeviceResource.java | 49 +------- src/org/traccar/api/resource/DriverResource.java | 41 +------ src/org/traccar/api/resource/GeofenceResource.java | 43 +------ src/org/traccar/api/resource/GroupResource.java | 47 +------- src/org/traccar/api/resource/UserResource.java | 37 ++---- 9 files changed, 201 insertions(+), 263 deletions(-) create mode 100644 src/org/traccar/api/BaseObjectResource.java (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index dfb8c5f47..75a7d179b 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -28,6 +28,7 @@ import org.eclipse.jetty.util.URIUtil; import org.traccar.database.AliasesManager; import org.traccar.database.CalendarManager; import org.traccar.database.AttributesManager; +import org.traccar.database.BaseObjectManager; import org.traccar.database.ConnectionManager; import org.traccar.database.DataManager; import org.traccar.database.DeviceManager; @@ -51,6 +52,14 @@ import org.traccar.geocoder.OpenCageGeocoder; import org.traccar.geocoder.Geocoder; import org.traccar.geolocation.UnwiredGeolocationProvider; import org.traccar.helper.Log; +import org.traccar.model.Attribute; +import org.traccar.model.BaseModel; +import org.traccar.model.Calendar; +import org.traccar.model.Device; +import org.traccar.model.Driver; +import org.traccar.model.Geofence; +import org.traccar.model.Group; +import org.traccar.model.User; import org.traccar.geolocation.GoogleGeolocationProvider; import org.traccar.geolocation.GeolocationProvider; import org.traccar.geolocation.MozillaGeolocationProvider; @@ -369,4 +378,23 @@ public final class Context { identityManager = testIdentityManager; } + public static BaseObjectManager getManager(Class clazz) { + if (clazz.equals(Device.class)) { + return (BaseObjectManager) deviceManager; + } else if (clazz.equals(Group.class)) { + return (BaseObjectManager) groupsManager; + } else if (clazz.equals(User.class)) { + return (BaseObjectManager) usersManager; + } else if (clazz.equals(Calendar.class)) { + return (BaseObjectManager) calendarManager; + } else if (clazz.equals(Attribute.class)) { + return (BaseObjectManager) attributesManager; + } else if (clazz.equals(Geofence.class)) { + return (BaseObjectManager) geofenceManager; + } else if (clazz.equals(Driver.class)) { + return (BaseObjectManager) driversManager; + } + return null; + } + } diff --git a/src/org/traccar/api/BaseObjectResource.java b/src/org/traccar/api/BaseObjectResource.java new file mode 100644 index 000000000..11e9a5d01 --- /dev/null +++ b/src/org/traccar/api/BaseObjectResource.java @@ -0,0 +1,126 @@ +/* + * 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; + +import java.sql.SQLException; + +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; + +import org.traccar.Context; +import org.traccar.database.BaseObjectManager; +import org.traccar.database.ExtendedObjectManager; +import org.traccar.database.SimpleObjectManager; +import org.traccar.model.BaseModel; +import org.traccar.model.Device; +import org.traccar.model.Group; +import org.traccar.model.User; + +public class BaseObjectResource extends BaseResource { + + private Class baseClass; + + public BaseObjectResource(Class baseClass) { + this.baseClass = baseClass; + } + + @POST + public Response add(T entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + if (baseClass.equals(Device.class)) { + Context.getPermissionsManager().checkDeviceReadonly(getUserId()); + Context.getPermissionsManager().checkDeviceLimit(getUserId()); + } + + BaseObjectManager manager = Context.getManager(baseClass); + manager.addItem(entity); + + Context.getDataManager().linkObject(User.class, getUserId(), baseClass, entity.getId(), true); + + if (manager instanceof SimpleObjectManager) { + ((SimpleObjectManager) manager).refreshUserItems(); + } + if (baseClass.equals(Group.class) || baseClass.equals(Device.class)) { + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); + Context.getPermissionsManager().refreshAllExtendedPermissions(); + } + return Response.ok(entity).build(); + } + + @Path("{id}") + @PUT + public Response update(T entity) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + if (baseClass.equals(Device.class)) { + Context.getPermissionsManager().checkDeviceReadonly(getUserId()); + } + if (baseClass.equals(User.class)) { + User before = Context.getPermissionsManager().getUser(entity.getId()); + Context.getPermissionsManager().checkUserUpdate(getUserId(), before, (User) entity); + } + Context.getPermissionsManager().checkPermission(baseClass, getUserId(), entity.getId()); + + Context.getManager(baseClass).updateItem(entity); + + if (baseClass.equals(Group.class) || baseClass.equals(Device.class)) { + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); + Context.getPermissionsManager().refreshAllExtendedPermissions(); + } + if (baseClass.equals(User.class) && Context.getNotificationManager() != null) { + Context.getNotificationManager().refresh(); + } + return Response.ok(entity).build(); + } + + @Path("{id}") + @DELETE + public Response remove(@PathParam("id") long id) throws SQLException { + Context.getPermissionsManager().checkReadonly(getUserId()); + if (baseClass.equals(Device.class)) { + Context.getPermissionsManager().checkDeviceReadonly(getUserId()); + } + Context.getPermissionsManager().checkPermission(baseClass, getUserId(), id); + + BaseObjectManager manager = Context.getManager(baseClass); + manager.removeItem(id); + + if (manager instanceof SimpleObjectManager) { + ((SimpleObjectManager) manager).refreshUserItems(); + } + if (manager instanceof ExtendedObjectManager) { + ((ExtendedObjectManager) manager).refreshExtendedPermissions(); + } + if (baseClass.equals(Group.class) || baseClass.equals(Device.class) || baseClass.equals(User.class)) { + Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); + if (baseClass.equals(User.class)) { + Context.getPermissionsManager().refreshAllUsersPermissions(); + } else { + Context.getPermissionsManager().refreshAllExtendedPermissions(); + } + } + // deprecated + if (baseClass.equals(Device.class)) { + Context.getAliasesManager().removeDevice(id); + } + return Response.noContent().build(); + } + +} diff --git a/src/org/traccar/api/resource/AttributeResource.java b/src/org/traccar/api/resource/AttributeResource.java index c12fcd9e6..55fd39fc6 100644 --- a/src/org/traccar/api/resource/AttributeResource.java +++ b/src/org/traccar/api/resource/AttributeResource.java @@ -22,29 +22,29 @@ 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.api.BaseObjectResource; import org.traccar.database.AttributesManager; import org.traccar.model.Attribute; import org.traccar.model.Position; -import org.traccar.model.User; import org.traccar.processing.ComputedAttributesHandler; @Path("attributes/computed") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class AttributeResource extends BaseResource { +public class AttributeResource extends BaseObjectResource { + + public AttributeResource() { + super(Attribute.class); + } @GET public Collection get( @@ -85,15 +85,11 @@ public class AttributeResource extends BaseResource { } - private Response add(Attribute entity) throws SQLException { + @POST + @Path("test") + public Response test(@QueryParam("deviceId") long deviceId, Attribute entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getAttributesManager().addItem(entity); - Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); - Context.getAttributesManager().refreshUserItems(); - return Response.ok(entity).build(); - } - - private Response test(long deviceId, Attribute entity) { + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); Position last = Context.getIdentityManager().getLastPosition(deviceId); if (last != null) { Object result = new ComputedAttributesHandler().computeAttribute(entity, last); @@ -114,33 +110,4 @@ public class AttributeResource extends BaseResource { } } - @POST - public Response post(@QueryParam("deviceId") long deviceId, Attribute entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - if (deviceId != 0) { - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - return test(deviceId, entity); - } else { - return add(entity); - } - } - - @Path("{id}") - @PUT - public Response update(Attribute entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Attribute.class, getUserId(), entity.getId()); - Context.getAttributesManager().updateItem(entity); - return Response.ok(entity).build(); - } - - @Path("{id}") - @DELETE - public Response remove(@PathParam("id") long id) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Attribute.class, getUserId(), id); - Context.getAttributesManager().removeItem(id); - return Response.noContent().build(); - } - } diff --git a/src/org/traccar/api/resource/CalendarResource.java b/src/org/traccar/api/resource/CalendarResource.java index f8d78a847..d43a3b02e 100644 --- a/src/org/traccar/api/resource/CalendarResource.java +++ b/src/org/traccar/api/resource/CalendarResource.java @@ -21,27 +21,25 @@ import java.util.Collection; 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.api.BaseObjectResource; import org.traccar.database.CalendarManager; import org.traccar.model.Calendar; -import org.traccar.model.User; @Path("calendars") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class CalendarResource extends BaseResource { +public class CalendarResource extends BaseObjectResource { + + public CalendarResource() { + super(Calendar.class); + } @GET public Collection get( @@ -66,30 +64,4 @@ public class CalendarResource extends BaseResource { return calendarManager.getItems(result); } - @POST - public Response add(Calendar entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getCalendarManager().addItem(entity); - Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); - Context.getCalendarManager().refreshUserItems(); - return Response.ok(entity).build(); - } - - @Path("{id}") - @PUT - public Response update(Calendar entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Calendar.class, getUserId(), entity.getId()); - Context.getCalendarManager().updateItem(entity); - return Response.ok(entity).build(); - } - - @Path("{id}") - @DELETE - public Response remove(@PathParam("id") long id) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Calendar.class, getUserId(), id); - Context.getCalendarManager().removeItem(id); - return Response.noContent().build(); - } } diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index a473b7bde..1c2c653a4 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -16,19 +16,15 @@ package org.traccar.api.resource; import org.traccar.Context; -import org.traccar.api.BaseResource; +import org.traccar.api.BaseObjectResource; import org.traccar.database.DeviceManager; import org.traccar.model.Device; import org.traccar.model.DeviceTotalDistance; -import org.traccar.model.User; 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; @@ -43,7 +39,11 @@ import java.util.Set; @Path("devices") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class DeviceResource extends BaseResource { +public class DeviceResource extends BaseObjectResource { + + public DeviceResource() { + super(Device.class); + } @GET public Collection get( @@ -80,43 +80,6 @@ public class DeviceResource extends BaseResource { return deviceManager.getItems(result); } - @POST - public Response add(Device entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDeviceReadonly(getUserId()); - Context.getPermissionsManager().checkDeviceLimit(getUserId()); - Context.getDeviceManager().addItem(entity); - Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); - Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); - Context.getPermissionsManager().refreshAllExtendedPermissions(); - return Response.ok(entity).build(); - } - - @Path("{id}") - @PUT - public Response update(Device entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDeviceReadonly(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getId()); - Context.getDeviceManager().updateItem(entity); - Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); - Context.getPermissionsManager().refreshAllExtendedPermissions(); - return Response.ok(entity).build(); - } - - @Path("{id}") - @DELETE - public Response remove(@PathParam("id") long id) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDeviceReadonly(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), id); - Context.getDeviceManager().removeItem(id); - Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); - Context.getPermissionsManager().refreshAllExtendedPermissions(); - Context.getAliasesManager().removeDevice(id); - return Response.noContent().build(); - } - @Path("{id}/distance") @PUT public Response updateTotalDistance(DeviceTotalDistance entity) throws SQLException { diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index d44979998..185f4a0dc 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -22,27 +22,25 @@ 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.api.BaseObjectResource; import org.traccar.database.DriversManager; import org.traccar.model.Driver; -import org.traccar.model.User; @Path("drivers") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class DriverResource extends BaseResource { +public class DriverResource extends BaseObjectResource { + + public DriverResource() { + super(Driver.class); + } @GET public Collection get( @@ -83,31 +81,4 @@ public class DriverResource extends BaseResource { } - @POST - public Response add(Driver entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getDriversManager().addItem(entity); - Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); - Context.getDriversManager().refreshUserItems(); - return Response.ok(entity).build(); - } - - @Path("{id}") - @PUT - public Response update(Driver entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Driver.class, getUserId(), entity.getId()); - Context.getDriversManager().updateItem(entity); - return Response.ok(entity).build(); - } - - @Path("{id}") - @DELETE - public Response remove(@PathParam("id") long id) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Driver.class, getUserId(), id); - Context.getDriversManager().removeItem(id); - return Response.noContent().build(); - } - } diff --git a/src/org/traccar/api/resource/GeofenceResource.java b/src/org/traccar/api/resource/GeofenceResource.java index 9a110fbcf..d07810732 100644 --- a/src/org/traccar/api/resource/GeofenceResource.java +++ b/src/org/traccar/api/resource/GeofenceResource.java @@ -16,22 +16,16 @@ package org.traccar.api.resource; import org.traccar.Context; -import org.traccar.api.BaseResource; +import org.traccar.api.BaseObjectResource; import org.traccar.database.GeofenceManager; import org.traccar.model.Geofence; -import org.traccar.model.User; 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 java.sql.SQLException; import java.util.Collection; @@ -41,7 +35,11 @@ import java.util.Set; @Path("geofences") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class GeofenceResource extends BaseResource { +public class GeofenceResource extends BaseObjectResource { + + public GeofenceResource() { + super(Geofence.class); + } @GET public Collection get( @@ -79,34 +77,5 @@ public class GeofenceResource extends BaseResource { result.retainAll(geofenceManager.getDeviceItems(deviceId)); } return geofenceManager.getItems(result); - - } - - @POST - public Response add(Geofence entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getGeofenceManager().addItem(entity); - Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); - Context.getGeofenceManager().refreshUserItems(); - return Response.ok(entity).build(); } - - @Path("{id}") - @PUT - public Response update(Geofence entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Geofence.class, getUserId(), entity.getId()); - Context.getGeofenceManager().updateItem(entity); - return Response.ok(entity).build(); - } - - @Path("{id}") - @DELETE - public Response remove(@PathParam("id") long id) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkPermission(Geofence.class, getUserId(), id); - Context.getGeofenceManager().removeItem(id); - return Response.noContent().build(); - } - } diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index 4482f06c0..2be4e6492 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -16,22 +16,16 @@ package org.traccar.api.resource; import org.traccar.Context; -import org.traccar.api.BaseResource; +import org.traccar.api.BaseObjectResource; import org.traccar.database.GroupsManager; import org.traccar.model.Group; -import org.traccar.model.User; 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 java.sql.SQLException; import java.util.Collection; import java.util.Set; @@ -39,7 +33,11 @@ import java.util.Set; @Path("groups") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class GroupResource extends BaseResource { +public class GroupResource extends BaseObjectResource { + + public GroupResource() { + super(Group.class); + } @GET public Collection get( @@ -62,37 +60,4 @@ public class GroupResource extends BaseResource { } return groupsManager.getItems(result); } - - @POST - public Response add(Group entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getGroupsManager().addItem(entity); - Context.getDataManager().linkObject(User.class, getUserId(), entity.getClass(), entity.getId(), true); - Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); - Context.getPermissionsManager().refreshAllExtendedPermissions(); - return Response.ok(entity).build(); - } - - @Path("{id}") - @PUT - public Response update(Group entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), entity.getId()); - Context.getGroupsManager().updateItem(entity); - Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); - Context.getPermissionsManager().refreshAllExtendedPermissions(); - return Response.ok(entity).build(); - } - - @Path("{id}") - @DELETE - public Response remove(@PathParam("id") long id) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkGroup(getUserId(), id); - Context.getGroupsManager().removeItem(id); - Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); - Context.getPermissionsManager().refreshAllExtendedPermissions(); - return Response.noContent().build(); - } - } diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index deb2dd2b4..b22e01216 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -16,19 +16,16 @@ package org.traccar.api.resource; import org.traccar.Context; -import org.traccar.api.BaseResource; +import org.traccar.api.BaseObjectResource; import org.traccar.database.UsersManager; import org.traccar.model.ManagedUser; import org.traccar.model.User; import javax.annotation.security.PermitAll; 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; @@ -41,7 +38,11 @@ import java.util.Set; @Path("users") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class UserResource extends BaseResource { +public class UserResource extends BaseObjectResource { + + public UserResource() { + super(User.class); + } @GET public Collection get(@QueryParam("userId") long userId) throws SQLException { @@ -61,6 +62,7 @@ public class UserResource extends BaseResource { return usersManager.getItems(result); } + @Override @PermitAll @POST public Response add(User entity) throws SQLException { @@ -89,29 +91,4 @@ public class UserResource extends BaseResource { return Response.ok(entity).build(); } - @Path("{id}") - @PUT - public Response update(User entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - User before = Context.getPermissionsManager().getUser(entity.getId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getId()); - Context.getPermissionsManager().checkUserUpdate(getUserId(), before, entity); - Context.getUsersManager().updateItem(entity); - if (Context.getNotificationManager() != null) { - Context.getNotificationManager().refresh(); - } - return Response.ok(entity).build(); - } - - @Path("{id}") - @DELETE - public Response remove(@PathParam("id") long id) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), id); - Context.getUsersManager().removeItem(id); - Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); - Context.getPermissionsManager().refreshAllUsersPermissions(); - return Response.noContent().build(); - } - } -- cgit v1.2.3 From 5446776933ff412361a3c7812c2bb6de9a78ccaf Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Thu, 27 Jul 2017 16:46:52 +0500 Subject: Optimize a few IFs --- src/org/traccar/Context.java | 2 +- src/org/traccar/api/BaseObjectResource.java | 13 +++++-------- 2 files changed, 6 insertions(+), 9 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 75a7d179b..306a37e83 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -378,7 +378,7 @@ public final class Context { identityManager = testIdentityManager; } - public static BaseObjectManager getManager(Class clazz) { + public static BaseObjectManager getManager(Class clazz) { if (clazz.equals(Device.class)) { return (BaseObjectManager) deviceManager; } else if (clazz.equals(Group.class)) { diff --git a/src/org/traccar/api/BaseObjectResource.java b/src/org/traccar/api/BaseObjectResource.java index 11e9a5d01..ea5d4966f 100644 --- a/src/org/traccar/api/BaseObjectResource.java +++ b/src/org/traccar/api/BaseObjectResource.java @@ -34,7 +34,7 @@ import org.traccar.model.Device; import org.traccar.model.Group; import org.traccar.model.User; -public class BaseObjectResource extends BaseResource { +public abstract class BaseObjectResource extends BaseResource { private Class baseClass; @@ -57,8 +57,7 @@ public class BaseObjectResource extends BaseResource { if (manager instanceof SimpleObjectManager) { ((SimpleObjectManager) manager).refreshUserItems(); - } - if (baseClass.equals(Group.class) || baseClass.equals(Device.class)) { + } else if (baseClass.equals(Group.class) || baseClass.equals(Device.class)) { Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); } @@ -71,8 +70,7 @@ public class BaseObjectResource extends BaseResource { Context.getPermissionsManager().checkReadonly(getUserId()); if (baseClass.equals(Device.class)) { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); - } - if (baseClass.equals(User.class)) { + } else if (baseClass.equals(User.class)) { User before = Context.getPermissionsManager().getUser(entity.getId()); Context.getPermissionsManager().checkUserUpdate(getUserId(), before, (User) entity); } @@ -83,8 +81,7 @@ public class BaseObjectResource extends BaseResource { if (baseClass.equals(Group.class) || baseClass.equals(Device.class)) { Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); - } - if (baseClass.equals(User.class) && Context.getNotificationManager() != null) { + } else if (baseClass.equals(User.class) && Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); @@ -116,7 +113,7 @@ public class BaseObjectResource extends BaseResource { Context.getPermissionsManager().refreshAllExtendedPermissions(); } } - // deprecated + // Next should be removed with Attribute Aliases if (baseClass.equals(Device.class)) { Context.getAliasesManager().removeDevice(id); } -- cgit v1.2.3 From 34d02fbb63eb3d0cfbbcf63de50561831b0ab38d Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Fri, 28 Jul 2017 08:19:56 +0500 Subject: One more condition optimizing --- src/org/traccar/api/BaseObjectResource.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/BaseObjectResource.java b/src/org/traccar/api/BaseObjectResource.java index ea5d4966f..4475e3b4d 100644 --- a/src/org/traccar/api/BaseObjectResource.java +++ b/src/org/traccar/api/BaseObjectResource.java @@ -101,9 +101,9 @@ public abstract class BaseObjectResource extends BaseResour if (manager instanceof SimpleObjectManager) { ((SimpleObjectManager) manager).refreshUserItems(); - } - if (manager instanceof ExtendedObjectManager) { - ((ExtendedObjectManager) manager).refreshExtendedPermissions(); + if (manager instanceof ExtendedObjectManager) { + ((ExtendedObjectManager) manager).refreshExtendedPermissions(); + } } if (baseClass.equals(Group.class) || baseClass.equals(Device.class) || baseClass.equals(User.class)) { Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); -- cgit v1.2.3 From 0da1f5da4e5e0e39259ab3333c1273ba5cb382a7 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Fri, 28 Jul 2017 10:43:21 +0500 Subject: Combine some GET functions --- src/org/traccar/api/BaseObjectResource.java | 25 +++++++++ src/org/traccar/api/ExtendedObjectResource.java | 62 ++++++++++++++++++++++ src/org/traccar/api/SimpleObjectResource.java | 43 +++++++++++++++ .../traccar/api/resource/AttributeResource.java | 48 +---------------- src/org/traccar/api/resource/CalendarResource.java | 35 +----------- src/org/traccar/api/resource/DriverResource.java | 52 +----------------- src/org/traccar/api/resource/GeofenceResource.java | 50 +---------------- src/org/traccar/api/resource/GroupResource.java | 32 +---------- 8 files changed, 140 insertions(+), 207 deletions(-) create mode 100644 src/org/traccar/api/ExtendedObjectResource.java create mode 100644 src/org/traccar/api/SimpleObjectResource.java (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/BaseObjectResource.java b/src/org/traccar/api/BaseObjectResource.java index 4475e3b4d..a1b90bc28 100644 --- a/src/org/traccar/api/BaseObjectResource.java +++ b/src/org/traccar/api/BaseObjectResource.java @@ -17,6 +17,7 @@ package org.traccar.api; import java.sql.SQLException; +import java.util.Set; import javax.ws.rs.DELETE; import javax.ws.rs.POST; @@ -28,6 +29,7 @@ import javax.ws.rs.core.Response; import org.traccar.Context; import org.traccar.database.BaseObjectManager; import org.traccar.database.ExtendedObjectManager; +import org.traccar.database.ManagableObjects; import org.traccar.database.SimpleObjectManager; import org.traccar.model.BaseModel; import org.traccar.model.Device; @@ -42,6 +44,29 @@ public abstract class BaseObjectResource extends BaseResour this.baseClass = baseClass; } + protected final Class getBaseClass() { + return baseClass; + } + + protected final Set getSimpleManagerItems(BaseObjectManager manager, boolean all, long userId) { + Set result = null; + if (all) { + if (Context.getPermissionsManager().isAdmin(getUserId())) { + result = manager.getAllItems(); + } else { + Context.getPermissionsManager().checkManager(getUserId()); + result = ((ManagableObjects) manager).getManagedItems(getUserId()); + } + } else { + if (userId == 0) { + userId = getUserId(); + } + Context.getPermissionsManager().checkUser(getUserId(), userId); + result = ((ManagableObjects) manager).getUserItems(userId); + } + return result; + } + @POST public Response add(T entity) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); diff --git a/src/org/traccar/api/ExtendedObjectResource.java b/src/org/traccar/api/ExtendedObjectResource.java new file mode 100644 index 000000000..007a7b1bd --- /dev/null +++ b/src/org/traccar/api/ExtendedObjectResource.java @@ -0,0 +1,62 @@ +/* + * 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; + +import java.sql.SQLException; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import javax.ws.rs.GET; +import javax.ws.rs.QueryParam; + +import org.traccar.Context; +import org.traccar.database.ExtendedObjectManager; +import org.traccar.model.BaseModel; + +public class ExtendedObjectResource extends BaseObjectResource { + + public ExtendedObjectResource(Class baseClass) { + super(baseClass); + } + + @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 { + + ExtendedObjectManager manager = (ExtendedObjectManager) Context.getManager(getBaseClass()); + if (refresh) { + manager.refreshItems(); + } + + Set result = new HashSet<>(getSimpleManagerItems(manager, all, userId)); + + if (groupId != 0) { + Context.getPermissionsManager().checkGroup(getUserId(), groupId); + result.retainAll(manager.getGroupItems(groupId)); + } + + if (deviceId != 0) { + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + result.retainAll(manager.getDeviceItems(deviceId)); + } + return manager.getItems(result); + + } + +} diff --git a/src/org/traccar/api/SimpleObjectResource.java b/src/org/traccar/api/SimpleObjectResource.java new file mode 100644 index 000000000..a7fcae0e7 --- /dev/null +++ b/src/org/traccar/api/SimpleObjectResource.java @@ -0,0 +1,43 @@ +/* + * 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; + +import java.sql.SQLException; +import java.util.Collection; + +import javax.ws.rs.GET; +import javax.ws.rs.QueryParam; + +import org.traccar.Context; +import org.traccar.database.BaseObjectManager; +import org.traccar.model.BaseModel; + +public class SimpleObjectResource extends BaseObjectResource { + + public SimpleObjectResource(Class baseClass) { + super(baseClass); + } + + @GET + public Collection get( + @QueryParam("all") boolean all, @QueryParam("userId") long userId) throws SQLException { + + BaseObjectManager manager = Context.getManager(getBaseClass()); + return manager.getItems(getSimpleManagerItems(manager, all, userId)); + } + +} diff --git a/src/org/traccar/api/resource/AttributeResource.java b/src/org/traccar/api/resource/AttributeResource.java index 55fd39fc6..26a1f6931 100644 --- a/src/org/traccar/api/resource/AttributeResource.java +++ b/src/org/traccar/api/resource/AttributeResource.java @@ -17,12 +17,8 @@ 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.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; @@ -31,8 +27,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.traccar.Context; -import org.traccar.api.BaseObjectResource; -import org.traccar.database.AttributesManager; +import org.traccar.api.ExtendedObjectResource; import org.traccar.model.Attribute; import org.traccar.model.Position; import org.traccar.processing.ComputedAttributesHandler; @@ -40,51 +35,12 @@ import org.traccar.processing.ComputedAttributesHandler; @Path("attributes/computed") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class AttributeResource extends BaseObjectResource { +public class AttributeResource extends ExtendedObjectResource { public AttributeResource() { super(Attribute.class); } - @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 { - - AttributesManager attributesManager = Context.getAttributesManager(); - if (refresh) { - attributesManager.refreshItems(); - } - - Set result = new HashSet<>(); - if (all) { - if (Context.getPermissionsManager().isAdmin(getUserId())) { - result.addAll(attributesManager.getAllItems()); - } else { - Context.getPermissionsManager().checkManager(getUserId()); - result.addAll(attributesManager.getManagedItems(getUserId())); - } - } else { - if (userId == 0) { - userId = getUserId(); - } - Context.getPermissionsManager().checkUser(getUserId(), userId); - result.addAll(attributesManager.getUserItems(userId)); - } - - if (groupId != 0) { - Context.getPermissionsManager().checkGroup(getUserId(), groupId); - result.retainAll(attributesManager.getGroupItems(groupId)); - } - - if (deviceId != 0) { - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - result.retainAll(attributesManager.getDeviceItems(deviceId)); - } - return attributesManager.getItems(result); - - } - @POST @Path("test") public Response test(@QueryParam("deviceId") long deviceId, Attribute entity) throws SQLException { diff --git a/src/org/traccar/api/resource/CalendarResource.java b/src/org/traccar/api/resource/CalendarResource.java index d43a3b02e..9399c34a5 100644 --- a/src/org/traccar/api/resource/CalendarResource.java +++ b/src/org/traccar/api/resource/CalendarResource.java @@ -16,52 +16,21 @@ */ package org.traccar.api.resource; -import java.sql.SQLException; -import java.util.Collection; -import java.util.Set; - import javax.ws.rs.Consumes; -import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import org.traccar.Context; -import org.traccar.api.BaseObjectResource; -import org.traccar.database.CalendarManager; +import org.traccar.api.SimpleObjectResource; import org.traccar.model.Calendar; @Path("calendars") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class CalendarResource extends BaseObjectResource { +public class CalendarResource extends SimpleObjectResource { public CalendarResource() { super(Calendar.class); } - @GET - public Collection get( - @QueryParam("all") boolean all, @QueryParam("userId") long userId) throws SQLException { - - CalendarManager calendarManager = Context.getCalendarManager(); - Set result = null; - if (all) { - if (Context.getPermissionsManager().isAdmin(getUserId())) { - result = calendarManager.getAllItems(); - } else { - Context.getPermissionsManager().checkManager(getUserId()); - result = calendarManager.getManagedItems(getUserId()); - } - } else { - if (userId == 0) { - userId = getUserId(); - } - Context.getPermissionsManager().checkUser(getUserId(), userId); - result = calendarManager.getUserItems(userId); - } - return calendarManager.getItems(result); - } - } diff --git a/src/org/traccar/api/resource/DriverResource.java b/src/org/traccar/api/resource/DriverResource.java index 185f4a0dc..91aa54c5e 100644 --- a/src/org/traccar/api/resource/DriverResource.java +++ b/src/org/traccar/api/resource/DriverResource.java @@ -16,69 +16,21 @@ */ 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.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import org.traccar.Context; -import org.traccar.api.BaseObjectResource; -import org.traccar.database.DriversManager; +import org.traccar.api.ExtendedObjectResource; import org.traccar.model.Driver; @Path("drivers") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class DriverResource extends BaseObjectResource { +public class DriverResource extends ExtendedObjectResource { public DriverResource() { super(Driver.class); } - @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.refreshItems(); - } - - Set result = new HashSet<>(); - if (all) { - if (Context.getPermissionsManager().isAdmin(getUserId())) { - result.addAll(driversManager.getAllItems()); - } else { - Context.getPermissionsManager().checkManager(getUserId()); - result.addAll(driversManager.getManagedItems(getUserId())); - } - } else { - if (userId == 0) { - userId = getUserId(); - } - Context.getPermissionsManager().checkUser(getUserId(), userId); - result.addAll(driversManager.getUserItems(userId)); - } - - if (groupId != 0) { - Context.getPermissionsManager().checkGroup(getUserId(), groupId); - result.retainAll(driversManager.getGroupItems(groupId)); - } - - if (deviceId != 0) { - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - result.retainAll(driversManager.getDeviceItems(deviceId)); - } - return driversManager.getItems(result); - - } - } diff --git a/src/org/traccar/api/resource/GeofenceResource.java b/src/org/traccar/api/resource/GeofenceResource.java index d07810732..58f2c188c 100644 --- a/src/org/traccar/api/resource/GeofenceResource.java +++ b/src/org/traccar/api/resource/GeofenceResource.java @@ -15,67 +15,21 @@ */ package org.traccar.api.resource; -import org.traccar.Context; -import org.traccar.api.BaseObjectResource; -import org.traccar.database.GeofenceManager; +import org.traccar.api.ExtendedObjectResource; import org.traccar.model.Geofence; import javax.ws.rs.Consumes; -import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import java.sql.SQLException; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - @Path("geofences") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class GeofenceResource extends BaseObjectResource { +public class GeofenceResource extends ExtendedObjectResource { public GeofenceResource() { super(Geofence.class); } - @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 { - - GeofenceManager geofenceManager = Context.getGeofenceManager(); - if (refresh) { - geofenceManager.refreshItems(); - } - - Set result = new HashSet<>(); - if (all) { - if (Context.getPermissionsManager().isAdmin(getUserId())) { - result.addAll(geofenceManager.getAllItems()); - } else { - Context.getPermissionsManager().checkManager(getUserId()); - result.addAll(geofenceManager.getManagedItems(getUserId())); - } - } else { - if (userId == 0) { - userId = getUserId(); - } - Context.getPermissionsManager().checkUser(getUserId(), userId); - result.addAll(geofenceManager.getUserItems(userId)); - } - - if (groupId != 0) { - Context.getPermissionsManager().checkGroup(getUserId(), groupId); - result.retainAll(geofenceManager.getGroupItems(groupId)); - } - - if (deviceId != 0) { - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - result.retainAll(geofenceManager.getDeviceItems(deviceId)); - } - return geofenceManager.getItems(result); - } } diff --git a/src/org/traccar/api/resource/GroupResource.java b/src/org/traccar/api/resource/GroupResource.java index 2be4e6492..fcea15d0a 100644 --- a/src/org/traccar/api/resource/GroupResource.java +++ b/src/org/traccar/api/resource/GroupResource.java @@ -15,49 +15,21 @@ */ package org.traccar.api.resource; -import org.traccar.Context; -import org.traccar.api.BaseObjectResource; -import org.traccar.database.GroupsManager; +import org.traccar.api.SimpleObjectResource; import org.traccar.model.Group; import javax.ws.rs.Consumes; -import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import java.sql.SQLException; -import java.util.Collection; -import java.util.Set; @Path("groups") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class GroupResource extends BaseObjectResource { +public class GroupResource extends SimpleObjectResource { public GroupResource() { super(Group.class); } - @GET - public Collection get( - @QueryParam("all") boolean all, @QueryParam("userId") long userId) throws SQLException { - GroupsManager groupsManager = Context.getGroupsManager(); - Set result = null; - if (all) { - if (Context.getPermissionsManager().isAdmin(getUserId())) { - result = groupsManager.getAllItems(); - } else { - Context.getPermissionsManager().checkManager(getUserId()); - result = groupsManager.getManagedItems(getUserId()); - } - } else { - if (userId == 0) { - userId = getUserId(); - } - Context.getPermissionsManager().checkUser(getUserId(), userId); - result = groupsManager.getUserItems(userId); - } - return groupsManager.getItems(result); - } } -- cgit v1.2.3 From ae76cbf971bfc9e47ef21e87606dacc7c0e3ddc6 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Mon, 31 Jul 2017 14:08:36 +0500 Subject: Implement SQL requests construction --- schema/changelog-3.14.xml | 4 +- setup/default.xml | 406 +-------------------- src/org/traccar/Config.java | 4 + src/org/traccar/api/resource/EventResource.java | 2 +- src/org/traccar/api/resource/PositionResource.java | 2 +- src/org/traccar/database/DataManager.java | 210 ++++++++--- src/org/traccar/database/QueryAdditional.java | 27 ++ src/org/traccar/database/StatisticsManager.java | 2 +- src/org/traccar/model/Device.java | 7 + src/org/traccar/model/Position.java | 9 + src/org/traccar/model/Server.java | 2 + src/org/traccar/model/User.java | 6 + test/org/traccar/database/DataManagerTest.java | 79 ++++ 13 files changed, 299 insertions(+), 461 deletions(-) create mode 100644 src/org/traccar/database/QueryAdditional.java create mode 100644 test/org/traccar/database/DataManagerTest.java (limited to 'src/org/traccar/api') diff --git a/schema/changelog-3.14.xml b/schema/changelog-3.14.xml index 7965bc020..f6cda4c1f 100644 --- a/schema/changelog-3.14.xml +++ b/schema/changelog-3.14.xml @@ -61,5 +61,7 @@ + + - \ No newline at end of file + diff --git a/setup/default.xml b/setup/default.xml index f0f9ef4a3..ea8c32fbd 100644 --- a/setup/default.xml +++ b/setup/default.xml @@ -29,163 +29,16 @@ true ./schema/changelog-master.xml - - - SELECT * FROM server - - - - UPDATE server SET - registration = :registration, - readonly = :readonly, - deviceReadonly = :deviceReadonly, - map = :map, - bingKey = :bingKey, - mapUrl = :mapUrl, - distanceUnit = :distanceUnit, - speedUnit = :speedUnit, - latitude = :latitude, - longitude = :longitude, - zoom = :zoom, - twelveHourFormat = :twelveHourFormat, - coordinateFormat = :coordinateFormat, - forceSettings = :forceSettings, - timezone = :timezone, - attributes = :attributes - WHERE id = :id - - + SELECT * FROM users WHERE email = :email - - SELECT * FROM users - - - - INSERT INTO users (name, email, phone, hashedPassword, salt, readonly, admin, map, distanceUnit, speedUnit, latitude, longitude, zoom, twelveHourFormat, coordinateFormat, disabled, expirationTime, deviceLimit, userLimit, deviceReadonly, token, timezone, attributes) - VALUES (:name, :email, :phone, :hashedPassword, :salt, :readonly, :admin, :map, :distanceUnit, :speedUnit, :latitude, :longitude, :zoom, :twelveHourFormat, :coordinateFormat, :disabled, :expirationTime, :deviceLimit, :userLimit, :deviceReadonly, :token, :timezone, :attributes) - - - - UPDATE users SET - name = :name, - email = :email, - phone = :phone, - readonly = :readonly, - admin = :admin, - map = :map, - distanceUnit = :distanceUnit, - speedUnit = :speedUnit, - latitude = :latitude, - longitude = :longitude, - zoom = :zoom, - twelveHourFormat = :twelveHourFormat, - coordinateFormat = :coordinateFormat, - disabled = :disabled, - expirationTime = :expirationTime, - deviceLimit = :deviceLimit, - userLimit = :userLimit, - deviceReadonly = :deviceReadonly, - token = :token, - timezone = :timezone, - attributes = :attributes - WHERE id = :id - - - - UPDATE users SET hashedPassword = :hashedPassword, salt = :salt WHERE id = :id - - - - DELETE FROM users WHERE id = :id - - - - SELECT userId, deviceId FROM user_device - - - - SELECT userId, groupId FROM user_group - - - - SELECT * FROM devices - - - - INSERT INTO devices (name, uniqueId, groupId, attributes, phone, model, contact, category) - VALUES (:name, :uniqueId, :groupId, :attributes, :phone, :model, :contact, :category) - - - - UPDATE devices SET - name = :name, - uniqueId = :uniqueId, - groupId = :groupId, - attributes = :attributes, - phone = :phone, - model = :model, - contact = :contact, - category = :category - WHERE id = :id - - - - UPDATE devices SET lastUpdate = :lastUpdate WHERE id = :id - - - - DELETE FROM devices WHERE id = :id - - - - INSERT INTO user_device (userId, deviceId) VALUES (:userId, :deviceId) - - - - DELETE FROM user_device WHERE userId = :userId AND deviceId = :deviceId - - - - SELECT * FROM groups - - - - INSERT INTO groups (name, groupId, attributes) VALUES (:name, :groupId, :attributes) - - - - UPDATE groups SET name = :name, groupId = :groupId, attributes = :attributes WHERE id = :id - - - - DELETE FROM groups WHERE id = :id - - - - INSERT INTO user_group (userId, groupId) VALUES (:userId, :groupId) - - - - DELETE FROM user_group WHERE userId = :userId AND groupId = :groupId - - SELECT * FROM positions WHERE deviceId = :deviceId AND fixTime BETWEEN :from AND :to ORDER BY fixTime - - SELECT * FROM positions WHERE id = :id - - - - INSERT INTO positions (deviceId, protocol, serverTime, deviceTime, fixTime, valid, latitude, longitude, altitude, speed, course, address, attributes, accuracy, network) - VALUES (:deviceId, :protocol, :now, :deviceTime, :fixTime, :valid, :latitude, :longitude, :altitude, :speed, :course, :address, :attributes, :accuracy, :network) - - SELECT positions.* FROM positions INNER JOIN devices ON positions.id = devices.positionid; @@ -194,102 +47,10 @@ UPDATE devices SET positionId = :id WHERE id = :deviceId - - SELECT * FROM events WHERE id = :id - - - - INSERT INTO events (type, serverTime, deviceId, positionId, geofenceId, attributes) - VALUES (:type, :serverTime, :deviceId, :positionId, :geofenceId, :attributes) - - SELECT * FROM events WHERE deviceId = :deviceId AND serverTime BETWEEN :from AND :to ORDER BY serverTime - - SELECT * FROM geofences - - - - INSERT INTO geofences (name, description, calendarid, area, attributes) - VALUES (:name, :description, :calendarid, :area, :attributes) - - - - UPDATE geofences SET - name = :name, - description = :description, - calendarid = :calendarid, - area = :area, - attributes = :attributes - WHERE id = :id - - - - DELETE FROM geofences WHERE id = :id - - - - SELECT userId, geofenceId FROM user_geofence - - - - INSERT INTO user_geofence (userId, geofenceId) VALUES (:userId, :geofenceId) - - - - DELETE FROM user_geofence WHERE userId = :userId AND geofenceId = :geofenceId - - - - SELECT groupId, geofenceId FROM group_geofence - - - - INSERT INTO group_geofence (groupId, geofenceId) VALUES (:groupId, :geofenceId) - - - - DELETE FROM group_geofence WHERE groupId = :groupId AND geofenceId = :geofenceId - - - - SELECT deviceId, geofenceId FROM device_geofence - - - - INSERT INTO device_geofence (deviceId, geofenceId) VALUES (:deviceId, :geofenceId) - - - - DELETE FROM device_geofence WHERE deviceId = :deviceId AND geofenceId = :geofenceId - - - - SELECT * FROM notifications - - - - INSERT INTO notifications (userId, type, web, mail, sms, attributes) - VALUES (:userId, :type, :web, :mail, :sms, :attributes) - - - - UPDATE notifications SET - userId = :userId, - type = :type, - web = :web, - mail = :mail, - sms = :sms, - attributes = :attributes - WHERE id = :id - - - - DELETE FROM notifications WHERE id = :id - - DELETE FROM positions WHERE serverTime < :serverTime AND id NOT IN (SELECT positionId FROM devices) @@ -323,171 +84,6 @@ SELECT * FROM statistics WHERE captureTime BETWEEN :from AND :to ORDER BY captureTime - - INSERT INTO statistics (captureTime, activeUsers, activeDevices, requests, messagesReceived, messagesStored, mailSent, smsSent, geocoderRequests, geolocationRequests, attributes) - VALUES (:captureTime, :activeUsers, :activeDevices, :requests, :messagesReceived, :messagesStored, :mailSent, :smsSent, :geocoderRequests, :geolocationRequests, :attributes) - - - - SELECT * FROM calendars - - - - INSERT INTO calendars (name, data, attributes) - VALUES (:name, :data, :attributes) - - - - UPDATE calendars SET - name = :name, - data = :data, - attributes = :attributes - WHERE id = :id - - - - DELETE FROM calendars WHERE id = :id - - - - SELECT userId, calendarId FROM user_calendar - - - - INSERT INTO user_calendar (userId, calendarId) VALUES (:userId, :calendarId) - - - - DELETE FROM user_calendar WHERE userId = :userId AND calendarId = :calendarId - - - - SELECT userId, managedUserId FROM user_user - - - - INSERT INTO user_user (userId, managedUserId) VALUES (:userId, :managedUserId) - - - - DELETE FROM user_user WHERE userId = :userId AND managedUserId = :managedUserId - - - - SELECT * FROM attributes - - - - INSERT INTO attributes (description, type, attribute, expression) - VALUES (:description, :type, :attribute, :expression) - - - - UPDATE attributes SET - description = :description, - type = :type, - attribute = :attribute, - expression = :expression - WHERE id = :id - - - - DELETE FROM attributes WHERE id = :id - - - - SELECT userId, attributeId FROM user_attribute - - - - INSERT INTO user_attribute (userId, attributeId) VALUES (:userId, :attributeId) - - - - DELETE FROM user_attribute WHERE userId = :userId AND attributeId = :attributeId - - - - SELECT groupId, attributeId FROM group_attribute - - - - INSERT INTO group_attribute (groupId, attributeId) VALUES (:groupId, :attributeId) - - - - DELETE FROM group_attribute WHERE groupId = :groupId AND attributeId = :attributeId - - - - SELECT deviceId, attributeId FROM device_attribute - - - - INSERT INTO device_attribute (deviceId, attributeId) VALUES (:deviceId, :attributeId) - - - - DELETE FROM device_attribute WHERE deviceId = :deviceId AND attributeId = :attributeId - - - - SELECT * FROM drivers - - - - INSERT INTO drivers (name, uniqueId, attributes) - VALUES (:name, :uniqueId, :attributes) - - - - UPDATE drivers SET - name = :name, - uniqueId = :uniqueId, - attributes = :attributes - WHERE id = :id - - - - DELETE FROM drivers WHERE id = :id - - - - SELECT userId, driverId FROM user_driver - - - - INSERT INTO user_driver (userId, driverId) VALUES (:userId, :driverId) - - - - DELETE FROM user_driver WHERE userId = :userId AND driverId = :driverId - - - - SELECT groupId, driverId FROM group_driver - - - - INSERT INTO group_driver (groupId, driverId) VALUES (:groupId, :driverId) - - - - DELETE FROM group_driver WHERE groupId = :groupId AND driverId = :driverId - - - - SELECT deviceId, driverId FROM device_driver - - - - INSERT INTO device_driver (deviceId, driverId) VALUES (:deviceId, :driverId) - - - - DELETE FROM device_driver WHERE deviceId = :deviceId AND driverId = :driverId - - 5001 diff --git a/src/org/traccar/Config.java b/src/org/traccar/Config.java index 0bc3cafaa..a0f3f8c2e 100644 --- a/src/org/traccar/Config.java +++ b/src/org/traccar/Config.java @@ -96,4 +96,8 @@ public class Config { return key.replaceAll("\\.", "_").replaceAll("(\\p{Lu})", "_$1").toUpperCase(); } + public void setString(String key, String value) { + properties.putIfAbsent(key, value); + } + } diff --git a/src/org/traccar/api/resource/EventResource.java b/src/org/traccar/api/resource/EventResource.java index b7fda6f73..a7cf9edbd 100644 --- a/src/org/traccar/api/resource/EventResource.java +++ b/src/org/traccar/api/resource/EventResource.java @@ -23,7 +23,7 @@ public class EventResource extends BaseResource { @Path("{id}") @GET public Event get(@PathParam("id") long id) throws SQLException { - Event event = Context.getDataManager().getEvent(id); + Event event = Context.getDataManager().getObject(Event.class, id); Context.getPermissionsManager().checkDevice(getUserId(), event.getDeviceId()); if (event.getGeofenceId() != 0) { Context.getPermissionsManager().checkPermission(Geofence.class, getUserId(), event.getGeofenceId()); diff --git a/src/org/traccar/api/resource/PositionResource.java b/src/org/traccar/api/resource/PositionResource.java index 6dab51744..c031b842f 100644 --- a/src/org/traccar/api/resource/PositionResource.java +++ b/src/org/traccar/api/resource/PositionResource.java @@ -54,7 +54,7 @@ public class PositionResource extends BaseResource { if (!positionIds.isEmpty()) { ArrayList positions = new ArrayList<>(); for (Long positionId : positionIds) { - Position position = Context.getDataManager().getPosition(positionId); + Position position = Context.getDataManager().getObject(Position.class, positionId); Context.getPermissionsManager().checkDevice(getUserId(), position.getDeviceId()); positions.add(position); } diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 07ad0be44..a753c311b 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -21,8 +21,11 @@ import java.net.URL; import java.net.URLClassLoader; import java.sql.SQLException; import java.text.SimpleDateFormat; +import java.util.Arrays; import java.util.Collection; import java.util.Date; +import java.util.HashSet; +import java.util.Set; import javax.naming.InitialContext; import javax.sql.DataSource; @@ -58,6 +61,12 @@ import com.zaxxer.hikari.HikariDataSource; public class DataManager { + public static final String ACTION_SELECT_ALL = "selectAll"; + public static final String ACTION_SELECT = "select"; + public static final String ACTION_INSERT = "insert"; + public static final String ACTION_UPDATE = "update"; + public static final String ACTION_DELETE = "delete"; + private final Config config; private DataSource dataSource; @@ -115,6 +124,73 @@ public class DataManager { } } + public static String constructObjectQuery(String action, Class clazz, boolean additional) { + switch (action) { + case ACTION_INSERT: + case ACTION_UPDATE: + StringBuilder result = new StringBuilder(); + StringBuilder fields = new StringBuilder(); + StringBuilder values = new StringBuilder(); + + Set methods = new HashSet<>(Arrays.asList(clazz.getMethods())); + methods.removeAll(Arrays.asList(Object.class.getMethods())); + methods.removeAll(Arrays.asList(BaseModel.class.getMethods())); + for (Method method : methods) { + if (method.getName().startsWith("get") && method.getParameterTypes().length == 0 + && (additional ? method.isAnnotationPresent(QueryAdditional.class) + : !method.isAnnotationPresent(QueryIgnore.class) + && !method.isAnnotationPresent(QueryAdditional.class))) { + String name = method.getName().substring(3, 4).toLowerCase() + + method.getName().substring(4); + if (action.equals(ACTION_INSERT)) { + fields.append(name).append(", "); + values.append(":").append(name).append(", "); + } else { + fields.append(name).append(" = :").append(name).append(",\n"); + } + } + } + fields.setLength(fields.length() - 2); + if (action.equals(ACTION_INSERT)) { + values.setLength(values.length() - 2); + result.append("INSERT INTO ").append(getObjectsTableName(clazz)).append(" ("); + result.append(fields).append(")\n"); + result.append("VALUES (").append(values).append(")"); + } else { + result.append("UPDATE ").append(getObjectsTableName(clazz)).append(" SET\n"); + result.append(fields); + result.append("\nWHERE id = :id"); + } + return result.toString(); + case ACTION_SELECT_ALL: + return "SELECT * FROM " + getObjectsTableName(clazz); + case ACTION_SELECT: + return "SELECT * FROM " + getObjectsTableName(clazz) + " WHERE id = :id"; + case ACTION_DELETE: + return "DELETE FROM " + getObjectsTableName(clazz) + " WHERE id = :id"; + default: + throw new IllegalArgumentException("Unknown action"); + } + } + + public static String constructPermissionQuery(String action, Class owner, Class property) { + switch (action) { + case ACTION_SELECT_ALL: + return "SELECT " + makeNameId(owner) + ", " + makeNameId(property) + " FROM " + + getPermissionsTableName(owner, property); + case ACTION_INSERT: + return "INSERT INTO " + getPermissionsTableName(owner, property) + + " (" + makeNameId(owner) + ", " + makeNameId(property) + ") VALUES (:" + + makeNameId(owner) + ", :" + makeNameId(property) + ")"; + case ACTION_DELETE: + return "DELETE FROM " + getPermissionsTableName(owner, property) + + " WHERE " + makeNameId(owner) + " = :" + makeNameId(owner) + + " AND " + makeNameId(property) + " = :" + makeNameId(property); + default: + throw new IllegalArgumentException("Unknown action"); + } + } + private String getQuery(String key) { String query = config.getString(key); if (query == null) { @@ -123,6 +199,59 @@ public class DataManager { return query; } + public String getQuery(String action, Class clazz) { + return getQuery(action, clazz, false); + } + + public String getQuery(String action, Class clazz, boolean additional) { + String queryName; + if (action.equals(ACTION_SELECT_ALL)) { + queryName = "database.select" + clazz.getSimpleName() + "s"; + } else { + queryName = "database." + action.toLowerCase() + clazz.getSimpleName(); + } + String query = config.getString(queryName); + if (query == null) { + query = constructObjectQuery(action, clazz, additional); + config.setString(queryName, query); + } + + return query; + } + + public String getQuery(String action, Class owner, Class property) { + String queryName; + if (action.equals(ACTION_SELECT_ALL)) { + queryName = "database.select" + owner.getSimpleName() + property.getSimpleName() + "s"; + } else if (action.equals(ACTION_INSERT)) { + queryName = "database.link" + owner.getSimpleName() + property.getSimpleName(); + } else { + queryName = "database.unlink" + owner.getSimpleName() + property.getSimpleName(); + } + String query = config.getString(queryName); + if (query == null) { + query = constructPermissionQuery(action, owner, property.equals(User.class) ? ManagedUser.class : property); + config.setString(queryName, query); + } + + return query; + } + + private static String getPermissionsTableName(Class owner, Class property) { + String ownerName = owner.getSimpleName(); + String propertyName = property.getSimpleName(); + if (propertyName.equals("ManagedUser")) { + propertyName = "User"; + } + return ownerName.substring(0, 1).toLowerCase() + ownerName.substring(1) + "_" + + propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); + } + + private static String getObjectsTableName(Class clazz) { + String name = clazz.getSimpleName(); + return name.substring(0, 1).toLowerCase() + name.substring(1) + "s"; + } + private void initDatabaseSchema() throws SQLException, LiquibaseException { if (config.hasKey("database.changelog")) { @@ -155,19 +284,8 @@ public class DataManager { } } - public void updateUser(User user) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateUser")) - .setObject(user) - .executeUpdate(); - if (user.getHashedPassword() != null) { - QueryBuilder.create(dataSource, getQuery("database.updateUserPassword")) - .setObject(user) - .executeUpdate(); - } - } - public void updateDeviceStatus(Device device) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateDeviceStatus")) + QueryBuilder.create(dataSource, getQuery(ACTION_UPDATE, Device.class, true)) .setObject(device) .executeUpdate(); } @@ -180,16 +298,10 @@ public class DataManager { .executeQuery(Position.class); } - public Position getPosition(long positionId) throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectPosition")) - .setLong("id", positionId) - .executeQuerySingle(Position.class); - } - public void addPosition(Position position) throws SQLException { - position.setId(QueryBuilder.create(dataSource, getQuery("database.insertPosition"), true) - .setDate("now", new Date()) + position.setId(QueryBuilder.create(dataSource, getQuery(ACTION_INSERT, Position.class), true) .setObject(position) + .setDate("serverTime", new Date()) .executeUpdate()); } @@ -220,16 +332,10 @@ public class DataManager { } public Server getServer() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectServers")) + return QueryBuilder.create(dataSource, getQuery(ACTION_SELECT_ALL, Server.class)) .executeQuerySingle(Server.class); } - public Event getEvent(long eventId) throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectEvent")) - .setLong("id", eventId) - .executeQuerySingle(Event.class); - } - public Collection getEvents(long deviceId, Date from, Date to) throws SQLException { return QueryBuilder.create(dataSource, getQuery("database.selectEvents")) .setLong("deviceId", deviceId) @@ -268,12 +374,6 @@ public class DataManager { .executeQuery(Statistics.class); } - public void addStatistics(Statistics statistics) throws SQLException { - statistics.setId(QueryBuilder.create(dataSource, getQuery("database.insertStatistics"), true) - .setObject(statistics) - .executeUpdate()); - } - public static Class getClassByName(String name) throws ClassNotFoundException { switch (name.toLowerCase().replace("id", "")) { case "device": @@ -302,44 +402,50 @@ public class DataManager { return name.substring(0, 1).toLowerCase() + name.substring(1) + (name.indexOf("Id") == -1 ? "Id" : ""); } + public Collection getPermissions(Class owner, Class property) + throws SQLException, ClassNotFoundException { + return QueryBuilder.create(dataSource, getQuery(ACTION_SELECT_ALL, owner, property)) + .executePermissionsQuery(); + } + public void linkObject(Class owner, long ownerId, Class property, long propertyId, boolean link) throws SQLException { - String query = "database." + (link ? "link" : "unlink") + owner.getSimpleName() + property.getSimpleName(); - QueryBuilder queryBuilder = QueryBuilder.create(dataSource, getQuery(query)); - - queryBuilder.setLong(makeNameId(owner), ownerId); - queryBuilder.setLong(makeNameId(property), propertyId); - queryBuilder.executeUpdate(); + QueryBuilder.create(dataSource, getQuery(link ? ACTION_INSERT : ACTION_DELETE, owner, property)) + .setLong(makeNameId(owner), ownerId) + .setLong(makeNameId(property), propertyId) + .executeUpdate(); } - public Collection getObjects(Class clazz) throws SQLException { - String query = "database.select" + clazz.getSimpleName() + "s"; - return QueryBuilder.create(dataSource, getQuery(query)).executeQuery(clazz); + public T getObject(Class clazz, long entityId) throws SQLException { + return QueryBuilder.create(dataSource, getQuery(ACTION_SELECT, clazz)) + .setLong("id", entityId) + .executeQuerySingle(clazz); } - public Collection getPermissions(Class owner, - Class property) throws SQLException, ClassNotFoundException { - String query = "database.select" + owner.getSimpleName() + property.getSimpleName() + "s"; - return QueryBuilder.create(dataSource, getQuery(query)).executePermissionsQuery(); + public Collection getObjects(Class clazz) throws SQLException { + return QueryBuilder.create(dataSource, getQuery(ACTION_SELECT_ALL, clazz)) + .executeQuery(clazz); } public void addObject(BaseModel entity) throws SQLException { - String query = "database.insert" + entity.getClass().getSimpleName(); - entity.setId(QueryBuilder.create(dataSource, getQuery(query), true) + entity.setId(QueryBuilder.create(dataSource, getQuery(ACTION_INSERT, entity.getClass()), true) .setObject(entity) .executeUpdate()); } public void updateObject(BaseModel entity) throws SQLException { - String query = "database.update" + entity.getClass().getSimpleName(); - QueryBuilder.create(dataSource, getQuery(query)) + QueryBuilder.create(dataSource, getQuery(ACTION_UPDATE, entity.getClass())) .setObject(entity) .executeUpdate(); + if (entity instanceof User && ((User) entity).getHashedPassword() != null) { + QueryBuilder.create(dataSource, getQuery(ACTION_UPDATE, User.class, true)) + .setObject(entity) + .executeUpdate(); + } } public void removeObject(Class clazz, long entityId) throws SQLException { - String query = "database.delete" + clazz.getSimpleName(); - QueryBuilder.create(dataSource, getQuery(query)) + QueryBuilder.create(dataSource, getQuery(ACTION_DELETE, clazz)) .setLong("id", entityId) .executeUpdate(); } diff --git a/src/org/traccar/database/QueryAdditional.java b/src/org/traccar/database/QueryAdditional.java new file mode 100644 index 000000000..7a42c1875 --- /dev/null +++ b/src/org/traccar/database/QueryAdditional.java @@ -0,0 +1,27 @@ +/* + * 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.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface QueryAdditional { +} diff --git a/src/org/traccar/database/StatisticsManager.java b/src/org/traccar/database/StatisticsManager.java index 5b42416ad..06a3e7b35 100644 --- a/src/org/traccar/database/StatisticsManager.java +++ b/src/org/traccar/database/StatisticsManager.java @@ -61,7 +61,7 @@ public class StatisticsManager { statistics.setGeolocationRequests(geolocationRequests); try { - Context.getDataManager().addStatistics(statistics); + Context.getDataManager().addObject(statistics); } catch (SQLException e) { Log.warning(e); } diff --git a/src/org/traccar/model/Device.java b/src/org/traccar/model/Device.java index 6a13c2b77..cd5dd12c4 100644 --- a/src/org/traccar/model/Device.java +++ b/src/org/traccar/model/Device.java @@ -18,6 +18,9 @@ package org.traccar.model; import java.util.Date; import java.util.List; +import org.traccar.database.QueryAdditional; +import org.traccar.database.QueryIgnore; + public class Device extends ExtendedModel { private String name; @@ -46,6 +49,7 @@ public class Device extends ExtendedModel { private String status; + @QueryIgnore public String getStatus() { return status != null ? status : STATUS_OFFLINE; } @@ -56,6 +60,7 @@ public class Device extends ExtendedModel { private Date lastUpdate; + @QueryAdditional public Date getLastUpdate() { if (lastUpdate != null) { return new Date(lastUpdate.getTime()); @@ -74,6 +79,7 @@ public class Device extends ExtendedModel { private long positionId; + @QueryIgnore public long getPositionId() { return positionId; } @@ -94,6 +100,7 @@ public class Device extends ExtendedModel { private List geofenceIds; + @QueryIgnore public List getGeofenceIds() { return geofenceIds; } diff --git a/src/org/traccar/model/Position.java b/src/org/traccar/model/Position.java index 4412b012c..66a6f91ce 100644 --- a/src/org/traccar/model/Position.java +++ b/src/org/traccar/model/Position.java @@ -17,6 +17,8 @@ package org.traccar.model; import java.util.Date; +import org.traccar.database.QueryIgnore; + public class Position extends Message { public static final String KEY_ORIGINAL = "raw"; @@ -196,6 +198,7 @@ public class Position extends Message { private boolean outdated; + @QueryIgnore public boolean getOutdated() { return outdated; } @@ -294,4 +297,10 @@ public class Position extends Message { this.network = network; } + @Override + @QueryIgnore + public String getType() { + return super.getType(); + } + } diff --git a/src/org/traccar/model/Server.java b/src/org/traccar/model/Server.java index cd5b0624e..246be0b4f 100644 --- a/src/org/traccar/model/Server.java +++ b/src/org/traccar/model/Server.java @@ -17,10 +17,12 @@ package org.traccar.model; import java.util.TimeZone; +import org.traccar.database.QueryIgnore; import org.traccar.helper.Log; public class Server extends ExtendedModel { + @QueryIgnore public String getVersion() { return Log.getAppVersion(); } diff --git a/src/org/traccar/model/User.java b/src/org/traccar/model/User.java index 6e6a079c2..72b53ee5d 100644 --- a/src/org/traccar/model/User.java +++ b/src/org/traccar/model/User.java @@ -16,6 +16,9 @@ package org.traccar.model; import com.fasterxml.jackson.annotation.JsonIgnore; + +import org.traccar.database.QueryAdditional; +import org.traccar.database.QueryIgnore; import org.traccar.helper.Hashing; import java.util.Date; @@ -228,6 +231,7 @@ public class User extends ExtendedModel { } } + @QueryIgnore public String getPassword() { return null; } @@ -243,6 +247,7 @@ public class User extends ExtendedModel { private String hashedPassword; @JsonIgnore + @QueryAdditional public String getHashedPassword() { return hashedPassword; } @@ -254,6 +259,7 @@ public class User extends ExtendedModel { private String salt; @JsonIgnore + @QueryAdditional public String getSalt() { return salt; } diff --git a/test/org/traccar/database/DataManagerTest.java b/test/org/traccar/database/DataManagerTest.java new file mode 100644 index 000000000..3383c3d22 --- /dev/null +++ b/test/org/traccar/database/DataManagerTest.java @@ -0,0 +1,79 @@ +package org.traccar.database; + +import org.junit.Assert; +import org.junit.Test; +import org.traccar.model.Attribute; +import org.traccar.model.Device; +import org.traccar.model.Driver; +import org.traccar.model.Geofence; +import org.traccar.model.Group; +import org.traccar.model.ManagedUser; +import org.traccar.model.Position; +import org.traccar.model.User; + +public class DataManagerTest { + + @Test + public void constructObjectQuery() { + Assert.assertEquals("SELECT * FROM users", + DataManager.constructObjectQuery(DataManager.ACTION_SELECT_ALL, User.class, false)); + Assert.assertEquals("DELETE FROM groups WHERE id = :id", + DataManager.constructObjectQuery(DataManager.ACTION_DELETE, Group.class, false)); + Assert.assertEquals("SELECT * FROM positions WHERE id = :id", + DataManager.constructObjectQuery(DataManager.ACTION_SELECT, Position.class, false)); + + String insertDevice = DataManager.constructObjectQuery(DataManager.ACTION_INSERT, Device.class, false); + Assert.assertFalse(insertDevice.contains("class")); + Assert.assertFalse(insertDevice.contains("id")); + Assert.assertFalse(insertDevice.contains("status")); + Assert.assertFalse(insertDevice.contains("lastUpdate")); + Assert.assertFalse(insertDevice.contains("geofenceIds")); + + String updateDeviceStatus = DataManager.constructObjectQuery("update", Device.class, true); + Assert.assertTrue(updateDeviceStatus.contains("lastUpdate")); + + String updateUser = DataManager.constructObjectQuery(DataManager.ACTION_UPDATE, User.class, false); + Assert.assertFalse(updateUser.contains("class")); + Assert.assertFalse(updateUser.contains("password")); + Assert.assertFalse(updateUser.contains("salt")); + + String updateUserPassword = DataManager.constructObjectQuery(DataManager.ACTION_UPDATE, User.class, true); + Assert.assertFalse(updateUserPassword.contains("name")); + Assert.assertTrue(updateUserPassword.contains("hashedPassword")); + Assert.assertTrue(updateUserPassword.contains("salt")); + + String insertPosition = DataManager.constructObjectQuery(DataManager.ACTION_INSERT, Position.class, false); + Assert.assertFalse(insertPosition.contains("type")); + Assert.assertFalse(insertPosition.contains("outdated")); + + } + + @Test + public void constructPermissionsQuery() { + Assert.assertEquals("SELECT userId, deviceId FROM user_device", + DataManager.constructPermissionQuery(DataManager.ACTION_SELECT_ALL, User.class, Device.class)); + + Assert.assertEquals("SELECT userId, managedUserId FROM user_user", + DataManager.constructPermissionQuery(DataManager.ACTION_SELECT_ALL, User.class, ManagedUser.class)); + + Assert.assertEquals("SELECT deviceId, driverId FROM device_driver", + DataManager.constructPermissionQuery(DataManager.ACTION_SELECT_ALL, Device.class, Driver.class)); + + Assert.assertEquals("SELECT groupId, geofenceId FROM group_geofence", + DataManager.constructPermissionQuery(DataManager.ACTION_SELECT_ALL, Group.class, Geofence.class)); + + Assert.assertEquals("INSERT INTO user_device (userId, deviceId) VALUES (:userId, :deviceId)", + DataManager.constructPermissionQuery(DataManager.ACTION_INSERT, User.class, Device.class)); + + Assert.assertEquals("DELETE FROM user_user WHERE userId = :userId AND managedUserId = :managedUserId", + DataManager.constructPermissionQuery(DataManager.ACTION_DELETE, User.class, ManagedUser.class)); + + Assert.assertEquals("INSERT INTO device_geofence (deviceId, geofenceId) VALUES (:deviceId, :geofenceId)", + DataManager.constructPermissionQuery(DataManager.ACTION_INSERT, Device.class, Geofence.class)); + + Assert.assertEquals("DELETE FROM group_attribute WHERE groupId = :groupId AND attributeId = :attributeId", + DataManager.constructPermissionQuery(DataManager.ACTION_DELETE, Group.class, Attribute.class)); + + } + +} -- cgit v1.2.3 From ba892a34c4a78ddc4ec7b24cc72b62278f608322 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 5 Sep 2017 18:14:36 +0500 Subject: Remove Attribute Aliases support --- schema/changelog-3.15.xml | 17 ++++ schema/changelog-master.xml | 1 + setup/default.xml | 21 ---- src/org/traccar/Context.java | 9 -- src/org/traccar/api/BaseObjectResource.java | 4 - .../api/resource/AttributeAliasResource.java | 93 ----------------- src/org/traccar/database/AliasesManager.java | 113 --------------------- src/org/traccar/database/DataManager.java | 24 ----- src/org/traccar/model/AttributeAlias.java | 51 ---------- swagger.json | 109 +++++--------------- 10 files changed, 44 insertions(+), 398 deletions(-) create mode 100644 schema/changelog-3.15.xml delete mode 100644 src/org/traccar/api/resource/AttributeAliasResource.java delete mode 100644 src/org/traccar/database/AliasesManager.java delete mode 100644 src/org/traccar/model/AttributeAlias.java (limited to 'src/org/traccar/api') diff --git a/schema/changelog-3.15.xml b/schema/changelog-3.15.xml new file mode 100644 index 000000000..a2d944abb --- /dev/null +++ b/schema/changelog-3.15.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + diff --git a/schema/changelog-master.xml b/schema/changelog-master.xml index d1b51b40e..58b2a8307 100644 --- a/schema/changelog-master.xml +++ b/schema/changelog-master.xml @@ -15,4 +15,5 @@ + diff --git a/setup/default.xml b/setup/default.xml index d96ceeb6d..95b69e216 100644 --- a/setup/default.xml +++ b/setup/default.xml @@ -62,27 +62,6 @@ DELETE FROM events WHERE serverTime < :serverTime - - SELECT * FROM attribute_aliases - - - - INSERT INTO attribute_aliases (deviceId, attribute, alias) - VALUES (:deviceId, :attribute, :alias) - - - - UPDATE attribute_aliases SET - deviceId = :deviceId, - attribute = :attribute, - alias = :alias - WHERE id = :id - - - - DELETE FROM attribute_aliases WHERE id = :id - - SELECT * FROM statistics WHERE captureTime BETWEEN :from AND :to ORDER BY captureTime diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 10fdd9f29..87d8257ee 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -25,7 +25,6 @@ import java.util.Properties; import org.apache.velocity.app.VelocityEngine; import org.eclipse.jetty.util.URIUtil; -import org.traccar.database.AliasesManager; import org.traccar.database.CalendarManager; import org.traccar.database.AttributesManager; import org.traccar.database.BaseObjectManager; @@ -202,12 +201,6 @@ public final class Context { return eventForwarder; } - private static AliasesManager aliasesManager; - - public static AliasesManager getAliasesManager() { - return aliasesManager; - } - private static AttributesManager attributesManager; public static AttributesManager getAttributesManager() { @@ -395,8 +388,6 @@ public final class Context { eventForwarder = new EventForwarder(); } - aliasesManager = new AliasesManager(dataManager); - attributesManager = new AttributesManager(dataManager); driversManager = new DriversManager(dataManager); diff --git a/src/org/traccar/api/BaseObjectResource.java b/src/org/traccar/api/BaseObjectResource.java index a1b90bc28..b13dc2e71 100644 --- a/src/org/traccar/api/BaseObjectResource.java +++ b/src/org/traccar/api/BaseObjectResource.java @@ -138,10 +138,6 @@ public abstract class BaseObjectResource extends BaseResour Context.getPermissionsManager().refreshAllExtendedPermissions(); } } - // Next should be removed with Attribute Aliases - if (baseClass.equals(Device.class)) { - Context.getAliasesManager().removeDevice(id); - } return Response.noContent().build(); } diff --git a/src/org/traccar/api/resource/AttributeAliasResource.java b/src/org/traccar/api/resource/AttributeAliasResource.java deleted file mode 100644 index b2636acf1..000000000 --- a/src/org/traccar/api/resource/AttributeAliasResource.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2016 Anton Tananaev (anton@traccar.org) - * Copyright 2016 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 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.model.AttributeAlias; - -@Path("attributes/aliases") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class AttributeAliasResource extends BaseResource { - - @GET - public Collection get(@QueryParam("deviceId") long deviceId) throws SQLException { - if (deviceId != 0) { - if (!Context.getPermissionsManager().isAdmin(getUserId())) { - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - } - return Context.getAliasesManager().getAttributeAliases(deviceId); - } else { - return Context.getAliasesManager().getAllAttributeAliases(getUserId()); - } - } - - @POST - public Response add(AttributeAlias entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDeviceReadonly(getUserId()); - if (!Context.getPermissionsManager().isAdmin(getUserId())) { - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - } - Context.getAliasesManager().addAttributeAlias(entity); - return Response.ok(entity).build(); - } - - @Path("{id}") - @PUT - public Response update(AttributeAlias entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDeviceReadonly(getUserId()); - if (!Context.getPermissionsManager().isAdmin(getUserId())) { - AttributeAlias oldEntity = Context.getAliasesManager().getAttributeAlias(entity.getId()); - Context.getPermissionsManager().checkDevice(getUserId(), oldEntity.getDeviceId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - } - Context.getAliasesManager().updateAttributeAlias(entity); - return Response.ok(entity).build(); - } - - @Path("{id}") - @DELETE - public Response remove(@PathParam("id") long id) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDeviceReadonly(getUserId()); - if (!Context.getPermissionsManager().isAdmin(getUserId())) { - AttributeAlias entity = Context.getAliasesManager().getAttributeAlias(id); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - } - Context.getAliasesManager().removeArrtibuteAlias(id); - return Response.noContent().build(); - } - -} diff --git a/src/org/traccar/database/AliasesManager.java b/src/org/traccar/database/AliasesManager.java deleted file mode 100644 index 4f4f09731..000000000 --- a/src/org/traccar/database/AliasesManager.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2016 Anton Tananaev (anton@traccar.org) - * Copyright 2016 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.ArrayList; -import java.util.Collection; -import java.util.HashSet; -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.AttributeAlias; - -public class AliasesManager { - - private final DataManager dataManager; - - private final Map> deviceAliases = new ConcurrentHashMap<>(); - private final Map aliasesById = new ConcurrentHashMap<>(); - - public AliasesManager(DataManager dataManager) { - this.dataManager = dataManager; - if (dataManager != null) { - try { - for (AttributeAlias attributeAlias : dataManager.getAttributeAliases()) { - getAttributeAliases(attributeAlias.getDeviceId()) - .add(attributeAlias); - aliasesById.put(attributeAlias.getId(), attributeAlias); - } - } catch (SQLException error) { - Log.warning(error); - } - } - } - - public Set getAttributeAliases(long deviceId) { - if (!deviceAliases.containsKey(deviceId)) { - deviceAliases.put(deviceId, new HashSet()); - } - return deviceAliases.get(deviceId); - } - - public void removeDevice(long deviceId) { - for (AttributeAlias attributeAlias : getAttributeAliases(deviceId)) { - aliasesById.remove(attributeAlias.getId()); - } - deviceAliases.remove(deviceId); - } - - public void addAttributeAlias(AttributeAlias attributeAlias) throws SQLException { - dataManager.addAttributeAlias(attributeAlias); - aliasesById.put(attributeAlias.getId(), attributeAlias); - getAttributeAliases(attributeAlias.getDeviceId()).add(attributeAlias); - } - - public void updateAttributeAlias(AttributeAlias attributeAlias) throws SQLException { - dataManager.updateAttributeAlias(attributeAlias); - AttributeAlias cachedAlias = aliasesById.get(attributeAlias.getId()); - if (cachedAlias.getDeviceId() != attributeAlias.getDeviceId()) { - getAttributeAliases(cachedAlias.getDeviceId()).remove(cachedAlias); - cachedAlias.setDeviceId(attributeAlias.getDeviceId()); - getAttributeAliases(cachedAlias.getDeviceId()).add(cachedAlias); - } - cachedAlias.setAttribute(attributeAlias.getAttribute()); - cachedAlias.setAlias(attributeAlias.getAlias()); - } - - public void removeArrtibuteAlias(long attributeAliasId) throws SQLException { - dataManager.removeAttributeAlias(attributeAliasId); - AttributeAlias cachedAlias = aliasesById.get(attributeAliasId); - getAttributeAliases(cachedAlias.getDeviceId()).remove(cachedAlias); - aliasesById.remove(attributeAliasId); - } - - public AttributeAlias getAttributeAlias(long deviceId, String attribute) { - for (AttributeAlias alias : getAttributeAliases(deviceId)) { - if (alias.getAttribute().equals(attribute)) { - return alias; - } - } - return null; - } - - public Collection getAllAttributeAliases(long userId) { - Collection userDevicesAliases = new ArrayList<>(); - for (long deviceId : Context.getPermissionsManager().getDevicePermissions(userId)) { - userDevicesAliases.addAll(getAttributeAliases(deviceId)); - } - return userDevicesAliases; - } - - public AttributeAlias getAttributeAlias(long id) { - return aliasesById.get(id); - } - -} diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 2e3e68bc9..4535a9c38 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -42,7 +42,6 @@ import liquibase.resource.ResourceAccessor; import org.traccar.Config; import org.traccar.helper.Log; import org.traccar.model.Attribute; -import org.traccar.model.AttributeAlias; import org.traccar.model.Device; import org.traccar.model.Driver; import org.traccar.model.Event; @@ -366,29 +365,6 @@ public class DataManager { .executeQuery(Event.class); } - public Collection getAttributeAliases() throws SQLException { - return QueryBuilder.create(dataSource, getQuery("database.selectAttributeAliases")) - .executeQuery(AttributeAlias.class); - } - - public void addAttributeAlias(AttributeAlias attributeAlias) throws SQLException { - attributeAlias.setId(QueryBuilder.create(dataSource, getQuery("database.insertAttributeAlias"), true) - .setObject(attributeAlias) - .executeUpdate()); - } - - public void updateAttributeAlias(AttributeAlias attributeAlias) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.updateAttributeAlias")) - .setObject(attributeAlias) - .executeUpdate(); - } - - public void removeAttributeAlias(long attributeAliasId) throws SQLException { - QueryBuilder.create(dataSource, getQuery("database.deleteAttributeAlias")) - .setLong("id", attributeAliasId) - .executeUpdate(); - } - public Collection getStatistics(Date from, Date to) throws SQLException { return QueryBuilder.create(dataSource, getQuery("database.selectStatistics")) .setDate("from", from) diff --git a/src/org/traccar/model/AttributeAlias.java b/src/org/traccar/model/AttributeAlias.java deleted file mode 100644 index 1599ab939..000000000 --- a/src/org/traccar/model/AttributeAlias.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2016 Anton Tananaev (anton@traccar.org) - * Copyright 2016 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.model; - -public class AttributeAlias extends BaseModel { - - private long deviceId; - - public long getDeviceId() { - return deviceId; - } - - public void setDeviceId(long deviceId) { - this.deviceId = deviceId; - } - - private String attribute; - - public String getAttribute() { - return attribute; - } - - public void setAttribute(String attribute) { - this.attribute = attribute; - } - - private String alias; - - public String getAlias() { - return alias; - } - - public void setAlias(String alias) { - this.alias = alias; - } - -} diff --git a/swagger.json b/swagger.json index ffe56c9da..eba9e0910 100644 --- a/swagger.json +++ b/swagger.json @@ -1,7 +1,7 @@ { "swagger": "2.0", "info": { - "version": "3.13", + "version": "3.14", "title": "traccar" }, "host": "demo.traccar.org", @@ -861,10 +861,25 @@ } } }, - "/statistics": { + "/reports/stops": { "get": { - "summary": "Fetch server Statistics", + "summary": "Fetch a list of ReportStops within the time period for the Devices or Groups", + "description": "At least one _deviceId_ or one _groupId_ must be passed", + "consumes": [ + "application/json", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + ], + "produces": [ + "application/json", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + ], "parameters": [ + { + "$ref": "#/parameters/deviceIdArray" + }, + { + "$ref": "#/parameters/groupIdArray" + }, { "$ref": "#/parameters/fromTime" }, @@ -878,20 +893,22 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/Statistics" + "$ref": "#/definitions/ReportStops" } } } } } }, - "/attributes/aliases": { + "/statistics": { "get": { - "summary": "Fetch a list of AttributeAlias", - "description": "Without params, it returns a list of AttributeAlias from all the user's Devices", + "summary": "Fetch server Statistics", "parameters": [ { - "$ref": "#/parameters/deviceId" + "$ref": "#/parameters/fromTime" + }, + { + "$ref": "#/parameters/toTime" } ], "responses": { @@ -900,61 +917,11 @@ "schema": { "type": "array", "items": { - "$ref": "#/definitions/AttributeAlias" + "$ref": "#/definitions/Statistics" } } } } - }, - "post": { - "summary": "Set an AttributeAlias", - "parameters": [ - { - "$ref": "#/parameters/AttributeAlias" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/AttributeAlias" - } - } - } - } - }, - "/attributes/aliases/{id}": { - "put": { - "summary": "Update an AttributeAlias", - "parameters": [ - { - "$ref": "#/parameters/entityId" - }, - { - "$ref": "#/parameters/AttributeAlias" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/AttributeAlias" - } - } - } - }, - "delete": { - "summary": "Delete an AttributeAlias", - "parameters": [ - { - "$ref": "#/parameters/entityId" - } - ], - "responses": { - "204": { - "description": "No Content" - } - } } }, "/calendars": { @@ -1714,22 +1681,6 @@ } } }, - "AttributeAlias": { - "properties": { - "id": { - "type": "integer" - }, - "deviceId": { - "type": "integer" - }, - "attribute": { - "type": "string" - }, - "alias": { - "type": "string" - } - } - }, "DeviceTotalDistance": { "properties": { "deviceId": { @@ -1868,14 +1819,6 @@ "$ref": "#/definitions/Geofence" } }, - "AttributeAlias": { - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/AttributeAlias" - } - }, "Calendar": { "name": "body", "in": "body", -- cgit v1.2.3 From 925806fe70e10e47bcc12eb8bcc4fe21a9ece220 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 12 Sep 2017 17:42:16 +0500 Subject: Implement Saved Commands --- schema/changelog-3.15.xml | 64 +++++++++- src/org/traccar/Context.java | 12 ++ src/org/traccar/api/BaseObjectResource.java | 7 ++ src/org/traccar/api/resource/CommandResource.java | 46 ++++++- .../traccar/api/resource/CommandTypeResource.java | 8 +- src/org/traccar/database/CommandsManager.java | 136 +++++++++++++++++++++ src/org/traccar/database/DataManager.java | 3 + src/org/traccar/database/DeviceManager.java | 51 -------- src/org/traccar/database/PermissionsManager.java | 26 ++++ src/org/traccar/model/Command.java | 18 +++ src/org/traccar/model/Server.java | 10 ++ src/org/traccar/model/User.java | 10 ++ 12 files changed, 332 insertions(+), 59 deletions(-) create mode 100644 src/org/traccar/database/CommandsManager.java (limited to 'src/org/traccar/api') diff --git a/schema/changelog-3.15.xml b/schema/changelog-3.15.xml index 37fd2e278..f6ed306dc 100644 --- a/schema/changelog-3.15.xml +++ b/schema/changelog-3.15.xml @@ -7,7 +7,7 @@ logicalFilePath="changelog-3.15"> - + @@ -21,5 +21,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 87d8257ee..210d52429 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -26,6 +26,7 @@ import java.util.Properties; import org.apache.velocity.app.VelocityEngine; import org.eclipse.jetty.util.URIUtil; import org.traccar.database.CalendarManager; +import org.traccar.database.CommandsManager; import org.traccar.database.AttributesManager; import org.traccar.database.BaseObjectManager; import org.traccar.database.ConnectionManager; @@ -56,6 +57,7 @@ import org.traccar.helper.Log; import org.traccar.model.Attribute; import org.traccar.model.BaseModel; import org.traccar.model.Calendar; +import org.traccar.model.Command; import org.traccar.model.Device; import org.traccar.model.Driver; import org.traccar.model.Geofence; @@ -213,6 +215,12 @@ public final class Context { return driversManager; } + private static CommandsManager commandsManager; + + public static CommandsManager getCommandsManager() { + return commandsManager; + } + private static StatisticsManager statisticsManager; public static StatisticsManager getStatisticsManager() { @@ -392,6 +400,8 @@ public final class Context { driversManager = new DriversManager(dataManager); + commandsManager = new CommandsManager(dataManager); + statisticsManager = new StatisticsManager(); if (config.getBoolean("sms.smpp.enable")) { @@ -421,6 +431,8 @@ public final class Context { return (BaseObjectManager) geofenceManager; } else if (clazz.equals(Driver.class)) { return (BaseObjectManager) driversManager; + } else if (clazz.equals(Command.class)) { + return (BaseObjectManager) commandsManager; } return null; } diff --git a/src/org/traccar/api/BaseObjectResource.java b/src/org/traccar/api/BaseObjectResource.java index b13dc2e71..4315832b5 100644 --- a/src/org/traccar/api/BaseObjectResource.java +++ b/src/org/traccar/api/BaseObjectResource.java @@ -32,6 +32,7 @@ import org.traccar.database.ExtendedObjectManager; import org.traccar.database.ManagableObjects; import org.traccar.database.SimpleObjectManager; import org.traccar.model.BaseModel; +import org.traccar.model.Command; import org.traccar.model.Device; import org.traccar.model.Group; import org.traccar.model.User; @@ -73,6 +74,8 @@ public abstract class BaseObjectResource extends BaseResour if (baseClass.equals(Device.class)) { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); Context.getPermissionsManager().checkDeviceLimit(getUserId()); + } else if (baseClass.equals(Command.class)) { + Context.getPermissionsManager().checkLimitCommands(getUserId()); } BaseObjectManager manager = Context.getManager(baseClass); @@ -98,6 +101,8 @@ public abstract class BaseObjectResource extends BaseResour } else if (baseClass.equals(User.class)) { User before = Context.getPermissionsManager().getUser(entity.getId()); Context.getPermissionsManager().checkUserUpdate(getUserId(), before, (User) entity); + } else if (baseClass.equals(Command.class)) { + Context.getPermissionsManager().checkLimitCommands(getUserId()); } Context.getPermissionsManager().checkPermission(baseClass, getUserId(), entity.getId()); @@ -118,6 +123,8 @@ public abstract class BaseObjectResource extends BaseResour Context.getPermissionsManager().checkReadonly(getUserId()); if (baseClass.equals(Device.class)) { Context.getPermissionsManager().checkDeviceReadonly(getUserId()); + } else if (baseClass.equals(Command.class)) { + Context.getPermissionsManager().checkLimitCommands(getUserId()); } Context.getPermissionsManager().checkPermission(baseClass, getUserId(), id); diff --git a/src/org/traccar/api/resource/CommandResource.java b/src/org/traccar/api/resource/CommandResource.java index 9ed92d3d5..f7e7d4f8c 100644 --- a/src/org/traccar/api/resource/CommandResource.java +++ b/src/org/traccar/api/resource/CommandResource.java @@ -16,26 +16,62 @@ package org.traccar.api.resource; import org.traccar.Context; -import org.traccar.api.BaseResource; +import org.traccar.api.ExtendedObjectResource; +import org.traccar.database.CommandsManager; import org.traccar.model.Command; +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.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("commands") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class CommandResource extends BaseResource { +public class CommandResource extends ExtendedObjectResource { + + public CommandResource() { + super(Command.class); + } + + @GET + @Path("send") + public Collection get(@QueryParam("deviceId") long deviceId, + @QueryParam("textChannel") boolean textChannel) throws SQLException { + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + CommandsManager commandsManager = Context.getCommandsManager(); + Set result = null; + result = new HashSet<>(commandsManager.getUserItems(getUserId())); + result.retainAll(commandsManager.getProperCommands(deviceId, textChannel)); + return commandsManager.getItems(result); + } @POST - public Response add(Command entity) throws Exception { + @Path("send") + public Response send(Command entity) throws Exception { Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); - Context.getDeviceManager().sendCommand(entity); + Command command = entity; + long deviceId = command.getDeviceId(); + long id = command.getId(); + if (deviceId != 0 && id != 0) { + Context.getPermissionsManager().checkPermission(Command.class, getUserId(), id); + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + Context.getPermissionsManager().checkUserDeviceCommand(getUserId(), deviceId, id); + Context.getCommandsManager().sendCommand(id, deviceId); + } else { + Context.getPermissionsManager().checkLimitCommands(getUserId()); + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + Context.getCommandsManager().sendCommand(command); + } return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/CommandTypeResource.java b/src/org/traccar/api/resource/CommandTypeResource.java index d5d220547..30f9300cb 100644 --- a/src/org/traccar/api/resource/CommandTypeResource.java +++ b/src/org/traccar/api/resource/CommandTypeResource.java @@ -36,8 +36,12 @@ public class CommandTypeResource extends BaseResource { @GET public Collection get(@QueryParam("deviceId") long deviceId, @QueryParam("textChannel") boolean textChannel) { - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - return Context.getDeviceManager().getCommandTypes(deviceId, textChannel); + if (deviceId != 0) { + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + return Context.getCommandsManager().getCommandTypes(deviceId, textChannel); + } else { + return Context.getCommandsManager().getAllCommandTypes(); + } } } diff --git a/src/org/traccar/database/CommandsManager.java b/src/org/traccar/database/CommandsManager.java new file mode 100644 index 000000000..9f97c929c --- /dev/null +++ b/src/org/traccar/database/CommandsManager.java @@ -0,0 +1,136 @@ +/* + * 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.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.traccar.BaseProtocol; +import org.traccar.Context; +import org.traccar.helper.Log; +import org.traccar.model.Command; +import org.traccar.model.CommandType; +import org.traccar.model.Position; + +public class CommandsManager extends ExtendedObjectManager { + + private boolean fallbackToText; + + public CommandsManager(DataManager dataManager) { + super(dataManager, Command.class); + fallbackToText = Context.getConfig().getBoolean("command.fallbackToSms"); + } + + public boolean checkDeviceCommand(long deviceId, long commandId) { + return getAllDeviceItems(deviceId).contains(commandId); + } + + public void sendCommand(Command command) throws Exception { + sendCommand(command, command.getDeviceId(), fallbackToText); + } + + public void sendCommand(long commandId, long deviceId) throws Exception { + sendCommand(getById(commandId), deviceId, false); + } + + public void sendCommand(Command command, long deviceId, boolean fallbackToText) throws Exception { + if (command.getTextChannel()) { + Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); + String phone = Context.getIdentityManager().getById(deviceId).getPhone(); + if (lastPosition != null) { + BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); + protocol.sendTextCommand(phone, command); + } else if (command.getType().equals(Command.TYPE_CUSTOM)) { + if (Context.getSmppManager() != null) { + Context.getSmppManager().sendMessageSync(phone, command.getString(Command.KEY_DATA), true); + } else { + throw new RuntimeException("SMPP client is not enabled"); + } + } else { + throw new RuntimeException("Command " + command.getType() + " is not supported"); + } + } else { + ActiveDevice activeDevice = Context.getConnectionManager().getActiveDevice(deviceId); + if (activeDevice != null) { + activeDevice.sendCommand(command); + } else { + if (fallbackToText) { + command.setTextChannel(true); + sendCommand(command, deviceId, false); + } else { + throw new RuntimeException("Device is not online"); + } + } + } + } + + public Collection getProperCommands(long deviceId, boolean textChannel) { + List result = new ArrayList<>(); + Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); + for (long commandId : getAllDeviceItems(deviceId)) { + Command command = getById(commandId); + if (command.getTextChannel() == textChannel) { + if (lastPosition != null) { + BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); + Collection protocolCommands = + textChannel ? protocol.getSupportedTextCommands() : protocol.getSupportedDataCommands(); + if (protocolCommands.contains(command.getType())) { + result.add(commandId); + } + } else if (command.getType().equals(Command.TYPE_CUSTOM)) { + result.add(commandId); + } + } + } + return result; + } + + public Collection getCommandTypes(long deviceId, boolean textChannel) { + List result = new ArrayList<>(); + Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); + if (lastPosition != null) { + BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); + Collection commands; + commands = textChannel ? protocol.getSupportedTextCommands() : protocol.getSupportedDataCommands(); + for (String commandKey : commands) { + result.add(new CommandType(commandKey)); + } + } else { + result.add(new CommandType(Command.TYPE_CUSTOM)); + } + return result; + } + + public Collection getAllCommandTypes() { + List result = new ArrayList<>(); + Field[] fields = Command.class.getDeclaredFields(); + for (Field field : fields) { + if (Modifier.isStatic(field.getModifiers()) && field.getName().startsWith("TYPE_")) { + try { + result.add(new CommandType(field.get(null).toString())); + } catch (IllegalArgumentException | IllegalAccessException error) { + Log.warning(error); + } + } + } + return result; + } + +} diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 4535a9c38..261541b4d 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -51,6 +51,7 @@ import org.traccar.model.ManagedUser; import org.traccar.model.Permission; import org.traccar.model.BaseModel; import org.traccar.model.Calendar; +import org.traccar.model.Command; import org.traccar.model.Position; import org.traccar.model.Server; import org.traccar.model.Statistics; @@ -390,6 +391,8 @@ public class DataManager { return Attribute.class; case "calendar": return Calendar.class; + case "command": + return Command.class; default: throw new ClassNotFoundException(); } diff --git a/src/org/traccar/database/DeviceManager.java b/src/org/traccar/database/DeviceManager.java index 2157e738d..1eb90b7eb 100644 --- a/src/org/traccar/database/DeviceManager.java +++ b/src/org/traccar/database/DeviceManager.java @@ -16,7 +16,6 @@ package org.traccar.database; import java.sql.SQLException; -import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; @@ -26,12 +25,9 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; -import org.traccar.BaseProtocol; import org.traccar.Config; import org.traccar.Context; import org.traccar.helper.Log; -import org.traccar.model.Command; -import org.traccar.model.CommandType; import org.traccar.model.Device; import org.traccar.model.DeviceState; import org.traccar.model.DeviceTotalDistance; @@ -55,8 +51,6 @@ public class DeviceManager extends BaseObjectManager implements Identity private final Map deviceStates = new ConcurrentHashMap<>(); - private boolean fallbackToText; - public DeviceManager(DataManager dataManager) { super(dataManager, Device.class); this.config = Context.getConfig(); @@ -68,7 +62,6 @@ public class DeviceManager extends BaseObjectManager implements Identity } dataRefreshDelay = config.getLong("database.refreshDelay", DEFAULT_REFRESH_DELAY) * 1000; lookupGroupsAttribute = config.getBoolean("deviceManager.lookupGroupsAttribute"); - fallbackToText = config.getBoolean("command.fallbackToSms"); refreshLastPositions(); } @@ -344,50 +337,6 @@ public class DeviceManager extends BaseObjectManager implements Identity } } - public void sendCommand(Command command) throws Exception { - long deviceId = command.getDeviceId(); - if (command.getTextChannel()) { - Position lastPosition = getLastPosition(deviceId); - if (lastPosition != null) { - BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); - protocol.sendTextCommand(getById(deviceId).getPhone(), command); - } else if (command.getType().equals(Command.TYPE_CUSTOM)) { - Context.getSmppManager().sendMessageSync(getById(deviceId).getPhone(), - command.getString(Command.KEY_DATA), true); - } else { - throw new RuntimeException("Command " + command.getType() + " is not supported"); - } - } else { - ActiveDevice activeDevice = Context.getConnectionManager().getActiveDevice(deviceId); - if (activeDevice != null) { - activeDevice.sendCommand(command); - } else { - if (fallbackToText) { - command.setTextChannel(true); - sendCommand(command); - } else { - throw new RuntimeException("Device is not online"); - } - } - } - } - - public Collection getCommandTypes(long deviceId, boolean textChannel) { - List result = new ArrayList<>(); - Position lastPosition = Context.getDeviceManager().getLastPosition(deviceId); - if (lastPosition != null) { - BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); - Collection commands; - commands = textChannel ? protocol.getSupportedTextCommands() : protocol.getSupportedDataCommands(); - for (String commandKey : commands) { - result.add(new CommandType(commandKey)); - } - } else { - result.add(new CommandType(Command.TYPE_CUSTOM)); - } - return result; - } - public DeviceState getDeviceState(long deviceId) { DeviceState deviceState = deviceStates.get(deviceId); if (deviceState == null) { diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 0708cc5c9..3da99dd13 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -20,6 +20,7 @@ import org.traccar.helper.Log; import org.traccar.model.Attribute; import org.traccar.model.BaseModel; import org.traccar.model.Calendar; +import org.traccar.model.Command; import org.traccar.model.Device; import org.traccar.model.Driver; import org.traccar.model.Geofence; @@ -197,6 +198,11 @@ public class PermissionsManager { return user != null && user.getDeviceReadonly(); } + public boolean isLimitCommands(long userId) { + User user = getUser(userId); + return user != null && user.getLimitCommands(); + } + public void checkReadonly(long userId) throws SecurityException { if (!isAdmin(userId) && (server.getReadonly() || isReadonly(userId))) { throw new SecurityException("Account is readonly"); @@ -209,6 +215,18 @@ public class PermissionsManager { } } + public void checkLimitCommands(long userId) throws SecurityException { + if (!isAdmin(userId) && (server.getLimitCommands() || isLimitCommands(userId))) { + throw new SecurityException("Account has limit sending commands"); + } + } + + public void checkUserDeviceCommand(long userId, long deviceId, long commandId) throws SecurityException { + if (!isAdmin(userId) && Context.getCommandsManager().checkDeviceCommand(deviceId, commandId)) { + throw new SecurityException("Command can not be sent to this device"); + } + } + public void checkUserEnabled(long userId) throws SecurityException { User user = getUser(userId); if (user == null) { @@ -300,6 +318,8 @@ public class PermissionsManager { manager = Context.getDriversManager(); } else if (object.equals(Calendar.class)) { manager = Context.getCalendarManager(); + } else if (object.equals(Command.class)) { + manager = Context.getCommandsManager(); } else { throw new IllegalArgumentException("Unknown object type"); } @@ -322,6 +342,7 @@ public class PermissionsManager { Context.getCalendarManager().refreshUserItems(); Context.getDriversManager().refreshUserItems(); Context.getAttributesManager().refreshUserItems(); + Context.getCommandsManager().refreshUserItems(); if (Context.getNotificationManager() != null) { Context.getNotificationManager().refresh(); } @@ -333,6 +354,7 @@ public class PermissionsManager { } Context.getDriversManager().refreshExtendedPermissions(); Context.getAttributesManager().refreshExtendedPermissions(); + Context.getCommandsManager().refreshExtendedPermissions(); } public void refreshPermissions(Permission permission) { @@ -351,6 +373,8 @@ public class PermissionsManager { Context.getAttributesManager().refreshUserItems(); } else if (permission.getPropertyClass().equals(Calendar.class)) { Context.getCalendarManager().refreshUserItems(); + } else if (permission.getPropertyClass().equals(Command.class)) { + Context.getCommandsManager().refreshUserItems(); } } else if (permission.getOwnerClass().equals(Device.class) || permission.getOwnerClass().equals(Group.class)) { if (permission.getPropertyClass().equals(Geofence.class) && Context.getGeofenceManager() != null) { @@ -359,6 +383,8 @@ public class PermissionsManager { Context.getDriversManager().refreshExtendedPermissions(); } else if (permission.getPropertyClass().equals(Attribute.class)) { Context.getAttributesManager().refreshExtendedPermissions(); + } else if (permission.getPropertyClass().equals(Command.class)) { + Context.getCommandsManager().refreshExtendedPermissions(); } } } diff --git a/src/org/traccar/model/Command.java b/src/org/traccar/model/Command.java index 6a48b14e9..67134dc7d 100644 --- a/src/org/traccar/model/Command.java +++ b/src/org/traccar/model/Command.java @@ -15,6 +15,8 @@ */ package org.traccar.model; +import org.traccar.database.QueryIgnore; + import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) @@ -85,4 +87,20 @@ public class Command extends Message { this.textChannel = textChannel; } + @QueryIgnore + @Override + public long getDeviceId() { + return super.getDeviceId(); + } + + private String description; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + } diff --git a/src/org/traccar/model/Server.java b/src/org/traccar/model/Server.java index bfe881479..072e85d55 100644 --- a/src/org/traccar/model/Server.java +++ b/src/org/traccar/model/Server.java @@ -147,4 +147,14 @@ public class Server extends ExtendedModel { public void setCoordinateFormat(String coordinateFormat) { this.coordinateFormat = coordinateFormat; } + + private boolean limitCommands; + + public boolean getLimitCommands() { + return limitCommands; + } + + public void setLimitCommands(boolean limitCommands) { + this.limitCommands = limitCommands; + } } diff --git a/src/org/traccar/model/User.java b/src/org/traccar/model/User.java index 043c23036..5d89dcfae 100644 --- a/src/org/traccar/model/User.java +++ b/src/org/traccar/model/User.java @@ -210,6 +210,16 @@ public class User extends ExtendedModel { } } + private boolean limitCommands; + + public boolean getLimitCommands() { + return limitCommands; + } + + public void setLimitCommands(boolean limitCommands) { + this.limitCommands = limitCommands; + } + @QueryIgnore public String getPassword() { return null; -- cgit v1.2.3 From 7b3a3ca4592688f0946076628aa86241a41b1aa8 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 13 Sep 2017 09:05:21 +0500 Subject: - Rename functions "isXxx" to "getUserXxx" - Rename function to "getSupportedCommands" - Some cleanup --- src/org/traccar/api/BaseObjectResource.java | 2 +- src/org/traccar/api/resource/CommandResource.java | 12 ++++---- src/org/traccar/api/resource/DeviceResource.java | 2 +- src/org/traccar/api/resource/UserResource.java | 10 +++---- src/org/traccar/database/CommandsManager.java | 2 +- src/org/traccar/database/PermissionsManager.java | 36 +++++++++++------------ 6 files changed, 31 insertions(+), 33 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/BaseObjectResource.java b/src/org/traccar/api/BaseObjectResource.java index 4315832b5..f0f31a154 100644 --- a/src/org/traccar/api/BaseObjectResource.java +++ b/src/org/traccar/api/BaseObjectResource.java @@ -52,7 +52,7 @@ public abstract class BaseObjectResource extends BaseResour protected final Set getSimpleManagerItems(BaseObjectManager manager, boolean all, long userId) { Set result = null; if (all) { - if (Context.getPermissionsManager().isAdmin(getUserId())) { + if (Context.getPermissionsManager().getUserAdmin(getUserId())) { result = manager.getAllItems(); } else { Context.getPermissionsManager().checkManager(getUserId()); diff --git a/src/org/traccar/api/resource/CommandResource.java b/src/org/traccar/api/resource/CommandResource.java index f7e7d4f8c..b7ea022de 100644 --- a/src/org/traccar/api/resource/CommandResource.java +++ b/src/org/traccar/api/resource/CommandResource.java @@ -49,9 +49,8 @@ public class CommandResource extends ExtendedObjectResource { @QueryParam("textChannel") boolean textChannel) throws SQLException { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); CommandsManager commandsManager = Context.getCommandsManager(); - Set result = null; - result = new HashSet<>(commandsManager.getUserItems(getUserId())); - result.retainAll(commandsManager.getProperCommands(deviceId, textChannel)); + Set result = new HashSet<>(commandsManager.getUserItems(getUserId())); + result.retainAll(commandsManager.getSupportedCommands(deviceId, textChannel)); return commandsManager.getItems(result); } @@ -59,9 +58,8 @@ public class CommandResource extends ExtendedObjectResource { @Path("send") public Response send(Command entity) throws Exception { Context.getPermissionsManager().checkReadonly(getUserId()); - Command command = entity; - long deviceId = command.getDeviceId(); - long id = command.getId(); + long deviceId = entity.getDeviceId(); + long id = entity.getId(); if (deviceId != 0 && id != 0) { Context.getPermissionsManager().checkPermission(Command.class, getUserId(), id); Context.getPermissionsManager().checkDevice(getUserId(), deviceId); @@ -70,7 +68,7 @@ public class CommandResource extends ExtendedObjectResource { } else { Context.getPermissionsManager().checkLimitCommands(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - Context.getCommandsManager().sendCommand(command); + Context.getCommandsManager().sendCommand(entity); } return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/DeviceResource.java b/src/org/traccar/api/resource/DeviceResource.java index 1c2c653a4..1fae92dc7 100644 --- a/src/org/traccar/api/resource/DeviceResource.java +++ b/src/org/traccar/api/resource/DeviceResource.java @@ -53,7 +53,7 @@ public class DeviceResource extends BaseObjectResource { DeviceManager deviceManager = Context.getDeviceManager(); Set result = null; if (all) { - if (Context.getPermissionsManager().isAdmin(getUserId())) { + if (Context.getPermissionsManager().getUserAdmin(getUserId())) { result = deviceManager.getAllItems(); } else { Context.getPermissionsManager().checkManager(getUserId()); diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index b22e01216..0eb328ab5 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -48,13 +48,13 @@ public class UserResource extends BaseObjectResource { public Collection get(@QueryParam("userId") long userId) throws SQLException { UsersManager usersManager = Context.getUsersManager(); Set result = null; - if (Context.getPermissionsManager().isAdmin(getUserId())) { + if (Context.getPermissionsManager().getUserAdmin(getUserId())) { if (userId != 0) { result = usersManager.getUserItems(userId); } else { result = usersManager.getAllItems(); } - } else if (Context.getPermissionsManager().isManager(getUserId())) { + } else if (Context.getPermissionsManager().getUserManager(getUserId())) { result = usersManager.getManagedItems(getUserId()); } else { throw new SecurityException("Admin or manager access required"); @@ -66,9 +66,9 @@ public class UserResource extends BaseObjectResource { @PermitAll @POST public Response add(User entity) throws SQLException { - if (!Context.getPermissionsManager().isAdmin(getUserId())) { + if (!Context.getPermissionsManager().getUserAdmin(getUserId())) { Context.getPermissionsManager().checkUserUpdate(getUserId(), new User(), entity); - if (Context.getPermissionsManager().isManager(getUserId())) { + if (Context.getPermissionsManager().getUserManager(getUserId())) { Context.getPermissionsManager().checkUserLimit(getUserId()); } else { Context.getPermissionsManager().checkRegistration(getUserId()); @@ -81,7 +81,7 @@ public class UserResource extends BaseObjectResource { } } Context.getUsersManager().addItem(entity); - if (Context.getPermissionsManager().isManager(getUserId())) { + if (Context.getPermissionsManager().getUserManager(getUserId())) { Context.getDataManager().linkObject(User.class, getUserId(), ManagedUser.class, entity.getId(), true); } Context.getUsersManager().refreshUserItems(); diff --git a/src/org/traccar/database/CommandsManager.java b/src/org/traccar/database/CommandsManager.java index 9f97c929c..ded12e0d2 100644 --- a/src/org/traccar/database/CommandsManager.java +++ b/src/org/traccar/database/CommandsManager.java @@ -81,7 +81,7 @@ public class CommandsManager extends ExtendedObjectManager { } } - public Collection getProperCommands(long deviceId, boolean textChannel) { + public Collection getSupportedCommands(long deviceId, boolean textChannel) { List result = new ArrayList<>(); Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); for (long commandId : getAllDeviceItems(deviceId)) { diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 3da99dd13..0d9c780a6 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -137,24 +137,24 @@ public class PermissionsManager { } } - public boolean isAdmin(long userId) { + public boolean getUserAdmin(long userId) { User user = getUser(userId); return user != null && user.getAdmin(); } public void checkAdmin(long userId) throws SecurityException { - if (!isAdmin(userId)) { + if (!getUserAdmin(userId)) { throw new SecurityException("Admin access required"); } } - public boolean isManager(long userId) { + public boolean getUserManager(long userId) { User user = getUser(userId); return user != null && user.getUserLimit() != 0; } public void checkManager(long userId) throws SecurityException { - if (!isManager(userId)) { + if (!getUserManager(userId)) { throw new SecurityException("Manager access required"); } } @@ -177,7 +177,7 @@ public class PermissionsManager { int deviceLimit = getUser(userId).getDeviceLimit(); if (deviceLimit != -1) { int deviceCount = 0; - if (isManager(userId)) { + if (getUserManager(userId)) { deviceCount = Context.getDeviceManager().getManagedItems(userId).size(); } else { deviceCount = Context.getDeviceManager().getUserItems(userId).size(); @@ -188,41 +188,41 @@ public class PermissionsManager { } } - public boolean isReadonly(long userId) { + public boolean getUserReadonly(long userId) { User user = getUser(userId); return user != null && user.getReadonly(); } - public boolean isDeviceReadonly(long userId) { + public boolean getUserDeviceReadonly(long userId) { User user = getUser(userId); return user != null && user.getDeviceReadonly(); } - public boolean isLimitCommands(long userId) { + public boolean getUserLimitCommands(long userId) { User user = getUser(userId); return user != null && user.getLimitCommands(); } public void checkReadonly(long userId) throws SecurityException { - if (!isAdmin(userId) && (server.getReadonly() || isReadonly(userId))) { + if (!getUserAdmin(userId) && (server.getReadonly() || getUserReadonly(userId))) { throw new SecurityException("Account is readonly"); } } public void checkDeviceReadonly(long userId) throws SecurityException { - if (!isAdmin(userId) && (server.getDeviceReadonly() || isDeviceReadonly(userId))) { + if (!getUserAdmin(userId) && (server.getDeviceReadonly() || getUserDeviceReadonly(userId))) { throw new SecurityException("Account is device readonly"); } } public void checkLimitCommands(long userId) throws SecurityException { - if (!isAdmin(userId) && (server.getLimitCommands() || isLimitCommands(userId))) { + if (!getUserAdmin(userId) && (server.getLimitCommands() || getUserLimitCommands(userId))) { throw new SecurityException("Account has limit sending commands"); } } public void checkUserDeviceCommand(long userId, long deviceId, long commandId) throws SecurityException { - if (!isAdmin(userId) && Context.getCommandsManager().checkDeviceCommand(deviceId, commandId)) { + if (!getUserAdmin(userId) && Context.getCommandsManager().checkDeviceCommand(deviceId, commandId)) { throw new SecurityException("Command can not be sent to this device"); } } @@ -258,20 +258,20 @@ public class PermissionsManager { if (userId == after.getId()) { checkAdmin(userId); } - if (!isAdmin(userId)) { + if (!getUserAdmin(userId)) { checkManager(userId); } } } public void checkUser(long userId, long managedUserId) throws SecurityException { - if (userId != managedUserId && !isAdmin(userId)) { + if (userId != managedUserId && !getUserAdmin(userId)) { checkManager(userId, managedUserId); } } public void checkGroup(long userId, long groupId) throws SecurityException { - if (!getGroupPermissions(userId).contains(groupId) && !isAdmin(userId)) { + if (!getGroupPermissions(userId).contains(groupId) && !getUserAdmin(userId)) { checkManager(userId); for (long managedUserId : usersManager.getUserItems(userId)) { if (getGroupPermissions(managedUserId).contains(groupId)) { @@ -283,7 +283,7 @@ public class PermissionsManager { } public void checkDevice(long userId, long deviceId) throws SecurityException { - if (!Context.getDeviceManager().getUserItems(userId).contains(deviceId) && !isAdmin(userId)) { + if (!Context.getDeviceManager().getUserItems(userId).contains(deviceId) && !getUserAdmin(userId)) { checkManager(userId); for (long managedUserId : usersManager.getUserItems(userId)) { if (Context.getDeviceManager().getUserItems(managedUserId).contains(deviceId)) { @@ -295,7 +295,7 @@ public class PermissionsManager { } public void checkRegistration(long userId) { - if (!server.getRegistration() && !isAdmin(userId)) { + if (!server.getRegistration() && !getUserAdmin(userId)) { throw new SecurityException("Registration disabled"); } } @@ -324,7 +324,7 @@ public class PermissionsManager { throw new IllegalArgumentException("Unknown object type"); } - if (manager != null && !manager.checkItemPermission(userId, objectId) && !isAdmin(userId)) { + if (manager != null && !manager.checkItemPermission(userId, objectId) && !getUserAdmin(userId)) { checkManager(userId); for (long managedUserId : usersManager.getManagedItems(userId)) { if (manager.checkItemPermission(managedUserId, objectId)) { -- cgit v1.2.3 From 7530522cbca477cb822cb494ffe12480e5237934 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 13 Sep 2017 13:46:38 +0500 Subject: Re implement "getSupportedCommands" function --- src/org/traccar/api/resource/CommandResource.java | 5 ++--- src/org/traccar/database/CommandsManager.java | 10 +++++----- 2 files changed, 7 insertions(+), 8 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/CommandResource.java b/src/org/traccar/api/resource/CommandResource.java index b7ea022de..6a258497f 100644 --- a/src/org/traccar/api/resource/CommandResource.java +++ b/src/org/traccar/api/resource/CommandResource.java @@ -45,12 +45,11 @@ public class CommandResource extends ExtendedObjectResource { @GET @Path("send") - public Collection get(@QueryParam("deviceId") long deviceId, - @QueryParam("textChannel") boolean textChannel) throws SQLException { + public Collection get(@QueryParam("deviceId") long deviceId) throws SQLException { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); CommandsManager commandsManager = Context.getCommandsManager(); Set result = new HashSet<>(commandsManager.getUserItems(getUserId())); - result.retainAll(commandsManager.getSupportedCommands(deviceId, textChannel)); + result.retainAll(commandsManager.getSupportedCommands(deviceId)); return commandsManager.getItems(result); } diff --git a/src/org/traccar/database/CommandsManager.java b/src/org/traccar/database/CommandsManager.java index 6eb6d9035..deb802b29 100644 --- a/src/org/traccar/database/CommandsManager.java +++ b/src/org/traccar/database/CommandsManager.java @@ -81,17 +81,17 @@ public class CommandsManager extends ExtendedObjectManager { } } - public Collection getSupportedCommands(long deviceId, boolean textChannel) { + public Collection getSupportedCommands(long deviceId) { List result = new ArrayList<>(); Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); + boolean online = Context.getConnectionManager().getActiveDevice(deviceId) != null; for (long commandId : getAllDeviceItems(deviceId)) { Command command = getById(commandId); - if (command.getTextChannel() == textChannel) { + if (command.getTextChannel() || online) { if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); - Collection protocolCommands = - textChannel ? protocol.getSupportedTextCommands() : protocol.getSupportedDataCommands(); - if (protocolCommands.contains(command.getType())) { + if (protocol.getSupportedTextCommands().contains(command.getType()) + || online && protocol.getSupportedDataCommands().contains(command.getType())) { result.add(commandId); } } else if (command.getType().equals(Command.TYPE_CUSTOM)) { -- cgit v1.2.3 From 9519b653a8cef055366b0903fdd371c8f86d1206 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Tue, 19 Sep 2017 10:42:07 +0500 Subject: Implement per device Notifications --- schema/changelog-3.15.xml | 50 ++++++ src/org/traccar/Context.java | 3 + src/org/traccar/api/BaseObjectResource.java | 2 - .../traccar/api/resource/CommandTypeResource.java | 4 +- .../traccar/api/resource/NotificationResource.java | 34 ++-- src/org/traccar/api/resource/UserResource.java | 3 - src/org/traccar/database/CommandsManager.java | 16 +- src/org/traccar/database/DataManager.java | 3 + src/org/traccar/database/NotificationManager.java | 187 +++++---------------- src/org/traccar/database/PermissionsManager.java | 11 +- src/org/traccar/model/CommandType.java | 33 ---- src/org/traccar/model/Notification.java | 10 +- src/org/traccar/model/Typed.java | 33 ++++ swagger.json | 110 ++++++++++-- 14 files changed, 264 insertions(+), 235 deletions(-) delete mode 100644 src/org/traccar/model/CommandType.java create mode 100644 src/org/traccar/model/Typed.java (limited to 'src/org/traccar/api') diff --git a/schema/changelog-3.15.xml b/schema/changelog-3.15.xml index f6ed306dc..9756fe696 100644 --- a/schema/changelog-3.15.xml +++ b/schema/changelog-3.15.xml @@ -83,5 +83,55 @@ + + + + + + + + + + + + + + + + + + + INSERT INTO user_notification (notificationid, userid) SELECT id AS notificationid, userid FROM notifications; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/org/traccar/Context.java b/src/org/traccar/Context.java index 210d52429..340eb742c 100644 --- a/src/org/traccar/Context.java +++ b/src/org/traccar/Context.java @@ -62,6 +62,7 @@ import org.traccar.model.Device; import org.traccar.model.Driver; import org.traccar.model.Geofence; import org.traccar.model.Group; +import org.traccar.model.Notification; import org.traccar.model.User; import org.traccar.geolocation.GoogleGeolocationProvider; import org.traccar.geolocation.GeolocationProvider; @@ -433,6 +434,8 @@ public final class Context { return (BaseObjectManager) driversManager; } else if (clazz.equals(Command.class)) { return (BaseObjectManager) commandsManager; + } else if (clazz.equals(Notification.class)) { + return (BaseObjectManager) notificationManager; } return null; } diff --git a/src/org/traccar/api/BaseObjectResource.java b/src/org/traccar/api/BaseObjectResource.java index f0f31a154..634957a49 100644 --- a/src/org/traccar/api/BaseObjectResource.java +++ b/src/org/traccar/api/BaseObjectResource.java @@ -111,8 +111,6 @@ public abstract class BaseObjectResource extends BaseResour if (baseClass.equals(Group.class) || baseClass.equals(Device.class)) { Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); Context.getPermissionsManager().refreshAllExtendedPermissions(); - } else if (baseClass.equals(User.class) && Context.getNotificationManager() != null) { - Context.getNotificationManager().refresh(); } return Response.ok(entity).build(); } diff --git a/src/org/traccar/api/resource/CommandTypeResource.java b/src/org/traccar/api/resource/CommandTypeResource.java index 30f9300cb..0a904bd8a 100644 --- a/src/org/traccar/api/resource/CommandTypeResource.java +++ b/src/org/traccar/api/resource/CommandTypeResource.java @@ -18,7 +18,7 @@ package org.traccar.api.resource; import org.traccar.Context; import org.traccar.api.BaseResource; -import org.traccar.model.CommandType; +import org.traccar.model.Typed; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -34,7 +34,7 @@ import java.util.Collection; public class CommandTypeResource extends BaseResource { @GET - public Collection get(@QueryParam("deviceId") long deviceId, + public Collection get(@QueryParam("deviceId") long deviceId, @QueryParam("textChannel") boolean textChannel) { if (deviceId != 0) { Context.getPermissionsManager().checkDevice(getUserId(), deviceId); diff --git a/src/org/traccar/api/resource/NotificationResource.java b/src/org/traccar/api/resource/NotificationResource.java index dee972607..540f02926 100644 --- a/src/org/traccar/api/resource/NotificationResource.java +++ b/src/org/traccar/api/resource/NotificationResource.java @@ -15,7 +15,6 @@ */ package org.traccar.api.resource; -import java.sql.SQLException; import java.util.Collection; import javax.mail.MessagingException; @@ -24,14 +23,14 @@ import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; 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.api.ExtendedObjectResource; import org.traccar.model.Event; import org.traccar.model.Notification; +import org.traccar.model.Typed; import org.traccar.notification.NotificationMail; import org.traccar.notification.NotificationSms; @@ -40,34 +39,23 @@ import com.cloudhopper.smpp.type.SmppChannelException; import com.cloudhopper.smpp.type.SmppTimeoutException; import com.cloudhopper.smpp.type.UnrecoverablePduException; -@Path("users/notifications") +@Path("notifications") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class NotificationResource extends BaseResource { +public class NotificationResource extends ExtendedObjectResource { - @GET - public Collection get(@QueryParam("all") boolean all, - @QueryParam("userId") long userId) throws SQLException { - if (all) { - return Context.getNotificationManager().getAllNotifications(); - } - if (userId == 0) { - userId = getUserId(); - } - Context.getPermissionsManager().checkUser(getUserId(), userId); - return Context.getNotificationManager().getAllUserNotifications(userId); + public NotificationResource() { + super(Notification.class); } - @POST - public Response update(Notification entity) throws SQLException { - Context.getPermissionsManager().checkReadonly(getUserId()); - Context.getPermissionsManager().checkUser(getUserId(), entity.getUserId()); - Context.getNotificationManager().updateNotification(entity); - return Response.ok(entity).build(); + @GET + @Path("types") + public Collection get() { + return Context.getNotificationManager().getAllNotificationTypes(); } - @Path("test") @POST + @Path("test") public Response testMessage() throws MessagingException, RecoverablePduException, UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException { NotificationMail.sendMailSync(getUserId(), new Event("test", 0), null); diff --git a/src/org/traccar/api/resource/UserResource.java b/src/org/traccar/api/resource/UserResource.java index 0eb328ab5..0f6f6edba 100644 --- a/src/org/traccar/api/resource/UserResource.java +++ b/src/org/traccar/api/resource/UserResource.java @@ -85,9 +85,6 @@ public class UserResource extends BaseObjectResource { Context.getDataManager().linkObject(User.class, getUserId(), ManagedUser.class, entity.getId(), true); } Context.getUsersManager().refreshUserItems(); - if (Context.getNotificationManager() != null) { - Context.getNotificationManager().refresh(); - } return Response.ok(entity).build(); } diff --git a/src/org/traccar/database/CommandsManager.java b/src/org/traccar/database/CommandsManager.java index deb802b29..521a2e1d1 100644 --- a/src/org/traccar/database/CommandsManager.java +++ b/src/org/traccar/database/CommandsManager.java @@ -26,7 +26,7 @@ import org.traccar.BaseProtocol; import org.traccar.Context; import org.traccar.helper.Log; import org.traccar.model.Command; -import org.traccar.model.CommandType; +import org.traccar.model.Typed; import org.traccar.model.Position; public class CommandsManager extends ExtendedObjectManager { @@ -102,29 +102,29 @@ public class CommandsManager extends ExtendedObjectManager { return result; } - public Collection getCommandTypes(long deviceId, boolean textChannel) { - List result = new ArrayList<>(); + public Collection getCommandTypes(long deviceId, boolean textChannel) { + List result = new ArrayList<>(); Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); if (lastPosition != null) { BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); Collection commands; commands = textChannel ? protocol.getSupportedTextCommands() : protocol.getSupportedDataCommands(); for (String commandKey : commands) { - result.add(new CommandType(commandKey)); + result.add(new Typed(commandKey)); } } else { - result.add(new CommandType(Command.TYPE_CUSTOM)); + result.add(new Typed(Command.TYPE_CUSTOM)); } return result; } - public Collection getAllCommandTypes() { - List result = new ArrayList<>(); + public Collection getAllCommandTypes() { + List result = new ArrayList<>(); Field[] fields = Command.class.getDeclaredFields(); for (Field field : fields) { if (Modifier.isStatic(field.getModifiers()) && field.getName().startsWith("TYPE_")) { try { - result.add(new CommandType(field.get(null).toString())); + result.add(new Typed(field.get(null).toString())); } catch (IllegalArgumentException | IllegalAccessException error) { Log.warning(error); } diff --git a/src/org/traccar/database/DataManager.java b/src/org/traccar/database/DataManager.java index 261541b4d..e88ff7f0d 100644 --- a/src/org/traccar/database/DataManager.java +++ b/src/org/traccar/database/DataManager.java @@ -48,6 +48,7 @@ import org.traccar.model.Event; import org.traccar.model.Geofence; import org.traccar.model.Group; import org.traccar.model.ManagedUser; +import org.traccar.model.Notification; import org.traccar.model.Permission; import org.traccar.model.BaseModel; import org.traccar.model.Calendar; @@ -393,6 +394,8 @@ public class DataManager { return Calendar.class; case "command": return Command.class; + case "notification": + return Notification.class; default: throw new ClassNotFoundException(); } diff --git a/src/org/traccar/database/NotificationManager.java b/src/org/traccar/database/NotificationManager.java index 98cae3499..a6ca0ea66 100644 --- a/src/org/traccar/database/NotificationManager.java +++ b/src/org/traccar/database/NotificationManager.java @@ -1,5 +1,6 @@ /* * Copyright 2016 - 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2016 - 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. @@ -18,57 +19,70 @@ package org.traccar.database; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.sql.SQLException; -import java.util.Collection; -import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; import org.traccar.Context; import org.traccar.helper.Log; import org.traccar.model.Event; import org.traccar.model.Notification; import org.traccar.model.Position; +import org.traccar.model.Typed; import org.traccar.notification.NotificationMail; import org.traccar.notification.NotificationSms; -public class NotificationManager { - - private final DataManager dataManager; - - private final Map> userNotifications = new HashMap<>(); - - private final ReadWriteLock notificationsLock = new ReentrantReadWriteLock(); +public class NotificationManager extends ExtendedObjectManager { public NotificationManager(DataManager dataManager) { - this.dataManager = dataManager; - refresh(); + super(dataManager, Notification.class); + } + + private Set getEffectiveNotifications(long userId, long deviceId) { + Set result = new HashSet<>(); + Set deviceNotifications = getAllDeviceItems(deviceId); + for (long itemId : getUserItems(userId)) { + if (getById(itemId).getAlways() || deviceNotifications.contains(itemId)) { + result.add(itemId); + } + } + return result; } public void updateEvent(Event event, Position position) { try { - dataManager.addObject(event); + getDataManager().addObject(event); } catch (SQLException error) { Log.warning(error); } - Set users = Context.getPermissionsManager().getDeviceUsers(event.getDeviceId()); + long deviceId = event.getDeviceId(); + Set users = Context.getPermissionsManager().getDeviceUsers(deviceId); for (long userId : users) { if (event.getGeofenceId() == 0 || Context.getGeofenceManager() != null && Context.getGeofenceManager().checkItemPermission(userId, event.getGeofenceId())) { - Notification notification = getUserNotificationByType(userId, event.getType()); - if (notification != null) { - if (notification.getWeb()) { - Context.getConnectionManager().updateEvent(userId, event); - } - if (notification.getMail()) { - NotificationMail.sendMailAsync(userId, event, position); + boolean webSent = false; + boolean mailSent = false; + boolean smsSent = Context.getSmppManager() == null; + for (long notificationId : getEffectiveNotifications(userId, deviceId)) { + Notification notification = getById(notificationId); + if (getById(notificationId).getType().equals(event.getType())) { + if (!webSent && notification.getWeb()) { + Context.getConnectionManager().updateEvent(userId, event); + webSent = true; + } + if (!mailSent && notification.getMail()) { + NotificationMail.sendMailAsync(userId, event, position); + mailSent = true; + } + if (!smsSent && notification.getSms()) { + NotificationSms.sendSmsAsync(userId, event, position); + smsSent = true; + } } - if (notification.getSms()) { - NotificationSms.sendSmsAsync(userId, event, position); + if (webSent && mailSent && smsSent) { + break; } } } @@ -84,135 +98,18 @@ public class NotificationManager { } } - private Set getUserNotificationsUnsafe(long userId) { - if (!userNotifications.containsKey(userId)) { - userNotifications.put(userId, new HashSet()); - } - return userNotifications.get(userId); - } - - public Set getUserNotifications(long userId) { - notificationsLock.readLock().lock(); - try { - return getUserNotificationsUnsafe(userId); - } finally { - notificationsLock.readLock().unlock(); - } - } - - public final void refresh() { - if (dataManager != null) { - try { - notificationsLock.writeLock().lock(); - try { - userNotifications.clear(); - for (Notification notification : dataManager.getObjects(Notification.class)) { - getUserNotificationsUnsafe(notification.getUserId()).add(notification); - } - } finally { - notificationsLock.writeLock().unlock(); - } - } catch (SQLException error) { - Log.warning(error); - } - } - } - - public Notification getUserNotificationByType(long userId, String type) { - notificationsLock.readLock().lock(); - try { - for (Notification notification : getUserNotificationsUnsafe(userId)) { - if (notification.getType().equals(type)) { - return notification; - } - } - } finally { - notificationsLock.readLock().unlock(); - } - return null; - } - - public void updateNotification(Notification notification) { - Notification cachedNotification = getUserNotificationByType(notification.getUserId(), notification.getType()); - if (cachedNotification != null) { - if (cachedNotification.getWeb() != notification.getWeb() - || cachedNotification.getMail() != notification.getMail() - || cachedNotification.getSms() != notification.getSms()) { - if (!notification.getWeb() && !notification.getMail() && !notification.getSms()) { - try { - dataManager.removeObject(Notification.class, cachedNotification.getId()); - } catch (SQLException error) { - Log.warning(error); - } - notificationsLock.writeLock().lock(); - try { - getUserNotificationsUnsafe(notification.getUserId()).remove(cachedNotification); - } finally { - notificationsLock.writeLock().unlock(); - } - } else { - notificationsLock.writeLock().lock(); - try { - cachedNotification.setWeb(notification.getWeb()); - cachedNotification.setMail(notification.getMail()); - cachedNotification.setSms(notification.getSms()); - cachedNotification.setAttributes(notification.getAttributes()); - } finally { - notificationsLock.writeLock().unlock(); - } - try { - dataManager.updateObject(cachedNotification); - } catch (SQLException error) { - Log.warning(error); - } - } - } else { - notification.setId(cachedNotification.getId()); - } - } else if (notification.getWeb() || notification.getMail() || notification.getSms()) { - try { - dataManager.addObject(notification); - } catch (SQLException error) { - Log.warning(error); - } - notificationsLock.writeLock().lock(); - try { - getUserNotificationsUnsafe(notification.getUserId()).add(notification); - } finally { - notificationsLock.writeLock().unlock(); - } - } - } - - public Set getAllNotifications() { - Set notifications = new HashSet<>(); - long id = 1; + public Set getAllNotificationTypes() { + Set types = new HashSet<>(); Field[] fields = Event.class.getDeclaredFields(); for (Field field : fields) { if (Modifier.isStatic(field.getModifiers()) && field.getName().startsWith("TYPE_")) { try { - Notification notification = new Notification(); - notification.setType(field.get(null).toString()); - notification.setId(id++); - notifications.add(notification); + types.add(new Typed(field.get(null).toString())); } catch (IllegalArgumentException | IllegalAccessException error) { Log.warning(error); } } } - return notifications; + return types; } - - public Collection getAllUserNotifications(long userId) { - Map notifications = new HashMap<>(); - for (Notification notification : getAllNotifications()) { - notification.setUserId(userId); - notifications.put(notification.getType(), notification); - } - for (Notification notification : getUserNotifications(userId)) { - notifications.put(notification.getType(), notification); - } - return notifications.values(); - } - } diff --git a/src/org/traccar/database/PermissionsManager.java b/src/org/traccar/database/PermissionsManager.java index 0d9c780a6..07b60ba58 100644 --- a/src/org/traccar/database/PermissionsManager.java +++ b/src/org/traccar/database/PermissionsManager.java @@ -26,6 +26,7 @@ import org.traccar.model.Driver; import org.traccar.model.Geofence; import org.traccar.model.Group; import org.traccar.model.ManagedUser; +import org.traccar.model.Notification; import org.traccar.model.Permission; import org.traccar.model.Server; import org.traccar.model.User; @@ -320,6 +321,8 @@ public class PermissionsManager { manager = Context.getCalendarManager(); } else if (object.equals(Command.class)) { manager = Context.getCommandsManager(); + } else if (object.equals(Notification.class)) { + manager = Context.getNotificationManager(); } else { throw new IllegalArgumentException("Unknown object type"); } @@ -344,7 +347,7 @@ public class PermissionsManager { Context.getAttributesManager().refreshUserItems(); Context.getCommandsManager().refreshUserItems(); if (Context.getNotificationManager() != null) { - Context.getNotificationManager().refresh(); + Context.getNotificationManager().refreshUserItems(); } } @@ -375,6 +378,9 @@ public class PermissionsManager { Context.getCalendarManager().refreshUserItems(); } else if (permission.getPropertyClass().equals(Command.class)) { Context.getCommandsManager().refreshUserItems(); + } else if (permission.getPropertyClass().equals(Notification.class) + && Context.getNotificationManager() != null) { + Context.getNotificationManager().refreshUserItems(); } } else if (permission.getOwnerClass().equals(Device.class) || permission.getOwnerClass().equals(Group.class)) { if (permission.getPropertyClass().equals(Geofence.class) && Context.getGeofenceManager() != null) { @@ -385,6 +391,9 @@ public class PermissionsManager { Context.getAttributesManager().refreshExtendedPermissions(); } else if (permission.getPropertyClass().equals(Command.class)) { Context.getCommandsManager().refreshExtendedPermissions(); + } else if (permission.getPropertyClass().equals(Notification.class) + && Context.getNotificationManager() != null) { + Context.getNotificationManager().refreshExtendedPermissions(); } } } diff --git a/src/org/traccar/model/CommandType.java b/src/org/traccar/model/CommandType.java deleted file mode 100644 index 210316f71..000000000 --- a/src/org/traccar/model/CommandType.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2016 Gabor Somogyi (gabor.g.somogyi@gmail.com) - * - * 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.model; - -public class CommandType { - - private String type; - - public CommandType(String type) { - this.type = type; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } -} diff --git a/src/org/traccar/model/Notification.java b/src/org/traccar/model/Notification.java index e7bb69903..9d6034fff 100644 --- a/src/org/traccar/model/Notification.java +++ b/src/org/traccar/model/Notification.java @@ -17,14 +17,14 @@ package org.traccar.model; public class Notification extends ExtendedModel { - private long userId; + private boolean always; - public long getUserId() { - return userId; + public boolean getAlways() { + return always; } - public void setUserId(long userId) { - this.userId = userId; + public void setAlways(boolean always) { + this.always = always; } private String type; diff --git a/src/org/traccar/model/Typed.java b/src/org/traccar/model/Typed.java new file mode 100644 index 000000000..313ec7bcd --- /dev/null +++ b/src/org/traccar/model/Typed.java @@ -0,0 +1,33 @@ +/* + * Copyright 2016 Gabor Somogyi (gabor.g.somogyi@gmail.com) + * + * 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.model; + +public class Typed { + + private String type; + + public Typed(String type) { + this.type = type; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/swagger.json b/swagger.json index 762ef3525..5f9abb9b8 100644 --- a/swagger.json +++ b/swagger.json @@ -627,19 +627,25 @@ } } }, - "/users/notifications": { + "/notifications": { "get": { - "summary": "Fetch a list of Notification types", - "description": "Without params, it returns a list of the user's enabled Notifications", + "summary": "Fetch a list of Notifications", + "description": "Without params, it returns a list of Notifications the user has access to", "parameters": [ { - "name": "all", - "in": "query", - "description": "To fetch a list of all available Notifications", - "type": "boolean" + "$ref": "#/parameters/all" }, { "$ref": "#/parameters/userId" + }, + { + "$ref": "#/parameters/deviceId" + }, + { + "$ref": "#/parameters/groupId" + }, + { + "$ref": "#/parameters/refresh" } ], "responses": { @@ -655,16 +661,32 @@ } }, "post": { - "summary": "Set or unset a Notification", + "summary": "Create a Notification", "parameters": [ { - "name": "body", - "in": "body", - "required": true, + "$ref": "#/parameters/Notification" + } + ], + "responses": { + "200": { + "description": "OK", "schema": { "$ref": "#/definitions/Notification" } } + } + } + }, + "/notifications/{id}": { + "put": { + "summary": "Update a Notification", + "parameters": [ + { + "$ref": "#/parameters/entityId" + }, + { + "$ref": "#/parameters/Notification" + } ], "responses": { "200": { @@ -674,6 +696,50 @@ } } } + }, + "delete": { + "summary": "Delete a Notification", + "parameters": [ + { + "$ref": "#/parameters/entityId" + } + ], + "responses": { + "204": { + "description": "No Content" + } + } + } + }, + "/notifications/types": { + "get": { + "summary": "Fetch a list of available Notification types", + "parameters": [], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/NotificationType" + } + } + } + } + } + }, + "/notifications/test": { + "post": { + "summary": "Send test notification to current user via Email and SMS", + "parameters": [], + "responses": { + "204": { + "description": "Successful sending" + }, + "400": { + "description": "Could happen if sending has failed" + } + } } }, "/commandtypes": { @@ -1604,8 +1670,8 @@ "type": { "type": "string" }, - "userId": { - "type": "integer" + "always": { + "type": "boolean" }, "web": { "type": "boolean" @@ -1613,9 +1679,19 @@ "mail": { "type": "boolean" }, + "sms": { + "type": "boolean" + }, "attributes": {} } }, + "NotificationType": { + "properties": { + "type": { + "type": "string" + } + } + }, "Event": { "properties": { "id": { @@ -1966,6 +2042,14 @@ "$ref": "#/definitions/Command" } }, + "Notification": { + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/Notification" + } + }, "deviceIdArray": { "name": "deviceId", "in": "query", -- cgit v1.2.3 From 9daa51652f28066534d42046961990e15b490562 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 20 Sep 2017 13:26:21 +0500 Subject: Move Commandtypes API to Commands --- src/org/traccar/api/resource/CommandResource.java | 12 +++++ .../traccar/api/resource/CommandTypeResource.java | 47 ---------------- swagger.json | 62 +++++++++++----------- 3 files changed, 43 insertions(+), 78 deletions(-) delete mode 100644 src/org/traccar/api/resource/CommandTypeResource.java (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/CommandResource.java b/src/org/traccar/api/resource/CommandResource.java index 6a258497f..7300840f0 100644 --- a/src/org/traccar/api/resource/CommandResource.java +++ b/src/org/traccar/api/resource/CommandResource.java @@ -19,6 +19,7 @@ import org.traccar.Context; import org.traccar.api.ExtendedObjectResource; import org.traccar.database.CommandsManager; import org.traccar.model.Command; +import org.traccar.model.Typed; import java.sql.SQLException; import java.util.Collection; @@ -72,4 +73,15 @@ public class CommandResource extends ExtendedObjectResource { return Response.ok(entity).build(); } + @GET + @Path("types") + public Collection get(@QueryParam("deviceId") long deviceId, + @QueryParam("textChannel") boolean textChannel) { + if (deviceId != 0) { + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + return Context.getCommandsManager().getCommandTypes(deviceId, textChannel); + } else { + return Context.getCommandsManager().getAllCommandTypes(); + } + } } diff --git a/src/org/traccar/api/resource/CommandTypeResource.java b/src/org/traccar/api/resource/CommandTypeResource.java deleted file mode 100644 index 0a904bd8a..000000000 --- a/src/org/traccar/api/resource/CommandTypeResource.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2016 Gabor Somogyi (gabor.g.somogyi@gmail.com) - * 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 org.traccar.Context; -import org.traccar.api.BaseResource; -import org.traccar.model.Typed; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import java.util.Collection; - -@Path("commandtypes") -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) -public class CommandTypeResource extends BaseResource { - - @GET - public Collection get(@QueryParam("deviceId") long deviceId, - @QueryParam("textChannel") boolean textChannel) { - if (deviceId != 0) { - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - return Context.getCommandsManager().getCommandTypes(deviceId, textChannel); - } else { - return Context.getCommandsManager().getAllCommandTypes(); - } - } - -} diff --git a/swagger.json b/swagger.json index 5f9abb9b8..120544798 100644 --- a/swagger.json +++ b/swagger.json @@ -155,6 +155,37 @@ } } }, + "/commands/types": { + "get": { + "summary": "Fetch a list of available Commands for the Device or all possible Commands if Device ommited", + "parameters": [ + { + "name": "deviceId", + "in": "query", + "type": "integer" + }, + { + "name": "textChannel", + "in": "query", + "type": "boolean" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/CommandType" + } + } + }, + "400": { + "description": "Could happen when trying to fetch from a device the user does not have permission" + } + } + } + }, "/devices": { "get": { "summary": "Fetch a list of Devices", @@ -742,37 +773,6 @@ } } }, - "/commandtypes": { - "get": { - "summary": "Fetch a list of available Commands for the Device or all possible Commands if Device ommited", - "parameters": [ - { - "name": "deviceId", - "in": "query", - "type": "integer" - }, - { - "name": "textChannel", - "in": "query", - "type": "boolean" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/CommandType" - } - } - }, - "400": { - "description": "Could happen when trying to fetch from a device the user does not have permission" - } - } - } - }, "/geofences": { "get": { "summary": "Fetch a list of Geofences", -- cgit v1.2.3 From b7a5bb6d48ba0363e9437f44eaa546de16f27aef Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Wed, 20 Sep 2017 14:56:34 +0500 Subject: Add copyright --- src/org/traccar/api/resource/CommandResource.java | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/CommandResource.java b/src/org/traccar/api/resource/CommandResource.java index 7300840f0..8da9f8447 100644 --- a/src/org/traccar/api/resource/CommandResource.java +++ b/src/org/traccar/api/resource/CommandResource.java @@ -1,5 +1,7 @@ /* * Copyright 2015 - 2017 Anton Tananaev (anton@traccar.org) + * Copyright 2016 Gabor Somogyi (gabor.g.somogyi@gmail.com) + * 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. -- cgit v1.2.3 From a2f215fe63bd313bfac2a894c170673ccbc252c4 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Thu, 19 Oct 2017 10:03:02 +0500 Subject: Implement buffered commands --- src/org/traccar/api/resource/CommandResource.java | 8 ++- src/org/traccar/database/CommandsManager.java | 60 ++++++++++++++--------- src/org/traccar/database/ConnectionManager.java | 5 +- swagger.json | 14 ++++-- 4 files changed, 56 insertions(+), 31 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/CommandResource.java b/src/org/traccar/api/resource/CommandResource.java index 8da9f8447..996c15daf 100644 --- a/src/org/traccar/api/resource/CommandResource.java +++ b/src/org/traccar/api/resource/CommandResource.java @@ -62,15 +62,19 @@ public class CommandResource extends ExtendedObjectResource { Context.getPermissionsManager().checkReadonly(getUserId()); long deviceId = entity.getDeviceId(); long id = entity.getId(); + boolean sent; if (deviceId != 0 && id != 0) { Context.getPermissionsManager().checkPermission(Command.class, getUserId(), id); Context.getPermissionsManager().checkDevice(getUserId(), deviceId); Context.getPermissionsManager().checkUserDeviceCommand(getUserId(), deviceId, id); - Context.getCommandsManager().sendCommand(id, deviceId); + sent = Context.getCommandsManager().sendCommand(id, deviceId); } else { Context.getPermissionsManager().checkLimitCommands(getUserId()); Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - Context.getCommandsManager().sendCommand(entity); + sent = Context.getCommandsManager().sendCommand(entity, deviceId); + } + if (!sent) { + return Response.accepted(entity).build(); } return Response.ok(entity).build(); } diff --git a/src/org/traccar/database/CommandsManager.java b/src/org/traccar/database/CommandsManager.java index 521a2e1d1..624fe56cd 100644 --- a/src/org/traccar/database/CommandsManager.java +++ b/src/org/traccar/database/CommandsManager.java @@ -21,6 +21,10 @@ import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; import org.traccar.BaseProtocol; import org.traccar.Context; @@ -31,26 +35,22 @@ import org.traccar.model.Position; public class CommandsManager extends ExtendedObjectManager { - private boolean fallbackToText; + private final Map> deviceQueues = new ConcurrentHashMap<>(); public CommandsManager(DataManager dataManager) { super(dataManager, Command.class); - fallbackToText = Context.getConfig().getBoolean("command.fallbackToSms"); } public boolean checkDeviceCommand(long deviceId, long commandId) { return !getAllDeviceItems(deviceId).contains(commandId); } - public void sendCommand(Command command) throws Exception { - sendCommand(command, command.getDeviceId(), fallbackToText); + public boolean sendCommand(long commandId, long deviceId) throws Exception { + return sendCommand(getById(commandId), deviceId); } - public void sendCommand(long commandId, long deviceId) throws Exception { - sendCommand(getById(commandId), deviceId, false); - } - - public void sendCommand(Command command, long deviceId, boolean fallbackToText) throws Exception { + public boolean sendCommand(Command command, long deviceId) throws Exception { + boolean sent = true; if (command.getTextChannel()) { Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); String phone = Context.getIdentityManager().getById(deviceId).getPhone(); @@ -71,32 +71,26 @@ public class CommandsManager extends ExtendedObjectManager { if (activeDevice != null) { activeDevice.sendCommand(command); } else { - if (fallbackToText) { - command.setTextChannel(true); - sendCommand(command, deviceId, false); - } else { - throw new RuntimeException("Device is not online"); - } + sent = !getDeviceQueue(deviceId).add(command); } } + return sent; } public Collection getSupportedCommands(long deviceId) { List result = new ArrayList<>(); Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); - boolean online = Context.getConnectionManager().getActiveDevice(deviceId) != null; for (long commandId : getAllDeviceItems(deviceId)) { Command command = getById(commandId); - if (command.getTextChannel() || online) { - if (lastPosition != null) { - BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); - if (protocol.getSupportedTextCommands().contains(command.getType()) - || online && protocol.getSupportedDataCommands().contains(command.getType())) { - result.add(commandId); - } - } else if (command.getType().equals(Command.TYPE_CUSTOM)) { + if (lastPosition != null) { + BaseProtocol protocol = Context.getServerManager().getProtocol(lastPosition.getProtocol()); + if ((command.getTextChannel() + ? protocol.getSupportedTextCommands() : protocol.getSupportedDataCommands()) + .contains(command.getType())) { result.add(commandId); } + } else if (command.getType().equals(Command.TYPE_CUSTOM)) { + result.add(commandId); } } return result; @@ -133,4 +127,22 @@ public class CommandsManager extends ExtendedObjectManager { return result; } + private Queue getDeviceQueue(long deviceId) { + if (!deviceQueues.containsKey(deviceId)) { + deviceQueues.put(deviceId, new ConcurrentLinkedQueue()); + } + return deviceQueues.get(deviceId); + } + + public void sendQueuedCommands(ActiveDevice activeDevice) { + Queue deviceQueue = deviceQueues.get(activeDevice.getDeviceId()); + if (deviceQueue != null) { + Command command = deviceQueue.poll(); + while (command != null) { + activeDevice.sendCommand(command); + command = deviceQueue.poll(); + } + } + } + } diff --git a/src/org/traccar/database/ConnectionManager.java b/src/org/traccar/database/ConnectionManager.java index de11db21b..e5a7a272f 100644 --- a/src/org/traccar/database/ConnectionManager.java +++ b/src/org/traccar/database/ConnectionManager.java @@ -57,7 +57,9 @@ public class ConnectionManager { } public void addActiveDevice(long deviceId, Protocol protocol, Channel channel, SocketAddress remoteAddress) { - activeDevices.put(deviceId, new ActiveDevice(deviceId, protocol, channel, remoteAddress)); + ActiveDevice activeDevice = new ActiveDevice(deviceId, protocol, channel, remoteAddress); + activeDevices.put(deviceId, activeDevice); + Context.getCommandsManager().sendQueuedCommands(activeDevice); } public void removeActiveDevice(Channel channel) { @@ -122,6 +124,7 @@ public class ConnectionManager { public void run(Timeout timeout) throws Exception { if (!timeout.isCancelled()) { updateDevice(deviceId, Device.STATUS_UNKNOWN, null); + activeDevices.remove(deviceId); } } }, deviceTimeout, TimeUnit.MILLISECONDS)); diff --git a/swagger.json b/swagger.json index 120544798..82f34ac1d 100644 --- a/swagger.json +++ b/swagger.json @@ -108,11 +108,11 @@ "/commands/send": { "get": { "summary": "Fetch a list of Saved Commands supported by Device at the moment", - "description": "Return a list of saved commands linked to Device and its groups, filtered by current Device state and protocol support", + "description": "Return a list of saved commands linked to Device and its groups, filtered by current Device protocol support", "parameters": [ { "$ref": "#/parameters/deviceId" - }, + } ], "responses": { "200": { @@ -144,13 +144,19 @@ ], "responses": { "200": { - "description": "OK", + "description": "Command sent", + "schema": { + "$ref": "#/definitions/Command" + } + }, + "202": { + "description": "Command queued", "schema": { "$ref": "#/definitions/Command" } }, "400": { - "description": "Could happen when dispatching to a device that is offline, the user doesn't have permission or an incorrect command _type_ for the device" + "description": "Could happen when the user doesn't have permission or an incorrect command _type_ for the device" } } } -- cgit v1.2.3 From ed72ff6e7f964bc56a4948c15c97f37c072bf326 Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Sun, 22 Oct 2017 18:55:34 +0500 Subject: Set deviceId in Saved Command before send --- src/org/traccar/api/resource/CommandResource.java | 9 +++------ src/org/traccar/database/CommandsManager.java | 14 +++++++++----- 2 files changed, 12 insertions(+), 11 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/CommandResource.java b/src/org/traccar/api/resource/CommandResource.java index 996c15daf..a25421e31 100644 --- a/src/org/traccar/api/resource/CommandResource.java +++ b/src/org/traccar/api/resource/CommandResource.java @@ -62,17 +62,14 @@ public class CommandResource extends ExtendedObjectResource { Context.getPermissionsManager().checkReadonly(getUserId()); long deviceId = entity.getDeviceId(); long id = entity.getId(); - boolean sent; - if (deviceId != 0 && id != 0) { + Context.getPermissionsManager().checkDevice(getUserId(), deviceId); + if (id != 0) { Context.getPermissionsManager().checkPermission(Command.class, getUserId(), id); - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); Context.getPermissionsManager().checkUserDeviceCommand(getUserId(), deviceId, id); - sent = Context.getCommandsManager().sendCommand(id, deviceId); } else { Context.getPermissionsManager().checkLimitCommands(getUserId()); - Context.getPermissionsManager().checkDevice(getUserId(), deviceId); - sent = Context.getCommandsManager().sendCommand(entity, deviceId); } + boolean sent = Context.getCommandsManager().sendCommand(entity); if (!sent) { return Response.accepted(entity).build(); } diff --git a/src/org/traccar/database/CommandsManager.java b/src/org/traccar/database/CommandsManager.java index cae4ac6f7..07695cbf7 100644 --- a/src/org/traccar/database/CommandsManager.java +++ b/src/org/traccar/database/CommandsManager.java @@ -45,11 +45,15 @@ public class CommandsManager extends ExtendedObjectManager { return !getAllDeviceItems(deviceId).contains(commandId); } - public boolean sendCommand(long commandId, long deviceId) throws Exception { - return sendCommand(getById(commandId), deviceId); - } - - public boolean sendCommand(Command command, long deviceId) throws Exception { + public boolean sendCommand(Command command) throws Exception { + long deviceId = command.getDeviceId(); + if (command.getId() != 0) { + Command savedCommand = getById(command.getId()); + command.setTextChannel(savedCommand.getTextChannel()); + command.setType(savedCommand.getType()); + command.setAttributes(savedCommand.getAttributes()); + command.setDescription(savedCommand.getDescription()); + } boolean sent = true; if (command.getTextChannel()) { Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); -- cgit v1.2.3 From 0283458de495e8f9f5393b1184c7a670e9851dcc Mon Sep 17 00:00:00 2001 From: Abyss777 Date: Mon, 23 Oct 2017 09:50:35 +0500 Subject: Implement command cloning --- src/org/traccar/api/resource/CommandResource.java | 3 +-- src/org/traccar/database/CommandsManager.java | 13 +++++-------- src/org/traccar/model/Command.java | 7 ++++++- 3 files changed, 12 insertions(+), 11 deletions(-) (limited to 'src/org/traccar/api') diff --git a/src/org/traccar/api/resource/CommandResource.java b/src/org/traccar/api/resource/CommandResource.java index a25421e31..703638701 100644 --- a/src/org/traccar/api/resource/CommandResource.java +++ b/src/org/traccar/api/resource/CommandResource.java @@ -69,8 +69,7 @@ public class CommandResource extends ExtendedObjectResource { } else { Context.getPermissionsManager().checkLimitCommands(getUserId()); } - boolean sent = Context.getCommandsManager().sendCommand(entity); - if (!sent) { + if (!Context.getCommandsManager().sendCommand(entity)) { return Response.accepted(entity).build(); } return Response.ok(entity).build(); diff --git a/src/org/traccar/database/CommandsManager.java b/src/org/traccar/database/CommandsManager.java index 07695cbf7..9ceb995ef 100644 --- a/src/org/traccar/database/CommandsManager.java +++ b/src/org/traccar/database/CommandsManager.java @@ -48,13 +48,9 @@ public class CommandsManager extends ExtendedObjectManager { public boolean sendCommand(Command command) throws Exception { long deviceId = command.getDeviceId(); if (command.getId() != 0) { - Command savedCommand = getById(command.getId()); - command.setTextChannel(savedCommand.getTextChannel()); - command.setType(savedCommand.getType()); - command.setAttributes(savedCommand.getAttributes()); - command.setDescription(savedCommand.getDescription()); + command = getById(command.getId()).clone(); + command.setDeviceId(deviceId); } - boolean sent = true; if (command.getTextChannel()) { Position lastPosition = Context.getIdentityManager().getLastPosition(deviceId); String phone = Context.getIdentityManager().getById(deviceId).getPhone(); @@ -75,10 +71,11 @@ public class CommandsManager extends ExtendedObjectManager { if (activeDevice != null) { activeDevice.sendCommand(command); } else { - sent = !getDeviceQueue(deviceId).add(command); + getDeviceQueue(deviceId).add(command); + return false; } } - return sent; + return true; } public Collection getSupportedCommands(long deviceId) { diff --git a/src/org/traccar/model/Command.java b/src/org/traccar/model/Command.java index 67134dc7d..09f0f251b 100644 --- a/src/org/traccar/model/Command.java +++ b/src/org/traccar/model/Command.java @@ -20,7 +20,7 @@ import org.traccar.database.QueryIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) -public class Command extends Message { +public class Command extends Message implements Cloneable { public static final String TYPE_CUSTOM = "custom"; public static final String TYPE_IDENTIFICATION = "deviceIdentification"; @@ -77,6 +77,11 @@ public class Command extends Message { public static final String KEY_SERVER = "server"; public static final String KEY_PORT = "port"; + @Override + public Command clone() throws CloneNotSupportedException { + return (Command) super.clone(); + } + private boolean textChannel; public boolean getTextChannel() { -- cgit v1.2.3