Java 类io.netty.handler.codec.http.HttpHeaders 实例源码

项目:wecard-server    文件:NettyServerHandler.java   
/**
 * 返回http信息
 * @param ctx
 * @param req
 * @param res
 */
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);
    }
}
项目:push-network-proxies    文件:MockingFCMServerHandler.java   
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = HttpHeaders.isKeepAlive(request);

    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(
        HTTP_1_1, currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST,
        Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/json");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}
项目:TFWebSock    文件:NettyHttpFileHandler.java   
/**
 * 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())));
}
项目:TFWebSock    文件:NettyHttpFileHandler.java   
public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
   if (res.getStatus().code() != 200) {
      ByteBuf f = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
      res.content().clear();
      res.content().writeBytes(f);
      f.release();
   }

   HttpHeaders.setContentLength(res, res.content().readableBytes());
   ChannelFuture f1;
   f1 = ctx.channel().writeAndFlush(res);

   if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
      f1.addListener(ChannelFutureListener.CLOSE);
   }
}
项目:mqttserver    文件:HttpSessionStore.java   
public static String getClientSessionId(HttpRequest req) {
    Set<Cookie> cookies;
    String value = req.headers().get(HttpHeaders.Names.COOKIE);
    if (value == null) {
        return null;
    } else {
        cookies = CookieDecoder.decode(value);
    }

    for (Cookie cookie : cookies) {
        if (cookie.getName().contains("JSESSIONID")) {
            return cookie.getValue();
        }
    }

    return null;
}
项目:netty-socketio-demo    文件:CookieUserAuthorizationListener.java   
/**
 * 从Http Cookie中获取用户Id
 * 
 * @param data
 * @return
 */
public static final PushUser getUser(HandshakeData data) {
    String _cookie = data.getSingleHeader(HttpHeaders.Names.COOKIE);
    if (_cookie != null) {
        Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(_cookie);
        for (Cookie cookie : cookies) {
            if (TokenManager.LOGIN_COOKIE_NAME.equals(cookie.name())) {
                String value = cookie.value();
                if (value != null) {
                    return getUserIdFromCookie(value);
                }
            }
        }
    }
    return null;
}
项目:tasfe-framework    文件:NettyHttpServletResponse.java   
/**
 * 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;
}
项目:async-sqs    文件:AsyncResponseConverterTest.java   
@Test
public void testConvert() throws IOException {
    Response responseMock = mock(Response.class);

    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(TEST_KEY_A, TEST_VALUE_B);
    headers.add(TEST_KEY_C, TEST_VALUE_D);

    when(responseMock.getHeaders()).thenReturn(headers);
    when(responseMock.getStatusCode()).thenReturn(STATUS_CODE);
    when(responseMock.getStatusText()).thenReturn(STATUS_TEXT);
    when(responseMock.getResponseBodyAsStream()).thenReturn(
            new ByteArrayInputStream(ENCODED_BODY.getBytes(StandardCharsets.UTF_8))
    );

    BiFunction<Response, Request, HttpResponse> converter = new AsyncResponseConverter();
    HttpResponse awsResponse = converter.apply(responseMock, null);

    assertThat(awsResponse.getHeaders().get(TEST_KEY_A)).isEqualTo(TEST_VALUE_B);
    assertThat(awsResponse.getHeaders().get(TEST_KEY_C)).isEqualTo(TEST_VALUE_D);
    assertThat(awsResponse.getStatusCode()).isEqualTo(STATUS_CODE);
    assertThat(awsResponse.getStatusText()).isEqualTo(STATUS_TEXT);
    assertThat(new BufferedReader(new InputStreamReader(awsResponse.getContent())).readLine())
            .isEqualTo(ENCODED_BODY);
}
项目:siddhi-io-http    文件:HttpIoUtil.java   
/**
 * Create new HTTP carbon message.
 *
 * @param payload
 * @param statusCode
 * @return
 */
private static HTTPCarbonMessage createErrorMessage(String payload, int statusCode) {

    HTTPCarbonMessage response = createHttpCarbonMessage(false);
    StringDataSource stringDataSource = new StringDataSource(payload
            , new HttpMessageDataStreamer(response).getOutputStream());
    response.setMessageDataSource(stringDataSource);
    byte[] errorMessageBytes = payload.getBytes(Charset.defaultCharset());

    HttpHeaders httpHeaders = response.getHeaders();
    httpHeaders.set(org.wso2.transport.http.netty.common.Constants.HTTP_CONNECTION,
            org.wso2.transport.http.netty.common.Constants.CONNECTION_KEEP_ALIVE);
    httpHeaders.set(org.wso2.transport.http.netty.common.Constants.HTTP_CONTENT_TYPE,
            org.wso2.transport.http.netty.common.Constants.TEXT_PLAIN);
    httpHeaders.set(org.wso2.transport.http.netty.common.Constants.HTTP_CONTENT_LENGTH,
            (String.valueOf(errorMessageBytes.length)));

    response.setProperty(org.wso2.transport.http.netty.common.Constants.HTTP_STATUS_CODE, statusCode);
    response.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
            org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
    return response;
}
项目:jsf-sdk    文件:HttpJsonHandler.java   
public static int writeBack(Channel channel, boolean isSuccess, String resultStr, boolean isKeepAlive) {
    ByteBuf content = Unpooled.copiedBuffer(resultStr, Constants.DEFAULT_CHARSET);
    HttpResponseStatus status;
    if (isSuccess) {
        status = HttpResponseStatus.OK;
    } else {
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    //logger.info("result str:{}", resultStr);
    res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    HttpHeaders.setContentLength(res, content.readableBytes());
    try {
        ChannelFuture f = channel.writeAndFlush(res);
        if (isKeepAlive) {
            HttpHeaders.setKeepAlive(res, true);
        } else {
            HttpHeaders.setKeepAlive(res, false);//set keepalive closed
            f.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e2) {
        logger.warn("Failed to send HTTP response to remote, cause by:", e2);
    }

    return content.readableBytes();
}
项目:proxyee-down    文件:BdyBatchDownIntercept.java   
@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);
}
项目:proxyee-down    文件:HttpDownUtil.java   
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();
}
项目:proxyee-down    文件:HttpDownUtil.java   
/**
 * 取下载文件的总大小
 */
