This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git


The following commit(s) were added to refs/heads/develop by this push:
     new 3c2978d1db fix: Addressed a lot of code-smells sonarcloud reported.
3c2978d1db is described below

commit 3c2978d1dba4213ff42cd608af1d626349fc440c
Author: Christofer Dutz <[email protected]>
AuthorDate: Sat Jul 22 12:31:59 2023 +0200

    fix: Addressed a lot of code-smells sonarcloud reported.
---
 .../canopen/SDODownloadConversation.java           |   2 -
 .../java/eip/base/protocol/EipProtocolLogic.java   |   4 +-
 .../org/apache/plc4x/java/eip/base/tag/EipTag.java |  17 +-
 .../apache/plc4x/java/knxnetip/ets/EtsParser.java  |  15 +-
 .../plc4x/java/knxnetip/tag/KnxNetIpTag.java       |  21 +--
 .../profinet/protocol/ProfinetProtocolLogic.java   |  78 ++++-----
 .../profinet/protocol/ProfinetProtocolLogic.java   |  26 +--
 .../readwrite/protocol/S7ProtocolEventLogic.java   |   3 +-
 .../plc4x/java/s7/readwrite/tag/S7SzlTag.java      |   8 +-
 .../java/org/apache/plc4x/kafka/Plc4xSinkTask.java |   2 +-
 .../plc4x/nifi/record/RecordPlc4xWriter.java       | 149 +++++++++--------
 .../org/apache/plc4x/java/spi/values/PlcBINT.java  |  10 +-
 .../org/apache/plc4x/java/spi/values/PlcBREAL.java |  10 +-
 .../plc4x/java/transport/serial/SerialChannel.java |  18 +-
 .../utils/rawsockets/netty/utils/ArpUtils.java     | 181 +++++++++++----------
 .../internal/handlers/ApiRequestHandler.java       |   2 +
 16 files changed, 278 insertions(+), 268 deletions(-)

diff --git 
a/plc4j/drivers/canopen/src/main/java/org/apache/plc4x/java/canopen/api/conversation/canopen/SDODownloadConversation.java
 
b/plc4j/drivers/canopen/src/main/java/org/apache/plc4x/java/canopen/api/conversation/canopen/SDODownloadConversation.java
index 1960b4345c..3883b83f76 100644
--- 
a/plc4j/drivers/canopen/src/main/java/org/apache/plc4x/java/canopen/api/conversation/canopen/SDODownloadConversation.java
+++ 
b/plc4j/drivers/canopen/src/main/java/org/apache/plc4x/java/canopen/api/conversation/canopen/SDODownloadConversation.java
@@ -32,13 +32,11 @@ import java.util.concurrent.CompletableFuture;
 
 public class SDODownloadConversation extends CANOpenConversationBase {
 
-    private final CANConversation delegate;
     private final IndexAddress indexAddress;
     private final byte[] data;
 
     public SDODownloadConversation(CANConversation delegate, int nodeId, int 
answerNodeId, IndexAddress indexAddress, PlcValue value, CANOpenDataType type) {
         super(delegate, nodeId, answerNodeId);
-        this.delegate = delegate;
         this.indexAddress = indexAddress;
 
         try {
diff --git 
a/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/protocol/EipProtocolLogic.java
 
b/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/protocol/EipProtocolLogic.java
index e6c72a17ba..74d2b7c427 100644
--- 
a/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/protocol/EipProtocolLogic.java
+++ 
b/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/protocol/EipProtocolLogic.java
@@ -819,7 +819,7 @@ public class EipProtocolLogic extends 
Plc4xProtocolBase<EipPacket> implements Ha
                             // TODO: return as type STRUCT with structuredType 
to let user
                             // apps/progs handle it.
                         }
-                        // TODO: This will fall-though to "default"
+                        return null;
                     }
                     default:
                         return null;
@@ -852,7 +852,7 @@ public class EipProtocolLogic extends 
Plc4xProtocolBase<EipPacket> implements Ha
                     else {
                         // This is a different type of STRUCTURED data
                     }
-                    // TODO: This will fall-though to "default"
+                    return null;
                 }                                                        
                 default:
                     return null;
diff --git 
a/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/tag/EipTag.java
 
