@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 当拦截的方法返回false直接返回,否则进入下一个handler if(!afterHandle(ctx, msg)){ // 释放ThreadLocal对象 DataHolder.removeAll(); HttpResponse response = HttpRenderUtil.render(null,HttpRenderUtil.CONTENT_TYPE_TEXT); // 从该channel直接返回 ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); return; } /** * 提交给下一个ChannelHandler去处理 * 并且不需要调用ReferenceCountUtil.release(msg);来释放引用计数 */ ctx.fireChannelRead(msg); }
/** * Sets the Date and Cache headers for the HTTP Response * * @param response * HTTP response * @param fileToCache * file to extract content type */ public void setDateAndCacheHeaders(HttpResponse response, File fileToCache) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE)); // Date header Calendar time = new GregorianCalendar(); response.headers().set(HttpHeaders.Names.DATE, dateFormatter.format(time.getTime())); // Add cache headers time.add(Calendar.SECOND, HTTP_CACHE_SECONDS); response.headers().set(HttpHeaders.Names.EXPIRES, dateFormatter.format(time.getTime())); response.headers().set(HttpHeaders.Names.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS); response.headers().set( HttpHeaders.Names.LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified()))); }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { //客户端channel已关闭则不转发了 if (!clientChannel.isOpen()) { ReferenceCountUtil.release(msg); return; } HttpProxyInterceptPipeline interceptPipeline = ((HttpProxyServerHandle) clientChannel.pipeline() .get("serverHandle")).getInterceptPipeline(); if (msg instanceof HttpResponse) { interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpResponse) msg); } else if (msg instanceof HttpContent) { interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpContent) msg); } else { clientChannel.writeAndFlush(msg); } }
private static HttpResponse setDino(XrpcRequest request, List<Dino> dinos) { try { Optional<DinoSetRequest> setRequest = Optional.of( DinoSetRequest.parseFrom( CodedInputStream.newInstance(request.getData().nioBuffer()))); setRequest.ifPresent(req -> dinos.add(req.getDino())); return Recipes.newResponse( HttpResponseStatus.OK, request .getByteBuf() .writeBytes(DinoSetReply.newBuilder().setResponseCode("OK").build().toByteArray()), Recipes.ContentType.Application_Octet_Stream); } catch (IOException e) { return Recipes.newResponseBadRequest("Malformed SetDino Request: " + e.getMessage()); } }
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { LOGGER.info("[Client ({})] <= [Server ({})] : {}", connectionInfo.getClientAddr(), connectionInfo.getServerAddr(), msg); if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (!response.headers().contains(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text())) { if (streams.isEmpty()) { throw new IllegalStateException("No active streams"); } response.headers().add(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), streams.poll()); } } ctx.write(msg, promise); }
public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, Netty4CorsConfig config) { if (!config.isCorsSupportEnabled()) { return; } String originHeader = request.headers().get(HttpHeaderNames.ORIGIN); if (!Strings.isNullOrEmpty(originHeader)) { final String originHeaderVal; if (config.isAnyOriginSupported()) { originHeaderVal = ANY_ORIGIN; } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HttpHeaderNames.HOST))) { originHeaderVal = originHeader; } else { originHeaderVal = null; } if (originHeaderVal != null) { resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal); } } if (config.isCredentialsAllowed()) { resp.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } }
private boolean setOrigin(final HttpResponse response) { final String origin = request.headers().get(HttpHeaderNames.ORIGIN); if (!Strings.isNullOrEmpty(origin)) { if ("null".equals(origin) && config.isNullOriginAllowed()) { setAnyOrigin(response); return true; } if (config.isAnyOriginSupported()) { if (config.isCredentialsAllowed()) { echoRequestOrigin(response); setVaryHeader(response); } else { setAnyOrigin(response); } return true; } if (config.isOriginAllowed(origin)) { setOrigin(response, origin); setVaryHeader(response); return true; } } return false; }
/** * Sets the Date and Cache headers for the HTTP Response * * @param response HTTP response * @param fileToCache file to extract content type */ private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE)); // Date header Calendar time = new GregorianCalendar(); response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime())); // Add cache headers time.add(Calendar.SECOND, HTTP_CACHE_SECONDS); response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime())); response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS); response.headers().set( HttpHeaderNames.LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified()))); }
/** * Get a Netty {@link HttpResponse}, committing the {@link HttpServletResponse}. */ public HttpResponse getNettyResponse() { if (committed) { return response; } committed = true; HttpHeaders headers = response.headers(); if (null != contentType) { String value = null == characterEncoding ? contentType : contentType + "; charset=" + characterEncoding; headers.set(HttpHeaders.Names.CONTENT_TYPE, value); } CharSequence date = getFormattedDate(); headers.set(HttpHeaders.Names.DATE, date); headers.set(HttpHeaders.Names.SERVER, servletContext.getServerInfoAscii()); // TODO cookies return response; }
/** * Sets the Date and Cache headers for the HTTP Response * * @param response HTTP response * @param fileToCache file to extract content type */ private void setDateAndCacheHeaders(HttpResponse response, File fileToCache) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE)); // Date header Calendar time = new GregorianCalendar(); response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime())); // Add cache headers time.add(Calendar.SECOND, HTTP_CACHE_SECONDS); response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime())); response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS); response.headers().set( HttpHeaderNames.LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified()))); }
public static void startDownTask(TaskInfo taskInfo, HttpRequest httpRequest, HttpResponse httpResponse, Channel clientChannel) { HttpHeaders httpHeaders = httpResponse.headers(); HttpDownInfo httpDownInfo = new HttpDownInfo(taskInfo, httpRequest); HttpDownServer.DOWN_CONTENT.put(taskInfo.getId(), httpDownInfo); httpHeaders.clear(); httpResponse.setStatus(HttpResponseStatus.OK); httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/html"); String host = HttpDownServer.isDev() ? "localhost" : ((InetSocketAddress) clientChannel.localAddress()).getHostString(); String js = "<script>window.top.location.href='http://" + host + ":" + HttpDownServer.VIEW_SERVER_PORT + "/#/tasks/new/" + httpDownInfo .getTaskInfo().getId() + "';</script>"; HttpContent content = new DefaultLastHttpContent(); content.content().writeBytes(js.getBytes()); httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, js.getBytes().length); clientChannel.writeAndFlush(httpResponse); clientChannel.writeAndFlush(content); clientChannel.close(); }
/** * 同步请求 * @param host * @param port * @param request * @return 超时返回null */ public HttpResponse syncRequest(String host,int port,HttpRequest request) { HttpResponse response=null; synchronized (request) { if(response==null) { HttpListener listener=new HttpListener(request); NettyClient client=new NettyClient(config,new InetSocketAddress(host, port),new HttpClientInitHandler(listener)); client.start(); response=listener.waitResponse();//阻塞等待结果 client.stop(); } } return response; }
/** * 同步请求 * @param host * @param port * @param request * @param waiteTimeMills * @return 超时返回null */ public HttpResponse syncRequest(String host,int port,HttpRequest request,long waiteTimeMills) { HttpResponse response=null; synchronized (request) { if(response==null) { HttpListener listener=new HttpListener(request); NettyClient client=new NettyClient(config,new InetSocketAddress(host, port),new HttpClientInitHandler(listener)); client.start(); response=listener.waitResponse(waiteTimeMills);//阻塞等待结果 client.stop(); } } return response; }
@Override public HttpResponse filterRequest(HttpRequest httpRequest, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) { replayingState.addHttpRequestToQueue(httpMessageInfo.getOriginalRequest()); replayingState.setHttpLock(false); for (ConditionsUpdater conditionsUpdater: conditionsUpdaters) { if (conditionsUpdater.shouldUpdate().test(httpRequest)) { try { URL url = new URL(httpRequest.getUri()); String event = url.getQuery(); conditionsUpdater.updater().update(replayingState, event); } catch (MalformedURLException e) { logger.error(e.getMessage(), e); } } } return null; }
@Override public HttpResponse filterRequest(HttpRequest httpRequest, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) { for (EventDetector eventDetector: eventDetectors) { if (eventDetector.canDetectPredicate().test(httpRequest)) { try { Optional<Map<String, String>> optionalEvent = eventDetector.getConverter().convert(httpRequest); if (optionalEvent.isPresent()) { Map<String, String> event = optionalEvent.get(); recordingState.storeTestCaseStep(event); logger.info("Recorded event {}", event); } } catch (UnsupportedEncodingException | MalformedURLException e) { logger.error("Error while trying to convert test case step", e); } } } return null; }
@Override public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) throws Exception { if (HttpDownUtil.checkReferer(pipeline.getHttpRequest(), "^https?://pan.baidu.com/disk/home.*$") && HttpDownUtil.checkUrl(pipeline.getHttpRequest(), "^.*method=batchdownload.*$")) { HttpHeaders resHeaders = httpResponse.headers(); long fileSize = HttpDownUtil.getDownFileSize(resHeaders); //百度合并下载分段最多为16M int connections = (int) Math.ceil(fileSize / CHUNK_16M); TaskInfo taskInfo = new TaskInfo() .setId(UUID.randomUUID().toString()) .setFileName(HttpDownUtil.getDownFileName(pipeline.getHttpRequest(), resHeaders)) .setTotalSize(HttpDownUtil.getDownFileSize(resHeaders)) .setConnections(connections) .setSupportRange(true); HttpDownUtil.startDownTask(taskInfo, pipeline.getHttpRequest(), httpResponse, clientChannel); return; } pipeline.afterResponse(clientChannel, proxyChannel, httpResponse); }
@Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { if (httpObject instanceof HttpRequest) { System.err.println("--->" + ((HttpRequest) httpObject).getUri()); } return super.clientToProxyRequest(httpObject); }
@Override protected void channelRead0( ChannelHandlerContext context, HttpObject message) throws Exception { if (message instanceof HttpResponse) { receive((HttpResponse) message); } if (message instanceof HttpContent) { receive((HttpContent) message); if (message instanceof LastHttpContent) { release(this); } } }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 当拦截的方法返回false直接返回,否则进入下一个handler if(!preHandle(ctx, msg)){ HttpResponse response = HttpRenderUtil.render(null,HttpRenderUtil.CONTENT_TYPE_TEXT); // 从该channel直接返回 ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); return; } /** * 提交给下一个ChannelHandler去处理 * 并且不需要调用ReferenceCountUtil.release(msg);来释放引用计数 */ ctx.fireChannelRead(msg); }
/** * 设置所有的Cookie */ @Deprecated public static void setCookies(){ HttpRequest request = DataHolder.getHttpRequest(); HttpResponse response = DataHolder.getHttpResponse(); CookieHelper.setCookies(request,response); }
@Override public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse, HttpProxyInterceptPipeline pipeline) throws Exception { TaskInfo taskInfo = HttpDownUtil .getTaskInfo(pipeline.getHttpRequest(), httpResponse.headers(), HttpDownServer.CLIENT_SSL_CONTEXT, HttpDownServer.LOOP_GROUP); HttpDownUtil.startDownTask(taskInfo, pipeline.getHttpRequest(), httpResponse, clientChannel); }
/** * 删除一个Cookie * @param name * @return */ @Deprecated public static boolean deleteCookie(String name) { HttpRequest request = DataHolder.getHttpRequest(); HttpResponse response = DataHolder.getHttpResponse(); return CookieHelper.deleteCookie(request,response,name); }
/** * 设置所有的Cookie * @param request * @param response */ public static void setCookies(HttpRequest request,HttpResponse response){ Set<Cookie> cookies = getCookies(request); if (!cookies.isEmpty()) { for (Cookie cookie : cookies) { setCookie(response,cookie); } } }
/** * 添加一个Cookie * @param response response * @param name cookie名字 * @param value cookie值 * @param domain cookie所在域 * @param maxAge cookie生命周期 以秒为单位 */ public static void addCookie(HttpResponse response,String name,String value,String domain,long maxAge){ Cookie cookie = new DefaultCookie(name,value); cookie.setPath("/"); if(domain!=null && domain.trim().length()>0) { cookie.setDomain(domain); } if(maxAge>0){ cookie.setMaxAge(maxAge); } setCookie(response,cookie); }
/** * 删除一个Cookie * @param request * @param response * @param name * @return */ public static boolean deleteCookie(HttpRequest request,HttpResponse response,String name) { Cookie cookie = getCookie(request,name); if(cookie!=null){ cookie.setMaxAge(0); cookie.setPath("/"); setCookie(response,cookie); return true; } return false; }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if(msg instanceof HttpRequest){ HttpRequest request = (HttpRequest) msg; boolean forceClose = false; HttpResponse response; try{ // 获得路由结果 RouteResult<RenderType> routeResult = RouterContext.getRouteResult(request.method(),request.uri()); // 根据路由获得具体的ControllerProxy ControllerProxy controllerProxy = RouterContext.getControllerProxy(routeResult); if(controllerProxy == null){ forceClose = true; response = HttpRenderUtil.getNotFoundResponse(); }else { // 每一个Controller的方法返回类型约定为Render的实现类 Render render = ProxyInvocation.invoke(controllerProxy); response = render.response(); } }catch(Exception e){ routerLogger.error("Server Internal Error,cause:",e); forceClose = true; if(e instanceof IllegalArgumentException || e instanceof InvocationException){ response = HttpRenderUtil.getErrorResponse(e.getMessage()); }else{ response = HttpRenderUtil.getServerErrorResponse(); } } DataHolder.store(DataHolder.HolderType.FORCE_CLOSE,forceClose); DataHolder.store(DataHolder.HolderType.RESPONSE,response); } /** * 提交给下一个ChannelHandler去处理 * 并且不需要调用ReferenceCountUtil.release(msg);来释放引用计数 */ ctx.fireChannelRead(msg); }
public HttpProxyServer start() { return DefaultHttpProxyServer.bootstrap() .withAddress(new InetSocketAddress(host, port)) .withFiltersSource(new HttpFiltersSourceAdapter() { @Override public HttpFilters filterRequest(HttpRequest originalRequest) { return new HttpFiltersAdapter(originalRequest) { final String mockedAddress = mockServer + ":" + mockPort; @Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { final HttpRequest request = (HttpRequest) httpObject; if (request.getUri().contains("google")) { request.setUri(mockedAddress); } super.clientToProxyRequest(request); return null; } }; } }).start(); }
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse) throws Exception { if (this.pos3 == 0) { this.httpResponse = httpResponse; } if (this.pos3 < intercepts.size()) { HttpProxyIntercept intercept = intercepts.get(this.pos3++); intercept.afterResponse(clientChannel, proxyChannel, this.httpResponse, this); } this.pos3 = 0; }
@Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception { LOGGER.info("[Client ({})] <= [Server ({})] : {}", connectionInfo.getClientAddr(), connectionInfo.getServerAddr(), httpObject); outboundChannel.writeAndFlush(ReferenceCountUtil.retain(httpObject)); if (httpObject instanceof HttpResponse) { currentRequest = null; delayOutboundHandler.next(); } }
public static ByteBuf responseBytes(HttpResponse response) { String resp = String.format("%s %s %s\r\n%s\r\n", response.protocolVersion(), response.status().codeAsText(), response.status().reasonPhrase(), headersString(response.headers())); return Unpooled.buffer().writeBytes(resp.getBytes()); }
private void addCookies(HttpResponse resp) { if (transport.resetCookies) { String cookieString = nettyRequest.headers().get(HttpHeaders.Names.COOKIE); if (cookieString != null) { Set<io.netty.handler.codec.http.cookie.Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. resp.headers().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookies)); } } } }
private void addCustomHeaders(HttpResponse response, Map<String, List<String>> customHeaders) { if (customHeaders != null) { for (Map.Entry<String, List<String>> headerEntry : customHeaders.entrySet()) { for (String headerValue : headerEntry.getValue()) { setHeaderField(response, headerEntry.getKey(), headerValue); } } } }
private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) { final HttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, true, true); if (setOrigin(response)) { setAllowMethods(response); setAllowHeaders(response); setAllowCredentials(response); setMaxAge(response); setPreflightHeaders(response); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { forbidden(ctx, request); } }
public void testCorsEnabledWithoutAllowOrigins() { // Set up a HTTP transport with only the CORS enabled setting Settings settings = Settings.builder() .put(HttpTransportSettings.SETTING_CORS_ENABLED.getKey(), true) .build(); HttpResponse response = executeRequest(settings, "remote-host", "request-host"); // inspect response and validate assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN), nullValue()); }
public void testCorsEnabledWithAllowOrigins() { final String originValue = "remote-host"; // create a http transport with CORS enabled and allow origin configured Settings settings = Settings.builder() .put(SETTING_CORS_ENABLED.getKey(), true) .put(SETTING_CORS_ALLOW_ORIGIN.getKey(), originValue) .build(); HttpResponse response = executeRequest(settings, originValue, "request-host"); // inspect response and validate assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN), notNullValue()); String allowedOrigins = response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat(allowedOrigins, is(originValue)); }
public void testCorsAllowOriginWithSameHost() { String originValue = "remote-host"; String host = "remote-host"; // create a http transport with CORS enabled Settings settings = Settings.builder() .put(SETTING_CORS_ENABLED.getKey(), true) .build(); HttpResponse response = executeRequest(settings, originValue, host); // inspect response and validate assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN), notNullValue()); String allowedOrigins = response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat(allowedOrigins, is(originValue)); originValue = "http://" + originValue; response = executeRequest(settings, originValue, host); assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN), notNullValue()); allowedOrigins = response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat(allowedOrigins, is(originValue)); originValue = originValue + ":5555"; host = host + ":5555"; response = executeRequest(settings, originValue, host); assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN), notNullValue()); allowedOrigins = response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat(allowedOrigins, is(originValue)); originValue = originValue.replace("http", "https"); response = executeRequest(settings, originValue, host); assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN), notNullValue()); allowedOrigins = response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat(allowedOrigins, is(originValue)); }
public void testThatStringLiteralWorksOnMatch() { final String originValue = "remote-host"; Settings settings = Settings.builder() .put(SETTING_CORS_ENABLED.getKey(), true) .put(SETTING_CORS_ALLOW_ORIGIN.getKey(), originValue) .put(SETTING_CORS_ALLOW_METHODS.getKey(), "get, options, post") .put(SETTING_CORS_ALLOW_CREDENTIALS.getKey(), true) .build(); HttpResponse response = executeRequest(settings, originValue, "request-host"); // inspect response and validate assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN), notNullValue()); String allowedOrigins = response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat(allowedOrigins, is(originValue)); assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS), equalTo("true")); }
public void testThatAnyOriginWorks() { final String originValue = Netty4CorsHandler.ANY_ORIGIN; Settings settings = Settings.builder() .put(SETTING_CORS_ENABLED.getKey(), true) .put(SETTING_CORS_ALLOW_ORIGIN.getKey(), originValue) .build(); HttpResponse response = executeRequest(settings, originValue, "request-host"); // inspect response and validate assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN), notNullValue()); String allowedOrigins = response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat(allowedOrigins, is(originValue)); assertThat(response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS), nullValue()); }
public void testHeadersSet() { Settings settings = Settings.builder().build(); try (Netty4HttpServerTransport httpServerTransport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(), new NullDispatcher())) { httpServerTransport.start(); final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); httpRequest.headers().add(HttpHeaderNames.ORIGIN, "remote"); final WriteCapturingChannel writeCapturingChannel = new WriteCapturingChannel(); Netty4HttpRequest request = new Netty4HttpRequest(xContentRegistry(), httpRequest, writeCapturingChannel); // send a response Netty4HttpChannel channel = new Netty4HttpChannel(httpServerTransport, request, null, randomBoolean(), threadPool.getThreadContext()); TestResponse resp = new TestResponse(); final String customHeader = "custom-header"; final String customHeaderValue = "xyz"; resp.addHeader(customHeader, customHeaderValue); channel.sendResponse(resp); // inspect what was written List<Object> writtenObjects = writeCapturingChannel.getWrittenObjects(); assertThat(writtenObjects.size(), is(1)); HttpResponse response = (HttpResponse) writtenObjects.get(0); assertThat(response.headers().get("non-existent-header"), nullValue()); assertThat(response.headers().get(customHeader), equalTo(customHeaderValue)); assertThat(response.headers().get(HttpHeaderNames.CONTENT_LENGTH), equalTo(Integer.toString(resp.content().length()))); assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE), equalTo(resp.contentType())); } }