Search in sources :

Example 6 with StorageException

use of org.traccar.storage.StorageException in project traccar by tananaev.

the class SecurityRequestFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    if (requestContext.getMethod().equals("OPTIONS")) {
        return;
    }
    SecurityContext securityContext = null;
    try {
        String authHeader = requestContext.getHeaderString(AUTHORIZATION_HEADER);
        if (authHeader != null) {
            try {
                String[] auth = decodeBasicAuth(authHeader);
                User user = Context.getPermissionsManager().login(auth[0], auth[1]);
                if (user != null) {
                    Main.getInjector().getInstance(StatisticsManager.class).registerRequest(user.getId());
                    securityContext = new UserSecurityContext(new UserPrincipal(user.getId()));
                }
            } catch (StorageException e) {
                throw new WebApplicationException(e);
            }
        } else if (request.getSession() != null) {
            Long userId = (Long) request.getSession().getAttribute(SessionResource.USER_ID_KEY);
            if (userId != null) {
                Context.getPermissionsManager().checkUserEnabled(userId);
                Main.getInjector().getInstance(StatisticsManager.class).registerRequest(userId);
                securityContext = new UserSecurityContext(new UserPrincipal(userId));
            }
        }
    } catch (SecurityException e) {
        LOGGER.warn("Authentication error", e);
    }
    if (securityContext != null) {
        requestContext.setSecurityContext(securityContext);
    } else {
        Method method = resourceInfo.getResourceMethod();
        if (!method.isAnnotationPresent(PermitAll.class)) {
            Response.ResponseBuilder responseBuilder = Response.status(Response.Status.UNAUTHORIZED);
            if (!XML_HTTP_REQUEST.equals(request.getHeader(X_REQUESTED_WITH))) {
                responseBuilder.header(WWW_AUTHENTICATE, BASIC_REALM);
            }
            throw new WebApplicationException(responseBuilder.build());
        }
    }
}
Also used : User(org.traccar.model.User) WebApplicationException(javax.ws.rs.WebApplicationException) Method(java.lang.reflect.Method) Response(javax.ws.rs.core.Response) StatisticsManager(org.traccar.database.StatisticsManager) SecurityContext(javax.ws.rs.core.SecurityContext) PermitAll(javax.annotation.security.PermitAll) StorageException(org.traccar.storage.StorageException)

Example 7 with StorageException

use of org.traccar.storage.StorageException in project traccar by tananaev.

the class FilterHandler method filter.

private boolean filter(Position position) {
    StringBuilder filterType = new StringBuilder();
    // filter out invalid data
    if (filterInvalid(position)) {
        filterType.append("Invalid ");
    }
    if (filterZero(position)) {
        filterType.append("Zero ");
    }
    if (filterFuture(position)) {
        filterType.append("Future ");
    }
    if (filterAccuracy(position)) {
        filterType.append("Accuracy ");
    }
    if (filterApproximate(position)) {
        filterType.append("Approximate ");
    }
    // filter out excessive data
    long deviceId = position.getDeviceId();
    if (filterDuplicate || filterStatic || filterDistance > 0 || filterMaxSpeed > 0 || filterMinPeriod > 0) {
        Position preceding = null;
        if (filterRelative) {
            try {
                Date newFixTime = position.getFixTime();
                preceding = Context.getDataManager().getPrecedingPosition(deviceId, newFixTime);
            } catch (StorageException e) {
                LOGGER.warn("Error retrieving preceding position; fallbacking to last received position.", e);
                preceding = getLastReceivedPosition(deviceId);
            }
        } else {
            preceding = getLastReceivedPosition(deviceId);
        }
        if (filterDuplicate(position, preceding) && !skipLimit(position, preceding) && !skipAttributes(position)) {
            filterType.append("Duplicate ");
        }
        if (filterStatic(position) && !skipLimit(position, preceding) && !skipAttributes(position)) {
            filterType.append("Static ");
        }
        if (filterDistance(position, preceding) && !skipLimit(position, preceding) && !skipAttributes(position)) {
            filterType.append("Distance ");
        }
        if (filterMaxSpeed(position, preceding)) {
            filterType.append("MaxSpeed ");
        }
        if (filterMinPeriod(position, preceding)) {
            filterType.append("MinPeriod ");
        }
    }
    if (filterType.length() > 0) {
        StringBuilder message = new StringBuilder();
        message.append("Position filtered by ");
        message.append(filterType.toString());
        message.append("filters from device: ");
        message.append(Context.getIdentityManager().getById(deviceId).getUniqueId());
        LOGGER.info(message.toString());
        return true;
    }
    return false;
}
Also used : Position(org.traccar.model.Position) StorageException(org.traccar.storage.StorageException) Date(java.util.Date)

Example 8 with StorageException

use of org.traccar.storage.StorageException in project traccar by tananaev.

the class SimpleObjectManager method refreshUserItems.

public final void refreshUserItems() {
    if (getDataManager() != null) {
        try {
            writeLock();
            userItems = new ConcurrentHashMap<>();
            for (Permission permission : getDataManager().getPermissions(User.class, getBaseClass())) {
                Set<Long> items = userItems.computeIfAbsent(permission.getOwnerId(), key -> new HashSet<>());
                items.add(permission.getPropertyId());
            }
        } catch (StorageException | ClassNotFoundException error) {
            LOGGER.warn("Error getting permissions", error);
        } finally {
            writeUnlock();
        }
    }
}
Also used : Permission(org.traccar.model.Permission) StorageException(org.traccar.storage.StorageException)

Example 9 with StorageException

use of org.traccar.storage.StorageException in project traccar by tananaev.

