Search in sources :

Example 1 with ServiceFault

use of org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault in project milo by eclipse.

the class UascServerSymmetricHandler method sendServiceFault.

private void sendServiceFault(ChannelHandlerContext ctx, long requestId, UInteger requestHandle, Throwable fault) {
    StatusCode statusCode = UaException.extract(fault).map(UaException::getStatusCode).orElse(StatusCode.BAD);
    ServiceFault serviceFault = new ServiceFault(new ResponseHeader(DateTime.now(), requestHandle, statusCode, null, null, null));
    serializationQueue.encode((binaryEncoder, chunkEncoder) -> {
        ByteBuf messageBuffer = BufferUtil.pooledBuffer();
        try {
            binaryEncoder.setBuffer(messageBuffer);
            binaryEncoder.writeMessage(null, serviceFault);
            checkMessageSize(messageBuffer);
            EncodedMessage encodedMessage = chunkEncoder.encodeSymmetric(secureChannel, requestId, messageBuffer, MessageType.SecureMessage);
            CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer();
            for (ByteBuf chunk : encodedMessage.getMessageChunks()) {
                chunkComposite.addComponent(chunk);
                chunkComposite.writerIndex(chunkComposite.writerIndex() + chunk.readableBytes());
            }
            ctx.writeAndFlush(chunkComposite, ctx.voidPromise());
        } catch (MessageEncodeException e) {
            logger.error("Error encoding {}: {}", serviceFault, e.getMessage(), e);
        } catch (UaSerializationException e) {
            logger.error("Error serializing ServiceFault: {}", e.getStatusCode(), e);
        } finally {
            messageBuffer.release();
        }
    });
}
Also used : EncodedMessage(org.eclipse.milo.opcua.stack.core.channel.ChunkEncoder.EncodedMessage) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) UaSerializationException(org.eclipse.milo.opcua.stack.core.UaSerializationException) ResponseHeader(org.eclipse.milo.opcua.stack.core.types.structured.ResponseHeader) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) ByteBuf(io.netty.buffer.ByteBuf) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) MessageEncodeException(org.eclipse.milo.opcua.stack.core.channel.MessageEncodeException) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode)

Example 2 with ServiceFault

use of org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault in project milo by eclipse.

the class OpcUaClient method maybeHandleServiceFault.

