From d365fa63940976ec53c3b94842c3fa6ad45af242 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Mon, 24 Jun 2024 06:28:03 -0700 Subject: Fix cache removal (fix #5356) --- src/main/java/org/traccar/session/cache/CacheManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/main/java/org/traccar/session/cache/CacheManager.java') diff --git a/src/main/java/org/traccar/session/cache/CacheManager.java b/src/main/java/org/traccar/session/cache/CacheManager.java index 064e5672f..f7458567c 100644 --- a/src/main/java/org/traccar/session/cache/CacheManager.java +++ b/src/main/java/org/traccar/session/cache/CacheManager.java @@ -170,7 +170,7 @@ public class CacheManager implements BroadcastInterface { public void removeDevice(long deviceId) { try { lock.writeLock().lock(); - if (deviceReferences.computeIfAbsent(deviceId, k -> new AtomicInteger()).incrementAndGet() <= 0) { + if (deviceReferences.computeIfAbsent(deviceId, k -> new AtomicInteger()).decrementAndGet() <= 0) { graph.removeObject(Device.class, deviceId); devicePositions.remove(deviceId); deviceReferences.remove(deviceId); -- cgit v1.2.3 From b8390005722dd1cdb24d762797ef3f98ebc37755 Mon Sep 17 00:00:00 2001 From: Anton Tananaev Date: Sat, 6 Jul 2024 17:46:17 -0700 Subject: Update instanceof expressions --- .../java/org/traccar/BaseMqttProtocolDecoder.java | 12 ++--- src/main/java/org/traccar/BasePipelineFactory.java | 16 +++---- src/main/java/org/traccar/BaseProtocolDecoder.java | 4 +- src/main/java/org/traccar/BaseProtocolEncoder.java | 6 +-- .../java/org/traccar/ExtendedObjectDecoder.java | 13 +++--- src/main/java/org/traccar/ProcessingHandler.java | 4 +- .../java/org/traccar/WrapperInboundHandler.java | 4 +- .../java/org/traccar/WrapperOutboundHandler.java | 3 +- .../java/org/traccar/api/BaseObjectResource.java | 9 ++-- .../java/org/traccar/api/ResourceErrorHandler.java | 3 +- .../traccar/api/security/PermissionsService.java | 9 ++-- .../handler/network/AcknowledgementHandler.java | 6 +-- .../handler/network/NetworkMessageHandler.java | 6 +-- .../handler/network/RemoteAddressHandler.java | 3 +- .../handler/network/StandardLoggingHandler.java | 6 +-- .../org/traccar/helper/model/AttributeUtil.java | 16 +++---- src/main/java/org/traccar/model/ExtendedModel.java | 16 +++---- .../traccar/notification/PropertiesProvider.java | 4 +- .../traccar/protocol/FlespiProtocolDecoder.java | 14 +++--- .../traccar/protocol/Gl200TextProtocolDecoder.java | 4 +- .../traccar/protocol/OutsafeProtocolDecoder.java | 8 ++-- .../org/traccar/protocol/T55ProtocolDecoder.java | 5 +-- .../org/traccar/session/cache/CacheManager.java | 8 ++-- .../java/org/traccar/storage/DatabaseStorage.java | 30 +++++-------- .../java/org/traccar/storage/MemoryStorage.java | 34 +++++---------- .../java/org/traccar/storage/QueryBuilder.java | 24 +++++----- src/test/java/org/traccar/ProtocolTest.java | 51 +++++++++++----------- 27 files changed, 135 insertions(+), 183 deletions(-) (limited to 'src/main/java/org/traccar/session/cache/CacheManager.java') diff --git a/src/main/java/org/traccar/BaseMqttProtocolDecoder.java b/src/main/java/org/traccar/BaseMqttProtocolDecoder.java index 0388563f5..5a55eee74 100644 --- a/src/main/java/org/traccar/BaseMqttProtocolDecoder.java +++ b/src/main/java/org/traccar/BaseMqttProtocolDecoder.java @@ -38,9 +38,7 @@ public abstract class BaseMqttProtocolDecoder extends BaseProtocolDecoder { protected final Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { - if (msg instanceof MqttConnectMessage) { - - MqttConnectMessage message = (MqttConnectMessage) msg; + if (msg instanceof MqttConnectMessage message) { DeviceSession deviceSession = getDeviceSession( channel, remoteAddress, message.payload().clientIdentifier()); @@ -55,9 +53,7 @@ public abstract class BaseMqttProtocolDecoder extends BaseProtocolDecoder { channel.writeAndFlush(new NetworkMessage(response, remoteAddress)); } - } else if (msg instanceof MqttSubscribeMessage) { - - MqttSubscribeMessage message = (MqttSubscribeMessage) msg; + } else if (msg instanceof MqttSubscribeMessage message) { MqttMessage response = MqttMessageBuilders.subAck() .packetId(message.variableHeader().messageId()) @@ -67,15 +63,13 @@ public abstract class BaseMqttProtocolDecoder extends BaseProtocolDecoder { channel.writeAndFlush(new NetworkMessage(response, remoteAddress)); } - } else if (msg instanceof MqttPublishMessage) { + } else if (msg instanceof MqttPublishMessage message) { DeviceSession deviceSession = getDeviceSession(channel, remoteAddress); if (deviceSession == null) { return null; } - MqttPublishMessage message = (MqttPublishMessage) msg; - Object result = decode(deviceSession, message); MqttMessage response = MqttMessageBuilders.pubAck() diff --git a/src/main/java/org/traccar/BasePipelineFactory.java b/src/main/java/org/traccar/BasePipelineFactory.java index 40360cca7..92b9759c1 100644 --- a/src/main/java/org/traccar/BasePipelineFactory.java +++ b/src/main/java/org/traccar/BasePipelineFactory.java @@ -64,10 +64,10 @@ public abstract class BasePipelineFactory extends ChannelInitializer { public static T getHandler(ChannelPipeline pipeline, Class clazz) { for (Map.Entry handlerEntry : pipeline) { ChannelHandler handler = handlerEntry.getValue(); - if (handler instanceof WrapperInboundHandler) { - handler = ((WrapperInboundHandler) handler).getWrappedHandler(); - } else if (handler instanceof WrapperOutboundHandler) { - handler = ((WrapperOutboundHandler) handler).getWrappedHandler(); + if (handler instanceof WrapperInboundHandler wrapperHandler) { + handler = wrapperHandler.getWrappedHandler(); + } else if (handler instanceof WrapperOutboundHandler wrapperHandler) { + handler = wrapperHandler.getWrappedHandler(); } if (clazz.isAssignableFrom(handler.getClass())) { return (T) handler; @@ -106,10 +106,10 @@ public abstract class BasePipelineFactory extends ChannelInitializer { if (handler instanceof BaseProtocolDecoder || handler instanceof BaseProtocolEncoder) { injectMembers(handler); } else { - if (handler instanceof ChannelInboundHandler) { - handler = new WrapperInboundHandler((ChannelInboundHandler) handler); - } else { - handler = new WrapperOutboundHandler((ChannelOutboundHandler) handler); + if (handler instanceof ChannelInboundHandler channelHandler) { + handler = new WrapperInboundHandler(channelHandler); + } else if (handler instanceof ChannelOutboundHandler channelHandler) { + handler = new WrapperOutboundHandler(channelHandler); } } pipeline.addLast(handler); diff --git a/src/main/java/org/traccar/BaseProtocolDecoder.java b/src/main/java/org/traccar/BaseProtocolDecoder.java index b764e5cdf..2f9c75ec2 100644 --- a/src/main/java/org/traccar/BaseProtocolDecoder.java +++ b/src/main/java/org/traccar/BaseProtocolDecoder.java @@ -168,8 +168,8 @@ public abstract class BaseProtocolDecoder extends ExtendedObjectDecoder { } Set deviceIds = new HashSet<>(); if (decodedMessage != null) { - if (decodedMessage instanceof Position) { - deviceIds.add(((Position) decodedMessage).getDeviceId()); + if (decodedMessage instanceof Position position) { + deviceIds.add(position.getDeviceId()); } else if (decodedMessage instanceof Collection) { Collection positions = (Collection) decodedMessage; for (Position position : positions) { diff --git a/src/main/java/org/traccar/BaseProtocolEncoder.java b/src/main/java/org/traccar/BaseProtocolEncoder.java index e357c27dc..2724a59b1 100644 --- a/src/main/java/org/traccar/BaseProtocolEncoder.java +++ b/src/main/java/org/traccar/BaseProtocolEncoder.java @@ -82,11 +82,9 @@ public abstract class BaseProtocolEncoder extends ChannelOutboundHandlerAdapter @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { - if (msg instanceof NetworkMessage) { - NetworkMessage networkMessage = (NetworkMessage) msg; - if (networkMessage.getMessage() instanceof Command) { + if (msg instanceof NetworkMessage networkMessage) { + if (networkMessage.getMessage() instanceof Command command) { - Command command = (Command) networkMessage.getMessage(); Object encodedCommand = encodeCommand(ctx.channel(), command); StringBuilder s = new StringBuilder(); diff --git a/src/main/java/org/traccar/ExtendedObjectDecoder.java b/src/main/java/org/traccar/ExtendedObjectDecoder.java index 9468e2fff..8d693c7cf 100644 --- a/src/main/java/org/traccar/ExtendedObjectDecoder.java +++ b/src/main/java/org/traccar/ExtendedObjectDecoder.java @@ -54,14 +54,12 @@ public abstract class ExtendedObjectDecoder extends ChannelInboundHandlerAdapter } private void saveOriginal(Object decodedMessage, Object originalMessage) { - if (getConfig().getBoolean(Keys.DATABASE_SAVE_ORIGINAL) && decodedMessage instanceof Position) { - Position position = (Position) decodedMessage; - if (originalMessage instanceof ByteBuf) { - ByteBuf buf = (ByteBuf) originalMessage; + if (getConfig().getBoolean(Keys.DATABASE_SAVE_ORIGINAL) && decodedMessage instanceof Position position) { + if (originalMessage instanceof ByteBuf buf) { position.set(Position.KEY_ORIGINAL, ByteBufUtil.hexDump(buf, 0, buf.writerIndex())); - } else if (originalMessage instanceof String) { + } else if (originalMessage instanceof String stringMessage) { position.set(Position.KEY_ORIGINAL, DataConverter.printHex( - ((String) originalMessage).getBytes(StandardCharsets.US_ASCII))); + stringMessage.getBytes(StandardCharsets.US_ASCII))); } } } @@ -78,8 +76,7 @@ public abstract class ExtendedObjectDecoder extends ChannelInboundHandlerAdapter decodedMessage = handleEmptyMessage(ctx.channel(), networkMessage.getRemoteAddress(), originalMessage); } if (decodedMessage != null) { - if (decodedMessage instanceof Collection) { - var collection = (Collection) decodedMessage; + if (decodedMessage instanceof Collection collection) { ctx.writeAndFlush(new AcknowledgementHandler.EventDecoded(collection)); for (Object o : collection) { saveOriginal(o, originalMessage); diff --git a/src/main/java/org/traccar/ProcessingHandler.java b/src/main/java/org/traccar/ProcessingHandler.java index bb040bfff..76442d402 100644 --- a/src/main/java/org/traccar/ProcessingHandler.java +++ b/src/main/java/org/traccar/ProcessingHandler.java @@ -131,8 +131,8 @@ public class ProcessingHandler extends ChannelInboundHandlerAdapter implements B @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - if (msg instanceof Position) { - bufferingManager.accept(ctx, (Position) msg); + if (msg instanceof Position position) { + bufferingManager.accept(ctx, position); } else { super.channelRead(ctx, msg); } diff --git a/src/main/java/org/traccar/WrapperInboundHandler.java b/src/main/java/org/traccar/WrapperInboundHandler.java index 5e2b1d304..7acca9c50 100644 --- a/src/main/java/org/traccar/WrapperInboundHandler.java +++ b/src/main/java/org/traccar/WrapperInboundHandler.java @@ -52,8 +52,7 @@ public class WrapperInboundHandler implements ChannelInboundHandler { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - if (msg instanceof NetworkMessage) { - NetworkMessage nm = (NetworkMessage) msg; + if (msg instanceof NetworkMessage nm) { handler.channelRead(new WrapperContext(ctx, nm.getRemoteAddress()), nm.getMessage()); } else { handler.channelRead(ctx, msg); @@ -85,7 +84,6 @@ public class WrapperInboundHandler implements ChannelInboundHandler { handler.handlerRemoved(ctx); } - @SuppressWarnings("deprecation") @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { handler.exceptionCaught(ctx, cause); diff --git a/src/main/java/org/traccar/WrapperOutboundHandler.java b/src/main/java/org/traccar/WrapperOutboundHandler.java index ae2b06ad2..8b9c01405 100644 --- a/src/main/java/org/traccar/WrapperOutboundHandler.java +++ b/src/main/java/org/traccar/WrapperOutboundHandler.java @@ -67,8 +67,7 @@ public class WrapperOutboundHandler implements ChannelOutboundHandler { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { - if (msg instanceof NetworkMessage) { - NetworkMessage nm = (NetworkMessage) msg; + if (msg instanceof NetworkMessage nm) { handler.write(new WrapperContext(ctx, nm.getRemoteAddress()), nm.getMessage(), promise); } else { handler.write(ctx, msg, promise); diff --git a/src/main/java/org/traccar/api/BaseObjectResource.java b/src/main/java/org/traccar/api/BaseObjectResource.java index 3c97dd1f8..e35850e1f 100644 --- a/src/main/java/org/traccar/api/BaseObjectResource.java +++ b/src/main/java/org/traccar/api/BaseObjectResource.java @@ -89,15 +89,13 @@ public abstract class BaseObjectResource extends BaseResour permissionsService.checkPermission(baseClass, getUserId(), entity.getId()); boolean skipReadonly = false; - if (entity instanceof User) { - User after = (User) entity; + if (entity instanceof User after) { User before = storage.getObject(User.class, new Request( new Columns.All(), new Condition.Equals("id", entity.getId()))); permissionsService.checkUserUpdate(getUserId(), before, (User) entity); skipReadonly = permissionsService.getUser(getUserId()) .compare(after, "notificationTokens", "termsAccepted"); - } else if (entity instanceof Group) { - Group group = (Group) entity; + } else if (entity instanceof Group group) { if (group.getId() == group.getGroupId()) { throw new IllegalArgumentException("Cycle in group hierarchy"); } @@ -108,8 +106,7 @@ public abstract class BaseObjectResource extends BaseResour storage.updateObject(entity, new Request( new Columns.Exclude("id"), new Condition.Equals("id", entity.getId()))); - if (entity instanceof User) { - User user = (User) entity; + if (entity instanceof User user) { if (user.getHashedPassword() != null) { storage.updateObject(entity, new Request( new Columns.Include("hashedPassword", "salt"), diff --git a/src/main/java/org/traccar/api/ResourceErrorHandler.java b/src/main/java/org/traccar/api/ResourceErrorHandler.java index 387f3db6a..5f5e70632 100644 --- a/src/main/java/org/traccar/api/ResourceErrorHandler.java +++ b/src/main/java/org/traccar/api/ResourceErrorHandler.java @@ -25,8 +25,7 @@ public class ResourceErrorHandler implements ExceptionMapper { @Override public Response toResponse(Exception e) { - if (e instanceof WebApplicationException) { - WebApplicationException webException = (WebApplicationException) e; + if (e instanceof WebApplicationException webException) { return Response.fromResponse(webException.getResponse()).entity(Log.exceptionStack(webException)).build(); } else { return Response.status(Response.Status.BAD_REQUEST).entity(Log.exceptionStack(e)).build(); diff --git a/src/main/java/org/traccar/api/security/PermissionsService.java b/src/main/java/org/traccar/api/security/PermissionsService.java index d4a6fba1a..721793c2f 100644 --- a/src/main/java/org/traccar/api/security/PermissionsService.java +++ b/src/main/java/org/traccar/api/security/PermissionsService.java @@ -128,8 +128,7 @@ public class PermissionsService { throws StorageException, SecurityException { if (!getUser(userId).getAdministrator()) { checkEdit(userId, object.getClass(), addition, skipReadonly); - if (object instanceof GroupedModel) { - GroupedModel after = ((GroupedModel) object); + if (object instanceof GroupedModel after) { if (after.getGroupId() > 0) { GroupedModel before = null; if (!addition) { @@ -141,8 +140,7 @@ public class PermissionsService { } } } - if (object instanceof Schedulable) { - Schedulable after = ((Schedulable) object); + if (object instanceof Schedulable after) { if (after.getCalendarId() > 0) { Schedulable before = null; if (!addition) { @@ -154,8 +152,7 @@ public class PermissionsService { } } } - if (object instanceof Notification) { - Notification after = ((Notification) object); + if (object instanceof Notification after) { if (after.getCommandId() > 0) { Notification before = null; if (!addition) { diff --git a/src/main/java/org/traccar/handler/network/AcknowledgementHandler.java b/src/main/java/org/traccar/handler/network/AcknowledgementHandler.java index e87f5d34c..7ba625e00 100644 --- a/src/main/java/org/traccar/handler/network/AcknowledgementHandler.java +++ b/src/main/java/org/traccar/handler/network/AcknowledgementHandler.java @@ -92,12 +92,10 @@ public class AcknowledgementHandler extends ChannelOutboundHandlerAdapter { if (queue == null) { queue = new LinkedList<>(); } - } else if (msg instanceof EventDecoded) { - EventDecoded event = (EventDecoded) msg; + } else if (msg instanceof EventDecoded event) { LOGGER.debug("Event decoded {}", event.getObjects().size()); waiting.addAll(event.getObjects()); - } else if (msg instanceof EventHandled) { - EventHandled event = (EventHandled) msg; + } else if (msg instanceof EventHandled event) { LOGGER.debug("Event handled"); waiting.remove(event.getObject()); } diff --git a/src/main/java/org/traccar/handler/network/NetworkMessageHandler.java b/src/main/java/org/traccar/handler/network/NetworkMessageHandler.java index c2fb9016a..f151c91a9 100644 --- a/src/main/java/org/traccar/handler/network/NetworkMessageHandler.java +++ b/src/main/java/org/traccar/handler/network/NetworkMessageHandler.java @@ -32,16 +32,14 @@ public class NetworkMessageHandler extends ChannelDuplexHandler { if (ctx.channel() instanceof DatagramChannel) { DatagramPacket packet = (DatagramPacket) msg; ctx.fireChannelRead(new NetworkMessage(packet.content(), packet.sender())); - } else if (msg instanceof ByteBuf) { - ByteBuf buffer = (ByteBuf) msg; + } else if (msg instanceof ByteBuf buffer) { ctx.fireChannelRead(new NetworkMessage(buffer, ctx.channel().remoteAddress())); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { - if (msg instanceof NetworkMessage) { - NetworkMessage message = (NetworkMessage) msg; + if (msg instanceof NetworkMessage message) { if (ctx.channel() instanceof DatagramChannel) { InetSocketAddress recipient = (InetSocketAddress) message.getRemoteAddress(); InetSocketAddress sender = (InetSocketAddress) ctx.channel().localAddress(); diff --git a/src/main/java/org/traccar/handler/network/RemoteAddressHandler.java b/src/main/java/org/traccar/handler/network/RemoteAddressHandler.java index c52bb2be1..9d5504ce1 100644 --- a/src/main/java/org/traccar/handler/network/RemoteAddressHandler.java +++ b/src/main/java/org/traccar/handler/network/RemoteAddressHandler.java @@ -44,8 +44,7 @@ public class RemoteAddressHandler extends ChannelInboundHandlerAdapter { InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress(); String hostAddress = remoteAddress != null ? remoteAddress.getAddress().getHostAddress() : null; - if (msg instanceof Position) { - Position position = (Position) msg; + if (msg instanceof Position position) { position.set(Position.KEY_IP, hostAddress); } } diff --git a/src/main/java/org/traccar/handler/network/StandardLoggingHandler.java b/src/main/java/org/traccar/handler/network/StandardLoggingHandler.java index f6ee08756..8e63cae4d 100644 --- a/src/main/java/org/traccar/handler/network/StandardLoggingHandler.java +++ b/src/main/java/org/traccar/handler/network/StandardLoggingHandler.java @@ -72,12 +72,10 @@ public class StandardLoggingHandler extends ChannelDuplexHandler { } private LogRecord createLogRecord(ChannelHandlerContext ctx, Object msg) { - if (msg instanceof NetworkMessage) { - NetworkMessage networkMessage = (NetworkMessage) msg; - if (networkMessage.getMessage() instanceof ByteBuf) { + if (msg instanceof NetworkMessage networkMessage) { + if (networkMessage.getMessage() instanceof ByteBuf data) { LogRecord record = new LogRecord(ctx.channel().localAddress(), networkMessage.getRemoteAddress()); record.setProtocol(protocol); - ByteBuf data = (ByteBuf) networkMessage.getMessage(); if (decodeTextData && BufferUtil.isPrintable(data, data.readableBytes())) { record.setData(data.getCharSequence( data.readerIndex(), data.readableBytes(), StandardCharsets.US_ASCII).toString() diff --git a/src/main/java/org/traccar/helper/model/AttributeUtil.java b/src/main/java/org/traccar/helper/model/AttributeUtil.java index 2630f64f0..0e3d91766 100644 --- a/src/main/java/org/traccar/helper/model/AttributeUtil.java +++ b/src/main/java/org/traccar/helper/model/AttributeUtil.java @@ -70,20 +70,20 @@ public final class AttributeUtil { if (result != null) { Class valueClass = key.getValueClass(); if (valueClass.equals(Boolean.class)) { - return (T) (result instanceof String - ? Boolean.parseBoolean((String) result) + return (T) (result instanceof String stringResult + ? Boolean.parseBoolean(stringResult) : result); } else if (valueClass.equals(Integer.class)) { - return (T) (Object) (result instanceof String - ? Integer.parseInt((String) result) + return (T) (Object) (result instanceof String stringResult + ? Integer.parseInt(stringResult) : ((Number) result).intValue()); } else if (valueClass.equals(Long.class)) { - return (T) (Object) (result instanceof String - ? Long.parseLong((String) result) + return (T) (Object) (result instanceof String stringResult + ? Long.parseLong(stringResult) : ((Number) result).longValue()); } else if (valueClass.equals(Double.class)) { - return (T) (Object) (result instanceof String - ? Double.parseDouble((String) result) + return (T) (Object) (result instanceof String stringResult + ? Double.parseDouble(stringResult) : ((Number) result).doubleValue()); } else { return (T) result; diff --git a/src/main/java/org/traccar/model/ExtendedModel.java b/src/main/java/org/traccar/model/ExtendedModel.java index d5cd094da..f1183e11a 100644 --- a/src/main/java/org/traccar/model/ExtendedModel.java +++ b/src/main/java/org/traccar/model/ExtendedModel.java @@ -105,8 +105,8 @@ public class ExtendedModel extends BaseModel { public double getDouble(String key) { if (attributes.containsKey(key)) { Object value = attributes.get(key); - if (value instanceof Number) { - return ((Number) attributes.get(key)).doubleValue(); + if (value instanceof Number numberValue) { + return numberValue.doubleValue(); } else { return Double.parseDouble(value.toString()); } @@ -118,8 +118,8 @@ public class ExtendedModel extends BaseModel { public boolean getBoolean(String key) { if (attributes.containsKey(key)) { Object value = attributes.get(key); - if (value instanceof Boolean) { - return (Boolean) attributes.get(key); + if (value instanceof Boolean booleanValue) { + return booleanValue; } else { return Boolean.parseBoolean(value.toString()); } @@ -131,8 +131,8 @@ public class ExtendedModel extends BaseModel { public int getInteger(String key) { if (attributes.containsKey(key)) { Object value = attributes.get(key); - if (value instanceof Number) { - return ((Number) attributes.get(key)).intValue(); + if (value instanceof Number numberValue) { + return numberValue.intValue(); } else { return Integer.parseInt(value.toString()); } @@ -144,8 +144,8 @@ public class ExtendedModel extends BaseModel { public long getLong(String key) { if (attributes.containsKey(key)) { Object value = attributes.get(key); - if (value instanceof Number) { - return ((Number) attributes.get(key)).longValue(); + if (value instanceof Number numberValue) { + return numberValue.longValue(); } else { return Long.parseLong(value.toString()); } diff --git a/src/main/java/org/traccar/notification/PropertiesProvider.java b/src/main/java/org/traccar/notification/PropertiesProvider.java index 91887b5d4..5178b9a9e 100644 --- a/src/main/java/org/traccar/notification/PropertiesProvider.java +++ b/src/main/java/org/traccar/notification/PropertiesProvider.java @@ -48,7 +48,7 @@ public class PropertiesProvider { } else { Object result = extendedModel.getAttributes().get(key.getKey()); if (result != null) { - return result instanceof String ? Integer.parseInt((String) result) : (Integer) result; + return result instanceof String stringResult ? Integer.parseInt(stringResult) : (Integer) result; } else { return key.getDefaultValue(); } @@ -65,7 +65,7 @@ public class PropertiesProvider { } else { Object result = extendedModel.getAttributes().get(key.getKey()); if (result != null) { - return result instanceof String ? Boolean.valueOf((String) result) : (Boolean) result; + return result instanceof String stringResult ? Boolean.valueOf(stringResult) : (Boolean) result; } else { return null; } diff --git a/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java b/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java index ea076afd8..168b3b3cd 100644 --- a/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/FlespiProtocolDecoder.java @@ -247,15 +247,15 @@ public class FlespiProtocolDecoder extends BaseHttpProtocolDecoder { } private void decodeUnknownParam(String name, JsonValue value, Position position) { - if (value instanceof JsonNumber) { - if (((JsonNumber) value).isIntegral()) { - position.set(name, ((JsonNumber) value).longValue()); + if (value instanceof JsonNumber jsonNumber) { + if (jsonNumber.isIntegral()) { + position.set(name, jsonNumber.longValue()); } else { - position.set(name, ((JsonNumber) value).doubleValue()); + position.set(name, jsonNumber.doubleValue()); } - position.set(name, ((JsonNumber) value).doubleValue()); - } else if (value instanceof JsonString) { - position.set(name, ((JsonString) value).getString()); + position.set(name, jsonNumber.doubleValue()); + } else if (value instanceof JsonString jsonString) { + position.set(name, jsonString.getString()); } else if (value == JsonValue.TRUE || value == JsonValue.FALSE) { position.set(name, value == JsonValue.TRUE); } diff --git a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java index 3afea3b1b..373e1c91c 100644 --- a/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/Gl200TextProtocolDecoder.java @@ -1729,8 +1729,8 @@ public class Gl200TextProtocolDecoder extends BaseProtocolDecoder { } if (result != null) { - if (result instanceof Position) { - ((Position) result).set(Position.KEY_TYPE, type); + if (result instanceof Position position) { + position.set(Position.KEY_TYPE, type); } else { for (Position p : (List) result) { p.set(Position.KEY_TYPE, type); diff --git a/src/main/java/org/traccar/protocol/OutsafeProtocolDecoder.java b/src/main/java/org/traccar/protocol/OutsafeProtocolDecoder.java index f71778412..0a6026d91 100644 --- a/src/main/java/org/traccar/protocol/OutsafeProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/OutsafeProtocolDecoder.java @@ -77,10 +77,10 @@ public class OutsafeProtocolDecoder extends BaseHttpProtocolDecoder { } private void decodeUnknownParam(String name, JsonValue value, Position position) { - if (value instanceof JsonNumber) { - position.set(name, ((JsonNumber) value).doubleValue()); - } else if (value instanceof JsonString) { - position.set(name, ((JsonString) value).getString()); + if (value instanceof JsonNumber jsonNumber) { + position.set(name, jsonNumber.doubleValue()); + } else if (value instanceof JsonString jsonString) { + position.set(name, jsonString.getString()); } else if (value == JsonValue.TRUE || value == JsonValue.FALSE) { position.set(name, value == JsonValue.TRUE); } diff --git a/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java b/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java index 9e7518ce5..2538c914d 100644 --- a/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java +++ b/src/main/java/org/traccar/protocol/T55ProtocolDecoder.java @@ -420,9 +420,8 @@ public class T55ProtocolDecoder extends BaseProtocolDecoder { sentence = sentence.substring(index); } else { deviceSession = getDeviceSession(channel, remoteAddress); - if (deviceSession == null && remoteAddress instanceof InetSocketAddress) { - String host = ((InetSocketAddress) remoteAddress).getHostString(); - deviceSession = getDeviceSession(channel, remoteAddress, host); + if (deviceSession == null && remoteAddress instanceof InetSocketAddress inetSocketAddress) { + deviceSession = getDeviceSession(channel, remoteAddress, inetSocketAddress.getHostString()); } } diff --git a/src/main/java/org/traccar/session/cache/CacheManager.java b/src/main/java/org/traccar/session/cache/CacheManager.java index f7458567c..39546a5a7 100644 --- a/src/main/java/org/traccar/session/cache/CacheManager.java +++ b/src/main/java/org/traccar/session/cache/CacheManager.java @@ -296,8 +296,8 @@ public class CacheManager implements BroadcastInterface { } } } else { - if (object instanceof GroupedModel) { - long groupId = ((GroupedModel) object).getGroupId(); + if (object instanceof GroupedModel groupedModel) { + long groupId = groupedModel.getGroupId(); if (groupId > 0) { invalidatePermission(object.getClass(), object.getId(), Group.class, groupId, true); } @@ -319,8 +319,8 @@ public class CacheManager implements BroadcastInterface { } } - if (object instanceof Schedulable) { - long calendarId = ((Schedulable) object).getCalendarId(); + if (object instanceof Schedulable schedulable) { + long calendarId = schedulable.getCalendarId(); if (calendarId > 0) { invalidatePermission(object.getClass(), object.getId(), Calendar.class, calendarId, true); } diff --git a/src/main/java/org/traccar/storage/DatabaseStorage.java b/src/main/java/org/traccar/storage/DatabaseStorage.java index d20429319..1ff043e77 100644 --- a/src/main/java/org/traccar/storage/DatabaseStorage.java +++ b/src/main/java/org/traccar/storage/DatabaseStorage.java @@ -206,28 +206,23 @@ public class DatabaseStorage extends Storage { private Map getConditionVariables(Condition genericCondition) { Map results = new HashMap<>(); - if (genericCondition instanceof Condition.Compare) { - var condition = (Condition.Compare) genericCondition; + if (genericCondition instanceof Condition.Compare condition) { if (condition.getValue() != null) { results.put(condition.getVariable(), condition.getValue()); } - } else if (genericCondition instanceof Condition.Between) { - var condition = (Condition.Between) genericCondition; + } else if (genericCondition instanceof Condition.Between condition) { results.put(condition.getFromVariable(), condition.getFromValue()); results.put(condition.getToVariable(), condition.getToValue()); - } else if (genericCondition instanceof Condition.Binary) { - var condition = (Condition.Binary) genericCondition; + } else if (genericCondition instanceof Condition.Binary condition) { results.putAll(getConditionVariables(condition.getFirst())); results.putAll(getConditionVariables(condition.getSecond())); - } else if (genericCondition instanceof Condition.Permission) { - var condition = (Condition.Permission) genericCondition; + } else if (genericCondition instanceof Condition.Permission condition) { if (condition.getOwnerId() > 0) { results.put(Permission.getKey(condition.getOwnerClass()), condition.getOwnerId()); } else { results.put(Permission.getKey(condition.getPropertyClass()), condition.getPropertyId()); } - } else if (genericCondition instanceof Condition.LatestPositions) { - var condition = (Condition.LatestPositions) genericCondition; + } else if (genericCondition instanceof Condition.LatestPositions condition) { if (condition.getDeviceId() > 0) { results.put("deviceId", condition.getDeviceId()); } @@ -249,43 +244,38 @@ public class DatabaseStorage extends Storage { if (appendWhere) { result.append(" WHERE "); } - if (genericCondition instanceof Condition.Compare) { + if (genericCondition instanceof Condition.Compare condition) { - var condition = (Condition.Compare) genericCondition; result.append(condition.getColumn()); result.append(" "); result.append(condition.getOperator()); result.append(" :"); result.append(condition.getVariable()); - } else if (genericCondition instanceof Condition.Between) { + } else if (genericCondition instanceof Condition.Between condition) { - var condition = (Condition.Between) genericCondition; result.append(condition.getColumn()); result.append(" BETWEEN :"); result.append(condition.getFromVariable()); result.append(" AND :"); result.append(condition.getToVariable()); - } else if (genericCondition instanceof Condition.Binary) { + } else if (genericCondition instanceof Condition.Binary condition) { - var condition = (Condition.Binary) genericCondition; result.append(formatCondition(condition.getFirst(), false)); result.append(" "); result.append(condition.getOperator()); result.append(" "); result.append(formatCondition(condition.getSecond(), false)); - } else if (genericCondition instanceof Condition.Permission) { + } else if (genericCondition instanceof Condition.Permission condition) { - var condition = (Condition.Permission) genericCondition; result.append("id IN ("); result.append(formatPermissionQuery(condition)); result.append(")"); - } else if (genericCondition instanceof Condition.LatestPositions) { + } else if (genericCondition instanceof Condition.LatestPositions condition) { - var condition = (Condition.LatestPositions) genericCondition; result.append("id IN ("); result.append("SELECT positionId FROM "); result.append(getStorageName(Device.class)); diff --git a/src/main/java/org/traccar/storage/MemoryStorage.java b/src/main/java/org/traccar/storage/MemoryStorage.java index 9b5db1209..18cb6a294 100644 --- a/src/main/java/org/traccar/storage/MemoryStorage.java +++ b/src/main/java/org/traccar/storage/MemoryStorage.java @@ -60,47 +60,37 @@ public class MemoryStorage extends Storage { return true; } - if (genericCondition instanceof Condition.Compare) { + if (genericCondition instanceof Condition.Compare condition) { - var condition = (Condition.Compare) genericCondition; Object value = retrieveValue(object, condition.getVariable()); int result = ((Comparable) value).compareTo(condition.getValue()); - switch (condition.getOperator()) { - case "<": - return result < 0; - case "<=": - return result <= 0; - case ">": - return result > 0; - case ">=": - return result >= 0; - case "=": - return result == 0; - default: - throw new RuntimeException("Unsupported comparison condition"); - } + return switch (condition.getOperator()) { + case "<" -> result < 0; + case "<=" -> result <= 0; + case ">" -> result > 0; + case ">=" -> result >= 0; + case "=" -> result == 0; + default -> throw new RuntimeException("Unsupported comparison condition"); + }; - } else if (genericCondition instanceof Condition.Between) { + } else if (genericCondition instanceof Condition.Between condition) { - var condition = (Condition.Between) genericCondition; Object fromValue = retrieveValue(object, condition.getFromVariable()); int fromResult = ((Comparable) fromValue).compareTo(condition.getFromValue()); Object toValue = retrieveValue(object, condition.getToVariable()); int toResult = ((Comparable) toValue).compareTo(condition.getToValue()); return fromResult >= 0 && toResult <= 0; - } else if (genericCondition instanceof Condition.Binary) { + } else if (genericCondition instanceof Condition.Binary condition) { - var condition = (Condition.Binary) genericCondition; if (condition.getOperator().equals("AND")) { return checkCondition(condition.getFirst(), object) && checkCondition(condition.getSecond(), object); } else if (condition.getOperator().equals("OR")) { return checkCondition(condition.getFirst(), object) || checkCondition(condition.getSecond(), object); } - } else if (genericCondition instanceof Condition.Permission) { + } else if (genericCondition instanceof Condition.Permission condition) { - var condition = (Condition.Permission) genericCondition; long id = (Long) retrieveValue(object, "id"); return getPermissionsSet(condition.getOwnerClass(), condition.getPropertyClass()).stream() .anyMatch(pair -> { diff --git a/src/main/java/org/traccar/storage/QueryBuilder.java b/src/main/java/org/traccar/storage/QueryBuilder.java index 2f4c07406..6a9c46807 100644 --- a/src/main/java/org/traccar/storage/QueryBuilder.java +++ b/src/main/java/org/traccar/storage/QueryBuilder.java @@ -267,18 +267,18 @@ public final class QueryBuilder { } public QueryBuilder setValue(String name, Object value) throws SQLException { - if (value instanceof Boolean) { - setBoolean(name, (Boolean) value); - } else if (value instanceof Integer) { - setInteger(name, (Integer) value); - } else if (value instanceof Long) { - setLong(name, (Long) value); - } else if (value instanceof Double) { - setDouble(name, (Double) value); - } else if (value instanceof String) { - setString(name, (String) value); - } else if (value instanceof Date) { - setDate(name, (Date) value); + if (value instanceof Boolean booleanValue) { + setBoolean(name, booleanValue); + } else if (value instanceof Integer integerValue) { + setInteger(name, integerValue); + } else if (value instanceof Long longValue) { + setLong(name, longValue); + } else if (value instanceof Double doubleValue) { + setDouble(name, doubleValue); + } else if (value instanceof String stringValue) { + setString(name, stringValue); + } else if (value instanceof Date dateValue) { + setDate(name, dateValue); } return this; } diff --git a/src/test/java/org/traccar/ProtocolTest.java b/src/test/java/org/traccar/ProtocolTest.java index 0726000be..273520155 100644 --- a/src/test/java/org/traccar/ProtocolTest.java +++ b/src/test/java/org/traccar/ProtocolTest.java @@ -28,6 +28,7 @@ import java.util.TimeZone; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -159,7 +160,7 @@ public class ProtocolTest extends BaseTest { private void verifyDecodedList(Object decodedObject, boolean checkLocation, Position expected) { assertNotNull(decodedObject, "list is null"); - assertTrue(decodedObject instanceof List, "not a list"); + assertInstanceOf(List.class, decodedObject, "not a list"); assertFalse(((List) decodedObject).isEmpty(), "list is empty"); for (Object item : (List) decodedObject) { @@ -171,7 +172,7 @@ public class ProtocolTest extends BaseTest { private void verifyDecodedPosition(Object decodedObject, boolean checkLocation, boolean checkAttributes, Position expected) { assertNotNull(decodedObject, "position is null"); - assertTrue(decodedObject instanceof Position, "not a position"); + assertInstanceOf(Position.class, decodedObject, "not a position"); Position position = (Position) decodedObject; @@ -225,55 +226,55 @@ public class ProtocolTest extends BaseTest { } if (attributes.containsKey(Position.KEY_INDEX)) { - assertTrue(attributes.get(Position.KEY_INDEX) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_INDEX)); } if (attributes.containsKey(Position.KEY_HDOP)) { - assertTrue(attributes.get(Position.KEY_HDOP) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_HDOP)); } if (attributes.containsKey(Position.KEY_VDOP)) { - assertTrue(attributes.get(Position.KEY_VDOP) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_VDOP)); } if (attributes.containsKey(Position.KEY_PDOP)) { - assertTrue(attributes.get(Position.KEY_PDOP) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_PDOP)); } if (attributes.containsKey(Position.KEY_SATELLITES)) { - assertTrue(attributes.get(Position.KEY_SATELLITES) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_SATELLITES)); } if (attributes.containsKey(Position.KEY_SATELLITES_VISIBLE)) { - assertTrue(attributes.get(Position.KEY_SATELLITES_VISIBLE) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_SATELLITES_VISIBLE)); } if (attributes.containsKey(Position.KEY_RSSI)) { - assertTrue(attributes.get(Position.KEY_RSSI) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_RSSI)); } if (attributes.containsKey(Position.KEY_ODOMETER)) { - assertTrue(attributes.get(Position.KEY_ODOMETER) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_ODOMETER)); } if (attributes.containsKey(Position.KEY_RPM)) { - assertTrue(attributes.get(Position.KEY_RPM) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_RPM)); } if (attributes.containsKey(Position.KEY_FUEL_LEVEL)) { - assertTrue(attributes.get(Position.KEY_FUEL_LEVEL) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_FUEL_LEVEL)); } if (attributes.containsKey(Position.KEY_FUEL_USED)) { - assertTrue(attributes.get(Position.KEY_FUEL_USED) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_FUEL_USED)); } if (attributes.containsKey(Position.KEY_POWER)) { - assertTrue(attributes.get(Position.KEY_POWER) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_POWER)); } if (attributes.containsKey(Position.KEY_BATTERY)) { - assertTrue(attributes.get(Position.KEY_BATTERY) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_BATTERY)); } if (attributes.containsKey(Position.KEY_BATTERY_LEVEL)) { @@ -282,39 +283,39 @@ public class ProtocolTest extends BaseTest { } if (attributes.containsKey(Position.KEY_CHARGE)) { - assertTrue(attributes.get(Position.KEY_CHARGE) instanceof Boolean); + assertInstanceOf(Boolean.class, attributes.get(Position.KEY_CHARGE)); } if (attributes.containsKey(Position.KEY_IGNITION)) { - assertTrue(attributes.get(Position.KEY_IGNITION) instanceof Boolean); + assertInstanceOf(Boolean.class, attributes.get(Position.KEY_IGNITION)); } if (attributes.containsKey(Position.KEY_MOTION)) { - assertTrue(attributes.get(Position.KEY_MOTION) instanceof Boolean); + assertInstanceOf(Boolean.class, attributes.get(Position.KEY_MOTION)); } if (attributes.containsKey(Position.KEY_ARCHIVE)) { - assertTrue(attributes.get(Position.KEY_ARCHIVE) instanceof Boolean); + assertInstanceOf(Boolean.class, attributes.get(Position.KEY_ARCHIVE)); } if (attributes.containsKey(Position.KEY_DRIVER_UNIQUE_ID)) { - assertTrue(attributes.get(Position.KEY_DRIVER_UNIQUE_ID) instanceof String); + assertInstanceOf(String.class, attributes.get(Position.KEY_DRIVER_UNIQUE_ID)); } if (attributes.containsKey(Position.KEY_STEPS)) { - assertTrue(attributes.get(Position.KEY_STEPS) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_STEPS)); } if (attributes.containsKey(Position.KEY_ROAMING)) { - assertTrue(attributes.get(Position.KEY_ROAMING) instanceof Boolean); + assertInstanceOf(Boolean.class, attributes.get(Position.KEY_ROAMING)); } if (attributes.containsKey(Position.KEY_HOURS)) { - assertTrue(attributes.get(Position.KEY_HOURS) instanceof Number); + assertInstanceOf(Number.class, attributes.get(Position.KEY_HOURS)); } if (attributes.containsKey(Position.KEY_RESULT)) { - assertTrue(attributes.get(Position.KEY_RESULT) instanceof String); + assertInstanceOf(String.class, attributes.get(Position.KEY_RESULT)); } if (position.getNetwork() != null) { @@ -351,7 +352,7 @@ public class ProtocolTest extends BaseTest { protected void verifyFrame(ByteBuf expected, Object object) { assertNotNull(object, "buffer is null"); - assertTrue(object instanceof ByteBuf, "not a buffer"); + assertInstanceOf(ByteBuf.class, object, "not a buffer"); assertEquals(ByteBufUtil.hexDump(expected), ByteBufUtil.hexDump((ByteBuf) object)); } -- cgit v1.2.3