You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by sr...@apache.org on 2023/07/31 17:37:29 UTC
[plc4x] branch develop updated: refactor(plc4j/opcua): slight cleanup and qc fixing
This is an automated email from the ASF dual-hosted git repository.
sruehl 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 c9efef33bc refactor(plc4j/opcua): slight cleanup and qc fixing
c9efef33bc is described below
commit c9efef33bc58128a388a176eae89be6fccbe1766
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Mon Jul 31 19:37:17 2023 +0200
refactor(plc4j/opcua): slight cleanup and qc fixing
---
.../apache/plc4x/java/opcua/OpcuaPlcDriver.java | 62 ++--
.../java/opcua/config/OpcuaConfiguration.java | 35 +-
.../java/opcua/context/CertificateGenerator.java | 9 +-
.../java/opcua/context/CertificateKeyPair.java | 14 +-
.../java/opcua/context/EncryptionHandler.java | 19 +-
.../plc4x/java/opcua/context/SecureChannel.java | 352 ++++++++++++---------
.../plc4x/java/opcua/optimizer/OpcuaOptimizer.java | 1 -
.../java/opcua/protocol/OpcuaProtocolLogic.java | 10 +-
.../opcua/protocol/OpcuaSubscriptionHandle.java | 47 +--
.../plc4x/java/opcua/tag/OpcuaPlcTagHandler.java | 2 -
.../org/apache/plc4x/java/opcua/tag/OpcuaTag.java | 2 +-
11 files changed, 288 insertions(+), 265 deletions(-)
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java
index 10cbe9dec1..1a0eed77a4 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/OpcuaPlcDriver.java
@@ -18,41 +18,39 @@
*/
package org.apache.plc4x.java.opcua;
+import io.netty.buffer.ByteBuf;
import org.apache.plc4x.java.api.PlcConnection;
import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
-import org.apache.plc4x.java.opcua.tag.OpcuaTag;
-import org.apache.plc4x.java.opcua.tag.OpcuaPlcTagHandler;
+import org.apache.plc4x.java.opcua.config.OpcuaConfiguration;
import org.apache.plc4x.java.opcua.optimizer.OpcuaOptimizer;
-import org.apache.plc4x.java.opcua.protocol.*;
-import org.apache.plc4x.java.opcua.config.*;
-import org.apache.plc4x.java.opcua.readwrite.*;
+import org.apache.plc4x.java.opcua.protocol.OpcuaProtocolLogic;
+import org.apache.plc4x.java.opcua.readwrite.OpcuaAPU;
+import org.apache.plc4x.java.opcua.tag.OpcuaPlcTagHandler;
+import org.apache.plc4x.java.opcua.tag.OpcuaTag;
+import org.apache.plc4x.java.spi.configuration.Configuration;
import org.apache.plc4x.java.spi.configuration.ConfigurationFactory;
import org.apache.plc4x.java.spi.connection.*;
import org.apache.plc4x.java.spi.transport.Transport;
import org.apache.plc4x.java.spi.values.PlcValueHandler;
-import org.apache.plc4x.java.spi.configuration.Configuration;
-import org.apache.plc4x.java.spi.connection.GeneratedDriverBase;
-import io.netty.buffer.ByteBuf;
import java.util.ServiceLoader;
+import java.util.function.ToIntFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import java.util.function.ToIntFunction;
-
import static org.apache.plc4x.java.spi.configuration.ConfigurationFactory.configure;
public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
public static final Pattern INET_ADDRESS_PATTERN = Pattern.compile("(:(?<transportCode>[a-z0-9]*))?://" +
- "(?<transportHost>[\\w.-]+)(:" +
- "(?<transportPort>\\d*))?");
+ "(?<transportHost>[\\w.-]+)(:" +
+ "(?<transportPort>\\d*))?");
public static final Pattern URI_PATTERN = Pattern.compile("^(?<protocolCode>opcua)" +
- INET_ADDRESS_PATTERN +
- "(?<transportEndpoint>[\\w/=]*)[\\?]?" +
- "(?<paramString>([^\\=]+\\=[^\\=&]+[&]?)*)"
- );
+ INET_ADDRESS_PATTERN +
+ "(?<transportEndpoint>[\\w/=]*)[\\?]?" +
+ "(?<paramString>([^\\=]+\\=[^\\=&]+[&]?)*)"
+ );
private boolean isEncrypted;
@@ -76,11 +74,6 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
return "tcp";
}
- @Override
- protected boolean awaitSetupComplete() {
- return true;
- }
-
@Override
protected boolean awaitDiscoverComplete() {
return isEncrypted;
@@ -101,11 +94,6 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
return true;
}
- @Override
- protected boolean canBrowse() {
- return false;
- }
-
@Override
protected OpcuaOptimizer getOptimizer() {
return new OpcuaOptimizer();
@@ -152,7 +140,7 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
final String paramString = matcher.group("paramString");
// Check if the protocol code matches this driver.
- if(!protocolCode.equals(getProtocolCode())) {
+ if (!protocolCode.equals(getProtocolCode())) {
// Actually this shouldn't happen as the DriverManager should have not used this driver in the first place.
throw new PlcConnectionException(
"This driver is not suited to handle this connection string");
@@ -161,7 +149,7 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
// Create the configuration object.
OpcuaConfiguration configuration = (OpcuaConfiguration) new ConfigurationFactory().createConfiguration(
getConfigurationType(), paramString);
- if(configuration == null) {
+ if (configuration == null) {
throw new PlcConnectionException("Unsupported configuration");
}
configuration.setTransportCode(transportCode);
@@ -175,12 +163,12 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
ServiceLoader<Transport> transportLoader = ServiceLoader.load(
Transport.class, Thread.currentThread().getContextClassLoader());
for (Transport curTransport : transportLoader) {
- if(curTransport.getTransportCode().equals(transportCode)) {
+ if (curTransport.getTransportCode().equals(transportCode)) {
transport = curTransport;
break;
}
}
- if(transport == null) {
+ if (transport == null) {
throw new PlcConnectionException("Unsupported transport " + transportCode);
}
@@ -189,7 +177,7 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
// Create an instance of the communication channel which the driver should use.
ChannelFactory channelFactory = transport.createChannelFactory(transportHost + ":" + transportPort);
- if(channelFactory == null) {
+ if (channelFactory == null) {
throw new PlcConnectionException("Unable to get channel factory from url " + transportHost + ":" + transportPort);
}
configure(configuration, channelFactory);
@@ -199,13 +187,13 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
// Make the "await setup complete" overridable via system property.
boolean awaitSetupComplete = awaitSetupComplete();
- if(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE) != null) {
+ if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE) != null) {
awaitSetupComplete = Boolean.parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_SETUP_COMPLETE));
}
// Make the "await disconnect complete" overridable via system property.
boolean awaitDisconnectComplete = awaitDisconnectComplete();
- if(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE) != null) {
+ if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE) != null) {
awaitDisconnectComplete = Boolean.parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCONNECT_COMPLETE));
}
@@ -221,7 +209,7 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
// Make the "await disconnect complete" overridable via system property.
boolean awaitDiscoverComplete = awaitDiscoverComplete();
- if(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCOVER_COMPLETE) != null) {
+ if (System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCOVER_COMPLETE) != null) {
awaitDiscoverComplete = Boolean.parseBoolean(System.getProperty(PROPERTY_PLC4X_FORCE_AWAIT_DISCOVER_COMPLETE));
}
@@ -239,7 +227,9 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
null);
}
- /** Estimate the Length of a Packet */
+ /**
+ * Estimate the Length of a Packet
+ */
public static class ByteLengthEstimator implements ToIntFunction<ByteBuf> {
@Override
public int applyAsInt(ByteBuf byteBuf) {
@@ -251,7 +241,7 @@ public class OpcuaPlcDriver extends GeneratedDriverBase<OpcuaAPU> {
}
@Override
- public OpcuaTag prepareTag(String tagAddress){
+ public OpcuaTag prepareTag(String tagAddress) {
return OpcuaTag.of(tagAddress);
}
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java
index 45c2161ac8..da712da668 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/config/OpcuaConfiguration.java
@@ -21,12 +21,10 @@ package org.apache.plc4x.java.opcua.config;
import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
import org.apache.plc4x.java.opcua.context.CertificateGenerator;
import org.apache.plc4x.java.opcua.context.CertificateKeyPair;
-import org.apache.plc4x.java.opcua.protocol.OpcuaProtocolLogic;
import org.apache.plc4x.java.opcua.readwrite.PascalByteString;
import org.apache.plc4x.java.spi.configuration.Configuration;
import org.apache.plc4x.java.spi.configuration.annotations.ConfigurationParameter;
import org.apache.plc4x.java.spi.configuration.annotations.defaults.BooleanDefaultValue;
-import org.apache.plc4x.java.spi.configuration.annotations.defaults.IntDefaultValue;
import org.apache.plc4x.java.spi.configuration.annotations.defaults.StringDefaultValue;
import org.apache.plc4x.java.transport.tcp.TcpTransportConfiguration;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
@@ -36,11 +34,11 @@ import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.IOException;
import java.nio.file.FileSystems;
-import java.nio.file.Path;
-import java.security.*;
-import java.security.cert.CertificateException;
+import java.security.KeyPair;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.Security;
import java.security.cert.X509Certificate;
public class OpcuaConfiguration implements Configuration, TcpTransportConfiguration {
@@ -123,7 +121,9 @@ public class OpcuaConfiguration implements Configuration, TcpTransportConfigurat
return ckp;
}
- public boolean isEncrypted() { return isEncrypted; }
+ public boolean isEncrypted() {
+ return isEncrypted;
+ }
public void setDiscovery(boolean discovery) {
this.discovery = discovery;
@@ -153,7 +153,9 @@ public class OpcuaConfiguration implements Configuration, TcpTransportConfigurat
this.keyStorePassword = keyStorePassword;
}
- public void setThumbprint(PascalByteString thumbprint) { this.thumbprint = thumbprint; }
+ public void setThumbprint(PascalByteString thumbprint) {
+ this.thumbprint = thumbprint;
+ }
public String getTransportCode() {
return code;
@@ -195,13 +197,15 @@ public class OpcuaConfiguration implements Configuration, TcpTransportConfigurat
this.endpoint = endpoint;
}
- public void setTransportEndpoint(String transportEndpoint) { this.transportEndpoint = transportEndpoint; }
+ public void setTransportEndpoint(String transportEndpoint) {
+ this.transportEndpoint = transportEndpoint;
+ }
public void openKeyStore() throws Exception {
this.isEncrypted = true;
File securityTempDir = new File(certDirectory, "security");
if (!securityTempDir.exists() && !securityTempDir.mkdirs()) {
- throw new PlcConnectionException("Unable to create directory please confirm folder permissions on " + certDirectory);
+ throw new PlcConnectionException("Unable to create directory please confirm folder permissions on " + certDirectory);
}
KeyStore keyStore = KeyStore.getInstance("PKCS12");
File serverKeyStore = securityTempDir.toPath().resolve(keyStoreFile).toFile();
@@ -211,7 +215,7 @@ public class OpcuaConfiguration implements Configuration, TcpTransportConfigurat
ckp = CertificateGenerator.generateCertificate();
LOGGER.info("Creating new KeyStore at {}", serverKeyStore);
keyStore.load(null, keyStorePassword.toCharArray());
- keyStore.setKeyEntry("plc4x-certificate-alias", ckp.getKeyPair().getPrivate(), keyStorePassword.toCharArray(), new X509Certificate[] { ckp.getCertificate() });
+ keyStore.setKeyEntry("plc4x-certificate-alias", ckp.getKeyPair().getPrivate(), keyStorePassword.toCharArray(), new X509Certificate[]{ckp.getCertificate()});
keyStore.store(new FileOutputStream(serverKeyStore), keyStorePassword.toCharArray());
} else {
LOGGER.info("Loading KeyStore at {}", serverKeyStore);
@@ -219,17 +223,18 @@ public class OpcuaConfiguration implements Configuration, TcpTransportConfigurat
String alias = keyStore.aliases().nextElement();
KeyPair kp = new KeyPair(keyStore.getCertificate(alias).getPublicKey(),
(PrivateKey) keyStore.getKey(alias, keyStorePassword.toCharArray()));
- ckp = new CertificateKeyPair(kp,(X509Certificate) keyStore.getCertificate(alias));
+ ckp = new CertificateKeyPair(kp, (X509Certificate) keyStore.getCertificate(alias));
}
}
@Override
public String toString() {
- return "Configuration{" +
- '}';
+ return "Configuration{" + '}';
}
- public void setSenderCertificate(byte[] certificate) { this.senderCertificate = certificate; }
+ public void setSenderCertificate(byte[] certificate) {
+ this.senderCertificate = certificate;
+ }
}
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateGenerator.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateGenerator.java
index 361230baba..5a18f7bede 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateGenerator.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateGenerator.java
@@ -54,6 +54,7 @@ public class CertificateGenerator<PKCS10CertificateRequest> {
kpg = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Security Algorithim is unsupported for certificate");
+ return null;
}
kpg.initialize(2048);
KeyPair caKeys = kpg.generateKeyPair();
@@ -73,7 +74,7 @@ public class CertificateGenerator<PKCS10CertificateRequest> {
final Calendar calender = Calendar.getInstance();
calender.add(Calendar.DATE, -1);
Date startDate = calender.getTime();
- calender.add(Calendar.DATE, 365*25);
+ calender.add(Calendar.DATE, 365 * 25);
Date expiryDate = calender.getTime();
KeyPairGenerator generator = null;
@@ -94,13 +95,13 @@ public class CertificateGenerator<PKCS10CertificateRequest> {
Locale.ENGLISH,
nameBuilder.build(),
subjectPublicKeyInfo
- );
+ );
- GeneralName[] gnArray = new GeneralName[] {new GeneralName(GeneralName.dNSName, InetAddress.getLocalHost().getHostName()), new GeneralName(GeneralName.uniformResourceIdentifier, APPURI)};
+ GeneralName[] gnArray = new GeneralName[]{new GeneralName(GeneralName.dNSName, InetAddress.getLocalHost().getHostName()), new GeneralName(GeneralName.uniformResourceIdentifier, APPURI)};
certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));
certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth}));
- certificateBuilder.addExtension(Extension.keyUsage,false, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature | KeyUsage.keyAgreement | KeyUsage.keyCertSign | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation));
+ certificateBuilder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature | KeyUsage.keyAgreement | KeyUsage.keyCertSign | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation));
certificateBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence(gnArray));
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateKeyPair.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateKeyPair.java
index ae65d8368b..d1d288d393 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateKeyPair.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/CertificateKeyPair.java
@@ -28,16 +28,22 @@ public class CertificateKeyPair {
private final X509Certificate certificate;
private final byte[] thumbprint;
- public CertificateKeyPair(KeyPair keyPair, X509Certificate certificate) throws Exception{
+ public CertificateKeyPair(KeyPair keyPair, X509Certificate certificate) throws Exception {
this.keyPair = keyPair;
this.certificate = certificate;
MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
this.thumbprint = messageDigest.digest(this.certificate.getEncoded());
}
- public KeyPair getKeyPair() { return keyPair; }
+ public KeyPair getKeyPair() {
+ return keyPair;
+ }
- public X509Certificate getCertificate() { return certificate; }
+ public X509Certificate getCertificate() {
+ return certificate;
+ }
- public byte[] getThumbPrint() { return thumbprint; }
+ public byte[] getThumbPrint() {
+ return thumbprint;
+ }
}
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/EncryptionHandler.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/EncryptionHandler.java
index 2cd34d74ed..3fec82c334 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/EncryptionHandler.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/EncryptionHandler.java
@@ -33,7 +33,10 @@ import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
-import java.security.*;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.Security;
+import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
@@ -42,6 +45,8 @@ public class EncryptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(OpcuaProtocolLogic.class);
+ private static int PREENCRYPTED_BLOCK_LENGTH = 190;
+
static {
// Required for SecurityPolicy.Aes256_Sha256_RsaPss
Security.addProvider(new BouncyCastleProvider());
@@ -70,7 +75,6 @@ public class EncryptionHandler {
}
public ReadBuffer encodeMessage(MessagePDU pdu, byte[] message) {
- int PREENCRYPTED_BLOCK_LENGTH = 190;
int unencryptedLength = pdu.getLengthInBytes();
int openRequestLength = message.length;
int positionFirstBlock = unencryptedLength - openRequestLength - 8;
@@ -101,7 +105,7 @@ public class EncryptionHandler {
}
buf.setPos(positionFirstBlock);
encryptBlock(buf, getBytes(buf.getBytes(), positionFirstBlock, positionFirstBlock + preEncryptedLength));
- return new ReadBufferByteBased(buf.getData(), ByteOrder.LITTLE_ENDIAN);
+ return new ReadBufferByteBased(buf.getBytes(), ByteOrder.LITTLE_ENDIAN);
} catch (SerializationException e) {
throw new PlcRuntimeException("Unable to parse apu prior to encrypting");
}
@@ -170,8 +174,7 @@ public class EncryptionHandler {
signature.update(data);
return signature.verify(data, 0, data.length - 256);
} catch (Exception e) {
- e.printStackTrace();
- LOGGER.error("Unable to sign Data");
+ LOGGER.error("Unable to sign Data", e);
return false;
}
}
@@ -199,8 +202,7 @@ public class EncryptionHandler {
}
}
} catch (Exception e) {
- LOGGER.error("Unable to encrypt Data");
- e.printStackTrace();
+ LOGGER.error("Unable to encrypt Data", e);
}
}
@@ -238,8 +240,7 @@ public class EncryptionHandler {
LOGGER.info("----------------Signature Length{}", ss.length);
return ss;
} catch (Exception e) {
- e.printStackTrace();
- LOGGER.error("Unable to sign Data");
+ LOGGER.error("Unable to sign Data", e);
return null;
}
}
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/SecureChannel.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/SecureChannel.java
index f5bc0ccc78..6669230a01 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/SecureChannel.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/context/SecureChannel.java
@@ -181,12 +181,12 @@ public class SecureChannel {
tokenId.get(),
transactionId,
transactionId,
- buffer.getData());
+ buffer.getBytes());
final OpcuaAPU apu;
try {
if (this.isEncrypted) {
- apu = OpcuaAPU.staticParse(encryptionHandler.encodeMessage(messageRequest, buffer.getData()), false);
+ apu = OpcuaAPU.staticParse(encryptionHandler.encodeMessage(messageRequest, buffer.getBytes()), false);
} else {
apu = new OpcuaAPU(messageRequest);
}
@@ -243,15 +243,18 @@ public class SecureChannel {
LOGGER.debug("Opcua Driver running in ACTIVE mode.");
this.context = context;
- OpcuaHelloRequest hello = new OpcuaHelloRequest(FINAL_CHUNK,
+ OpcuaHelloRequest hello = new OpcuaHelloRequest(
+ FINAL_CHUNK,
VERSION,
DEFAULT_RECEIVE_BUFFER_SIZE,
DEFAULT_SEND_BUFFER_SIZE,
DEFAULT_MAX_MESSAGE_SIZE,
DEFAULT_MAX_CHUNK_COUNT,
- this.endpoint);
+ this.endpoint
+ );
- Consumer<Integer> requestConsumer = t -> context.sendRequest(new OpcuaAPU(hello))
+ Consumer<Integer> requestConsumer = t -> context
+ .sendRequest(new OpcuaAPU(hello))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
.check(p -> p.getMessage() instanceof OpcuaAcknowledgeResponse)
.unwrap(p -> (OpcuaAcknowledgeResponse) p.getMessage())
@@ -260,7 +263,6 @@ public class SecureChannel {
}
public void onConnectOpenSecureChannel(ConversationContext<OpcuaAPU> context, OpcuaAcknowledgeResponse opcuaAcknowledgeResponse) {
-
int transactionId = channelTransactionManager.getTransactionIdentifier();
RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
@@ -269,7 +271,8 @@ public class SecureChannel {
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
- NULL_EXTENSION_OBJECT);
+ NULL_EXTENSION_OBJECT
+ );
OpenSecureChannelRequest openSecureChannelRequest;
if (this.isEncrypted) {
@@ -279,7 +282,8 @@ public class SecureChannel {
SecurityTokenRequestType.securityTokenRequestTypeIssue,
MessageSecurityMode.messageSecurityModeSignAndEncrypt,
new PascalByteString(clientNonce.length, clientNonce),
- lifetime);
+ lifetime
+ );
} else {
openSecureChannelRequest = new OpenSecureChannelRequest(
requestHeader,
@@ -287,37 +291,45 @@ public class SecureChannel {
SecurityTokenRequestType.securityTokenRequestTypeIssue,
MessageSecurityMode.messageSecurityModeNone,
NULL_BYTE_STRING,
- lifetime);
+ lifetime
+ );
}
- ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
+ ExpandedNodeId expandedNodeId = new ExpandedNodeId(
+ false, //Namespace Uri Specified
false, //Server Index Specified
- new NodeIdFourByte((short) 0, Integer.parseInt(openSecureChannelRequest.getIdentifier())),
+ new NodeIdFourByte(
+ (short) 0, Integer.parseInt(openSecureChannelRequest.getIdentifier())
+ ),
null,
- null);
+ null
+ );
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
null,
- openSecureChannelRequest);
+ openSecureChannelRequest
+ );
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
extObject.serialize(buffer);
- OpcuaOpenRequest openRequest = new OpcuaOpenRequest(FINAL_CHUNK,
+ OpcuaOpenRequest openRequest = new OpcuaOpenRequest(
+ FINAL_CHUNK,
0,
new PascalString(this.securityPolicy),
this.publicCertificate,
this.thumbprint,
transactionId,
transactionId,
- buffer.getData());
+ buffer.getBytes()
+ );
final OpcuaAPU apu;
if (this.isEncrypted) {
- apu = OpcuaAPU.staticParse(encryptionHandler.encodeMessage(openRequest, buffer.getData()), false);
+ apu = OpcuaAPU.staticParse(encryptionHandler.encodeMessage(openRequest, buffer.getBytes()), false);
} else {
apu = new OpcuaAPU(openRequest);
}
@@ -342,8 +354,9 @@ public class SecureChannel {
LOGGER.debug("Got Secure Response Connection Response");
try {
OpenSecureChannelResponse openSecureChannelResponse = (OpenSecureChannelResponse) message.getBody();
- tokenId.set((int) ((ChannelSecurityToken) openSecureChannelResponse.getSecurityToken()).getTokenId());
- channelId.set((int) ((ChannelSecurityToken) openSecureChannelResponse.getSecurityToken()).getChannelId());
+ ChannelSecurityToken securityToken = (ChannelSecurityToken) openSecureChannelResponse.getSecurityToken();
+ tokenId.set((int) securityToken.getTokenId());
+ channelId.set((int) securityToken.getChannelId());
onConnectCreateSessionRequest(context);
} catch (PlcConnectionException e) {
LOGGER.error("Error occurred while connecting to OPC UA server", e);
@@ -361,32 +374,36 @@ public class SecureChannel {
}
public void onConnectCreateSessionRequest(ConversationContext<OpcuaAPU> context) throws PlcConnectionException {
-
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
+ RequestHeader requestHeader = new RequestHeader(
+ new NodeId(authenticationToken),
getCurrentDateTime(),
0L,
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
- NULL_EXTENSION_OBJECT);
+ NULL_EXTENSION_OBJECT
+ );
LocalizedText applicationName = new LocalizedText(
true,
true,
new PascalString("en"),
- APPLICATION_TEXT);
+ APPLICATION_TEXT
+ );
int noOfDiscoveryUrls = -1;
List<PascalString> discoveryUrls = new ArrayList<>(0);
- ApplicationDescription clientDescription = new ApplicationDescription(APPLICATION_URI,
+ ApplicationDescription clientDescription = new ApplicationDescription(
+ APPLICATION_URI,
PRODUCT_URI,
applicationName,
ApplicationType.applicationTypeClient,
NULL_STRING,
NULL_STRING,
noOfDiscoveryUrls,
- discoveryUrls);
+ discoveryUrls
+ );
CreateSessionRequest createSessionRequest = new CreateSessionRequest(
requestHeader,
@@ -397,13 +414,16 @@ public class SecureChannel {
new PascalByteString(clientNonce.length, clientNonce),
NULL_BYTE_STRING,
120000L,
- 0L);
+ 0L
+ );
- ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
+ ExpandedNodeId expandedNodeId = new ExpandedNodeId(
+ false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(createSessionRequest.getIdentifier())),
null,
- null);
+ null
+ );
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
@@ -436,25 +456,21 @@ public class SecureChannel {
ServiceFault serviceFault = (ServiceFault) unknownExtensionObject;
ResponseHeader header = (ResponseHeader) serviceFault.getResponseHeader();
LOGGER.error("Subscription ServiceFault returned from server with error code, '{}'", header.getServiceResult().toString());
-
}
} catch (PlcConnectionException e) {
LOGGER.error("Error occurred while connecting to OPC UA server");
} catch (ParseException e) {
- LOGGER.error("Unable to parse the returned Subscription response");
- e.printStackTrace();
+ LOGGER.error("Unable to parse the returned Subscription response", e);
}
}
} catch (ParseException e) {
LOGGER.error("Error parsing", e);
}
-
};
Consumer<TimeoutException> timeout = e -> {
- LOGGER.error("Timeout while waiting for subscription response");
- e.printStackTrace();
+ LOGGER.error("Timeout while waiting for subscription response", e);
};
BiConsumer<OpcuaAPU, Throwable> error = (message, e) -> LOGGER.error("Error while waiting for subscription response", e);
@@ -466,7 +482,6 @@ public class SecureChannel {
}
private void onConnectActivateSessionRequest(ConversationContext<OpcuaAPU> context, CreateSessionResponse opcuaMessageResponse, CreateSessionResponse sessionResponse) throws PlcConnectionException, ParseException {
-
senderCertificate = sessionResponse.getServerCertificate().getStringValue();
encryptionHandler.setServerCertificate(EncryptionHandler.getCertificateX509(senderCertificate));
this.senderNonce = sessionResponse.getServerNonce().getStringValue();
@@ -477,7 +492,7 @@ public class SecureChannel {
endpoints[1] = "opc.tcp://" + address.getHostName() + ":" + configuration.getPort() + configuration.getTransportEndpoint();
endpoints[2] = "opc.tcp://" + address.getCanonicalHostName() + ":" + configuration.getPort() + configuration.getTransportEndpoint();
} catch (UnknownHostException e) {
- e.printStackTrace();
+ LOGGER.debug("error getting host", e);
}
selectEndpoint(sessionResponse);
@@ -490,13 +505,15 @@ public class SecureChannel {
int requestHandle = getRequestHandle();
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
+ RequestHeader requestHeader = new RequestHeader(
+ new NodeId(authenticationToken),
getCurrentDateTime(),
requestHandle,
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
- NULL_EXTENSION_OBJECT);
+ NULL_EXTENSION_OBJECT
+ );
SignatureData clientSignature = new SignatureData(NULL_STRING, NULL_BYTE_STRING);
@@ -508,18 +525,22 @@ public class SecureChannel {
0,
null,
userIdentityToken,
- clientSignature);
+ clientSignature
+ );
- ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
+ ExpandedNodeId expandedNodeId = new ExpandedNodeId(
+ false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(activateSessionRequest.getIdentifier())),
null,
- null);
+ null
+ );
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
null,
- activateSessionRequest);
+ activateSessionRequest
+ );
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
@@ -531,36 +552,36 @@ public class SecureChannel {
if (message.getBody() instanceof ServiceFault) {
ServiceFault fault = (ServiceFault) message.getBody();
LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", ((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode(), OpcuaStatusCode.enumForValue(((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode()));
- } else {
- LOGGER.debug("Got Activate Session Response Connection Response");
- try {
- ActivateSessionResponse responseMessage;
-
- ExtensionObjectDefinition unknownExtensionObject = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false).getBody();
- if (unknownExtensionObject instanceof ActivateSessionResponse) {
- responseMessage = (ActivateSessionResponse) unknownExtensionObject;
+ return;
+ }
+ } catch (ParseException e) {
+ LOGGER.error("Error parsing", e);
+ return;
+ }
+ LOGGER.debug("Got Activate Session Response Connection Response");
+ try {
+ ActivateSessionResponse responseMessage;
- long returnedRequestHandle = ((ResponseHeader) responseMessage.getResponseHeader()).getRequestHandle();
- if (!(requestHandle == returnedRequestHandle)) {
- LOGGER.error("Request handle isn't as expected, we might have missed a packet. {} != {}", requestHandle, returnedRequestHandle);
- }
+ ExtensionObjectDefinition unknownExtensionObject = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false).getBody();
+ if (unknownExtensionObject instanceof ActivateSessionResponse) {
+ responseMessage = (ActivateSessionResponse) unknownExtensionObject;
- // Send an event that connection setup is complete.
- keepAlive();
- context.fireConnected();
- } else {
- ServiceFault serviceFault = (ServiceFault) unknownExtensionObject;
- ResponseHeader header = (ResponseHeader) serviceFault.getResponseHeader();
- LOGGER.error("Subscription ServiceFault returned from server with error code, '{}'", header.getServiceResult().toString());
- }
- } catch (ParseException e) {
- LOGGER.error("Unable to parse the returned Subscription response", e);
+ long returnedRequestHandle = ((ResponseHeader) responseMessage.getResponseHeader()).getRequestHandle();
+ if (!(requestHandle == returnedRequestHandle)) {
+ LOGGER.error("Request handle isn't as expected, we might have missed a packet. {} != {}", requestHandle, returnedRequestHandle);
}
+
+ // Send an event that connection setup is complete.
+ keepAlive();
+ context.fireConnected();
+ } else {
+ ServiceFault serviceFault = (ServiceFault) unknownExtensionObject;
+ ResponseHeader header = (ResponseHeader) serviceFault.getResponseHeader();
+ LOGGER.error("Subscription ServiceFault returned from server with error code, '{}'", header.getServiceResult().toString());
}
} catch (ParseException e) {
- LOGGER.error("Error parsing", e);
+ LOGGER.error("Unable to parse the returned Subscription response", e);
}
-
};
Consumer<TimeoutException> timeout = e -> LOGGER.error("Timeout while waiting for activate session response", e);
@@ -581,11 +602,13 @@ public class SecureChannel {
keepAlive.complete(null);
}
- ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
+ ExpandedNodeId expandedNodeId = new ExpandedNodeId(
+ false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, 473),
null,
- null); //Identifier for OpenSecureChannel
+ null
+ ); //Identifier for OpenSecureChannel
RequestHeader requestHeader = new RequestHeader(
new NodeId(authenticationToken),
@@ -594,11 +617,13 @@ public class SecureChannel {
0L,
NULL_STRING,
5000L,
- NULL_EXTENSION_OBJECT);
+ NULL_EXTENSION_OBJECT
+ );
CloseSessionRequest closeSessionRequest = new CloseSessionRequest(
requestHeader,
- true);
+ true
+ );
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
@@ -616,29 +641,28 @@ public class SecureChannel {
if (message.getBody() instanceof ServiceFault) {
ServiceFault fault = (ServiceFault) message.getBody();
LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", ((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode(), OpcuaStatusCode.enumForValue(((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode()));
- } else {
- LOGGER.debug("Got Close Session Response Connection Response");
- try {
- CloseSessionResponse responseMessage;
+ return;
+ }
+ } catch (ParseException e) {
+ LOGGER.error("Error parsing", e);
+ }
+ LOGGER.debug("Got Close Session Response Connection Response");
+ try {
+ CloseSessionResponse responseMessage;
- ExtensionObjectDefinition unknownExtensionObject = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false).getBody();
- if (unknownExtensionObject instanceof CloseSessionResponse) {
- responseMessage = (CloseSessionResponse) unknownExtensionObject;
+ ExtensionObjectDefinition unknownExtensionObject = ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN), false).getBody();
+ if (unknownExtensionObject instanceof CloseSessionResponse) {
+ responseMessage = (CloseSessionResponse) unknownExtensionObject;
- LOGGER.trace("Got Close Session Response Connection Response" + responseMessage);
- onDisconnectCloseSecureChannel(context);
- } else {
- ServiceFault serviceFault = (ServiceFault) unknownExtensionObject;
- ResponseHeader header = (ResponseHeader) serviceFault.getResponseHeader();
- LOGGER.error("Subscription ServiceFault returned from server with error code, '{}'", header.getServiceResult().toString());
- }
- } catch (ParseException e) {
- LOGGER.error("Unable to parse the returned Close Session response");
- e.printStackTrace();
- }
+ LOGGER.trace("Got Close Session Response Connection Response" + responseMessage);
+ onDisconnectCloseSecureChannel(context);
+ } else {
+ ServiceFault serviceFault = (ServiceFault) unknownExtensionObject;
+ ResponseHeader header = (ResponseHeader) serviceFault.getResponseHeader();
+ LOGGER.error("Subscription ServiceFault returned from server with error code, '{}'", header.getServiceResult().toString());
}
} catch (ParseException e) {
- LOGGER.error("Error parsing", e);
+ LOGGER.error("Unable to parse the returned Close Session response", e);
}
};
@@ -654,26 +678,30 @@ public class SecureChannel {
}
private void onDisconnectCloseSecureChannel(ConversationContext<OpcuaAPU> context) {
-
int transactionId = channelTransactionManager.getTransactionIdentifier();
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
+ RequestHeader requestHeader = new RequestHeader(
+ new NodeId(authenticationToken),
getCurrentDateTime(),
0L, //RequestHandle
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
- NULL_EXTENSION_OBJECT);
+ NULL_EXTENSION_OBJECT
+ );
CloseSecureChannelRequest closeSecureChannelRequest = new CloseSecureChannelRequest(requestHeader);
- ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
+ ExpandedNodeId expandedNodeId = new ExpandedNodeId(
+ false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(closeSecureChannelRequest.getIdentifier())),
null,
- null);
+ null
+ );
- OpcuaCloseRequest closeRequest = new OpcuaCloseRequest(FINAL_CHUNK,
+ OpcuaCloseRequest closeRequest = new OpcuaCloseRequest(
+ FINAL_CHUNK,
channelId.get(),
tokenId.get(),
transactionId,
@@ -681,7 +709,9 @@ public class SecureChannel {
new ExtensionObject(
expandedNodeId,
null,
- closeSecureChannelRequest));
+ closeSecureChannelRequest
+ )
+ );
Consumer<Integer> requestConsumer = t -> {
context.sendRequest(new OpcuaAPU(closeRequest))
@@ -695,7 +725,6 @@ public class SecureChannel {
};
channelTransactionManager.submit(requestConsumer, transactionId);
-
}
public void onDiscover(ConversationContext<OpcuaAPU> context) {
@@ -720,20 +749,21 @@ public class SecureChannel {
});
channelTransactionManager.submit(requestConsumer, channelTransactionManager.getTransactionIdentifier());
-
}
public void onDiscoverOpenSecureChannel(ConversationContext<OpcuaAPU> context, OpcuaAcknowledgeResponse opcuaAcknowledgeResponse) {
int transactionId = channelTransactionManager.getTransactionIdentifier();
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
+ RequestHeader requestHeader = new RequestHeader(
+ new NodeId(authenticationToken),
getCurrentDateTime(),
0L, //RequestHandle
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
- NULL_EXTENSION_OBJECT);
+ NULL_EXTENSION_OBJECT
+ );
OpenSecureChannelRequest openSecureChannelRequest = new OpenSecureChannelRequest(
requestHeader,
@@ -744,16 +774,19 @@ public class SecureChannel {
lifetime);
- ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
+ ExpandedNodeId expandedNodeId = new ExpandedNodeId(
+ false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(openSecureChannelRequest.getIdentifier())),
null,
- null);
+ null
+ );
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
null,
- openSecureChannelRequest);
+ openSecureChannelRequest
+ );
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
@@ -766,7 +799,7 @@ public class SecureChannel {
NULL_BYTE_STRING,
transactionId,
transactionId,
- buffer.getData());
+ buffer.getBytes());
Consumer<Integer> requestConsumer = t -> context.sendRequest(new OpcuaAPU(openRequest))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
@@ -788,7 +821,7 @@ public class SecureChannel {
}
}
} catch (ParseException e) {
- e.printStackTrace();
+ LOGGER.debug("error caught", e);
}
});
@@ -799,8 +832,9 @@ public class SecureChannel {
}
public void onDiscoverGetEndpointsRequest(ConversationContext<OpcuaAPU> context, OpcuaOpenResponse opcuaOpenResponse, OpenSecureChannelResponse openSecureChannelResponse) throws PlcConnectionException {
- tokenId.set((int) ((ChannelSecurityToken) openSecureChannelResponse.getSecurityToken()).getTokenId());
- channelId.set((int) ((ChannelSecurityToken) openSecureChannelResponse.getSecurityToken()).getChannelId());
+ ChannelSecurityToken securityToken = (ChannelSecurityToken) openSecureChannelResponse.getSecurityToken();
+ tokenId.set((int) securityToken.getTokenId());
+ channelId.set((int) securityToken.getChannelId());
int transactionId = channelTransactionManager.getTransactionIdentifier();
@@ -812,13 +846,15 @@ public class SecureChannel {
throw new PlcConnectionException("Sequence number isn't as expected, we might have missed a packet. - " + transactionId + " != " + nextSequenceNumber);
}
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
+ RequestHeader requestHeader = new RequestHeader(
+ new NodeId(authenticationToken),
getCurrentDateTime(),
0L,
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
- NULL_EXTENSION_OBJECT);
+ NULL_EXTENSION_OBJECT
+ );
GetEndpointsRequest endpointsRequest = new GetEndpointsRequest(
requestHeader,
@@ -826,18 +862,22 @@ public class SecureChannel {
0,
null,
0,
- null);
+ null
+ );
- ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
+ ExpandedNodeId expandedNodeId = new ExpandedNodeId(
+ false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(endpointsRequest.getIdentifier())),
null,
- null);
+ null
+ );
ExtensionObject extObject = new ExtensionObject(
expandedNodeId,
null,
- endpointsRequest);
+ endpointsRequest
+ );
try {
WriteBufferByteBased buffer = new WriteBufferByteBased(extObject.getLengthInBytes(), org.apache.plc4x.java.spi.generation.ByteOrder.LITTLE_ENDIAN);
@@ -848,7 +888,8 @@ public class SecureChannel {
tokenId.get(),
nextSequenceNumber,
nextRequestId,
- buffer.getData());
+ buffer.getBytes()
+ );
Consumer<Integer> requestConsumer = t -> context.sendRequest(new OpcuaAPU(messageRequest))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
@@ -861,28 +902,28 @@ public class SecureChannel {
if (message.getBody() instanceof ServiceFault) {
ServiceFault fault = (ServiceFault) message.getBody();
LOGGER.error("Failed to connect to opc ua server for the following reason:- {}, {}", ((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode(), OpcuaStatusCode.enumForValue(((ResponseHeader) fault.getResponseHeader()).getServiceResult().getStatusCode()));
- } else {
- LOGGER.debug("Got Create Session Response Connection Response");
- GetEndpointsResponse response = (GetEndpointsResponse) message.getBody();
-
- List<ExtensionObjectDefinition> endpoints = response.getEndpoints();
- for (ExtensionObjectDefinition endpoint : endpoints) {
- EndpointDescription endpointDescription = (EndpointDescription) endpoint;
- if (endpointDescription.getEndpointUrl().getStringValue().equals(this.endpoint.getStringValue()) && endpointDescription.getSecurityPolicyUri().getStringValue().equals(this.securityPolicy)) {
- LOGGER.info("Found OPC UA endpoint {}", this.endpoint.getStringValue());
- this.configuration.setSenderCertificate(endpointDescription.getServerCertificate().getStringValue());
- }
+ return;
+ }
+ LOGGER.debug("Got Create Session Response Connection Response");
+ GetEndpointsResponse response = (GetEndpointsResponse) message.getBody();
+
+ List<ExtensionObjectDefinition> endpoints = response.getEndpoints();
+ for (ExtensionObjectDefinition endpoint : endpoints) {
+ EndpointDescription endpointDescription = (EndpointDescription) endpoint;
+ if (endpointDescription.getEndpointUrl().getStringValue().equals(this.endpoint.getStringValue()) && endpointDescription.getSecurityPolicyUri().getStringValue().equals(this.securityPolicy)) {
+ LOGGER.info("Found OPC UA endpoint {}", this.endpoint.getStringValue());
+ this.configuration.setSenderCertificate(endpointDescription.getServerCertificate().getStringValue());
}
+ }
- try {
- MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
- byte[] digest = messageDigest.digest(this.configuration.getSenderCertificate());
- this.configuration.setThumbprint(new PascalByteString(digest.length, digest));
- } catch (NoSuchAlgorithmException e) {
- LOGGER.error("Failed to find hashing algorithm");
- }
- onDiscoverCloseSecureChannel(context, response);
+ try {
+ MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
+ byte[] digest = messageDigest.digest(this.configuration.getSenderCertificate());
+ this.configuration.setThumbprint(new PascalByteString(digest.length, digest));
+ } catch (NoSuchAlgorithmException e) {
+ LOGGER.error("Failed to find hashing algorithm");
}
+ onDiscoverCloseSecureChannel(context, response);
} catch (ParseException e) {
LOGGER.error("Error parsing", e);
}
@@ -895,26 +936,30 @@ public class SecureChannel {
}
private void onDiscoverCloseSecureChannel(ConversationContext<OpcuaAPU> context, GetEndpointsResponse message) {
-
int transactionId = channelTransactionManager.getTransactionIdentifier();
- RequestHeader requestHeader = new RequestHeader(new NodeId(authenticationToken),
+ RequestHeader requestHeader = new RequestHeader(
+ new NodeId(authenticationToken),
getCurrentDateTime(),
0L, //RequestHandle
0L,
NULL_STRING,
REQUEST_TIMEOUT_LONG,
- NULL_EXTENSION_OBJECT);
+ NULL_EXTENSION_OBJECT
+ );
CloseSecureChannelRequest closeSecureChannelRequest = new CloseSecureChannelRequest(requestHeader);
- ExpandedNodeId expandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
+ ExpandedNodeId expandedNodeId = new ExpandedNodeId(
+ false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, Integer.parseInt(closeSecureChannelRequest.getIdentifier())),
null,
- null);
+ null
+ );
- OpcuaCloseRequest closeRequest = new OpcuaCloseRequest(FINAL_CHUNK,
+ OpcuaCloseRequest closeRequest = new OpcuaCloseRequest(
+ FINAL_CHUNK,
channelId.get(),
tokenId.get(),
transactionId,
@@ -922,7 +967,9 @@ public class SecureChannel {
new ExtensionObject(
expandedNodeId,
null,
- closeSecureChannelRequest));
+ closeSecureChannelRequest
+ )
+ );
Consumer<Integer> requestConsumer = t -> context.sendRequest(new OpcuaAPU(closeRequest))
.expectResponse(OpcuaAPU.class, REQUEST_TIMEOUT)
@@ -999,12 +1046,12 @@ public class SecureChannel {
this.thumbprint,
transactionId,
transactionId,
- buffer.getData());
+ buffer.getBytes());
final OpcuaAPU apu;
if (this.isEncrypted) {
- apu = OpcuaAPU.staticParse(encryptionHandler.encodeMessage(openRequest, buffer.getData()), false);
+ apu = OpcuaAPU.staticParse(encryptionHandler.encodeMessage(openRequest, buffer.getBytes()), false);
} else {
apu = new OpcuaAPU(openRequest);
}
@@ -1032,7 +1079,7 @@ public class SecureChannel {
lifetime = token.getRevisedLifetime();
}
} catch (ParseException e) {
- e.printStackTrace();
+ LOGGER.error("parse exception caught", e);
}
});
channelTransactionManager.submit(requestConsumer, transactionId);
@@ -1092,8 +1139,6 @@ public class SecureChannel {
* @throws PlcRuntimeException - If no endpoint with a compatible policy is found raise and error.
*/
private void selectEndpoint(CreateSessionResponse sessionResponse) throws PlcRuntimeException {
- List<String> returnedEndpoints = new ArrayList<>();
-
// Get a list of the endpoints which match ours.
Stream<EndpointDescription> filteredEndpoints = sessionResponse.getServerEndpoints().stream()
.map(e -> (EndpointDescription) e)
@@ -1130,20 +1175,20 @@ public class SecureChannel {
"Endpoint returned from the server doesn't match the format '{protocol-code}:({transport-code})?//{transport-host}(:{transport-port})(/{transport-endpoint})'");
}
LOGGER.trace("Using Endpoint {} {} {}", matcher.group("transportHost"), matcher.group("transportPort"), matcher.group("transportEndpoint"));
- if (this.configuration.isDiscovery() && !this.endpoints.contains(matcher.group("transportHost"))) {
+ if (configuration.isDiscovery() && !this.endpoints.contains(matcher.group("transportHost"))) {
return false;
}
- if (!this.configuration.getPort().equals(matcher.group("transportPort"))) {
+ if (!configuration.getPort().equals(matcher.group("transportPort"))) {
return false;
}
- if (!this.configuration.getTransportEndpoint().equals(matcher.group("transportEndpoint"))) {
+ if (!configuration.getTransportEndpoint().equals(matcher.group("transportEndpoint"))) {
return false;
}
- if (!this.configuration.isDiscovery()) {
- this.configuration.setHost(matcher.group("transportHost"));
+ if (!configuration.isDiscovery()) {
+ configuration.setHost(matcher.group("transportHost"));
}
return true;
@@ -1181,16 +1226,19 @@ public class SecureChannel {
//If we aren't using authentication tell the server we would like to log in anonymously
AnonymousIdentityToken anonymousIdentityToken = new AnonymousIdentityToken();
- extExpandedNodeId = new ExpandedNodeId(false, //Namespace Uri Specified
+ extExpandedNodeId = new ExpandedNodeId(
+ false, //Namespace Uri Specified
false, //Server Index Specified
new NodeIdFourByte((short) 0, OpcuaNodeIdServices.AnonymousIdentityToken_Encoding_DefaultBinary.getValue()),
null,
- null);
+ null
+ );
return new ExtensionObject(
extExpandedNodeId,
new ExtensionObjectEncodingMask(false, false, true),
- new UserIdentityToken(new PascalString(securityPolicy), anonymousIdentityToken));
+ new UserIdentityToken(new PascalString(securityPolicy), anonymousIdentityToken)
+ );
case userTokenTypeUserName:
//Encrypt the password using the server nonce and server public key
byte[] passwordBytes = this.password == null ? new byte[0] : this.password.getBytes();
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/optimizer/OpcuaOptimizer.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/optimizer/OpcuaOptimizer.java
index 8097c46583..5daec530e7 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/optimizer/OpcuaOptimizer.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/optimizer/OpcuaOptimizer.java
@@ -53,5 +53,4 @@ public class OpcuaOptimizer extends BaseOptimizer{
return processedRequests;
}
-
}
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java
index dd1ea925f9..f8ecec3245 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaProtocolLogic.java
@@ -27,8 +27,8 @@ import org.apache.plc4x.java.api.types.PlcValueType;
import org.apache.plc4x.java.api.value.PlcValue;
import org.apache.plc4x.java.opcua.config.OpcuaConfiguration;
import org.apache.plc4x.java.opcua.context.SecureChannel;
-import org.apache.plc4x.java.opcua.tag.OpcuaTag;
import org.apache.plc4x.java.opcua.readwrite.*;
+import org.apache.plc4x.java.opcua.tag.OpcuaTag;
import org.apache.plc4x.java.spi.ConversationContext;
import org.apache.plc4x.java.spi.Plc4xProtocolBase;
import org.apache.plc4x.java.spi.configuration.HasConfiguration;
@@ -38,8 +38,8 @@ import org.apache.plc4x.java.spi.messages.*;
import org.apache.plc4x.java.spi.messages.utils.ResponseItem;
import org.apache.plc4x.java.spi.model.DefaultPlcConsumerRegistration;
import org.apache.plc4x.java.spi.model.DefaultPlcSubscriptionTag;
-import org.apache.plc4x.java.spi.values.PlcValueHandler;
import org.apache.plc4x.java.spi.values.PlcList;
+import org.apache.plc4x.java.spi.values.PlcValueHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -195,7 +195,7 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
future.complete(new DefaultPlcReadResponse(request, status));
return;
}
- } catch (ParseException|PlcRuntimeException e) {
+ } catch (ParseException | PlcRuntimeException e) {
future.completeExceptionally(new PlcRuntimeException(e));
}
};
@@ -220,7 +220,7 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
return future;
}
- private NodeId generateNodeId(OpcuaTag tag) {
+ static NodeId generateNodeId(OpcuaTag tag) {
NodeId nodeId = null;
if (tag.getIdentifierType() == OpcuaIdentifierType.BINARY_IDENTIFIER) {
nodeId = new NodeId(new NodeIdTwoByte(Short.parseShort(tag.getIdentifier())));
@@ -855,7 +855,7 @@ public class OpcuaProtocolLogic extends Plc4xProtocolBase<OpcuaAPU> implements H
try {
responseMessage = (CreateSubscriptionResponse) ExtensionObject.staticParse(new ReadBufferByteBased(opcuaResponse, ByteOrder.LITTLE_ENDIAN), false).getBody();
} catch (ParseException e) {
- e.printStackTrace();
+ LOGGER.error("error parsing", e);
}
// Pass the response back to the application.
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaSubscriptionHandle.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaSubscriptionHandle.java
index 1650111840..bde3faac13 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaSubscriptionHandle.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/protocol/OpcuaSubscriptionHandle.java
@@ -88,13 +88,13 @@ public class OpcuaSubscriptionHandle extends DefaultPlcSubscriptionHandle {
for (String tagName : this.tagNames) {
final DefaultPlcSubscriptionTag tagDefaultPlcSubscription = (DefaultPlcSubscriptionTag) subscriptionRequest.getTag(tagName);
- NodeId idNode = generateNodeId((OpcuaTag) tagDefaultPlcSubscription.getTag());
+ NodeId idNode = OpcuaProtocolLogic.generateNodeId((OpcuaTag) tagDefaultPlcSubscription.getTag());
ReadValueId readValueId = new ReadValueId(
- idNode,
- 0xD,
- OpcuaProtocolLogic.NULL_STRING,
- new QualifiedName(0, OpcuaProtocolLogic.NULL_STRING));
+ idNode,
+ 0xD,
+ OpcuaProtocolLogic.NULL_STRING,
+ new QualifiedName(0, OpcuaProtocolLogic.NULL_STRING));
MonitoringMode monitoringMode;
switch (tagDefaultPlcSubscription.getPlcSubscriptionType()) {
@@ -114,15 +114,15 @@ public class OpcuaSubscriptionHandle extends DefaultPlcSubscriptionHandle {
long clientHandle = clientHandles.getAndIncrement();
MonitoringParameters parameters = new MonitoringParameters(
- clientHandle,
- (double) cycleTime, // sampling interval
- OpcuaProtocolLogic.NULL_EXTENSION_OBJECT, // filter, null means use default
- 1L, // queue size
- true // discard oldest
+ clientHandle,
+ (double) cycleTime, // sampling interval
+ OpcuaProtocolLogic.NULL_EXTENSION_OBJECT, // filter, null means use default
+ 1L, // queue size
+ true // discard oldest
);
MonitoredItemCreateRequest request = new MonitoredItemCreateRequest(
- readValueId, monitoringMode, parameters);
+ readValueId, monitoringMode, parameters);
requestList.add(request);
}
@@ -443,29 +443,4 @@ public class OpcuaSubscriptionHandle extends DefaultPlcSubscriptionHandle {
return new DefaultPlcConsumerRegistration(plcSubscriber, consumer, this);
}
- /**
- * Given an PLC4X OpcuaTag generate the OPC UA Node Id
- *
- * @param tag - The PLC4X OpcuaTag, this is the tag generated from the OpcuaTag class from the parsed tag string.
- * @return NodeId - Returns an OPC UA Node Id which can be sent over the wire.
- */
- private NodeId generateNodeId(OpcuaTag tag) {
- NodeId nodeId = null;
- if (tag.getIdentifierType() == OpcuaIdentifierType.BINARY_IDENTIFIER) {
- nodeId = new NodeId(new NodeIdTwoByte(Short.parseShort(tag.getIdentifier())));
- } else if (tag.getIdentifierType() == OpcuaIdentifierType.NUMBER_IDENTIFIER) {
- nodeId = new NodeId(new NodeIdNumeric((short) tag.getNamespace(), Long.parseLong(tag.getIdentifier())));
- } else if (tag.getIdentifierType() == OpcuaIdentifierType.GUID_IDENTIFIER) {
- UUID guid = UUID.fromString(tag.getIdentifier());
- byte[] guidBytes = new byte[16];
- System.arraycopy(guid.getMostSignificantBits(), 0, guidBytes, 0, 8);
- System.arraycopy(guid.getLeastSignificantBits(), 0, guidBytes, 8, 8);
- nodeId = new NodeId(new NodeIdGuid((short) tag.getNamespace(), guidBytes));
- } else if (tag.getIdentifierType() == OpcuaIdentifierType.STRING_IDENTIFIER) {
- nodeId = new NodeId(new NodeIdString((short) tag.getNamespace(), new PascalString(tag.getIdentifier())));
- }
- return nodeId;
- }
-
-
}
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/tag/OpcuaPlcTagHandler.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/tag/OpcuaPlcTagHandler.java
index 42e6839ae9..90a6a42bd1 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/tag/OpcuaPlcTagHandler.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/tag/OpcuaPlcTagHandler.java
@@ -22,8 +22,6 @@ import org.apache.plc4x.java.api.exceptions.PlcInvalidTagException;
import org.apache.plc4x.java.api.model.PlcQuery;
import org.apache.plc4x.java.spi.connection.PlcTagHandler;
-/**
- */
public class OpcuaPlcTagHandler implements PlcTagHandler {
@Override
diff --git a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/tag/OpcuaTag.java b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/tag/OpcuaTag.java
index 00f6d816ee..4b92e8a9d1 100644
--- a/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/tag/OpcuaTag.java
+++ b/plc4j/drivers/opcua/src/main/java/org/apache/plc4x/java/opcua/tag/OpcuaTag.java
@@ -25,8 +25,8 @@ import org.apache.plc4x.java.api.model.ArrayInfo;
import org.apache.plc4x.java.api.model.PlcSubscriptionTag;
import org.apache.plc4x.java.api.types.PlcSubscriptionType;
import org.apache.plc4x.java.api.types.PlcValueType;
-import org.apache.plc4x.java.opcua.readwrite.OpcuaIdentifierType;
import org.apache.plc4x.java.opcua.readwrite.OpcuaDataType;
+import org.apache.plc4x.java.opcua.readwrite.OpcuaIdentifierType;
import java.time.Duration;
import java.util.List;