private void maybeHandleServiceFault(UaResponseMessage response, Throwable ex) {
    if (faultListeners.isEmpty())
        return;
    if (ex != null) {
        if (ex instanceof UaServiceFaultException) {
            UaServiceFaultException faultException = (UaServiceFaultException) ex;
            ServiceFault serviceFault = faultException.getServiceFault();
            logger.debug("Notifying {} ServiceFaultListeners", faultListeners.size());
            faultNotificationQueue.submit(() -> faultListeners.forEach(h -> h.onServiceFault(serviceFault)));
        } else if (ex.getCause() instanceof UaServiceFaultException) {
            UaServiceFaultException faultException = (UaServiceFaultException) ex.getCause();
            ServiceFault serviceFault = faultException.getServiceFault();
            logger.debug("Notifying {} ServiceFaultListeners", faultListeners.size());
            faultNotificationQueue.submit(() -> faultListeners.forEach(h -> h.onServiceFault(serviceFault)));
        }
    }
}
Also used : Arrays(java.util.Arrays) BrowseNextRequest(org.eclipse.milo.opcua.stack.core.types.structured.BrowseNextRequest) WriteValue(org.eclipse.milo.opcua.stack.core.types.structured.WriteValue) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) PublishRequest(org.eclipse.milo.opcua.stack.core.types.structured.PublishRequest) WriteRequest(org.eclipse.milo.opcua.stack.core.types.structured.WriteRequest) MonitoredItemCreateRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest) DataTypeManager(org.eclipse.milo.opcua.stack.core.types.DataTypeManager) WriteResponse(org.eclipse.milo.opcua.stack.core.types.structured.WriteResponse) SessionInitializer(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.SessionInitializer) TranslateBrowsePathsToNodeIdsRequest(org.eclipse.milo.opcua.stack.core.types.structured.TranslateBrowsePathsToNodeIdsRequest) ModifySubscriptionRequest(org.eclipse.milo.opcua.stack.core.types.structured.ModifySubscriptionRequest) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) NodeId(org.eclipse.milo.opcua.stack.core.types.builtin.NodeId) ModifyMonitoredItemsRequest(org.eclipse.milo.opcua.stack.core.types.structured.ModifyMonitoredItemsRequest) UaResponseMessage(org.eclipse.milo.opcua.stack.core.serialization.UaResponseMessage) AddReferencesItem(org.eclipse.milo.opcua.stack.core.types.structured.AddReferencesItem) TransferSubscriptionsResponse(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsResponse) ManifestUtil(org.eclipse.milo.opcua.stack.core.util.ManifestUtil) ReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId) SetPublishingModeResponse(org.eclipse.milo.opcua.stack.core.types.structured.SetPublishingModeResponse) SetMonitoringModeRequest(org.eclipse.milo.opcua.stack.core.types.structured.SetMonitoringModeRequest) MonitoringMode(org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode) SetMonitoringModeResponse(org.eclipse.milo.opcua.stack.core.types.structured.SetMonitoringModeResponse) RepublishRequest(org.eclipse.milo.opcua.stack.core.types.structured.RepublishRequest) ModifyMonitoredItemsResponse(org.eclipse.milo.opcua.stack.core.types.structured.ModifyMonitoredItemsResponse) ConversionUtil.a(org.eclipse.milo.opcua.stack.core.util.ConversionUtil.a) OpcUaClientConfigBuilder(org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfigBuilder) MonitoredItemModifyRequest(org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemModifyRequest) Stack(org.eclipse.milo.opcua.stack.core.Stack) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) DeleteNodesRequest(org.eclipse.milo.opcua.stack.core.types.structured.DeleteNodesRequest) HistoryUpdateRequest(org.eclipse.milo.opcua.stack.core.types.structured.HistoryUpdateRequest) RegisterNodesRequest(org.eclipse.milo.opcua.stack.core.types.structured.RegisterNodesRequest) UaRequestMessage(org.eclipse.milo.opcua.stack.core.serialization.UaRequestMessage) DeleteNodesItem(org.eclipse.milo.opcua.stack.core.types.structured.DeleteNodesItem) DeleteMonitoredItemsRequest(org.eclipse.milo.opcua.stack.core.types.structured.DeleteMonitoredItemsRequest) DeleteMonitoredItemsResponse(org.eclipse.milo.opcua.stack.core.types.structured.DeleteMonitoredItemsResponse) TransferSubscriptionsRequest(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsRequest) DeleteReferencesItem(org.eclipse.milo.opcua.stack.core.types.structured.DeleteReferencesItem) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) RegisterNodesResponse(org.eclipse.milo.opcua.stack.core.types.structured.RegisterNodesResponse) Lists.newCopyOnWriteArrayList(com.google.common.collect.Lists.newCopyOnWriteArrayList) OpcUaClientConfig(org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig) SessionFsm(org.eclipse.milo.opcua.sdk.client.session.SessionFsm) UaStackClient(org.eclipse.milo.opcua.stack.client.UaStackClient) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) SetTriggeringRequest(org.eclipse.milo.opcua.stack.core.types.structured.SetTriggeringRequest) ExecutionException(java.util.concurrent.ExecutionException) DeleteReferencesResponse(org.eclipse.milo.opcua.stack.core.types.structured.DeleteReferencesResponse) AddNodesResponse(org.eclipse.milo.opcua.stack.core.types.structured.AddNodesResponse) AddNodesRequest(org.eclipse.milo.opcua.stack.core.types.structured.AddNodesRequest) DiscoveryClient(org.eclipse.milo.opcua.stack.client.DiscoveryClient) Namespaces(org.eclipse.milo.opcua.stack.core.util.Namespaces) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) LoggerFactory(org.slf4j.LoggerFactory) AddNodesItem(org.eclipse.milo.opcua.stack.core.types.structured.AddNodesItem) DeleteReferencesRequest(org.eclipse.milo.opcua.stack.core.types.structured.DeleteReferencesRequest) ReadRequest(org.eclipse.milo.opcua.stack.core.types.structured.ReadRequest) OpcUaSubscriptionManager(org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaSubscriptionManager) QualifiedName(org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName) Unit(org.eclipse.milo.opcua.stack.core.util.Unit) BrowseDescription(org.eclipse.milo.opcua.stack.core.types.structured.BrowseDescription) AttributeId(org.eclipse.milo.opcua.stack.core.AttributeId) CreateSubscriptionResponse(org.eclipse.milo.opcua.stack.core.types.structured.CreateSubscriptionResponse) DeleteNodesResponse(org.eclipse.milo.opcua.stack.core.types.structured.DeleteNodesResponse) VariableTypeInitializer(org.eclipse.milo.opcua.sdk.client.model.VariableTypeInitializer) HistoryReadRequest(org.eclipse.milo.opcua.stack.core.types.structured.HistoryReadRequest) UByte(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UByte) Predicate(java.util.function.Predicate) BrowsePath(org.eclipse.milo.opcua.stack.core.types.structured.BrowsePath) HistoryUpdateDetails(org.eclipse.milo.opcua.stack.core.types.structured.HistoryUpdateDetails) RepublishResponse(org.eclipse.milo.opcua.stack.core.types.structured.RepublishResponse) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) Objects(java.util.Objects) SubscriptionAcknowledgement(org.eclipse.milo.opcua.stack.core.types.structured.SubscriptionAcknowledgement) List(java.util.List) UnregisterNodesResponse(org.eclipse.milo.opcua.stack.core.types.structured.UnregisterNodesResponse) AddReferencesRequest(org.eclipse.milo.opcua.stack.core.types.structured.AddReferencesRequest) AddReferencesResponse(org.eclipse.milo.opcua.stack.core.types.structured.AddReferencesResponse) TranslateBrowsePathsToNodeIdsResponse(org.eclipse.milo.opcua.stack.core.types.structured.TranslateBrowsePathsToNodeIdsResponse) Optional(java.util.Optional) DeleteSubscriptionsResponse(org.eclipse.milo.opcua.stack.core.types.structured.DeleteSubscriptionsResponse) CreateSubscriptionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CreateSubscriptionRequest) BrowseResponse(org.eclipse.milo.opcua.stack.core.types.structured.BrowseResponse) Identifiers(org.eclipse.milo.opcua.stack.core.Identifiers) BrowseRequest(org.eclipse.milo.opcua.stack.core.types.structured.BrowseRequest) UnregisterNodesRequest(org.eclipse.milo.opcua.stack.core.types.structured.UnregisterNodesRequest) CallMethodRequest(org.eclipse.milo.opcua.stack.core.types.structured.CallMethodRequest) CallResponse(org.eclipse.milo.opcua.stack.core.types.structured.CallResponse) CreateMonitoredItemsResponse(org.eclipse.milo.opcua.stack.core.types.structured.CreateMonitoredItemsResponse) CompletableFuture(java.util.concurrent.CompletableFuture) Function(java.util.function.Function) RequestHeader(org.eclipse.milo.opcua.stack.core.types.structured.RequestHeader) NamespaceTable(org.eclipse.milo.opcua.stack.core.NamespaceTable) CallRequest(org.eclipse.milo.opcua.stack.core.types.structured.CallRequest) SerializationContext(org.eclipse.milo.opcua.stack.core.serialization.SerializationContext) UShort(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort) SessionFsmFactory(org.eclipse.milo.opcua.sdk.client.session.SessionFsmFactory) ReadResponse(org.eclipse.milo.opcua.stack.core.types.structured.ReadResponse) ServiceFaultListener(org.eclipse.milo.opcua.sdk.client.api.ServiceFaultListener) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) BrowseNextResponse(org.eclipse.milo.opcua.stack.core.types.structured.BrowseNextResponse) DeleteSubscriptionsRequest(org.eclipse.milo.opcua.stack.core.types.structured.DeleteSubscriptionsRequest) HistoryReadDetails(org.eclipse.milo.opcua.stack.core.types.structured.HistoryReadDetails) SetTriggeringResponse(org.eclipse.milo.opcua.stack.core.types.structured.SetTriggeringResponse) HistoryReadResponse(org.eclipse.milo.opcua.stack.core.types.structured.HistoryReadResponse) HistoryUpdateResponse(org.eclipse.milo.opcua.stack.core.types.structured.HistoryUpdateResponse) ExecutionQueue(org.eclipse.milo.opcua.stack.core.util.ExecutionQueue) Logger(org.slf4j.Logger) PublishResponse(org.eclipse.milo.opcua.stack.core.types.structured.PublishResponse) Unsigned.ushort(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.ushort) ObjectTypeInitializer(org.eclipse.milo.opcua.sdk.client.model.ObjectTypeInitializer) UserTokenType(org.eclipse.milo.opcua.stack.core.types.enumerated.UserTokenType) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException) ViewDescription(org.eclipse.milo.opcua.stack.core.types.structured.ViewDescription) CreateMonitoredItemsRequest(org.eclipse.milo.opcua.stack.core.types.structured.CreateMonitoredItemsRequest) SetPublishingModeRequest(org.eclipse.milo.opcua.stack.core.types.structured.SetPublishingModeRequest) UaClient(org.eclipse.milo.opcua.sdk.client.api.UaClient) ModifySubscriptionResponse(org.eclipse.milo.opcua.stack.core.types.structured.ModifySubscriptionResponse) UaException(org.eclipse.milo.opcua.stack.core.UaException) HistoryReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.HistoryReadValueId) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException)

