io.netty.handler.codec.http.FullHttpRequest Java Examples
The following examples show how to use
io.netty.handler.codec.http.FullHttpRequest.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HelloWorldHttp1Handler.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpUtil.isKeepAlive(req); ByteBuf content = ctx.alloc().buffer(); content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate()); ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")"); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } }
Example #2
Source File: ChatHandler.java From momo-cloud-permission with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //首次连接是FullHttpRequest,处理参数 if (msg instanceof FullHttpRequest) { FullHttpRequest request = (FullHttpRequest) msg; String uri = request.uri(); Map paramMap = getUrlParams(uri); //如果url包含参数,需要处理 if (uri.contains("?")) { String newUri = uri.substring(0, uri.indexOf("?")); request.setUri(newUri); } Object obj = paramMap.get("token"); if (null == obj || "undefined".equals(obj)) { ctx.channel().close(); return; } ChannelManager.putChannel(ChannelManager.channelLongText(ctx), ctx.channel()); } else if (msg instanceof TextWebSocketFrame) { //正常的TEXT消息类型 // TextWebSocketFrame frame = (TextWebSocketFrame) msg; } super.channelRead(ctx, msg); }
Example #3
Source File: ProtocolHandler.java From activemq-artemis with Apache License 2.0 | 6 votes |
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest request = (FullHttpRequest) msg; HttpHeaders headers = request.headers(); String upgrade = headers.get("upgrade"); if (upgrade != null && upgrade.equalsIgnoreCase("websocket")) { ctx.pipeline().addLast("websocket-handler", new WebSocketServerHandler(websocketSubprotocolIds, ConfigurationHelper.getIntProperty(TransportConstants.STOMP_MAX_FRAME_PAYLOAD_LENGTH, TransportConstants.DEFAULT_STOMP_MAX_FRAME_PAYLOAD_LENGTH, nettyAcceptor.getConfiguration()))); ctx.pipeline().addLast(new ProtocolDecoder(false, false)); ctx.pipeline().remove(this); ctx.pipeline().remove("http-handler"); ctx.fireChannelRead(msg); } else if (upgrade != null && upgrade.equalsIgnoreCase(NettyConnector.ACTIVEMQ_REMOTING)) { // HORNETQ-1391 // Send the response and close the connection if necessary. ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)).addListener(ChannelFutureListener.CLOSE); } } else { super.channelRead(ctx, msg); } }
Example #4
Source File: Http2StreamFrameToHttpObjectCodecTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
@Test public void testDowngradeHeaders() throws Exception { EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(true)); Http2Headers headers = new DefaultHttp2Headers(); headers.path("/"); headers.method("GET"); assertTrue(ch.writeInbound(new DefaultHttp2HeadersFrame(headers))); HttpRequest request = ch.readInbound(); assertThat(request.uri(), is("/")); assertThat(request.method(), is(HttpMethod.GET)); assertThat(request.protocolVersion(), is(HttpVersion.HTTP_1_1)); assertFalse(request instanceof FullHttpRequest); assertTrue(HttpUtil.isTransferEncodingChunked(request)); assertThat(ch.readInbound(), is(nullValue())); assertFalse(ch.finish()); }
Example #5
Source File: TwilioScriptHandler.java From arcusplatform with Apache License 2.0 | 6 votes |
private Map<String, Object> initializeContext(FullHttpRequest request) { HttpRequestParameters requestParams = new HttpRequestParameters(request); Map<String, Object> context = new HashMap<>(); context.put(SCRIPT_PARAM, requestParams.getParameter(SCRIPT_PARAM)); context.put(STEP_PARAM, requestParams.getParameter(STEP_PARAM, getInitialStep())); context.put(PLACE_ID_PARAM_NAME, requestParams.getParameter(PLACE_ID_PARAM_NAME, "")); context.put(PERSON_ID_PARAM_NAME, requestParams.getParameter(PERSON_ID_PARAM_NAME)); context.put(TWILIO_DIGITS_PARAM, requestParams.getParameter(TWILIO_DIGITS_PARAM, "")); context.put(NOTIFICATION_ID_PARAM_NAME, requestParams.getParameter(NOTIFICATION_ID_PARAM_NAME)); context.put(NOTIFICATION_EVENT_TIME_PARAM_NAME, requestParams.getParameter(NOTIFICATION_EVENT_TIME_PARAM_NAME)); context.put(CUSTOM_MESSAGE_PARAM, requestParams.getParameter(CUSTOM_MESSAGE_PARAM, "")); context.put(CUSTOM_PARAMETERS_KEY, getCustomParameters(requestParams)); customizeContext(context, requestParams); return context; }
Example #6
Source File: WebSocketHandler.java From socketio with Apache License 2.0 | 6 votes |
private void handshake(final ChannelHandlerContext ctx, final FullHttpRequest req, final String requestPath) { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true, maxWebSocketFrameSize); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker != null) { handshaker.handshake(ctx.channel(), req).addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { final String sessionId = PipelineUtils.getSessionId(requestPath); if (future.isSuccess()) { ctx.channel().pipeline().addBefore( SocketIOChannelInitializer.SOCKETIO_WEBSOCKET_HANDLER, SocketIOChannelInitializer.WEBSOCKET_FRAME_AGGREGATOR, new WebSocketFrameAggregator(maxWebSocketFrameSize)); connect(ctx, req, sessionId); } else { log.error("Can't handshake: {}", sessionId, future.cause()); } } }); } else { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } }
Example #7
Source File: UserAuthHandler.java From JavaQuarkBBS with Apache License 2.0 | 6 votes |
/** * HTTP握手反馈 */ private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request){ //判断是否是WebSocket协议 if (!request.decoderResult().isSuccess() || !"websocket".equals(request.headers().get("Upgrade"))) { logger.warn("protobuf don't support WebSocket"); ctx.channel().close(); return; } WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory( WEBSOCKET_URL, null, true); handshaker = handshakerFactory.newHandshaker(request); if (handshaker == null){ WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); }else { // 动态加入websocket的编解码处理 handshaker.handshake(ctx.channel(), request); // 存储已经连接的Channel manager.addChannel(ctx.channel()); } }
Example #8
Source File: TestUtils.java From digdag with Apache License 2.0 | 6 votes |
/** * Starts a proxy that fails all requests except every {@code failures}'th request per unique (method, uri) pair. */ public static HttpProxyServer startRequestFailingProxy(int defaultFailures, ConcurrentMap<String, List<FullHttpRequest>> requests, HttpResponseStatus error, BiFunction<FullHttpRequest, Integer, Optional<Boolean>> customFailDecider) { return startRequestFailingProxy(request -> { String key = request.getMethod() + " " + request.getUri(); List<FullHttpRequest> keyedRequests = requests.computeIfAbsent(key, k -> new ArrayList<>()); int n; synchronized (keyedRequests) { keyedRequests.add(request.copy()); n = keyedRequests.size(); } boolean fail = customFailDecider.apply(request, n).or(() -> n % defaultFailures != 0); if (fail) { return Optional.of(error); } else { return Optional.absent(); } }); }
Example #9
Source File: UserAuthHandler.java From HappyChat with Apache License 2.0 | 6 votes |
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) { if (!request.decoderResult().isSuccess() || !"websocket".equals(request.headers().get("Upgrade"))) { logger.warn("protobuf don't support websocket"); ctx.channel().close(); return; } WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory( Constants.WEBSOCKET_URL, null, true); handshaker = handshakerFactory.newHandshaker(request); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { // 动态加入websocket的编解码处理 handshaker.handshake(ctx.channel(), request); UserInfo userInfo = new UserInfo(); userInfo.setAddr(NettyUtil.parseChannelRemoteAddr(ctx.channel())); // 存储已经连接的Channel UserInfoManager.addChannel(ctx.channel()); } }
Example #10
Source File: WebSocketRequestBuilder.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
public FullHttpRequest build() { FullHttpRequest req = new DefaultFullHttpRequest(httpVersion, method, uri); HttpHeaders headers = req.headers(); if (host != null) { headers.set(HttpHeaderNames.HOST, host); } if (upgrade != null) { headers.set(HttpHeaderNames.UPGRADE, upgrade); } if (connection != null) { headers.set(HttpHeaderNames.CONNECTION, connection); } if (key != null) { headers.set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key); } if (origin != null) { headers.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, origin); } if (version != null) { headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, version.toHttpHeaderValue()); } return req; }
Example #11
Source File: EndPointManager.java From ThinkMap with Apache License 2.0 | 6 votes |
public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) throws Exception { if (endPoints.containsKey(uri.getPath())) { endPoints.get(uri.getPath()).handle(context, uri, request); return; } for (Map.Entry<Pattern, EndPoint> e : specialPoints.entrySet()) { if (e.getKey().matcher(uri.getPath()).find()) { e.getValue().handle(context, uri, request); return; } } if (def != null) { def.handle(context, uri, request); } else { HTTPHandler.sendHttpResponse(context, request, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND) ); } }
Example #12
Source File: ChunkEndPoint.java From ThinkMap with Apache License 2.0 | 6 votes |
@Override public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, context.alloc().buffer()); response.headers().add("Access-Control-Allow-Origin", "*"); response.headers().add("Access-Control-Allow-Methods", "POST"); if (request.getMethod() == OPTIONS) { response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept"); } if (request.getMethod() == POST) { String[] args = request.content().toString(Charsets.UTF_8).split(":"); ByteBuf out = response.content(); if (plugin.getChunkManager(plugin.getTargetWorld()).getChunkBytes(Integer.parseInt(args[0]), Integer.parseInt(args[1]), out)) { response.headers().add("Content-Encoding", "gzip"); } else { out.writeBytes(new byte[1]); } } sendHttpResponse(context, request, response); }
Example #13
Source File: AsyncRequestHandler.java From nesty with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest httpRequest) throws Exception { this.context = ctx; // build context httpContext = HttpContext.build(new NettyHttpRequestVisitor(context.channel(), httpRequest)); // execute async logic code block doRun(); }
Example #14
Source File: WebSocketServerProtocolHandshakeHandler.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception { FullHttpRequest req = (FullHttpRequest) msg; try { if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketLocation(ctx.pipeline(), req, websocketPath), subprotocols, allowExtensions, maxFramePayloadSize); final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req); handshakeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } else { ctx.fireUserEventTriggered( WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE); } } }); WebSocketServerProtocolHandler.setHandshaker(ctx, handshaker); ctx.pipeline().replace(this, "WS403Responder", WebSocketServerProtocolHandler.forbiddenHttpRequestResponder()); } } finally { req.release(); } }
Example #15
Source File: WebSocketServerHandler.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; boolean handle = handleWebSocketFrame(ctx, frame); if (handle) { ctx.fireChannelRead(frame.content().retain()); } } }
Example #16
Source File: WebSocketIndexPageHandler.java From tools-journey with Apache License 2.0 | 5 votes |
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
Example #17
Source File: GoogleHomeHandler.java From arcusplatform with Apache License 2.0 | 5 votes |
private void writeResult(ChannelHandlerContext ctx, FullHttpRequest req, Request googleRequest, Response res) { String json = Transformers.GSON.toJson(res); logger.trace("[{}] resulted in response [{}]", googleRequest, json); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.content().writeBytes(json.getBytes(StandardCharsets.UTF_8)); httpSender.sendHttpResponse(ctx, req, response); }
Example #18
Source File: TestVerifyPinRESTHandler.java From arcusplatform with Apache License 2.0 | 5 votes |
@Test public void testMissingPinErrors() throws Exception { EasyMock.expect(personDao.findById(person.getId())).andReturn(person); EasyMock.expect(grantDao.findForEntity(person.getId())).andReturn(Arrays.asList(grant)); EasyMock.expect(client.getPrincipalId()).andReturn(person.getId()).anyTimes(); replay(); FullHttpRequest req = createRequest(null, person.getCurrPlace().toString()); FullHttpResponse res = handler.respond(req, ctx); assertError(res, Errors.CODE_MISSING_PARAM); }
Example #19
Source File: UserAuthHandler.java From HappyChat with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } else if (msg instanceof WebSocketFrame) { handleWebSocket(ctx, (WebSocketFrame) msg); } }
Example #20
Source File: CorsHandlerTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private static FullHttpRequest optionsRequest(final String origin, final String requestHeaders, final AsciiString connection) { final FullHttpRequest httpRequest = createHttpRequest(OPTIONS); httpRequest.headers().set(ORIGIN, origin); httpRequest.headers().set(ACCESS_CONTROL_REQUEST_METHOD, httpRequest.method().toString()); httpRequest.headers().set(ACCESS_CONTROL_REQUEST_HEADERS, requestHeaders); if (connection != null) { httpRequest.headers().set(CONNECTION, connection); } return httpRequest; }
Example #21
Source File: WebSocketUriFilter.java From Summer with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) { if (wsUri.equalsIgnoreCase(request.uri())) { SessionContext sctx = serverContext.getSessionContextGroup().getSessionByChannel(ctx); if (sctx != null) sctx.setRealAddress(ForwardedAddressUtil.parse(request.headers().get(ForwardedAddressUtil.KEY))); ctx.fireChannelRead(request.retain()); } else { ctx.close(); throw new WebSocketUriNoFoundException(request.uri()); } }
Example #22
Source File: UploadHandler.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception { long startTime = System.nanoTime(); HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req); try { String place = null; int num = 0; while(decoder.hasNext()) { num++; InterfaceHttpData httpData = decoder.next(); if(httpData.getHttpDataType() == HttpDataType.Attribute && httpData.getName().equalsIgnoreCase("place")) { place = ((Attribute) httpData).getValue(); } else if(httpData.getHttpDataType() == HttpDataType.FileUpload) { String camProtAddr = URLDecoder.decode(httpData.getName(), "UTF-8"); Device d = findCamera(camProtAddr); if(d == null) { UPLOAD_UNKNOWN.inc(); logger.warn("ignoring preview upload for non-existent camera {}", camProtAddr); continue; } write(place, d, (FileUpload) httpData); } } HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); ChannelFuture future = ctx.writeAndFlush(response); if(!HttpHeaders.isKeepAlive(req)) { future.addListener(ChannelFutureListener.CLOSE); } UPLOAD_NUM.update(num); UPLOAD_SUCCESS.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); } catch (Exception ex) { UPLOAD_FAIL.update(System.nanoTime() - startTime, TimeUnit.NANOSECONDS); } finally { decoder.cleanFiles(); } }
Example #23
Source File: HttpThriftBufDecoder.java From nettythrift with Apache License 2.0 | 5 votes |
protected void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpHeaderUtil.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaderUtil.isKeepAlive(req) || res.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
Example #24
Source File: FrontendIntegrationTest.java From ambry with Apache License 2.0 | 5 votes |
/** * Verifies that a request returns the right response code once the blob has been deleted. * @param httpRequest the {@link FullHttpRequest} to send to the server. * @param expectedStatusCode the expected {@link HttpResponseStatus}. * @throws ExecutionException * @throws InterruptedException */ private void verifyDeleted(FullHttpRequest httpRequest, HttpResponseStatus expectedStatusCode) throws ExecutionException, InterruptedException { ResponseParts responseParts = nettyClient.sendRequest(httpRequest, null, null).get(); HttpResponse response = getHttpResponse(responseParts); assertEquals("Unexpected response status", expectedStatusCode, response.status()); assertTrue("No Date header", response.headers().get(HttpHeaderNames.DATE, null) != null); assertNoContent(responseParts.queue, 1); assertTrue("Channel should be active", HttpUtil.isKeepAlive(response)); verifyTrackingHeaders(response); }
Example #25
Source File: AbstractHandler.java From InChat with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof TextWebSocketFrame){ System.out.println("TextWebSocketFrame"+msg); textdoMessage(ctx,(TextWebSocketFrame)msg); }else if (msg instanceof WebSocketFrame){ System.out.println("WebSocketFrame"+msg); webdoMessage(ctx,(WebSocketFrame)msg); }else if (msg instanceof FullHttpRequest){ System.out.println("FullHttpRequest"+msg); httpdoMessage(ctx,(FullHttpRequest)msg); } }
Example #26
Source File: WhoisProtocolModuleTest.java From nomulus with Apache License 2.0 | 5 votes |
@Test public void testSuccess_multiFrameInboundMessage() { String frame1 = "test"; String frame2 = "1.tld"; String frame3 = "\r\nte"; String frame4 = "st2.tld\r"; String frame5 = "\ntest3.tld"; // No newline yet. assertThat(channel.writeInbound(Unpooled.wrappedBuffer(frame1.getBytes(US_ASCII)))).isFalse(); // Still no newline yet. assertThat(channel.writeInbound(Unpooled.wrappedBuffer(frame2.getBytes(US_ASCII)))).isFalse(); // First newline encountered. assertThat(channel.writeInbound(Unpooled.wrappedBuffer(frame3.getBytes(US_ASCII)))).isTrue(); FullHttpRequest actualRequest1 = channel.readInbound(); FullHttpRequest expectedRequest1 = makeWhoisHttpRequest( "test1.tld", PROXY_CONFIG.whois.relayHost, PROXY_CONFIG.whois.relayPath, TestModule.provideFakeAccessToken().get()); assertThat(actualRequest1).isEqualTo(expectedRequest1); // No more message at this point. assertThat((Object) channel.readInbound()).isNull(); // More inbound bytes, but no newline. assertThat(channel.writeInbound(Unpooled.wrappedBuffer(frame4.getBytes(US_ASCII)))).isFalse(); // Second message read. assertThat(channel.writeInbound(Unpooled.wrappedBuffer(frame5.getBytes(US_ASCII)))).isTrue(); FullHttpRequest actualRequest2 = channel.readInbound(); FullHttpRequest expectedRequest2 = makeWhoisHttpRequest( "test2.tld", PROXY_CONFIG.whois.relayHost, PROXY_CONFIG.whois.relayPath, TestModule.provideFakeAccessToken().get()); assertThat(actualRequest2).isEqualTo(expectedRequest2); // The third message is not complete yet. assertThat(channel.isActive()).isTrue(); assertThat((Object) channel.readInbound()).isNull(); }
Example #27
Source File: ProjectionManagerHttp.java From esjc with MIT License | 5 votes |
private CompletableFuture<String> get(String uri, UserCredentials userCredentials, HttpResponseStatus expectedStatus) { FullHttpRequest request = newRequest(HttpMethod.GET, uri, defaultOr(userCredentials)); return client.send(request).thenApply(response -> { if (response.status().code() == expectedStatus.code()) { return response.content().toString(UTF_8); } else if (response.status().code() == HttpResponseStatus.NOT_FOUND.code()) { throw new ProjectionNotFoundException(request, response); } else { throw new ProjectionException(request, response); } }); }
Example #28
Source File: RecurlyCallbackHttpHandler.java From arcusplatform with Apache License 2.0 | 5 votes |
public TemplatedResponse doHandle(FullHttpRequest request, ChannelHandlerContext ctx) throws Exception { Context timer = WEBHOOK_TIMER.time(); try{ String recurlyXML = request.content().toString(CharsetUtil.UTF_8); Document document = XMLHelper.parse(recurlyXML); String transactionType = document.getDocumentElement().getTagName(); WebhookHandler<? extends Object>handler=handlers.get(transactionType); if(transactionType.equals(TRANS_TYPE_CLOSED_INVOICE_NOTIFICATION)){ ClosedInvoiceNotification notification = XMLHelper.unmarshall(document,ClosedInvoiceNotification.class); ((WebhookHandler)handler).handleWebhook(notification); } else{ IGNORED_COUNTER.inc(); LOGGER.info(MSG_IGNORE_NOTIFICATION); } return createTemplateResponse(HttpResponseStatus.NO_CONTENT); } catch(Exception e){ ERRORED_COUNTER.inc(); LOGGER.error("Unknown error processing recurly webhook",e); return createTemplateResponse(HttpResponseStatus.BAD_REQUEST); } finally{ timer.stop(); } }
Example #29
Source File: SimpleWampWebsocketListener.java From GreenBits with GNU General Public License v3.0 | 5 votes |
private static void sendHttpResponse( ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); HttpHeaders.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
Example #30
Source File: TestAppLaunchHandler.java From arcusplatform with Apache License 2.0 | 5 votes |
@Test public void testMacUserAgent() throws Exception { FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "https://app.arcus.com/app/launch"); request.headers().add(HttpHeaders.Names.USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"); expectGetClient(); Capture<SessionHandoff> handoff = captureNewToken(); replay(); FullHttpResponse response = handler.respond(request, mockContext()); assertHandoff(handoff.getValue()); assertRedirectTo(response, "https://dev-app.arcus.com/other/run?token=token"); }