public static long getDownFileSize(HttpHeaders resHeaders) {
  String contentRange = resHeaders.get(HttpHeaderNames.CONTENT_RANGE);
  if (contentRange != null) {
    Pattern pattern = Pattern.compile("^[^\\d]*(\\d+)-(\\d+)/.*$");
    Matcher matcher = pattern.matcher(contentRange);
    if (matcher.find()) {
      long startSize = Long.parseLong(matcher.group(1));
      long endSize = Long.parseLong(matcher.group(2));
      return endSize - startSize + 1;
    }
  } else {
    String contentLength = resHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
    if (contentLength != null) {
      return Long.valueOf(resHeaders.get(HttpHeaderNames.CONTENT_LENGTH));
    }
  }
  return 0;
}
项目:little_mitm    文件:ProxyUtilsTest.java   
@Test
public void testAddNewViaHeaderToExistingViaHeader() {
    String hostname = "hostname";

    HttpMessage httpMessage = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/endpoint");
    httpMessage.headers().add(HttpHeaders.Names.VIA, "1.1 otherproxy");
    ProxyUtils.addVia(httpMessage, hostname);

    List<String> viaHeaders = httpMessage.headers().getAll(HttpHeaders.Names.VIA);
    assertThat(viaHeaders, hasSize(2));

    assertEquals("1.1 otherproxy", viaHeaders.get(0));

    String expectedViaHeader = "1.1 " + hostname;
    assertEquals(expectedViaHeader, viaHeaders.get(1));
}
项目:ServiceCOLDCache    文件:NettyRequestProxyFilter.java   
protected HttpResponse handleNonProxyRequest(FullHttpRequest req) {
    String uri = req.getUri();
    if ("/version".equals(uri)) {
        if (HttpMethod.GET.equals(req.getMethod())) {
            JsonObject jsonObj = new JsonObject();
            jsonObj.addProperty("name", m_appConfig.getAppName());
            jsonObj.addProperty("version", m_appConfig.getAppVersion());
            byte[] content = jsonObj.toString().getBytes(CharsetUtil.UTF_8);
            DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.copiedBuffer(content));
            HttpHeaders.setKeepAlive(resp, false);
            HttpHeaders.setHeader(resp, HttpHeaders.Names.CONTENT_TYPE,
                    "application/json");
            HttpHeaders.setContentLength(resp, content.length);
            return resp;
        }
    }

    return RESPONSE_404;
}
项目:ServiceCOLDCache    文件:NettyRequestProxyFilter.java   
private void debugRequestInfo(HttpObject httpObject, String key) {
    if (m_debugInfo && httpObject instanceof HttpRequest) {
        if (key != null) {
            LOGGER.debug("Cache Key: " + key);
        }
        if (httpObject instanceof FullHttpRequest) {
            FullHttpRequest req = (FullHttpRequest) httpObject;
            HttpHeaders headers = req.headers();
            LOGGER.debug("Headers:");
            for (Iterator<Entry<String, String>> it = headers.iterator(); it
                    .hasNext();) {
                Entry<String, String> entry = it.next();
                LOGGER.debug("\t" + entry.getKey() + ":\t"
                        + entry.getValue());
            }
            ByteBuf content = req.content();
            int length = content.readableBytes();
            LOGGER.debug("Content Length: " + length);
            if (length != 0) {
                LOGGER.debug("Content: "
                        + content.toString(Charset.forName("UTF-8")));
            }
        }
    }
}
项目:megaphone    文件:Redirect30xInterceptor.java   
private HttpHeaders propagatedHeaders(Request request, Realm realm, boolean keepBody) {

        HttpHeaders headers = request.getHeaders()//
                .remove(HttpHeaders.Names.HOST)//
                .remove(HttpHeaders.Names.CONTENT_LENGTH);

        if (!keepBody) {
            headers.remove(HttpHeaders.Names.CONTENT_TYPE);
        }

        if (realm != null && realm.getScheme() == AuthScheme.NTLM) {
            headers.remove(AUTHORIZATION)//
                    .remove(PROXY_AUTHORIZATION);
        }
        return headers;
    }
