JulianFeinauer commented on a change in pull request #57: Feature/plc4 x 108
ping method
URL: https://github.com/apache/incubator-plc4x/pull/57#discussion_r270356482
##########
File path:
plc4j/protocols/driver-bases/base/src/main/java/org/apache/plc4x/java/base/connection/AbstractPlcConnection.java
##########
@@ -57,6 +67,51 @@ public boolean canSubscribe() {
return false;
}
+ /**
+ * The default implementation uses the {@link #ping(int)} method.
+ * Drivers that want to implement a more specific version have to overide
it.
+ */
+ @Override
+ public boolean isConnected() {
+ return ping(PING_TIMEOUT_MS);
+ }
+
+ /**
+ * Method that sends a test-request or ping to the PLC to check if the PLC
is still there.
+ * In most cases this method should only be used from the {@link
#isConnected()} method.
+ * This method can only be used if ghe {@link #getInetSocketAddress()}
returns a Socket Adress.
+ * Otherwise it throws a {@link NotImplementedException} to inform the
user about that.
+ */
+ protected boolean ping(int timeout) {
+ Optional<InetSocketAddress> address = getInetSocketAddress();
+ if (!address.isPresent()) {
+ throw new NotImplementedException("Tries to check the connection
with ping, " +
+ "but no Socket Address is given!");
+ }
+ Socket s = null;
+ try {
+ s = new Socket();
+ s.connect(address.get(), timeout);
+ return true;
+ } catch (Exception e) {
+ LOGGER.debug("Unable to ping PLC", e);
+ return false;
+ } finally {
+ if (s != null) {
+ try {
+ s.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ /**
+ * Strategy Pattern method for the {@link #ping(int)} method.
+ * If a driver has no Inet Socket adress, it has to return an Empty
Optional, never null.
Review comment:
Indeed this is redundandent. But I'm a bit "conservative" with these Java 8
features as there may be people not so used to them so I think its okay to make
it *really* clear :)
Better safe than sorry.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services