Example 3 with ServiceFault

use of org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault in project milo by eclipse.

the class UascClientMessageHandler method onOpenSecureChannel.

private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    if (secureChannelTimeout != null) {
        if (secureChannelTimeout.cancel()) {
            logger.debug("OpenSecureChannel timeout canceled");
            secureChannelTimeout = null;
        } else {
            logger.warn("timed out waiting for secure channel");
            handshakeFuture.completeExceptionally(new UaException(StatusCodes.Bad_Timeout, "timed out waiting for secure channel"));
            ctx.close();
            return;
        }
    }
    // skip messageType, chunkType, messageSize, secureChannelId
    buffer.skipBytes(3 + 1 + 4 + 4);
    AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer, config.getEncodingLimits());
    if (headerRef.compareAndSet(null, securityHeader)) {
        // first time we've received the header; validate and verify the server certificate
        CertificateValidator certificateValidator = config.getCertificateValidator();
        SecurityPolicy securityPolicy = SecurityPolicy.fromUri(securityHeader.getSecurityPolicyUri());
        if (securityPolicy != SecurityPolicy.None) {
            ByteString serverCertificateBytes = securityHeader.getSenderCertificate();
            List<X509Certificate> serverCertificateChain = CertificateUtil.decodeCertificates(serverCertificateBytes.bytesOrEmpty());
            certificateValidator.validateCertificateChain(serverCertificateChain);
        }
    } else {
        if (!securityHeader.equals(headerRef.get())) {
            throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "subsequent AsymmetricSecurityHeader did not match");
        }
    }
    if (accumulateChunk(buffer)) {
        final List<ByteBuf> buffersToDecode = chunkBuffers;
        chunkBuffers = new ArrayList<>(maxChunkCount);
        serializationQueue.decode((binaryDecoder, chunkDecoder) -> {
            ByteBuf message;
            try {
                ChunkDecoder.DecodedMessage decodedMessage = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode);
                message = decodedMessage.getMessage();
            } catch (MessageAbortException e) {
                logger.warn("Received message abort chunk; error={}, reason={}", e.getStatusCode(), e.getMessage());
                return;
            } catch (MessageDecodeException e) {
                logger.error("Error decoding asymmetric message", e);
                handshakeFuture.completeExceptionally(e);
                ctx.close();
                return;
            }
            try {
                UaResponseMessage response = (UaResponseMessage) binaryDecoder.setBuffer(message).readMessage(null);
                StatusCode serviceResult = response.getResponseHeader().getServiceResult();
                if (serviceResult.isGood()) {
                    OpenSecureChannelResponse oscr = (OpenSecureChannelResponse) response;
                    secureChannel.setChannelId(oscr.getSecurityToken().getChannelId().longValue());
                    logger.debug("Received OpenSecureChannelResponse.");
                    NonceUtil.validateNonce(oscr.getServerNonce(), secureChannel.getSecurityPolicy());
                    installSecurityToken(ctx, oscr);
                    handshakeFuture.complete(secureChannel);
                } else {
                    ServiceFault serviceFault = (response instanceof ServiceFault) ? (ServiceFault) response : new ServiceFault(response.getResponseHeader());
                    handshakeFuture.completeExceptionally(new UaServiceFaultException(serviceFault));
                    ctx.close();
                }
            } catch (Throwable t) {
                logger.error("Error decoding OpenSecureChannelResponse", t);
                handshakeFuture.completeExceptionally(t);
                ctx.close();
            } finally {
                message.release();
            }
        });
    }
}
Also used : UaResponseMessage(org.eclipse.milo.opcua.stack.core.serialization.UaResponseMessage) OpenSecureChannelResponse(org.eclipse.milo.opcua.stack.core.types.structured.OpenSecureChannelResponse) UaException(org.eclipse.milo.opcua.stack.core.UaException) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) CertificateValidator(org.eclipse.milo.opcua.stack.core.security.CertificateValidator) MessageAbortException(org.eclipse.milo.opcua.stack.core.channel.MessageAbortException) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) X509Certificate(java.security.cert.X509Certificate) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException) ChunkDecoder(org.eclipse.milo.opcua.stack.core.channel.ChunkDecoder) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) MessageDecodeException(org.eclipse.milo.opcua.stack.core.channel.MessageDecodeException) AsymmetricSecurityHeader(org.eclipse.milo.opcua.stack.core.channel.headers.AsymmetricSecurityHeader)

