use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project lispflowmapping by opendaylight.
the class LispXtrSouthboundHandlerTest method channelReadCompleteTest.
/**
* Tests {@link LispXtrSouthboundHandler#channelReadComplete} method.
*/
@Test
public void channelReadCompleteTest() throws Exception {
ChannelHandlerContext ctxMock = Mockito.mock(ChannelHandlerContext.class);
handler.channelReadComplete(ctxMock);
Mockito.verify(ctxMock).flush();
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project LanternServer by LanternPowered.
the class QueryHandler method handleFullStats.
private void handleFullStats(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) {
final LanternGame game = this.queryServer.getGame();
final LanternServer server = game.getServer();
final Platform platform = game.getPlatform();
final PluginContainer api = platform.getContainer(Platform.Component.API);
final PluginContainer impl = platform.getContainer(Platform.Component.IMPLEMENTATION);
final PluginContainer mc = platform.getContainer(Platform.Component.GAME);
final StringBuilder plugins = new StringBuilder().append(impl.getName()).append(" ").append(impl.getVersion()).append(" on ").append(api.getName()).append(" ").append(api.getVersion());
if (this.showPlugins) {
final List<PluginContainer> containers = new ArrayList<>(game.getPluginManager().getPlugins());
containers.remove(api);
containers.remove(impl);
containers.remove(mc);
char delim = ':';
for (PluginContainer plugin : containers) {
plugins.append(delim).append(' ').append(plugin.getName());
delim = ';';
}
}
final List<String> playerNames = server.getOnlinePlayers().stream().map(CommandSource::getName).collect(Collectors.toList());
final Cause cause = Cause.of(EventContext.empty(), new SimpleRemoteConnection((InetSocketAddress) ctx.channel().remoteAddress(), null));
final QueryServerEvent.Full event = SpongeEventFactory.createQueryServerEventFull(cause, (InetSocketAddress) ctx.channel().localAddress(), new HashMap<>(), "MINECRAFT", "SMP", getWorldName(), server.getMotd().toPlain(), playerNames, plugins.toString(), mc.getVersion().orElse("unknown"), server.getMaxPlayers(), Integer.MAX_VALUE, playerNames.size(), 0);
final InetSocketAddress address = event.getAddress();
final Map<String, Object> data = new LinkedHashMap<>();
data.put("hostname", event.getMotd());
data.put("gametype", event.getGameType());
data.put("game_id", event.getGameId());
data.put("version", event.getVersion());
data.put("plugins", event.getPlugins());
data.put("map", event.getMap());
data.put("numplayers", event.getPlayerCount());
data.put("maxplayers", event.getMaxPlayerCount());
data.put("hostport", address.getPort());
data.put("hostip", address.getHostString());
event.getCustomValuesMap().entrySet().stream().filter(entry -> !data.containsKey(entry.getKey())).forEach(entry -> data.put(entry.getKey(), entry.getValue()));
final ByteBuf buf = ctx.alloc().buffer();
buf.writeByte(ACTION_STATS);
buf.writeInt(sessionId);
// constant: splitnum\x00\x80\x00
buf.writeBytes(new byte[] { 0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, (byte) 0x80, 0x00 });
for (Entry<String, Object> e : data.entrySet()) {
writeString(buf, e.getKey());
writeString(buf, String.valueOf(e.getValue()));
}
buf.writeByte(0);
// constant: \x01player_\x00\x00
buf.writeBytes(new byte[] { 0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00 });
for (Player player : game.getServer().getOnlinePlayers()) {
writeString(buf, player.getName());
}
buf.writeByte(0);
ctx.write(new DatagramPacket(buf, packet.sender()));
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project LogHub by fbacchella.
the class TestServer method testSimple.
@Test(timeout = 2000)
public void testSimple() throws InterruptedException {
Properties empty = new Properties(Collections.emptyMap());
BlockingQueue<Event> receiver = new ArrayBlockingQueue<>(1);
TesterReceiver r = new TesterReceiver(receiver, new Pipeline(Collections.emptyList(), "testone", null));
r.configure(empty);
final ChannelFuture[] sent = new ChannelFuture[1];
EventLoopGroup workerGroup = new DefaultEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(LocalChannel.class);
b.handler(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
public void channelActive(ChannelHandlerContext ctx) {
sent[0] = ctx.writeAndFlush(Unpooled.copiedBuffer("Message\r\n", CharsetUtil.UTF_8));
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
}
});
// Start the client.
ChannelFuture f = b.connect(new LocalAddress(TestServer.class.getCanonicalName())).sync();
Thread.sleep(100);
sent[0].sync();
f.channel().close();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
Event e = receiver.poll();
Assert.assertEquals("Message", e.get("message"));
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project bgpcep by opendaylight.
the class PCCDispatcherImpl method createClient.
@Override
@SuppressWarnings("unchecked")
public Future<PCEPSession> createClient(final InetSocketAddress remoteAddress, final long reconnectTime, final PCEPSessionListenerFactory listenerFactory, final PCEPSessionNegotiatorFactory negotiatorFactory, final KeyMapping keys, final InetSocketAddress localAddress, final BigInteger dbVersion) {
final Bootstrap b = new Bootstrap();
b.group(this.workerGroup);
b.localAddress(localAddress);
setChannelFactory(b, keys);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.option(ChannelOption.SO_REUSEADDR, true);
b.option(ChannelOption.RCVBUF_ALLOCATOR, new io.netty.channel.FixedRecvByteBufAllocator(1));
final long retryTimer = reconnectTime == -1 ? 0 : reconnectTime;
final PCCReconnectPromise promise = new PCCReconnectPromise(remoteAddress, (int) retryTimer, CONNECT_TIMEOUT, b);
final ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(final SocketChannel ch) {
ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getDecoders());
ch.pipeline().addLast("negotiator", negotiatorFactory.getSessionNegotiator(new PCEPSessionNegotiatorFactoryDependencies() {
@Override
public PCEPSessionListenerFactory getListenerFactory() {
return listenerFactory;
}
@Override
public PCEPPeerProposal getPeerProposal() {
return new PCCPeerProposal(dbVersion);
}
}, ch, promise));
ch.pipeline().addLast(PCCDispatcherImpl.this.factory.getEncoders());
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelInactive(final ChannelHandlerContext ctx) {
if (promise.isCancelled()) {
return;
}
if (!promise.isInitialConnectFinished()) {
LOG.debug("Connection to {} was dropped during negotiation, reattempting", remoteAddress);
return;
}
LOG.debug("Reconnecting after connection to {} was dropped", remoteAddress);
PCCDispatcherImpl.this.createClient(remoteAddress, reconnectTime, listenerFactory, negotiatorFactory, keys, localAddress, dbVersion);
}
});
}
};
b.handler(channelInitializer);
promise.connect();
return promise;
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project drill by axbaretto.
the class UserServer method getHandshakeHandler.
@Override
protected ServerHandshakeHandler<UserToBitHandshake> getHandshakeHandler(final BitToUserConnection connection) {
return new ServerHandshakeHandler<UserToBitHandshake>(RpcType.HANDSHAKE, UserToBitHandshake.PARSER) {
@Override
protected void consumeHandshake(ChannelHandlerContext ctx, UserToBitHandshake inbound) throws Exception {
BitToUserHandshake handshakeResp = getHandshakeResponse(inbound);
OutboundRpcMessage msg = new OutboundRpcMessage(RpcMode.RESPONSE, this.handshakeType, coordinationId, handshakeResp);
ctx.writeAndFlush(msg);
if (handshakeResp.getStatus() != HandshakeStatus.SUCCESS && handshakeResp.getStatus() != HandshakeStatus.AUTH_REQUIRED) {
// If handling handshake results in an error, throw an exception to terminate the connection.
throw new RpcException("Handshake request failed: " + handshakeResp.getErrorMessage());
}
}
@Override
public BitToUserHandshake getHandshakeResponse(UserToBitHandshake inbound) throws Exception {
if (logger.isTraceEnabled()) {
logger.trace("Handling handshake from user to bit. {}", serializeUserToBitHandshakeWithoutPassword(inbound));
}
// if timeout is unsupported or is set to false, disable timeout.
if (!inbound.hasSupportTimeout() || !inbound.getSupportTimeout()) {
connection.disableReadTimeout();
logger.warn("Timeout Disabled as client doesn't support it.", connection.getName());
}
BitToUserHandshake.Builder respBuilder = BitToUserHandshake.newBuilder().setRpcVersion(UserRpcConfig.RPC_VERSION).setServerInfos(UserRpcUtils.getRpcEndpointInfos(SERVER_NAME)).addAllSupportedMethods(UserRpcConfig.SUPPORTED_SERVER_METHODS);
try {
if (inbound.getRpcVersion() != UserRpcConfig.RPC_VERSION) {
final String errMsg = String.format("Invalid rpc version. Expected %d, actual %d.", UserRpcConfig.RPC_VERSION, inbound.getRpcVersion());
return handleFailure(respBuilder, HandshakeStatus.RPC_VERSION_MISMATCH, errMsg, null);
}
connection.setHandshake(inbound);
if (!config.isAuthEnabled()) {
connection.finalizeSession(inbound.getCredentials().getUserName());
respBuilder.setStatus(HandshakeStatus.SUCCESS);
return respBuilder.build();
}
// If sasl_support field is absent in handshake message then treat the client as < 1.10 client
final boolean clientSupportsSasl = inbound.hasSaslSupport();
// saslSupportOrdinal will be set to UNKNOWN_SASL_SUPPORT, if sasl_support field in handshake is set to a
// value which is unknown to this server. We will treat those clients as one which knows SASL protocol.
final int saslSupportOrdinal = (clientSupportsSasl) ? inbound.getSaslSupport().ordinal() : SaslSupport.UNKNOWN_SASL_SUPPORT.ordinal();
// Check if client doesn't support SASL or only supports SASL_AUTH and server has encryption enabled
if ((!clientSupportsSasl || saslSupportOrdinal == SaslSupport.SASL_AUTH.ordinal()) && config.isEncryptionEnabled()) {
throw new UserAuthenticationException("The server doesn't allow client without encryption support." + " Please upgrade your client or talk to your system administrator.");
}
if (!clientSupportsSasl) {
// for backward compatibility < 1.10
final String userName = inbound.getCredentials().getUserName();
if (logger.isTraceEnabled()) {
logger.trace("User {} on connection {} is likely using an older client.", userName, connection.getRemoteAddress());
}
try {
String password = "";
final UserProperties props = inbound.getProperties();
for (int i = 0; i < props.getPropertiesCount(); i++) {
Property prop = props.getProperties(i);
if (DrillProperties.PASSWORD.equalsIgnoreCase(prop.getKey())) {
password = prop.getValue();
break;
}
}
final PlainFactory plainFactory;
try {
plainFactory = (PlainFactory) config.getAuthProvider().getAuthenticatorFactory(PlainFactory.SIMPLE_NAME);
} catch (final SaslException e) {
throw new UserAuthenticationException("The server no longer supports username/password" + " based authentication. Please talk to your system administrator.");
}
plainFactory.getAuthenticator().authenticate(userName, password);
connection.changeHandlerTo(config.getMessageHandler());
connection.finalizeSession(userName);
respBuilder.setStatus(HandshakeStatus.SUCCESS);
if (logger.isTraceEnabled()) {
logger.trace("Authenticated {} successfully using PLAIN from {}", userName, connection.getRemoteAddress());
}
return respBuilder.build();
} catch (UserAuthenticationException ex) {
return handleFailure(respBuilder, HandshakeStatus.AUTH_FAILED, ex.getMessage(), ex);
}
}
// Offer all the configured mechanisms to client. If certain mechanism doesn't support encryption
// like PLAIN, those should fail during the SASL handshake negotiation.
respBuilder.addAllAuthenticationMechanisms(config.getAuthProvider().getAllFactoryNames());
// set the encrypted flag in handshake message. For older clients this field is optional so will be ignored
respBuilder.setEncrypted(connection.isEncryptionEnabled());
respBuilder.setMaxWrappedSize(connection.getMaxWrappedSize());
// for now, this means PLAIN credentials will be sent over twice
// (during handshake and during sasl exchange)
respBuilder.setStatus(HandshakeStatus.AUTH_REQUIRED);
return respBuilder.build();
} catch (Exception e) {
return handleFailure(respBuilder, HandshakeStatus.UNKNOWN_FAILURE, e.getMessage(), e);
}
}
};
}
Aggregations