aboutsummaryrefslogtreecommitdiff
path: root/src/org/traccar/database/GeofenceManager.java
blob: 0a07e2cf396c4c12c4a0af8613f5435eb68dd6e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*
 * Copyright 2016 Anton Tananaev (anton.tananaev@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.traccar.database;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.traccar.Context;
import org.traccar.helper.Log;
import org.traccar.model.Device;
import org.traccar.model.Geofence;
import org.traccar.model.GroupGeofence;
import org.traccar.model.Position;
import org.traccar.model.DeviceGeofence;
import org.traccar.model.GeofencePermission;

public class GeofenceManager {

    private final DataManager dataManager;

    private final Map<Long, Geofence> geofences = new HashMap<>();
    private final Map<Long, Set<Long>> userGeofences = new HashMap<>();
    private final Map<Long, Set<Long>> groupGeofences = new HashMap<>();

    private final Map<Long, Set<Long>> deviceGeofencesWithGroups = new HashMap<>();
    private final Map<Long, Set<Long>> deviceGeofences = new HashMap<>();

    private final ReadWriteLock deviceGeofencesLock = new ReentrantReadWriteLock();
    private final ReadWriteLock geofencesLock = new ReentrantReadWriteLock();
    private final ReadWriteLock groupGeofencesLock = new ReentrantReadWriteLock();

    public GeofenceManager(DataManager dataManager) {
        this.dataManager = dataManager;
        refresh();
    }

    public Set<Long> getUserGeofencesIds(long userId) {
        if (!userGeofences.containsKey(userId)) {
            userGeofences.put(userId, new HashSet<Long>());
        }
        return userGeofences.get(userId);
    }

    private Set<Long> getGroupGeofences(long groupId) {
        if (!groupGeofences.containsKey(groupId)) {
            groupGeofences.put(groupId, new HashSet<Long>());
        }
        return groupGeofences.get(groupId);
    }

    public Set<Long> getAllDeviceGeofences(long deviceId) {
        deviceGeofencesLock.readLock().lock();
        try {
            return getDeviceGeofences(deviceGeofencesWithGroups, deviceId);
        } finally {
            deviceGeofencesLock.readLock().unlock();
        }

    }

    public Set<Long> getDeviceGeofences(long deviceId) {
        deviceGeofencesLock.readLock().lock();
        try {
            return getDeviceGeofences(deviceGeofences, deviceId);
        } finally {
            deviceGeofencesLock.readLock().unlock();
        }
    }

    private Set<Long> getDeviceGeofences(Map<Long, Set<Long>> deviceGeofences, long deviceId) {
        if (!deviceGeofences.containsKey(deviceId)) {
            deviceGeofences.put(deviceId, new HashSet<Long>());
        }
        return deviceGeofences.get(deviceId);
    }

    public final void refresh() {
        if (dataManager != null) {
            try {
                geofencesLock.writeLock().lock();
                groupGeofencesLock.writeLock().lock();
                deviceGeofencesLock.writeLock().lock();
                try {
                    geofences.clear();
                    for (Geofence geofence : dataManager.getGeofences()) {
                        geofences.put(geofence.getId(), geofence);
                    }

                    userGeofences.clear();
                    for (GeofencePermission geofencePermission : dataManager.getGeofencePermissions()) {
                        getUserGeofencesIds(geofencePermission.getUserId()).add(geofencePermission.getGeofenceId());
                    }

                    groupGeofences.clear();
                    for (GroupGeofence groupGeofence : dataManager.getGroupGeofences()) {
                        getGroupGeofences(groupGeofence.getGroupId()).add(groupGeofence.getGeofenceId());
                    }

                    deviceGeofences.clear();
                    deviceGeofencesWithGroups.clear();

                    for (DeviceGeofence deviceGeofence : dataManager.getDeviceGeofences()) {
                        getDeviceGeofences(deviceGeofences, deviceGeofence.getDeviceId())
                            .add(deviceGeofence.getGeofenceId());
                        getDeviceGeofences(deviceGeofencesWithGroups, deviceGeofence.getDeviceId())
                            .add(deviceGeofence.getGeofenceId());
                    }

                    for (Device device : dataManager.getAllDevicesCached()) {
                        long groupId = device.getGroupId();
                        while (groupId != 0) {
                            getDeviceGeofences(deviceGeofencesWithGroups,
                                    device.getId()).addAll(getGroupGeofences(groupId));
                            groupId = dataManager.getGroupById(groupId).getGroupId();
                        }
                        List<Long> deviceGeofenceIds = device.getGeofenceIds();
                        if (deviceGeofenceIds == null) {
                            deviceGeofenceIds = new ArrayList<Long>();
                        } else {
                            deviceGeofenceIds.clear();
                        }
                        Position lastPosition = Context.getConnectionManager().getLastPosition(device.getId());
                        if (lastPosition != null) {
                            for (Long geofenceId : deviceGeofencesWithGroups.get(device.getId())) {
                                if (getGeofence(geofenceId).getGeometry()
                                        .containsPoint(lastPosition.getLatitude(), lastPosition.getLongitude())) {
                                    deviceGeofenceIds.add(geofenceId);
                                }
                            }
                        }
                        device.setGeofenceIds(deviceGeofenceIds);
                    }

                } finally {
                    geofencesLock.writeLock().unlock();
                    groupGeofencesLock.writeLock().unlock();
                    deviceGeofencesLock.writeLock().unlock();
                }

            } catch (SQLException error) {
                Log.warning(error);
            }
        }
    }

    public final Collection<Geofence> getAllGeofences() {
        geofencesLock.readLock().lock();
        try {
            return geofences.values();
        } finally {
            geofencesLock.readLock().unlock();
        }
    }

    public final Collection<Geofence> getUserGeofences(long userId) {
        geofencesLock.readLock().lock();
        try {
            Collection<Geofence> result = new LinkedList<>();
            for (Long geofenceId : getUserGeofencesIds(userId)) {
                result.add(getGeofence(geofenceId));
            }
            return result;
        } finally {
            geofencesLock.readLock().unlock();
        }
    }

    public final Geofence getGeofence(Long geofenceId) {
        geofencesLock.readLock().lock();
        try {
            return geofences.get(geofenceId);
        } finally {
            geofencesLock.readLock().unlock();
        }
    }

    public final void updateGeofence(Geofence geofence) {
        geofencesLock.writeLock().lock();
        try {
            geofences.put(geofence.getId(), geofence);
        } finally {
            geofencesLock.writeLock().unlock();
        }
        try {
            dataManager.updateGeofence(geofence);
        } catch (SQLException error) {
            Log.warning(error);
        }
    }

    public boolean checkGeofence(long userId, long geofenceId) {
        return getUserGeofencesIds(userId).contains(geofenceId);
    }

    public List<Long> getCurrentDeviceGeofences(Position position) {
        List<Long> result = new ArrayList<Long>();
        for (Long geofenceId : getAllDeviceGeofences(position.getDeviceId())) {
            if (getGeofence(geofenceId).getGeometry().containsPoint(position.getLatitude(), position.getLongitude())) {
                result.add(geofenceId);
            }
        }
        return result;
    }

}