You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by cd...@apache.org on 2019/09/04 09:42:55 UTC

[plc4x] branch develop updated (25d008f -> c97b2bb)

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

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


    from 25d008f  Merge pull request #81 from rvs/simple
     new 5afd1c3  - Implemented a first version of a pcap-socket (Virtual Raw-Socket that reads from PCAP files)
     new 3393961  - Added a missing argument to the virtual field template.
     new c97b2bb  - Added a missing lengthExpression to the manual field

The 3 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../resources/templates/java/pojo-template.ftlh    |   2 +-
 .../mspec/model/fields/DefaultManualField.java     |   8 +-
 .../mspec/parser/MessageFormatListener.java        |   4 +-
 .../{raw-socket => pcap-socket}/pom.xml            |   8 +-
 .../java/base/connection/PcapChannelFactory.java}  |  58 ++++-------
 plc4j/protocols/driver-bases/pom.xml               |   1 +
 plc4j/utils/{raw-sockets => pcap-sockets}/pom.xml  |  17 +---
 .../utils/pcapsockets/PcapSocketException.java}    |  10 +-
 .../utils/pcapsockets}/netty/PacketHandler.java    |   2 +-
 .../utils/pcapsockets/netty/PcapSocketAddress.java |  25 +++--
 .../pcapsockets/netty/PcapSocketChannel.java}      | 110 ++++++++++-----------
 .../netty/PcapSocketChannelConfig.java}            |  15 +--
 .../netty/PcapSocketChannelOption.java}            |  13 ++-
 .../pcapsockets}/netty/TcpIpPacketHandler.java     |   8 +-
 plc4j/utils/pom.xml                                |   7 +-
 .../utils/rawsockets/netty/TcpIpPacketHandler.java |   6 +-
 .../src/remote-resources/META-INF/LICENSE          |   5 +-
 17 files changed, 145 insertions(+), 154 deletions(-)
 copy plc4j/protocols/driver-bases/{raw-socket => pcap-socket}/pom.xml (88%)
 copy plc4j/protocols/driver-bases/{raw-socket/src/main/java/org/apache/plc4x/java/base/connection/RawSocketChannelFactory.java => pcap-socket/src/main/java/org/apache/plc4x/java/base/connection/PcapChannelFactory.java} (62%)
 copy plc4j/utils/{raw-sockets => pcap-sockets}/pom.xml (83%)
 copy plc4j/utils/{raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/RawSocketException.java => pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/PcapSocketException.java} (75%)
 copy plc4j/utils/{raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets => pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets}/netty/PacketHandler.java (94%)
 copy sandbox/code-gen/src/main/java/org/apache/plc4x/codegen/ast/ExceptionType.java => plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketAddress.java (67%)
 copy plc4j/utils/{raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketChannel.java => pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannel.java} (68%)
 copy plc4j/utils/{raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketChannelConfig.java => pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelConfig.java} (76%)
 copy plc4j/utils/{raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketChannelOption.java => pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelOption.java} (70%)
 copy plc4j/utils/{raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets => pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets}/netty/TcpIpPacketHandler.java (85%)


[plc4x] 03/03: - Added a missing lengthExpression to the manual field

Posted by cd...@apache.org.
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

commit c97b2bb3278c4c87dceff6c1c8ba1d31f5750d61
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Wed Sep 4 11:42:02 2019 +0200

    - Added a missing lengthExpression to the manual field
---
 .../language/mspec/model/fields/DefaultManualField.java           | 8 +++++++-
 .../language/mspec/parser/MessageFormatListener.java              | 4 +++-
 2 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/model/fields/DefaultManualField.java b/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/model/fields/DefaultManualField.java
index 2221426..3cbd337 100644
--- a/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/model/fields/DefaultManualField.java
+++ b/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/model/fields/DefaultManualField.java
@@ -29,14 +29,16 @@ public class DefaultManualField extends DefaultTaggedField implements ManualFiel
     private final String name;
     private final Term serializationExpression;
     private final Term deserializationExpression;
+    private final Term lengthExpression;
     private final Term[] params;
 
