From ce661ec77a957b70c15509c6801e6f34b32ad11d Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Mon, 30 May 2022 13:12:37 -0700 Subject: Improve dependency injection --- src/main/java/org/traccar/WebDataHandler.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src/main/java/org/traccar/WebDataHandler.java') diff --git a/src/main/java/org/traccar/WebDataHandler.java b/src/main/java/org/traccar/WebDataHandler.java index 678096d34..2c0aa0f8e 100644 --- a/src/main/java/org/traccar/WebDataHandler.java +++ b/src/main/java/org/traccar/WebDataHandler.java @@ -287,8 +287,10 @@ public class WebDataHandler extends BaseDataHandler { @Override protected Position handlePosition(Position position) { - AsyncRequestAndCallback request = new AsyncRequestAndCallback(position); - request.send(); + if (url != null) { + AsyncRequestAndCallback request = new AsyncRequestAndCallback(position); + request.send(); + } return position; } -- cgit v1.2.3 From d3e83f9fa0d066e5a15fde225599cc43071c031a Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Thu, 16 Jun 2022 07:09:00 -0700 Subject: Remove groups manager --- src/main/java/org/traccar/Context.java | 13 +-- src/main/java/org/traccar/WebDataHandler.java | 8 +- .../java/org/traccar/api/BaseObjectResource.java | 11 +- .../java/org/traccar/database/DeviceManager.java | 9 +- .../traccar/database/ExtendedObjectManager.java | 115 --------------------- .../java/org/traccar/database/GroupsManager.java | 64 ------------ .../org/traccar/database/PermissionsManager.java | 11 +- .../org/traccar/reports/EventsReportProvider.java | 5 +- .../org/traccar/reports/RouteReportProvider.java | 8 +- .../org/traccar/reports/StopsReportProvider.java | 8 +- .../org/traccar/reports/TripsReportProvider.java | 8 +- src/test/java/org/traccar/WebDataHandlerTest.java | 3 +- 12 files changed, 48 insertions(+), 215 deletions(-) delete mode 100644 src/main/java/org/traccar/database/ExtendedObjectManager.java delete mode 100644 src/main/java/org/traccar/database/GroupsManager.java (limited to 'src/main/java/org/traccar/WebDataHandler.java') diff --git a/src/main/java/org/traccar/Context.java b/src/main/java/org/traccar/Context.java index cbbc73d76..9e8e3c521 100644 --- a/src/main/java/org/traccar/Context.java +++ b/src/main/java/org/traccar/Context.java @@ -19,14 +19,13 @@ import org.traccar.config.Config; import org.traccar.database.BaseObjectManager; import org.traccar.database.DataManager; import org.traccar.database.DeviceManager; -import org.traccar.database.GroupsManager; import org.traccar.database.IdentityManager; import org.traccar.database.PermissionsManager; import org.traccar.helper.Log; import org.traccar.model.BaseModel; import org.traccar.model.Device; -import org.traccar.model.Group; import org.traccar.session.ConnectionManager; +import org.traccar.session.cache.CacheManager; import org.traccar.storage.Storage; public final class Context { @@ -46,12 +45,6 @@ public final class Context { return identityManager; } - private static GroupsManager groupsManager; - - public static GroupsManager getGroupsManager() { - return groupsManager; - } - private static DeviceManager deviceManager; public static DeviceManager getDeviceManager() { @@ -75,9 +68,9 @@ public final class Context { throw e; } - groupsManager = new GroupsManager(Main.getInjector().getInstance(DataManager.class)); deviceManager = new DeviceManager( config, + Main.getInjector().getInstance(CacheManager.class), Main.getInjector().getInstance(DataManager.class), Main.getInjector().getInstance(ConnectionManager.class)); @@ -92,8 +85,6 @@ public final class Context { public static BaseObjectManager getManager(Class clazz) { if (clazz.equals(Device.class)) { return (BaseObjectManager) deviceManager; - } else if (clazz.equals(Group.class)) { - return (BaseObjectManager) groupsManager; } return null; } diff --git a/src/main/java/org/traccar/WebDataHandler.java b/src/main/java/org/traccar/WebDataHandler.java index 2c0aa0f8e..db99ecaf8 100644 --- a/src/main/java/org/traccar/WebDataHandler.java +++ b/src/main/java/org/traccar/WebDataHandler.java @@ -31,6 +31,7 @@ import org.traccar.helper.Checksum; import org.traccar.model.Device; import org.traccar.model.Position; import org.traccar.model.Group; +import org.traccar.session.cache.CacheManager; import javax.inject.Inject; import javax.ws.rs.core.HttpHeaders; @@ -60,6 +61,7 @@ public class WebDataHandler extends BaseDataHandler { private static final String KEY_POSITION = "position"; private static final String KEY_DEVICE = "device"; + private final CacheManager cacheManager; private final IdentityManager identityManager; private final ObjectMapper objectMapper; private final Client client; @@ -78,8 +80,10 @@ public class WebDataHandler extends BaseDataHandler { @Inject public WebDataHandler( - Config config, IdentityManager identityManager, ObjectMapper objectMapper, Client client) { + Config config, CacheManager cacheManager, IdentityManager identityManager, + ObjectMapper objectMapper, Client client) { + this.cacheManager = cacheManager; this.identityManager = identityManager; this.objectMapper = objectMapper; this.client = client; @@ -171,7 +175,7 @@ public class WebDataHandler extends BaseDataHandler { if (request.contains("{group}")) { String deviceGroupName = ""; if (device.getGroupId() != 0) { - Group group = Context.getGroupsManager().getById(device.getGroupId()); + Group group = cacheManager.getObject(Group.class, device.getGroupId()); if (group != null) { deviceGroupName = group.getName(); } diff --git a/src/main/java/org/traccar/api/BaseObjectResource.java b/src/main/java/org/traccar/api/BaseObjectResource.java index f8545a5d7..78aa12dbe 100644 --- a/src/main/java/org/traccar/api/BaseObjectResource.java +++ b/src/main/java/org/traccar/api/BaseObjectResource.java @@ -18,7 +18,6 @@ package org.traccar.api; import org.traccar.Context; import org.traccar.database.BaseObjectManager; -import org.traccar.database.ExtendedObjectManager; import org.traccar.helper.LogAction; import org.traccar.model.BaseModel; import org.traccar.model.Device; @@ -92,10 +91,16 @@ public abstract class BaseObjectResource extends BaseResour public Response update(T entity) throws StorageException { permissionsService.checkEdit(getUserId(), entity, false); permissionsService.checkPermission(baseClass, getUserId(), entity.getId()); + if (entity instanceof User) { User before = storage.getObject(User.class, new Request( new Columns.All(), new Condition.Equals("id", "id", entity.getId()))); permissionsService.checkUserUpdate(getUserId(), before, (User) entity); + } else if (entity instanceof Group) { + Group group = (Group) entity; + if (group.getId() == group.getGroupId()) { + throw new IllegalArgumentException("Cycle in group hierarchy"); + } } BaseObjectManager manager = Context.getManager(baseClass); @@ -125,9 +130,6 @@ public abstract class BaseObjectResource extends BaseResour BaseObjectManager manager = Context.getManager(baseClass); if (manager != null) { manager.removeItem(id); - if (manager instanceof ExtendedObjectManager) { - ((ExtendedObjectManager) manager).refreshExtendedPermissions(); - } } else { storage.removeObject(baseClass, new Request(new Condition.Equals("id", "id", id))); } @@ -137,7 +139,6 @@ public abstract class BaseObjectResource extends BaseResour if (baseClass.equals(Group.class) || baseClass.equals(Device.class) || baseClass.equals(User.class)) { if (baseClass.equals(Group.class)) { - Context.getGroupsManager().refreshItems(); Context.getDeviceManager().updateDeviceCache(true); } Context.getPermissionsManager().refreshDeviceAndGroupPermissions(); diff --git a/src/main/java/org/traccar/database/DeviceManager.java b/src/main/java/org/traccar/database/DeviceManager.java index 9ba486988..29c17c41f 100644 --- a/src/main/java/org/traccar/database/DeviceManager.java +++ b/src/main/java/org/traccar/database/DeviceManager.java @@ -46,6 +46,7 @@ public class DeviceManager extends BaseObjectManager implements Identity private static final Logger LOGGER = LoggerFactory.getLogger(DeviceManager.class); private final Config config; + private final CacheManager cacheManager; private final ConnectionManager connectionManager; private final long dataRefreshDelay; @@ -56,9 +57,11 @@ public class DeviceManager extends BaseObjectManager implements Identity private final Map deviceStates = new ConcurrentHashMap<>(); - public DeviceManager(Config config, DataManager dataManager, ConnectionManager connectionManager) { + public DeviceManager( + Config config, CacheManager cacheManager, DataManager dataManager, ConnectionManager connectionManager) { super(dataManager, Device.class); this.config = config; + this.cacheManager = cacheManager; this.connectionManager = connectionManager; try { writeLock(); @@ -351,8 +354,8 @@ public class DeviceManager extends BaseObjectManager implements Identity result = device.getAttributes().get(attributeName); if (result == null) { long groupId = device.getGroupId(); - while (groupId != 0) { - Group group = Context.getGroupsManager().getById(groupId); + while (groupId > 0) { + Group group = cacheManager.getObject(Group.class, device.getGroupId()); if (group != null) { result = group.getAttributes().get(attributeName); if (result != null) { diff --git a/src/main/java/org/traccar/database/ExtendedObjectManager.java b/src/main/java/org/traccar/database/ExtendedObjectManager.java deleted file mode 100644 index fe0ebb96e..000000000 --- a/src/main/java/org/traccar/database/ExtendedObjectManager.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2017 - 2020 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.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.traccar.Context; -import org.traccar.model.Device; -import org.traccar.model.Group; -import org.traccar.model.Permission; -import org.traccar.model.BaseModel; -import org.traccar.storage.StorageException; - -public abstract class ExtendedObjectManager extends SimpleObjectManager { - - private static final Logger LOGGER = LoggerFactory.getLogger(ExtendedObjectManager.class); - - private final Map> deviceItems = new ConcurrentHashMap<>(); - private final Map> deviceItemsWithGroups = new ConcurrentHashMap<>(); - private final Map> groupItems = new ConcurrentHashMap<>(); - - protected ExtendedObjectManager(DataManager dataManager, Class baseClass) { - super(dataManager, baseClass); - refreshExtendedPermissions(); - } - - public Set getAllDeviceItems(long deviceId) { - try { - readLock(); - Set result = deviceItemsWithGroups.get(deviceId); - if (result != null) { - return new HashSet<>(result); - } else { - return new HashSet<>(); - } - } finally { - readUnlock(); - } - } - - @Override - public void removeItem(long itemId) throws StorageException { - super.removeItem(itemId); - refreshExtendedPermissions(); - } - - public void refreshExtendedPermissions() { - if (getDataManager() != null) { - try { - Collection databaseGroupPermissions = - getDataManager().getPermissions(Group.class, getBaseClass()); - - Collection databaseDevicePermissions = - getDataManager().getPermissions(Device.class, getBaseClass()); - - writeLock(); - - groupItems.clear(); - deviceItems.clear(); - deviceItemsWithGroups.clear(); - - for (Permission groupPermission : databaseGroupPermissions) { - groupItems - .computeIfAbsent(groupPermission.getOwnerId(), key -> new HashSet<>()) - .add(groupPermission.getPropertyId()); - } - - for (Permission devicePermission : databaseDevicePermissions) { - deviceItems - .computeIfAbsent(devicePermission.getOwnerId(), key -> new HashSet<>()) - .add(devicePermission.getPropertyId()); - deviceItemsWithGroups - .computeIfAbsent(devicePermission.getOwnerId(), key -> new HashSet<>()) - .add(devicePermission.getPropertyId()); - } - - for (Device device : getDataManager().getObjects(Device.class)) { - long groupId = device.getGroupId(); - while (groupId > 0) { - deviceItemsWithGroups - .computeIfAbsent(device.getId(), key -> new HashSet<>()) - .addAll(groupItems.getOrDefault(groupId, new HashSet<>())); - Group group = Context.getGroupsManager().getById(groupId); - groupId = group != null ? group.getGroupId() : 0; - } - } - - } catch (StorageException | ClassNotFoundException error) { - LOGGER.warn("Refresh permissions error", error); - } finally { - writeUnlock(); - } - } - } -} diff --git a/src/main/java/org/traccar/database/GroupsManager.java b/src/main/java/org/traccar/database/GroupsManager.java deleted file mode 100644 index 4df848042..000000000 --- a/src/main/java/org/traccar/database/GroupsManager.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2017 - 2022 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.HashSet; -import java.util.Set; - -import org.traccar.model.Group; -import org.traccar.storage.StorageException; - -public class GroupsManager extends BaseObjectManager { - - public GroupsManager(DataManager dataManager) { - super(dataManager, Group.class); - } - - 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 = getById(group.getGroupId()); - } - } - - @Override - public Set getAllItems() { - Set result = super.getAllItems(); - if (result.isEmpty()) { - refreshItems(); - result = super.getAllItems(); - } - return result; - } - - @Override - protected void addNewItem(Group group) { - checkGroupCycles(group); - super.addNewItem(group); - } - - @Override - public void updateItem(Group group) throws StorageException { - checkGroupCycles(group); - super.updateItem(group); - } - -} diff --git a/src/main/java/org/traccar/database/PermissionsManager.java b/src/main/java/org/traccar/database/PermissionsManager.java index 833480eea..595e236fa 100644 --- a/src/main/java/org/traccar/database/PermissionsManager.java +++ b/src/main/java/org/traccar/database/PermissionsManager.java @@ -162,9 +162,8 @@ public class PermissionsManager { groupPermissions.clear(); devicePermissions.clear(); try { - GroupTree groupTree = new GroupTree(Context.getGroupsManager().getItems( - Context.getGroupsManager().getAllItems()), - Context.getDeviceManager().getAllDevices()); + var groups = dataManager.getObjects(Group.class); + GroupTree groupTree = new GroupTree(groups, Context.getDeviceManager().getAllDevices()); for (Permission groupPermission : dataManager.getPermissions(User.class, Group.class)) { Set userGroupPermissions = getGroupPermissions(groupPermission.getOwnerId()); Set userDevicePermissions = getDevicePermissions(groupPermission.getOwnerId()); @@ -182,9 +181,9 @@ public class PermissionsManager { } groupDevices.clear(); - for (long groupId : Context.getGroupsManager().getAllItems()) { - for (Device device : groupTree.getDevices(groupId)) { - getGroupDevices(groupId).add(device.getId()); + for (var group : groups) { + for (Device device : groupTree.getDevices(group.getId())) { + getGroupDevices(group.getId()).add(device.getId()); } } diff --git a/src/main/java/org/traccar/reports/EventsReportProvider.java b/src/main/java/org/traccar/reports/EventsReportProvider.java index 5148695a9..b1f7149a2 100644 --- a/src/main/java/org/traccar/reports/EventsReportProvider.java +++ b/src/main/java/org/traccar/reports/EventsReportProvider.java @@ -134,8 +134,9 @@ public class EventsReportProvider { Device device = Context.getIdentityManager().getById(deviceId); deviceEvents.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceEvents.getDeviceName())); - if (device.getGroupId() != 0) { - Group group = Context.getGroupsManager().getById(device.getGroupId()); + if (device.getGroupId() > 0) { + Group group = storage.getObject(Group.class, new Request( + new Columns.All(), new Condition.Equals("id", "id", device.getGroupId()))); if (group != null) { deviceEvents.setGroupName(group.getName()); } diff --git a/src/main/java/org/traccar/reports/RouteReportProvider.java b/src/main/java/org/traccar/reports/RouteReportProvider.java index b1a806960..903dfe369 100644 --- a/src/main/java/org/traccar/reports/RouteReportProvider.java +++ b/src/main/java/org/traccar/reports/RouteReportProvider.java @@ -28,6 +28,9 @@ import org.traccar.reports.common.ReportUtils; import org.traccar.reports.model.DeviceReportSection; import org.traccar.storage.Storage; import org.traccar.storage.StorageException; +import org.traccar.storage.query.Columns; +import org.traccar.storage.query.Condition; +import org.traccar.storage.query.Request; import javax.inject.Inject; import java.io.File; @@ -77,8 +80,9 @@ public class RouteReportProvider { Device device = Context.getIdentityManager().getById(deviceId); deviceRoutes.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceRoutes.getDeviceName())); - if (device.getGroupId() != 0) { - Group group = Context.getGroupsManager().getById(device.getGroupId()); + if (device.getGroupId() > 0) { + Group group = storage.getObject(Group.class, new Request( + new Columns.All(), new Condition.Equals("id", "id", device.getGroupId()))); if (group != null) { deviceRoutes.setGroupName(group.getName()); } diff --git a/src/main/java/org/traccar/reports/StopsReportProvider.java b/src/main/java/org/traccar/reports/StopsReportProvider.java index a6a9a94cc..b9d36eb97 100644 --- a/src/main/java/org/traccar/reports/StopsReportProvider.java +++ b/src/main/java/org/traccar/reports/StopsReportProvider.java @@ -28,6 +28,9 @@ import org.traccar.reports.model.DeviceReportSection; import org.traccar.reports.model.StopReportItem; import org.traccar.storage.Storage; import org.traccar.storage.StorageException; +import org.traccar.storage.query.Columns; +import org.traccar.storage.query.Condition; +import org.traccar.storage.query.Request; import javax.inject.Inject; import java.io.File; @@ -85,8 +88,9 @@ public class StopsReportProvider { Device device = Context.getIdentityManager().getById(deviceId); deviceStops.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceStops.getDeviceName())); - if (device.getGroupId() != 0) { - Group group = Context.getGroupsManager().getById(device.getGroupId()); + if (device.getGroupId() > 0) { + Group group = storage.getObject(Group.class, new Request( + new Columns.All(), new Condition.Equals("id", "id", device.getGroupId()))); if (group != null) { deviceStops.setGroupName(group.getName()); } diff --git a/src/main/java/org/traccar/reports/TripsReportProvider.java b/src/main/java/org/traccar/reports/TripsReportProvider.java index bff559664..97cfccf74 100644 --- a/src/main/java/org/traccar/reports/TripsReportProvider.java +++ b/src/main/java/org/traccar/reports/TripsReportProvider.java @@ -28,6 +28,9 @@ import org.traccar.reports.model.DeviceReportSection; import org.traccar.reports.model.TripReportItem; import org.traccar.storage.Storage; import org.traccar.storage.StorageException; +import org.traccar.storage.query.Columns; +import org.traccar.storage.query.Condition; +import org.traccar.storage.query.Request; import javax.inject.Inject; import java.io.File; @@ -85,8 +88,9 @@ public class TripsReportProvider { Device device = Context.getIdentityManager().getById(deviceId); deviceTrips.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceTrips.getDeviceName())); - if (device.getGroupId() != 0) { - Group group = Context.getGroupsManager().getById(device.getGroupId()); + if (device.getGroupId() > 0) { + Group group = storage.getObject(Group.class, new Request( + new Columns.All(), new Condition.Equals("id", "id", device.getGroupId()))); if (group != null) { deviceTrips.setGroupName(group.getName()); } diff --git a/src/test/java/org/traccar/WebDataHandlerTest.java b/src/test/java/org/traccar/WebDataHandlerTest.java index aaec9f530..ff9c80ce6 100644 --- a/src/test/java/org/traccar/WebDataHandlerTest.java +++ b/src/test/java/org/traccar/WebDataHandlerTest.java @@ -6,6 +6,7 @@ import org.traccar.config.Keys; import org.traccar.database.IdentityManager; import org.traccar.model.Device; import org.traccar.model.Position; +import org.traccar.session.cache.CacheManager; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyLong; @@ -30,7 +31,7 @@ public class WebDataHandlerTest extends ProtocolTest { var identityManager = mock(IdentityManager.class); when(identityManager.getById(anyLong())).thenReturn(device); - WebDataHandler handler = new WebDataHandler(config, identityManager, null, null); + WebDataHandler handler = new WebDataHandler(config, mock(CacheManager.class), identityManager, null, null); assertEquals( "http://localhost/?fixTime=1451610123000&gprmc=$GPRMC,010203.000,A,2000.0000,N,03000.0000,E,0.00,0.00,010116,,*05&name=test", -- cgit v1.2.3 From 03b50c61afd7c9d7e19a76feb261147dd0f69588 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Sat, 18 Jun 2022 11:44:40 -0700 Subject: Remove identity manager --- src/main/java/org/traccar/BaseProtocolDecoder.java | 11 ------ src/main/java/org/traccar/BaseProtocolEncoder.java | 15 +------- src/main/java/org/traccar/Context.java | 9 ----- src/main/java/org/traccar/MainEventHandler.java | 14 +++---- src/main/java/org/traccar/MainModule.java | 6 --- src/main/java/org/traccar/WebDataHandler.java | 10 ++--- .../traccar/api/resource/AttributeResource.java | 4 +- .../java/org/traccar/database/DeviceManager.java | 2 +- .../java/org/traccar/database/IdentityManager.java | 24 ------------ .../traccar/handler/ComputedAttributesHandler.java | 8 +--- .../traccar/protocol/CastelProtocolEncoder.java | 4 +- .../traccar/protocol/GalileoProtocolDecoder.java | 3 +- .../org/traccar/protocol/Gt06ProtocolDecoder.java | 7 +--- .../traccar/protocol/MeiligaoProtocolDecoder.java | 3 +- .../traccar/protocol/MeitrackProtocolDecoder.java | 3 +- .../traccar/protocol/PretraceProtocolEncoder.java | 2 +- .../org/traccar/protocol/Pt502ProtocolDecoder.java | 3 +- .../traccar/protocol/TeltonikaProtocolDecoder.java | 8 ++-- .../org/traccar/reports/EventsReportProvider.java | 3 +- .../org/traccar/reports/RouteReportProvider.java | 3 +- .../org/traccar/reports/StopsReportProvider.java | 3 +- .../org/traccar/reports/SummaryReportProvider.java | 6 +-- .../org/traccar/reports/TripsReportProvider.java | 3 +- .../org/traccar/reports/common/ReportUtils.java | 18 +++++---- src/test/java/org/traccar/BaseTest.java | 9 ----- src/test/java/org/traccar/WebDataHandlerTest.java | 8 ++-- .../traccar/handler/ComputedAttributesTest.java | 2 +- .../java/org/traccar/reports/ReportUtilsTest.java | 43 +++++++++++----------- 28 files changed, 75 insertions(+), 159 deletions(-) delete mode 100644 src/main/java/org/traccar/database/IdentityManager.java (limited to 'src/main/java/org/traccar/WebDataHandler.java') diff --git a/src/main/java/org/traccar/BaseProtocolDecoder.java b/src/main/java/org/traccar/BaseProtocolDecoder.java index f7e726f02..382daf92f 100644 --- a/src/main/java/org/traccar/BaseProtocolDecoder.java +++ b/src/main/java/org/traccar/BaseProtocolDecoder.java @@ -19,7 +19,6 @@ import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import org.traccar.config.Keys; import org.traccar.database.CommandsManager; -import org.traccar.database.IdentityManager; import org.traccar.database.MediaManager; import org.traccar.database.StatisticsManager; import org.traccar.helper.UnitsConverter; @@ -47,7 +46,6 @@ public abstract class BaseProtocolDecoder extends ExtendedObjectDecoder { private final Protocol protocol; - private IdentityManager identityManager; private CacheManager cacheManager; private ConnectionManager connectionManager; private StatisticsManager statisticsManager; @@ -58,15 +56,6 @@ public abstract class BaseProtocolDecoder extends ExtendedObjectDecoder { this.protocol = protocol; } - public IdentityManager getIdentityManager() { - return identityManager; - } - - @Inject - public void setIdentityManager(IdentityManager identityManager) { - this.identityManager = identityManager; - } - public CacheManager getCacheManager() { return cacheManager; } diff --git a/src/main/java/org/traccar/BaseProtocolEncoder.java b/src/main/java/org/traccar/BaseProtocolEncoder.java index 612d91c57..bc1180a08 100644 --- a/src/main/java/org/traccar/BaseProtocolEncoder.java +++ b/src/main/java/org/traccar/BaseProtocolEncoder.java @@ -21,10 +21,10 @@ import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.traccar.database.IdentityManager; import org.traccar.helper.NetworkUtil; import org.traccar.helper.model.AttributeUtil; import org.traccar.model.Command; +import org.traccar.model.Device; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; @@ -39,8 +39,6 @@ public abstract class BaseProtocolEncoder extends ChannelOutboundHandlerAdapter private CacheManager cacheManager; - private IdentityManager identityManager; - public BaseProtocolEncoder(Protocol protocol) { this.protocol = protocol; } @@ -54,21 +52,12 @@ public abstract class BaseProtocolEncoder extends ChannelOutboundHandlerAdapter this.cacheManager = cacheManager; } - public IdentityManager getIdentityManager() { - return identityManager; - } - - @Inject - public void setIdentityManager(IdentityManager identityManager) { - this.identityManager = identityManager; - } - public String getProtocolName() { return protocol != null ? protocol.getName() : PROTOCOL_UNKNOWN; } protected String getUniqueId(long deviceId) { - return identityManager.getById(deviceId).getUniqueId(); + return cacheManager.getObject(Device.class, deviceId).getUniqueId(); } protected void initDevicePassword(Command command, String defaultPassword) { diff --git a/src/main/java/org/traccar/Context.java b/src/main/java/org/traccar/Context.java index c549b20c2..45d075912 100644 --- a/src/main/java/org/traccar/Context.java +++ b/src/main/java/org/traccar/Context.java @@ -19,7 +19,6 @@ import org.traccar.config.Config; import org.traccar.database.BaseObjectManager; import org.traccar.database.DataManager; import org.traccar.database.DeviceManager; -import org.traccar.database.IdentityManager; import org.traccar.database.PermissionsManager; import org.traccar.helper.Log; import org.traccar.model.BaseModel; @@ -37,12 +36,6 @@ public final class Context { return config; } - private static IdentityManager identityManager; - - public static IdentityManager getIdentityManager() { - return identityManager; - } - private static DeviceManager deviceManager; public static DeviceManager getDeviceManager() { @@ -70,8 +63,6 @@ public final class Context { config, Main.getInjector().getInstance(DataManager.class)); - identityManager = deviceManager; - permissionsManager = new PermissionsManager( Main.getInjector().getInstance(DataManager.class), Main.getInjector().getInstance(Storage.class)); diff --git a/src/main/java/org/traccar/MainEventHandler.java b/src/main/java/org/traccar/MainEventHandler.java index e1aee3cc8..d2665cbcc 100644 --- a/src/main/java/org/traccar/MainEventHandler.java +++ b/src/main/java/org/traccar/MainEventHandler.java @@ -74,12 +74,14 @@ public class MainEventHandler extends ChannelInboundHandlerAdapter { if (msg instanceof Position) { Position position = (Position) msg; + Device device = cacheManager.getObject(Device.class, position.getDeviceId()); + try { if (PositionUtil.isLatest(cacheManager, position)) { - Device device = new Device(); - device.setId(position.getDeviceId()); - device.setPositionId(position.getId()); - storage.updateObject(device, new Request( + Device updatedDevice = new Device(); + updatedDevice.setId(position.getDeviceId()); + updatedDevice.setPositionId(position.getId()); + storage.updateObject(updatedDevice, new Request( new Columns.Include("positionId"), new Condition.Equals("id", "id"))); @@ -92,11 +94,9 @@ public class MainEventHandler extends ChannelInboundHandlerAdapter { LOGGER.warn("Failed to update device", error); } - String uniqueId = Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId(); - StringBuilder builder = new StringBuilder(); builder.append("[").append(NetworkUtil.session(ctx.channel())).append("] "); - builder.append("id: ").append(uniqueId); + builder.append("id: ").append(device.getUniqueId()); for (String attribute : logAttributes) { switch (attribute) { case "time": diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java index a7e531808..d57ee5d38 100644 --- a/src/main/java/org/traccar/MainModule.java +++ b/src/main/java/org/traccar/MainModule.java @@ -31,7 +31,6 @@ import org.traccar.broadcast.BroadcastService; import org.traccar.config.Config; import org.traccar.config.Keys; import org.traccar.database.DeviceManager; -import org.traccar.database.IdentityManager; import org.traccar.database.LdapProvider; import org.traccar.database.StatisticsManager; import org.traccar.geocoder.AddressFormat; @@ -108,11 +107,6 @@ public class MainModule extends AbstractModule { return Context.getConfig(); } - @Provides - public static IdentityManager provideIdentityManager() { - return Context.getIdentityManager(); - } - @Provides public static Client provideClient() { return ClientBuilder.newClient().register( diff --git a/src/main/java/org/traccar/WebDataHandler.java b/src/main/java/org/traccar/WebDataHandler.java index db99ecaf8..192a15bcf 100644 --- a/src/main/java/org/traccar/WebDataHandler.java +++ b/src/main/java/org/traccar/WebDataHandler.java @@ -26,7 +26,6 @@ import org.slf4j.LoggerFactory; import org.traccar.config.Config; import org.traccar.config.Keys; -import org.traccar.database.IdentityManager; import org.traccar.helper.Checksum; import org.traccar.model.Device; import org.traccar.model.Position; @@ -62,7 +61,6 @@ public class WebDataHandler extends BaseDataHandler { private static final String KEY_DEVICE = "device"; private final CacheManager cacheManager; - private final IdentityManager identityManager; private final ObjectMapper objectMapper; private final Client client; @@ -80,11 +78,9 @@ public class WebDataHandler extends BaseDataHandler { @Inject public WebDataHandler( - Config config, CacheManager cacheManager, IdentityManager identityManager, - ObjectMapper objectMapper, Client client) { + Config config, CacheManager cacheManager, ObjectMapper objectMapper, Client client) { this.cacheManager = cacheManager; - this.identityManager = identityManager; this.objectMapper = objectMapper; this.client = client; this.url = config.getString(Keys.FORWARD_URL); @@ -138,7 +134,7 @@ public class WebDataHandler extends BaseDataHandler { public String formatRequest(Position position) throws UnsupportedEncodingException, JsonProcessingException { - Device device = identityManager.getById(position.getDeviceId()); + Device device = cacheManager.getObject(Device.class, position.getDeviceId()); String request = url .replace("{name}", URLEncoder.encode(device.getName(), StandardCharsets.UTF_8.name())) @@ -302,7 +298,7 @@ public class WebDataHandler extends BaseDataHandler { private Map prepareJsonPayload(Position position) { Map data = new HashMap<>(); - Device device = identityManager.getById(position.getDeviceId()); + Device device = cacheManager.getObject(Device.class, position.getDeviceId()); data.put(KEY_POSITION, position); diff --git a/src/main/java/org/traccar/api/resource/AttributeResource.java b/src/main/java/org/traccar/api/resource/AttributeResource.java index 43d8a7ccd..fb74b9bbe 100644 --- a/src/main/java/org/traccar/api/resource/AttributeResource.java +++ b/src/main/java/org/traccar/api/resource/AttributeResource.java @@ -28,7 +28,6 @@ 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.ExtendedObjectResource; import org.traccar.config.Config; import org.traccar.model.Attribute; @@ -62,8 +61,7 @@ public class AttributeResource extends ExtendedObjectResource { new Columns.All(), new Condition.LatestPositions(deviceId))); - Object result = new ComputedAttributesHandler(config, Context.getIdentityManager(), null) - .computeAttribute(entity, position); + Object result = new ComputedAttributesHandler(config, null).computeAttribute(entity, position); if (result != null) { switch (entity.getType()) { case "number": diff --git a/src/main/java/org/traccar/database/DeviceManager.java b/src/main/java/org/traccar/database/DeviceManager.java index 4516255c1..d6c442f10 100644 --- a/src/main/java/org/traccar/database/DeviceManager.java +++ b/src/main/java/org/traccar/database/DeviceManager.java @@ -27,7 +27,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; -public class DeviceManager extends BaseObjectManager implements IdentityManager { +public class DeviceManager extends BaseObjectManager { private final long dataRefreshDelay; diff --git a/src/main/java/org/traccar/database/IdentityManager.java b/src/main/java/org/traccar/database/IdentityManager.java deleted file mode 100644 index 1e0eb00c5..000000000 --- a/src/main/java/org/traccar/database/IdentityManager.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2015 - 2022 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.database; - -import org.traccar.model.Device; - -public interface IdentityManager { - - Device getById(long id); - -} diff --git a/src/main/java/org/traccar/handler/ComputedAttributesHandler.java b/src/main/java/org/traccar/handler/ComputedAttributesHandler.java index bec3d38e0..82ac4e804 100644 --- a/src/main/java/org/traccar/handler/ComputedAttributesHandler.java +++ b/src/main/java/org/traccar/handler/ComputedAttributesHandler.java @@ -34,7 +34,6 @@ import org.slf4j.LoggerFactory; import org.traccar.BaseDataHandler; import org.traccar.config.Config; import org.traccar.config.Keys; -import org.traccar.database.IdentityManager; import org.traccar.model.Attribute; import org.traccar.model.Device; import org.traccar.model.Position; @@ -47,7 +46,6 @@ public class ComputedAttributesHandler extends BaseDataHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ComputedAttributesHandler.class); - private final IdentityManager identityManager; private final CacheManager cacheManager; private final JexlEngine engine; @@ -55,9 +53,7 @@ public class ComputedAttributesHandler extends BaseDataHandler { private final boolean includeDeviceAttributes; @Inject - public ComputedAttributesHandler( - Config config, IdentityManager identityManager, CacheManager cacheManager) { - this.identityManager = identityManager; + public ComputedAttributesHandler(Config config, CacheManager cacheManager) { this.cacheManager = cacheManager; engine = new JexlEngine(); engine.setStrict(true); @@ -68,7 +64,7 @@ public class ComputedAttributesHandler extends BaseDataHandler { private MapContext prepareContext(Position position) { MapContext result = new MapContext(); if (includeDeviceAttributes) { - Device device = identityManager.getById(position.getDeviceId()); + Device device = cacheManager.getObject(Device.class, position.getDeviceId()); if (device != null) { for (Object key : device.getAttributes().keySet()) { result.set((String) key, device.getAttributes().get(key)); diff --git a/src/main/java/org/traccar/protocol/CastelProtocolEncoder.java b/src/main/java/org/traccar/protocol/CastelProtocolEncoder.java index 0fb4bf8b4..61dde3e80 100644 --- a/src/main/java/org/traccar/protocol/CastelProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/CastelProtocolEncoder.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 - 2019 Anton Tananaev (anton@traccar.org) + * Copyright 2018 - 2022 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. @@ -33,7 +33,7 @@ public class CastelProtocolEncoder extends BaseProtocolEncoder { private ByteBuf encodeContent(long deviceId, short type, ByteBuf content) { ByteBuf buf = Unpooled.buffer(0); - String uniqueId = getIdentityManager().getById(deviceId).getUniqueId(); + String uniqueId = getUniqueId(deviceId); buf.writeByte('@'); buf.writeByte('@'); diff --git a/src/main/java/org/traccar/protocol/GalileoProtocolDecoder.java b/src/main/java/org/traccar/protocol/GalileoProtocolDecoder.java index a2ba7b029..bf14d47e0 100644 --- a/src/main/java/org/traccar/protocol/GalileoProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/GalileoProtocolDecoder.java @@ -320,14 +320,13 @@ public class GalileoProtocolDecoder extends BaseProtocolDecoder { } else { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); - String uniqueId = getIdentityManager().getById(deviceSession.getDeviceId()).getUniqueId(); position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); getLastLocation(position, null); - position.set(Position.KEY_IMAGE, writeMediaFile(uniqueId, photo, "jpg")); + position.set(Position.KEY_IMAGE, writeMediaFile(deviceSession.getUniqueId(), photo, "jpg")); photo.release(); photo = null; diff --git a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java index 4b9757874..c53fbfe5a 100644 --- a/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/Gt06ProtocolDecoder.java @@ -31,7 +31,6 @@ import org.traccar.helper.Parser; import org.traccar.helper.PatternBuilder; import org.traccar.helper.UnitsConverter; import org.traccar.model.CellTower; -import org.traccar.model.Device; import org.traccar.model.Network; import org.traccar.model.Position; import org.traccar.model.WifiAccessPoint; @@ -1026,8 +1025,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { if (photo.writableBytes() > 0) { sendPhotoRequest(channel, pictureId); } else { - Device device = getIdentityManager().getById(deviceSession.getDeviceId()); - position.set(Position.KEY_IMAGE, writeMediaFile(device.getUniqueId(), photo, "jpg")); + position.set(Position.KEY_IMAGE, writeMediaFile(deviceSession.getUniqueId(), photo, "jpg")); photos.remove(pictureId).release(); } @@ -1262,8 +1260,7 @@ public class Gt06ProtocolDecoder extends BaseProtocolDecoder { position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); getLastLocation(position, new Date(timestamp)); - Device device = getIdentityManager().getById(deviceSession.getDeviceId()); - position.set(Position.KEY_IMAGE, writeMediaFile(device.getUniqueId(), photo, "jpg")); + position.set(Position.KEY_IMAGE, writeMediaFile(deviceSession.getUniqueId(), photo, "jpg")); photos.remove(mediaId).release(); } } diff --git a/src/main/java/org/traccar/protocol/MeiligaoProtocolDecoder.java b/src/main/java/org/traccar/protocol/MeiligaoProtocolDecoder.java index 0b6bf8663..f3b56973a 100644 --- a/src/main/java/org/traccar/protocol/MeiligaoProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/MeiligaoProtocolDecoder.java @@ -468,10 +468,9 @@ public class MeiligaoProtocolDecoder extends BaseProtocolDecoder { } else if (command == MSG_POSITION_IMAGE) { byte imageIndex = buf.readByte(); buf.readUnsignedByte(); // image upload type - String uniqueId = getIdentityManager().getById(deviceSession.getDeviceId()).getUniqueId(); ByteBuf photo = photos.remove(imageIndex); try { - position.set(Position.KEY_IMAGE, writeMediaFile(uniqueId, photo, "jpg")); + position.set(Position.KEY_IMAGE, writeMediaFile(deviceSession.getUniqueId(), photo, "jpg")); } finally { photo.release(); } diff --git a/src/main/java/org/traccar/protocol/MeitrackProtocolDecoder.java b/src/main/java/org/traccar/protocol/MeitrackProtocolDecoder.java index 30689436d..87459d3fc 100644 --- a/src/main/java/org/traccar/protocol/MeitrackProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/MeitrackProtocolDecoder.java @@ -19,6 +19,7 @@ import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import org.traccar.BaseProtocolDecoder; +import org.traccar.model.Device; import org.traccar.session.DeviceSession; import org.traccar.NetworkMessage; import org.traccar.Protocol; @@ -203,7 +204,7 @@ public class MeitrackProtocolDecoder extends BaseProtocolDecoder { position.set(Position.PREFIX_ADC + i, parser.nextHexInt()); } - String deviceModel = getIdentityManager().getById(deviceSession.getDeviceId()).getModel(); + String deviceModel = getCacheManager().getObject(Device.class, deviceSession.getDeviceId()).getModel(); if (deviceModel == null) { deviceModel = ""; } diff --git a/src/main/java/org/traccar/protocol/PretraceProtocolEncoder.java b/src/main/java/org/traccar/protocol/PretraceProtocolEncoder.java index 106ba9537..a109e7a07 100644 --- a/src/main/java/org/traccar/protocol/PretraceProtocolEncoder.java +++ b/src/main/java/org/traccar/protocol/PretraceProtocolEncoder.java @@ -34,7 +34,7 @@ public class PretraceProtocolEncoder extends BaseProtocolEncoder { @Override protected Object encodeCommand(Command command) { - String uniqueId = getIdentityManager().getById(command.getDeviceId()).getUniqueId(); + String uniqueId = getUniqueId(command.getDeviceId()); switch (command.getType()) { case Command.TYPE_CUSTOM: diff --git a/src/main/java/org/traccar/protocol/Pt502ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Pt502ProtocolDecoder.java index 21b91203f..2a6a81a65 100644 --- a/src/main/java/org/traccar/protocol/Pt502ProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/Pt502ProtocolDecoder.java @@ -174,14 +174,13 @@ public class Pt502ProtocolDecoder extends BaseProtocolDecoder { } else { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); - String uniqueId = getIdentityManager().getById(deviceSession.getDeviceId()).getUniqueId(); Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); getLastLocation(position, null); - position.set(Position.KEY_IMAGE, writeMediaFile(uniqueId, photo, "jpg")); + position.set(Position.KEY_IMAGE, writeMediaFile(deviceSession.getUniqueId(), photo, "jpg")); photo.release(); photo = null; diff --git a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java index f91eef837..77047fe26 100644 --- a/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/TeltonikaProtocolDecoder.java @@ -119,7 +119,8 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { return printable; } - private void decodeSerial(Channel channel, SocketAddress remoteAddress, Position position, ByteBuf buf) { + private void decodeSerial( + Channel channel, SocketAddress remoteAddress, DeviceSession deviceSession, Position position, ByteBuf buf) { getLastLocation(position, null); @@ -148,10 +149,9 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { channel, remoteAddress, photoId, photo.writerIndex(), Math.min(IMAGE_PACKET_MAX, photo.writableBytes())); } else { - String uniqueId = getIdentityManager().getById(position.getDeviceId()).getUniqueId(); photos.remove(photoId); try { - position.set(Position.KEY_IMAGE, writeMediaFile(uniqueId, photo, "jpg")); + position.set(Position.KEY_IMAGE, writeMediaFile(deviceSession.getUniqueId(), photo, "jpg")); } finally { photo.release(); } @@ -601,7 +601,7 @@ public class TeltonikaProtocolDecoder extends BaseProtocolDecoder { ByteBufUtil.hexDump(buf.readSlice(length))); } } else if (codec == CODEC_12) { - decodeSerial(channel, remoteAddress, position, buf); + decodeSerial(channel, remoteAddress, deviceSession, position, buf); } else { decodeLocation(position, buf, codec); } diff --git a/src/main/java/org/traccar/reports/EventsReportProvider.java b/src/main/java/org/traccar/reports/EventsReportProvider.java index 4db842fdb..69d95d1be 100644 --- a/src/main/java/org/traccar/reports/EventsReportProvider.java +++ b/src/main/java/org/traccar/reports/EventsReportProvider.java @@ -17,7 +17,6 @@ package org.traccar.reports; import org.apache.poi.ss.util.WorkbookUtil; -import org.traccar.Context; import org.traccar.config.Config; import org.traccar.config.Keys; import org.traccar.model.Device; @@ -133,7 +132,7 @@ public class EventsReportProvider { } } DeviceReportSection deviceEvents = new DeviceReportSection(); - Device device = Context.getIdentityManager().getById(deviceId); + Device device = reportUtils.getDevice(deviceId); deviceEvents.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceEvents.getDeviceName())); if (device.getGroupId() > 0) { diff --git a/src/main/java/org/traccar/reports/RouteReportProvider.java b/src/main/java/org/traccar/reports/RouteReportProvider.java index b4401bc87..2364cc0f3 100644 --- a/src/main/java/org/traccar/reports/RouteReportProvider.java +++ b/src/main/java/org/traccar/reports/RouteReportProvider.java @@ -17,7 +17,6 @@ package org.traccar.reports; import org.apache.poi.ss.util.WorkbookUtil; -import org.traccar.Context; import org.traccar.config.Config; import org.traccar.config.Keys; import org.traccar.helper.model.PositionUtil; @@ -79,7 +78,7 @@ public class RouteReportProvider { for (long deviceId: reportUtils.getDeviceList(deviceIds, groupIds)) { var positions = PositionUtil.getPositions(storage, deviceId, from, to); DeviceReportSection deviceRoutes = new DeviceReportSection(); - Device device = Context.getIdentityManager().getById(deviceId); + Device device = reportUtils.getDevice(deviceId); deviceRoutes.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceRoutes.getDeviceName())); if (device.getGroupId() > 0) { diff --git a/src/main/java/org/traccar/reports/StopsReportProvider.java b/src/main/java/org/traccar/reports/StopsReportProvider.java index 192d7a0f7..3b1f3c1fe 100644 --- a/src/main/java/org/traccar/reports/StopsReportProvider.java +++ b/src/main/java/org/traccar/reports/StopsReportProvider.java @@ -17,7 +17,6 @@ package org.traccar.reports; import org.apache.poi.ss.util.WorkbookUtil; -import org.traccar.Context; import org.traccar.config.Config; import org.traccar.config.Keys; import org.traccar.helper.model.PositionUtil; @@ -86,7 +85,7 @@ public class StopsReportProvider { for (long deviceId: reportUtils.getDeviceList(deviceIds, groupIds)) { Collection stops = detectStops(deviceId, from, to); DeviceReportSection deviceStops = new DeviceReportSection(); - Device device = Context.getIdentityManager().getById(deviceId); + Device device = reportUtils.getDevice(deviceId); deviceStops.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceStops.getDeviceName())); if (device.getGroupId() > 0) { diff --git a/src/main/java/org/traccar/reports/SummaryReportProvider.java b/src/main/java/org/traccar/reports/SummaryReportProvider.java index f3a9786b9..1f136adeb 100644 --- a/src/main/java/org/traccar/reports/SummaryReportProvider.java +++ b/src/main/java/org/traccar/reports/SummaryReportProvider.java @@ -17,7 +17,6 @@ package org.traccar.reports; import org.jxls.util.JxlsHelper; -import org.traccar.Context; import org.traccar.api.security.PermissionsService; import org.traccar.config.Config; import org.traccar.config.Keys; @@ -58,10 +57,11 @@ public class SummaryReportProvider { this.storage = storage; } - private SummaryReportItem calculateSummaryResult(long deviceId, Collection positions) { + private SummaryReportItem calculateSummaryResult( + long deviceId, Collection positions) throws StorageException { SummaryReportItem result = new SummaryReportItem(); result.setDeviceId(deviceId); - result.setDeviceName(Context.getIdentityManager().getById(deviceId).getName()); + result.setDeviceName(reportUtils.getDevice(deviceId).getName()); if (positions != null && !positions.isEmpty()) { Position firstPosition = null; Position previousPosition = null; diff --git a/src/main/java/org/traccar/reports/TripsReportProvider.java b/src/main/java/org/traccar/reports/TripsReportProvider.java index 928609b9e..95612ab30 100644 --- a/src/main/java/org/traccar/reports/TripsReportProvider.java +++ b/src/main/java/org/traccar/reports/TripsReportProvider.java @@ -17,7 +17,6 @@ package org.traccar.reports; import org.apache.poi.ss.util.WorkbookUtil; -import org.traccar.Context; import org.traccar.config.Config; import org.traccar.config.Keys; import org.traccar.helper.model.PositionUtil; @@ -85,7 +84,7 @@ public class TripsReportProvider { for (long deviceId: reportUtils.getDeviceList(deviceIds, groupIds)) { Collection trips = detectTrips(deviceId, from, to); DeviceReportSection deviceTrips = new DeviceReportSection(); - Device device = Context.getIdentityManager().getById(deviceId); + Device device = reportUtils.getDevice(deviceId); deviceTrips.setDeviceName(device.getName()); sheetNames.add(WorkbookUtil.createSafeSheetName(deviceTrips.getDeviceName())); if (device.getGroupId() > 0) { diff --git a/src/main/java/org/traccar/reports/common/ReportUtils.java b/src/main/java/org/traccar/reports/common/ReportUtils.java index bb37bfa9c..ab009161f 100644 --- a/src/main/java/org/traccar/reports/common/ReportUtils.java +++ b/src/main/java/org/traccar/reports/common/ReportUtils.java @@ -31,7 +31,6 @@ import org.traccar.api.security.PermissionsService; import org.traccar.config.Config; import org.traccar.config.Keys; import org.traccar.database.DeviceManager; -import org.traccar.database.IdentityManager; import org.traccar.geocoder.Geocoder; import org.traccar.handler.events.MotionEventHandler; import org.traccar.helper.UnitsConverter; @@ -74,7 +73,6 @@ public class ReportUtils { private final Config config; private final Storage storage; private final PermissionsService permissionsService; - private final IdentityManager identityManager; private final DeviceManager deviceManager; private final TripsConfig tripsConfig; private final VelocityEngine velocityEngine; @@ -82,13 +80,12 @@ public class ReportUtils { @Inject public ReportUtils( - Config config, Storage storage, PermissionsService permissionsService, IdentityManager identityManager, + Config config, Storage storage, PermissionsService permissionsService, DeviceManager deviceManager, TripsConfig tripsConfig, VelocityEngine velocityEngine, @Nullable Geocoder geocoder) { this.config = config; this.storage = storage; this.permissionsService = permissionsService; - this.identityManager = identityManager; this.deviceManager = deviceManager; this.tripsConfig = tripsConfig; this.velocityEngine = velocityEngine; @@ -104,6 +101,12 @@ public class ReportUtils { new Condition.Permission(User.class, userId, clazz)))); } + public Device getDevice(long deviceId) throws StorageException { + return storage.getObject(Device.class, new Request( + new Columns.Include("id"), + new Condition.Equals("id", "id", deviceId))); + } + public void checkPeriodLimit(Date from, Date to) { long limit = config.getLong(Keys.REPORT_PERIOD_LIMIT) * 1000; if (limit > 0 && to.getTime() - from.getTime() > limit) { @@ -212,7 +215,7 @@ public class ReportUtils { long tripDuration = endTrip.getFixTime().getTime() - startTrip.getFixTime().getTime(); long deviceId = startTrip.getDeviceId(); trip.setDeviceId(deviceId); - trip.setDeviceName(identityManager.getById(deviceId).getName()); + trip.setDeviceName(getDevice(deviceId).getName()); trip.setStartPositionId(startTrip.getId()); trip.setStartLat(startTrip.getLatitude()); @@ -259,7 +262,8 @@ public class ReportUtils { } private StopReportItem calculateStop( - ArrayList positions, int startIndex, int endIndex, boolean ignoreOdometer) { + ArrayList positions, int startIndex, int endIndex, + boolean ignoreOdometer) throws StorageException { Position startStop = positions.get(startIndex); Position endStop = positions.get(endIndex); @@ -268,7 +272,7 @@ public class ReportUtils { long deviceId = startStop.getDeviceId(); stop.setDeviceId(deviceId); - stop.setDeviceName(identityManager.getById(deviceId).getName()); + stop.setDeviceName(getDevice(deviceId).getName()); stop.setPositionId(startStop.getId()); stop.setLatitude(startStop.getLatitude()); diff --git a/src/test/java/org/traccar/BaseTest.java b/src/test/java/org/traccar/BaseTest.java index 6db568300..c784150dd 100644 --- a/src/test/java/org/traccar/BaseTest.java +++ b/src/test/java/org/traccar/BaseTest.java @@ -3,7 +3,6 @@ package org.traccar; import io.netty.channel.Channel; import org.traccar.config.Config; import org.traccar.database.CommandsManager; -import org.traccar.database.IdentityManager; import org.traccar.database.MediaManager; import org.traccar.database.StatisticsManager; import org.traccar.model.Device; @@ -14,8 +13,6 @@ import org.traccar.session.cache.CacheManager; import java.net.SocketAddress; import java.util.HashSet; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.any; @@ -29,9 +26,6 @@ public class BaseTest { decoder.setConfig(config); var device = mock(Device.class); when(device.getId()).thenReturn(1L); - var identityManager = mock(IdentityManager.class); - when(identityManager.getById(anyLong())).thenReturn(device); - decoder.setIdentityManager(identityManager); var cacheManager = mock(CacheManager.class); when(cacheManager.getConfig()).thenReturn(config); when(cacheManager.getObject(eq(Device.class), anyLong())).thenReturn(device); @@ -69,9 +63,6 @@ public class BaseTest { when(cacheManager.getConfig()).thenReturn(mock(Config.class)); when(cacheManager.getObject(eq(Device.class), anyLong())).thenReturn(device); encoder.setCacheManager(cacheManager); - var identityManager = mock(IdentityManager.class); - when(identityManager.getById(anyLong())).thenReturn(device); - encoder.setIdentityManager(identityManager); return encoder; } diff --git a/src/test/java/org/traccar/WebDataHandlerTest.java b/src/test/java/org/traccar/WebDataHandlerTest.java index ff9c80ce6..1e6e1214f 100644 --- a/src/test/java/org/traccar/WebDataHandlerTest.java +++ b/src/test/java/org/traccar/WebDataHandlerTest.java @@ -3,13 +3,13 @@ package org.traccar; import org.junit.Test; import org.traccar.config.Config; import org.traccar.config.Keys; -import org.traccar.database.IdentityManager; import org.traccar.model.Device; import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -28,10 +28,10 @@ public class WebDataHandlerTest extends ProtocolTest { when(device.getName()).thenReturn("test"); when(device.getUniqueId()).thenReturn("123456789012345"); when(device.getStatus()).thenReturn(Device.STATUS_ONLINE); - var identityManager = mock(IdentityManager.class); - when(identityManager.getById(anyLong())).thenReturn(device); + var cacheManager = mock(CacheManager.class); + when(cacheManager.getObject(eq(Device.class), anyLong())).thenReturn(device); - WebDataHandler handler = new WebDataHandler(config, mock(CacheManager.class), identityManager, null, null); + WebDataHandler handler = new WebDataHandler(config, cacheManager, null, null); assertEquals( "http://localhost/?fixTime=1451610123000&gprmc=$GPRMC,010203.000,A,2000.0000,N,03000.0000,E,0.00,0.00,010116,,*05&name=test", diff --git a/src/test/java/org/traccar/handler/ComputedAttributesTest.java b/src/test/java/org/traccar/handler/ComputedAttributesTest.java index e3886317c..2668c4f14 100644 --- a/src/test/java/org/traccar/handler/ComputedAttributesTest.java +++ b/src/test/java/org/traccar/handler/ComputedAttributesTest.java @@ -14,7 +14,7 @@ public class ComputedAttributesTest { @Test public void testComputedAttributes() { - ComputedAttributesHandler handler = new ComputedAttributesHandler(new Config(), null, null); + ComputedAttributesHandler handler = new ComputedAttributesHandler(new Config(), null); Date date = new Date(); Position position = new Position(); diff --git a/src/test/java/org/traccar/reports/ReportUtilsTest.java b/src/test/java/org/traccar/reports/ReportUtilsTest.java index 1440c4c30..c7f2a2cc6 100644 --- a/src/test/java/org/traccar/reports/ReportUtilsTest.java +++ b/src/test/java/org/traccar/reports/ReportUtilsTest.java @@ -1,20 +1,21 @@ package org.traccar.reports; import org.apache.velocity.app.VelocityEngine; +import org.junit.Before; import org.junit.Test; import org.traccar.BaseTest; import org.traccar.api.security.PermissionsService; import org.traccar.config.Config; import org.traccar.database.DeviceManager; -import org.traccar.database.IdentityManager; import org.traccar.helper.model.PositionUtil; import org.traccar.model.Device; import org.traccar.model.Position; import org.traccar.reports.common.ReportUtils; +import org.traccar.reports.common.TripsConfig; import org.traccar.reports.model.StopReportItem; import org.traccar.reports.model.TripReportItem; -import org.traccar.reports.common.TripsConfig; import org.traccar.storage.Storage; +import org.traccar.storage.StorageException; import java.text.DateFormat; import java.text.ParseException; @@ -30,11 +31,19 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ReportUtilsTest extends BaseTest { + + private Storage storage; + + @Before + public void init() throws StorageException { + storage = mock(Storage.class); + when(storage.getObject(any(), any())).thenReturn(mock(Device.class)); + } private Date date(String time) throws ParseException { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); @@ -53,15 +62,7 @@ public class ReportUtilsTest extends BaseTest { return position; } - - private IdentityManager mockIdentityManager() { - var device = mock(Device.class); - when(device.getName()).thenReturn("test"); - var identityManager = mock(IdentityManager.class); - when(identityManager.getById(anyLong())).thenReturn(device); - return identityManager; - } - + @Test public void testCalculateDistance() { Position startPosition = new Position(); @@ -77,7 +78,7 @@ public class ReportUtilsTest extends BaseTest { @Test public void testCalculateSpentFuel() { ReportUtils reportUtils = new ReportUtils( - mock(Config.class), mock(Storage.class), mock(PermissionsService.class), mockIdentityManager(), + mock(Config.class), storage, mock(PermissionsService.class), mock(DeviceManager.class), mock(TripsConfig.class), mock(VelocityEngine.class), null); Position startPosition = new Position(); Position endPosition = new Position(); @@ -102,7 +103,7 @@ public class ReportUtilsTest extends BaseTest { TripsConfig tripsConfig = new TripsConfig(500, 300000, 180000, 900000, false, false, 0.01); ReportUtils reportUtils = new ReportUtils( - mock(Config.class), mock(Storage.class), mock(PermissionsService.class), mockIdentityManager(), + mock(Config.class), storage, mock(PermissionsService.class), mock(DeviceManager.class), tripsConfig, mock(VelocityEngine.class), null); Collection trips = reportUtils.detectTripsAndStops(data, false, TripReportItem.class); @@ -157,7 +158,7 @@ public class ReportUtilsTest extends BaseTest { TripsConfig tripsConfig = new TripsConfig(500, 300000, 180000, 900000, true, false, 0.01); ReportUtils reportUtils = new ReportUtils( - mock(Config.class), mock(Storage.class), mock(PermissionsService.class), mockIdentityManager(), + mock(Config.class), storage, mock(PermissionsService.class), mock(DeviceManager.class), tripsConfig, mock(VelocityEngine.class), null); Collection trips = reportUtils.detectTripsAndStops(data, false, TripReportItem.class); @@ -228,7 +229,7 @@ public class ReportUtilsTest extends BaseTest { TripsConfig tripsConfig = new TripsConfig(500, 300000, 180000, 900000, false, false, 0.01); ReportUtils reportUtils = new ReportUtils( - mock(Config.class), mock(Storage.class), mock(PermissionsService.class), mockIdentityManager(), + mock(Config.class), storage, mock(PermissionsService.class), mock(DeviceManager.class), tripsConfig, mock(VelocityEngine.class), null); Collection trips = reportUtils.detectTripsAndStops(data, false, TripReportItem.class); @@ -279,7 +280,7 @@ public class ReportUtilsTest extends BaseTest { TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000, false, false, 0.01); ReportUtils reportUtils = new ReportUtils( - mock(Config.class), mock(Storage.class), mock(PermissionsService.class), mockIdentityManager(), + mock(Config.class), storage, mock(PermissionsService.class), mock(DeviceManager.class), tripsConfig, mock(VelocityEngine.class), null); Collection result = reportUtils.detectTripsAndStops(data, false, StopReportItem.class); @@ -308,7 +309,7 @@ public class ReportUtilsTest extends BaseTest { TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000, false, false, 0.01); ReportUtils reportUtils = new ReportUtils( - mock(Config.class), mock(Storage.class), mock(PermissionsService.class), mockIdentityManager(), + mock(Config.class), storage, mock(PermissionsService.class), mock(DeviceManager.class), tripsConfig, mock(VelocityEngine.class), null); Collection result = reportUtils.detectTripsAndStops(data, false, StopReportItem.class); @@ -337,7 +338,7 @@ public class ReportUtilsTest extends BaseTest { TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000, false, false, 0.01); ReportUtils reportUtils = new ReportUtils( - mock(Config.class), mock(Storage.class), mock(PermissionsService.class), mockIdentityManager(), + mock(Config.class), storage, mock(PermissionsService.class), mock(DeviceManager.class), tripsConfig, mock(VelocityEngine.class), null); Collection result = reportUtils.detectTripsAndStops(data, false, StopReportItem.class); @@ -366,7 +367,7 @@ public class ReportUtilsTest extends BaseTest { TripsConfig tripsConfig = new TripsConfig(500, 300000, 200000, 900000, false, false, 0.01); ReportUtils reportUtils = new ReportUtils( - mock(Config.class), mock(Storage.class), mock(PermissionsService.class), mockIdentityManager(), + mock(Config.class), storage, mock(PermissionsService.class), mock(DeviceManager.class), tripsConfig, mock(VelocityEngine.class), null); Collection result = reportUtils.detectTripsAndStops(data, false, StopReportItem.class); @@ -391,7 +392,7 @@ public class ReportUtilsTest extends BaseTest { TripsConfig tripsConfig = new TripsConfig(500, 200000, 200000, 900000, false, false, 0.01); ReportUtils reportUtils = new ReportUtils( - mock(Config.class), mock(Storage.class), mock(PermissionsService.class), mockIdentityManager(), + mock(Config.class), storage, mock(PermissionsService.class), mock(DeviceManager.class), tripsConfig, mock(VelocityEngine.class), null); Collection trips = reportUtils.detectTripsAndStops(data, false, TripReportItem.class); -- cgit v1.2.3 From e665a2c7f4dd925bed116961da48bb018d6f57f7 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Sat, 18 Jun 2022 14:36:31 -0700 Subject: Remove static injector usages --- src/main/java/org/traccar/BasePipelineFactory.java | 7 +++++-- src/main/java/org/traccar/MainEventHandler.java | 8 +++++--- src/main/java/org/traccar/MainModule.java | 5 ++--- src/main/java/org/traccar/WebDataHandler.java | 9 +++++---- src/main/java/org/traccar/api/resource/DeviceResource.java | 6 +++++- src/main/java/org/traccar/database/MailManager.java | 7 ++++--- src/main/java/org/traccar/session/ConnectionManager.java | 12 ++++++------ 7 files changed, 32 insertions(+), 22 deletions(-) (limited to 'src/main/java/org/traccar/WebDataHandler.java') diff --git a/src/main/java/org/traccar/BasePipelineFactory.java b/src/main/java/org/traccar/BasePipelineFactory.java index 3eb7011a1..915c3f7ea 100644 --- a/src/main/java/org/traccar/BasePipelineFactory.java +++ b/src/main/java/org/traccar/BasePipelineFactory.java @@ -15,6 +15,7 @@ */ package org.traccar; +import com.google.inject.Injector; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelInboundHandler; @@ -55,11 +56,13 @@ import java.util.Map; public abstract class BasePipelineFactory extends ChannelInitializer { + private final Injector injector; private final TrackerConnector connector; private final String protocol; private int timeout; public BasePipelineFactory(TrackerConnector connector, Config config, String protocol) { + this.injector = Main.getInjector(); this.connector = connector; this.protocol = protocol; timeout = config.getInteger(Keys.PROTOCOL_TIMEOUT.withPrefix(protocol)); @@ -76,7 +79,7 @@ public abstract class BasePipelineFactory extends ChannelInitializer { private void addHandlers(ChannelPipeline pipeline, Class... handlerClasses) { for (Class handlerClass : handlerClasses) { if (handlerClass != null) { - pipeline.addLast(Main.getInjector().getInstance(handlerClass)); + pipeline.addLast(injector.getInstance(handlerClass)); } } } @@ -111,7 +114,7 @@ public abstract class BasePipelineFactory extends ChannelInitializer { addProtocolHandlers(handler -> { if (handler instanceof BaseProtocolDecoder || handler instanceof BaseProtocolEncoder) { - Main.getInjector().injectMembers(handler); + injector.injectMembers(handler); } else { if (handler instanceof ChannelInboundHandler) { handler = new WrapperInboundHandler((ChannelInboundHandler) handler); diff --git a/src/main/java/org/traccar/MainEventHandler.java b/src/main/java/org/traccar/MainEventHandler.java index d2665cbcc..965421d2f 100644 --- a/src/main/java/org/traccar/MainEventHandler.java +++ b/src/main/java/org/traccar/MainEventHandler.java @@ -55,13 +55,16 @@ public class MainEventHandler extends ChannelInboundHandlerAdapter { private final CacheManager cacheManager; private final Storage storage; private final ConnectionManager connectionManager; + private final StatisticsManager statisticsManager; @Inject public MainEventHandler( - Config config, CacheManager cacheManager, Storage storage, ConnectionManager connectionManager) { + Config config, CacheManager cacheManager, Storage storage, + ConnectionManager connectionManager, StatisticsManager statisticsManager) { this.cacheManager = cacheManager; this.storage = storage; this.connectionManager = connectionManager; + this.statisticsManager = statisticsManager; String connectionlessProtocolList = config.getString(Keys.STATUS_IGNORE_OFFLINE); if (connectionlessProtocolList != null) { connectionlessProtocols.addAll(Arrays.asList(connectionlessProtocolList.split("[, ]"))); @@ -139,8 +142,7 @@ public class MainEventHandler extends ChannelInboundHandlerAdapter { } LOGGER.info(builder.toString()); - Main.getInjector().getInstance(StatisticsManager.class) - .registerMessageStored(position.getDeviceId(), position.getProtocol()); + statisticsManager.registerMessageStored(position.getDeviceId(), position.getProtocol()); } } diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java index 3120118fc..5a5675859 100644 --- a/src/main/java/org/traccar/MainModule.java +++ b/src/main/java/org/traccar/MainModule.java @@ -111,9 +111,8 @@ public class MainModule extends AbstractModule { } @Provides - public static Client provideClient() { - return ClientBuilder.newClient().register( - (ContextResolver) clazz -> Main.getInjector().getInstance(ObjectMapper.class)); + public static Client provideClient(ObjectMapper objectMapper) { + return ClientBuilder.newClient().register((ContextResolver) clazz -> objectMapper); } @Singleton diff --git a/src/main/java/org/traccar/WebDataHandler.java b/src/main/java/org/traccar/WebDataHandler.java index 192a15bcf..d25c4fd3c 100644 --- a/src/main/java/org/traccar/WebDataHandler.java +++ b/src/main/java/org/traccar/WebDataHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 - 2020 Anton Tananaev (anton@traccar.org) + * Copyright 2015 - 2022 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. @@ -63,6 +63,7 @@ public class WebDataHandler extends BaseDataHandler { private final CacheManager cacheManager; private final ObjectMapper objectMapper; private final Client client; + private final Timer timer; private final String url; private final String header; @@ -78,11 +79,12 @@ public class WebDataHandler extends BaseDataHandler { @Inject public WebDataHandler( - Config config, CacheManager cacheManager, ObjectMapper objectMapper, Client client) { + Config config, CacheManager cacheManager, ObjectMapper objectMapper, Client client, Timer timer) { this.cacheManager = cacheManager; this.objectMapper = objectMapper; this.client = client; + this.timer = timer; this.url = config.getString(Keys.FORWARD_URL); this.header = config.getString(Keys.FORWARD_HEADER); this.json = config.getBoolean(Keys.FORWARD_JSON); @@ -248,8 +250,7 @@ public class WebDataHandler extends BaseDataHandler { } private void schedule() { - Main.getInjector().getInstance(Timer.class).newTimeout( - this, retryDelay * (long) Math.pow(2, retries++), TimeUnit.MILLISECONDS); + timer.newTimeout(this, retryDelay * (long) Math.pow(2, retries++), TimeUnit.MILLISECONDS); } @Override diff --git a/src/main/java/org/traccar/api/resource/DeviceResource.java b/src/main/java/org/traccar/api/resource/DeviceResource.java index 2509c9003..6660752d3 100644 --- a/src/main/java/org/traccar/api/resource/DeviceResource.java +++ b/src/main/java/org/traccar/api/resource/DeviceResource.java @@ -28,6 +28,7 @@ import org.traccar.storage.query.Columns; import org.traccar.storage.query.Condition; import org.traccar.storage.query.Request; +import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; @@ -45,6 +46,9 @@ import java.util.List; @Consumes(MediaType.APPLICATION_JSON) public class DeviceResource extends BaseObjectResource { + @Inject + private CacheManager cacheManager; + public DeviceResource() { super(Device.class); } @@ -122,7 +126,7 @@ public class DeviceResource extends BaseObjectResource { new Columns.Include("positionId"), new Condition.Equals("id", "id"))); - Main.getInjector().getInstance(CacheManager.class).updatePosition(position); + cacheManager.updatePosition(position); } else { throw new IllegalArgumentException(); } diff --git a/src/main/java/org/traccar/database/MailManager.java b/src/main/java/org/traccar/database/MailManager.java index 54f617d5f..ac0db2d97 100644 --- a/src/main/java/org/traccar/database/MailManager.java +++ b/src/main/java/org/traccar/database/MailManager.java @@ -18,7 +18,6 @@ package org.traccar.database; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.traccar.Main; import org.traccar.config.Config; import org.traccar.model.User; import org.traccar.notification.PropertiesProvider; @@ -42,10 +41,12 @@ public final class MailManager { private static final Logger LOGGER = LoggerFactory.getLogger(MailManager.class); private final Config config; + private final StatisticsManager statisticsManager; @Inject - public MailManager(Config config) { + public MailManager(Config config, StatisticsManager statisticsManager) { this.config = config; + this.statisticsManager = statisticsManager; } private static Properties getProperties(PropertiesProvider provider) { @@ -145,7 +146,7 @@ public final class MailManager { } try (Transport transport = session.getTransport()) { - Main.getInjector().getInstance(StatisticsManager.class).registerMail(); + statisticsManager.registerMail(); transport.connect( properties.getProperty("mail.smtp.host"), properties.getProperty("mail.smtp.username"), diff --git a/src/main/java/org/traccar/session/ConnectionManager.java b/src/main/java/org/traccar/session/ConnectionManager.java index cead771c9..05c4893fd 100644 --- a/src/main/java/org/traccar/session/ConnectionManager.java +++ b/src/main/java/org/traccar/session/ConnectionManager.java @@ -15,12 +15,12 @@ */ package org.traccar.session; +import com.google.inject.Injector; import io.netty.channel.Channel; import io.netty.util.Timeout; import io.netty.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.traccar.Main; import org.traccar.Protocol; import org.traccar.config.Config; import org.traccar.config.Keys; @@ -64,6 +64,7 @@ public class ConnectionManager { private final Map deviceStates = new ConcurrentHashMap<>(); + private final Injector injector; private final Config config; private final CacheManager cacheManager; private final Storage storage; @@ -75,8 +76,9 @@ public class ConnectionManager { @Inject public ConnectionManager( - Config config, CacheManager cacheManager, Storage storage, + Injector injector, Config config, CacheManager cacheManager, Storage storage, NotificationManager notificationManager, Timer timer) { + this.injector = injector; this.config = config; this.cacheManager = cacheManager; this.storage = storage; @@ -279,15 +281,13 @@ public class ConnectionManager { DeviceState deviceState = getDeviceState(deviceId); Map result = new HashMap<>(); - Map event = Main.getInjector() - .getInstance(MotionEventHandler.class).updateMotionState(deviceState); + Map event = injector.getInstance(MotionEventHandler.class).updateMotionState(deviceState); if (event != null) { result.putAll(event); } double speedLimit = AttributeUtil.lookup(cacheManager, Keys.EVENT_OVERSPEED_LIMIT, deviceId); - event = Main.getInjector().getInstance(OverspeedEventHandler.class) - .updateOverspeedState(deviceState, speedLimit); + event = injector.getInstance(OverspeedEventHandler.class).updateOverspeedState(deviceState, speedLimit); if (event != null) { result.putAll(event); } -- cgit v1.2.3 From 33733f835e88a62c4a5259ab330723b88037adf1 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Wed, 13 Jul 2022 09:39:22 -0700 Subject: Simplify attribute check --- src/main/java/org/traccar/BaseProtocolEncoder.java | 2 +- src/main/java/org/traccar/WebDataHandler.java | 2 +- src/main/java/org/traccar/handler/CopyAttributesHandler.java | 3 +-- src/main/java/org/traccar/handler/DistanceHandler.java | 4 ++-- src/main/java/org/traccar/handler/EngineHoursHandler.java | 2 +- src/main/java/org/traccar/handler/FilterHandler.java | 4 ++-- src/main/java/org/traccar/handler/MotionHandler.java | 2 +- src/main/java/org/traccar/handler/events/FuelDropEventHandler.java | 4 ++-- src/main/java/org/traccar/handler/events/IgnitionEventHandler.java | 4 ++-- src/main/java/org/traccar/handler/events/MotionEventHandler.java | 2 +- src/main/java/org/traccar/model/ExtendedModel.java | 4 ++++ src/main/java/org/traccar/notificators/NotificatorFirebase.java | 2 +- src/main/java/org/traccar/notificators/NotificatorPushover.java | 2 +- src/main/java/org/traccar/protocol/GalileoProtocolDecoder.java | 2 +- src/main/java/org/traccar/protocol/Gps103ProtocolDecoder.java | 2 +- src/main/java/org/traccar/protocol/S168ProtocolDecoder.java | 2 +- src/main/java/org/traccar/reports/SummaryReportProvider.java | 3 +-- src/main/java/org/traccar/reports/common/ReportUtils.java | 7 +++---- 18 files changed, 27 insertions(+), 26 deletions(-) (limited to 'src/main/java/org/traccar/WebDataHandler.java') diff --git a/src/main/java/org/traccar/BaseProtocolEncoder.java b/src/main/java/org/traccar/BaseProtocolEncoder.java index bc1180a08..9c3934184 100644 --- a/src/main/java/org/traccar/BaseProtocolEncoder.java +++ b/src/main/java/org/traccar/BaseProtocolEncoder.java @@ -61,7 +61,7 @@ public abstract class BaseProtocolEncoder extends ChannelOutboundHandlerAdapter } protected void initDevicePassword(Command command, String defaultPassword) { - if (!command.getAttributes().containsKey(Command.KEY_DEVICE_PASSWORD)) { + if (!command.hasAttribute(Command.KEY_DEVICE_PASSWORD)) { String password = AttributeUtil.getDevicePassword( cacheManager, command.getDeviceId(), getProtocolName(), defaultPassword); command.set(Command.KEY_DEVICE_PASSWORD, password); diff --git a/src/main/java/org/traccar/WebDataHandler.java b/src/main/java/org/traccar/WebDataHandler.java index d25c4fd3c..d0aa32e53 100644 --- a/src/main/java/org/traccar/WebDataHandler.java +++ b/src/main/java/org/traccar/WebDataHandler.java @@ -125,7 +125,7 @@ public class WebDataHandler extends BaseDataHandler { } private String calculateStatus(Position position) { - if (position.getAttributes().containsKey(Position.KEY_ALARM)) { + if (position.hasAttribute(Position.KEY_ALARM)) { return "0xF841"; // STATUS_PANIC_ON } else if (position.getSpeed() < 1.0) { return "0xF020"; // STATUS_LOCATION diff --git a/src/main/java/org/traccar/handler/CopyAttributesHandler.java b/src/main/java/org/traccar/handler/CopyAttributesHandler.java index 50d36471a..1fa47cfaa 100644 --- a/src/main/java/org/traccar/handler/CopyAttributesHandler.java +++ b/src/main/java/org/traccar/handler/CopyAttributesHandler.java @@ -46,8 +46,7 @@ public class CopyAttributesHandler extends BaseDataHandler { Position last = cacheManager.getPosition(position.getDeviceId()); if (last != null && attributesString != null) { for (String attribute : attributesString.split("[ ,]")) { - if (last.getAttributes().containsKey(attribute) - && !position.getAttributes().containsKey(attribute)) { + if (last.hasAttribute(attribute) && !position.hasAttribute(attribute)) { position.getAttributes().put(attribute, last.getAttributes().get(attribute)); } } diff --git a/src/main/java/org/traccar/handler/DistanceHandler.java b/src/main/java/org/traccar/handler/DistanceHandler.java index fb82b5d8e..87c4a81c9 100644 --- a/src/main/java/org/traccar/handler/DistanceHandler.java +++ b/src/main/java/org/traccar/handler/DistanceHandler.java @@ -49,7 +49,7 @@ public class DistanceHandler extends BaseDataHandler { protected Position handlePosition(Position position) { double distance = 0.0; - if (position.getAttributes().containsKey(Position.KEY_DISTANCE)) { + if (position.hasAttribute(Position.KEY_DISTANCE)) { distance = position.getDouble(Position.KEY_DISTANCE); } double totalDistance = 0.0; @@ -57,7 +57,7 @@ public class DistanceHandler extends BaseDataHandler { Position last = cacheManager.getPosition(position.getDeviceId()); if (last != null) { totalDistance = last.getDouble(Position.KEY_TOTAL_DISTANCE); - if (!position.getAttributes().containsKey(Position.KEY_DISTANCE)) { + if (!position.hasAttribute(Position.KEY_DISTANCE)) { distance = DistanceCalculator.distance( position.getLatitude(), position.getLongitude(), last.getLatitude(), last.getLongitude()); diff --git a/src/main/java/org/traccar/handler/EngineHoursHandler.java b/src/main/java/org/traccar/handler/EngineHoursHandler.java index bfffdcb0c..54a1a0c25 100644 --- a/src/main/java/org/traccar/handler/EngineHoursHandler.java +++ b/src/main/java/org/traccar/handler/EngineHoursHandler.java @@ -35,7 +35,7 @@ public class EngineHoursHandler extends BaseDataHandler { @Override protected Position handlePosition(Position position) { - if (!position.getAttributes().containsKey(Position.KEY_HOURS)) { + if (!position.hasAttribute(Position.KEY_HOURS)) { Position last = cacheManager.getPosition(position.getDeviceId()); if (last != null) { long hours = last.getLong(Position.KEY_HOURS); diff --git a/src/main/java/org/traccar/handler/FilterHandler.java b/src/main/java/org/traccar/handler/FilterHandler.java index 00cbf92a0..0bd57319a 100644 --- a/src/main/java/org/traccar/handler/FilterHandler.java +++ b/src/main/java/org/traccar/handler/FilterHandler.java @@ -103,7 +103,7 @@ public class FilterHandler extends BaseDataHandler { private boolean filterDuplicate(Position position, Position last) { if (filterDuplicate && last != null && position.getFixTime().equals(last.getFixTime())) { for (String key : position.getAttributes().keySet()) { - if (!last.getAttributes().containsKey(key)) { + if (!last.hasAttribute(key)) { return false; } } @@ -163,7 +163,7 @@ public class FilterHandler extends BaseDataHandler { if (skipAttributes) { String string = AttributeUtil.lookup(cacheManager, Keys.FILTER_SKIP_ATTRIBUTES, position.getDeviceId()); for (String attribute : string.split("[ ,]")) { - if (position.getAttributes().containsKey(attribute)) { + if (position.hasAttribute(attribute)) { return true; } } diff --git a/src/main/java/org/traccar/handler/MotionHandler.java b/src/main/java/org/traccar/handler/MotionHandler.java index 7b2c04ecf..25ee615c5 100644 --- a/src/main/java/org/traccar/handler/MotionHandler.java +++ b/src/main/java/org/traccar/handler/MotionHandler.java @@ -35,7 +35,7 @@ public class MotionHandler extends BaseDataHandler { @Override protected Position handlePosition(Position position) { - if (!position.getAttributes().containsKey(Position.KEY_MOTION)) { + if (!position.hasAttribute(Position.KEY_MOTION)) { position.set(Position.KEY_MOTION, position.getSpeed() > speedThreshold); } return position; diff --git a/src/main/java/org/traccar/handler/events/FuelDropEventHandler.java b/src/main/java/org/traccar/handler/events/FuelDropEventHandler.java index 2d105af3e..25ae1fadb 100644 --- a/src/main/java/org/traccar/handler/events/FuelDropEventHandler.java +++ b/src/main/java/org/traccar/handler/events/FuelDropEventHandler.java @@ -53,8 +53,8 @@ public class FuelDropEventHandler extends BaseEventHandler { cacheManager, Keys.EVENT_FUEL_DROP_THRESHOLD, position.getDeviceId()); if (fuelDropThreshold > 0) { Position lastPosition = cacheManager.getPosition(position.getDeviceId()); - if (position.getAttributes().containsKey(Position.KEY_FUEL_LEVEL) - && lastPosition != null && lastPosition.getAttributes().containsKey(Position.KEY_FUEL_LEVEL)) { + if (position.hasAttribute(Position.KEY_FUEL_LEVEL) + && lastPosition != null && lastPosition.hasAttribute(Position.KEY_FUEL_LEVEL)) { double drop = lastPosition.getDouble(Position.KEY_FUEL_LEVEL) - position.getDouble(Position.KEY_FUEL_LEVEL); diff --git a/src/main/java/org/traccar/handler/events/IgnitionEventHandler.java b/src/main/java/org/traccar/handler/events/IgnitionEventHandler.java index 6e411539c..3c5ac3545 100644 --- a/src/main/java/org/traccar/handler/events/IgnitionEventHandler.java +++ b/src/main/java/org/traccar/handler/events/IgnitionEventHandler.java @@ -47,11 +47,11 @@ public class IgnitionEventHandler extends BaseEventHandler { Map result = null; - if (position.getAttributes().containsKey(Position.KEY_IGNITION)) { + if (position.hasAttribute(Position.KEY_IGNITION)) { boolean ignition = position.getBoolean(Position.KEY_IGNITION); Position lastPosition = cacheManager.getPosition(position.getDeviceId()); - if (lastPosition != null && lastPosition.getAttributes().containsKey(Position.KEY_IGNITION)) { + if (lastPosition != null && lastPosition.hasAttribute(Position.KEY_IGNITION)) { boolean oldIgnition = lastPosition.getBoolean(Position.KEY_IGNITION); if (ignition && !oldIgnition) { diff --git a/src/main/java/org/traccar/handler/events/MotionEventHandler.java b/src/main/java/org/traccar/handler/events/MotionEventHandler.java index bc9d5f722..1be1896ef 100644 --- a/src/main/java/org/traccar/handler/events/MotionEventHandler.java +++ b/src/main/java/org/traccar/handler/events/MotionEventHandler.java @@ -92,7 +92,7 @@ public class MotionEventHandler extends BaseEventHandler { double distance = PositionUtil.calculateDistance(motionPosition, position, false); Boolean ignition = null; if (tripsConfig.getUseIgnition() - && position.getAttributes().containsKey(Position.KEY_IGNITION)) { + && position.hasAttribute(Position.KEY_IGNITION)) { ignition = position.getBoolean(Position.KEY_IGNITION); } if (newMotion) { diff --git a/src/main/java/org/traccar/model/ExtendedModel.java b/src/main/java/org/traccar/model/ExtendedModel.java index 8353d0e66..0fa1856d1 100644 --- a/src/main/java/org/traccar/model/ExtendedModel.java +++ b/src/main/java/org/traccar/model/ExtendedModel.java @@ -22,6 +22,10 @@ public class ExtendedModel extends BaseModel { private Map attributes = new LinkedHashMap<>(); + public boolean hasAttribute(String key) { + return attributes.containsKey(key); + } + public Map getAttributes() { return attributes; } diff --git a/src/main/java/org/traccar/notificators/NotificatorFirebase.java b/src/main/java/org/traccar/notificators/NotificatorFirebase.java index 5787b7ef2..17a6735ee 100644 --- a/src/main/java/org/traccar/notificators/NotificatorFirebase.java +++ b/src/main/java/org/traccar/notificators/NotificatorFirebase.java @@ -69,7 +69,7 @@ public class NotificatorFirebase implements Notificator { @Override public void send(User user, Event event, Position position) { - if (user.getAttributes().containsKey("notificationTokens")) { + if (user.hasAttribute("notificationTokens")) { var shortMessage = notificationFormatter.formatMessage(user, event, position, "short"); diff --git a/src/main/java/org/traccar/notificators/NotificatorPushover.java b/src/main/java/org/traccar/notificators/NotificatorPushover.java index 32ceae780..671984f86 100644 --- a/src/main/java/org/traccar/notificators/NotificatorPushover.java +++ b/src/main/java/org/traccar/notificators/NotificatorPushover.java @@ -65,7 +65,7 @@ public class NotificatorPushover implements Notificator { public void send(User user, Event event, Position position) { String device = ""; - if (user.getAttributes().containsKey("notificator.pushover.device")) { + if (user.hasAttribute("notificator.pushover.device")) { device = user.getString("notificator.pushover.device").replaceAll(" *, *", ","); } diff --git a/src/main/java/org/traccar/protocol/GalileoProtocolDecoder.java b/src/main/java/org/traccar/protocol/GalileoProtocolDecoder.java index 0a57087fe..d8a753abe 100644 --- a/src/main/java/org/traccar/protocol/GalileoProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/GalileoProtocolDecoder.java @@ -284,7 +284,7 @@ public class GalileoProtocolDecoder extends BaseProtocolDecoder { if (hasLocation && position.getFixTime() != null) { positions.add(position); - } else if (position.getAttributes().containsKey(Position.KEY_RESULT)) { + } else if (position.hasAttribute(Position.KEY_RESULT)) { position.setDeviceId(deviceSession.getDeviceId()); getLastLocation(position, null); positions.add(position); diff --git a/src/main/java/org/traccar/protocol/Gps103ProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gps103ProtocolDecoder.java index a2009e1b2..b63bcd0c0 100644 --- a/src/main/java/org/traccar/protocol/Gps103ProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/Gps103ProtocolDecoder.java @@ -202,7 +202,7 @@ public class Gps103ProtocolDecoder extends BaseProtocolDecoder { position.set(Position.PREFIX_TEMP + 1, Double.parseDouble(alarm.substring(2))); } else if (alarm.startsWith("oil ")) { position.set(Position.KEY_FUEL_LEVEL, Double.parseDouble(alarm.substring(4))); - } else if (!position.getAttributes().containsKey(Position.KEY_ALARM) && !alarm.equals("tracker")) { + } else if (!position.hasAttribute(Position.KEY_ALARM) && !alarm.equals("tracker")) { position.set(Position.KEY_EVENT, alarm); } diff --git a/src/main/java/org/traccar/protocol/S168ProtocolDecoder.java b/src/main/java/org/traccar/protocol/S168ProtocolDecoder.java index a88bfa65a..cf665c6ba 100644 --- a/src/main/java/org/traccar/protocol/S168ProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/S168ProtocolDecoder.java @@ -107,7 +107,7 @@ public class S168ProtocolDecoder extends BaseProtocolDecoder { if (network.getCellTowers() != null || network.getWifiAccessPoints() != null) { position.setNetwork(network); } - if (!position.getAttributes().containsKey(Position.KEY_SATELLITES)) { + if (!position.hasAttribute(Position.KEY_SATELLITES)) { getLastLocation(position, null); } diff --git a/src/main/java/org/traccar/reports/SummaryReportProvider.java b/src/main/java/org/traccar/reports/SummaryReportProvider.java index 02033b9e5..9415f3e81 100644 --- a/src/main/java/org/traccar/reports/SummaryReportProvider.java +++ b/src/main/java/org/traccar/reports/SummaryReportProvider.java @@ -79,8 +79,7 @@ public class SummaryReportProvider { result.setSpentFuel(reportUtils.calculateFuel(firstPosition, previousPosition)); long durationMilliseconds; - if (firstPosition.getAttributes().containsKey(Position.KEY_HOURS) - && previousPosition.getAttributes().containsKey(Position.KEY_HOURS)) { + if (firstPosition.hasAttribute(Position.KEY_HOURS) && previousPosition.hasAttribute(Position.KEY_HOURS)) { durationMilliseconds = previousPosition.getLong(Position.KEY_HOURS) - firstPosition.getLong(Position.KEY_HOURS); result.setEngineHours(durationMilliseconds); diff --git a/src/main/java/org/traccar/reports/common/ReportUtils.java b/src/main/java/org/traccar/reports/common/ReportUtils.java index ce5e3d8d4..253a6a2b6 100644 --- a/src/main/java/org/traccar/reports/common/ReportUtils.java +++ b/src/main/java/org/traccar/reports/common/ReportUtils.java @@ -154,9 +154,9 @@ public class ReportUtils { } public String findDriver(Position firstPosition, Position lastPosition) { - if (firstPosition.getAttributes().containsKey(Position.KEY_DRIVER_UNIQUE_ID)) { + if (firstPosition.hasAttribute(Position.KEY_DRIVER_UNIQUE_ID)) { return firstPosition.getString(Position.KEY_DRIVER_UNIQUE_ID); - } else if (lastPosition.getAttributes().containsKey(Position.KEY_DRIVER_UNIQUE_ID)) { + } else if (lastPosition.hasAttribute(Position.KEY_DRIVER_UNIQUE_ID)) { return lastPosition.getString(Position.KEY_DRIVER_UNIQUE_ID); } return null; @@ -298,8 +298,7 @@ public class ReportUtils { stop.setDuration(stopDuration); stop.setSpentFuel(calculateFuel(startStop, endStop)); - if (startStop.getAttributes().containsKey(Position.KEY_HOURS) - && endStop.getAttributes().containsKey(Position.KEY_HOURS)) { + if (startStop.hasAttribute(Position.KEY_HOURS) && endStop.hasAttribute(Position.KEY_HOURS)) { stop.setEngineHours(endStop.getLong(Position.KEY_HOURS) - startStop.getLong(Position.KEY_HOURS)); } -- cgit v1.2.3 From ae3eddba7e0a6688807f71d2c290618d1c49da05 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Sun, 2 Oct 2022 08:39:06 -0700 Subject: Use singletons where possible --- src/main/java/org/traccar/MainEventHandler.java | 9 +++++---- src/main/java/org/traccar/MainModule.java | 9 ++++++++- src/main/java/org/traccar/WebDataHandler.java | 2 ++ src/main/java/org/traccar/api/CorsResponseFilter.java | 2 ++ src/main/java/org/traccar/api/security/LoginService.java | 2 ++ src/main/java/org/traccar/api/signature/CryptoManager.java | 2 ++ src/main/java/org/traccar/api/signature/TokenManager.java | 2 ++ src/main/java/org/traccar/database/MediaManager.java | 2 ++ src/main/java/org/traccar/database/NotificationManager.java | 2 ++ src/main/java/org/traccar/handler/ComputedAttributesHandler.java | 2 ++ src/main/java/org/traccar/handler/CopyAttributesHandler.java | 2 ++ src/main/java/org/traccar/handler/DefaultDataHandler.java | 2 ++ src/main/java/org/traccar/handler/DistanceHandler.java | 2 ++ src/main/java/org/traccar/handler/EngineHoursHandler.java | 2 ++ src/main/java/org/traccar/handler/FilterHandler.java | 2 ++ src/main/java/org/traccar/handler/HemisphereHandler.java | 2 ++ src/main/java/org/traccar/handler/MotionHandler.java | 2 ++ src/main/java/org/traccar/handler/RemoteAddressHandler.java | 2 ++ src/main/java/org/traccar/handler/SpeedLimitHandler.java | 2 ++ src/main/java/org/traccar/handler/TimeHandler.java | 2 ++ src/main/java/org/traccar/handler/events/AlertEventHandler.java | 2 ++ .../java/org/traccar/handler/events/BehaviorEventHandler.java | 2 ++ .../org/traccar/handler/events/CommandResultEventHandler.java | 2 ++ src/main/java/org/traccar/handler/events/DriverEventHandler.java | 2 ++ src/main/java/org/traccar/handler/events/FuelEventHandler.java | 2 ++ .../java/org/traccar/handler/events/GeofenceEventHandler.java | 2 ++ .../java/org/traccar/handler/events/IgnitionEventHandler.java | 2 ++ .../java/org/traccar/handler/events/MaintenanceEventHandler.java | 2 ++ src/main/java/org/traccar/handler/events/MediaEventHandler.java | 2 ++ src/main/java/org/traccar/handler/events/MotionEventHandler.java | 2 ++ .../java/org/traccar/handler/events/OverspeedEventHandler.java | 2 ++ .../java/org/traccar/notification/NotificationFormatter.java | 2 ++ .../java/org/traccar/notification/TextTemplateFormatter.java | 2 ++ src/main/java/org/traccar/notificators/NotificatorMail.java | 2 ++ src/main/java/org/traccar/notificators/NotificatorPushover.java | 2 ++ src/main/java/org/traccar/notificators/NotificatorSms.java | 2 ++ src/main/java/org/traccar/notificators/NotificatorTelegram.java | 2 ++ src/main/java/org/traccar/notificators/NotificatorTraccar.java | 2 ++ src/main/java/org/traccar/notificators/NotificatorWeb.java | 8 +++----- src/main/java/org/traccar/reports/common/ReportUtils.java | 2 ++ src/main/java/org/traccar/reports/common/TripsConfig.java | 2 ++ src/main/java/org/traccar/web/WebServer.java | 2 -- 42 files changed, 92 insertions(+), 12 deletions(-) (limited to 'src/main/java/org/traccar/WebDataHandler.java') diff --git a/src/main/java/org/traccar/MainEventHandler.java b/src/main/java/org/traccar/MainEventHandler.java index 52eb43faf..17bcad0dd 100644 --- a/src/main/java/org/traccar/MainEventHandler.java +++ b/src/main/java/org/traccar/MainEventHandler.java @@ -16,6 +16,7 @@ package org.traccar; import io.netty.channel.Channel; +import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.socket.DatagramChannel; @@ -23,7 +24,6 @@ import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.timeout.IdleStateEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.traccar.broadcast.BroadcastService; import org.traccar.config.Config; import org.traccar.config.Keys; import org.traccar.database.StatisticsManager; @@ -41,11 +41,14 @@ import org.traccar.storage.query.Condition; import org.traccar.storage.query.Request; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; +@Singleton +@ChannelHandler.Sharable public class MainEventHandler extends ChannelInboundHandlerAdapter { private static final Logger LOGGER = LoggerFactory.getLogger(MainEventHandler.class); @@ -57,17 +60,15 @@ public class MainEventHandler extends ChannelInboundHandlerAdapter { private final Storage storage; private final ConnectionManager connectionManager; private final StatisticsManager statisticsManager; - private final BroadcastService broadcastService; @Inject public MainEventHandler( Config config, CacheManager cacheManager, Storage storage, ConnectionManager connectionManager, - StatisticsManager statisticsManager, BroadcastService broadcastService) { + StatisticsManager statisticsManager) { this.cacheManager = cacheManager; this.storage = storage; this.connectionManager = connectionManager; this.statisticsManager = statisticsManager; - this.broadcastService = broadcastService; String connectionlessProtocolList = config.getString(Keys.STATUS_IGNORE_OFFLINE); if (connectionlessProtocolList != null) { connectionlessProtocols.addAll(Arrays.asList(connectionlessProtocolList.split("[, ]"))); diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java index 94669915b..c4cda578e 100644 --- a/src/main/java/org/traccar/MainModule.java +++ b/src/main/java/org/traccar/MainModule.java @@ -99,10 +99,11 @@ public class MainModule extends AbstractModule { protected void configure() { bindConstant().annotatedWith(Names.named("configFile")).to(configFile); bind(Config.class).asEagerSingleton(); - bind(Storage.class).to(DatabaseStorage.class); + bind(Storage.class).to(DatabaseStorage.class).in(Scopes.SINGLETON); bind(Timer.class).to(HashedWheelTimer.class).in(Scopes.SINGLETON); } + @Singleton @Provides public static ObjectMapper provideObjectMapper(Config config) { ObjectMapper objectMapper = new ObjectMapper(); @@ -114,6 +115,7 @@ public class MainModule extends AbstractModule { return objectMapper; } + @Singleton @Provides public static Client provideClient(ObjectMapperContextResolver objectMapperContextResolver) { return ClientBuilder.newClient().register(objectMapperContextResolver); @@ -130,6 +132,7 @@ public class MainModule extends AbstractModule { return null; } + @Singleton @Provides public static MailManager provideMailManager(Config config, StatisticsManager statisticsManager) { if (config.getBoolean(Keys.MAIL_DEBUG)) { @@ -265,6 +268,7 @@ public class MainModule extends AbstractModule { return null; } + @Singleton @Provides public static GeolocationHandler provideGeolocationHandler( Config config, @Nullable GeolocationProvider geolocationProvider, CacheManager cacheManager, @@ -275,6 +279,7 @@ public class MainModule extends AbstractModule { return null; } + @Singleton @Provides public static GeocoderHandler provideGeocoderHandler( Config config, @Nullable Geocoder geocoder, CacheManager cacheManager) { @@ -284,6 +289,7 @@ public class MainModule extends AbstractModule { return null; } + @Singleton @Provides public static SpeedLimitHandler provideSpeedLimitHandler(@Nullable SpeedLimitProvider speedLimitProvider) { if (speedLimitProvider != null) { @@ -302,6 +308,7 @@ public class MainModule extends AbstractModule { return new NullBroadcastService(); } + @Singleton @Provides public static EventForwarder provideEventForwarder(Config config, Client client, CacheManager cacheManager) { if (config.hasKey(Keys.EVENT_FORWARD_URL)) { diff --git a/src/main/java/org/traccar/WebDataHandler.java b/src/main/java/org/traccar/WebDataHandler.java index d0aa32e53..9b26c8875 100644 --- a/src/main/java/org/traccar/WebDataHandler.java +++ b/src/main/java/org/traccar/WebDataHandler.java @@ -33,6 +33,7 @@ import org.traccar.model.Group; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -52,6 +53,7 @@ import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +@Singleton @ChannelHandler.Sharable public class WebDataHandler extends BaseDataHandler { diff --git a/src/main/java/org/traccar/api/CorsResponseFilter.java b/src/main/java/org/traccar/api/CorsResponseFilter.java index 5375e207f..67d0341a1 100644 --- a/src/main/java/org/traccar/api/CorsResponseFilter.java +++ b/src/main/java/org/traccar/api/CorsResponseFilter.java @@ -20,11 +20,13 @@ import org.traccar.config.Config; import org.traccar.config.Keys; import javax.inject.Inject; +import javax.inject.Singleton; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import java.io.IOException; +@Singleton public class CorsResponseFilter implements ContainerResponseFilter { private final String allowed; diff --git a/src/main/java/org/traccar/api/security/LoginService.java b/src/main/java/org/traccar/api/security/LoginService.java index 1e82a4cf2..32487f06b 100644 --- a/src/main/java/org/traccar/api/security/LoginService.java +++ b/src/main/java/org/traccar/api/security/LoginService.java @@ -28,9 +28,11 @@ import org.traccar.storage.query.Request; import javax.annotation.Nullable; import javax.inject.Inject; +import javax.inject.Singleton; import java.io.IOException; import java.security.GeneralSecurityException; +@Singleton public class LoginService { private final Storage storage; diff --git a/src/main/java/org/traccar/api/signature/CryptoManager.java b/src/main/java/org/traccar/api/signature/CryptoManager.java index 8a3e7704c..249d5bd97 100644 --- a/src/main/java/org/traccar/api/signature/CryptoManager.java +++ b/src/main/java/org/traccar/api/signature/CryptoManager.java @@ -21,6 +21,7 @@ import org.traccar.storage.query.Columns; import org.traccar.storage.query.Request; import javax.inject.Inject; +import javax.inject.Singleton; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyPair; @@ -33,6 +34,7 @@ import java.security.spec.ECGenParameterSpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; +@Singleton public class CryptoManager { private final Storage storage; diff --git a/src/main/java/org/traccar/api/signature/TokenManager.java b/src/main/java/org/traccar/api/signature/TokenManager.java index a352ecc10..6a0d90b40 100644 --- a/src/main/java/org/traccar/api/signature/TokenManager.java +++ b/src/main/java/org/traccar/api/signature/TokenManager.java @@ -21,11 +21,13 @@ import org.apache.commons.codec.binary.Base64; import org.traccar.storage.StorageException; import javax.inject.Inject; +import javax.inject.Singleton; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Date; import java.util.concurrent.TimeUnit; +@Singleton public class TokenManager { private static final int DEFAULT_EXPIRATION_DAYS = 7; diff --git a/src/main/java/org/traccar/database/MediaManager.java b/src/main/java/org/traccar/database/MediaManager.java index 2b3e3e1ee..c1ef810ee 100644 --- a/src/main/java/org/traccar/database/MediaManager.java +++ b/src/main/java/org/traccar/database/MediaManager.java @@ -22,6 +22,7 @@ import org.traccar.config.Config; import org.traccar.config.Keys; import javax.inject.Inject; +import javax.inject.Singleton; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -34,6 +35,7 @@ import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; +@Singleton public class MediaManager { private static final Logger LOGGER = LoggerFactory.getLogger(MediaManager.class); diff --git a/src/main/java/org/traccar/database/NotificationManager.java b/src/main/java/org/traccar/database/NotificationManager.java index 5be627f2a..5ea89fcac 100644 --- a/src/main/java/org/traccar/database/NotificationManager.java +++ b/src/main/java/org/traccar/database/NotificationManager.java @@ -36,11 +36,13 @@ import org.traccar.storage.query.Request; import javax.annotation.Nullable; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Arrays; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; +@Singleton public class NotificationManager { private static final Logger LOGGER = LoggerFactory.getLogger(NotificationManager.class); diff --git a/src/main/java/org/traccar/handler/ComputedAttributesHandler.java b/src/main/java/org/traccar/handler/ComputedAttributesHandler.java index 82ac4e804..c9f1f63d7 100644 --- a/src/main/java/org/traccar/handler/ComputedAttributesHandler.java +++ b/src/main/java/org/traccar/handler/ComputedAttributesHandler.java @@ -40,7 +40,9 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class ComputedAttributesHandler extends BaseDataHandler { diff --git a/src/main/java/org/traccar/handler/CopyAttributesHandler.java b/src/main/java/org/traccar/handler/CopyAttributesHandler.java index 1fa47cfaa..e5c9bc29a 100644 --- a/src/main/java/org/traccar/handler/CopyAttributesHandler.java +++ b/src/main/java/org/traccar/handler/CopyAttributesHandler.java @@ -25,7 +25,9 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class CopyAttributesHandler extends BaseDataHandler { diff --git a/src/main/java/org/traccar/handler/DefaultDataHandler.java b/src/main/java/org/traccar/handler/DefaultDataHandler.java index f6a20628b..89255a5fe 100644 --- a/src/main/java/org/traccar/handler/DefaultDataHandler.java +++ b/src/main/java/org/traccar/handler/DefaultDataHandler.java @@ -25,7 +25,9 @@ import org.traccar.storage.query.Columns; import org.traccar.storage.query.Request; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class DefaultDataHandler extends BaseDataHandler { diff --git a/src/main/java/org/traccar/handler/DistanceHandler.java b/src/main/java/org/traccar/handler/DistanceHandler.java index 87c4a81c9..30dc9ff2b 100644 --- a/src/main/java/org/traccar/handler/DistanceHandler.java +++ b/src/main/java/org/traccar/handler/DistanceHandler.java @@ -25,9 +25,11 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; import java.math.BigDecimal; import java.math.RoundingMode; +@Singleton @ChannelHandler.Sharable public class DistanceHandler extends BaseDataHandler { diff --git a/src/main/java/org/traccar/handler/EngineHoursHandler.java b/src/main/java/org/traccar/handler/EngineHoursHandler.java index 54a1a0c25..c10fe9064 100644 --- a/src/main/java/org/traccar/handler/EngineHoursHandler.java +++ b/src/main/java/org/traccar/handler/EngineHoursHandler.java @@ -22,7 +22,9 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class EngineHoursHandler extends BaseDataHandler { diff --git a/src/main/java/org/traccar/handler/FilterHandler.java b/src/main/java/org/traccar/handler/FilterHandler.java index 37f5cd566..f09cb16a3 100644 --- a/src/main/java/org/traccar/handler/FilterHandler.java +++ b/src/main/java/org/traccar/handler/FilterHandler.java @@ -35,8 +35,10 @@ import org.traccar.storage.query.Order; import org.traccar.storage.query.Request; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Date; +@Singleton @ChannelHandler.Sharable public class FilterHandler extends BaseDataHandler { diff --git a/src/main/java/org/traccar/handler/HemisphereHandler.java b/src/main/java/org/traccar/handler/HemisphereHandler.java index f760457a3..ccbde9fe5 100644 --- a/src/main/java/org/traccar/handler/HemisphereHandler.java +++ b/src/main/java/org/traccar/handler/HemisphereHandler.java @@ -22,7 +22,9 @@ import org.traccar.config.Keys; import org.traccar.model.Position; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class HemisphereHandler extends BaseDataHandler { diff --git a/src/main/java/org/traccar/handler/MotionHandler.java b/src/main/java/org/traccar/handler/MotionHandler.java index 25ee615c5..10312f9b3 100644 --- a/src/main/java/org/traccar/handler/MotionHandler.java +++ b/src/main/java/org/traccar/handler/MotionHandler.java @@ -22,7 +22,9 @@ import org.traccar.model.Position; import org.traccar.reports.common.TripsConfig; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class MotionHandler extends BaseDataHandler { diff --git a/src/main/java/org/traccar/handler/RemoteAddressHandler.java b/src/main/java/org/traccar/handler/RemoteAddressHandler.java index 809f67ca2..e18d34ef2 100644 --- a/src/main/java/org/traccar/handler/RemoteAddressHandler.java +++ b/src/main/java/org/traccar/handler/RemoteAddressHandler.java @@ -23,8 +23,10 @@ import org.traccar.config.Keys; import org.traccar.model.Position; import javax.inject.Inject; +import javax.inject.Singleton; import java.net.InetSocketAddress; +@Singleton @ChannelHandler.Sharable public class RemoteAddressHandler extends ChannelInboundHandlerAdapter { diff --git a/src/main/java/org/traccar/handler/SpeedLimitHandler.java b/src/main/java/org/traccar/handler/SpeedLimitHandler.java index 0469b9f16..0c6025999 100644 --- a/src/main/java/org/traccar/handler/SpeedLimitHandler.java +++ b/src/main/java/org/traccar/handler/SpeedLimitHandler.java @@ -24,7 +24,9 @@ import org.traccar.model.Position; import org.traccar.speedlimit.SpeedLimitProvider; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class SpeedLimitHandler extends ChannelInboundHandlerAdapter { diff --git a/src/main/java/org/traccar/handler/TimeHandler.java b/src/main/java/org/traccar/handler/TimeHandler.java index 439c076c7..c98b0bd4c 100644 --- a/src/main/java/org/traccar/handler/TimeHandler.java +++ b/src/main/java/org/traccar/handler/TimeHandler.java @@ -24,10 +24,12 @@ import org.traccar.config.Keys; import org.traccar.model.Position; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Arrays; import java.util.HashSet; import java.util.Set; +@Singleton @ChannelHandler.Sharable public class TimeHandler extends ChannelInboundHandlerAdapter { diff --git a/src/main/java/org/traccar/handler/events/AlertEventHandler.java b/src/main/java/org/traccar/handler/events/AlertEventHandler.java index 75626ca6c..9f77df989 100644 --- a/src/main/java/org/traccar/handler/events/AlertEventHandler.java +++ b/src/main/java/org/traccar/handler/events/AlertEventHandler.java @@ -26,7 +26,9 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class AlertEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/BehaviorEventHandler.java b/src/main/java/org/traccar/handler/events/BehaviorEventHandler.java index 3c2fa6a97..51bbd82d6 100644 --- a/src/main/java/org/traccar/handler/events/BehaviorEventHandler.java +++ b/src/main/java/org/traccar/handler/events/BehaviorEventHandler.java @@ -24,9 +24,11 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Collections; import java.util.Map; +@Singleton @ChannelHandler.Sharable public class BehaviorEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/CommandResultEventHandler.java b/src/main/java/org/traccar/handler/events/CommandResultEventHandler.java index 858f84e09..772176e9c 100644 --- a/src/main/java/org/traccar/handler/events/CommandResultEventHandler.java +++ b/src/main/java/org/traccar/handler/events/CommandResultEventHandler.java @@ -23,7 +23,9 @@ import org.traccar.model.Event; import org.traccar.model.Position; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class CommandResultEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/DriverEventHandler.java b/src/main/java/org/traccar/handler/events/DriverEventHandler.java index 1ad66ba64..51fdc0307 100644 --- a/src/main/java/org/traccar/handler/events/DriverEventHandler.java +++ b/src/main/java/org/traccar/handler/events/DriverEventHandler.java @@ -23,9 +23,11 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Collections; import java.util.Map; +@Singleton @ChannelHandler.Sharable public class DriverEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/FuelEventHandler.java b/src/main/java/org/traccar/handler/events/FuelEventHandler.java index d5d4ab9be..462cc4223 100644 --- a/src/main/java/org/traccar/handler/events/FuelEventHandler.java +++ b/src/main/java/org/traccar/handler/events/FuelEventHandler.java @@ -25,8 +25,10 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Map; +@Singleton @ChannelHandler.Sharable public class FuelEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/GeofenceEventHandler.java b/src/main/java/org/traccar/handler/events/GeofenceEventHandler.java index 70bdb84cb..b1be7e8ad 100644 --- a/src/main/java/org/traccar/handler/events/GeofenceEventHandler.java +++ b/src/main/java/org/traccar/handler/events/GeofenceEventHandler.java @@ -33,11 +33,13 @@ import org.traccar.storage.query.Condition; import org.traccar.storage.query.Request; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +@Singleton @ChannelHandler.Sharable public class GeofenceEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/IgnitionEventHandler.java b/src/main/java/org/traccar/handler/events/IgnitionEventHandler.java index 3c5ac3545..b2e9a3325 100644 --- a/src/main/java/org/traccar/handler/events/IgnitionEventHandler.java +++ b/src/main/java/org/traccar/handler/events/IgnitionEventHandler.java @@ -27,7 +27,9 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class IgnitionEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/MaintenanceEventHandler.java b/src/main/java/org/traccar/handler/events/MaintenanceEventHandler.java index be3e9bf8d..4fcfcd079 100644 --- a/src/main/java/org/traccar/handler/events/MaintenanceEventHandler.java +++ b/src/main/java/org/traccar/handler/events/MaintenanceEventHandler.java @@ -26,7 +26,9 @@ import org.traccar.model.Position; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton @ChannelHandler.Sharable public class MaintenanceEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/MediaEventHandler.java b/src/main/java/org/traccar/handler/events/MediaEventHandler.java index 5b9013fad..a49e08e8d 100644 --- a/src/main/java/org/traccar/handler/events/MediaEventHandler.java +++ b/src/main/java/org/traccar/handler/events/MediaEventHandler.java @@ -20,10 +20,12 @@ import org.traccar.model.Event; import org.traccar.model.Position; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; +@Singleton @ChannelHandler.Sharable public class MediaEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/MotionEventHandler.java b/src/main/java/org/traccar/handler/events/MotionEventHandler.java index 0777f353a..3511cf682 100644 --- a/src/main/java/org/traccar/handler/events/MotionEventHandler.java +++ b/src/main/java/org/traccar/handler/events/MotionEventHandler.java @@ -34,9 +34,11 @@ import org.traccar.storage.query.Condition; import org.traccar.storage.query.Request; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Collections; import java.util.Map; +@Singleton @ChannelHandler.Sharable public class MotionEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/handler/events/OverspeedEventHandler.java b/src/main/java/org/traccar/handler/events/OverspeedEventHandler.java index c03b8eb7b..3928fcc88 100644 --- a/src/main/java/org/traccar/handler/events/OverspeedEventHandler.java +++ b/src/main/java/org/traccar/handler/events/OverspeedEventHandler.java @@ -37,9 +37,11 @@ import org.traccar.storage.query.Condition; import org.traccar.storage.query.Request; import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Collections; import java.util.Map; +@Singleton @ChannelHandler.Sharable public class OverspeedEventHandler extends BaseEventHandler { diff --git a/src/main/java/org/traccar/notification/NotificationFormatter.java b/src/main/java/org/traccar/notification/NotificationFormatter.java index fa244d9b4..9ee3b97b6 100644 --- a/src/main/java/org/traccar/notification/NotificationFormatter.java +++ b/src/main/java/org/traccar/notification/NotificationFormatter.java @@ -28,7 +28,9 @@ import org.traccar.model.User; import org.traccar.session.cache.CacheManager; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton public class NotificationFormatter { private final CacheManager cacheManager; diff --git a/src/main/java/org/traccar/notification/TextTemplateFormatter.java b/src/main/java/org/traccar/notification/TextTemplateFormatter.java index be894af96..444f4a7c2 100644 --- a/src/main/java/org/traccar/notification/TextTemplateFormatter.java +++ b/src/main/java/org/traccar/notification/TextTemplateFormatter.java @@ -30,6 +30,7 @@ import org.traccar.model.User; import org.traccar.storage.StorageException; import javax.inject.Inject; +import javax.inject.Singleton; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; @@ -37,6 +38,7 @@ import java.nio.file.Paths; import java.security.GeneralSecurityException; import java.util.Locale; +@Singleton public class TextTemplateFormatter { private static final Logger LOGGER = LoggerFactory.getLogger(TextTemplateFormatter.class); diff --git a/src/main/java/org/traccar/notificators/NotificatorMail.java b/src/main/java/org/traccar/notificators/NotificatorMail.java index 75571cfc4..19fde6756 100644 --- a/src/main/java/org/traccar/notificators/NotificatorMail.java +++ b/src/main/java/org/traccar/notificators/NotificatorMail.java @@ -24,8 +24,10 @@ import org.traccar.notification.MessageException; import org.traccar.notification.NotificationFormatter; import javax.inject.Inject; +import javax.inject.Singleton; import javax.mail.MessagingException; +@Singleton public class NotificatorMail implements Notificator { private final MailManager mailManager; diff --git a/src/main/java/org/traccar/notificators/NotificatorPushover.java b/src/main/java/org/traccar/notificators/NotificatorPushover.java index 105cb27f0..e00db0579 100644 --- a/src/main/java/org/traccar/notificators/NotificatorPushover.java +++ b/src/main/java/org/traccar/notificators/NotificatorPushover.java @@ -24,9 +24,11 @@ import org.traccar.model.User; import org.traccar.notification.NotificationFormatter; import javax.inject.Inject; +import javax.inject.Singleton; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; +@Singleton public class NotificatorPushover implements Notificator { private final NotificationFormatter notificationFormatter; diff --git a/src/main/java/org/traccar/notificators/NotificatorSms.java b/src/main/java/org/traccar/notificators/NotificatorSms.java index 544b67a5e..e37d10888 100644 --- a/src/main/java/org/traccar/notificators/NotificatorSms.java +++ b/src/main/java/org/traccar/notificators/NotificatorSms.java @@ -25,7 +25,9 @@ import org.traccar.notification.NotificationFormatter; import org.traccar.sms.SmsManager; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton public class NotificatorSms implements Notificator { private final SmsManager smsManager; diff --git a/src/main/java/org/traccar/notificators/NotificatorTelegram.java b/src/main/java/org/traccar/notificators/NotificatorTelegram.java index a00cd36f1..38e87c222 100644 --- a/src/main/java/org/traccar/notificators/NotificatorTelegram.java +++ b/src/main/java/org/traccar/notificators/NotificatorTelegram.java @@ -25,9 +25,11 @@ import org.traccar.model.User; import org.traccar.notification.NotificationFormatter; import javax.inject.Inject; +import javax.inject.Singleton; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; +@Singleton public class NotificatorTelegram implements Notificator { private final NotificationFormatter notificationFormatter; diff --git a/src/main/java/org/traccar/notificators/NotificatorTraccar.java b/src/main/java/org/traccar/notificators/NotificatorTraccar.java index 123b16ad8..9ae39f975 100644 --- a/src/main/java/org/traccar/notificators/NotificatorTraccar.java +++ b/src/main/java/org/traccar/notificators/NotificatorTraccar.java @@ -24,9 +24,11 @@ import org.traccar.model.User; import org.traccar.notification.NotificationFormatter; import javax.inject.Inject; +import javax.inject.Singleton; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; +@Singleton public class NotificatorTraccar implements Notificator { private final NotificationFormatter notificationFormatter; diff --git a/src/main/java/org/traccar/notificators/NotificatorWeb.java b/src/main/java/org/traccar/notificators/NotificatorWeb.java index f495042a5..deabeade1 100644 --- a/src/main/java/org/traccar/notificators/NotificatorWeb.java +++ b/src/main/java/org/traccar/notificators/NotificatorWeb.java @@ -16,7 +16,6 @@ */ package org.traccar.notificators; -import org.traccar.broadcast.BroadcastService; import org.traccar.model.Event; import org.traccar.model.Position; import org.traccar.model.User; @@ -24,19 +23,18 @@ import org.traccar.notification.NotificationFormatter; import org.traccar.session.ConnectionManager; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton public final class NotificatorWeb implements Notificator { private final ConnectionManager connectionManager; - private final BroadcastService broadcastService; private final NotificationFormatter notificationFormatter; @Inject public NotificatorWeb( - ConnectionManager connectionManager, BroadcastService broadcastService, - NotificationFormatter notificationFormatter) { + ConnectionManager connectionManager, NotificationFormatter notificationFormatter) { this.connectionManager = connectionManager; - this.broadcastService = broadcastService; this.notificationFormatter = notificationFormatter; } diff --git a/src/main/java/org/traccar/reports/common/ReportUtils.java b/src/main/java/org/traccar/reports/common/ReportUtils.java index 57ed4d148..1de774dab 100644 --- a/src/main/java/org/traccar/reports/common/ReportUtils.java +++ b/src/main/java/org/traccar/reports/common/ReportUtils.java @@ -52,6 +52,7 @@ import org.traccar.storage.query.Request; import javax.annotation.Nullable; import javax.inject.Inject; +import javax.inject.Singleton; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -67,6 +68,7 @@ import java.util.Locale; import java.util.Objects; import java.util.stream.Collectors; +@Singleton public class ReportUtils { private final Config config; diff --git a/src/main/java/org/traccar/reports/common/TripsConfig.java b/src/main/java/org/traccar/reports/common/TripsConfig.java index c28cbeed4..52db97b74 100644 --- a/src/main/java/org/traccar/reports/common/TripsConfig.java +++ b/src/main/java/org/traccar/reports/common/TripsConfig.java @@ -20,7 +20,9 @@ import org.traccar.config.Config; import org.traccar.config.Keys; import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton public class TripsConfig { @Inject diff --git a/src/main/java/org/traccar/web/WebServer.java b/src/main/java/org/traccar/web/WebServer.java index 62ac338eb..a7ac4d6b2 100644 --- a/src/main/java/org/traccar/web/WebServer.java +++ b/src/main/java/org/traccar/web/WebServer.java @@ -52,7 +52,6 @@ import org.traccar.api.security.SecurityRequestFilter; import org.traccar.config.Config; import org.traccar.config.Keys; -import javax.inject.Inject; import javax.servlet.DispatcherType; import javax.servlet.ServletException; import javax.servlet.SessionCookieConfig; @@ -76,7 +75,6 @@ public class WebServer implements LifecycleObject { private final Config config; private final Server server; - @Inject public WebServer(Injector injector, Config config) { this.injector = injector; this.config = config; -- cgit v1.2.3 From d9d990b492896d7e42a503c002de7715f6d12a30 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Thu, 10 Nov 2022 08:29:10 -0800 Subject: Add comment --- src/main/java/org/traccar/WebDataHandler.java | 1 + 1 file changed, 1 insertion(+) (limited to 'src/main/java/org/traccar/WebDataHandler.java') diff --git a/src/main/java/org/traccar/WebDataHandler.java b/src/main/java/org/traccar/WebDataHandler.java index 9b26c8875..2d2e3dc8f 100644 --- a/src/main/java/org/traccar/WebDataHandler.java +++ b/src/main/java/org/traccar/WebDataHandler.java @@ -126,6 +126,7 @@ public class WebDataHandler extends BaseDataHandler { return s.toString(); } + // OpenGTS status code private String calculateStatus(Position position) { if (position.hasAttribute(Position.KEY_ALARM)) { return "0xF841"; // STATUS_PANIC_ON -- cgit v1.2.3 From 5877cb1b3f1fa7331c4310b9754a3ec442586497 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Sun, 13 Nov 2022 11:48:43 -0800 Subject: Refactor position forwarding --- src/main/java/org/traccar/BasePipelineFactory.java | 2 +- src/main/java/org/traccar/MainModule.java | 16 ++ .../org/traccar/PositionForwardingHandler.java | 141 +++++++++ src/main/java/org/traccar/WebDataHandler.java | 316 --------------------- src/main/java/org/traccar/config/Keys.java | 17 +- .../org/traccar/database/NotificationManager.java | 6 +- .../java/org/traccar/forward/EventForwarder.java | 2 +- .../org/traccar/forward/EventForwarderJson.java | 22 +- .../java/org/traccar/forward/PositionData.java | 45 +++ .../org/traccar/forward/PositionForwarder.java | 20 ++ .../org/traccar/forward/PositionForwarderJson.java | 86 ++++++ .../org/traccar/forward/PositionForwarderUrl.java | 166 +++++++++++ .../java/org/traccar/forward/ResultHandler.java | 20 ++ src/test/java/org/traccar/WebDataHandlerTest.java | 42 --- .../traccar/forward/PositionForwarderUrlTest.java | 42 +++ 15 files changed, 561 insertions(+), 382 deletions(-) create mode 100644 src/main/java/org/traccar/PositionForwardingHandler.java delete mode 100644 src/main/java/org/traccar/WebDataHandler.java create mode 100644 src/main/java/org/traccar/forward/PositionData.java create mode 100644 src/main/java/org/traccar/forward/PositionForwarder.java create mode 100644 src/main/java/org/traccar/forward/PositionForwarderJson.java create mode 100644 src/main/java/org/traccar/forward/PositionForwarderUrl.java create mode 100644 src/main/java/org/traccar/forward/ResultHandler.java delete mode 100644 src/test/java/org/traccar/WebDataHandlerTest.java create mode 100644 src/test/java/org/traccar/forward/PositionForwarderUrlTest.java (limited to 'src/main/java/org/traccar/WebDataHandler.java') diff --git a/src/main/java/org/traccar/BasePipelineFactory.java b/src/main/java/org/traccar/BasePipelineFactory.java index 0d91ec7e4..b184da45c 100644 --- a/src/main/java/org/traccar/BasePipelineFactory.java +++ b/src/main/java/org/traccar/BasePipelineFactory.java @@ -140,7 +140,7 @@ public abstract class BasePipelineFactory extends ChannelInitializer { CopyAttributesHandler.class, EngineHoursHandler.class, ComputedAttributesHandler.class, - WebDataHandler.class, + PositionForwardingHandler.class, DefaultDataHandler.class, MediaEventHandler.class, CommandResultEventHandler.class, diff --git a/src/main/java/org/traccar/MainModule.java b/src/main/java/org/traccar/MainModule.java index 9a5cca4c7..9d450fef7 100644 --- a/src/main/java/org/traccar/MainModule.java +++ b/src/main/java/org/traccar/MainModule.java @@ -37,6 +37,9 @@ import org.traccar.database.LdapProvider; import org.traccar.database.StatisticsManager; import org.traccar.forward.EventForwarder; import org.traccar.forward.EventForwarderJson; +import org.traccar.forward.PositionForwarder; +import org.traccar.forward.PositionForwarderJson; +import org.traccar.forward.PositionForwarderUrl; import org.traccar.geocoder.AddressFormat; import org.traccar.geocoder.BanGeocoder; import org.traccar.geocoder.BingMapsGeocoder; @@ -318,6 +321,19 @@ public class MainModule extends AbstractModule { return null; } + @Singleton + @Provides + public static PositionForwarder providePositionForwarder(Config config, Client client, ObjectMapper objectMapper) { + if (config.hasKey(Keys.FORWARD_URL)) { + if (config.getBoolean(Keys.FORWARD_JSON)) { + return new PositionForwarderJson(config, client, objectMapper); + } else { + return new PositionForwarderUrl(config, client, objectMapper); + } + } + return null; + } + @Singleton @Provides public static VelocityEngine provideVelocityEngine(Config config) { diff --git a/src/main/java/org/traccar/PositionForwardingHandler.java b/src/main/java/org/traccar/PositionForwardingHandler.java new file mode 100644 index 000000000..83f91e937 --- /dev/null +++ b/src/main/java/org/traccar/PositionForwardingHandler.java @@ -0,0 +1,141 @@ +/* + * Copyright 2015 - 2022 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; + +import io.netty.channel.ChannelHandler; +import io.netty.util.Timeout; +import io.netty.util.Timer; +import io.netty.util.TimerTask; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.traccar.config.Config; +import org.traccar.config.Keys; +import org.traccar.forward.PositionData; +import org.traccar.forward.PositionForwarder; +import org.traccar.forward.ResultHandler; +import org.traccar.model.Device; +import org.traccar.model.Position; +import org.traccar.session.cache.CacheManager; + +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +@Singleton +@ChannelHandler.Sharable +public class PositionForwardingHandler extends BaseDataHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(PositionForwardingHandler.class); + + private final CacheManager cacheManager; + private final Timer timer; + + private final PositionForwarder positionForwarder; + + private final boolean retryEnabled; + private final int retryDelay; + private final int retryCount; + private final int retryLimit; + + private final AtomicInteger deliveryPending; + + @Inject + public PositionForwardingHandler( + Config config, CacheManager cacheManager, Timer timer, @Nullable PositionForwarder positionForwarder) { + + this.cacheManager = cacheManager; + this.timer = timer; + this.positionForwarder = positionForwarder; + + this.retryEnabled = config.getBoolean(Keys.FORWARD_RETRY_ENABLE); + this.retryDelay = config.getInteger(Keys.FORWARD_RETRY_DELAY); + this.retryCount = config.getInteger(Keys.FORWARD_RETRY_COUNT); + this.retryLimit = config.getInteger(Keys.FORWARD_RETRY_LIMIT); + + this.deliveryPending = new AtomicInteger(); + } + + class AsyncRequestAndCallback implements ResultHandler, TimerTask { + + private final PositionData positionData; + + private int retries = 0; + + AsyncRequestAndCallback(PositionData positionData) { + this.positionData = positionData; + deliveryPending.incrementAndGet(); + } + + private void send() { + positionForwarder.forward(positionData, this); + } + + private void retry(Throwable throwable) { + boolean scheduled = false; + try { + if (retryEnabled && deliveryPending.get() <= retryLimit && retries < retryCount) { + schedule(); + scheduled = true; + } + } finally { + int pending = scheduled ? deliveryPending.get() : deliveryPending.decrementAndGet(); + LOGGER.warn("Position forwarding failed: " + pending + " pending", throwable); + } + } + + private void schedule() { + timer.newTimeout(this, retryDelay * (long) Math.pow(2, retries++), TimeUnit.MILLISECONDS); + } + + @Override + public void onResult(boolean success, Throwable throwable) { + if (success) { + deliveryPending.decrementAndGet(); + } else { + retry(throwable); + } + } + + @Override + public void run(Timeout timeout) { + boolean sent = false; + try { + if (!timeout.isCancelled()) { + send(); + sent = true; + } + } finally { + if (!sent) { + deliveryPending.decrementAndGet(); + } + } + } + } + + @Override + protected Position handlePosition(Position position) { + if (positionForwarder != null) { + PositionData positionData = new PositionData(); + positionData.setPosition(position); + positionData.setDevice(cacheManager.getObject(Device.class, position.getDeviceId())); + new AsyncRequestAndCallback(positionData).send(); + } + return position; + } + +} diff --git a/src/main/java/org/traccar/WebDataHandler.java b/src/main/java/org/traccar/WebDataHandler.java deleted file mode 100644 index 2d2e3dc8f..000000000 --- a/src/main/java/org/traccar/WebDataHandler.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright 2015 - 2022 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; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.netty.channel.ChannelHandler; -import io.netty.util.Timer; -import io.netty.util.Timeout; -import io.netty.util.TimerTask; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.traccar.config.Config; -import org.traccar.config.Keys; -import org.traccar.helper.Checksum; -import org.traccar.model.Device; -import org.traccar.model.Position; -import org.traccar.model.Group; -import org.traccar.session.cache.CacheManager; - -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Entity; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.InvocationCallback; -import java.util.HashMap; -import java.util.Map; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Calendar; -import java.util.Formatter; -import java.util.Locale; -import java.util.TimeZone; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -@Singleton -@ChannelHandler.Sharable -public class WebDataHandler extends BaseDataHandler { - - private static final Logger LOGGER = LoggerFactory.getLogger(WebDataHandler.class); - - private static final String KEY_POSITION = "position"; - private static final String KEY_DEVICE = "device"; - - private final CacheManager cacheManager; - private final ObjectMapper objectMapper; - private final Client client; - private final Timer timer; - - private final String url; - private final String header; - private final boolean json; - private final boolean urlVariables; - - private final boolean retryEnabled; - private final int retryDelay; - private final int retryCount; - private final int retryLimit; - - private final AtomicInteger deliveryPending; - - @Inject - public WebDataHandler( - Config config, CacheManager cacheManager, ObjectMapper objectMapper, Client client, Timer timer) { - - this.cacheManager = cacheManager; - this.objectMapper = objectMapper; - this.client = client; - this.timer = timer; - this.url = config.getString(Keys.FORWARD_URL); - this.header = config.getString(Keys.FORWARD_HEADER); - this.json = config.getBoolean(Keys.FORWARD_JSON); - this.urlVariables = config.getBoolean(Keys.FORWARD_URL_VARIABLES); - - this.retryEnabled = config.getBoolean(Keys.FORWARD_RETRY_ENABLE); - this.retryDelay = config.getInteger(Keys.FORWARD_RETRY_DELAY, 100); - this.retryCount = config.getInteger(Keys.FORWARD_RETRY_COUNT, 10); - this.retryLimit = config.getInteger(Keys.FORWARD_RETRY_LIMIT, 100); - - this.deliveryPending = new AtomicInteger(0); - } - - private static String formatSentence(Position position) { - - StringBuilder s = new StringBuilder("$GPRMC,"); - - try (Formatter f = new Formatter(s, Locale.ENGLISH)) { - - Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH); - calendar.setTimeInMillis(position.getFixTime().getTime()); - - f.format("%1$tH%1$tM%1$tS.%1$tL,A,", calendar); - - double lat = position.getLatitude(); - double lon = position.getLongitude(); - - f.format("%02d%07.4f,%c,", (int) Math.abs(lat), Math.abs(lat) % 1 * 60, lat < 0 ? 'S' : 'N'); - f.format("%03d%07.4f,%c,", (int) Math.abs(lon), Math.abs(lon) % 1 * 60, lon < 0 ? 'W' : 'E'); - - f.format("%.2f,%.2f,", position.getSpeed(), position.getCourse()); - f.format("%1$td%1$tm%1$ty,,", calendar); - } - - s.append(Checksum.nmea(s.substring(1))); - - return s.toString(); - } - - // OpenGTS status code - private String calculateStatus(Position position) { - if (position.hasAttribute(Position.KEY_ALARM)) { - return "0xF841"; // STATUS_PANIC_ON - } else if (position.getSpeed() < 1.0) { - return "0xF020"; // STATUS_LOCATION - } else { - return "0xF11C"; // STATUS_MOTION_MOVING - } - } - - public String formatRequest(Position position) throws UnsupportedEncodingException, JsonProcessingException { - - Device device = cacheManager.getObject(Device.class, position.getDeviceId()); - - String request = url - .replace("{name}", URLEncoder.encode(device.getName(), StandardCharsets.UTF_8.name())) - .replace("{uniqueId}", device.getUniqueId()) - .replace("{status}", device.getStatus()) - .replace("{deviceId}", String.valueOf(position.getDeviceId())) - .replace("{protocol}", String.valueOf(position.getProtocol())) - .replace("{deviceTime}", String.valueOf(position.getDeviceTime().getTime())) - .replace("{fixTime}", String.valueOf(position.getFixTime().getTime())) - .replace("{valid}", String.valueOf(position.getValid())) - .replace("{latitude}", String.valueOf(position.getLatitude())) - .replace("{longitude}", String.valueOf(position.getLongitude())) - .replace("{altitude}", String.valueOf(position.getAltitude())) - .replace("{speed}", String.valueOf(position.getSpeed())) - .replace("{course}", String.valueOf(position.getCourse())) - .replace("{accuracy}", String.valueOf(position.getAccuracy())) - .replace("{statusCode}", calculateStatus(position)); - - if (position.getAddress() != null) { - request = request.replace( - "{address}", URLEncoder.encode(position.getAddress(), StandardCharsets.UTF_8.name())); - } - - if (request.contains("{attributes}")) { - String attributes = objectMapper.writeValueAsString(position.getAttributes()); - request = request.replace( - "{attributes}", URLEncoder.encode(attributes, StandardCharsets.UTF_8.name())); - } - - if (request.contains("{gprmc}")) { - request = request.replace("{gprmc}", formatSentence(position)); - } - - if (request.contains("{group}")) { - String deviceGroupName = ""; - if (device.getGroupId() != 0) { - Group group = cacheManager.getObject(Group.class, device.getGroupId()); - if (group != null) { - deviceGroupName = group.getName(); - } - } - - request = request.replace("{group}", URLEncoder.encode(deviceGroupName, StandardCharsets.UTF_8.name())); - } - - return request; - } - - class AsyncRequestAndCallback implements InvocationCallback, TimerTask { - - private int retries = 0; - private Map payload; - private final Invocation.Builder requestBuilder; - private MediaType mediaType = MediaType.APPLICATION_JSON_TYPE; - - AsyncRequestAndCallback(Position position) { - - String formattedUrl; - try { - formattedUrl = json && !urlVariables ? url : formatRequest(position); - } catch (UnsupportedEncodingException | JsonProcessingException e) { - throw new RuntimeException("Forwarding formatting error", e); - } - - requestBuilder = client.target(formattedUrl).request(); - if (header != null && !header.isEmpty()) { - for (String line: header.split("\\r?\\n")) { - String[] values = line.split(":", 2); - String headerName = values[0].trim(); - String headerValue = values[1].trim(); - if (headerName.equals(HttpHeaders.CONTENT_TYPE)) { - mediaType = MediaType.valueOf(headerValue); - } else { - requestBuilder.header(headerName, headerValue); - } - } - } - - if (json) { - payload = prepareJsonPayload(position); - } - - deliveryPending.incrementAndGet(); - } - - private void send() { - LOGGER.debug("Position forwarding initiated"); - if (json) { - try { - Entity entity = Entity.entity(objectMapper.writeValueAsString(payload), mediaType); - requestBuilder.async().post(entity, this); - } catch (JsonProcessingException e) { - throw new RuntimeException("Failed to serialize location to json", e); - } - } else { - requestBuilder.async().get(this); - } - } - - private void retry(Throwable throwable) { - boolean scheduled = false; - try { - if (retryEnabled && deliveryPending.get() <= retryLimit && retries < retryCount) { - schedule(); - scheduled = true; - } - } finally { - int pending = scheduled ? deliveryPending.get() : deliveryPending.decrementAndGet(); - LOGGER.warn("Position forwarding failed: " + pending + " pending", throwable); - } - } - - private void schedule() { - timer.newTimeout(this, retryDelay * (long) Math.pow(2, retries++), TimeUnit.MILLISECONDS); - } - - @Override - public void completed(Response response) { - if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { - deliveryPending.decrementAndGet(); - LOGGER.debug("Position forwarding succeeded"); - } else { - retry(new RuntimeException("Status code 2xx expected")); - } - } - - @Override - public void failed(Throwable throwable) { - retry(throwable); - } - - @Override - public void run(Timeout timeout) { - boolean sent = false; - try { - if (!timeout.isCancelled()) { - send(); - sent = true; - } - } finally { - if (!sent) { - deliveryPending.decrementAndGet(); - } - } - } - - } - - @Override - protected Position handlePosition(Position position) { - - if (url != null) { - AsyncRequestAndCallback request = new AsyncRequestAndCallback(position); - request.send(); - } - - return position; - } - - private Map prepareJsonPayload(Position position) { - - Map data = new HashMap<>(); - Device device = cacheManager.getObject(Device.class, position.getDeviceId()); - - data.put(KEY_POSITION, position); - - if (device != null) { - data.put(KEY_DEVICE, device); - } - - return data; - } - -} diff --git a/src/main/java/org/traccar/config/Keys.java b/src/main/java/org/traccar/config/Keys.java index 1da01518c..b60cd82a0 100644 --- a/src/main/java/org/traccar/config/Keys.java +++ b/src/main/java/org/traccar/config/Keys.java @@ -720,14 +720,6 @@ public final class Keys { "forward.json", List.of(KeyType.CONFIG)); - /** - * Boolean value to enable URL parameters in json mode. For example, {uniqueId} for device identifier, - * {latitude} and {longitude} for coordinates. - */ - public static final ConfigKey FORWARD_URL_VARIABLES = new BooleanConfigKey( - "forward.urlVariables", - List.of(KeyType.CONFIG)); - /** * Position forwarding retrying enable. When enabled, additional attempts are made to deliver positions. If initial * delivery fails, because of an unreachable server or an HTTP response different from '2xx', the software waits @@ -745,7 +737,8 @@ public final class Keys { */ public static final ConfigKey FORWARD_RETRY_DELAY = new IntegerConfigKey( "forward.retry.delay", - List.of(KeyType.CONFIG)); + List.of(KeyType.CONFIG), + 100); /** * Position forwarding retry maximum retries. @@ -753,7 +746,8 @@ public final class Keys { */ public static final ConfigKey FORWARD_RETRY_COUNT = new IntegerConfigKey( "forward.retry.count", - List.of(KeyType.CONFIG)); + List.of(KeyType.CONFIG), + 10); /** * Position forwarding retry pending positions limit. @@ -761,7 +755,8 @@ public final class Keys { */ public static final ConfigKey FORWARD_RETRY_LIMIT = new IntegerConfigKey( "forward.retry.limit", - List.of(KeyType.CONFIG)); + List.of(KeyType.CONFIG), + 100); /** * Events forwarding URL. diff --git a/src/main/java/org/traccar/database/NotificationManager.java b/src/main/java/org/traccar/database/NotificationManager.java index 7c82454b2..1eec7e097 100644 --- a/src/main/java/org/traccar/database/NotificationManager.java +++ b/src/main/java/org/traccar/database/NotificationManager.java @@ -129,7 +129,11 @@ public class NotificationManager { if (event.getMaintenanceId() != 0) { eventData.setMaintenance(cacheManager.getObject(Maintenance.class, event.getMaintenanceId())); } - eventForwarder.forward(eventData); + eventForwarder.forward(eventData, (success, throwable) -> { + if (!success) { + LOGGER.warn("Event forwarding failed", throwable); + } + }); } } diff --git a/src/main/java/org/traccar/forward/EventForwarder.java b/src/main/java/org/traccar/forward/EventForwarder.java index c3ad5efc0..1f991c0b5 100644 --- a/src/main/java/org/traccar/forward/EventForwarder.java +++ b/src/main/java/org/traccar/forward/EventForwarder.java @@ -16,5 +16,5 @@ package org.traccar.forward; public interface EventForwarder { - void forward(EventData eventData); + void forward(EventData eventData, ResultHandler resultHandler); } diff --git a/src/main/java/org/traccar/forward/EventForwarderJson.java b/src/main/java/org/traccar/forward/EventForwarderJson.java index c136fd4e2..7527d568a 100644 --- a/src/main/java/org/traccar/forward/EventForwarderJson.java +++ b/src/main/java/org/traccar/forward/EventForwarderJson.java @@ -15,33 +15,29 @@ */ package org.traccar.forward; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.traccar.config.Config; import org.traccar.config.Keys; -import javax.inject.Inject; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.client.InvocationCallback; +import javax.ws.rs.core.Response; public class EventForwarderJson implements EventForwarder { - private static final Logger LOGGER = LoggerFactory.getLogger(EventForwarderJson.class); - private final String url; private final String header; private final Client client; - @Inject public EventForwarderJson(Config config, Client client) { this.client = client; url = config.getString(Keys.EVENT_FORWARD_URL); header = config.getString(Keys.EVENT_FORWARD_HEADERS); } - public void forward(EventData eventData) { + @Override + public void forward(EventData eventData, ResultHandler resultHandler) { var requestBuilder = client.target(url).request(); if (header != null && !header.isEmpty()) { @@ -51,14 +47,20 @@ public class EventForwarderJson implements EventForwarder { } } - requestBuilder.async().post(Entity.json(eventData), new InvocationCallback<>() { + requestBuilder.async().post(Entity.json(eventData), new InvocationCallback() { @Override - public void completed(Object o) { + public void completed(Response response) { + if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { + resultHandler.onResult(true, null); + } else { + int code = response.getStatusInfo().getStatusCode(); + resultHandler.onResult(false, new RuntimeException("HTTP code " + code)); + } } @Override public void failed(Throwable throwable) { - LOGGER.warn("Event forwarding failed", throwable); + resultHandler.onResult(false, throwable); } }); } diff --git a/src/main/java/org/traccar/forward/PositionData.java b/src/main/java/org/traccar/forward/PositionData.java new file mode 100644 index 000000000..784cf52f5 --- /dev/null +++ b/src/main/java/org/traccar/forward/PositionData.java @@ -0,0 +1,45 @@ +/* + * Copyright 2022 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.forward; + +import com.fasterxml.jackson.annotation.JsonInclude; +import org.traccar.model.Device; +import org.traccar.model.Position; + +@JsonInclude(JsonInclude.Include.NON_NULL) +public class PositionData { + + private Position position; + + public Position getPosition() { + return position; + } + + public void setPosition(Position position) { + this.position = position; + } + + private Device device; + + public Device getDevice() { + return device; + } + + public void setDevice(Device device) { + this.device = device; + } + +} diff --git a/src/main/java/org/traccar/forward/PositionForwarder.java b/src/main/java/org/traccar/forward/PositionForwarder.java new file mode 100644 index 000000000..58bd1dcc7 --- /dev/null +++ b/src/main/java/org/traccar/forward/PositionForwarder.java @@ -0,0 +1,20 @@ +/* + * Copyright 2022 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.forward; + +public interface PositionForwarder { + void forward(PositionData positionData, ResultHandler resultHandler); +} diff --git a/src/main/java/org/traccar/forward/PositionForwarderJson.java b/src/main/java/org/traccar/forward/PositionForwarderJson.java new file mode 100644 index 000000000..27b96308e --- /dev/null +++ b/src/main/java/org/traccar/forward/PositionForwarderJson.java @@ -0,0 +1,86 @@ +/* + * Copyright 2022 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.forward; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.traccar.config.Config; +import org.traccar.config.Keys; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.InvocationCallback; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +public class PositionForwarderJson implements PositionForwarder { + + private final String url; + private final String header; + + private final Client client; + private final ObjectMapper objectMapper; + + public PositionForwarderJson(Config config, Client client, ObjectMapper objectMapper) { + this.client = client; + this.objectMapper = objectMapper; + this.url = config.getString(Keys.FORWARD_URL); + this.header = config.getString(Keys.FORWARD_HEADER); + } + + @Override + public void forward(PositionData positionData, ResultHandler resultHandler) { + var requestBuilder = client.target(url).request(); + + MediaType mediaType = MediaType.APPLICATION_JSON_TYPE; + if (header != null && !header.isEmpty()) { + for (String line: header.split("\\r?\\n")) { + String[] values = line.split(":", 2); + String headerName = values[0].trim(); + String headerValue = values[1].trim(); + if (headerName.equals(HttpHeaders.CONTENT_TYPE)) { + mediaType = MediaType.valueOf(headerValue); + } else { + requestBuilder.header(headerName, headerValue); + } + } + } + + try { + var entity = Entity.entity(objectMapper.writeValueAsString(positionData), mediaType); + requestBuilder.async().post(entity, new InvocationCallback() { + @Override + public void completed(Response response) { + if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { + resultHandler.onResult(true, null); + } else { + int code = response.getStatusInfo().getStatusCode(); + resultHandler.onResult(false, new RuntimeException("HTTP code " + code)); + } + } + + @Override + public void failed(Throwable throwable) { + resultHandler.onResult(false, throwable); + } + }); + } catch (JsonProcessingException e) { + resultHandler.onResult(false, e); + } + } + +} diff --git a/src/main/java/org/traccar/forward/PositionForwarderUrl.java b/src/main/java/org/traccar/forward/PositionForwarderUrl.java new file mode 100644 index 000000000..53cc7ad24 --- /dev/null +++ b/src/main/java/org/traccar/forward/PositionForwarderUrl.java @@ -0,0 +1,166 @@ +/* + * Copyright 2022 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.forward; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.traccar.config.Config; +import org.traccar.config.Keys; +import org.traccar.helper.Checksum; +import org.traccar.model.Device; +import org.traccar.model.Position; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.InvocationCallback; +import javax.ws.rs.core.Response; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Calendar; +import java.util.Formatter; +import java.util.Locale; +import java.util.TimeZone; + +public class PositionForwarderUrl implements PositionForwarder { + + private final String url; + private final String header; + + private final Client client; + private final ObjectMapper objectMapper; + + public PositionForwarderUrl(Config config, Client client, ObjectMapper objectMapper) { + this.client = client; + this.objectMapper = objectMapper; + this.url = config.getString(Keys.FORWARD_URL); + this.header = config.getString(Keys.FORWARD_HEADER); + } + + @Override + public void forward(PositionData positionData, ResultHandler resultHandler) { + try { + String url = formatRequest(positionData); + var requestBuilder = client.target(url).request(); + + if (header != null && !header.isEmpty()) { + for (String line: header.split("\\r?\\n")) { + String[] values = line.split(":", 2); + String headerName = values[0].trim(); + String headerValue = values[1].trim(); + requestBuilder.header(headerName, headerValue); + } + } + + requestBuilder.async().get(new InvocationCallback() { + @Override + public void completed(Response response) { + if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { + resultHandler.onResult(true, null); + } else { + int code = response.getStatusInfo().getStatusCode(); + resultHandler.onResult(false, new RuntimeException("HTTP code " + code)); + } + } + + @Override + public void failed(Throwable throwable) { + resultHandler.onResult(false, throwable); + } + }); + } catch (UnsupportedEncodingException | JsonProcessingException e) { + resultHandler.onResult(false, e); + } + } + + public String formatRequest( + PositionData positionData) throws UnsupportedEncodingException, JsonProcessingException { + + Position position = positionData.getPosition(); + Device device = positionData.getDevice(); + + String request = url + .replace("{name}", URLEncoder.encode(device.getName(), StandardCharsets.UTF_8)) + .replace("{uniqueId}", device.getUniqueId()) + .replace("{status}", device.getStatus()) + .replace("{deviceId}", String.valueOf(position.getDeviceId())) + .replace("{protocol}", String.valueOf(position.getProtocol())) + .replace("{deviceTime}", String.valueOf(position.getDeviceTime().getTime())) + .replace("{fixTime}", String.valueOf(position.getFixTime().getTime())) + .replace("{valid}", String.valueOf(position.getValid())) + .replace("{latitude}", String.valueOf(position.getLatitude())) + .replace("{longitude}", String.valueOf(position.getLongitude())) + .replace("{altitude}", String.valueOf(position.getAltitude())) + .replace("{speed}", String.valueOf(position.getSpeed())) + .replace("{course}", String.valueOf(position.getCourse())) + .replace("{accuracy}", String.valueOf(position.getAccuracy())) + .replace("{statusCode}", calculateStatus(position)); + + if (position.getAddress() != null) { + request = request.replace( + "{address}", URLEncoder.encode(position.getAddress(), StandardCharsets.UTF_8)); + } + + if (request.contains("{attributes}")) { + String attributes = objectMapper.writeValueAsString(position.getAttributes()); + request = request.replace( + "{attributes}", URLEncoder.encode(attributes, StandardCharsets.UTF_8)); + } + + if (request.contains("{gprmc}")) { + request = request.replace("{gprmc}", formatSentence(position)); + } + + return request; + } + + private static String formatSentence(Position position) { + + StringBuilder s = new StringBuilder("$GPRMC,"); + + try (Formatter f = new Formatter(s, Locale.ENGLISH)) { + + Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH); + calendar.setTimeInMillis(position.getFixTime().getTime()); + + f.format("%1$tH%1$tM%1$tS.%1$tL,A,", calendar); + + double lat = position.getLatitude(); + double lon = position.getLongitude(); + + f.format("%02d%07.4f,%c,", (int) Math.abs(lat), Math.abs(lat) % 1 * 60, lat < 0 ? 'S' : 'N'); + f.format("%03d%07.4f,%c,", (int) Math.abs(lon), Math.abs(lon) % 1 * 60, lon < 0 ? 'W' : 'E'); + + f.format("%.2f,%.2f,", position.getSpeed(), position.getCourse()); + f.format("%1$td%1$tm%1$ty,,", calendar); + } + + s.append(Checksum.nmea(s.substring(1))); + + return s.toString(); + } + + // OpenGTS status code + private String calculateStatus(Position position) { + if (position.hasAttribute(Position.KEY_ALARM)) { + return "0xF841"; // STATUS_PANIC_ON + } else if (position.getSpeed() < 1.0) { + return "0xF020"; // STATUS_LOCATION + } else { + return "0xF11C"; // STATUS_MOTION_MOVING + } + } + +} diff --git a/src/main/java/org/traccar/forward/ResultHandler.java b/src/main/java/org/traccar/forward/ResultHandler.java new file mode 100644 index 000000000..009daf495 --- /dev/null +++ b/src/main/java/org/traccar/forward/ResultHandler.java @@ -0,0 +1,20 @@ +/* + * Copyright 2022 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.forward; + +public interface ResultHandler { + void onResult(boolean success, Throwable throwable); +} diff --git a/src/test/java/org/traccar/WebDataHandlerTest.java b/src/test/java/org/traccar/WebDataHandlerTest.java deleted file mode 100644 index 99dbb83fa..000000000 --- a/src/test/java/org/traccar/WebDataHandlerTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.traccar; - -import org.junit.Test; -import org.traccar.config.Config; -import org.traccar.config.Keys; -import org.traccar.model.Device; -import org.traccar.model.Position; -import org.traccar.session.cache.CacheManager; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class WebDataHandlerTest extends ProtocolTest { - - @Test - public void testFormatRequest() throws Exception { - - Config config = new Config(); - config.setString(Keys.FORWARD_URL, "http://localhost/?fixTime={fixTime}&gprmc={gprmc}&name={name}"); - - Position position = position("2016-01-01 01:02:03.000", true, 20, 30); - - var device = mock(Device.class); - when(device.getId()).thenReturn(1L); - when(device.getName()).thenReturn("test"); - when(device.getUniqueId()).thenReturn("123456789012345"); - when(device.getStatus()).thenReturn(Device.STATUS_ONLINE); - var cacheManager = mock(CacheManager.class); - when(cacheManager.getObject(eq(Device.class), anyLong())).thenReturn(device); - - WebDataHandler handler = new WebDataHandler(config, cacheManager, null, null, null); - - assertEquals( - "http://localhost/?fixTime=1451610123000&gprmc=$GPRMC,010203.000,A,2000.0000,N,03000.0000,E,0.00,0.00,010116,,*05&name=test", - handler.formatRequest(position)); - - } - -} diff --git a/src/test/java/org/traccar/forward/PositionForwarderUrlTest.java b/src/test/java/org/traccar/forward/PositionForwarderUrlTest.java new file mode 100644 index 000000000..522958052 --- /dev/null +++ b/src/test/java/org/traccar/forward/PositionForwarderUrlTest.java @@ -0,0 +1,42 @@ +package org.traccar.forward; + +import org.junit.Test; +import org.traccar.ProtocolTest; +import org.traccar.config.Config; +import org.traccar.config.Keys; +import org.traccar.model.Device; +import org.traccar.model.Position; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PositionForwarderUrlTest extends ProtocolTest { + + @Test + public void testFormatRequest() throws Exception { + + Config config = new Config(); + config.setString(Keys.FORWARD_URL, "http://localhost/?fixTime={fixTime}&gprmc={gprmc}&name={name}"); + + Position position = position("2016-01-01 01:02:03.000", true, 20, 30); + + var device = mock(Device.class); + when(device.getId()).thenReturn(1L); + when(device.getName()).thenReturn("test"); + when(device.getUniqueId()).thenReturn("123456789012345"); + when(device.getStatus()).thenReturn(Device.STATUS_ONLINE); + + PositionData positionData = new PositionData(); + positionData.setPosition(position); + positionData.setDevice(device); + + PositionForwarderUrl forwarder = new PositionForwarderUrl(config, null, null); + + assertEquals( + "http://localhost/?fixTime=1451610123000&gprmc=$GPRMC,010203.000,A,2000.0000,N,03000.0000,E,0.00,0.00,010116,,*05&name=test", + forwarder.formatRequest(positionData)); + + } + +} -- cgit v1.2.3