Example 4 with ServiceFault

use of org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault in project milo by eclipse.

the class UaStackClient method deliverResponse.

/**
 * Complete {@code future} with {@code response} on the {@code deliveryQueue}.
 * <p>
 * This is done for two reasons:
 * 1. the transport future is completed on its serialization queue thread, which we want to get off of ASAP.
 * 2. the futures need to be completed serially, in the order received from the server.
 *
 * @param request  the original {@link UaRequestMessage}.
 * @param response the {@link UaResponseMessage}.
 * @param future   the {@link CompletableFuture} awaiting completion.
 */
private void deliverResponse(UaRequestMessage request, @Nullable UaResponseMessage response, @Nullable Throwable failure, CompletableFuture<UaResponseMessage> future) {
    deliveryQueue.submit(() -> {
        if (response != null) {
            ResponseHeader header = response.getResponseHeader();
            UInteger requestHandle = header.getRequestHandle();
            if (header.getServiceResult().isGood()) {
                future.complete(response);
            } else {
                ServiceFault serviceFault;
                if (response instanceof ServiceFault) {
                    serviceFault = (ServiceFault) response;
                } else {
                    serviceFault = new ServiceFault(header);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Received ServiceFault request={} requestHandle={}, result={}", request.getClass().getSimpleName(), requestHandle, header.getServiceResult());
                }
                future.completeExceptionally(new UaServiceFaultException(serviceFault));
            }
        } else {
            assert failure != null;
            if (logger.isDebugEnabled()) {
                logger.debug("sendRequest() failed, request={}, requestHandle={}", request.getClass().getSimpleName(), request.getRequestHeader().getRequestHandle(), failure);
            }
            future.completeExceptionally(failure);
        }
    });
}
Also used : ResponseHeader(org.eclipse.milo.opcua.stack.core.types.structured.ResponseHeader) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) UaServiceFaultException(org.eclipse.milo.opcua.stack.core.UaServiceFaultException)