the class MainEventHandler method channelRead.

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof Position) {
        Position position = (Position) msg;
        try {
            Context.getDeviceManager().updateLatestPosition(position);
        } catch (StorageException error) {
            LOGGER.warn("Failed to update device", error);
        }
        String uniqueId = Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId();
        StringBuilder builder = new StringBuilder();
        builder.append(formatChannel(ctx.channel())).append(" ");
        builder.append("id: ").append(uniqueId);
        for (String attribute : logAttributes) {
            switch(attribute) {
                case "time":
                    builder.append(", time: ").append(DateUtil.formatDate(position.getFixTime(), false));
                    break;
                case "position":
                    builder.append(", lat: ").append(String.format("%.5f", position.getLatitude()));
                    builder.append(", lon: ").append(String.format("%.5f", position.getLongitude()));
                    break;
                case "speed":
                    if (position.getSpeed() > 0) {
                        builder.append(", speed: ").append(String.format("%.1f", position.getSpeed()));
                    }
                    break;
                case "course":
                    builder.append(", course: ").append(String.format("%.1f", position.getCourse()));
                    break;
                case "accuracy":
                    if (position.getAccuracy() > 0) {
                        builder.append(", accuracy: ").append(String.format("%.1f", position.getAccuracy()));
                    }
                    break;
                case "outdated":
                    if (position.getOutdated()) {
                        builder.append(", outdated");
                    }
                    break;
                case "invalid":
                    if (!position.getValid()) {
                        builder.append(", invalid");
                    }
                    break;
                default:
                    Object value = position.getAttributes().get(attribute);
                    if (value != null) {
                        builder.append(", ").append(attribute).append(": ").append(value);
                    }
                    break;
            }
        }
        LOGGER.info(builder.toString());
        Main.getInjector().getInstance(StatisticsManager.class).registerMessageStored(position.getDeviceId(), position.getProtocol());
    }
}
Also used : StatisticsManager(org.traccar.database.StatisticsManager) Position(org.traccar.model.Position) StorageException(org.traccar.storage.StorageException)

Example 10 with StorageException

use of org.traccar.storage.StorageException in project traccar by tananaev.

the class ConnectionManager method updateDevice.

public void updateDevice(final long deviceId, String status, Date time) {
    Device device = Context.getIdentityManager().getById(deviceId);
    if (device == null) {
        return;
    }
    String oldStatus = device.getStatus();
    device.setStatus(status);
    if (!status.equals(oldStatus)) {
        String eventType;
        Map<Event, Position> events = new HashMap<>();
        switch(status) {
            case Device.STATUS_ONLINE:
                eventType = Event.TYPE_DEVICE_ONLINE;
                break;
            case Device.STATUS_UNKNOWN:
                eventType = Event.TYPE_DEVICE_UNKNOWN;
                if (updateDeviceState) {
                    events.putAll(updateDeviceState(deviceId));
                }
                break;
            default:
                eventType = Event.TYPE_DEVICE_OFFLINE;
                if (updateDeviceState) {
                    events.putAll(updateDeviceState(deviceId));
                }
                break;
        }
        events.put(new Event(eventType, deviceId), null);
        Context.getNotificationManager().updateEvents(events);
    }
    Timeout timeout = timeouts.remove(deviceId);
    if (timeout != null) {
        timeout.cancel();
    }
    if (time != null) {
        device.setLastUpdate(time);
    }
    if (status.equals(Device.STATUS_ONLINE)) {
        timeouts.put(deviceId, GlobalTimer.getTimer().newTimeout(timeout1 -> {
            if (!timeout1.isCancelled()) {
                updateDevice(deviceId, Device.STATUS_UNKNOWN, null);
            }
        }, deviceTimeout, TimeUnit.MILLISECONDS));
    }
    try {
        Context.getDeviceManager().updateDeviceStatus(device);
    } catch (StorageException e) {
        LOGGER.warn("Update device status error", e);
    }
    updateDevice(device);
}
Also used : Device(org.traccar.model.Device) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) SocketAddress(java.net.SocketAddress) Event(org.traccar.model.Event) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) HashMap(java.util.HashMap) Channel(io.netty.channel.Channel) Keys(org.traccar.config.Keys) MotionEventHandler(org.traccar.handler.events.MotionEventHandler) HashSet(java.util.HashSet) TimeUnit(java.util.concurrent.TimeUnit) StorageException(org.traccar.storage.StorageException) GlobalTimer(org.traccar.GlobalTimer) Map(java.util.Map) Context(org.traccar.Context) Protocol(org.traccar.Protocol) DeviceState(org.traccar.model.DeviceState) Position(org.traccar.model.Position) Main(org.traccar.Main) OverspeedEventHandler(org.traccar.handler.events.OverspeedEventHandler) Position(org.traccar.model.Position) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Device(org.traccar.model.Device) Timeout(io.netty.util.Timeout) Event(org.traccar.model.Event) StorageException(org.traccar.storage.StorageException)

Aggregations

StorageException (org.traccar.storage.StorageException)10 HashSet (java.util.HashSet)4 Device (org.traccar.model.Device)4 Date (java.util.Date)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Set (java.util.Set)3 Permission (org.traccar.model.Permission)3 Position (org.traccar.model.Position)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 Context (org.traccar.Context)2 StatisticsManager (org.traccar.database.StatisticsManager)2 Group (org.traccar.model.Group)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 Channel (io.netty.channel.Channel)1 Timeout (io.netty.util.Timeout)1 Method (java.lang.reflect.Method)1 SocketAddress (java.net.SocketAddress)1