-    public DefaultManualField(String[] tags, TypeReference type, String name, Term serializationExpression, Term deserializationExpression, Term[] params) {
+    public DefaultManualField(String[] tags, TypeReference type, String name, Term serializationExpression, Term deserializationExpression, Term lengthExpression, Term[] params) {
         super(tags);
         this.type = type;
         this.name = name;
         this.serializationExpression = serializationExpression;
         this.deserializationExpression = deserializationExpression;
+        this.lengthExpression = lengthExpression;
         this.params = params;
     }
 
@@ -56,6 +58,10 @@ public class DefaultManualField extends DefaultTaggedField implements ManualFiel
         return deserializationExpression;
     }
 
+    public Term getLengthExpression() {
+        return lengthExpression;
+    }
+
     public Term[] getParams() {
         return params;
     }
diff --git a/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/parser/MessageFormatListener.java b/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/parser/MessageFormatListener.java
index 071f866..224e858 100644
--- a/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/parser/MessageFormatListener.java
+++ b/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/parser/MessageFormatListener.java
@@ -181,9 +181,11 @@ public class MessageFormatListener extends MSpecBaseListener {
         Term serializationExpression = getExpressionTerm(serializationExpressionString);
         String deserializationExpressionString = ctx.deserializationExpression.expr.getText();
         Term deserializationExpression = getExpressionTerm(deserializationExpressionString);
+        String lengthExpressionString = ctx.lengthExpression.expr.getText();
+        Term lengthExpression =  getExpressionTerm(lengthExpressionString);
         Term[] params = getFieldParams((MSpecParser.FieldDefinitionContext) ctx.parent.parent);
         Field field = new DefaultManualField(null, type, name, serializationExpression, deserializationExpression,
-            params);
+            lengthExpression, params);
         if(parserContexts.peek() != null) {
             parserContexts.peek().add(field);
         }


[plc4x] 01/03: - Implemented a first version of a pcap-socket (Virtual Raw-Socket that reads from PCAP files)

Posted by cd...@apache.org.
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

commit 5afd1c32a060cfa212069659a6644445bacd9527
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Wed Sep 4 11:40:27 2019 +0200

    - Implemented a first version of a pcap-socket (Virtual Raw-Socket that reads from PCAP files)
---
 plc4j/protocols/driver-bases/pcap-socket/pom.xml   |  67 +++++
 .../java/base/connection/PcapChannelFactory.java   |  93 +++++++
 plc4j/protocols/driver-bases/pom.xml               |   1 +
 plc4j/utils/pcap-sockets/pom.xml                   |  90 +++++++
 .../utils/pcapsockets/PcapSocketException.java     |  34 +++
 .../utils/pcapsockets/netty/PacketHandler.java}    |  18 +-
 .../pcapsockets/netty/PcapSocketAddress.java}      |  32 +--
 .../utils/pcapsockets/netty/PcapSocketChannel.java | 275 +++++++++++++++++++++
 .../pcapsockets/netty/PcapSocketChannelConfig.java |  69 ++++++
 .../netty/PcapSocketChannelOption.java}            |  34 +--
 .../pcapsockets}/netty/TcpIpPacketHandler.java     |   8 +-
 plc4j/utils/pom.xml                                |   7 +-
 .../utils/rawsockets/netty/TcpIpPacketHandler.java |   6 +-
 .../src/remote-resources/META-INF/LICENSE          |   5 +-
 14 files changed, 685 insertions(+), 54 deletions(-)

