本文代码基于opc-ua-java-stack-1.02-source-code-and-sample-applications-337.2-stable
源码官网链接
package OpcUa;
import org.opcfoundation.ua.core.MessageSecurityMode;
import org.opcfoundation.ua.transport.security.SecurityPolicy;
public class UAParam {
private String applicationName="myClient";
private String url;
private Integer authentication;//0:匿名;1:验证用户名、密码,2:certificate,3:IssuedToken
private String userName;
private String password;
private MessageSecurityMode securityMode;//None;Sign;Sign&Encrypt
private SecurityPolicy securityPolicie;//Basic128Rsa15;Basic256;Basic256Sha256
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getAuthentication() {
return authentication;
}
public void setAuthentication(Integer authentication) {
this.authentication = authentication;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public MessageSecurityMode getSecurityMode() {
return securityMode;
}
public void setSecurityMode(MessageSecurityMode securityMode) {
this.securityMode = securityMode;
}
public SecurityPolicy getSecurityPolicie() {
return securityPolicie;
}
public void setSecurityPolicie(SecurityPolicy securityPolicie) {
this.securityPolicie = securityPolicie;
}
}
package OpcUa;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.opcfoundation.ua.common.ServiceResultException;
import org.opcfoundation.ua.transport.security.Cert;
import org.opcfoundation.ua.transport.security.KeyPair;
import org.opcfoundation.ua.transport.security.PrivKey;
import org.opcfoundation.ua.utils.CertificateUtils;
/**
* Keys for examples
* Keystore.p12 contains 20 RSA keypairs with the following aliases
*
* alias dname
*
* server_8192 CN=server
* server_4096 CN=server
* server_2048 CN=server
* server_1024 CN=server
* server_512 CN=server
*
* client_8192 CN=client
* client_4096 CN=client
* client_2048 CN=client
* client_1024 CN=client
* client_512 CN=client
*
* https_server_8192 CN=https_server
* https_server_4096 CN=https_server
* https_server_2048 CN=https_server
* https_server_1024 CN=https_server
* https_server_512 CN=https_server
*
* https_client_8192 CN=https_client
* https_client_4096 CN=https_client
* https_client_2048 CN=https_client
* https_client_1024 CN=https_client
* https_client_512 CN=https_client
*
* Keystore password is "password".
* Private key passwords are "password".
*
*/
public class ExampleKeys {
private static final String PRIVKEY_PASSWORD = "Opc.Ua";
/**
* Load file certificate and private key from applicationName.der & .pfx - or create ones if they do not exist
* @return the KeyPair composed of the certificate and private key
* @throws ServiceResultException
*/
public static KeyPair getCert1(String applicationName,String hostName,String applicationUri) throws ServiceResultException{
File certFile = new File(applicationName + ".der");
File privKeyFile = new File(applicationName+ ".pem");
try {
Cert myCertificate = Cert.load( certFile );
PrivKey myPrivateKey = PrivKey.load( privKeyFile, PRIVKEY_PASSWORD );
return new KeyPair(myCertificate, myPrivateKey);
} catch (CertificateException e) {
throw new ServiceResultException( e );
} catch (IOException e) {
try {
KeyPair keys = CertificateUtils.createApplicationInstanceCertificate(applicationName, null, applicationUri, 3650, hostName);
keys.getCertificate().save(certFile);
keys.getPrivateKey().save(privKeyFile);
return keys;
} catch (Exception e1) {
throw new ServiceResultException( e1 );
}
} catch (NoSuchAlgorithmException e) {
throw new ServiceResultException( e );
} catch (InvalidKeyException e) {
throw new ServiceResultException( e );
} catch (InvalidKeySpecException e) {
throw new ServiceResultException( e );
} catch (NoSuchPaddingException e) {
throw new ServiceResultException( e );
} catch (InvalidAlgorithmParameterException e) {
throw new ServiceResultException( e );
} catch (IllegalBlockSizeException e) {
throw new ServiceResultException( e );
} catch (BadPaddingException e) {
throw new ServiceResultException( e );
} catch (InvalidParameterSpecException e) {
throw new ServiceResultException( e );
}
}
/**
* Load file certificate and private key from applicationName.der & .pfx - or create ones if they do not exist
* @return the KeyPair composed of the certificate and private key
* @throws ServiceResultException
*/
public static KeyPair getCert(String applicationName)
throws ServiceResultException
{
File certFile = new File(applicationName + ".der");
File privKeyFile = new File(applicationName+ ".pem");
try {
Cert myServerCertificate = Cert.load( certFile );
PrivKey myServerPrivateKey = PrivKey.loadFromKeyStore( privKeyFile, PRIVKEY_PASSWORD );
return new KeyPair(myServerCertificate, myServerPrivateKey);
} catch (CertificateException e) {
throw new ServiceResultException( e );
} catch (IOException e) {
try {
String hostName = InetAddress.getLocalHost().getHostName();
String applicationUri = "urn:"+hostName+":"+applicationName;
KeyPair keys = CertificateUtils.createApplicationInstanceCertificate(applicationName, null, applicationUri, 3650, hostName);
keys.getCertificate().save(certFile);
keys.getPrivateKey().save(privKeyFile);
return keys;
} catch (Exception e1) {
throw new ServiceResultException( e1 );
}
} catch (UnrecoverableKeyException e) {
throw new ServiceResultException( e );
} catch (NoSuchAlgorithmException e) {
throw new ServiceResultException( e );
} catch (KeyStoreException e) {
throw new ServiceResultException( e );
}
}
/**
* Load CA certificate and private key from SampleCA.der & .pfx - or create ones if they do not exist
* @return the KeyPair composed of the certificate and private key
* @throws ServiceResultException
*/
public static KeyPair getCACert()
throws ServiceResultException
{
File certFile = new File("SampleCA.der");
File privKeyFile = new File("SampleCA.pem");
try {
Cert myServerCertificate = Cert.load( certFile );
PrivKey myServerPrivateKey = PrivKey.loadFromKeyStore( privKeyFile, PRIVKEY_PASSWORD );
return new KeyPair(myServerCertificate, myServerPrivateKey);
} catch (CertificateException e) {
throw new ServiceResultException( e );
} catch (IOException e) {
try {
KeyPair keys = CertificateUtils.createIssuerCertificate("SampleCA", 3650, null);
keys.getCertificate().save(certFile);
keys.getPrivateKey().save(privKeyFile, PRIVKEY_PASSWORD);
return keys;
} catch (Exception e1) {
throw new ServiceResultException( e1 );
}
} catch (UnrecoverableKeyException e) {
throw new ServiceResultException( e );
} catch (NoSuchAlgorithmException e) {
throw new ServiceResultException( e );
} catch (KeyStoreException e) {
throw new ServiceResultException( e );
}
}
/**
* Load file certificate and private key from applicationName.der & .pfx - or create ones if they do not exist
* @param applicationName
* @param caKey
* @return the KeyPair composed of the certificate and private key
* @throws ServiceResultException
*/
public static KeyPair getHttpsCert(String applicationName)
throws ServiceResultException
{
File certFile = new File(applicationName + "_https.der");
File privKeyFile = new File(applicationName+ "_https.pem");
try {
Cert myServerCertificate = Cert.load( certFile );
PrivKey myServerPrivateKey = PrivKey.loadFromKeyStore( privKeyFile, PRIVKEY_PASSWORD );
return new KeyPair(myServerCertificate, myServerPrivateKey);
} catch (CertificateException e) {
throw new ServiceResultException( e );
} catch (IOException e) {
try {
KeyPair caCert = CertificateUtils.createIssuerCertificate(applicationName, 3650, null);;//getCACert();
String hostName = InetAddress.getLocalHost().getHostName();
String applicationUri = "urn:"+hostName+":"+applicationName;
KeyPair keys = CertificateUtils.createHttpsCertificate(hostName, applicationUri, 3650, caCert);
keys.getCertificate().save(certFile);
keys.getPrivateKey().save(privKeyFile, PRIVKEY_PASSWORD);
return keys;
} catch (Exception e1) {
throw new ServiceResultException( e1 );
}
} catch (UnrecoverableKeyException e) {
throw new ServiceResultException( e );
} catch (NoSuchAlgorithmException e) {
throw new ServiceResultException( e );
} catch (KeyStoreException e) {
throw new ServiceResultException( e );
}
}
/**
* Open keypair from keystore.p12 used in some of these examples.
*
* Usable aliases are : "server", "client", "https_server", "https_client"
* Usable keysizes are : 8192, 4096, 2048, 1024
*
* @param alias
* @param keysize
* @return
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws UnrecoverableKeyException
*/
// public static KeyPair getKeyPair(String alias, int keysize) throws ServiceResultException {
// try {
// Certificate cert = ks.getCertificate(alias+"_"+keysize);
// Key key = ks.getKey(alias+"_"+keysize, "password".toCharArray());
// KeyPair pair = new KeyPair( new Cert( (X509Certificate) cert ), new PrivKey( (RSAPrivateKey) key ) );
// return pair;
// } catch (KeyStoreException e) {
// throw new ServiceResultException( e );
// } catch (UnrecoverableKeyException e) {
// throw new ServiceResultException( e );
// } catch (NoSuchAlgorithmException e) {
// throw new ServiceResultException( e );
// } catch (CertificateEncodingException e) {
// throw new ServiceResultException( e );
// }
// }
//
// static KeyStore ks;
//
// static {
// try {
// ks = KeyStore.getInstance("pkcs12");
// InputStream is = ExampleKeys.class.getResourceAsStream("keystore.p12");
// try {
// ks.load( is, "password".toCharArray() );
// } catch (NoSuchAlgorithmException e) {
// throw new RuntimeException(e);
// } catch (CertificateException e) {
// throw new RuntimeException(e);
// } catch (IOException e) {
// throw new RuntimeException(e);
// } finally {
// try {
// is.close();
// } catch (IOException e) {
// }
// }
// } catch (KeyStoreException e) {
// throw new RuntimeException(e);
// }
// }
}
package OpcUa;
import static org.opcfoundation.ua.utils.EndpointUtil.selectByProtocol;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.UUID;
import org.opcfoundation.ua.application.Application;
import org.opcfoundation.ua.application.Client;
import org.opcfoundation.ua.application.SessionChannel;
import org.opcfoundation.ua.builtintypes.DataValue;
import org.opcfoundation.ua.builtintypes.DateTime;
import org.opcfoundation.ua.builtintypes.ExpandedNodeId;
import org.opcfoundation.ua.builtintypes.ExtensionObject;
import org.opcfoundation.ua.builtintypes.NodeId;
import org.opcfoundation.ua.builtintypes.QualifiedName;
import org.opcfoundation.ua.builtintypes.StatusCode;
import org.opcfoundation.ua.builtintypes.UnsignedInteger;
import org.opcfoundation.ua.builtintypes.Variant;
import org.opcfoundation.ua.common.ServiceFaultException;
import org.opcfoundation.ua.common.ServiceResultException;
import org.opcfoundation.ua.core.Attributes;
import org.opcfoundation.ua.core.BrowseDescription;
import org.opcfoundation.ua.core.BrowseDirection;
import org.opcfoundation.ua.core.BrowseResponse;
import org.opcfoundation.ua.core.BrowseResult;
import org.opcfoundation.ua.core.BrowseResultMask;
import org.opcfoundation.ua.core.EndpointDescription;
import org.opcfoundation.ua.core.HistoryData;
import org.opcfoundation.ua.core.HistoryReadResponse;
import org.opcfoundation.ua.core.HistoryReadResult;
import org.opcfoundation.ua.core.HistoryReadValueId;
import org.opcfoundation.ua.core.IdType;
import org.opcfoundation.ua.core.MessageSecurityMode;
import org.opcfoundation.ua.core.NodeClass;
import org.opcfoundation.ua.core.ReadRawModifiedDetails;
import org.opcfoundation.ua.core.ReadResponse;
import org.opcfoundation.ua.core.ReadValueId;
import org.opcfoundation.ua.core.ReferenceDescription;
import org.opcfoundation.ua.core.TimestampsToReturn;
import org.opcfoundation.ua.core.WriteResponse;
import org.opcfoundation.ua.core.WriteValue;
import org.opcfoundation.ua.encoding.EncoderContext;
import org.opcfoundation.ua.transport.security.KeyPair;
import org.opcfoundation.ua.transport.security.SecurityPolicy;
import org.opcfoundation.ua.utils.EndpointUtil;
import org.opcfoundation.ua.utils.NumericRange;
import org.opcfoundation.ua.utils.StackUtils;
public class OpcUaUtil {
public static long num = 0;
private final static String url1 = "opc.tcp://xxxxx:53530/OPCUA/SimulationServer";
private final static String url2 = "https://xxxxx:53443/OPCUA/SimulationServer";
private static SessionChannel session = null;
static{
UAParam param = new UAParam();
param.setUrl(url1);//tcp or https
param.setAuthentication(1);
param.setUserName("Cyril");
param.setPassword("123123");
// param.setSecurityMode(MessageSecurityMode.None);
param.setSecurityMode(MessageSecurityMode.SignAndEncrypt);
param.setSecurityPolicie(SecurityPolicy.BASIC256SHA256);
try {
session = getSession(param);
} catch (UnknownHostException | ServiceResultException e) {
e.printStackTrace();
session = null;
}
}
public static SessionChannel getSession() {
return session;
}
public static SessionChannel getSession(UAParam param) throws ServiceResultException, UnknownHostException{
String hostName = InetAddress.getLocalHost().getHostName();
String applicationName = param.getApplicationName();
String applicationUri = "urn:"+hostName+":OPCUA:"+applicationName;
SessionChannel mySession =null;
Application myClientApplication = new Application();
Client myClient = new Client(myClientApplication);
if(param.getSecurityMode()!=null&&!param.getSecurityMode().equals(MessageSecurityMode.None)){
//证书要在Server端信任
KeyPair myClientApplicationInstanceCertificate = ExampleKeys.getCert1(applicationName,hostName,applicationUri);
myClientApplication.setApplicationUri(applicationUri);
myClientApplication.addApplicationInstanceCertificate(myClientApplicationInstanceCertificate);
KeyPair myHttpsCertificate = ExampleKeys.getHttpsCert("httpsClient");
myClientApplication.getHttpsSettings().setKeyPair(myHttpsCertificate);
////////// DISCOVER ENDPOINT /////////
// Discover server's endpoints, and choose one
EndpointDescription[] endpoints = myClient.discoverEndpoints(param.getUrl());
// Filter out all but opc.tcp protocol endpoints
if (param.getUrl().startsWith("opc.tcp")){
endpoints = EndpointUtil.selectByProtocol(endpoints, "opc.tcp");
endpoints = EndpointUtil.selectByMessageSecurityMode(endpoints, param.getSecurityMode());
if(param.getSecurityPolicie()!=null){
endpoints = EndpointUtil.selectBySecurityPolicy(endpoints, param.getSecurityPolicie());
}
endpoints = EndpointUtil.sortBySecurityLevel(endpoints);
}else{
endpoints = selectByProtocol(endpoints, "https");
EndpointDescription[] np = new EndpointDescription[1];
np[0] = endpoints[0];
endpoints = np;
}
//////////////////////////////////////
if(endpoints.length==0){
return null;
}
EndpointDescription endpoint = endpoints[endpoints.length - 1];
mySession = myClient.createSessionChannel(endpoint);
}else{
mySession = myClient.createSessionChannel(param.getUrl());
}
if(param.getAuthentication()==0){//用户名密码验证
mySession.activate();
}else if(param.getAuthentication()==1){
mySession.activate(param.getUserName(), param.getPassword());
}else{
mySession.activate();
}
return mySession;
}
/**
* History Read
*
* @param mySession SessionChannel
* @param nodeIdStrs List String => "ns=5;s=Random1"
* @param startTime Format => yyyy-MM-dd hh:mm:ss:SSS CST=>GMT
* @param endTime Format => yyyy-MM-dd hh:mm:ss:SSS CST=>GMT
*/
public static DataValue[] historyRead(SessionChannel mySession,List nodeIdStrs,String startTime,String endTime)
throws ServiceFaultException, ServiceResultException, ParseException{
if(mySession==null)
mySession = session;
if(nodeIdStrs==null || nodeIdStrs.size()<1)
return null;
List nodeIdList = new ArrayList<>();
for (String nis : nodeIdStrs) {
nodeIdList.add(NodeId.get(getIdType(nis),getNs(nis), getId(nis)));
}
ReadRawModifiedDetails rrmd = new ReadRawModifiedDetails();
rrmd.setIsReadModified(false);
SimpleDateFormat ff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
Date s1 = ff.parse(startTime);
Date s2 = ff.parse(endTime);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar1.setTime(s1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar2.setTime(s2);
rrmd.setStartTime(new DateTime(calendar1.get(Calendar.YEAR),calendar1.get(Calendar.MONTH),calendar1.get(Calendar.DAY_OF_MONTH)
,calendar1.get(Calendar.HOUR),calendar1.get(Calendar.MINUTE),calendar1.get(Calendar.SECOND),calendar1.get(Calendar.MILLISECOND)));
rrmd.setEndTime(new DateTime(calendar2.get(Calendar.YEAR),calendar2.get(Calendar.MONTH),calendar2.get(Calendar.DAY_OF_MONTH)
,calendar2.get(Calendar.HOUR),calendar2.get(Calendar.MINUTE),calendar2.get(Calendar.SECOND),calendar2.get(Calendar.MILLISECOND)));
rrmd.setNumValuesPerNode(UnsignedInteger.getFromBits(1000));
rrmd.setReturnBounds(true);
ExtensionObject eo = ExtensionObject.encode(rrmd, QualifiedName.DEFAULT_BINARY_ENCODING, StackUtils.getDefaultSerializer(),
EncoderContext.getDefaultInstance());
HistoryReadValueId[] NodesToRead = new HistoryReadValueId[nodeIdStrs.size()];
for (int i = 0; i < NodesToRead.length; i++) {
HistoryReadValueId hrvi = new HistoryReadValueId();
hrvi.setNodeId(nodeIdList.get(i));
NumericRange parsedIndexRange = new NumericRange(-1);
hrvi.setParsedIndexRange(parsedIndexRange);
NodesToRead[i] = hrvi;
}
HistoryReadResponse resp = mySession.HistoryRead(null, eo, TimestampsToReturn.Source, false, NodesToRead);
HistoryReadResult[] hrr = resp.getResults();
for (HistoryReadResult historyReadResult : hrr) {
HistoryReadResult tt = historyReadResult;
ExtensionObject dc = tt.getHistoryData();
HistoryData data = ((ExtensionObject) dc).decode(StackUtils.getDefaultSerializer(), EncoderContext.getDefaultInstance(), null);
DataValue[] dataArr = data.getDataValues();
return dataArr;
}
return null;
}
/**
* Write Nodes
*
* @param mySession SessionChannel
* @param nodeIdStrs List String => "ns=5;s=Random1"
* @param values datas for write
*/
public static boolean writeNodes(SessionChannel mySession,List nodeIdStrs,List
package OpcUa;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import org.opcfoundation.ua.application.SessionChannel;
import org.opcfoundation.ua.builtintypes.DataValue;
import org.opcfoundation.ua.builtintypes.DateTime;
import org.opcfoundation.ua.builtintypes.ExpandedNodeId;
import org.opcfoundation.ua.common.ServiceResultException;
import org.opcfoundation.ua.core.ReferenceDescription;
import utils.OpcUaUtil;
public class OpcTest {
public static void main(String[] args) throws UnknownHostException, ServiceResultException, ParseException {
SessionChannel session = OpcUaUtil.getSession();
//read
List list = Arrays.asList("ns=5;s=Counter1");
List re = OpcUaUtil.readNodes(session, list);
for (String string : re) {
System.out.println(string);
}
//browse
/* String nodeIdStr = "ns=0;i=3048";
List list = OpcUaUtil.browseNode(session, nodeIdStr);
for (ReferenceDescription[] referenceDescriptions : list) {
if(referenceDescriptions==null)
System.out.println("null");
else{
for (ReferenceDescription rd : referenceDescriptions) {
ExpandedNodeId nid = rd.getNodeId();
System.out.println("ns="+nid.getNamespaceIndex()+";"+OpcUaUtil.getIdType2(nid.getIdType())+"="+nid.getValue());
}
}
}*/
/* //deep browse
String nodeIdStr = "ns=0;i=2311";
OpcUaUtil.deepBrowseNode(session,nodeIdStr,null,0);*/
//historyRead
/* SimpleDateFormat bjSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
bjSdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); // 设置北京时区
List list = Arrays.asList("ns=5;s=Random1");
DataValue[] re = OpcUaUtil.historyRead(session, list, "2018-12-07 08:45:00:000", "2018-12-07 08:45:10:000");
for (DataValue dataValue : re) {
DateTime dt = dataValue.getSourceTimestamp();
Calendar cc = dt.getUtcCalendar();
System.out.println(String.format("%-25s", dataValue.getValue())+" "+bjSdf.format(cc.getTime()));
}*/
//write
/* List sList = Arrays.asList("ns=3;s=Duration");
List