public static HttpRequest adapter(HttpRequest httpRequest) { if (httpRequest instanceof DefaultHttpRequest) { HttpVer version; if (httpRequest.protocolVersion().minorVersion() == 0) { version = HttpVer.HTTP_1_0; } else { version = HttpVer.HTTP_1_1; } HttpHeadsInfo httpHeadsInfo = new HttpHeadsInfo(); for (Entry<String, String> entry : httpRequest.headers()) { httpHeadsInfo.set(entry.getKey(), entry.getValue()); } return new HttpRequestInfo(version, httpRequest.method().toString(), httpRequest.uri(), httpHeadsInfo, null); } return httpRequest; }
@DataProvider(value = { "80 | false | localhost | localhost", "80 | true | localhost | localhost:80", "8080 | false | localhost | localhost:8080", "443 | true | localhost | localhost", "443 | false | localhost | localhost:443", "8080 | true | localhost | localhost:8080", }, splitBy = "\\|") @Test public void streamDownstreamCall_setsHostHeaderCorrectly(int downstreamPort, boolean isSecure, String downstreamHost, String expectedHostHeader) { // given DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); ChannelHandlerContext ctx = mockChannelHandlerContext(); StreamingCallback streamingCallback = mock(StreamingCallback.class); // when new StreamingAsyncHttpClient(200, 200, true) .streamDownstreamCall(downstreamHost, downstreamPort, request, isSecure, false, streamingCallback, 200, ctx); // then assertThat(request.headers().get(HOST)).isEqualTo(expectedHostHeader); }
HttpClientOperations(Channel channel, BiFunction<? super HttpClientResponse, ? super HttpClientRequest, ? extends Publisher<Void>> handler, ContextHandler<?> context) { super(channel, handler, context); this.isSecure = channel.pipeline() .get(NettyPipeline.SslHandler) != null; String[] redirects = channel.attr(REDIRECT_ATTR_KEY) .get(); this.redirectedFrom = redirects == null ? EMPTY_REDIRECTIONS : redirects; this.nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); this.requestHeaders = nettyRequest.headers(); this.requestHeaders.set(HttpHeaderNames.USER_AGENT, HttpClient.USER_AGENT); this.inboundPrefetch = 16; chunkedTransfer(true); }
@Override public void channelRead0(ChannelHandlerContext ctx, DefaultHttpRequest request) throws Exception { // TODO Auto-generated method stub if(request.getMethod().equals(RtspMethods.TEARDOWN)) handleRtspTEARDOWNMethod(ctx,request); else if(request.getMethod().equals(RtspMethods.OPTIONS)) handleRtspOPTIONSMethod(ctx,request); else if(request.getMethod().equals(RtspMethods.DESCRIBE)) handleRtspDESCRIBEMethod(ctx,request); else if(request.getMethod().equals(RtspMethods.SETUP)) handleRtspSETUPMethod(ctx,request); else if(request.getMethod().equals(RtspMethods.PLAY)) handleRtspPLAYMethod(ctx,request); else if(request.getMethod().equals(RtspMethods.PAUSE)) handleRtspPAUSEMethod(ctx,request); else System.err.println("Exception in ServerHandler"); }
@BeforeMethod public void setUp() throws Exception { HTTPCarbonMessage httpCarbonMessage = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "msf4j")); httpCarbonMessage.getHeaders().add("testA", "test1"); httpCarbonMessage.getHeaders().add("testA", "test2"); httpCarbonMessage.setHeader("Accept", "application/json"); httpCarbonMessage.setHeader("Content-Type", "text/html"); httpCarbonMessage.setHeader("Content-Language", "en"); httpCarbonMessage.setHeader("Content-Length", "1024"); httpCarbonMessage.setHeader("Date", "Sun, 06 Nov 1994 08:49:37 GMT"); httpCarbonMessage.getHeaders().add("Accept-Language", "da"); httpCarbonMessage.getHeaders().add("Accept-Language", "en-gb;q=0.8"); httpCarbonMessage.getHeaders().add("Accept-Language", "en;q=0.7"); httpCarbonMessage.getHeaders().add("Cookie", "JSESSIONID=3508015E4EF0ECA8C4B761FCC4BC1718"); httpHeaders1 = new HttpHeadersImpl(httpCarbonMessage.getHeaders()); HTTPCarbonMessage httpCarbonMessage2 = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "msf4j")); httpHeaders2 = new HttpHeadersImpl(httpCarbonMessage2.getHeaders()); }
@SuppressWarnings("unchecked") public static HttpRequest createHttpRequest(HTTPCarbonMessage msg) { HttpMethod httpMethod; if (null != msg.getProperty(Constants.HTTP_METHOD)) { httpMethod = new HttpMethod((String) msg.getProperty(Constants.HTTP_METHOD)); } else { httpMethod = new HttpMethod(DEFAULT_HTTP_METHOD_POST); } HttpVersion httpVersion; if (null != msg.getProperty(Constants.HTTP_VERSION)) { httpVersion = new HttpVersion((String) msg.getProperty(Constants.HTTP_VERSION), true); } else { httpVersion = new HttpVersion(DEFAULT_VERSION_HTTP_1_1, true); } if ((String) msg.getProperty(Constants.TO) == null) { msg.setProperty(Constants.TO, "/"); } HttpRequest outgoingRequest = new DefaultHttpRequest(httpVersion, httpMethod, (String) msg.getProperty(Constants.TO), false); HttpHeaders headers = msg.getHeaders(); outgoingRequest.headers().setAll(headers); return outgoingRequest; }
private HTTPCarbonMessage createHttpRequest(String method, String location) { URL locationUrl = null; try { locationUrl = new URL(location); } catch (MalformedURLException e) { TestUtil.handleException("MalformedURLException occurred while running unitTestForRedirectHandler ", e); } HttpMethod httpMethod = new HttpMethod(method); HTTPCarbonMessage httpCarbonRequest = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, httpMethod, "")); httpCarbonRequest.setProperty(Constants.PORT, locationUrl.getPort()); httpCarbonRequest.setProperty(Constants.PROTOCOL, locationUrl.getProtocol()); httpCarbonRequest.setProperty(Constants.HOST, locationUrl.getHost()); httpCarbonRequest.setProperty(Constants.HTTP_METHOD, method); httpCarbonRequest.setProperty(Constants.REQUEST_URL, locationUrl.getPath()); httpCarbonRequest.setProperty(Constants.TO, locationUrl.getPath()); httpCarbonRequest.setHeader(Constants.HOST, locationUrl.getHost()); httpCarbonRequest.setHeader(Constants.PORT, Integer.toString(locationUrl.getPort())); httpCarbonRequest.setEndOfMsgAdded(true); return httpCarbonRequest; }
@Test(expected = AuthenticationHeaderMissingException.class) public void testAuthenticationHeaderMissing() throws Exception { AuthenticationProvider authenticationProvider = EasyMock .createMock(AuthenticationProvider.class); HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "testUri"); Module module = new DiscardingModule(); Session session = module.startSession(null); session.setCustomer(new Customer("testUserName", "testPassword")); session.setServiceName("testServiceName"); module.close(); EasyMock.replay(authenticationProvider); @SuppressWarnings("resource") // close() method invokes only authenticationProvider.close(), which has been invoked explicitly above. AuthenticationPreProcessor authenticationPreProcessor = new AuthenticationPreProcessor( authenticationProvider); authenticationPreProcessor.process(httpRequest, session); EasyMock.verify(authenticationProvider); }
@Test public void testSuccessfulAdding() { Accountancy accountancy = EasyMock.createMock(Accountancy.class); Module module = new DiscardingModule(); Session session = module.startSession(null); session.setCustomer(new Customer("testUserName", "testPassword")); session.setServiceName("testServiceName"); module.close(); Capture<AccountancyItem> capture = new Capture<AccountancyItem>(); accountancy.addItem(EasyMock.capture(capture)); EasyMock.replay(accountancy); accountancyPostProcessor = new AccountancyPostProcessor(accountancy); accountancyPostProcessor.process(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/testRequestPath"), session); EasyMock.verify(accountancy); }
@Test(expected = IllegalStateException.class) public void testCustomerIsNull() { Accountancy accountancy = EasyMock.createMock(Accountancy.class); Module module = new DiscardingModule(); Session session = module.startSession(null); // The lack of setter invocation for customer session.setServiceName("testServiceName"); module.close(); EasyMock.replay(accountancy); accountancyPostProcessor = new AccountancyPostProcessor(accountancy); accountancyPostProcessor.process(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/testRequestPath"), session); EasyMock.verify(accountancy); }
@Test(expected = IllegalStateException.class) public void testServiceNameIsNull() { Accountancy accountancy = EasyMock.createMock(Accountancy.class); Module module = new DiscardingModule(); Session session = module.startSession(null); session.setCustomer(new Customer("testUserName", "testPassword")); // The lack of setter invocation for service name module.close(); EasyMock.replay(accountancy); accountancyPostProcessor = new AccountancyPostProcessor(accountancy); accountancyPostProcessor.process(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/testRequestPath"), session); EasyMock.verify(accountancy); }
@Test(expected = IllegalStateException.class) public void testCustomerAndServiceNameAreNull() { Accountancy accountancy = EasyMock.createMock(Accountancy.class); Module module = new DiscardingModule(); Session session = module.startSession(null); // The lack of setter invocation for customer // The lack of setter invocation for service name module.close(); EasyMock.replay(accountancy); accountancyPostProcessor = new AccountancyPostProcessor(accountancy); accountancyPostProcessor.process(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/testRequestPath"), session); EasyMock.verify(accountancy); }
@Test public void testThreadBoundaries() throws Exception { Thread thread = new Thread( new Runnable() { public void run() { EmbeddedChannel channel = new EmbeddedChannel( new HttpServerTracingHandler(httpTracingState), new ApplicationHandler()); DefaultHttpRequest request = new DefaultHttpRequest(HTTP_1_1, GET, "/foo"); channel.writeInbound(request); channel.runPendingTasks(); synchronized (httpTracing) { httpTracing.notify(); } } }); thread.start(); synchronized (httpTracing) { httpTracing.wait(); } Assert.assertEquals(2, spans.size()); }
@Test public void testDeniedRule() throws UnknownHostException { List<Http1DeterministicRuleEngineConfig.Rule> blacklist = new ArrayList<>(); HashMultimap<String, String> headers = HashMultimap.create(); headers.put("User-Agent", "Bad-actor: 1.0"); Http1DeterministicRuleEngineConfig.Rule bad = new Http1DeterministicRuleEngineConfig.Rule( HttpMethod.GET, "/path/to/failure", HttpVersion.HTTP_1_0, headers); blacklist.add(bad); Http1Filter http1Filter = new Http1Filter(new Http1FilterConfig(ImmutableList.copyOf(blacklist))); EmbeddedChannel chDeny = new EmbeddedChannel(http1Filter); DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/path/to/failure"); request.headers().set("User-Agent", "Bad-actor: 1.0"); chDeny.writeInbound(request); chDeny.runPendingTasks(); assertFalse(chDeny.isActive()); assertFalse(chDeny.isOpen()); }
@Test public void testAllowedRule() throws UnknownHostException { List<Http1DeterministicRuleEngineConfig.Rule> blacklist = new ArrayList<>(); HashMultimap<String, String> headers = HashMultimap.create(); headers.put("User-Agent", "Bad-actor: 1.0"); Http1DeterministicRuleEngineConfig.Rule bad = new Http1DeterministicRuleEngineConfig.Rule( HttpMethod.POST, "/path/to/failure", HttpVersion.HTTP_1_1, headers); blacklist.add(bad); Http1Filter http1Filter = new Http1Filter(new Http1FilterConfig(ImmutableList.copyOf(blacklist))); EmbeddedChannel chAllow = new EmbeddedChannel(http1Filter); DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_0, HttpMethod.GET, "/path/to/failure"); request.headers().set("User-Agent", "Bad-actor: 1.0"); chAllow.writeInbound(request); assertTrue(chAllow.isActive()); assertTrue(chAllow.isOpen()); }
public void start(final HyperSession parent, WritableByteChannel dest, String chanid, Map<String, Cookie> cookies, long size, long offset, final OperationCallback callback) { this.dest = dest; this.cookies = cookies; this.callback = callback; this.size = size; this.sent = offset; this.src = this.allocateChannel(parent, callback); if (this.callback.hasErrors()) { callback.complete(); return; } // send a request to get things going HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/download/" + chanid); req.headers().set(Names.HOST, parent.getInfo().getHost()); req.headers().set(Names.USER_AGENT, "DivConq HyperAPI Client 1.0"); req.headers().set(Names.CONNECTION, HttpHeaders.Values.CLOSE); req.headers().set(Names.COOKIE, ClientCookieEncoder.STRICT.encode(this.cookies.values())); // send request this.src.writeAndFlush(req); }
@Test public void testSetCookie() throws Exception { DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); String cookie1Name = "PREF"; String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi"; String cookie1Domain = ".google.com"; String cookie1Path = "/"; Cookie cookie = new DefaultCookie(cookie1Name, cookie1Value); cookie.setPath(cookie1Path); cookie.setDomain(cookie1Domain); new HttpClientRequest<ByteBuf>(nettyRequest).withCookie(cookie); String cookieHeader = nettyRequest.headers().get(HttpHeaders.Names.COOKIE); Assert.assertNotNull("No cookie header found.", cookieHeader); Set<Cookie> decodeCookies = CookieDecoder.decode(cookieHeader); Assert.assertNotNull("No cookie found with name.", decodeCookies); Assert.assertEquals("Unexpected number of cookies.", 1, decodeCookies.size()); Cookie decodedCookie = decodeCookies.iterator().next(); Assert.assertEquals("Unexpected cookie name.", cookie1Name, decodedCookie.getName()); Assert.assertEquals("Unexpected cookie path.", cookie1Path, decodedCookie.getPath()); Assert.assertEquals("Unexpected cookie domain.", cookie1Domain, decodedCookie.getDomain()); }
@Test public void testGetCookie() throws Exception { DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); String cookie1Name = "PREF"; String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi"; String cookie1Domain = ".google.com"; String cookie1Path = "/"; String cookie1Header = cookie1Name + '=' + cookie1Value + "; expires=Thu, 18-Feb-2016 07:47:08 GMT; path=" + cookie1Path + "; domain=" + cookie1Domain; nettyRequest.headers().add(HttpHeaders.Names.COOKIE, cookie1Header); HttpServerRequest<ByteBuf> request = new HttpServerRequest<ByteBuf>(nettyRequest, PublishSubject.<ByteBuf>create()); Map<String,Set<Cookie>> cookies = request.getCookies(); Assert.assertEquals("Unexpected number of cookies.", 1, cookies.size()); Set<Cookie> cookies1 = cookies.get(cookie1Name); Assert.assertNotNull("No cookie found with name: " + cookie1Name, cookies1); Assert.assertEquals("Unexpected number of cookies with name: " + cookie1Name, 1, cookies1.size() ); Cookie cookie = cookies1.iterator().next(); Assert.assertEquals("Unexpected cookie name.", cookie1Name, cookie.getName()); Assert.assertEquals("Unexpected cookie path.", cookie1Path, cookie.getPath()); }
protected boolean checkSecured(String applicationId, ApplicationRedirectConfig config, ResourceRequest request) throws Exception { if (request.requestContext().securityContext() != null && request.requestContext().securityContext().isAuthenticated()) { return true; } String authorization = ((DefaultHttpRequest)request.requestContext().requestAttributes().getAttribute(HttpResourceRequestDecoder.HTTP_REQUEST)).headers().get("Authorization"); if (authorization != null) { return true; } RequestAttributes attribs = new DefaultRequestAttributes(); attribs.setAttribute(AuthzConstants.ATTR_REQUEST_CONTEXT, new UnAuthorizedRequestContext(request.requestContext())); attribs.setAttribute(AuthzConstants.ATTR_REQUEST_RESOURCE_STATE, request.state()); RequestContext authzRequest = new RequestContext.Builder().requestAttributes(attribs).build(); ResourceState resourceState = client.read(authzRequest, "/" + applicationId + "/authz/authzCheck"); boolean authorized = (Boolean) resourceState.getProperty(AuthzConstants.ATTR_AUTHZ_RESULT); if (authorized) { return false; } else { return true; } }
/** * Creates a {@link NettyRequest} with the given parameters. * @param httpMethod the {@link HttpMethod} desired. * @param uri the URI desired. * @param headers {@link HttpHeaders} that need to be a part of the request. * @param channel the {@link Channel} that the request arrived over. * @return {@link NettyRequest} encapsulating a {@link HttpRequest} with the given parameters. * @throws RestServiceException if the {@code httpMethod} is not recognized by {@link NettyRequest}. */ private NettyRequest createNettyRequest(HttpMethod httpMethod, String uri, HttpHeaders headers, Channel channel) throws RestServiceException { MetricRegistry metricRegistry = new MetricRegistry(); RestRequestMetricsTracker.setDefaults(metricRegistry); HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, httpMethod, uri, false); if (headers != null) { httpRequest.headers().set(headers); } NettyRequest nettyRequest = new NettyRequest(httpRequest, channel, new NettyMetrics(metricRegistry), BLACKLISTED_QUERY_PARAM_SET); assertEquals("Auto-read is in an invalid state", (!httpMethod.equals(HttpMethod.POST) && !httpMethod.equals(HttpMethod.PUT)) || NettyRequest.bufferWatermark <= 0, channel.config().isAutoRead()); return nettyRequest; }
public void testThatPipeliningWorksWithChunkedRequests() throws InterruptedException { final int numberOfRequests = randomIntBetween(2, 128); final EmbeddedChannel embeddedChannel = new EmbeddedChannel( new AggregateUrisAndHeadersHandler(), new HttpPipeliningHandler(numberOfRequests), new WorkEmulatorHandler()); for (int i = 0; i < numberOfRequests; i++) { final DefaultHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/" + i); embeddedChannel.writeInbound(request); embeddedChannel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT); } final List<CountDownLatch> latches = new ArrayList<>(); for (int i = numberOfRequests - 1; i >= 0; i--) { latches.add(finishRequest(Integer.toString(i))); } for (final CountDownLatch latch : latches) { latch.await(); } embeddedChannel.flush(); for (int i = 0; i < numberOfRequests; i++) { assertReadHttpMessageHasContent(embeddedChannel, Integer.toString(i)); } assertTrue(embeddedChannel.isOpen()); }
public static void main(String[] args) { NettyHttpClient client=new NettyHttpClient(); long time=System.currentTimeMillis(); HttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/baidu?tn=monline_6_dg&ie=utf-8&wd=netty+http客户端"); HttpResponse response=client.syncRequest("www.baidu.com", 80, request); System.out.println(System.currentTimeMillis()-time); System.out.println(response); FullHttpResponse rsp=(FullHttpResponse) response; System.out.println("content:"+rsp.content().toString(CharsetUtil.UTF_8)); // new Scanner(System.in).nextLine(); }
public HTTPCarbonMessage createHttpCarbonMessage(String method) { HTTPCarbonMessage httpCarbonMessage = null; switch (method) { case "GET": { httpCarbonMessage = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "")); break; } case "PUT": { httpCarbonMessage = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "")); break; } case "PATCH": { httpCarbonMessage = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PATCH, "")); break; } case "DELETE": { httpCarbonMessage = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, "")); break; } case "POST": { httpCarbonMessage = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "")); break; } default: { log.error("Invalid request type."); break; } } return httpCarbonMessage; }
/** * Create new HTTP carbon messge. * * @param isRequest * @return */ private static HTTPCarbonMessage createHttpCarbonMessage(boolean isRequest) { HTTPCarbonMessage httpCarbonMessage; if (isRequest) { httpCarbonMessage = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "")); httpCarbonMessage.setEndOfMsgAdded(true); } else { httpCarbonMessage = new HTTPCarbonMessage( new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK)); httpCarbonMessage.setEndOfMsgAdded(true); } return httpCarbonMessage; }
public HttpRequest adapt(SdkHttpRequest sdkRequest) { String uri = sdkRequest.getUri().toString(); HttpMethod method = toNettyHttpMethod(sdkRequest.method()); HttpHeaders headers = new DefaultHttpHeaders(); DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri, headers); sdkRequest.headers().forEach(request.headers()::add); return request; }
@Test public void testGetUri() { String url = "http://does.not.exist/file"; DefaultHttpRequest request = mock(DefaultHttpRequest.class); when(request.getUri()).thenReturn(url); LittleProxyRequest lpr = new LittleProxyRequest(request); assertEquals(url, lpr.getUri()); }
/** * Helper method that generates a {@link HttpRequest} for the downstream call's first chunk that uses the given * downstreamPath and downstreamMethod, and the query string and headers from the incomingRequest will be added and * passed through without modification. */ @SuppressWarnings("UnusedParameters") protected HttpRequest generateSimplePassthroughRequest(RequestInfo<?> incomingRequest, String downstreamPath, HttpMethod downstreamMethod, ChannelHandlerContext ctx) { String queryString = extractQueryString(incomingRequest.getUri()); String downstreamUri = downstreamPath; // TODO: Add logic to support when downstreamPath already has a query string on it. The two query strings should be combined if (queryString != null) downstreamUri += queryString; HttpRequest downstreamRequestInfo = new DefaultHttpRequest(HttpVersion.HTTP_1_1, downstreamMethod, downstreamUri); downstreamRequestInfo.headers().set(incomingRequest.getHeaders()); return downstreamRequestInfo; }
@Test public void getRequestInfo_creates_new_RequestInfo_based_on_msg_if_state_requestInfo_is_null_and_msg_is_a_HttpRequest() { // given assertThat(state.getRequestInfo(), nullValue()); String expectedUri = "/some/uri/" + UUID.randomUUID().toString(); HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, expectedUri); // when RequestInfo<?> result = handler.getRequestInfo(state, httpRequest); // then assertThat(result.getUri(), is(expectedUri)); }
@Before public void beforeMethod() { handler = new DTraceStartHandler(userIdHeaderKeys); channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); stateAttributeMock = mock(Attribute.class); state = new HttpProcessingState(); httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/uri"); doReturn(channelMock).when(ctxMock).channel(); doReturn(stateAttributeMock).when(channelMock).attr(ChannelAttributes.HTTP_PROCESSING_STATE_ATTRIBUTE_KEY); doReturn(state).when(stateAttributeMock).get(); resetTracingAndMdc(); }
@Override public HttpRequest buildStartMessage(TransportRequest request, AttributeMap channelAttrs) { DefaultHttpRequest httpRequest = new DefaultHttpRequest(HttpTransport.HTTP_VERSION, HttpMethod.POST, url.getPath()); HttpHeaders httpHeaders = httpRequest.headers(); setCommonHeaders(httpHeaders, request, channelAttrs); httpHeaders.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); return httpRequest; }
@Override public HttpRequest buildFullMessage( TransportRequest request, byte[] body, AttributeMap channelAttrs) { DefaultHttpRequest httpRequest = new DefaultFullHttpRequest( HttpTransport.HTTP_VERSION, HttpMethod.POST, url.getPath(), Unpooled.wrappedBuffer(body)); setCommonHeaders(httpRequest.headers(), request, channelAttrs); HttpUtil.setContentLength(httpRequest, body.length); return httpRequest; }
private HttpRequest newChunkedHttpRequest() { DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/foo"); req.headers() .add(HeaderMapper.SERVICE, "service") .add(HeaderMapper.PROCEDURE, "procedure") .add(HeaderMapper.CALLER, "caller") .add(HeaderMapper.ENCODING, "http"); return req; }
/** * Copy the given {@link HttpRequest} verbatim. * * @param original * @return */ private HttpRequest copy(HttpRequest original) { if (original instanceof FullHttpRequest) { return ((FullHttpRequest) original).copy(); } else { HttpRequest request = new DefaultHttpRequest(original.getProtocolVersion(), original.getMethod(), original.getUri()); request.headers().set(original.headers()); return request; } }
/** * Copy the given {@link HttpRequest} verbatim. * * @param original * @return */ private HttpRequest copy(HttpRequest original) { if (original instanceof DefaultFullHttpRequest) { ByteBuf content = ((DefaultFullHttpRequest) original).content(); return new DefaultFullHttpRequest(original.getProtocolVersion(), original.getMethod(), original.getUri(), content); } else { return new DefaultHttpRequest(original.getProtocolVersion(), original.getMethod(), original.getUri()); } }
private void handleRtspPLAYMethod(ChannelHandlerContext ctx, DefaultHttpRequest request) { // TODO Auto-generated method stub System.out.println("PLAY"); FullHttpResponse response = null; String sessionID = request.headers().get(RtspHeaders.Names.SESSION); String uri = request.getUri(); String path = uri.substring(uri.indexOf("8554")+4); String filePath = changeUriToAbsolutePath(path); if (filePath.endsWith("/")) filePath = filePath.substring(0, filePath.length() - 1); File file = new File(filePath); if (file.isDirectory() || !file.exists()) { return; } long rtpTime = System.currentTimeMillis(); int trackID = 1; String rtpInfo = "url="+uri+"/trackID="+trackID+";seq=10000;rtptime="+rtpTime; response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); response.headers().set(RtspHeaders.Names.CSEQ,request.headers().get(RtspHeaders.Names.CSEQ)); response.headers().set(RtspHeaders.Names.SESSION,sessionID); response.headers().set(RtspHeaders.Names.RTP_INFO,rtpInfo); response.headers().set(RtspHeaders.Names.RANGE,"npt=0.000-"); writeResponseWithFuture(ctx, request, response); RtpPacketization rtpPacket = new RtpPacketization(ctx, filePath); rtpThread = new Thread(rtpPacket); rtpThread.start(); }
private void handleRtspSETUPMethod(ChannelHandlerContext ctx, DefaultHttpRequest request) { // TODO Auto-generated method stub System.out.println("SETUP"); FullHttpResponse response = null; URI uri = null; try { uri = new URI(request.getUri()); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } String path = uri.getPath(); String filePath = changeUriToAbsolutePath(path).substring(0,changeUriToAbsolutePath(path).lastIndexOf("/")); if(filePath.endsWith("/")) filePath = filePath.substring(0,filePath.length()-1); File file = new File(filePath); if (file.isDirectory() || !file.exists()) { return; } String localAddress = ctx.channel().localAddress().toString(); String remoteAddress = ctx.channel().remoteAddress().toString(); String remotePort = remoteAddress.substring(remoteAddress.indexOf(":")+1); String interleaved = request.headers().get(RtspHeaders.Names.TRANSPORT).substring(request.headers().get(RtspHeaders.Names.TRANSPORT).indexOf("interleaved")); String serverTransport = "RTP/AVP/TCP;unicast;destination="+localAddress.substring(1,localAddress.indexOf(String.valueOf(ServerMain.PORT))-1) + ";source="+remoteAddress.substring(1,remoteAddress.indexOf(remotePort)-1) + ";interleaved="+interleaved.substring(interleaved.indexOf("=")+1); response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); response.headers().set(RtspHeaders.Names.CSEQ, request.headers().get(RtspHeaders.Names.CSEQ)); response.headers().set(RtspHeaders.Names.TRANSPORT, serverTransport); response.headers().set(RtspHeaders.Names.SESSION,"1"); writeResponseWithFuture(ctx,request,response); }
private void handleRtspOPTIONSMethod(ChannelHandlerContext ctx, DefaultHttpRequest request) { // TODO Auto-generated method stub System.out.println("OPTIONS"); String options = RtspMethods.OPTIONS.name()+", "+RtspMethods.DESCRIBE.name()+", "+RtspMethods.SETUP.name() +", "+RtspMethods.TEARDOWN.name()+", "+RtspMethods.PLAY.name()+", "+RtspMethods.PAUSE.name(); FullHttpResponse response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, RtspResponseStatuses.OK); response.headers().set(RtspHeaders.Names.CSEQ,request.headers().get(RtspHeaders.Names.CSEQ)); response.headers().set(RtspHeaders.Names.PUBLIC,options); writeResponseWithFuture(ctx,request,response); }
private void writeResponseWithFuture(ChannelHandlerContext ctx, DefaultHttpRequest request, HttpResponse response) { // TODO Auto-generated method stub ChannelFuture responseFuture; ChannelFuture lastresponseFuture; responseFuture = ctx.write(response,ctx.newProgressivePromise()); lastresponseFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); responseFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " "+future.cause()+" "+future.isCancelled()+" "+future.isDone()+" "+future.isSuccess()+" "/*+future.sync()*/); } @Override public void operationProgressed(ChannelProgressiveFuture paramF, long paramLong1, long paramLong2) throws Exception { // TODO Auto-generated method stub } }); if (!HttpHeaders.isKeepAlive(request)) { lastresponseFuture.addListener(ChannelFutureListener.CLOSE); } }
@BeforeClass public void setUp() throws IOException { HTTPCarbonMessage httpCarbonMessage = new HTTPCarbonMessage( new DefaultHttpRequest(HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.GET, "msf4j")); httpCarbonMessage.setHeader("testK", "testV"); request = new Request(httpCarbonMessage); request.setProperty("TO", "msf4j"); request.setProperty("HTTP_METHOD", HttpMethod.GET); httpServerRequest = new TraceableHttpServerRequest(request); }
private HttpObject convertClientHeaders(int streamId, HttpHeaders headers, boolean endStream) throws Http2Exception { // Leading headers will always have :method, trailers will never have it. final HttpMethod method = headers.method(); if (method == null) { return convertTrailingHeaders(streamId, headers); } // Convert leading headers. final HttpRequest req = new DefaultHttpRequest( HttpVersion.HTTP_1_1, io.netty.handler.codec.http.HttpMethod.valueOf(method.name()), headers.path(), false); convert(streamId, headers, req.headers(), false); if (endStream) { req.headers().remove(HttpHeaderNames.TRANSFER_ENCODING); req.headers().remove(HttpHeaderNames.CONTENT_LENGTH); } else if (HttpUtil.getContentLength(req, -1L) >= 0) { // Avoid the case where both 'content-length' and 'transfer-encoding' are set. req.headers().remove(HttpHeaderNames.TRANSFER_ENCODING); } else { req.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); } return req; }