use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project carbon-apimgt by wso2.
the class WebsocketInboundHandler method channelRead.
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
String channelId = ctx.channel().id().asLongText();
// This block is for the health check of the ports 8099 and 9099
if (msg instanceof FullHttpRequest && ((FullHttpRequest) msg).headers() != null && !((FullHttpRequest) msg).headers().contains(HttpHeaders.UPGRADE) && ((FullHttpRequest) msg).uri().equals(APIConstants.WEB_SOCKET_HEALTH_CHECK_PATH)) {
ctx.fireChannelRead(msg);
return;
}
InboundMessageContext inboundMessageContext;
if (InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(channelId)) {
inboundMessageContext = InboundMessageContextDataHolder.getInstance().getInboundMessageContextForConnectionId(channelId);
} else {
inboundMessageContext = new InboundMessageContext();
InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelId, inboundMessageContext);
}
inboundMessageContext.setUserIP(getRemoteIP(ctx));
if (APIUtil.isAnalyticsEnabled()) {
WebSocketUtils.setApiPropertyToChannel(ctx, org.wso2.carbon.apimgt.gateway.handlers.analytics.Constants.REQUEST_START_TIME_PROPERTY, System.currentTimeMillis());
WebSocketUtils.setApiPropertyToChannel(ctx, org.wso2.carbon.apimgt.gateway.handlers.analytics.Constants.USER_IP_PROPERTY, inboundMessageContext.getUserIP());
}
// check if the request is a handshake
if (msg instanceof FullHttpRequest) {
FullHttpRequest req = (FullHttpRequest) msg;
populateContextHeaders(req, inboundMessageContext);
InboundProcessorResponseDTO responseDTO = webSocketProcessor.handleHandshake(req, ctx, inboundMessageContext);
if (!responseDTO.isError()) {
setApiAuthPropertiesToChannel(ctx, inboundMessageContext);
if (StringUtils.isNotEmpty(inboundMessageContext.getToken())) {
req.headers().set(APIMgtGatewayConstants.WS_JWT_TOKEN_HEADER, inboundMessageContext.getToken());
}
ctx.fireChannelRead(req);
publishHandshakeEvent(ctx, inboundMessageContext);
InboundWebsocketProcessorUtil.publishGoogleAnalyticsData(inboundMessageContext, ctx.channel().remoteAddress().toString());
} else {
InboundMessageContextDataHolder.getInstance().removeInboundMessageContextForConnection(channelId);
FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(responseDTO.getErrorCode()), Unpooled.copiedBuffer(responseDTO.getErrorMessage(), CharsetUtil.UTF_8));
httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());
ctx.writeAndFlush(httpResponse);
}
} else if ((msg instanceof CloseWebSocketFrame) || (msg instanceof PingWebSocketFrame)) {
// remove inbound message context from data holder
InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().remove(channelId);
// if the inbound frame is a closed frame, throttling, analytics will not be published.
ctx.fireChannelRead(msg);
} else if (msg instanceof WebSocketFrame) {
InboundProcessorResponseDTO responseDTO = webSocketProcessor.handleRequest((WebSocketFrame) msg, inboundMessageContext);
if (responseDTO.isError()) {
if (responseDTO.isCloseConnection()) {
// remove inbound message context from data holder
InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().remove(channelId);
if (log.isDebugEnabled()) {
log.debug("Error while handling Outbound Websocket frame. Closing connection for " + ctx.channel().toString());
}
ctx.writeAndFlush(new CloseWebSocketFrame(responseDTO.getErrorCode(), responseDTO.getErrorMessage() + StringUtils.SPACE + "Connection closed" + "!"));
ctx.close();
} else {
String errorMessage = responseDTO.getErrorResponseString();
ctx.writeAndFlush(new TextWebSocketFrame(errorMessage));
if (responseDTO.getErrorCode() == WebSocketApiConstants.FrameErrorConstants.THROTTLED_OUT_ERROR) {
if (log.isDebugEnabled()) {
log.debug("Inbound Websocket frame is throttled. " + ctx.channel().toString());
}
publishPublishThrottledEvent(ctx);
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Sending Inbound Websocket frame." + ctx.channel().toString());
}
ctx.fireChannelRead(msg);
// publish analytics events if analytics is enabled
publishPublishEvent(ctx);
}
}
}
use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project ballerina by ballerina-lang.
the class WebSocketRemoteServerFrameHandler method channelRead0.
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
if (frame instanceof TextWebSocketFrame) {
// Echos the same text
String text = ((TextWebSocketFrame) frame).text();
if (PING.equals(text)) {
ctx.channel().writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(ByteBuffer.wrap(new byte[] { 1, 2, 3, 4, 5 }))));
return;
}
ctx.channel().writeAndFlush(new TextWebSocketFrame(text));
} else if (frame instanceof CloseWebSocketFrame) {
ctx.close();
isOpen = false;
} else {
String message = "unsupported frame type: " + frame.getClass().getName();
throw new UnsupportedOperationException(message);
}
}
use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project ballerina by ballerina-lang.
the class WebSocketClient method shutDown.
/**
* Shutdown the WebSocket Client.
*/
public void shutDown() throws InterruptedException {
channel.writeAndFlush(new CloseWebSocketFrame());
channel.closeFuture().sync();
group.shutdownGracefully();
}
use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project ballerina by ballerina-lang.
the class WebSocketClientHandler method channelRead0.
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
Channel ch = ctx.channel();
if (!handshaker.isHandshakeComplete()) {
handshaker.finishHandshake(ch, (FullHttpResponse) msg);
LOGGER.debug("WebSocket Client connected!");
handshakeFuture.setSuccess();
return;
}
if (msg instanceof FullHttpResponse) {
FullHttpResponse response = (FullHttpResponse) msg;
throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
}
WebSocketFrame frame = (WebSocketFrame) msg;
if (frame instanceof TextWebSocketFrame) {
TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
LOGGER.debug("WebSocket Client received text message: " + textFrame.text());
String textReceived = textFrame.text();
callback.call(textReceived);
} else if (frame instanceof CloseWebSocketFrame) {
isConnected = false;
LOGGER.debug("WebSocket Client received closing");
ch.close();
}
}
use of io.netty.handler.codec.http.websocketx.CloseWebSocketFrame in project netty-socketio by mrniko.
the class WebSocketTransport method channelRead.
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof CloseWebSocketFrame) {
ctx.channel().writeAndFlush(msg).addListener(ChannelFutureListener.CLOSE);
} else if (msg instanceof BinaryWebSocketFrame || msg instanceof TextWebSocketFrame) {
ByteBufHolder frame = (ByteBufHolder) msg;
ClientHead client = clientsBox.get(ctx.channel());
if (client == null) {
log.debug("Client with was already disconnected. Channel closed!");
ctx.channel().close();
frame.release();
return;
}
ctx.pipeline().fireChannelRead(new PacketsMessage(client, frame.content(), Transport.WEBSOCKET));
frame.release();
} else if (msg instanceof FullHttpRequest) {
FullHttpRequest req = (FullHttpRequest) msg;
QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri());
String path = queryDecoder.path();
List<String> transport = queryDecoder.parameters().get("transport");
List<String> sid = queryDecoder.parameters().get("sid");
if (transport != null && NAME.equals(transport.get(0))) {
try {
if (!configuration.getTransports().contains(Transport.WEBSOCKET)) {
log.debug("{} transport not supported by configuration.", Transport.WEBSOCKET);
ctx.channel().close();
return;
}
if (sid != null && sid.get(0) != null) {
final UUID sessionId = UUID.fromString(sid.get(0));
handshake(ctx, sessionId, path, req);
} else {
ClientHead client = ctx.channel().attr(ClientHead.CLIENT).get();
// first connection
handshake(ctx, client.getSessionId(), path, req);
}
} finally {
req.release();
}
} else {
ctx.fireChannelRead(msg);
}
} else {
ctx.fireChannelRead(msg);
}
}
Aggregations