Example 5 with ServiceFault

use of org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault in project milo by eclipse.

the class SessionFsmFactory method transferSubscriptions.

@SuppressWarnings("Duplicates")
private static CompletableFuture<Unit> transferSubscriptions(FsmContext<State, Event> ctx, OpcUaClient client, OpcUaSession session) {
    UaStackClient stackClient = client.getStackClient();
    OpcUaSubscriptionManager subscriptionManager = client.getSubscriptionManager();
    ImmutableList<UaSubscription> subscriptions = subscriptionManager.getSubscriptions();
    if (subscriptions.isEmpty()) {
        return completedFuture(Unit.VALUE);
    }
    CompletableFuture<Unit> transferFuture = new CompletableFuture<>();
    UInteger[] subscriptionIdsArray = subscriptions.stream().map(UaSubscription::getSubscriptionId).toArray(UInteger[]::new);
    TransferSubscriptionsRequest request = new TransferSubscriptionsRequest(client.newRequestHeader(session.getAuthenticationToken()), subscriptionIdsArray, true);
    LOGGER.debug("[{}] Sending TransferSubscriptionsRequest...", ctx.getInstanceId());
    stackClient.sendRequest(request).thenApply(TransferSubscriptionsResponse.class::cast).whenComplete((tsr, ex) -> {
        if (tsr != null) {
            List<TransferResult> results = l(tsr.getResults());
            LOGGER.debug("[{}] TransferSubscriptions supported: {}", ctx.getInstanceId(), tsr.getResponseHeader().getServiceResult());
            if (LOGGER.isDebugEnabled()) {
                try {
                    Stream<UInteger> subscriptionIds = subscriptions.stream().map(UaSubscription::getSubscriptionId);
                    Stream<StatusCode> statusCodes = results.stream().map(TransferResult::getStatusCode);
                    // noinspection UnstableApiUsage
                    String[] ss = Streams.zip(subscriptionIds, statusCodes, (i, s) -> String.format("id=%s/%s", i, StatusCodes.lookup(s.getValue()).map(sa -> sa[0]).orElse(s.toString()))).toArray(String[]::new);
                    LOGGER.debug("[{}] TransferSubscriptions results: {}", ctx.getInstanceId(), Arrays.toString(ss));
                } catch (Throwable t) {
                    LOGGER.error("[{}] error logging TransferSubscription results", ctx.getInstanceId(), t);
                }
            }
            client.getConfig().getExecutor().execute(() -> {
                for (int i = 0; i < results.size(); i++) {
                    TransferResult result = results.get(i);
                    if (!result.getStatusCode().isGood()) {
                        UaSubscription subscription = subscriptions.get(i);
                        subscriptionManager.transferFailed(subscription.getSubscriptionId(), result.getStatusCode());
                    }
                }
            });
            transferFuture.complete(Unit.VALUE);
        } else {
            StatusCode statusCode = UaException.extract(ex).map(UaException::getStatusCode).orElse(StatusCode.BAD);
            LOGGER.debug("[{}] TransferSubscriptions not supported: {}", ctx.getInstanceId(), statusCode);
            client.getConfig().getExecutor().execute(() -> {
                // because the list from getSubscriptions() above is a copy.
                for (UaSubscription subscription : subscriptions) {
                    subscriptionManager.transferFailed(subscription.getSubscriptionId(), statusCode);
                }
            });
            // supported but server implementations interpret the spec differently.
            if (statusCode.getValue() == StatusCodes.Bad_NotImplemented || statusCode.getValue() == StatusCodes.Bad_NotSupported || statusCode.getValue() == StatusCodes.Bad_OutOfService || statusCode.getValue() == StatusCodes.Bad_ServiceUnsupported) {
                // One of the expected responses; continue moving through the FSM.
                transferFuture.complete(Unit.VALUE);
            } else {
                // An unexpected response; complete exceptionally and start over.
                // Subsequent runs through the FSM will not attempt transfer because
                // transferFailed() has been called for all the existing subscriptions.
                // This will prevent us from getting stuck in a "loop" attempting to
                // reconnect to a defective server that responds with a channel-level
                // Error message to subscription transfer requests instead of an
                // application-level ServiceFault.
                transferFuture.completeExceptionally(ex);
            }
        }
    });
    return transferFuture;
}
Also used : X509Certificate(java.security.cert.X509Certificate) KEY_CLOSE_FUTURE(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_CLOSE_FUTURE) KeyPair(java.security.KeyPair) SignedSoftwareCertificate(org.eclipse.milo.opcua.stack.core.types.structured.SignedSoftwareCertificate) Arrays(java.util.Arrays) ApplicationType(org.eclipse.milo.opcua.stack.core.types.enumerated.ApplicationType) ScheduledFuture(java.util.concurrent.ScheduledFuture) CompletableFuture.completedFuture(java.util.concurrent.CompletableFuture.completedFuture) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) LoggerFactory(org.slf4j.LoggerFactory) ServerState(org.eclipse.milo.opcua.stack.core.types.enumerated.ServerState) ExtensionObject(org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject) ReadRequest(org.eclipse.milo.opcua.stack.core.types.structured.ReadRequest) TransferResult(org.eclipse.milo.opcua.stack.core.types.structured.TransferResult) KEY_WAIT_TIME(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_WAIT_TIME) OpcUaSubscriptionManager(org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaSubscriptionManager) ByteBuffer(java.nio.ByteBuffer) QualifiedName(org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName) UserIdentityToken(org.eclipse.milo.opcua.stack.core.types.structured.UserIdentityToken) SecurityAlgorithm(org.eclipse.milo.opcua.stack.core.security.SecurityAlgorithm) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) Unit(org.eclipse.milo.opcua.stack.core.util.Unit) AttributeId(org.eclipse.milo.opcua.stack.core.AttributeId) KEY_SESSION_INITIALIZERS(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_SESSION_INITIALIZERS) CertificateUtil(org.eclipse.milo.opcua.stack.core.util.CertificateUtil) CreateSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CreateSessionRequest) ActivateSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.ActivateSessionRequest) TimestampsToReturn(org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn) Predicate(java.util.function.Predicate) KEY_SESSION_ACTIVITY_LISTENERS(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_SESSION_ACTIVITY_LISTENERS) TransferSubscriptionsResponse(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsResponse) Streams(com.google.common.collect.Streams) Bytes(com.google.common.primitives.Bytes) ReadValueId(org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId) ServiceFault(org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault) KEY_WAIT_FUTURE(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_WAIT_FUTURE) ActivateSessionResponse(org.eclipse.milo.opcua.stack.core.types.structured.ActivateSessionResponse) List(java.util.List) Stream(java.util.stream.Stream) PrivateKey(java.security.PrivateKey) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) KEY_KEEP_ALIVE_FAILURE_COUNT(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_KEEP_ALIVE_FAILURE_COUNT) EndpointUtil(org.eclipse.milo.opcua.stack.core.util.EndpointUtil) OpcUaSession(org.eclipse.milo.opcua.sdk.client.OpcUaSession) CertificateEncodingException(java.security.cert.CertificateEncodingException) Identifiers(org.eclipse.milo.opcua.stack.core.Identifiers) CloseSessionRequest(org.eclipse.milo.opcua.stack.core.types.structured.CloseSessionRequest) KEY_SESSION_FUTURE(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_SESSION_FUTURE) ActionContext(com.digitalpetri.strictmachine.dsl.ActionContext) DataValue(org.eclipse.milo.opcua.stack.core.types.builtin.DataValue) OpcUaClient(org.eclipse.milo.opcua.sdk.client.OpcUaClient) SignedIdentityToken(org.eclipse.milo.opcua.sdk.client.api.identity.SignedIdentityToken) CompletableFuture(java.util.concurrent.CompletableFuture) CreateSessionResponse(org.eclipse.milo.opcua.stack.core.types.structured.CreateSessionResponse) RequestHeader(org.eclipse.milo.opcua.stack.core.types.structured.RequestHeader) ImmutableList(com.google.common.collect.ImmutableList) EndpointDescription(org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription) ConversionUtil.l(org.eclipse.milo.opcua.stack.core.util.ConversionUtil.l) SignatureData(org.eclipse.milo.opcua.stack.core.types.structured.SignatureData) ReadResponse(org.eclipse.milo.opcua.stack.core.types.structured.ReadResponse) FutureUtils.complete(org.eclipse.milo.opcua.stack.core.util.FutureUtils.complete) ServiceFaultListener(org.eclipse.milo.opcua.sdk.client.api.ServiceFaultListener) SessionFuture(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.SessionFuture) SecurityPolicy(org.eclipse.milo.opcua.stack.core.security.SecurityPolicy) TransferSubscriptionsRequest(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsRequest) KEY_SESSION(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_SESSION) StatusCodes(org.eclipse.milo.opcua.stack.core.StatusCodes) SignatureUtil(org.eclipse.milo.opcua.stack.core.util.SignatureUtil) Fsm(com.digitalpetri.strictmachine.Fsm) Logger(org.slf4j.Logger) OpcUaClientConfig(org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig) UaStackClient(org.eclipse.milo.opcua.stack.client.UaStackClient) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) KEY_KEEP_ALIVE_SCHEDULED_FUTURE(org.eclipse.milo.opcua.sdk.client.session.SessionFsm.KEY_KEEP_ALIVE_SCHEDULED_FUTURE) TimeUnit(java.util.concurrent.TimeUnit) NonceUtil(org.eclipse.milo.opcua.stack.core.util.NonceUtil) FsmContext(com.digitalpetri.strictmachine.FsmContext) ApplicationDescription(org.eclipse.milo.opcua.stack.core.types.structured.ApplicationDescription) FutureUtils.failedFuture(org.eclipse.milo.opcua.stack.core.util.FutureUtils.failedFuture) UaException(org.eclipse.milo.opcua.stack.core.UaException) FsmBuilder(com.digitalpetri.strictmachine.dsl.FsmBuilder) UaSubscription(org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription) TransferSubscriptionsRequest(org.eclipse.milo.opcua.stack.core.types.structured.TransferSubscriptionsRequest) ByteString(org.eclipse.milo.opcua.stack.core.types.builtin.ByteString) Unit(org.eclipse.milo.opcua.stack.core.util.Unit) TimeUnit(java.util.concurrent.TimeUnit) TransferResult(org.eclipse.milo.opcua.stack.core.types.structured.TransferResult) StatusCode(org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode) Unsigned.uint(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint) CompletableFuture(java.util.concurrent.CompletableFuture) UaStackClient(org.eclipse.milo.opcua.stack.client.UaStackClient) UInteger(org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger) OpcUaSubscriptionManager(org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaSubscriptionManager)