diff --git a/plc4j/protocols/driver-bases/pcap-socket/pom.xml b/plc4j/protocols/driver-bases/pcap-socket/pom.xml
new file mode 100644
index 0000000..170c474
--- /dev/null
+++ b/plc4j/protocols/driver-bases/pcap-socket/pom.xml
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <modelVersion>4.0.0</modelVersion>
+
+  <parent>
+    <groupId>org.apache.plc4x</groupId>
+    <artifactId>plc4j-protocols-driver-bases</artifactId>
+    <version>0.5.0-SNAPSHOT</version>
+  </parent>
+
+  <artifactId>plc4j-protocol-driver-base-pcap-socket</artifactId>
+  <name>PLC4J: Protocol: Driver-Base: PCAP</name>
+  <description>Base classes needed to implement plc4x drivers based on an simulated network device using a PCAP capture file to simulate network trafic.</description>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.plc4x</groupId>
+      <artifactId>plc4j-protocol-driver-base</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.plc4x</groupId>
+      <artifactId>plc4j-api</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.plc4x</groupId>
+      <artifactId>plc4j-utils-pcap-sockets</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+    </dependency>
+
+    <dependency>
+      <groupId>io.netty</groupId>
+      <artifactId>netty-transport</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>io.netty</groupId>
+      <artifactId>netty-common</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>ch.qos.logback</groupId>
+      <artifactId>logback-classic</artifactId>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+
+</project>
\ No newline at end of file
diff --git a/plc4j/protocols/driver-bases/pcap-socket/src/main/java/org/apache/plc4x/java/base/connection/PcapChannelFactory.java b/plc4j/protocols/driver-bases/pcap-socket/src/main/java/org/apache/plc4x/java/base/connection/PcapChannelFactory.java
new file mode 100644
index 0000000..79ae1c7
--- /dev/null
+++ b/plc4j/protocols/driver-bases/pcap-socket/src/main/java/org/apache/plc4x/java/base/connection/PcapChannelFactory.java
@@ -0,0 +1,93 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.java.base.connection;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.EventLoopGroup;
+import io.netty.channel.oio.OioEventLoopGroup;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
+import org.apache.plc4x.java.api.exceptions.PlcException;
+import org.apache.plc4x.java.utils.pcapsockets.netty.PcapSocketAddress;
+import org.apache.plc4x.java.utils.pcapsockets.netty.PcapSocketChannel;
+import org.apache.plc4x.java.utils.pcapsockets.netty.PcapSocketChannelOption;
+import org.apache.plc4x.java.utils.pcapsockets.netty.TcpIpPacketHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+
+public class PcapChannelFactory implements ChannelFactory {
+
+    private static final Logger logger = LoggerFactory.getLogger(PcapChannelFactory.class);
+
+    private final File pcapFile;
+
+    public PcapChannelFactory(File pcapFile) {
+        this.pcapFile = pcapFile;
+    }
+
+    @Override
+    public Channel createChannel(ChannelHandler channelHandler)
+        throws PlcConnectionException {
+        try {
+            final EventLoopGroup workerGroup = new OioEventLoopGroup();
+
+            Bootstrap bootstrap = new Bootstrap();
+            bootstrap.group(workerGroup);
+            bootstrap.channel(PcapSocketChannel.class);
+            bootstrap.option(PcapSocketChannelOption.PACKET_HANDLER, new TcpIpPacketHandler());
+            bootstrap.option(PcapSocketChannelOption.SPEED_FACTOR, 1.000f);
+            bootstrap.handler(channelHandler);
+
+            // Start the client.
+            ChannelFuture f = bootstrap.connect(new PcapSocketAddress(pcapFile)).sync();
+            f.addListener(new GenericFutureListener<Future<? super Void>>() {
+                @Override public void operationComplete(Future<? super Void> future) throws Exception {
+                    if (!future.isSuccess()) {
+                        logger.info("Unable to connect, shutting down worker thread.");
+                        workerGroup.shutdownGracefully();
+                    }
+                }
+            });
+            // Wait for sync
+            f.sync();
+            f.awaitUninterruptibly();
+            // Wait till the session is finished initializing.
+            return f.channel();
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new PlcConnectionException("Error creating channel.", e);
+        }
+    }
+
+    @Override
+    public void ping() throws PlcException {
+        // Raw-Sockets are absolutely passive, so there is nothing to do for a ping.
+    }
+
+    public File getPcapFile() {
+        return pcapFile;
+    }
+
+}
diff --git a/plc4j/protocols/driver-bases/pom.xml b/plc4j/protocols/driver-bases/pom.xml
index c6b4c5d..0034532 100644
--- a/plc4j/protocols/driver-bases/pom.xml
+++ b/plc4j/protocols/driver-bases/pom.xml
@@ -35,6 +35,7 @@
 
   <modules>
     <module>base</module>
+    <module>pcap-socket</module>
     <module>raw-socket</module>
     <module>serial</module>
     <module>tcp</module>