项目:riposte    文件:HttpUtils.java   
/**
 * @param headers
 *     The headers containing the content-type header to parse
 * @param def
 *     The default charset to use if one wasn't found in the headers
 *
 * @return The encoding specified in the header or the default Charset if not specified.
 **/
public static Charset determineCharsetFromContentType(HttpHeaders headers, Charset def) {
    if (headers == null)
        return def;

    String contentTypeHeader = headers.get(HttpHeaders.Names.CONTENT_TYPE);
    if (contentTypeHeader == null)
        return def;

    String charset;
    Matcher m = CONTENT_TYPE_CHARSET_EXTRACTOR_PATTERN.matcher(contentTypeHeader);
    if (m.find()) {
        charset = m.group(1).trim().toUpperCase();
        try {
            return Charset.forName(charset);
        }
        catch (Exception ex) {
            throw new InvalidCharsetInContentTypeHeaderException("Invalid charset in Content-Type header", ex,
                                                                 contentTypeHeader);
        }
    }

    return def;
}
项目:cerberus-management-service    文件:CmsRequestSecurityValidatorTest.java   
@Test
public void test_validateSecureRequestForEndpoint_adds_security_context_to_request() {
    final RequestInfo<Void> requestInfo = mock(RequestInfo.class);
    when(requestInfo.getUri()).thenReturn("https://localhost");
    final HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.add(CmsRequestSecurityValidator.HEADER_X_VAULT_TOKEN, vaultToken);
    when(requestInfo.getHeaders()).thenReturn(httpHeaders);

    final Map<String, String> meta = Maps.newHashMap();
    meta.put(VaultAuthPrincipal.METADATA_KEY_IS_ADMIN, Boolean.TRUE.toString());
    meta.put(VaultAuthPrincipal.METADATA_KEY_USERNAME, "username");
    meta.put(VaultAuthPrincipal.METADATA_KEY_GROUPS, "group1,group2");
    final VaultClientTokenResponse clientTokenResponse = new VaultClientTokenResponse()
            .setId(vaultToken)
            .setMeta(meta);
    when(vaultAdminClient.lookupToken(vaultToken)).thenReturn(clientTokenResponse);

    subject.validateSecureRequestForEndpoint(requestInfo, securedEndpoint);

    verify(requestInfo).addRequestAttribute(eq(SECURITY_CONTEXT_ATTR_KEY), any(SecurityContext.class));
}
项目:msf4j-intro-webinar-samples    文件:AbstractBasicAuthInterceptor.java   
@Override
public boolean preCall(HttpRequest request, HttpResponder responder, ServiceMethodInfo serviceMethodInfo) {
    HttpHeaders headers = request.headers();
    if (headers != null) {
        String authHeader = headers.get(HttpHeaders.Names.AUTHORIZATION);
        if (authHeader != null) {
            String authType = authHeader.substring(0, AUTH_TYPE_BASIC_LENGTH);
            String authEncoded = authHeader.substring(AUTH_TYPE_BASIC_LENGTH).trim();
            if (AUTH_TYPE_BASIC.equals(authType) && !authEncoded.isEmpty()) {
                byte[] decodedByte = authEncoded.getBytes(Charset.forName("UTF-8"));
                String authDecoded = new String(Base64.getDecoder().decode(decodedByte), Charset.forName("UTF-8"));
                String[] authParts = authDecoded.split(":");
                String username = authParts[0];
                String password = authParts[1];
                if (authenticate(username, password)) {
                    return true;
                }
            }

        }
    }
    Multimap<String, String> map = ArrayListMultimap.create();
    map.put(HttpHeaders.Names.WWW_AUTHENTICATE, AUTH_TYPE_BASIC);
    responder.sendStatus(HttpResponseStatus.UNAUTHORIZED, map);
    return false;
}
项目:cerberus-management-service    文件:AuthenticateUserTest.java   
@Test
public void execute_throws_api_error_when_bad_auth_header() {
    final RequestInfo<Void> requestInfo = mock(RequestInfo.class);
    final HttpHeaders httpHeaders = new DefaultHttpHeaders();
    httpHeaders.add(HttpHeaders.Names.AUTHORIZATION, invalidAuthorizationHeader);
    when(requestInfo.getHeaders()).thenReturn(httpHeaders);

    try {
        final CompletableFuture<ResponseInfo<AuthResponse>> completableFuture =
                subject.execute(requestInfo, executor, null);
        completableFuture.join();
        fail("Expected exception not thrown.");
    } catch (CompletionException cex) {
        assertThat(cex.getCause()).isInstanceOf(ApiException.class);
    }
}
项目:SI    文件:RestHandler.java   
public boolean sendResponseMessage(String requestId, String statusCode, String body) {
    ChannelHandlerContext ctx = sessionMap.get(requestId);

    if(ctx == null) return false;

    removeSession(requestId);

    try {
        DefaultFullHttpResponse response = this.makeHttpResponse(HttpResponseStatus.valueOf(Integer.parseInt(statusCode)), body != null ? body.getBytes() : null);
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);

        HttpServerHandler.sendHttpMessage(response, ctx.channel()).
                                addListener(ChannelFutureListener.CLOSE).
                                addListener(new FilnalEventListener(ctx, true));
    } catch (Exception e) {
        log.debug("Handled exception", e);

        sendError(ctx);
    }

    return true;

}
项目:SI    文件:HttpHandler.java   
@Override
public boolean sendHttpResponse(OneM2mResponse resMessage) {
    ChannelHandlerContext ctx = sessionMap.get(resMessage.getRequestIdentifier());
    DefaultFullHttpResponse response = null;

    if(ctx == null) return false;

    removeSession(resMessage.getRequestIdentifier());

    try {
        response = HttpResponseCodec.encode(resMessage, httpVersion);
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);

        HttpServerHandler.sendHttpMessage(response, ctx.channel()).
                                addListener(ChannelFutureListener.CLOSE).
                                addListener(new FilnalEventListener(ctx, true));
    } catch (Exception e) {
        log.debug("Handled exception", e);

        sendError(ctx);
    }

    return true;

}
项目:restlet-framework    文件:NettyServerCall.java   
@Override
public void writeResponseHead(Response restletResponse) throws IOException {
    setNettyResponse(new DefaultHttpResponse(HTTP_1_1, new HttpResponseStatus(getStatusCode(), getReasonPhrase())));
    HttpHeaders headers = getNettyResponse().headers();

    // this.response.clear();
    for (Header header : getResponseHeaders()) {
        headers.add(header.getName(), header.getValue());
    }

    // Decide whether to close the connection or not.
    if (isKeepAlive()) {
        headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        getNettyChannel().write(getNettyResponse());
    } else {
        getNettyChannel().writeAndFlush(getNettyResponse()).addListener(ChannelFutureListener.CLOSE);
    }
}
项目:riposte    文件:ResponseSender.java   
/**
 * Copied from {@link io.netty.handler.codec.http.HttpObjectDecoder#isContentAlwaysEmpty(HttpMessage)} in Netty
 * version 4.0.36-Final.
 *
 * <p>See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html">RFC 2616 Section 4.4</a> and <a
 * href="https://github.com/netty/netty/issues/222">Netty Issue 222</a> for details on why this logic is necessary.
 *
 * @return true if this response should always be an empty body (per the RFC) and therefore *not* chunked (and with
 * a content-length header of 0), false if the RFC does not forbid a body and it is therefore eligible for
 * chunking.
 */