Aggregations

ServiceFault (org.eclipse.milo.opcua.stack.core.types.structured.ServiceFault)7 UaException (org.eclipse.milo.opcua.stack.core.UaException)4 StatusCode (org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode)4 ResponseHeader (org.eclipse.milo.opcua.stack.core.types.structured.ResponseHeader)4 ByteBuf (io.netty.buffer.ByteBuf)3 UaServiceFaultException (org.eclipse.milo.opcua.stack.core.UaServiceFaultException)3 SecurityPolicy (org.eclipse.milo.opcua.stack.core.security.SecurityPolicy)3 ByteString (org.eclipse.milo.opcua.stack.core.types.builtin.ByteString)3 UInteger (org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger)3 X509Certificate (java.security.cert.X509Certificate)2 Arrays (java.util.Arrays)2 List (java.util.List)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 Predicate (java.util.function.Predicate)2 ServiceFaultListener (org.eclipse.milo.opcua.sdk.client.api.ServiceFaultListener)2 OpcUaClientConfig (org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig)2 OpcUaSubscriptionManager (org.eclipse.milo.opcua.sdk.client.subscriptions.OpcUaSubscriptionManager)2 UaStackClient (org.eclipse.milo.opcua.stack.client.UaStackClient)2 AttributeId (org.eclipse.milo.opcua.stack.core.AttributeId)2 Identifiers (org.eclipse.milo.opcua.stack.core.Identifiers)2