use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project alien4cloud by alien4cloud.
the class WebSocketClientHandler method messageReceived.
@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
// The first message must be authentication response
if (this.authenticationUrl != null && (this.cookies == null || this.cookies.isEmpty())) {
HttpResponse response = (HttpResponse) msg;
CharSequence cookieData = response.headers().get(new AsciiString("set-cookie"));
if (cookieData != null) {
this.cookies = ServerCookieDecoder.decode(cookieData.toString());
if (this.cookies == null || this.cookies.isEmpty()) {
throw new WebSocketAuthenticationFailureException("Could not authenticate");
}
if (log.isDebugEnabled()) {
for (Cookie cookie : this.cookies) {
log.debug("Server says must set cookie with name {} and value {}", cookie.name(), cookie.value());
}
}
} else {
throw new ITException("Could not authenticate");
}
if (log.isDebugEnabled()) {
log.debug("Authentication succeeded for user {}", this.user);
}
handShaker.handshake(ctx.channel());
return;
}
// The second one must be the response for web socket handshake
if (!handShaker.isHandshakeComplete()) {
handShaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
if (log.isDebugEnabled()) {
log.debug("Web socket client connected for user {}", this.user);
}
handshakeFuture.setSuccess();
return;
}
// Take the byte buff and send it up to Stomp decoder
if (msg instanceof WebSocketFrame) {
if (log.isDebugEnabled()) {
if (msg instanceof TextWebSocketFrame) {
log.debug("Received text frame {}", ((TextWebSocketFrame) msg).text());
}
}
ReferenceCountUtil.retain(msg);
ctx.fireChannelRead(((WebSocketFrame) msg).content());
}
}
use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project alien4cloud by alien4cloud.
the class WebSocketClientHandler method write.
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof HttpRequest) {
if (this.cookies != null && !this.cookies.isEmpty()) {
HttpRequest request = (HttpRequest) msg;
request.headers().set(new AsciiString("cookie"), ClientCookieEncoder.encode(cookies));
if (log.isDebugEnabled()) {
log.debug("Write HttpRequest {} enriched with security cookie", request);
}
}
super.write(ctx, msg, promise);
return;
}
String wrappedFrame = ((ByteBuf) msg).toString(Charset.forName("UTF-8"));
if (log.isDebugEnabled()) {
log.debug("Write text frame {}", wrappedFrame);
}
WebSocketFrame webSocketFrame = new TextWebSocketFrame(wrappedFrame);
super.write(ctx, webSocketFrame, promise);
}
use of io.netty.handler.codec.http.websocketx.WebSocketFrame in project undertow by undertow-io.
the class WebSocketTestClient method destroy.
/**
* Destroy the client and also close open connections if any exist
*/
public void destroy() {
if (!closed) {
final CountDownLatch latch = new CountDownLatch(1);
send(new CloseWebSocketFrame(), new FrameListener() {
@Override
public void onFrame(WebSocketFrame frame) {
latch.countDown();
}
@Override
public void onError(Throwable t) {
latch.countDown();
}
});
try {
latch.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
// bootstrap.releaseExternalResources();
if (ch != null) {
ch.close().syncUninterruptibly();
}
try {
bootstrap.group().shutdownGracefully(0, 1, TimeUnit.SECONDS).get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
use of io.netty.handler.codec.http.websocketx.WebSocketFrame 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.WebSocketFrame in project async-http-client by AsyncHttpClient.
the class WebSocketHandler method handleRead.
@Override
public void handleRead(Channel channel, NettyResponseFuture<?> future, Object e) throws Exception {
if (e instanceof HttpResponse) {
HttpResponse response = (HttpResponse) e;
if (logger.isDebugEnabled()) {
HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
logger.debug("\n\nRequest {}\n\nResponse {}\n", httpRequest, response);
}
WebSocketUpgradeHandler handler = getWebSocketUpgradeHandler(future);
HttpResponseStatus status = new NettyResponseStatus(future.getUri(), response, channel);
HttpHeaders responseHeaders = response.headers();
if (!interceptors.exitAfterIntercept(channel, future, handler, response, status, responseHeaders)) {
switch(handler.onStatusReceived(status)) {
case CONTINUE:
upgrade(channel, future, handler, response, responseHeaders);
break;
default:
abort(channel, future, handler, status);
}
}
} else if (e instanceof WebSocketFrame) {
WebSocketFrame frame = (WebSocketFrame) e;
NettyWebSocket webSocket = getNettyWebSocket(future);
// retain because we might buffer the frame
if (webSocket.isReady()) {
webSocket.handleFrame(frame);
} else {
// WebSocket hasn't been opened yet, but upgrading the pipeline triggered a read and a frame was sent along the HTTP upgrade response
// as we want to keep sequential order (but can't notify user of open before upgrading so he doesn't to try send immediately), we have to buffer
webSocket.bufferFrame(frame);
}
} else if (!(e instanceof LastHttpContent)) {
// ignore, end of handshake response
logger.error("Invalid message {}", e);
}
}
Aggregations