/** * Process response debug * * @param response Response Object * @param m_ctx Netty Context * @return Return indicator shows if the response requires handling for debugging. If true, the caller needs to stop handling response */ public boolean debugResponse(FullHttpResponse response, ChannelHandlerContext m_ctx) { boolean consume = false; if (debugEnabled()) { Attribute<CacheResultVerifier> debugResult = m_ctx.attr(DEBUG_RESULT); if (debugResult.get() != null) { try { CacheVerifiedResult result = debugResult.get().fetchResult(response); m_cacheManager.getStats().addCacheVerifiedResult(result); } catch (Exception e) { LOGGER.error(e.getMessage()); } finally { consume = true; } } } return consume; }
@Test @SuppressWarnings("unchecked") public void testIssueDebugRequest_fromDebugFilter() { Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true); FullHttpRequest request = Mockito.mock(FullHttpRequest.class); FullHttpResponse cacheResponse = Mockito.mock(FullHttpResponse.class); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(request.copy()).thenReturn(request); Mockito.when(m_cacheManager.get("test_req")).thenReturn(cacheResponse); Mockito.when(m_policyManager.generateCacheKey(request)).thenReturn("test_req"); Attribute<CacheResultVerifier> debugging = Mockito.mock(Attribute.class); Mockito.when(ctx.attr(DebugManager.DEBUG_RESULT)).thenReturn(debugging); debugManager.issueDebugRequest(request, ctx, true); CacheResultVerifier verifier = new CacheResultVerifier("test_req", request, cacheResponse); Mockito.verify(debugging, Mockito.times(1)).set(Mockito.refEq(verifier)); }
@Test @SuppressWarnings("unchecked") public void testIssueDebugRequest_sslFromDebugFilter() { Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true); FullHttpRequest request = Mockito.mock(FullHttpRequest.class); FullHttpResponse cacheResponse = Mockito.mock(FullHttpResponse.class); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Mockito.when(ctx.handler()).thenReturn(clientToProxyConnection); Mockito.when(request.copy()).thenReturn(request); String key = "https://serverHostAndPort=www.ebay.com:443"; Mockito.when(m_cacheManager.get(key)).thenReturn(cacheResponse); Mockito.when(m_policyManager.generateCacheKey(request)).thenReturn(key); Attribute<CacheResultVerifier> debugging = Mockito.mock(Attribute.class); Mockito.when(ctx.attr(DebugManager.DEBUG_RESULT)).thenReturn(debugging); debugManager.issueDebugRequest(request, ctx, true); Assert.assertTrue((Boolean) readField(clientToProxyConnection, "mitming")); CacheResultVerifier verifier = new CacheResultVerifier(key, request, cacheResponse); Mockito.verify(debugging, Mockito.times(1)).set(Mockito.refEq(verifier)); }
@Test @SuppressWarnings("unchecked") public void testDebugResponse_consume() { Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true); FullHttpResponse actualResponse = Mockito.mock(FullHttpResponse.class); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Attribute<CacheResultVerifier> debugging = Mockito.mock(Attribute.class); Mockito.when(ctx.attr(DebugManager.DEBUG_RESULT)).thenReturn(debugging); CacheResultVerifier verifier = Mockito.mock(CacheResultVerifier.class); CacheVerifiedResult result = new CacheVerifiedResult(); result.key = "test_req"; Mockito.when(verifier.fetchResult(actualResponse)).thenReturn(result); Mockito.when(debugging.get()).thenReturn(verifier); CacheStats cacheStats = Mockito.mock(CacheStats.class); Mockito.when(m_cacheManager.getStats()).thenReturn(cacheStats); debugManager.debugResponse(actualResponse, ctx); Mockito.verify(cacheStats, Mockito.times(1)).addCacheVerifiedResult(verifier.fetchResult(actualResponse)); }
@Override public void handle(ChannelHandlerContext ctx, List<Packet> out) throws Exception { Attribute<InetSocketAddress> attr = ctx.attr(PipelineUtil.ADDRESS_ATTRIBUTE); PocketServer instance = PocketServer.getInstance(); InetSocketAddress address = attr.get(); Optional<PocketPlayer> optional = instance.getPlayer(address); if (!optional.isPresent()) { instance.getLogger().debug("No player found for {}.", address); return; } PocketPlayer player = optional.get(); if (player.getEntityId() != entityId) { instance.getLogger().debug("{} possibly spoofing block packets.", player); return; } //player.getWorld().setBlock(x, y, z, Material.AIR); //TODO: Debug why this doesn't set the correct positions PacketPlayOutUpdateBlock packet = new PacketPlayOutUpdateBlock(new PacketPlayOutUpdateBlock.BlockRecord(x, z, y, (byte) 0, (byte) 0)); instance.broadcast(packet); }
@Override public void handle(ChannelHandlerContext ctx, List<Packet> out) throws Exception { Attribute<InetSocketAddress> attr = ctx.attr(PipelineUtil.ADDRESS_ATTRIBUTE); Optional<PocketPlayer> optional = PocketServer.getInstance().getPlayer(attr.get()); if (!optional.isPresent()) { PocketServer.getInstance().getLogger().debug("No player found for address {}", attr.get()); } PocketPlayer player = optional.get(); if (player.getEntityId() != entityId) { PocketServer.getInstance().getLogger().debug("Possible spoof for player from address {}", attr.get()); } PocketServer.getInstance().getLogger().debug(MoreObjects.toStringHelper(this) .add("x", x) .add("y", y) .add("z", z) .add("pitch", pitch) .add("yaw", yaw) .add("bodyYaw", bodyYaw) .add("mode", mode) .add("onGround", onGround) .toString() ); PocketServer.getInstance().broadcast(this, p -> p != player); //TODO: Update player location }
@Before public void beforeMethod() { stateMock = mock(HttpProcessingState.class); ctxMock = mock(ChannelHandlerContext.class); channelMock = mock(Channel.class); stateAttrMock = mock(Attribute.class); endpointMock = mock(Endpoint.class); maxRequestSizeInBytes = 10; httpContentMock = mock(HttpContent.class); byteBufMock = mock(ByteBuf.class); requestInfo = mock(RequestInfo.class); handler = new RequestInfoSetterHandler(maxRequestSizeInBytes); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttrMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(stateMock).when(stateAttrMock).get(); doReturn(endpointMock).when(stateMock).getEndpointForExecution(); doReturn(byteBufMock).when(httpContentMock).content(); doReturn(null).when(endpointMock).maxRequestSizeInBytesOverride(); doReturn(requestInfo).when(stateMock).getRequestInfo(); }
@Before public void beforeMethod() { handlerSpy = spy(new DTraceEndHandler()); channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); resetTracingAndMdc(); responseInfoMock = mock(ResponseInfo.class); doReturn(true).when(responseInfoMock).isResponseSendingLastChunkSent(); state.setResponseInfo(responseInfoMock); lastChunkChannelFutureMock = mock(ChannelFuture.class); state.setResponseWriterFinalChunkChannelFuture(lastChunkChannelFutureMock); doAnswer(invocation -> { currentSpanWhenCompleteCurrentSpanWasCalled = Tracer.getInstance().getCurrentSpan(); invocation.callRealMethod(); currentSpanAfterCompleteCurrentSpanWasCalled = Tracer.getInstance().getCurrentSpan(); return null; }).when(handlerSpy).completeCurrentSpan(); }
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); firstChunkMsgMock = mock(HttpRequest.class); lastChunkMsgMock = mock(LastHttpContent.class); filter1Mock = mock(RequestAndResponseFilter.class); filter2Mock = mock(RequestAndResponseFilter.class); filtersList = Arrays.asList(filter1Mock, filter2Mock); handlerSpy = spy(new RequestFilterHandler(filtersList)); requestInfoMock = mock(RequestInfo.class); state.setRequestInfo(requestInfoMock); }
@Before public void beforeMethod() { stateMock = mock(HttpProcessingState.class); ctxMock = mock(ChannelHandlerContext.class); channelMock = mock(Channel.class); stateAttrMock = mock(Attribute.class); metricsListenerMock = mock(MetricsListener.class); msgMock = mock(HttpRequest.class); responseSenderMock = mock(ResponseSender.class); responseInfo = ResponseInfo.newBuilder(UUID.randomUUID().toString()).build(); endpointExecutedMock = mock(Endpoint.class); customSerializerMock = mock(ObjectMapper.class); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttrMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(stateMock).when(stateAttrMock).get(); doReturn(responseInfo).when(stateMock).getResponseInfo(); doReturn(endpointExecutedMock).when(stateMock).getEndpointForExecution(); doReturn(customSerializerMock).when(endpointExecutedMock).customResponseContentSerializer(any(RequestInfo.class)); handlerSpy = spy(new ResponseSenderHandler(responseSenderMock)); }
@Before public void beforeMethod() { stateMock = mock(HttpProcessingState.class); ctxMock = mock(ChannelHandlerContext.class); channelMock = mock(Channel.class); stateAttrMock = mock(Attribute.class); requestInfoMock = mock(RequestInfo.class); endpointMock = mock(StandardEndpoint.class); matcherMock = mock(Matcher.class); endpoints = new ArrayList<>(Collections.singleton(endpointMock)); httpHeaders = new DefaultHttpHeaders(); maxRequestSizeInBytes = 10; msg = mock(HttpRequest.class); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttrMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(stateMock).when(stateAttrMock).get(); doReturn(endpointMock).when(stateMock).getEndpointForExecution(); doReturn(matcherMock).when(endpointMock).requestMatcher(); doReturn(Optional.of(defaultPath)).when(matcherMock).matchesPath(any(RequestInfo.class)); doReturn(true).when(matcherMock).matchesMethod(any(RequestInfo.class)); doReturn(requestInfoMock).when(stateMock).getRequestInfo(); doReturn(httpHeaders).when(msg).headers(); handlerSpy = spy(new RoutingHandler(endpoints, maxRequestSizeInBytes)); }
@Before public void beforeMethod() { stateMock = mock(HttpProcessingState.class); ctxMock = mock(ChannelHandlerContext.class); channelMock = mock(Channel.class); pipelineMock = mock(ChannelPipeline.class); stateAttrMock = mock(Attribute.class); proxyRouterProcessingStateAttrMock = mock(Attribute.class); metricsListenerMock = mock(MetricsListener.class); msgMockFirstChunkOnly = mock(HttpRequest.class); msgMockFullRequest = mock(FullHttpRequest.class); msgMockLastChunkOnly = mock(LastHttpContent.class); idleChannelTimeoutHandlerMock = mock(IdleChannelTimeoutHandler.class); doReturn(channelMock).when(ctxMock).channel(); doReturn(pipelineMock).when(ctxMock).pipeline(); doReturn(idleChannelTimeoutHandlerMock).when(pipelineMock).get(IDLE_CHANNEL_TIMEOUT_HANDLER_NAME); doReturn(stateAttrMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(stateMock).when(stateAttrMock).get(); doReturn(proxyRouterProcessingStateAttrMock).when(channelMock).attr(ChannelAttributes.PROXY_ROUTER_PROCESSING_STATE_ATTRIBUTE_KEY); handler = new RequestStateCleanerHandler(metricsListenerMock, incompleteHttpCallTimeoutMillis); }
@Before public void beforeMethod() { requestValidatorMock = mock(RequestValidator.class); stateMock = mock(HttpProcessingState.class); ctxMock = mock(ChannelHandlerContext.class); channelMock = mock(Channel.class); stateAttrMock = mock(Attribute.class); endpointMock = mock(Endpoint.class); requestInfoMock = mock(RequestInfo.class); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttrMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(stateMock).when(stateAttrMock).get(); doReturn(endpointMock).when(stateMock).getEndpointForExecution(); doReturn(requestInfoMock).when(stateMock).getRequestInfo(); doReturn(true).when(endpointMock).isValidateRequestContent(any()); doReturn(content).when(requestInfoMock).getContent(); doReturn(true).when(requestInfoMock).isCompleteRequestWithAllChunks(); doReturn(true).when(requestInfoMock).isContentDeserializerSetup(); doReturn(content.length()).when(requestInfoMock).getRawContentLengthInBytes(); handler = new RequestContentValidationHandler(requestValidatorMock); }
@Before public void beforeMethod() { msg = mock(LastHttpContent.class); stateMock = mock(HttpProcessingState.class); ctxMock = mock(ChannelHandlerContext.class); channelMock = mock(Channel.class); stateAttrMock = mock(Attribute.class); endpointMock = mock(Endpoint.class); requestInfoSpy = spy((RequestInfo<String>) RequestInfoImpl.dummyInstanceForUnknownRequests()); String rawContentString = UUID.randomUUID().toString(); Whitebox.setInternalState(requestInfoSpy, "rawContent", rawContentString); Whitebox.setInternalState(requestInfoSpy, "rawContentBytes", rawContentString.getBytes()); defaultHandlerDeserializerMock = mock(ObjectMapper.class); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttrMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(stateMock).when(stateAttrMock).get(); doReturn(endpointMock).when(stateMock).getEndpointForExecution(); doReturn(requestInfoSpy).when(stateMock).getRequestInfo(); doReturn(contentTypeRef).when(endpointMock).requestContentType(); doReturn(endpointMatcher).when(endpointMock).requestMatcher(); handler = new RequestContentDeserializerHandler(defaultHandlerDeserializerMock); }
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); consumerMock = mock(Consumer.class); inObj = new Object(); throwExceptionDuringCall = false; currentSpanStackWhenConsumerWasCalled = new ArrayList<>(); currentMdcInfoWhenConsumerWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenConsumerWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenConsumerWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(consumerMock).accept(inObj); resetTracingAndMdc(); }
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); runnableMock = mock(Runnable.class); throwExceptionDuringCall = false; currentSpanStackWhenRunnableWasCalled = new ArrayList<>(); currentMdcInfoWhenRunnableWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenRunnableWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenRunnableWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(runnableMock).run(); resetTracingAndMdc(); }
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); supplierMock = mock(Supplier.class); outObj = new Object(); throwExceptionDuringCall = false; currentSpanStackWhenSupplierWasCalled = new ArrayList<>(); currentMdcInfoWhenSupplierWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenSupplierWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenSupplierWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return outObj; }).when(supplierMock).get(); resetTracingAndMdc(); }
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); consumerMock = mock(Consumer.class); inObj = mock(ChannelFuture.class); throwExceptionDuringCall = false; currentSpanStackWhenChannelFutureWasCalled = new ArrayList<>(); currentMdcInfoWhenChannelFutureWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenChannelFutureWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenChannelFutureWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(consumerMock).accept(inObj); resetTracingAndMdc(); }
@Before public void beforeMethod() throws Exception { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); callableMock = mock(Callable.class); throwExceptionDuringCall = false; currentSpanStackWhenCallableWasCalled = new ArrayList<>(); currentMdcInfoWhenCallableWasCalled = new ArrayList<>(); doAnswer(invocation -> { currentSpanStackWhenCallableWasCalled.add(Tracer.getInstance().getCurrentSpanStackCopy()); currentMdcInfoWhenCallableWasCalled.add(MDC.getCopyOfContextMap()); if (throwExceptionDuringCall) throw new RuntimeException("kaboom"); return null; }).when(callableMock).call(); resetTracingAndMdc(); }
@Before public void beforeMethod() { helperSpy = spy(new AsyncHttpClientHelper()); channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); eventLoopMock = mock(EventLoop.class); signatureCalculator = mock(SignatureCalculator.class); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); doReturn(eventLoopMock).when(channelMock).eventLoop(); handlerWithTracingAndMdcDummyExample = new AsyncCompletionHandlerWithTracingAndMdcSupport<>( null, null, false, null, null, null, null, null ); resetTracingAndMdc(); }
@Override protected void channelRead0(final ChannelHandlerContext channelHandlerContext, final ResponseMessage response) throws Exception { // We are only interested in AUTHENTICATE responses here. Everything else can // get passed down the pipeline if (response.getStatus().getCode() == ResponseStatusCode.AUTHENTICATE) { final Attribute<SaslClient> saslClient = channelHandlerContext.attr(saslClientKey); final Attribute<Subject> subject = channelHandlerContext.attr(subjectKey); RequestMessage.Builder messageBuilder = RequestMessage.build(Tokens.OPS_AUTHENTICATION); // First time through we don't have a sasl client if (saslClient.get() == null) { subject.set(login()); saslClient.set(saslClient(getHostName(channelHandlerContext))); messageBuilder.addArg(Tokens.ARGS_SASL_MECHANISM, getMechanism()); messageBuilder.addArg(Tokens.ARGS_SASL, saslClient.get().hasInitialResponse() ? evaluateChallenge(subject, saslClient, NULL_CHALLENGE) : null); } else { messageBuilder.addArg(Tokens.ARGS_SASL, evaluateChallenge(subject, saslClient, (byte[])response.getResult().getData())); } channelHandlerContext.writeAndFlush(messageBuilder.create()); } else { channelHandlerContext.fireChannelRead(response); } }
@Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { if (httpObject instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) httpObject; if (ProxyUtils.isCONNECT(httpRequest)) { Attribute<String> hostname = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.HOST_ATTRIBUTE_NAME)); String hostAndPort = httpRequest.getUri(); // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example) // would be unexpected. String hostNoDefaultPort = BrowserMobHttpUtil.removeMatchingPort(hostAndPort, 443); hostname.set(hostNoDefaultPort); } } return null; }
public static boolean bind(Channel channel, NettyClient nettyClient){ Attribute<NettyClient> attribute = channel.attr(KEY_CLIENT); if(attribute != null){ return false; } synchronized (channel) { attribute = channel.attr(KEY_CLIENT); if(attribute == null){ return false; } attribute.set(nettyClient); } return true; }
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Attribute<HttpServerChannelHandler> attr = ctx.attr(SERVER_HANDLER_KEY); HttpServerChannelHandler handler = attr.get(); if (handler != null) { handler.exceptionCaught(ctx, cause); } else { if (cause instanceof ClosedChannelException) { // The channel is closed so we do nothing here LOG.debug("Channel already closed. Ignoring this exception."); return; } else { // we cannot throw the exception here LOG.warn("HttpServerChannelHandler is not found as attachment to handle exception, send 404 back to the client.", cause); // Now we just send 404 back to the client HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND); response.headers().set(Exchange.CONTENT_TYPE, "text/plain"); response.headers().set(Exchange.CONTENT_LENGTH, 0); ctx.writeAndFlush(response); ctx.close(); } } }
@Override protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception { Attribute<ObjectOutputStream> oosAttr = ctx.attr(OOS); ObjectOutputStream oos = oosAttr.get(); if (oos == null) { oos = newObjectOutputStream(new ByteBufOutputStream(out)); ObjectOutputStream newOos = oosAttr.setIfAbsent(oos); if (newOos != null) { oos = newOos; } } synchronized (oos) { if (resetInterval != 0) { // Resetting will prevent OOM on the receiving side. writtenObjects ++; if (writtenObjects % resetInterval == 0) { oos.reset(); } } oos.writeObject(msg); oos.flush(); } }
@Override protected void messageReceived(ChannelHandlerContext ctx, Packet packet) throws Exception { Attribute<InetSocketAddress> addressAttribute = ctx.attr(PipelineUtils.ADDRESS_ATTRIBUTE); InetSocketAddress address = addressAttribute.get(); try { List<Packet> out = Lists.newLinkedList(); packet.record(this); packet.handle(ctx, out); packet.close(); for (Packet outbound : out) { ctx.write(outbound).addListener(new PacketChannelListener(address, packet)); } ctx.flush(); } finally { addressAttribute.remove(); } }
private DefaultClientRequestContext(DefaultClientRequestContext ctx, Request request) { super(ctx.meterRegistry(), ctx.sessionProtocol(), ctx.method(), ctx.path(), ctx.query(), request); this.eventLoop = ctx.eventLoop(); this.options = ctx.options(); this.endpoint = ctx.endpoint(); this.fragment = ctx.fragment(); log = new DefaultRequestLog(this); writeTimeoutMillis = ctx.writeTimeoutMillis(); responseTimeoutMillis = ctx.responseTimeoutMillis(); maxResponseLength = ctx.maxResponseLength(); for (Iterator<Attribute<?>> i = ctx.attrs(); i.hasNext();) { addAttr(i.next()); } runThreadLocalContextCustomizer(); }
@Test public void testGetSetString() { AttributeKey<String> key = AttributeKey.valueOf("Nothing"); Attribute<String> one = map.attr(key); assertSame(one, map.attr(key)); one.setIfAbsent("Whoohoo"); assertSame("Whoohoo", one.get()); one.setIfAbsent("What"); assertNotSame("What", one.get()); one.remove(); assertNull(one.get()); }
@Test public void testGetSetInt() { AttributeKey<Integer> key = AttributeKey.valueOf("Nada"); Attribute<Integer> one = map.attr(key); assertSame(one, map.attr(key)); one.setIfAbsent(3653); assertEquals(Integer.valueOf(3653), one.get()); one.setIfAbsent(1); assertNotSame(1, one.get()); one.remove(); assertNull(one.get()); }
@Test public void testBlockingRead() throws Exception{ Channel channel = client.connect("192.168.13.64", 8888); ByteBuffer buffer = ByteBuffer.allocate(10); buffer.putShort((short)8); buffer.putLong(3l); buffer.flip(); boolean wrote = false; while (!wrote) { while (channel.isWritable()) { channel.writeAndFlush(buffer.array()); wrote = true; break; } } Attribute<BlockingRead> value = channel.attr(BlockingRead.CHANNEL_BLOCKING_READ_KEY); if (value.get() == null) { throw new NullPointerException(); } Object result = value.get().read(); System.out.println(result); System.in.read(); }
@Test public void joinRoom_firstTime_isOpen() { KixmppServer server = (KixmppServer)Mockito.when(Mockito.mock(KixmppServer.class).getEventEngine()) .thenReturn(new KixmppEventEngine()).getMock(); MucService mucService = (MucService)Mockito.when(Mockito.mock(MucService.class).getServer()) .thenReturn(server).getMock(); KixmppJid roomJid = new KixmppJid("testnode", "testdomain"); MucRoom mucRoom = new MucRoom(mucService, roomJid, new MucRoomSettings(false, true, null)); Channel channel = Mockito.mock(Channel.class); Attribute<KixmppJid> jidAttribute = Mockito.mock(Attribute.class); Mockito.when(jidAttribute.get()).thenReturn(new KixmppJid("test.user", "testdomain", "testresource")); Mockito.when(channel.attr(BindKixmppServerModule.JID)).thenReturn(jidAttribute); Mockito.when(channel.closeFuture()).thenReturn(Mockito.mock(ChannelFuture.class)); Assert.assertEquals(0, mucRoom.getUsers().size()); mucRoom.join(channel, "nickname"); Assert.assertEquals(1, mucRoom.getUsers().size()); }
@Test(expected = RoomJoinNotAllowedException.class) public void joinRoom_firstTime_isNotOpen_noMemberAdded() { KixmppServer server = (KixmppServer)Mockito.when(Mockito.mock(KixmppServer.class).getEventEngine()) .thenReturn(new KixmppEventEngine()).getMock(); MucService mucService = (MucService)Mockito.when(Mockito.mock(MucService.class).getServer()) .thenReturn(server).getMock(); KixmppJid roomJid = new KixmppJid("testnode", "testdomain"); MucRoom mucRoom = new MucRoom(mucService, roomJid, new MucRoomSettings(false, false, null)); Channel channel = Mockito.mock(Channel.class); Attribute<KixmppJid> jidAttribute = Mockito.mock(Attribute.class); Mockito.when(jidAttribute.get()).thenReturn(new KixmppJid("test.user", "testdomain", "testresource")); Mockito.when(channel.attr(BindKixmppServerModule.JID)).thenReturn(jidAttribute); Mockito.when(channel.closeFuture()).thenReturn(Mockito.mock(ChannelFuture.class)); mucRoom.join(channel, "nickname"); }
@Test public void joinRoom_firstTime_isNotOpen_memberAdded() { KixmppServer server = (KixmppServer)Mockito.when(Mockito.mock(KixmppServer.class).getEventEngine()) .thenReturn(new KixmppEventEngine()).getMock(); MucService mucService = (MucService)Mockito.when(Mockito.mock(MucService.class).getServer()) .thenReturn(server).getMock(); KixmppJid roomJid = new KixmppJid("testnode", "testdomain"); MucRoom mucRoom = new MucRoom(mucService, roomJid, new MucRoomSettings(false, false, null)); Channel channel = Mockito.mock(Channel.class); Attribute<KixmppJid> jidAttribute = Mockito.mock(Attribute.class); Mockito.when(jidAttribute.get()).thenReturn(new KixmppJid("test.user", "testdomain", "testresource")); Mockito.when(channel.attr(BindKixmppServerModule.JID)).thenReturn(jidAttribute); Mockito.when(channel.closeFuture()).thenReturn(Mockito.mock(ChannelFuture.class)); Assert.assertEquals(0, mucRoom.getUsers().size()); mucRoom.addUser(new KixmppJid("test.user", "testdomain", "testresource"), "nickname", MucRole.Participant, MucAffiliation.Member); mucRoom.join(channel, "nickname"); Assert.assertEquals(1, mucRoom.getUsers().size()); }
@Override protected void initChannel(SocketChannel ch) throws Exception { final ChannelPipeline p = ch.pipeline(); final UUID uuid = UUID.randomUUID(); LOG.debug("KaaTcpServerInitializer Initializing Channel {} connection from {}:{}", uuid, ch.remoteAddress().getAddress().toString(), ch.remoteAddress().getPort()); Attribute<UUID> uuidAttr = ch.attr(AbstractNettyServer.UUID_KEY); uuidAttr.set(uuid); p.addLast("binaryDecoder", new ByteArrayDecoder()); p.addLast("kaaTcpDecoder", getDecoder()); p.addLast("binaryEncoder", new ByteArrayEncoder()); p.addLast("kaaTcpEncoder", new KaaTcpEncoder()); p.addLast("mainHandler", getMainHandler(uuid)); p.addLast("kaaTcpExceptionHandler", new KaaTcpExceptionHandler()); }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { Attribute<UUID> sessionUuidAttr = ctx.channel().attr(AbstractNettyServer.UUID_KEY); if (!(msg instanceof AbstractCommand)) { LOG.warn("Session [{}] got invalid HTTP response: {}", sessionUuidAttr, msg); super.write(ctx, msg, promise); return; } else { LOG.trace("Session [{}] got valid HTTP response: {}", sessionUuidAttr, msg); } AbstractCommand cp = (AbstractCommand) msg; HttpResponse httpResponse = cp.getResponse(); ChannelFuture future = ctx.writeAndFlush(httpResponse, promise); if (!HttpHeaders.isKeepAlive(httpResponse)) { future.addListener(ChannelFutureListener.CLOSE); } }
@Override protected void initChannel(SocketChannel ch) throws Exception { final ChannelPipeline p = ch.pipeline(); final UUID uuid = UUID.randomUUID(); LOG.info("DefaultServerInitializer Initializing Channel {} connection from {}:{}", uuid, ch.remoteAddress().getAddress().toString(), ch.remoteAddress().getPort()); Attribute<UUID> uuidAttr = ch.attr(AbstractNettyServer.UUID_KEY); uuidAttr.set(uuid); p.addLast("httpDecoder", new HttpRequestDecoder()); p.addLast("httpAggregator", new HttpObjectAggregator(getClientMaxBodySize())); p.addLast("httpDecoderAux", getRequestDecoder()); p.addLast("httpEncoder", new HttpResponseEncoder()); p.addLast("httpEncoderAux", new ResponseEncoder()); p.addLast("handler", getMainHandler(uuid)); p.addLast("httpExceptionHandler", new DefaultExceptionHandler()); }
@Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) { try { if (ConnectionResetByPeer.test(cause)) { log.trace("execution of: " + ctx.channel().attr(PATH).get() + " resulted in error", cause); } else { Attribute<NettyWebSocket> ws = ctx.channel().attr(NettyWebSocket.KEY); if (ws != null && ws.get() != null) { ws.get().handle(cause); } else { log.debug("execution of: " + ctx.channel().attr(PATH).get() + " resulted in error", cause); } } } finally { ctx.close(); } }
@Override public void end() { if (ctx != null) { Attribute<NettyWebSocket> ws = ctx.channel().attr(NettyWebSocket.KEY); if (ws != null && ws.get() != null) { status = HttpResponseStatus.SWITCHING_PROTOCOLS; ws.get().hankshake(); ctx = null; committed = true; return; } if (!committed) { DefaultHttpResponse rsp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status); headers.set(HttpHeaderNames.CONTENT_LENGTH, 0); // dump headers rsp.headers().set(headers); if (keepAlive) { ctx.write(rsp, ctx.voidPromise()); } else { ctx.write(rsp).addListener(CLOSE); } committed = true; } ctx = null; } }