diff --git a/plc4j/utils/pcap-sockets/pom.xml b/plc4j/utils/pcap-sockets/pom.xml
new file mode 100644
index 0000000..4064c47
--- /dev/null
+++ b/plc4j/utils/pcap-sockets/pom.xml
@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You under the Apache License, Version 2.0
+  (the "License"); you may not use this file except in compliance with
+  the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <modelVersion>4.0.0</modelVersion>
+
+  <parent>
+    <groupId>org.apache.plc4x</groupId>
+    <artifactId>plc4j-utils</artifactId>
+    <version>0.5.0-SNAPSHOT</version>
+  </parent>
+
+  <artifactId>plc4j-utils-pcap-sockets</artifactId>
+
+  <name>PLC4J: Utils: Pcap-Sockets</name>
+  <description>An implementation of a Netty Channel that uses a PCAP packet dump as input and simulates a raw socket device by replaying the recorded traffic.</description>
+
+  <dependencies>
+    <dependency>
+      <groupId>io.netty</groupId>
+      <artifactId>netty-buffer</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>io.netty</groupId>
+      <artifactId>netty-transport</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.pcap4j</groupId>
+      <artifactId>pcap4j-core</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.pcap4j</groupId>
+      <artifactId>pcap4j-packetfactory-static</artifactId>
+      <scope>runtime</scope>
+    </dependency>
+
+    <dependency>
+      <groupId>org.apache.commons</groupId>
+      <artifactId>commons-lang3</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.slf4j</groupId>
+      <artifactId>slf4j-api</artifactId>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-dependency-plugin</artifactId>
+        <configuration>
+          <usedDependencies>
+            <usedDependency>org.pcap4j:pcap4j-packetfactory-static</usedDependency>
+          </usedDependencies>
+        </configuration>
+      </plugin>
+
+      <!-- This is currently a work in progress ... skip this till it reaches a slightly more mature state -->
+      <plugin>
+        <groupId>org.sonarsource.scanner.maven</groupId>
+        <artifactId>sonar-maven-plugin</artifactId>
+        <configuration>
+          <skip>true</skip>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+
+</project>
\ No newline at end of file
diff --git a/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/PcapSocketException.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/PcapSocketException.java
new file mode 100644
index 0000000..6806adf
--- /dev/null
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/PcapSocketException.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2014 The Netty Project
+ *
+ * The Netty Project licenses this file to you under the Apache License,
+ * version 2.0 (the "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at:
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.plc4x.java.utils.pcapsockets;
+
+public class PcapSocketException extends Exception {
+
+    private static final long serialVersionUID = 1L;
+
+    public PcapSocketException() {
+        super();
+    }
+
+    public PcapSocketException(String message) {
+        super(message);
+    }
+
+    public PcapSocketException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+}
diff --git a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PacketHandler.java
similarity index 54%
copy from plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
copy to plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PacketHandler.java
index 64a1e5b..0aae4be 100644
--- a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PacketHandler.java
@@ -16,22 +16,12 @@ KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */
-package org.apache.plc4x.java.utils.rawsockets.netty;
+package org.apache.plc4x.java.utils.pcapsockets.netty;
 
-import org.pcap4j.packet.*;
+import org.pcap4j.packet.Packet;
 
-public class TcpIpPacketHandler implements PacketHandler {
+public interface PacketHandler {
 
-    @Override
-    public byte[] getData(Packet packet) {
-        EthernetPacket ethernetPacket = (EthernetPacket) packet;
-        IpV4Packet ipv4Packet = (IpV4Packet) ethernetPacket.getPayload();
-        TcpPacket tcpPacket = (TcpPacket) ipv4Packet.getPayload();
-        if(tcpPacket.getPayload() instanceof UnknownPacket) {
-            UnknownPacket unknownPacket = (UnknownPacket) tcpPacket.getPayload();
-            return tcpPacket.getPayload().getRawData();
-        }
-        return new byte[0];
-    }
+    byte[] getData(Packet packet);
 
 }
diff --git a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketAddress.java
similarity index 54%
copy from plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
copy to plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketAddress.java
index 64a1e5b..78310e2 100644
--- a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketAddress.java
@@ -16,22 +16,22 @@ KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */
-package org.apache.plc4x.java.utils.rawsockets.netty;
-
-import org.pcap4j.packet.*;
-
-public class TcpIpPacketHandler implements PacketHandler {
-
-    @Override
-    public byte[] getData(Packet packet) {
-        EthernetPacket ethernetPacket = (EthernetPacket) packet;
-        IpV4Packet ipv4Packet = (IpV4Packet) ethernetPacket.getPayload();
-        TcpPacket tcpPacket = (TcpPacket) ipv4Packet.getPayload();
-        if(tcpPacket.getPayload() instanceof UnknownPacket) {
-            UnknownPacket unknownPacket = (UnknownPacket) tcpPacket.getPayload();
-            return tcpPacket.getPayload().getRawData();
-        }
-        return new byte[0];
+package org.apache.plc4x.java.utils.pcapsockets.netty;
+
+import java.io.File;
+import java.net.SocketAddress;
+
+public class PcapSocketAddress extends SocketAddress {
+    private static final long serialVersionUID = 1L;
+
+    private File pcapFile;
+
+    public PcapSocketAddress(File pcapFile) {
+        this.pcapFile = pcapFile;
+    }
+
+    public File getPcapFile() {
+        return pcapFile;
     }
 
 }
diff --git a/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannel.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannel.java
new file mode 100644
index 0000000..aff7ec0
--- /dev/null
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannel.java
@@ -0,0 +1,275 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.plc4x.java.utils.pcapsockets.netty;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelConfig;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelPromise;
+import io.netty.channel.oio.OioByteStreamChannel;
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.plc4x.java.utils.pcapsockets.PcapSocketException;
+import org.pcap4j.core.*;
+import org.pcap4j.packet.Packet;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.SocketAddress;
+import java.net.SocketTimeoutException;
+import java.sql.Timestamp;
+
+/**
+ * TODO write comment
+ *
+ * @author julian
+ * Created by julian on 2019-08-16
+ */
+public class PcapSocketChannel extends OioByteStreamChannel {
+
+    private static final Logger logger = LoggerFactory.getLogger(PcapSocketChannel.class);
+
+    private final PcapSocketChannelConfig config;
+
+    private PcapSocketAddress remoteRawSocketAddress;
+    private SocketAddress localAddress;
+    private PcapHandle handle;
+    private Thread loopThread;
+
+    public PcapSocketChannel() {
+        super(null);
+        config = new PcapSocketChannelConfig(this);
+    }
+
+    @Override
+    protected boolean isInputShutdown() {
+        return false;
+    }
+
+    @Override
+    protected ChannelFuture shutdownInput() {
+        throw new NotImplementedException("");
+    }
+
+    @Override
+    protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
+        if(!(remoteAddress instanceof PcapSocketAddress)) {
+            logger.error("Expecting remote address of type PcapSocketAddress");
+            pipeline().fireExceptionCaught(
+                new PcapSocketException("Expecting remote address of type PcapSocketAddress"));
+            return;
+        }
+        this.localAddress = localAddress;
+        remoteRawSocketAddress = (PcapSocketAddress) remoteAddress;
+
+
+        // Get a handle to the network-device and open it.
+        File pcapFile = remoteRawSocketAddress.getPcapFile();
+        if(!pcapFile.exists()) {
+            logger.error(String.format("Couldn't find PCAP capture file at: %s", pcapFile.getAbsolutePath()));
+            pipeline().fireExceptionCaught(new PcapSocketException(String.format(
+                "Couldn't find PCAP capture file at: %s", pcapFile.getAbsolutePath())));
+            return;
+        }
+        if(logger.isDebugEnabled()) {
+            logger.debug(String.format("Opening PCAP capture file at: %s", pcapFile.getAbsolutePath()));
+        }
+        handle = Pcaps.openOffline(remoteRawSocketAddress.getPcapFile().getAbsolutePath(),
+            PcapHandle.TimestampPrecision.NANO);
+
+        // Create a buffer where the raw socket worker can send data to.
+        ByteBuf buffer = Unpooled.buffer();
+
+        // Start a thread that processes the callbacks from the raw socket and simply
+        // forwards the bytes read to the buffer.
+        loopThread = new Thread(() -> {
+            try {
+                handle.loop(-1, new PacketListener() {
+                    private Timestamp lastPacketTime = null;
+
+                    @Override
+                    public void gotPacket(Packet packet) {
+                        Timestamp curPacketTime = handle.getTimestamp();
+
+                        // If last-time is not null, wait for the given number of nano-seconds.
+                        if(lastPacketTime != null) {
+                            int numMicrosecondsSleep = curPacketTime.getNanos() - lastPacketTime.getNanos();
+                            nanoSecondSleep(numMicrosecondsSleep);
+                        }
+
+                        // Send the bytes to the netty pipeline.
+                        buffer.writeBytes(config.getPacketHandler().getData(packet));
+
+                        // Remember the timestamp of the current packet.
+                        lastPacketTime = curPacketTime;
+                    }
+                });
+            } catch (PcapNativeException | NotOpenException e) {
+                logger.error("PCAP loop thread died!", e);
+                pipeline().fireExceptionCaught(e);
+            } catch (InterruptedException e) {
+                logger.warn("PCAP loop thread was interrupted (hopefully intentionally)", e);
+                Thread.currentThread().interrupt();
+            }
+        });
+        loopThread.start();
+
+        // Right now we're using an output stream that simply discards everything.
+        // This is ok while implementing passive drivers for protocols, however as
+        // soon as we start implementing ethernet layer protocols, we'll have to also
+        // be able to actually send data. The PcapInputStream simply acts as a
+        // breaking point if no packets are coming in and the read operation would
+        // simply block indefinitely.
+        activate(new PcapInputStream(buffer), new DiscardingOutputStream());
+    }
+
+    @Override
+    protected SocketAddress localAddress0() {
+        return localAddress;
+    }
+
+    @Override
+    protected SocketAddress remoteAddress0() {
+        return remoteRawSocketAddress;
+    }
+
+    @Override
+    protected void doBind(SocketAddress localAddress) {
+        throw new UnsupportedOperationException("Not implemented");
+    }
+
+    @Override
+    protected void doDisconnect() {
+        this.loopThread.interrupt();
+        if (this.handle != null) {
+            this.handle.close();
+        }
+    }
+
+    @Override protected int doReadBytes(ByteBuf buf) throws Exception {
+        if (handle == null || !handle.isOpen()) {
+            return -1;
+        }
+        try {
+            return super.doReadBytes(buf);
+        } catch (SocketTimeoutException ignored) {
+            return 0;
+        }
+    }
+
+    @Override
+    public ChannelConfig config() {
+        return this.config;
+    }
+
+    @Override
+    public boolean isOpen() {
+        return true;
+    }
+
+    @Override
+    protected AbstractUnsafe newUnsafe() {
+        return new RawSocketUnsafe();
+    }
+
+    /**
+     * Use a busy wait loop for waiting. This should never be used in a
+     * production environment as it consumes 100% of one CPU core time to
+     * achieve, however it's the only accurate way to sleep for less than
+     * a millisecond.
+     *
+     * @param numNanos number of nano-seconds to wait.
+     */
+    private void nanoSecondSleep(long numNanos) {
+        long endTime = System.nanoTime() + numNanos;
+        while(endTime > System.nanoTime()) {
+            // Do Nothing ...
+        }
+    }
+
+    /**
+     * This output stream simply discards anything it should send.
+     */
+    private static class DiscardingOutputStream extends OutputStream {
+        @Override
+        public void write(int b) throws IOException {
+            // discard
+            logger.debug("Discarding {}", b);
+        }
+
+        @Override
+        public void write(byte[] b, int off, int len) {
+            logger.debug("Discarding {}", b);
+        }
+    }
+
+    /**
+     * InputStream that fulfills the contract of Netty for read operations to timeout.
+     * Without this the InputStream would simply block indefinitely which would block
+     * the entire IO module.
+     */
+    private static class PcapInputStream extends InputStream {
+        final ByteBuf buf;
+
+        private PcapInputStream(ByteBuf buf) {
+            this.buf = buf;
+        }
+
+        @Override
+        public int available() {
+            return buf.readableBytes();
+        }
+
+        @Override
+        public int read() throws IOException {
+            // Timeout 10 ms
+            final long timeout = System.nanoTime() + 10_000;
+            // Yes, this could make the thread go nuts in case of no data,
+            // but the Netty guys are doing it the same way and there probably
+            // is a reason for it ;-)
+            while (System.nanoTime() < timeout) {
+                if (buf.readableBytes() > 0) {
+                    return buf.readByte() & 0xFF;
+                }
+            }
+            throw new SocketTimeoutException();
+        }
+    }
+
+    /**
+     * Internal helper to wrap access to unsafe operations (Only used internally by netty)
+     */
+    private class RawSocketUnsafe extends AbstractUnsafe {
+        @Override
+        public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
+            try {
+                doConnect(remoteAddress, localAddress);
+                pipeline().fireChannelActive();
+                promise.setSuccess();
+            } catch (Exception e) {
+                promise.setFailure(e);
+            }
+        }
+    }
+}
diff --git a/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelConfig.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelConfig.java
new file mode 100644
index 0000000..e1ddb23
--- /dev/null
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelConfig.java
@@ -0,0 +1,69 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License.  You may obtain a copy of the License at
+
+  http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied.  See the License for the
+specific language governing permissions and limitations
+under the License.
+*/
+package org.apache.plc4x.java.utils.pcapsockets.netty;
+
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelConfig;
+import io.netty.channel.ChannelOption;
+import io.netty.channel.DefaultChannelConfig;
+import org.pcap4j.packet.Packet;
+
+import java.util.Map;
+
+public class PcapSocketChannelConfig extends DefaultChannelConfig implements ChannelConfig {
+
+    private PacketHandler packetHandler;
+
+    public PcapSocketChannelConfig(Channel channel) {
+        super(channel);
+        packetHandler = new PacketHandler() {
+            @Override
+            public byte[] getData(Packet packet) {
+                return packet.getRawData();
+            }
+        };
+    }
+
+    @Override
+    public Map<ChannelOption<?>, Object> getOptions() {
+        return getOptions(super.getOptions(), PcapSocketChannelOption.PACKET_HANDLER);
+    }
+
+    @Override
+    public <T> boolean setOption(ChannelOption<T> option, T value) {
+        if(option == PcapSocketChannelOption.PACKET_HANDLER) {
+            if(value instanceof PacketHandler) {
+                packetHandler = (PacketHandler) value;
+                return true;
+            }
+            return false;
+        } else {
+            return super.setOption(option, value);
+        }
+    }
+
+    public void setPacketHandler(PacketHandler packetHandler) {
+        this.packetHandler = packetHandler;
+    }
+
+    public PacketHandler getPacketHandler() {
+        return packetHandler;
+    }
+
+}
diff --git a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelOption.java
similarity index 54%
copy from plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
copy to plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelOption.java
index 64a1e5b..71ed72e 100644
--- a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelOption.java
@@ -16,22 +16,24 @@ KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */
-package org.apache.plc4x.java.utils.rawsockets.netty;
-
-import org.pcap4j.packet.*;
-
-public class TcpIpPacketHandler implements PacketHandler {
-
-    @Override
-    public byte[] getData(Packet packet) {
-        EthernetPacket ethernetPacket = (EthernetPacket) packet;
-        IpV4Packet ipv4Packet = (IpV4Packet) ethernetPacket.getPayload();
-        TcpPacket tcpPacket = (TcpPacket) ipv4Packet.getPayload();
-        if(tcpPacket.getPayload() instanceof UnknownPacket) {
-            UnknownPacket unknownPacket = (UnknownPacket) tcpPacket.getPayload();
-            return tcpPacket.getPayload().getRawData();
-        }
-        return new byte[0];
+package org.apache.plc4x.java.utils.pcapsockets.netty;
+
+import io.netty.channel.ChannelOption;
+
+public class PcapSocketChannelOption<T> extends ChannelOption<T> {
+
+    public static final ChannelOption<PacketHandler> PACKET_HANDLER =
+        ChannelOption.valueOf(PacketHandler.class, "PACKET_HANDLER");
+
+    /**
+     * Option to increase/decrease the replay speed of the recording.
+     * 1.0 being real-time.
+     */
+    public static final ChannelOption<Float> SPEED_FACTOR =
+        ChannelOption.valueOf(Float.class, "SPEED_FACTOR");
+
+    protected PcapSocketChannelOption() {
+        super(null);
     }
 
 }
diff --git a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/TcpIpPacketHandler.java
similarity index 85%
copy from plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
copy to plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/TcpIpPacketHandler.java
index 64a1e5b..076c75e 100644
--- a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/TcpIpPacketHandler.java
@@ -16,10 +16,14 @@ KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */
-package org.apache.plc4x.java.utils.rawsockets.netty;
+package org.apache.plc4x.java.utils.pcapsockets.netty;
 
 import org.pcap4j.packet.*;
 
+/**
+ * Little helper to automatically unwrap TCP packets to only
+ * pass along the payload and not the raw Ethernet packet.
+ */
 public class TcpIpPacketHandler implements PacketHandler {
 
     @Override
@@ -29,7 +33,7 @@ public class TcpIpPacketHandler implements PacketHandler {
         TcpPacket tcpPacket = (TcpPacket) ipv4Packet.getPayload();
         if(tcpPacket.getPayload() instanceof UnknownPacket) {
             UnknownPacket unknownPacket = (UnknownPacket) tcpPacket.getPayload();
-            return tcpPacket.getPayload().getRawData();
+            return unknownPacket.getRawData();
         }
         return new byte[0];
     }
diff --git a/plc4j/utils/pom.xml b/plc4j/utils/pom.xml
index 59de591..cf95b52 100644
--- a/plc4j/utils/pom.xml
+++ b/plc4j/utils/pom.xml
@@ -34,11 +34,16 @@
   <description>A collection of utilities used in multiple modules.</description>
 
   <modules>
+    <!-- Base module for all types of PLC4X drivers -->
     <module>driver-base-java</module>
-    <module>protocol-test-utils</module>
+    <!-- Non-default input options -->
     <module>raw-sockets</module>
+    <module>pcap-sockets</module>
+    <!-- Utilities for building tests -->
     <module>test-utils</module>
+    <module>protocol-test-utils</module>
 
+    <!-- Utilities used externally by users -->
     <module>connection-pool</module>
     <module>opm</module>
     <module>scraper</module>
diff --git a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
index 64a1e5b..b5be164 100644
--- a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
+++ b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/TcpIpPacketHandler.java
@@ -20,6 +20,10 @@ package org.apache.plc4x.java.utils.rawsockets.netty;
 
 import org.pcap4j.packet.*;
 
+/**
+ * Little helper to automatically unwrap TCP packets to only
+ * pass along the payload and not the raw Ethernet packet.
+ */
 public class TcpIpPacketHandler implements PacketHandler {
 
     @Override
@@ -29,7 +33,7 @@ public class TcpIpPacketHandler implements PacketHandler {
         TcpPacket tcpPacket = (TcpPacket) ipv4Packet.getPayload();
         if(tcpPacket.getPayload() instanceof UnknownPacket) {
             UnknownPacket unknownPacket = (UnknownPacket) tcpPacket.getPayload();
-            return tcpPacket.getPayload().getRawData();
+            return unknownPacket.getRawData();
         }
         return new byte[0];
     }
diff --git a/plc4j/utils/raw-sockets/src/remote-resources/META-INF/LICENSE b/plc4j/utils/raw-sockets/src/remote-resources/META-INF/LICENSE
index 1a8a165..12e360a 100644
--- a/plc4j/utils/raw-sockets/src/remote-resources/META-INF/LICENSE
+++ b/plc4j/utils/raw-sockets/src/remote-resources/META-INF/LICENSE
@@ -2,8 +2,5 @@
 ----------------------------------------------
 
 The Files:
-src/main/java/org/apache/plc4x/java/utils/rawsockets/RawSocketListener.java
-src/main/java/org/apache/plc4x/java/utils/rawsockets/RawIpSocket.java
-src/main/java/org/apache/plc4x/java/utils/rawsockets/RawSocketException.java
-src/main/java/org/apache/plc4x/java/utils/rawsockets/RawSocketListener.java
+src/main/java/org/apache/plc4x/java/utils/rawsockets/atic/RawIpSocket.java
 Are copyrighted by the The Netty Project which is distributed under the Apache 2.0 license.
\ No newline at end of file


[plc4x] 02/03: - Added a missing argument to the virtual field template.

Posted by cd...@apache.org.
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

commit 33939616ae70e7f3e8b2b908c6a2ab55d1c2e922
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Wed Sep 4 11:41:39 2019 +0200

    - Added a missing argument to the virtual field template.
---
 .../language-java/src/main/resources/templates/java/pojo-template.ftlh  | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/build-utils/language-java/src/main/resources/templates/java/pojo-template.ftlh b/build-utils/language-java/src/main/resources/templates/java/pojo-template.ftlh
index c8c5fb6..094a9ea 100644
--- a/build-utils/language-java/src/main/resources/templates/java/pojo-template.ftlh
+++ b/build-utils/language-java/src/main/resources/templates/java/pojo-template.ftlh
@@ -100,7 +100,7 @@ public<#if type.abstract> abstract</#if> class ${typeName}<#if type.parentType??
 </#list>
 <#list type.virtualFields as field>
     public ${helper.getLanguageTypeNameForField(field)}<#if field.loopType??>[]</#if> get${field.name?cap_first}() {
-        return (${helper.getLanguageTypeNameForField(field)}) (${helper.toDeserializationExpression(field.valueExpression)});;
+        return (${helper.getLanguageTypeNameForField(field)}) (${helper.toDeserializationExpression(field.valueExpression, type.parserArguments)});
     }
 
 </#list>