protected boolean isContentAlwaysEmpty(ResponseInfo<?> res) {
    int code = res.getHttpStatusCode();

    // Correctly handle return codes of 1xx.
    //
    // See:
    //     - http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html Section 4.4
    //     - https://github.com/netty/netty/issues/222
    if (code >= 100 && code < 200) {
        // One exception: Hixie 76 websocket handshake response
        return !(code == 101 && !res.getHeaders().contains(HttpHeaders.Names.SEC_WEBSOCKET_ACCEPT)
                 && res.getHeaders().contains(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET, true));
    }

    switch (code) {
        case 204:
        case 205:
        case 304:
            return true;
    }

    return false;
}
项目:riposte    文件:HttpUtilsTest.java   
@Test
public void extractCookies_handles_cookie_values_leniently() {
    // given
    //these are cookie values seen in the wild...
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), "2094%3Az%7C2021%3Ab");
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), "geoloc=cc=US,rc=OR,tp=vhigh,tz=PST,la=45.4978,lo=-122.6937,bw=5000");
    Cookie cookie3 = new DefaultCookie(UUID.randomUUID().toString(), "\"dm=n.com&si=27431295-a282-4745-8cd5-542e7fce" +
            "429e&ss=1477551008358&sl=76&tt=437632&obo=12&sh=1477552753923%3D76%3A12%3A437632%2C1477552698670%3D75%3" +
            "A12%3A429879%2C1477552677137%3D74%3A12%3A426596%2C1477552672564%3D73%3A12%3A425585%2C1477552669893%3D72" +
            "%3A12%3A423456&bcn=%2F%2F3408178b.mpstat.us%2F&ld=1477552753923&r=http%3A%2F%2Fwww.nike.com%2Fbe%2Fde_de%" +
            "2F&ul=1477552756811\"");
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2, cookie3));

    HttpRequest nettyRequestMock = mock(HttpRequest.class);
    doReturn(headers).when(nettyRequestMock).headers();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
    assertThat(extractedCookies.contains(cookie3), is(true));
}
项目:riposte    文件:VerifyRequestSizeValidationComponentTest.java   
@Test
public void should_return_bad_request_when_chunked_request_exceeds_global_configured_max_request_size() throws Exception {
    NettyHttpClientRequestBuilder request = request()
        .withMethod(HttpMethod.POST)
        .withUri(BasicEndpoint.MATCHING_PATH)
        .withPaylod(generatePayloadOfSizeInBytes(GLOBAL_MAX_REQUEST_SIZE + 1))
        .withHeader(HttpHeaders.Names.TRANSFER_ENCODING, CHUNKED);

    // when
    NettyHttpClientResponse serverResponse = request.execute(serverConfig.endpointsPort(),
                                                            incompleteCallTimeoutMillis);

    // then
    assertThat(serverResponse.statusCode).isEqualTo(HttpResponseStatus.BAD_REQUEST.code());
    assertBadRequestErrorMessageAndMetadata(serverResponse.payload);
}
项目:riposte    文件:VerifyRequestSizeValidationComponentTest.java   
@Test
public void should_return_expected_response_when_chunked_request_not_exceeding_global_request_size() throws Exception {
    NettyHttpClientRequestBuilder request = request()
        .withMethod(HttpMethod.POST)
        .withUri(BasicEndpoint.MATCHING_PATH)
        .withPaylod(generatePayloadOfSizeInBytes(GLOBAL_MAX_REQUEST_SIZE))
        .withHeader(HttpHeaders.Names.TRANSFER_ENCODING, CHUNKED);

    // when
    NettyHttpClientResponse serverResponse = request.execute(serverConfig.endpointsPort(),
                                                            incompleteCallTimeoutMillis);

    // then
    assertThat(serverResponse.statusCode).isEqualTo(HttpResponseStatus.OK.code());
    assertThat(serverResponse.payload).isEqualTo(BasicEndpoint.RESPONSE_PAYLOAD);
}
项目:riposte    文件:VerifyRequestSizeValidationComponentTest.java   
@Test
public void should_return_bad_request_when_chunked_request_exceeds_endpoint_overridden_configured_max_request_size() throws Exception {
    NettyHttpClientRequestBuilder request = request()
        .withMethod(HttpMethod.POST)
        .withUri(BasicEndpointWithRequestSizeValidationOverride.MATCHING_PATH)
        .withPaylod(generatePayloadOfSizeInBytes(BasicEndpointWithRequestSizeValidationOverride.MAX_REQUEST_SIZE + 1))
        .withHeader(HttpHeaders.Names.TRANSFER_ENCODING, CHUNKED);

    // when
    NettyHttpClientResponse serverResponse = request.execute(serverConfig.endpointsPort(),
                                                            incompleteCallTimeoutMillis);

    // then
    assertThat(serverResponse.statusCode).isEqualTo(HttpResponseStatus.BAD_REQUEST.code());
    assertBadRequestErrorMessageAndMetadata(serverResponse.payload);
}
项目:Dream-Catcher    文件:HarCaptureFilter.java   
protected void captureRequestCookies(HttpRequest httpRequest) {
    Log.e("InnerHandle", "captureRequestCookies " + harEntry.getId());
    String cookieHeader = httpRequest.headers().get(HttpHeaders.Names.COOKIE);
    if (cookieHeader == null) {
        return;
    }

    Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader);

    for (Cookie cookie : cookies) {
        HarCookie harCookie = new HarCookie();

        harCookie.setName(cookie.name());
        harCookie.setValue(cookie.value());

        harRequest.getRequest().getCookies().add(harCookie);
        harRequest.addHeader(cookie.name(), cookie.value());
    }
}
项目:megaphone    文件:BasicAuthTest.java   
public void handle(String s, Request r, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

            LOGGER.info("request: " + request.getRequestURI());

            if ("/uff".equals(request.getRequestURI())) {
                LOGGER.info("redirect to /bla");
                response.setStatus(302);
                response.setContentLength(0);
                response.setHeader("Location", "/bla");

            } else {
                LOGGER.info("got redirected" + request.getRequestURI());
                response.setStatus(200);
                response.addHeader("X-Auth", request.getHeader("Authorization"));
                response.addHeader("X-" + HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.getContentLength()));
                byte[] b = "content".getBytes(UTF_8);
                response.setContentLength(b.length);
                response.getOutputStream().write(b);
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
项目:riposte    文件:HttpServletResponseWrapperForResponseInfoTest.java   
@DataProvider(value = {
    "true",
    "false"
}, splitBy = "\\|")
@Test
public void containsHeader_delegates_to_responseInfo(boolean containsHeader) {
    // given
    HttpHeaders headersMock = mock(HttpHeaders.class);
    doReturn(headersMock).when(responseInfoMock).getHeaders();
    String headerName = UUID.randomUUID().toString();
    doReturn(containsHeader).when(headersMock).contains(headerName);

    // expect
    assertThat(wrapper.containsHeader(headerName)).isEqualTo(containsHeader);
    verify(headersMock).contains(headerName);
}
项目:riposte    文件:HttpServletRequestWrapperForRequestInfoTest.java   
@Test
public void getHeaders_delegates_to_requestInfo_headers() {
    // given
    HttpHeaders headersMock = mock(HttpHeaders.class);
    String headerKey = UUID.randomUUID().toString();
    List<String> headerVal = Arrays.asList(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    doReturn(headerVal).when(headersMock).getAll(headerKey);
    doReturn(headersMock).when(requestInfoMock).getHeaders();

    // when
    Enumeration<String> result = wrapper.getHeaders(headerKey);

    // then
    verify(headersMock).getAll(headerKey);
    assertThat(Collections.list(result)).isEqualTo(headerVal);
}
项目:riposte    文件:HttpServletRequestWrapperForRequestInfoTest.java   
@DataProvider(value = {
    "true   |   somehost",
    "false  |   somehost",
    "true   |   null",
    "false  |   null"
}, splitBy = "\\|")
@Test
public void getRequestURL_constructs_result_from_scheme_and_host_header_and_requestInfo_path(boolean ssl,
                                                                                             String hostHeader) {
    // given
    Whitebox.setInternalState(wrapper, "isSsl", ssl);
    if (hostHeader != null)
        headers.set(HttpHeaders.Names.HOST, hostHeader);
    String path = "/" + UUID.randomUUID().toString();
    doReturn(path).when(requestInfoMock).getPath();
    String expectedResult = (ssl) ? "https://" : "http://";
    expectedResult += (hostHeader == null) ? "unknown" : hostHeader;
    expectedResult += path;

    // when
    StringBuffer result = wrapper.getRequestURL();

    // then
    assertThat(result.toString()).isEqualTo(expectedResult);
}
项目:riposte    文件:HttpServletRequestWrapperForRequestInfoTest.java   
@DataProvider(value = {
    "null       |   unknown",
    "foobar     |   foobar",
    "host:foo   |   host"
}, splitBy = "\\|")
@Test
public void getServerName_parses_value_from_host_header(String hostHeaderVal, String expectedResult) {
    // given
    if (hostHeaderVal != null)
        headers.set(HttpHeaders.Names.HOST, hostHeaderVal);

    // when
    String result = wrapper.getServerName();

    // then
    assertThat(result).isEqualTo(expectedResult);
}
项目:riposte    文件:HttpServletRequestWrapperForRequestInfoTest.java   
@DataProvider(value = {
    "null       |   -1",
    "foobar     |   -1",
    "host:4242  |   4242"
}, splitBy = "\\|")
@Test
public void getServerPort_parses_value_from_host_header(String hostHeaderVal, int expectedResult) {
    // given
    if (hostHeaderVal != null)
        headers.set(HttpHeaders.Names.HOST, hostHeaderVal);

    // when
    int result = wrapper.getServerPort();

    // then
    assertThat(result).isEqualTo(expectedResult);
}
项目:riposte    文件:HttpUtilsTest.java   
@Test
public void extractCookies_works_if_cookies_defined_in_headers() {
    // given
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2));

    HttpRequest nettyRequestMock = mock(HttpRequest.class);
    doReturn(headers).when(nettyRequestMock).headers();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
}
项目:yarpc-java    文件:TransportRequestDecoderConfiguration.java   
private Span createSpan(
    Instant start, String service, String procedure, String caller, HttpHeaders httpHeaders) {
  SpanBuilder spanBuilder =
      tracer
          .buildSpan(procedure)
          .withStartTimestamp(Instant.EPOCH.until(start, ChronoUnit.MICROS))
          .withTag(SpanTags.CALLER, caller)
          .withTag(SpanTags.SERVICE, service)
          .withTag(SpanTags.ENCODING, httpHeaders.get(HeaderMapper.ENCODING))
          .withTag(SpanTags.TRANSPORT, "http");
  SpanContext parent =
      tracer.extract(Builtin.HTTP_HEADERS, new TextMapExtractAdapter(httpHeaders));
  if (parent != null) {
    spanBuilder.asChildOf(parent);
  }
  return spanBuilder.start();
}
项目:riposte    文件:RequestInfoForLoggingRiposteAdapterTest.java   
@Test
public void getHeaderMapDelegatesToRequestInfoAndCachesResult() {
    Map<String, List<String>> expectedHeaderMap = new TreeMap<>(MapBuilder.<String, List<String>>builder()
                                                                          .put("header1", Arrays.asList("h1val1"))
                                                                          .put("header2", Arrays.asList("h2val1", "h2val2"))
                                                                          .build());

    HttpHeaders nettyHeaders = new DefaultHttpHeaders();
    for (Map.Entry<String, List<String>> headerEntry : expectedHeaderMap.entrySet()) {
        nettyHeaders.add(headerEntry.getKey(), headerEntry.getValue());
    }
    setFieldOnRequestInfo("headers", nettyHeaders);
    Map<String, List<String>> actualHeaderMap = adapter.getHeadersMap();
    assertThat(actualHeaderMap, is(expectedHeaderMap));
    assertThat(adapter.getHeadersMap(), sameInstance(actualHeaderMap));
}
项目:wecard-server    文件:NHttpMessage.java   
/**
 * 写入数据到客户端
 *
 * @param messageResult
 */
public void write(final MessageResult messageResult) {
    String json = messageResult.toJson();
    ByteBuf content = Unpooled.copiedBuffer(json, CharsetUtil.UTF_8);
    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
    HttpHeaders.setContentLength(res, content.readableBytes());

    // Send the response
    ChannelFuture f = this.channel.writeAndFlush(res);
}