use of org.xnio.Cancellable in project wildfly-core by wildfly.
the class ConnectSyncUnitTestCase method getConfiguration.
private static ProtocolConnectionConfiguration getConfiguration(IoFuture.Status initialStatus, boolean completeOnRecheck, boolean failOnRecheck) {
final FutureResult<Connection> futureResult = new FutureResult<>();
// It seems you need to add a cancel handler if you want a
// call to futureResult.getIoFuture().cancel() to trigger a change in the future to State.CANCELLED.
// So add one so we can test whether cancel() has been called.
futureResult.addCancelHandler(new Cancellable() {
public Cancellable cancel() {
futureResult.setCancelled();
return this;
}
});
final MockConnection connection = initialStatus == IoFuture.Status.DONE || completeOnRecheck ? new MockConnection() : null;
final TestTimeoutHandler timeoutHandler = new TestTimeoutHandler(futureResult, initialStatus, connection, failOnRecheck);
final MockEndpoint endpoint = new MockEndpoint(futureResult);
ProtocolConnectionConfiguration result = ProtocolConnectionConfiguration.create(endpoint, URI.create("http://127.0.0.1"));
result.setTimeoutHandler(timeoutHandler);
return result;
}
use of org.xnio.Cancellable in project OpenUnison by TremoloSecurity.
the class ConnectionBuilder method connectImpl.
private IoFuture<WebSocketChannel> connectImpl(final URI uri, final FutureResult<WebSocketChannel> ioFuture, final int redirectCount) {
WebSocketLogger.REQUEST_LOGGER.debugf("Opening websocket connection to %s", uri);
final String scheme = uri.getScheme().equals("wss") ? "https" : "http";
final URI newUri;
try {
newUri = new URI(scheme, uri.getUserInfo(), uri.getHost(), uri.getPort() == -1 ? (uri.getScheme().equals("wss") ? 443 : 80) : uri.getPort(), uri.getPath().isEmpty() ? "/" : uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
final WebSocketClientHandshake handshake = WebSocketClientHandshake.create(version, newUri, clientNegotiation, clientExtensions);
final Map<String, String> originalHeaders = handshake.createHeaders();
originalHeaders.put(Headers.HOST_STRING, uri.getHost() + ":" + newUri.getPort());
final Map<String, List<String>> headers = new HashMap<>();
for (Map.Entry<String, String> entry : originalHeaders.entrySet()) {
List<String> list = new ArrayList<>();
list.add(entry.getValue());
headers.put(entry.getKey(), list);
}
headers.putAll(this.additionalHeaders);
if (clientNegotiation != null) {
clientNegotiation.beforeRequest(headers);
}
InetSocketAddress toBind = bindAddress;
String sysBind = System.getProperty(WebSocketClient.BIND_PROPERTY);
if (toBind == null && sysBind != null) {
toBind = new InetSocketAddress(sysBind, 0);
}
if (proxyUri != null) {
UndertowClient.getInstance().connect(new ClientCallback<ClientConnection>() {
@Override
public void completed(final ClientConnection connection) {
int port = uri.getPort() > 0 ? uri.getPort() : uri.getScheme().equals("https") || uri.getScheme().equals("wss") ? 443 : 80;
ClientRequest cr = new ClientRequest().setMethod(Methods.CONNECT).setPath(uri.getHost() + ":" + port).setProtocol(Protocols.HTTP_1_1);
cr.getRequestHeaders().put(Headers.HOST, proxyUri.getHost() + ":" + (proxyUri.getPort() > 0 ? proxyUri.getPort() : 80));
connection.sendRequest(cr, new ClientCallback<ClientExchange>() {
@Override
public void completed(ClientExchange result) {
result.setResponseListener(new ClientCallback<ClientExchange>() {
@Override
public void completed(ClientExchange response) {
try {
if (response.getResponse().getResponseCode() == 200) {
try {
StreamConnection targetConnection = connection.performUpgrade();
WebSocketLogger.REQUEST_LOGGER.debugf("Established websocket connection to %s", uri);
if (uri.getScheme().equals("wss") || uri.getScheme().equals("https")) {
handleConnectionWithExistingConnection(((UndertowXnioSsl) ssl).wrapExistingConnection(targetConnection, optionMap));
} else {
handleConnectionWithExistingConnection(targetConnection);
}
} catch (IOException e) {
ioFuture.setException(e);
} catch (Exception e) {
ioFuture.setException(new IOException(e));
}
} else {
ioFuture.setException(UndertowMessages.MESSAGES.proxyConnectionFailed(response.getResponse().getResponseCode()));
}
} catch (Exception e) {
ioFuture.setException(new IOException(e));
}
}
private void handleConnectionWithExistingConnection(StreamConnection targetConnection) {
final IoFuture<?> result;
result = HttpUpgrade.performUpgrade(targetConnection, newUri, headers, new WebsocketConnectionListener(optionMap, handshake, newUri, ioFuture), handshake.handshakeChecker(newUri, headers));
result.addNotifier(new IoFuture.Notifier<Object, Object>() {
@Override
public void notify(IoFuture<?> res, Object attachment) {
if (res.getStatus() == IoFuture.Status.FAILED) {
ioFuture.setException(res.getException());
}
}
}, null);
ioFuture.addCancelHandler(new Cancellable() {
@Override
public Cancellable cancel() {
result.cancel();
return null;
}
});
}
@Override
public void failed(IOException e) {
ioFuture.setException(e);
}
});
}
@Override
public void failed(IOException e) {
ioFuture.setException(e);
}
});
}
@Override
public void failed(IOException e) {
ioFuture.setException(e);
}
}, bindAddress, proxyUri, worker, proxySsl, bufferPool, optionMap);
} else {
final IoFuture<?> result;
if (ssl != null) {
result = HttpUpgrade.performUpgrade(worker, ssl, toBind, newUri, headers, new WebsocketConnectionListener(optionMap, handshake, newUri, ioFuture), null, optionMap, handshake.handshakeChecker(newUri, headers));
} else {
result = HttpUpgrade.performUpgrade(worker, toBind, newUri, headers, new WebsocketConnectionListener(optionMap, handshake, newUri, ioFuture), null, optionMap, handshake.handshakeChecker(newUri, headers));
}
result.addNotifier(new IoFuture.Notifier<Object, Object>() {
@Override
public void notify(IoFuture<?> res, Object attachment) {
if (res.getStatus() == IoFuture.Status.FAILED) {
IOException exception = res.getException();
if (exception instanceof RedirectException) {
if (redirectCount == MAX_REDIRECTS) {
ioFuture.setException(UndertowMessages.MESSAGES.tooManyRedirects(exception));
} else {
String path = ((RedirectException) exception).getLocation();
try {
connectImpl(new URI(path), ioFuture, redirectCount + 1);
} catch (URISyntaxException e) {
ioFuture.setException(new IOException(e));
}
}
} else {
ioFuture.setException(exception);
}
}
}
}, null);
ioFuture.addCancelHandler(new Cancellable() {
@Override
public Cancellable cancel() {
result.cancel();
return null;
}
});
}
return ioFuture.getIoFuture();
}
use of org.xnio.Cancellable in project jboss-remoting by jboss-remoting.
the class EndpointImpl method connect.
IoFuture<Connection> connect(final URI destination, final SocketAddress bindAddress, final OptionMap connectOptions, final AuthenticationConfiguration configuration, final SSLContext sslContext) {
Assert.checkNotNullParam("destination", destination);
Assert.checkNotNullParam("connectOptions", connectOptions);
final String protocol = AUTH_CONFIGURATION_CLIENT.getSaslProtocol(configuration) != null ? AUTH_CONFIGURATION_CLIENT.getSaslProtocol(configuration) : connectOptions.contains(RemotingOptions.SASL_PROTOCOL) ? connectOptions.get(RemotingOptions.SASL_PROTOCOL) : RemotingOptions.DEFAULT_SASL_PROTOCOL;
UnaryOperator<SaslClientFactory> factoryOperator = factory -> new ProtocolSaslClientFactory(factory, protocol);
if (connectOptions.contains(RemotingOptions.SERVER_NAME)) {
final String serverName = connectOptions.get(RemotingOptions.SERVER_NAME);
factoryOperator = and(factoryOperator, factory -> new ServerNameSaslClientFactory(factory, serverName));
}
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(RemotingPermission.CONNECT);
}
final String scheme = AUTH_CONFIGURATION_CLIENT.getRealProtocol(destination, configuration);
synchronized (connectionLock) {
boolean ok = false;
try {
resourceUntick("Connection to " + destination);
} catch (NotOpenException e) {
return new FailedIoFuture<>(e);
}
try {
final ProtocolRegistration protocolRegistration = connectionProviders.get(scheme);
if (protocolRegistration == null) {
return new FailedIoFuture<>(new UnknownURISchemeException("No connection provider for URI scheme \"" + scheme + "\" is installed"));
}
final ConnectionProvider connectionProvider = protocolRegistration.getProvider();
final FutureResult<Connection> futureResult = new FutureResult<Connection>(getExecutor());
// Mark the stack because otherwise debugging connect problems can be incredibly tough
final StackTraceElement[] mark = Thread.currentThread().getStackTrace();
final UnaryOperator<SaslClientFactory> finalFactoryOperator = factoryOperator;
final Result<ConnectionHandlerFactory> result = new Result<ConnectionHandlerFactory>() {
private final AtomicBoolean flag = new AtomicBoolean();
public boolean setCancelled() {
if (!flag.compareAndSet(false, true)) {
return false;
}
log.logf(getClass().getName(), Logger.Level.TRACE, null, "Registered cancellation result");
closeTick1("a cancelled connection");
futureResult.setCancelled();
return true;
}
public boolean setException(final IOException exception) {
if (!flag.compareAndSet(false, true)) {
return false;
}
log.logf(getClass().getName(), Logger.Level.TRACE, exception, "Registered exception result");
closeTick1("a failed connection (2)");
SpiUtils.glueStackTraces(exception, mark, 1, "asynchronous invocation");
futureResult.setException(exception);
return true;
}
public boolean setResult(final ConnectionHandlerFactory connHandlerFactory) {
if (!flag.compareAndSet(false, true)) {
return false;
}
synchronized (connectionLock) {
log.logf(getClass().getName(), Logger.Level.TRACE, null, "Registered successful result %s", connHandlerFactory);
final ConnectionImpl connection = new ConnectionImpl(EndpointImpl.this, connHandlerFactory, protocolRegistration.getContext(), destination, null, configuration, protocol);
connections.add(connection);
connection.getConnectionHandler().addCloseHandler(SpiUtils.asyncClosingCloseHandler(connection));
connection.addCloseHandler(resourceCloseHandler);
connection.addCloseHandler(connectionCloseHandler);
// see if we were closed in the meantime
if (EndpointImpl.this.isCloseFlagSet()) {
connection.closeAsync();
futureResult.setCancelled();
} else {
futureResult.setResult(connection);
}
}
return true;
}
};
final Cancellable connect;
if (System.getSecurityManager() == null)
connect = connectionProvider.connect(destination, bindAddress, connectOptions, result, configuration, sslContext, finalFactoryOperator, Collections.emptyList());
else
connect = doPrivileged((PrivilegedAction<Cancellable>) () -> connectionProvider.connect(destination, bindAddress, connectOptions, result, configuration, sslContext, finalFactoryOperator, Collections.emptyList()));
ok = true;
futureResult.addCancelHandler(connect);
return futureResult.getIoFuture();
} finally {
if (!ok) {
closeTick1("a failed connection (1)");
}
}
}
}
use of org.xnio.Cancellable in project jboss-remoting by jboss-remoting.
the class RemoteConnectionProvider method connect.
public Cancellable connect(final URI destination, final SocketAddress bindAddress, final OptionMap connectOptions, final Result<ConnectionHandlerFactory> result, final AuthenticationConfiguration authenticationConfiguration, final SSLContext sslContext, final UnaryOperator<SaslClientFactory> saslClientFactoryOperator, final Collection<String> serverMechs) {
if (!isOpen()) {
throw new IllegalStateException("Connection provider is closed");
}
Assert.checkNotNullParam("destination", destination);
Assert.checkNotNullParam("connectOptions", connectOptions);
Assert.checkNotNullParam("result", result);
Assert.checkNotNullParam("authenticationConfiguration", authenticationConfiguration);
Assert.checkNotNullParam("saslClientFactoryOperator", saslClientFactoryOperator);
if (sslRequired)
Assert.checkNotNullParam("sslContext", sslContext);
log.tracef("Attempting to connect to \"%s\" with options %s", destination, connectOptions);
// cancellable that will be returned by this method
final FutureResult<ConnectionHandlerFactory> cancellableResult = new FutureResult<ConnectionHandlerFactory>();
cancellableResult.addCancelHandler(new Cancellable() {
@Override
public Cancellable cancel() {
cancellableResult.setCancelled();
return this;
}
});
final IoFuture<ConnectionHandlerFactory> returnedFuture = cancellableResult.getIoFuture();
returnedFuture.addNotifier(IoUtils.<ConnectionHandlerFactory>resultNotifier(), result);
final boolean useSsl = sslRequired || connectOptions.get(Options.SSL_ENABLED, true);
final ChannelListener<StreamConnection> openListener = new ChannelListener<StreamConnection>() {
public void handleEvent(final StreamConnection connection) {
try {
connection.setOption(Options.TCP_NODELAY, Boolean.TRUE);
} catch (IOException e) {
// ignore
}
final SslChannel sslChannel = connection instanceof SslChannel ? (SslChannel) connection : null;
final RemoteConnection remoteConnection = new RemoteConnection(connection, sslChannel, connectOptions, RemoteConnectionProvider.this);
cancellableResult.addCancelHandler(new Cancellable() {
@Override
public Cancellable cancel() {
RemoteConnectionHandler.sendCloseRequestBody(remoteConnection);
remoteConnection.handlePreAuthCloseRequest();
return this;
}
});
if (connection.isOpen()) {
remoteConnection.setResult(cancellableResult);
connection.getSinkChannel().setWriteListener(remoteConnection.getWriteListener());
final ClientConnectionOpenListener openListener = new ClientConnectionOpenListener(destination, remoteConnection, connectionProviderContext, authenticationConfiguration, saslClientFactoryOperator, serverMechs, connectOptions);
openListener.handleEvent(connection.getSourceChannel());
}
}
};
final AuthenticationContextConfigurationClient configurationClient = ClientConnectionOpenListener.AUTH_CONFIGURATION_CLIENT;
final InetSocketAddress address = configurationClient.getDestinationInetSocketAddress(destination, authenticationConfiguration, 0);
final IoFuture<? extends StreamConnection> future;
if (useSsl) {
future = createSslConnection(destination, (InetSocketAddress) bindAddress, address, connectOptions, authenticationConfiguration, sslContext, openListener);
} else {
future = createConnection(destination, (InetSocketAddress) bindAddress, address, connectOptions, openListener);
}
pendingInboundConnections.add(returnedFuture);
// if the connection fails, we need to propagate that
future.addNotifier(new IoFuture.HandlingNotifier<StreamConnection, FutureResult<ConnectionHandlerFactory>>() {
public void handleFailed(final IOException exception, final FutureResult<ConnectionHandlerFactory> attachment) {
attachment.setException(exception);
}
public void handleCancelled(final FutureResult<ConnectionHandlerFactory> attachment) {
attachment.setCancelled();
}
}, cancellableResult);
returnedFuture.addNotifier(new IoFuture.HandlingNotifier<ConnectionHandlerFactory, IoFuture<ConnectionHandlerFactory>>() {
public void handleCancelled(IoFuture<ConnectionHandlerFactory> attachment) {
pendingInboundConnections.remove(attachment);
future.cancel();
}
public void handleFailed(final IOException exception, IoFuture<ConnectionHandlerFactory> attachment) {
pendingInboundConnections.remove(attachment);
}
public void handleDone(final ConnectionHandlerFactory data, IoFuture<ConnectionHandlerFactory> attachment) {
pendingInboundConnections.remove(attachment);
}
}, returnedFuture);
return returnedFuture;
}
use of org.xnio.Cancellable in project jboss-remoting by jboss-remoting.
the class RemoteConnectionProvider method closeAction.
protected void closeAction() {
try {
final Cancellable[] cancellables;
synchronized (pendingInboundConnections) {
cancellables = pendingInboundConnections.toArray(new Cancellable[pendingInboundConnections.size()]);
pendingInboundConnections.clear();
}
for (Cancellable pendingConnection : cancellables) {
pendingConnection.cancel();
}
closeComplete();
} finally {
if (server != null && objectName != null) {
try {
server.unregisterMBean(objectName);
} catch (Throwable ignored) {
}
}
}
}
Aggregations