b/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/tag/EipTag.java
index d8ac9898e8..fcaf501f47 100644
--- 
a/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/tag/EipTag.java
+++ 
b/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/tag/EipTag.java
@@ -39,10 +39,9 @@ public class EipTag implements PlcTag, Serializable {
     private static final Pattern ADDRESS_PATTERN =
         
Pattern.compile("^(?<tag>[%a-zA-Z_.0-9]+\\[?[0-9]*]?):?(?<dataType>[A-Z]*):?(?<elementNb>[0-9]*)");
 
-    private static final String TAG = "tag";
-    private static final String ELEMENTS = "elementNb";
-    private static final String TYPE = "dataType";
-
+    private static final String GROUP_NAME_TAG = "tag";
+    private static final String GROUP_NAME_GROUP_NAME_ELEMENTS = "elementNb";
+    private static final String GROUP_NAME_TYPE = "dataType";
 
     private final String tag;
     private CIPDataTypeCode type;
@@ -111,14 +110,14 @@ public class EipTag implements PlcTag, Serializable {
     public static EipTag of(String tagString) {
         Matcher matcher = ADDRESS_PATTERN.matcher(tagString);
         if (matcher.matches()) {
-            String tag = matcher.group(TAG);
+            String tag = matcher.group(GROUP_NAME_TAG);
             int nb = 1;
             CIPDataTypeCode type;
-            if (!matcher.group(ELEMENTS).isEmpty()) {
-                nb = Integer.parseInt(matcher.group(ELEMENTS));
+            if (!matcher.group(GROUP_NAME_GROUP_NAME_ELEMENTS).isEmpty()) {
+                nb = 
Integer.parseInt(matcher.group(GROUP_NAME_GROUP_NAME_ELEMENTS));
             }
-            if (!matcher.group(TYPE).isEmpty()) {
-                type = CIPDataTypeCode.valueOf(matcher.group(TYPE));
+            if (!matcher.group(GROUP_NAME_TYPE).isEmpty()) {
+                type = CIPDataTypeCode.valueOf(matcher.group(GROUP_NAME_TYPE));
             } else {
                 type = CIPDataTypeCode.DINT;
             }
diff --git 
a/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/ets/EtsParser.java
 
b/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/ets/EtsParser.java
index 5cc69f76f6..1cc4b50248 100644
--- 
a/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/ets/EtsParser.java
+++ 
b/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/ets/EtsParser.java
@@ -74,14 +74,15 @@ public class EtsParser {
                 File knxMasterFile = new File(tempDir.toFile(), 
"knx_master.xml");
                 // If the file contains: <KNX 
xmlns="http://knx.org/xml/project/21";> it's an ETS6 file
                 // In all other cases, we'll treat it as ETS5
-                Scanner scanner = new Scanner(knxMasterFile);
                 String etsSchemaVersion = null;
-                while (scanner.hasNextLine()) {
-                    final String curLine = scanner.nextLine();
-                    if(curLine.contains("http://knx.org/xml/project/";)) {
-                        etsSchemaVersion = 
curLine.substring(curLine.indexOf("http://knx.org/xml/project/";) + 
"http://knx.org/xml/project/".length());
-                        etsSchemaVersion = etsSchemaVersion.substring(0, 
etsSchemaVersion.indexOf("\""));
-                        break;
+                try(Scanner scanner = new Scanner(knxMasterFile)) {
+                    while (scanner.hasNextLine()) {
+                        final String curLine = scanner.nextLine();
+                        if(curLine.contains("http://knx.org/xml/project/";)) {
+                            etsSchemaVersion = 
curLine.substring(curLine.indexOf("http://knx.org/xml/project/";) + 
"http://knx.org/xml/project/".length());
+                            etsSchemaVersion = etsSchemaVersion.substring(0, 
etsSchemaVersion.indexOf("\""));
+                            break;
+                        }
                     }
                 }
                 EtsFileHandler fileHandler = ("21".equals(etsSchemaVersion)) ? 
new Ets6FileHandler() : new Ets5FileHandler();
diff --git 
a/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/tag/KnxNetIpTag.java
 
b/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/tag/KnxNetIpTag.java
index 56138d3fe5..debc323bad 100644
--- 
a/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/tag/KnxNetIpTag.java
+++ 
b/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/tag/KnxNetIpTag.java
@@ -120,20 +120,17 @@ public class KnxNetIpTag implements PlcTag {
             return false;
         }
         // NOTE: This case fallthrough is intentional :-)
-        switch (getLevels()) {
-            case 3:
-                if(!WILDCARD.equals(getMiddleGroup()) && 
!getMiddleGroup().equals(otherAddress.getMiddleGroup())) {
-                    return false;
-                }
-            case 2:
-                if(!WILDCARD.equals(getSubGroup()) && 
!getSubGroup().equals(otherAddress.getSubGroup())) {
-                    return false;
-                }
-            case 1:
-                return WILDCARD.equals(getMainGroup()) || 
getMainGroup().equals(otherAddress.getMainGroup());
-            default:
+        if(getLevels() == 3) {
+            if (!WILDCARD.equals(getMiddleGroup()) && 
!getMiddleGroup().equals(otherAddress.getMiddleGroup())) {
                 return false;
+            }
         }
+        if(getLevels() >= 2) {
+            if (!WILDCARD.equals(getSubGroup()) && 
!getSubGroup().equals(otherAddress.getSubGroup())) {
+                return false;
+            }
+        }
+        return WILDCARD.equals(getMainGroup()) || 
getMainGroup().equals(otherAddress.getMainGroup());
     }
 
 }
diff --git 
a/plc4j/drivers/profinet-ng/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java
 
b/plc4j/drivers/profinet-ng/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java
index 42cc71a7d4..d35607ace6 100644
--- 
a/plc4j/drivers/profinet-ng/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java
+++ 
b/plc4j/drivers/profinet-ng/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java
@@ -50,7 +50,7 @@ import java.util.concurrent.CompletableFuture;
 
 public class ProfinetProtocolLogic extends Plc4xProtocolBase<Ethernet_Frame> 
implements HasConfiguration<ProfinetConfiguration> {
 
-    private ProfinetDriverContext driverContext;
+    private ProfinetDriverContext profinetDriverContext;
     private ProfinetConfiguration configuration;
 
     private final Logger logger = 
LoggerFactory.getLogger(ProfinetProtocolLogic.class);
@@ -62,7 +62,7 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
             throw new PlcRuntimeException(
                 "Expecting a driverContext of type ProfinetDriverContext, but 
got " + driverContext.getClass().getName());
         }
-        this.driverContext = (ProfinetDriverContext) driverContext;
+        this.profinetDriverContext = (ProfinetDriverContext) driverContext;
     }
 
     @Override
@@ -95,7 +95,7 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
 
             // Check if we actually got the vendor-id and product-id ...
             // without these, we don't know what to do with the device.
-            if ((driverContext.getVendorId() == 0) || 
(driverContext.getDeviceId() == 0)) {
+            if ((profinetDriverContext.getVendorId() == 0) || 
(profinetDriverContext.getDeviceId() == 0)) {
                 logger.error("Unable to determine vendor-id or product-id, 
closing channel...");
                 context.getChannel().close();
                 return;
@@ -103,10 +103,10 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
 
             // Look up the GSD file for this device ...
             ProfinetISO15745Profile deviceProfile =
-                configuration.getGsdProfile(driverContext.getVendorId(), 
driverContext.getDeviceId());
+                
configuration.getGsdProfile(profinetDriverContext.getVendorId(), 
profinetDriverContext.getDeviceId());
             if (deviceProfile == null) {
                 logger.error("Unable to find GSD profile for device with 
vendor-id {} and device-id {}",
-                    driverContext.getVendorId(), driverContext.getDeviceId());
+                    profinetDriverContext.getVendorId(), 
profinetDriverContext.getDeviceId());
                 context.getChannel().close();
                 return;
             }
@@ -115,11 +115,11 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
             if (configuration.dapId != null) {
                 for (ProfinetDeviceAccessPointItem 
profinetDeviceAccessPointItem : 
deviceProfile.getProfileBody().getApplicationProcess().getDeviceAccessPointList())
 {
                     
if(profinetDeviceAccessPointItem.getId().equalsIgnoreCase(configuration.dapId)) 
{
-                        
driverContext.setDapId(profinetDeviceAccessPointItem.getId());
+                        
profinetDriverContext.setDapId(profinetDeviceAccessPointItem.getId());
                         break;
                     }
                 }
-                if(driverContext.getDapId() == null) {
+                if(profinetDriverContext.getDapId() == null) {
                     logger.error("Couldn't find requested device access points 
(DAP): {}", configuration.dapId);
                     context.getChannel().close();
                 }
@@ -151,7 +151,7 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
                 // Try to read the RealIdentificationData ...
                 RawSocketChannel pnChannel = ((RawSocketChannel) 
context.getChannel());
                 CompletableFuture<PnIoCm_Block_RealIdentificationData> future1 
=
-                    
PnDcpPacketFactory.sendRealIdentificationDataRequest(context, pnChannel, 
driverContext);
+                    
PnDcpPacketFactory.sendRealIdentificationDataRequest(context, pnChannel, 
profinetDriverContext);
                 future1.whenComplete((realIdentificationData, throwable1) -> {
                     if(throwable1 != null) {
                         logger.error("Unable to detect device access point, 
closing channel...", throwable1);
@@ -190,12 +190,12 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
                         }
                         long moduleIdentNumber = 
Long.parseLong(moduleIdentNumberStr, 16);
                         if(moduleIdentNumber == dapModuleIdentificationNumber) 
{
-                            driverContext.setDap(curDap);
+                            profinetDriverContext.setDap(curDap);
                             break;
                         }
                     }
                     // Abort, if we weren't able to detect a DAP.
-                    if(driverContext.getDap() == null) {
+                    if(profinetDriverContext.getDap() == null) {
                         logger.error("Unable to auto-detect the device access 
point, closing channel...");
                         context.getChannel().close();
                         return;
@@ -259,8 +259,8 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
                             }
                         }
                     }
-                    driverContext.setModuleIndex(moduleIndex);
-                    driverContext.setSubmoduleIndex(submoduleIndex);
+                    profinetDriverContext.setModuleIndex(moduleIndex);
+                    profinetDriverContext.setSubmoduleIndex(submoduleIndex);
 
                     context.fireConnected();
                 });
@@ -320,7 +320,7 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
         Map<String, List<PlcBrowseItem>> values = new HashMap<>();
         for (String queryName : browseRequest.getQueryNames()) {
             List<PlcBrowseItem> items = new ArrayList<>();
-            for(Map.Entry<Integer, Map<Integer, ProfinetVirtualSubmoduleItem>> 
slotEntry : driverContext.getSubmoduleIndex().entrySet()) {
+            for(Map.Entry<Integer, Map<Integer, ProfinetVirtualSubmoduleItem>> 
slotEntry : profinetDriverContext.getSubmoduleIndex().entrySet()) {
                 int slot = slotEntry.getKey();
                 for(Map.Entry<Integer, ProfinetVirtualSubmoduleItem> 
subslotEntry: slotEntry.getValue().entrySet()) {
                     int subslot = subslotEntry.getKey();
@@ -369,7 +369,7 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
     @Override
     public CompletableFuture<PlcSubscriptionResponse> 
subscribe(PlcSubscriptionRequest subscriptionRequest) {
         // When subscribing, we actually set up the PN IO Application Relation 
and make the remote device start sending data.
-        if (driverContext.getDap() == null) {
+        if (profinetDriverContext.getDap() == null) {
             return CompletableFuture.failedFuture(new 
PlcConnectionException("DAP not set"));
         }
 
@@ -420,12 +420,12 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
                 int subslotNumber = subslotEntry.getKey();
                 Map<ProfinetTag.Direction, Map<Integer, ProfinetTag>> 
direction = subslotEntry.getValue();
 
-                int iocsLength = 
driverContext.getSubmoduleIndex().get(slotNumber).get(subslotNumber).getIoData().getIocsLength();
+                int iocsLength = 
profinetDriverContext.getSubmoduleIndex().get(slotNumber).get(subslotNumber).getIoData().getIocsLength();
                 // The default is 1
                 if(iocsLength == 0) {
                     iocsLength = 1;
                 }
-                int iopsLength = 
driverContext.getSubmoduleIndex().get(slotNumber).get(subslotNumber).getIoData().getIopsLength();
+                int iopsLength = 
profinetDriverContext.getSubmoduleIndex().get(slotNumber).get(subslotNumber).getIoData().getIopsLength();
                 // The default is 1
                 if(iopsLength == 0) {
                     iopsLength = 1;
@@ -478,12 +478,12 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
         blocks.add(new PnIoCm_Block_ArReq(
             ProfinetDriverContext.BLOCK_VERSION_HIGH, 
ProfinetDriverContext.BLOCK_VERSION_LOW,
             PnIoCm_ArType.IO_CONTROLLER,
-            driverContext.generateUuid(),
-            driverContext.getSessionKey(),
+            profinetDriverContext.generateUuid(),
+            profinetDriverContext.getSessionKey(),
             localMacAddress,
-            driverContext.getCmInitiatorObjectUuid(),
+            profinetDriverContext.getCmInitiatorObjectUuid(),
             false,
-            driverContext.isNonLegacyStartupMode(),
+            profinetDriverContext.isNonLegacyStartupMode(),
             false,
             false,
             PnIoCm_CompanionArType.SINGLE_AR,
@@ -506,14 +506,14 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
                 false,
                 PnIoCm_RtClass.RT_CLASS_2,
                 ProfinetDriverContext.DEFAULT_IO_DATA_SIZE,
-                driverContext.getAndIncrementIdentification(),
-                driverContext.getSendClockFactor(),
-                driverContext.getReductionRatio(),
+                profinetDriverContext.getAndIncrementIdentification(),
+                profinetDriverContext.getSendClockFactor(),
+                profinetDriverContext.getReductionRatio(),
                 1,
                 0,
                 0xffffffffL,
-                driverContext.getWatchdogFactor(),
-                driverContext.getDataHoldFactor(),
+                profinetDriverContext.getWatchdogFactor(),
+                profinetDriverContext.getDataHoldFactor(),
                 0xC000,
                 ProfinetDriverContext.DEFAULT_EMPTY_MAC_ADDRESS,
                 Collections.singletonList(
@@ -533,14 +533,14 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
                 false,
                 PnIoCm_RtClass.RT_CLASS_2,
                 ProfinetDriverContext.DEFAULT_IO_DATA_SIZE,
-                driverContext.getAndIncrementIdentification(),
-                driverContext.getSendClockFactor(),
-                driverContext.getReductionRatio(),
+                profinetDriverContext.getAndIncrementIdentification(),
+                profinetDriverContext.getSendClockFactor(),
+                profinetDriverContext.getReductionRatio(),
                 1,
                 0,
                 0xffffffffL,
-                driverContext.getWatchdogFactor(),
-                driverContext.getDataHoldFactor(),
+                profinetDriverContext.getWatchdogFactor(),
+                profinetDriverContext.getDataHoldFactor(),
                 0xC000,
                 ProfinetDriverContext.DEFAULT_EMPTY_MAC_ADDRESS,
                 Collections.singletonList(
@@ -567,9 +567,9 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
             DceRpc_PacketType.WORKING,
             false, false, false,
             IntegerEncoding.BIG_ENDIAN, CharacterEncoding.ASCII, 
FloatingPointEncoding.IEEE,
-            new DceRpc_ObjectUuid((byte) 0x00, (short) 0x0001, 
Integer.decode("0x" + driverContext.getDeviceId()), Integer.decode("0x" + 
driverContext.getVendorId())),
+            new DceRpc_ObjectUuid((byte) 0x00, (short) 0x0001, 
Integer.decode("0x" + profinetDriverContext.getDeviceId()), Integer.decode("0x" 
+ profinetDriverContext.getVendorId())),
             new DceRpc_InterfaceUuid_DeviceInterface(),
-            driverContext.getActivityUuid(),
+            profinetDriverContext.getActivityUuid(),
             0L, 0L,
             DceRpc_Operation.CONNECT,
             (short) 0,
@@ -584,8 +584,8 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
             (short) 64,
             new IpAddress(localAddress.getAddress().getAddress()),
             new IpAddress(remoteAddress.getAddress().getAddress()),
-            driverContext.getLocalPort(),
-            driverContext.getRemotePortImplicitCommunication(),
+            profinetDriverContext.getLocalPort(),
+            profinetDriverContext.getRemotePortImplicitCommunication(),
             packet
         );
         Ethernet_Frame ethernetFrame = new Ethernet_Frame(
@@ -607,13 +607,13 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
         if (blockMap.containsKey(ProfinetDiscoverer.DEVICE_TYPE_NAME)) {
             PnDcp_Block_DevicePropertiesDeviceVendor block =
                 (PnDcp_Block_DevicePropertiesDeviceVendor) 
blockMap.get(ProfinetDiscoverer.DEVICE_TYPE_NAME);
-            driverContext.setDeviceType(new 
String(block.getDeviceVendorValue()));
+            profinetDriverContext.setDeviceType(new 
String(block.getDeviceVendorValue()));
         }
 
         if (blockMap.containsKey(ProfinetDiscoverer.DEVICE_NAME_OF_STATION)) {
             PnDcp_Block_DevicePropertiesNameOfStation block =
                 (PnDcp_Block_DevicePropertiesNameOfStation) 
blockMap.get(ProfinetDiscoverer.DEVICE_NAME_OF_STATION);
-            driverContext.setDeviceName(new String(block.getNameOfStation()));
+            profinetDriverContext.setDeviceName(new 
String(block.getNameOfStation()));
         }
 
         if (blockMap.containsKey(ProfinetDiscoverer.DEVICE_ROLE)) {
@@ -632,14 +632,14 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
             if (block.getPnioDevice()) {
                 roles.add("DEVICE");
             }
-            driverContext.setRoles(roles);
+            profinetDriverContext.setRoles(roles);
         }
 
         if (blockMap.containsKey(ProfinetDiscoverer.DEVICE_ID)) {
             PnDcp_Block_DevicePropertiesDeviceId block =
                 (PnDcp_Block_DevicePropertiesDeviceId) 
blockMap.get(ProfinetDiscoverer.DEVICE_ID);
-            driverContext.setVendorId(block.getVendorId());
-            driverContext.setDeviceId(block.getDeviceId());
+            profinetDriverContext.setVendorId(block.getVendorId());
+            profinetDriverContext.setDeviceId(block.getDeviceId());
         }
     }
 
diff --git 
a/plc4j/drivers/profinet/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java
 
b/plc4j/drivers/profinet/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java
index 2ebcbee453..95beb4f774 100644
--- 
a/plc4j/drivers/profinet/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java
+++ 
b/plc4j/drivers/profinet/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java
@@ -53,7 +53,7 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
 
     private final Logger LOGGER = 
LoggerFactory.getLogger(ProfinetProtocolLogic.class);
 
-    private ProfinetDriverContext driverContext;
+    private ProfinetDriverContext profinetDriverContext;
     private Map<String, ProfinetDevice> devices = new HashMap<>();
 
     public ProfinetProtocolLogic() {
@@ -63,12 +63,12 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
 
     public void setDriverContext(ProfinetDriverContext driverContext) {
         super.setDriverContext(driverContext);
-        this.driverContext = driverContext;
+        this.profinetDriverContext = driverContext;
     }
 
     @Override
     public void setConfiguration(ProfinetConfiguration configuration) {
-        driverContext.setConfiguration(configuration);
+        profinetDriverContext.setConfiguration(configuration);
 
         Map<String, ConfigurationProfinetDevice> configuredDevices = 
configuration.getDevices().getConfiguredDevices();
 
@@ -85,7 +85,7 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
             
devices.get(entry.getValue().getDevicename()).setIpAddress(entry.getValue().getIpaddress());
         }
 
-        driverContext.setHandler(new ProfinetDeviceMessageHandler(devices));
+        profinetDriverContext.setHandler(new 
ProfinetDeviceMessageHandler(devices));
         for (Map.Entry<String, ProfinetDevice> device : devices.entrySet()) {
             
device.getValue().getDeviceContext().setConfiguration(configuration);
         }
@@ -97,15 +97,15 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
 
         // Open the receiving UDP port and keep it open.
         try {
-            driverContext.setSocket(new 
DatagramSocket(ProfinetDriverContext.DEFAULT_UDP_PORT));
+            profinetDriverContext.setSocket(new 
DatagramSocket(ProfinetDriverContext.DEFAULT_UDP_PORT));
         } catch (SocketException e) {
             throw new RuntimeException(e);
         }
 
-        driverContext.getHandler().setConfiguredDevices(devices);
+        profinetDriverContext.getHandler().setConfiguredDevices(devices);
 
         for (Map.Entry<String, ProfinetDevice> device : devices.entrySet()) {
-            device.getValue().setContext(context, 
this.driverContext.getChannel());
+            device.getValue().setContext(context, 
this.profinetDriverContext.getChannel());
         }
     }
 
@@ -118,10 +118,10 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
      * @throws PlcConnectionException
      */
     private void onDeviceDiscovery() throws InterruptedException, 
PlcConnectionException {
-        ProfinetPlcDiscoverer discoverer = new 
ProfinetPlcDiscoverer(driverContext.getChannel());
-        driverContext.getChannel().setDiscoverer(discoverer);
+        ProfinetPlcDiscoverer discoverer = new 
ProfinetPlcDiscoverer(profinetDriverContext.getChannel());
+        profinetDriverContext.getChannel().setDiscoverer(discoverer);
         DefaultPlcDiscoveryRequest request = new 
DefaultPlcDiscoveryRequest(discoverer, new LinkedHashMap<>());
-        discoverer.ongoingDiscoverWithHandler(request, 
driverContext.getHandler(), 5000L, 30000L);
+        discoverer.ongoingDiscoverWithHandler(request, 
profinetDriverContext.getHandler(), 5000L, 30000L);
         waitForDeviceDiscovery();
     }
 
@@ -186,13 +186,13 @@ public class ProfinetProtocolLogic extends 
Plc4xProtocolBase<Ethernet_Frame> imp
             String localAddress = 
channel.getLocalAddress().toString().substring(1).split(":")[0];
             localIpAddress = InetAddress.getByName(localAddress);
             PcapNetworkInterface devByAddress = 
Pcaps.getDevByAddress(localIpAddress);
-            driverContext.setChannel(new 
ProfinetChannel(Collections.singletonList(devByAddress), devices));
-            driverContext.getChannel().setConfiguredDevices(devices);
+            profinetDriverContext.setChannel(new 
ProfinetChannel(Collections.singletonList(devByAddress), devices));
+            profinetDriverContext.getChannel().setConfiguredDevices(devices);
             // Set both the network-interface and the channel for this device
             // TODO: Find out what they are needed for ...
             for (Map.Entry<String, ProfinetDevice> entry : devices.entrySet()) 
{
                 entry.getValue().getDeviceContext().setNetworkInterface(new 
ProfinetNetworkInterface(devByAddress));
-                
entry.getValue().getDeviceContext().setChannel(driverContext.getChannel());
+                
entry.getValue().getDeviceContext().setChannel(profinetDriverContext.getChannel());
             }
         } catch (PcapNativeException | UnknownHostException e) {
             throw new RuntimeException(e);
diff --git 
a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/protocol/S7ProtocolEventLogic.java
 
b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/protocol/S7ProtocolEventLogic.java
index ac36d0651c..eb6939432e 100644
--- 
a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/protocol/S7ProtocolEventLogic.java
+++ 
b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/protocol/S7ProtocolEventLogic.java
@@ -42,7 +42,6 @@ import java.util.function.Consumer;
 public class S7ProtocolEventLogic implements PlcSubscriber {
 
     private final org.slf4j.Logger logger = 
LoggerFactory.getLogger(S7ProtocolEventLogic.class);
-
     private final BlockingQueue<?> eventQueue;
     private final BlockingQueue<PlcSubscriptionEvent> dispachQueue = new 
ArrayBlockingQueue<>(1024);
 
@@ -133,7 +132,7 @@ public class S7ProtocolEventLogic implements PlcSubscriber {
                         dispatchQueue.add(modeEvent);
                     } else if (obj instanceof S7PayloadDiagnosticMessage) {
                         S7PayloadDiagnosticMessage msg = 
(S7PayloadDiagnosticMessage) obj;
-                        if ((msg.getEventId() >= 0x0A000) & (msg.getEventId() 
<= 0x0BFFF)) {
+                        if ((msg.getEventId() >= 0x0A000) && (msg.getEventId() 
<= 0x0BFFF)) {
                             S7UserEvent userEvent = new S7UserEvent(msg);
                             dispatchQueue.add(userEvent);
                         } else {
diff --git 
a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/tag/S7SzlTag.java
 
b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/tag/S7SzlTag.java
index 26a9ffd3a0..002b9ad574 100644
--- 
a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/tag/S7SzlTag.java
+++ 
b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/tag/S7SzlTag.java
@@ -33,8 +33,8 @@ public class S7SzlTag implements PlcTag {
     private static final Pattern SSL_ADDRESS_PATTERN =
         
Pattern.compile("^SZL_ID=(?<szlId>16#[0-9a-fA-F]{4});INDEX=(?<index>16#[0-9a-fA-F]{4})");
  
     
-    private static final String SZL_ID = "szlId";    
-    private static final String INDEX = "index";    
+    private static final String GROUP_NAME_SZL_ID = "szlId";
+    private static final String GROUP_NAME_INDEX = "index";
     
     private final int szlId;
     private final int index;
@@ -74,8 +74,8 @@ public class S7SzlTag implements PlcTag {
     public static S7SzlTag of(String tagString) {
         Matcher matcher = SSL_ADDRESS_PATTERN.matcher(tagString);
         if (matcher.matches()){
-            String strSxlId = matcher.group(SZL_ID);
-            String strIndex = matcher.group(INDEX);
+            String strSxlId = matcher.group(GROUP_NAME_SZL_ID);
+            String strIndex = matcher.group(GROUP_NAME_INDEX);
             strSxlId = strSxlId.replaceAll("16#", "");
             strIndex = strIndex.replaceAll("16#", "");
             return new S7SzlTag(Integer.parseInt(strSxlId, 
16),Integer.parseInt(strIndex, 16));
diff --git 
a/plc4j/integrations/apache-kafka/src/main/java/org/apache/plc4x/kafka/Plc4xSinkTask.java
 
b/plc4j/integrations/apache-kafka/src/main/java/org/apache/plc4x/kafka/Plc4xSinkTask.java
index 728913606d..55da47c41b 100644
--- 
a/plc4j/integrations/apache-kafka/src/main/java/org/apache/plc4x/kafka/Plc4xSinkTask.java
+++ 
b/plc4j/integrations/apache-kafka/src/main/java/org/apache/plc4x/kafka/Plc4xSinkTask.java
@@ -206,7 +206,7 @@ public class Plc4xSinkTask extends SinkTask {
                         log.debug("Ignoring write request received on wrong 
topic");
                     } else if (!tags.containsKey(tagName)) {
                         log.warn("Unable to find address for tag " + tagName);
-                    } else if ((System.currentTimeMillis() > expires) & 
!(expires == 0)) {
+                    } else if ((System.currentTimeMillis() > expires) && 
!(expires == 0)) {
                         log.warn("Write request has expired {} - {}, 
discarding {}", expires, System.currentTimeMillis(), tagName);
                     } else {
                         String address = tags.get(tagName);
diff --git 
a/plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/record/RecordPlc4xWriter.java
 
b/plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/record/RecordPlc4xWriter.java
index c8948ae239..ca8f0267cd 100644
--- 
a/plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/record/RecordPlc4xWriter.java
+++ 
b/plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/record/RecordPlc4xWriter.java
@@ -39,28 +39,28 @@ import org.apache.plc4x.java.api.messages.PlcReadResponse;
 
 public class RecordPlc4xWriter implements Plc4xWriter {
 
-       private final RecordSetWriterFactory recordSetWriterFactory;
-       private final AtomicReference<WriteResult> writeResultRef;
-       private final Map<String, String> originalAttributes;
+    private final RecordSetWriterFactory recordSetWriterFactory;
+    private final AtomicReference<WriteResult> writeResultRef;
+    private final Map<String, String> originalAttributes;
     private String mimeType;
-       
-       private RecordSet fullRecordSet;
-       private RecordSchema writeSchema;
-       
-       
-       public RecordPlc4xWriter(RecordSetWriterFactory recordSetWriterFactory, 
Map<String, String> originalAttributes) {
-               this.recordSetWriterFactory = recordSetWriterFactory;
+
+    private RecordSet fullRecordSet;
+    private RecordSchema writeSchema;
+
+
+    public RecordPlc4xWriter(RecordSetWriterFactory recordSetWriterFactory, 
Map<String, String> originalAttributes) {
+        this.recordSetWriterFactory = recordSetWriterFactory;
         this.writeResultRef = new AtomicReference<>();
         this.originalAttributes = originalAttributes;
-       }
+    }
 
-       @Override
-       public long writePlcReadResponse(PlcReadResponse response, OutputStream 
outputStream, ComponentLog logger, Plc4xReadResponseRowCallback callback, 
RecordSchema recordSchema) throws Exception {
-               if (fullRecordSet == null) {
+    @Override
+    public long writePlcReadResponse(PlcReadResponse response, OutputStream 
outputStream, ComponentLog logger, Plc4xReadResponseRowCallback callback, 
RecordSchema recordSchema) throws Exception {
+        if (fullRecordSet == null) {
             fullRecordSet = new 
Plc4xReadResponseRecordSetWithCallback(response, callback, recordSchema);
             writeSchema = recordSetWriterFactory.getSchema(originalAttributes, 
fullRecordSet.getSchema());
         }
-               Map<String, String> empty = new HashMap<>();
+        Map<String, String> empty = new HashMap<>();
         try (final RecordSetWriter resultSetWriter = 
recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, empty)) {
             writeResultRef.set(resultSetWriter.write(fullRecordSet));
             if (mimeType == null) {
@@ -70,64 +70,69 @@ public class RecordPlc4xWriter implements Plc4xWriter {
         } catch (final Exception e) {
             throw new IOException(e);
         }
-       }
-       
-       @Override
-       public long writePlcReadResponse(PlcReadResponse response, OutputStream 
outputStream, ComponentLog logger, Plc4xReadResponseRowCallback callback, 
RecordSchema recordSchema, FlowFile originalFlowFile) throws Exception {
-        if (fullRecordSet == null) {   
+    }
+
+    @Override
+    public long writePlcReadResponse(PlcReadResponse response, OutputStream 
outputStream, ComponentLog logger, Plc4xReadResponseRowCallback callback, 
RecordSchema recordSchema, FlowFile originalFlowFile) throws Exception {
+        if (fullRecordSet == null) {
             fullRecordSet = new 
Plc4xReadResponseRecordSetWithCallback(response, callback, recordSchema);
             writeSchema = recordSetWriterFactory.getSchema(originalAttributes, 
fullRecordSet.getSchema());
         }
 
-        final RecordSetWriter resultSetWriter;
-        if (originalFlowFile != null){
-            try {
-                resultSetWriter = recordSetWriterFactory.createWriter(logger, 
writeSchema, outputStream, originalFlowFile);
-            } catch (final Exception e) {
-                throw new IOException(e);
+        RecordSetWriter resultSetWriter = null;
+        try {
+            if (originalFlowFile != null) {
+                try {
+                    resultSetWriter = 
recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, 
originalFlowFile);
+                } catch (final Exception e) {
+                    throw new IOException(e);
+                }
+            } else {
+                resultSetWriter = recordSetWriterFactory.createWriter(logger, 
writeSchema, outputStream, Collections.emptyMap());
+            }
+
+            writeResultRef.set(resultSetWriter.write(fullRecordSet));
+            if (mimeType == null) {
+                mimeType = resultSetWriter.getMimeType();
+            }
+            return writeResultRef.get().getRecordCount();
+        } finally {
+            if (resultSetWriter != null) {
+                resultSetWriter.close();
             }
-        } else {
-            resultSetWriter = recordSetWriterFactory.createWriter(logger, 
writeSchema, outputStream, Collections.emptyMap());
-        }
-        
-        
-        writeResultRef.set(resultSetWriter.write(fullRecordSet));
-        if (mimeType == null) {
-            mimeType = resultSetWriter.getMimeType();
         }
-        return writeResultRef.get().getRecordCount();
-       }
-
-       
-       @Override
-       public void writeEmptyPlcReadResponse(OutputStream outputStream, 
ComponentLog logger) throws IOException {
-               Map<String, String> empty = new HashMap<>();
-               try (final RecordSetWriter resultSetWriter = 
recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, empty)) {
+    }
+
+
+    @Override
+    public void writeEmptyPlcReadResponse(OutputStream outputStream, 
ComponentLog logger) throws IOException {
+        Map<String, String> empty = new HashMap<>();
+        try (final RecordSetWriter resultSetWriter = 
recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, empty)) {
             mimeType = resultSetWriter.getMimeType();
             resultSetWriter.beginRecordSet();
             resultSetWriter.finishRecordSet();
         } catch (final Exception e) {
             throw new IOException(e);
         }
-       }
-       
-       @Override
-       public void writeEmptyPlcReadResponse(OutputStream outputStream, 
ComponentLog logger, FlowFile originalFlowFile) throws IOException {
-               try (final RecordSetWriter resultSetWriter = 
recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, 
originalFlowFile)) {
+    }
+
+    @Override
+    public void writeEmptyPlcReadResponse(OutputStream outputStream, 
ComponentLog logger, FlowFile originalFlowFile) throws IOException {
+        try (final RecordSetWriter resultSetWriter = 
recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, 
originalFlowFile)) {
             mimeType = resultSetWriter.getMimeType();
             resultSetWriter.beginRecordSet();
             resultSetWriter.finishRecordSet();
         } catch (final Exception e) {
             throw new IOException(e);
         }
-       }
-
-       @Override
-       public String getMimeType() {
-               return mimeType;
-       }
-       
-       @Override
+    }
+
+    @Override
+    public String getMimeType() {
+        return mimeType;
+    }
+
+    @Override
     public Map<String, String> getAttributesToAdd() {
         Map<String, String> attributesToAdd = new HashMap<>();
         attributesToAdd.put(CoreAttributes.MIME_TYPE.key(), mimeType);
@@ -142,40 +147,42 @@ public class RecordPlc4xWriter implements Plc4xWriter {
         return attributesToAdd;
     }
 
-       @Override
+    @Override
     public void updateCounters(ProcessSession session) {
         final WriteResult result = writeResultRef.get();
         if (result != null) {
             session.adjustCounter("Records Written", result.getRecordCount(), 
false);
         }
     }
-       
-       private static class Plc4xReadResponseRecordSetWithCallback extends 
Plc4xReadResponseRecordSet {
+
+    private static class Plc4xReadResponseRecordSetWithCallback extends 
Plc4xReadResponseRecordSet {
         private final Plc4xReadResponseRowCallback callback;
+
         public Plc4xReadResponseRecordSetWithCallback(final PlcReadResponse 
readResponse, Plc4xReadResponseRowCallback callback, RecordSchema recordSchema) 
throws IOException {
             super(readResponse, recordSchema);
             this.callback = callback;
         }
+
         @Override
         public Record next() throws IOException {
-                if (hasMoreRows()) {
-                       PlcReadResponse response = getReadResponse();
-                    final Record record = createRecord(response);
-                    setMoreRows(false);
-                    if (callback != null) {
-                        callback.processRow(response);
-                    }
-                    return record;
-                } else {
-                    return null;
+            if (hasMoreRows()) {
+                PlcReadResponse response = getReadResponse();
+                final Record record = createRecord(response);
+                setMoreRows(false);
+                if (callback != null) {
+                    callback.processRow(response);
                 }
+                return record;
+            } else {
+                return null;
+            }
         }
-       }
+    }
 
-    public RecordSchema getRecordSchema(){
+    public RecordSchema getRecordSchema() {
         try {
             return this.fullRecordSet.getSchema();
-        } catch (IOException e){
+        } catch (IOException e) {
             return null;
         }
     }
diff --git 
a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBINT.java 
b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBINT.java
index 7592fb9521..d4aba0d371 100644
--- a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBINT.java
+++ b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBINT.java
@@ -57,22 +57,22 @@ public class PlcBINT extends PlcIECValue<BigInteger> {
     }
 
     public PlcBINT(Byte value) {
-        this.value = BigInteger.valueOf(value);;
+        this.value = BigInteger.valueOf(value);
         this.isNullable = false;
     }
 
     public PlcBINT(Short value) {
-        this.value = BigInteger.valueOf(value);;
+        this.value = BigInteger.valueOf(value);
         this.isNullable = false;
     }
 
     public PlcBINT(Integer value) {
-        this.value = BigInteger.valueOf(value);;
+        this.value = BigInteger.valueOf(value);
         this.isNullable = false;
     }
 
     public PlcBINT(Long value) {
-        this.value = BigInteger.valueOf(value);;
+        this.value = BigInteger.valueOf(value);
         this.isNullable = false;
     }
 
@@ -97,7 +97,7 @@ public class PlcBINT extends PlcIECValue<BigInteger> {
     }
 
     public PlcBINT(String value) {
-        this.value = new BigInteger(value.trim());;
+        this.value = new BigInteger(value.trim());
         this.isNullable = false;
     }
 
diff --git 
a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBREAL.java 
b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBREAL.java
index 8fd5aac988..74b7e3d092 100644
--- a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBREAL.java
+++ b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBREAL.java
@@ -57,22 +57,22 @@ public class PlcBREAL extends PlcIECValue<BigDecimal> {
     }
 
     public PlcBREAL(Byte value) {
-        this.value = BigDecimal.valueOf(value);;
+        this.value = BigDecimal.valueOf(value);
         this.isNullable = false;
     }
 
     public PlcBREAL(Short value) {
-        this.value = BigDecimal.valueOf(value);;
+        this.value = BigDecimal.valueOf(value);
         this.isNullable = false;
     }
 
     public PlcBREAL(Integer value) {
-        this.value = BigDecimal.valueOf(value);;
+        this.value = BigDecimal.valueOf(value);
         this.isNullable = false;
     }
 
     public PlcBREAL(Long value) {
-        this.value = BigDecimal.valueOf(value);;
+        this.value = BigDecimal.valueOf(value);
         this.isNullable = false;
     }
 
@@ -97,7 +97,7 @@ public class PlcBREAL extends PlcIECValue<BigDecimal> {
     }
 
     public PlcBREAL(String value) {
-        this.value = new BigDecimal(value.trim());;
+        this.value = new BigDecimal(value.trim());
         this.isNullable = false;
     }
 
diff --git 
a/plc4j/transports/serial/src/main/java/org/apache/plc4x/java/transport/serial/SerialChannel.java
 
b/plc4j/transports/serial/src/main/java/org/apache/plc4x/java/transport/serial/SerialChannel.java
index e29e28a280..51586ba314 100644
--- 
a/plc4j/transports/serial/src/main/java/org/apache/plc4x/java/transport/serial/SerialChannel.java
+++ 
b/plc4j/transports/serial/src/main/java/org/apache/plc4x/java/transport/serial/SerialChannel.java
@@ -47,10 +47,10 @@ public class SerialChannel extends AbstractNioByteChannel 
implements DuplexChann
     private final SerialChannelConfig config;
 
     private final VoidChannelPromise unsafeVoidPromise = new 
VoidChannelPromise(this, false);
-    private boolean readPending = false; // Did we receive an EOF?
+    private boolean serialReadPending = false; // Did we receive an EOF?
     private SocketAddress remoteAddress;
     private boolean active = false;
-    private SerialSelectionKey selectionKey;
+    private SerialSelectionKey serialSelectionKey;
     private SerialChannelHandler comPort;
     private final DefaultChannelPipeline pipeline; // Copied from 
AbstractChannel
 
@@ -165,7 +165,7 @@ public class SerialChannel extends AbstractNioByteChannel 
implements DuplexChann
             logger.debug("Using Com Port {}, trying to open port", 
comPort.getIdentifier());
             if (comPort.open()) {
                 logger.debug("Opened port successful to {}", 
comPort.getIdentifier());
-                comPort.registerSelectionKey(selectionKey);
+                comPort.registerSelectionKey(serialSelectionKey);
 
                 this.active = true;
                 return true;
@@ -275,13 +275,13 @@ public class SerialChannel extends AbstractNioByteChannel 
implements DuplexChann
                         close = allocHandle.lastBytesRead() < 0;
                         if (close) {
                             // There is nothing left to read as we received an 
EOF.
-                            readPending = false;
+                            serialReadPending = false;
                         }
                         break;
                     }
 
                     allocHandle.incMessagesRead(1);
-                    readPending = false;
+                    serialReadPending = false;
                     pipeline.fireChannelRead(byteBuf);
                 } while (allocHandle.continueReading());
 
@@ -297,13 +297,13 @@ public class SerialChannel extends AbstractNioByteChannel 
implements DuplexChann
                 // handleReadException(pipeline, byteBuf, t, close, 
allocHandle);
                 t.printStackTrace();
             } finally {
-                // Check if there is a readPending which was not processed yet.
+                // Check if there is a serialReadPending which was not 
processed yet.
                 // This could be for two reasons:
                 // * The user called Channel.read() or 
ChannelHandlerContext.read() in channelRead(...) method
                 // * The user called Channel.read() or 
ChannelHandlerContext.read() in channelReadComplete(...) method
                 //
                 // See https://github.com/netty/netty/issues/2254
-                if (!readPending && !config.isAutoRead()) {
+                if (!serialReadPending && !config.isAutoRead()) {
                     // TODO
                 }
             }
@@ -349,12 +349,12 @@ public class SerialChannel extends AbstractNioByteChannel 
implements DuplexChann
                 SerialPollingSelector selector = (SerialPollingSelector) 
method.invoke(eventLoop);
 
                 // Register the channel
-                selectionKey = (SerialSelectionKey) ((SerialChannel) 
promise.channel()).javaChannel().register(selector, 0, SerialChannel.this);
+                serialSelectionKey = (SerialSelectionKey) ((SerialChannel) 
promise.channel()).javaChannel().register(selector, 0, SerialChannel.this);
 
                 // Set selection key
                 final Field selectionKeyField = 
AbstractNioChannel.class.getDeclaredField("selectionKey");
                 selectionKeyField.setAccessible(true);
-                selectionKeyField.set(SerialChannel.this, selectionKey);
+                selectionKeyField.set(SerialChannel.this, serialSelectionKey);
 
                 // Set event loop (again, via reflection)
                 final Field loop = 
AbstractChannel.class.getDeclaredField("eventLoop");
diff --git 
a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/utils/ArpUtils.java
 
b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/utils/ArpUtils.java
index 9c01d0cb76..c19d56e0a8 100644
--- 
a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/utils/ArpUtils.java
+++ 
b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/utils/ArpUtils.java
@@ -103,15 +103,18 @@ public class ArpUtils {
             }
             final MacAddress localMacAddress = first.get();
 
-            // This handle will be used for receiving response packets.
-            PcapHandle receivingHandle = nif.openLive(
-                65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100);
-            // This handle will be used for sending the request packet.
-            PcapHandle sendingHandle = nif.openLive(
-                65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100);
-            // The executor, that handles processing the incoming packets.
-            ExecutorService arpExecutor = Executors.newSingleThreadExecutor();
+            PcapHandle receivingHandle = null;
+            PcapHandle sendingHandle = null;
+            ExecutorService arpExecutor = null;
             try {
+                // This handle will be used for receiving response packets.
+                receivingHandle = nif.openLive(
+                    65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 
100);
+                // This handle will be used for sending the request packet.
+                sendingHandle = nif.openLive(
+                    65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 
100);
+                // The executor, that handles processing the incoming packets.
+                arpExecutor = Executors.newSingleThreadExecutor();
                 StringBuilder sb = new StringBuilder("arp");
                 sb.append(" and ether dst 
").append(Pcaps.toBpfString(localMacAddress)).append(" and (");
                 boolean firstAddress = true;
@@ -140,10 +143,11 @@ public class ArpUtils {
                 // The resolution task actually runs in one of the
                 // arpExecutor pools threads and just makes sure the
                 // incoming packet is passed to the listener.
+                final PcapHandle finalReceivingHandle = receivingHandle;
                 Runnable resolutionTask = () -> {
                     try {
-                        while (receivingHandle.isOpen()) {
-                            final Packet nextPacket = 
receivingHandle.getNextPacket();
+                        while (finalReceivingHandle.isOpen()) {
+                            final Packet nextPacket = 
finalReceivingHandle.getNextPacket();
                             if (nextPacket != null) {
                                 listener.gotPacket(nextPacket);
                             }
@@ -193,13 +197,13 @@ public class ArpUtils {
                 logger.error("error", e);
             } finally {
                 // Gracefully shut down.
-                if (receivingHandle.isOpen()) {
+                if ((receivingHandle != null) && receivingHandle.isOpen()) {
                     receivingHandle.close();
                 }
-                if (sendingHandle.isOpen()) {
+                if ((sendingHandle != null) && sendingHandle.isOpen()) {
                     sendingHandle.close();
                 }
-                if (!arpExecutor.isShutdown()) {
+                if ((arpExecutor != null) && !arpExecutor.isShutdown()) {
                     arpExecutor.shutdown();
                 }
             }
@@ -214,103 +218,106 @@ public class ArpUtils {
     /**
      * Used to get the mac address for a given IP address.
      *
-     * @param nif network device
-     * @param remoteAddress remote ip address that we want to get the mac 
address for
-     * @param localAddress local ip address of the device asking the question
+     * @param nif             network device
+     * @param remoteAddress   remote ip address that we want to get the mac 
address for
+     * @param localAddress    local ip address of the device asking the 
question
      * @param localMacAddress local mac address of the device asking the 
question
      * @return optional that possibly contains the mac address we were looking 
for.
      */
     public static Optional<MacAddress> resolveMacAddress(PcapNetworkInterface 
nif, InetSocketAddress remoteAddress, InetSocketAddress localAddress, 
MacAddress localMacAddress) {
+        PcapHandle receivingHandle = null;
+        PcapHandle sendingHandle = null;
+        ExecutorService arpExecutor = null;
         try {
             // This handle will be used for receiving response packets.
-            PcapHandle receivingHandle = nif.openLive(
+            receivingHandle = nif.openLive(
                 65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100);
             // This handle will be used for sending the request packet.
-            PcapHandle sendingHandle = nif.openLive(
+            sendingHandle = nif.openLive(
                 65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100);
             // The executor, that handles processing the incoming packets.
-            ExecutorService arpExecutor = Executors.newSingleThreadExecutor();
+            arpExecutor = Executors.newSingleThreadExecutor();
             CompletableFuture<MacAddress> remoteMacAddressFuture = new 
CompletableFuture<>();
-            try {
-                // Try to limit the number of processed incoming packets to 
the minimum.
-                // So far we know the source host ip as well as the target ip 
and mac address.
-                receivingHandle.setFilter(
-                    String.format("arp and src host %s and dst host %s and 
ether dst %s",
-                        Pcaps.toBpfString(remoteAddress.getAddress()), 
Pcaps.toBpfString(localAddress.getAddress()),
-                        Pcaps.toBpfString(localMacAddress)),
-                    BpfProgram.BpfCompileMode.OPTIMIZE);
 
-                // Register the listener, which will be processing all packets 
that pass
-                // the filter (Should actually only be one)
-                PacketListener listener =
-                    packet -> {
-                        if (packet.contains(ArpPacket.class)) {
-                            ArpPacket arp = packet.get(ArpPacket.class);
-                            if 
(arp.getHeader().getOperation().equals(ArpOperation.REPLY)) {
-                                
remoteMacAddressFuture.complete(arp.getHeader().getSrcHardwareAddr());
-                            }
-                        }
-                    };
+            // Try to limit the number of processed incoming packets to the 
minimum.
+            // So far we know the source host ip as well as the target ip and 
mac address.
+            receivingHandle.setFilter(
+                String.format("arp and src host %s and dst host %s and ether 
dst %s",
+                    Pcaps.toBpfString(remoteAddress.getAddress()), 
Pcaps.toBpfString(localAddress.getAddress()),
+                    Pcaps.toBpfString(localMacAddress)),
+                BpfProgram.BpfCompileMode.OPTIMIZE);
 
-                // The resolution task actually runs in one of the
-                // arpExecutor pools threads and just makes sure the
-                // incoming packet is passed to the listener.
-                Runnable resolutionTask = () -> {
-                    try {
-                        receivingHandle.loop(1, listener);
-                    } catch (InterruptedException e) {
-                        Thread.currentThread().interrupt();
-                    } catch (PcapNativeException | NotOpenException e) {
-                        remoteMacAddressFuture.completeExceptionally(e);
+            // Register the listener, which will be processing all packets 
that pass
+            // the filter (Should actually only be one)
+            PacketListener listener =
+                packet -> {
+                    if (packet.contains(ArpPacket.class)) {
+                        ArpPacket arp = packet.get(ArpPacket.class);
+                        if 
(arp.getHeader().getOperation().equals(ArpOperation.REPLY)) {
+                            
remoteMacAddressFuture.complete(arp.getHeader().getSrcHardwareAddr());
+                        }
                     }
                 };
-                arpExecutor.execute(resolutionTask);
-
-                // Actually assemble the ARP packet.
-                ArpPacket.Builder arpBuilder = new ArpPacket.Builder();
-                arpBuilder.hardwareType(ArpHardwareType.ETHERNET)
-                    .protocolType(EtherType.IPV4)
-                    .hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES)
-                    .protocolAddrLength((byte) 
ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES)
-                    .operation(ArpOperation.REQUEST)
-                    .srcHardwareAddr(localMacAddress)
-                    .srcProtocolAddr(localAddress.getAddress())
-                    .dstHardwareAddr(MacAddress.ETHER_BROADCAST_ADDRESS)
-                    .dstProtocolAddr(remoteAddress.getAddress());
-                EthernetPacket.Builder etherBuilder = new 
EthernetPacket.Builder();
-                etherBuilder
-                    .dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS)
-                    .srcAddr(localMacAddress)
-                    .type(EtherType.ARP)
-                    .payloadBuilder(arpBuilder)
-                    .paddingAtBuild(true);
-                Packet arpRequestPacket = etherBuilder.build();
 
-                // Send the arp lookup packet.
-                sendingHandle.sendPacket(arpRequestPacket);
-
-                // Wait for the future to complete (It's completed in the 
packet listener).
+            // The resolution task actually runs in one of the
+            // arpExecutor pools threads and just makes sure the
+            // incoming packet is passed to the listener.
+            final PcapHandle finalReceivingHandle = receivingHandle;
+            Runnable resolutionTask = () -> {
                 try {
-                    return Optional.of(remoteMacAddressFuture.get(1000, 
TimeUnit.MILLISECONDS));
+                    finalReceivingHandle.loop(1, listener);
                 } catch (InterruptedException e) {
                     Thread.currentThread().interrupt();
-                } catch (ExecutionException | TimeoutException e) {
-                    return Optional.empty();
-                }
-            } finally {
-                // Gracefully shut down.
-                if (receivingHandle.isOpen()) {
-                    receivingHandle.close();
-                }
-                if (sendingHandle.isOpen()) {
-                    sendingHandle.close();
-                }
-                if (!arpExecutor.isShutdown()) {
-                    arpExecutor.shutdown();
+                } catch (PcapNativeException | NotOpenException e) {
+                    remoteMacAddressFuture.completeExceptionally(e);
                 }
+            };
+            arpExecutor.execute(resolutionTask);
+
+            // Actually assemble the ARP packet.
+            ArpPacket.Builder arpBuilder = new ArpPacket.Builder();
+            arpBuilder.hardwareType(ArpHardwareType.ETHERNET)
+                .protocolType(EtherType.IPV4)
+                .hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES)
+                .protocolAddrLength((byte) 
ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES)
+                .operation(ArpOperation.REQUEST)
+                .srcHardwareAddr(localMacAddress)
+                .srcProtocolAddr(localAddress.getAddress())
+                .dstHardwareAddr(MacAddress.ETHER_BROADCAST_ADDRESS)
+                .dstProtocolAddr(remoteAddress.getAddress());
+            EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder();
+            etherBuilder
+                .dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS)
+                .srcAddr(localMacAddress)
+                .type(EtherType.ARP)
+                .payloadBuilder(arpBuilder)
+                .paddingAtBuild(true);
+            Packet arpRequestPacket = etherBuilder.build();
+
+            // Send the arp lookup packet.
+            sendingHandle.sendPacket(arpRequestPacket);
+
+            // Wait for the future to complete (It's completed in the packet 
listener).
+            try {
+                return Optional.of(remoteMacAddressFuture.get(1000, 
TimeUnit.MILLISECONDS));
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+            } catch (ExecutionException | TimeoutException e) {
+                return Optional.empty();
             }
         } catch (NotOpenException | PcapNativeException e) {
             return Optional.empty();
+        } finally {
+            // Gracefully shut down.
+            if ((receivingHandle != null) && receivingHandle.isOpen()) {
+                receivingHandle.close();
+            }
+            if ((sendingHandle != null) && sendingHandle.isOpen()) {
+                sendingHandle.close();
+            }
+            if ((arpExecutor != null) && !arpExecutor.isShutdown()) {
+                arpExecutor.shutdown();
+            }
         }
         return Optional.empty();
     }
diff --git 
a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java
 
b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java
index 29c95038a4..b3616289fa 100644
--- 
a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java
+++ 
b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java
@@ -18,6 +18,7 @@
  */
 package org.apache.plc4x.test.driver.internal.handlers;
 
+import org.apache.commons.lang3.NotImplementedException;
 import org.apache.plc4x.java.api.PlcConnection;
 import org.apache.plc4x.java.api.exceptions.PlcRuntimeException;
 import org.apache.plc4x.java.api.messages.PlcReadRequest;
@@ -86,6 +87,7 @@ public class ApiRequestHandler {
             }
             case "TestSubscriptionRequest":{
                 // TODO: chris add your stuff here...
+                throw new NotImplementedException();
             }
             default:
                 throw new PlcRuntimeException("Unknown class name" + typeName);

Reply via email to