use of org.eclipse.milo.opcua.sdk.server.OpcUaServer in project milo by eclipse.
the class UaNodeTest method setup.
@BeforeTest
public void setup() throws Exception {
server = Mockito.mock(OpcUaServer.class);
AddressSpaceManager addressSpaceManager = new AddressSpaceManager(server);
NamespaceTable namespaceTable = new NamespaceTable();
ObjectTypeManager objectTypeManager = new ObjectTypeManager();
VariableTypeManager variableTypeManager = new VariableTypeManager();
Mockito.when(server.getNamespaceTable()).thenReturn(namespaceTable);
Mockito.when(server.getAddressSpaceManager()).thenReturn(addressSpaceManager);
Mockito.when(server.getObjectTypeManager()).thenReturn(objectTypeManager);
Mockito.when(server.getVariableTypeManager()).thenReturn(variableTypeManager);
UaNodeManager nodeManager = new UaNodeManager();
addressSpaceManager.register(nodeManager);
UaNodeContext nodeContext = new UaNodeContext() {
@Override
public OpcUaServer getServer() {
return server;
}
@Override
public NodeManager<UaNode> getNodeManager() {
return nodeManager;
}
};
new NodeLoader(nodeContext, nodeManager).loadNodes();
ObjectTypeInitializer.initialize(server.getNamespaceTable(), objectTypeManager);
VariableTypeInitializer.initialize(server.getNamespaceTable(), variableTypeManager);
}
use of org.eclipse.milo.opcua.sdk.server.OpcUaServer in project milo by eclipse.
the class InstanceDeclarationHierarchyTest method test.
@Test
public void test() throws Exception {
NamespaceTable namespaceTable = new NamespaceTable();
UaNodeManager nodeManager = new UaNodeManager();
AddressSpaceManager addressSpaceManager = Mockito.mock(AddressSpaceManager.class);
Mockito.when(addressSpaceManager.getManagedNode(Mockito.any(NodeId.class))).then((Answer<Optional<UaNode>>) invocationOnMock -> nodeManager.getNode(invocationOnMock.getArgument(0)));
Mockito.when(addressSpaceManager.getManagedNode(Mockito.any(ExpandedNodeId.class))).then((Answer<Optional<UaNode>>) invocationOnMock -> nodeManager.getNode(invocationOnMock.getArgument(0), namespaceTable));
Mockito.when(addressSpaceManager.getManagedReferences(Mockito.any(NodeId.class))).then((Answer<List<Reference>>) invocationOnMock -> nodeManager.getReferences(invocationOnMock.getArgument(0)));
OpcUaServer server = Mockito.mock(OpcUaServer.class);
Mockito.when(server.getAddressSpaceManager()).thenReturn(addressSpaceManager);
Mockito.when(server.getNamespaceTable()).thenReturn(namespaceTable);
UaNodeContext context = new UaNodeContext() {
@Override
public OpcUaServer getServer() {
return server;
}
@Override
public NodeManager<UaNode> getNodeManager() {
return nodeManager;
}
};
new NodeLoader(context, nodeManager).loadNodes();
InstanceDeclarationHierarchy idh = InstanceDeclarationHierarchy.create(addressSpaceManager, namespaceTable, Identifiers.AnalogItemType);
System.out.println(idh);
assertNotNull(idh);
}
use of org.eclipse.milo.opcua.sdk.server.OpcUaServer in project milo by eclipse.
the class NodeFactoryTest method setup.
@BeforeTest
public void setup() throws Exception {
server = Mockito.mock(OpcUaServer.class);
NamespaceTable namespaceTable = new NamespaceTable();
Mockito.when(server.getNamespaceTable()).thenReturn(namespaceTable);
nodeManager = new UaNodeManager();
AddressSpaceManager addressSpaceManager = Mockito.mock(AddressSpaceManager.class);
Mockito.when(addressSpaceManager.getManagedNode(Mockito.any(NodeId.class))).then((Answer<Optional<UaNode>>) invocationOnMock -> nodeManager.getNode(invocationOnMock.getArgument(0)));
Mockito.when(addressSpaceManager.getManagedNode(Mockito.any(ExpandedNodeId.class))).then((Answer<Optional<UaNode>>) invocationOnMock -> nodeManager.getNode(invocationOnMock.getArgument(0), namespaceTable));
Mockito.when(addressSpaceManager.getManagedReferences(Mockito.any(NodeId.class))).then((Answer<List<Reference>>) invocationOnMock -> nodeManager.getReferences(invocationOnMock.getArgument(0)));
Mockito.when(server.getAddressSpaceManager()).thenReturn(addressSpaceManager);
UaNodeContext context = new UaNodeContext() {
@Override
public OpcUaServer getServer() {
return server;
}
@Override
public NodeManager<UaNode> getNodeManager() {
return nodeManager;
}
};
new NodeLoader(context, nodeManager).loadNodes();
ObjectTypeManager objectTypeManager = new ObjectTypeManager();
ObjectTypeInitializer.initialize(server.getNamespaceTable(), objectTypeManager);
VariableTypeManager variableTypeManager = new VariableTypeManager();
VariableTypeInitializer.initialize(server.getNamespaceTable(), variableTypeManager);
nodeFactory = new NodeFactory(context, objectTypeManager, variableTypeManager);
}
use of org.eclipse.milo.opcua.sdk.server.OpcUaServer in project milo by eclipse.
the class TestServer method create.
public static OpcUaServer create(int port) throws Exception {
File securityTempDir = new File(System.getProperty("java.io.tmpdir"), "security");
if (!securityTempDir.exists() && !securityTempDir.mkdirs()) {
throw new Exception("unable to create security temp dir: " + securityTempDir);
}
LoggerFactory.getLogger(TestServer.class).info("security temp dir: {}", securityTempDir.getAbsolutePath());
KeyStoreLoader loader = new KeyStoreLoader().load(securityTempDir);
DefaultCertificateManager certificateManager = new DefaultCertificateManager(loader.getServerKeyPair(), loader.getServerCertificateChain());
File pkiDir = securityTempDir.toPath().resolve("pki").toFile();
DefaultTrustListManager trustListManager = new DefaultTrustListManager(pkiDir);
LoggerFactory.getLogger(TestServer.class).info("pki dir: {}", pkiDir.getAbsolutePath());
DefaultServerCertificateValidator certificateValidator = new DefaultServerCertificateValidator(trustListManager);
KeyPair httpsKeyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048);
SelfSignedHttpsCertificateBuilder httpsCertificateBuilder = new SelfSignedHttpsCertificateBuilder(httpsKeyPair);
httpsCertificateBuilder.setCommonName(HostnameUtil.getHostname());
HostnameUtil.getHostnames("localhost", false).forEach(httpsCertificateBuilder::addDnsName);
X509Certificate httpsCertificate = httpsCertificateBuilder.build();
UsernameIdentityValidator identityValidator = new UsernameIdentityValidator(true, authChallenge -> {
String username = authChallenge.getUsername();
String password = authChallenge.getPassword();
boolean user1 = "user1".equals(username) && "password".equals(password);
boolean user2 = "user2".equals(username) && "password".equals(password);
boolean admin = "admin".equals(username) && "password".equals(password);
return user1 || user2 || admin;
});
// If you need to use multiple certificates you'll have to be smarter than this.
X509Certificate certificate = certificateManager.getCertificates().stream().findFirst().orElseThrow(() -> new UaRuntimeException(StatusCodes.Bad_ConfigurationError, "no certificate found"));
// The configured application URI must match the one in the certificate(s)
String applicationUri = CertificateUtil.getSanUri(certificate).orElseThrow(() -> new UaRuntimeException(StatusCodes.Bad_ConfigurationError, "certificate is missing the application URI"));
Set<EndpointConfiguration> endpointConfigurations = createEndpointConfigurations(certificate, port);
OpcUaServerConfig serverConfig = OpcUaServerConfig.builder().setApplicationUri(applicationUri).setApplicationName(LocalizedText.english("Eclipse Milo OPC UA Example Server")).setEndpoints(endpointConfigurations).setBuildInfo(new BuildInfo("urn:eclipse:milo:example-server", "eclipse", "eclipse milo example server", OpcUaServer.SDK_VERSION, "", DateTime.now())).setCertificateManager(certificateManager).setTrustListManager(trustListManager).setCertificateValidator(certificateValidator).setHttpsKeyPair(httpsKeyPair).setHttpsCertificate(httpsCertificate).setIdentityValidator(identityValidator).setProductUri("urn:eclipse:milo:example-server").build();
return new OpcUaServer(serverConfig);
}
use of org.eclipse.milo.opcua.sdk.server.OpcUaServer in project milo by eclipse.
the class AbstractMethodInvocationHandler method invoke.
@Override
public final CallMethodResult invoke(AccessContext accessContext, CallMethodRequest request) {
try {
checkExecutableAttributes(accessContext);
Variant[] inputArgumentValues = request.getInputArguments();
if (inputArgumentValues == null)
inputArgumentValues = new Variant[0];
if (inputArgumentValues.length != getInputArguments().length) {
throw new UaException(StatusCodes.Bad_ArgumentsMissing);
}
StatusCode[] inputDataTypeCheckResults = new StatusCode[inputArgumentValues.length];
for (int i = 0; i < inputArgumentValues.length; i++) {
Argument argument = getInputArguments()[i];
Variant variant = inputArgumentValues[i];
Object value = variant.getValue();
// TODO this needs to be able to match when argument DataType is an alias type
// extract subtype logic from AttributeWriter...
boolean dataTypeMatch = value == null || variant.getDataType().flatMap(xni -> xni.toNodeId(node.getNodeContext().getNamespaceTable())).map(type -> {
if (type.equals(argument.getDataType())) {
return true;
} else {
if (Identifiers.Structure.equals(type) && value instanceof ExtensionObject) {
SerializationContext serializationContext = getNode().getNodeContext().getServer().getSerializationContext();
try {
Object decoded = ((ExtensionObject) value).decode(serializationContext);
if (decoded instanceof UaStructure) {
return ((UaStructure) decoded).getTypeId().toNodeId(node.getNodeContext().getNamespaceTable()).map(argument.getDataType()::equals).orElse(false);
}
} catch (UaSerializationException e) {
LoggerFactory.getLogger(getClass()).warn("Error decoding argument value", e);
}
}
return false;
}
}).orElse(false);
switch(argument.getValueRank()) {
case ValueRanks.Scalar:
if (value != null && value.getClass().isArray()) {
dataTypeMatch = false;
}
break;
case ValueRanks.OneDimension:
case ValueRanks.OneOrMoreDimensions:
if (value != null && !value.getClass().isArray()) {
dataTypeMatch = false;
}
break;
default:
break;
}
if (dataTypeMatch) {
inputDataTypeCheckResults[i] = StatusCode.GOOD;
} else {
inputDataTypeCheckResults[i] = new StatusCode(StatusCodes.Bad_TypeMismatch);
}
}
if (Arrays.stream(inputDataTypeCheckResults).anyMatch(StatusCode::isBad)) {
throw new InvalidArgumentException(inputDataTypeCheckResults);
}
validateInputArgumentValues(inputArgumentValues);
InvocationContext invocationContext = new InvocationContext() {
@Override
public OpcUaServer getServer() {
return node.getNodeContext().getServer();
}
@Override
public NodeId getObjectId() {
return request.getObjectId();
}
@Override
public UaMethodNode getMethodNode() {
return node;
}
@Override
public Optional<Session> getSession() {
return accessContext.getSession();
}
};
Variant[] outputValues = invoke(invocationContext, inputArgumentValues);
return new CallMethodResult(StatusCode.GOOD, new StatusCode[0], new DiagnosticInfo[0], outputValues);
} catch (InvalidArgumentException e) {
return new CallMethodResult(e.getStatusCode(), e.getInputArgumentResults(), e.getInputArgumentDiagnosticInfos(), new Variant[0]);
} catch (UaException e) {
return new CallMethodResult(e.getStatusCode(), new StatusCode[0], new DiagnosticInfo[0], new Variant[0]);
}
}
Aggregations