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

项目:elasticsearch_my    文件:Netty4CorsHandler.java   
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");
    }
}
项目:elasticsearch_my    文件:Netty4CorsHandler.java   
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;
}
项目:elasticsearch_my    文件:Netty4CorsHandler.java   
private boolean validateOrigin() {
    if (config.isAnyOriginSupported()) {
        return true;
    }

    final String origin = request.headers().get(HttpHeaderNames.ORIGIN);
    if (Strings.isNullOrEmpty(origin)) {
        // Not a CORS request so we cannot validate it. It may be a non CORS request.
        return true;
    }

    if ("null".equals(origin) && config.isNullOriginAllowed()) {
        return true;
    }

    // if the origin is the same as the host of the request, then allow
    if (isSameOrigin(origin, request.headers().get(HttpHeaderNames.HOST))) {
        return true;
    }

    return config.isOriginAllowed(origin);
}
项目:elasticsearch_my    文件:Netty4HttpChannelTests.java   
private FullHttpResponse executeRequest(final Settings settings, final String originValue, final String host) {
    // construct request and send it over the transport layer
    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, "/");
        if (originValue != null) {
            httpRequest.headers().add(HttpHeaderNames.ORIGIN, originValue);
        }
        httpRequest.headers().add(HttpHeaderNames.HOST, host);
        final WriteCapturingChannel writeCapturingChannel = new WriteCapturingChannel();
        final Netty4HttpRequest request = new Netty4HttpRequest(xContentRegistry(), httpRequest, writeCapturingChannel);

        Netty4HttpChannel channel =
                new Netty4HttpChannel(httpServerTransport, request, null, randomBoolean(), threadPool.getThreadContext());
        channel.sendResponse(new TestResponse());

        // get the response
        List<Object> writtenObjects = writeCapturingChannel.getWrittenObjects();
        assertThat(writtenObjects.size(), is(1));
        return (FullHttpResponse) writtenObjects.get(0);
    }
}
项目:ace    文件:StaticFileServerHandler.java   
/**
 * 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())));
}
项目:WebSandboxMC    文件:WebSocketIndexPageHandler.java   
private void sendTextResource(String prepend, String name, String mimeType, FullHttpRequest req, ChannelHandlerContext ctx) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader((this.getResourceAsStream(name))));
    // TODO: read only once and buffer
    String line;
    StringBuffer buffer = new StringBuffer();
    if (prepend != null) buffer.append(prepend);
    while ((line = reader.readLine()) != null) {
        buffer.append(line);
        buffer.append('\n');
    }
    ByteBuf content = Unpooled.copiedBuffer(buffer, java.nio.charset.Charset.forName("UTF-8"));

    FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, OK, content);

    res.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeType);
    HttpUtil.setContentLength(res, content.readableBytes());

    sendHttpResponse(ctx, req, res);
}
项目: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;
}
项目:HFSN    文件:HttpFileServerHandler.java   
/**
 * 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())));
}
项目:standalone-hystrix-dashboard    文件:HystrixDashboardProxyEurekaTest.java   
@Test
public void testShouldFetchDataWithHeaders(TestContext testContext) throws Exception {
  final String fakeEurekaServerUrl = "http://localhost:" + FAKE_EUREKA_SERVER_PORT + "/eureka/v2/apps";
  final String dashboardProxyUrl = DASHBOARD_EUREKA_PROXY_URL + fakeEurekaServerUrl;

  final Async fetchData = testContext.async();

  httpClient.getNow(dashboardProxyUrl, resp -> resp.bodyHandler(buffer -> {
    final String responseData = buffer.toString(StandardCharsets.UTF_8);

    if (resp.statusCode() != 200) {
      testContext.fail("Response Status => " + resp.statusCode() + "\nResponse: " + responseData);
    } else {
      testContext.assertTrue("application/xml".equals(resp.getHeader(HttpHeaderNames.CONTENT_TYPE)));

      testContext.assertTrue(responseData.contains("<apps__hashcode>UP_2_</apps__hashcode>"));
      testContext.assertTrue(responseData.contains("<registrationTimestamp>1472352522224</registrationTimestamp>"));

      fetchData.complete();
    }
  }));

  fetchData.awaitSuccess(5000L);
}
项目:Elastic-Components    文件:AddHttpResponseGeneratorImpl.java   
@Override
public HttpResponse generate(JsonObject value) {
    ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder();

    fields.forEach(field -> {
        builder.put(field, value.getValue(field));
    });

    return new HttpResponse(
        HttpResponseStatus.CREATED.code(),
        ImmutableMap.of(
            HttpHeaderNames.CONTENT_TYPE.toString(), ServerUtils.APPLICATION_JSON_UTF_8
        ),
        new JsonObject(builder.build()).encode()
    );
}
项目:knotx    文件:HttpRepositoryConnectorProxyImpl.java   
private MultiMap buildHeaders(String hostHeader, MultiMap headers) {
  MultiMap result = filteredHeaders(headers);

  if (customRequestHeader.containsKey("name") && customRequestHeader.containsKey("value")) {
    result.set(
        customRequestHeader.getString("name"),
        customRequestHeader.getString("value")
    );
  }

  //Overide host header if provided in client destination
  if (StringUtils.isNotBlank(hostHeader)) {
    result.set(HttpHeaderNames.HOST.toString(), hostHeader);
  }

  return result;
}
项目:twill    文件:TrackerService.java   
private void writeResourceReport(Channel channel) {
  ByteBuf content = Unpooled.buffer();
  Writer writer = new OutputStreamWriter(new ByteBufOutputStream(content), CharsetUtil.UTF_8);
  try {
    reportAdapter.toJson(resourceReport.get(), writer);
    writer.close();
  } catch (IOException e) {
    LOG.error("error writing resource report", e);
    writeAndClose(channel, new DefaultFullHttpResponse(
      HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR,
      Unpooled.copiedBuffer(e.getMessage(), StandardCharsets.UTF_8)));
    return;
  }

  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
  HttpUtil.setContentLength(response, content.readableBytes());
  response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
  channel.writeAndFlush(response);
}
项目:shortcircuit-proxy    文件:HttpStaticFileServerHandler.java   
/**
 * 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())));
}
项目: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);
    }
}
项目:lannister    文件:HttpClient.java   
protected static void setDefaultHeaders(HttpRequest httpRequest) {
    if (!httpRequest.headers().contains(HttpHeaderNames.HOST)) {
        httpRequest.headers().set(HttpHeaderNames.HOST, httpRequest.uriObject().getHost());
    }
    if (!httpRequest.headers().contains(HttpHeaderNames.CONNECTION)) {
        httpRequest.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }
    if (!httpRequest.headers().contains(HttpHeaderNames.ACCEPT_ENCODING)) {
        httpRequest.headers().set(HttpHeaderNames.ACCEPT_ENCODING,
                HttpHeaderValues.GZIP + ", " + HttpHeaderValues.DEFLATE);
    }
    if (!httpRequest.headers().contains(HttpHeaderNames.ACCEPT_CHARSET)) {
        httpRequest.headers().set(HttpHeaderNames.ACCEPT_CHARSET, "utf-8");
    }
    if (!httpRequest.headers().contains(HttpHeaderNames.CONTENT_TYPE)) {
        httpRequest.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    }
}
项目:lannister    文件:HttpRequestRouter.java   
private void handleStaticResource(HttpResponse response, String webResourceRequestPath) throws IOException {
    String requestPath = webResourceRequestPath;
    if (requestPath.startsWith("/")) {
        requestPath = requestPath.substring(1, requestPath.length());
    }

    InputStream is = Application.class.getClassLoader().getResourceAsStream(requestPath);

    try {
        if (is == null) {
            set404Response(response);
        }
        else {
            response.content().writeBytes(IOUtils.toByteArray(is));

            String ext = Files.getFileExtension(requestPath);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,
                    Settings.INSTANCE.webResourceExtensionToMimes().get(ext));
        }
    }
    finally {
        if (is != null) {
            is.close();
        }
    }
}
项目:lannister    文件:HttpRequestRouter.java   
protected static void setDefaultHeaders(FullHttpRequest request, HttpResponse response) {
    response.headers().add(HttpHeaderNames.SERVER,
            "lannister " + net.anyflow.lannister.Settings.INSTANCE.version());

    boolean keepAlive = HttpHeaderValues.KEEP_ALIVE.toString()
            .equals(request.headers().get(HttpHeaderNames.CONNECTION));
    if (keepAlive) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    if (Settings.INSTANCE.getProperty("webserver.allowCrossDomain", "false").equalsIgnoreCase("true")) {
        response.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, "POST, GET, PUT, DELETE");
        response.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "X-PINGARUNER");
        response.headers().add(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, "1728000");
    }

    response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
}
项目:lannister    文件:HttpRequest.java   
public Map<String, List<String>> parameters() {

        if (parameters != null) { return parameters; }

        Map<String, List<String>> ret = Maps.newHashMap();

        if (HttpMethod.GET.equals(method()) || HttpMethod.DELETE.equals(method())) {
            ret.putAll(new QueryStringDecoder(uri()).parameters());
            return ret;
        }
        else if (headers().contains(HttpHeaderNames.CONTENT_TYPE)
                && headers().get(HttpHeaderNames.CONTENT_TYPE)
                        .startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString())
                && (HttpMethod.POST.equals(method()) || HttpMethod.PUT.equals(method()))) {

            ret.putAll(new QueryStringDecoder("/dummy?" + content().toString(CharsetUtil.UTF_8)).parameters());
        }

        return ret;
    }
项目:lannister    文件:HttpResponse.java   
public static HttpResponse createServerDefault(String requestCookie) {
    HttpResponse ret = new HttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.buffer());

    ret.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");

    if (requestCookie == null) { return ret; }

    Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(requestCookie);
    if (cookies.isEmpty()) { return ret; }

    // Reset the cookies if necessary.
    for (Cookie cookie : cookies) {
        ret.headers().add(HttpHeaderNames.SET_COOKIE, ClientCookieEncoder.STRICT.encode(cookie));
    }

    return ret;
}
项目:vertx-utils    文件:HealthcheckHandler.java   
protected void processHeartBeatResponse(Boolean exists, HttpServerRequest request, long startTime) {
    HttpResponseStatus status;
    final boolean includeBody = !request.method().equals(HttpMethod.HEAD);

    if (exists) {
        status = HttpResponseStatus.OK;
    } else {
        status = HttpResponseStatus.SERVICE_UNAVAILABLE;
    }

    setCommonHttpResponse(request, status);

    String responseBody = status.reasonPhrase();
    if (includeBody) {
        request.response().end(responseBody);
    } else {
        request.response().putHeader(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(responseBody.length()));
        request.response().end();
    }

    long totalTime = System.currentTimeMillis() - startTime;
    LOG.debug("handle", "healthcheckResponse", new String[]{"method", "status", "totalTime"},
            request.method(), status.code(), totalTime);
}
项目:vertx-utils    文件:HealthcheckHandler.java   
protected void processExceptionResponse(HttpServerRequest request, Exception ex, long startTime) {
    HttpResponseStatus status = HttpResponseStatus.SERVICE_UNAVAILABLE;
    final boolean includeBody = !request.method().equals(HttpMethod.HEAD);
    String responseBody = status.reasonPhrase() + ": " + ex.getMessage();

    setCommonHttpResponse(request, status);

    if (includeBody) {
        request.response().end(responseBody);
    } else {
        request.response().putHeader(HttpHeaderNames.CONTENT_LENGTH, Integer.toString(responseBody.length()));
        request.response().end();
    }

    long totalTime = System.currentTimeMillis() - startTime;
    LOG.debug("handle", "healthcheckResponse", new String[] {"method", "status", "totalTime"}, request.method(),
            status.code(), totalTime);
}
项目:vertx-utils    文件:HealthcheckHandlerTest.java   
@Test
public void testHandle() {
    stub(existsResult.result()).toReturn(true);
    handler.handle(request);

    verify(vertx, times(1)).fileSystem();

    verify(fileSystem, times(1)).exists(eq("filepath"), existCaptor.capture());

    existCaptor.getValue().handle(existsResult);

    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE);
    verify(response, times(1)).putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL);
    verify(response, times(1)).setStatusCode(OK.code());
    verify(response, times(1)).setStatusMessage(OK.reasonPhrase());
    verify(response, times(1)).end(OK.reasonPhrase());
}
项目:vertx-utils    文件:HealthcheckHandlerTest.java   
@Test
public void testSyncHandle() {
    handler = new SyncHealthcheckHandler(vertx, "filepath");
    stub(fileSystem.existsBlocking(eq("filepath"))).toReturn(true);
    stub(vertx.fileSystem()).toReturn(fileSystem);

    handler.handle(request);
    verify(vertx, times(1)).fileSystem();
    verify(fileSystem, times(1)).existsBlocking(eq("filepath"));

    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE);
    verify(response, times(1)).putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL);
    verify(response, times(1)).setStatusCode(OK.code());
    verify(response, times(1)).setStatusMessage(OK.reasonPhrase());
    verify(response, times(1)).end(OK.reasonPhrase());
}
项目:vertx-utils    文件:HealthcheckHandlerTest.java   
@Test
public void testHandleNotExists() {
    stub(existsResult.result()).toReturn(false);
    handler.handle(request);

    verify(vertx, times(1)).fileSystem();

    verify(fileSystem, times(1)).exists(eq("filepath"), existCaptor.capture());

    existCaptor.getValue().handle(existsResult);

    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE);
    verify(response, times(1)).putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL);
    verify(response, times(1)).setStatusCode(SERVICE_UNAVAILABLE.code());
    verify(response, times(1)).setStatusMessage(SERVICE_UNAVAILABLE.reasonPhrase());
    verify(response, times(1)).end(SERVICE_UNAVAILABLE.reasonPhrase());
}
项目:vertx-utils    文件:HealthcheckHandlerTest.java   
@Test
public void testHandleExsistsException() {
    IllegalArgumentException exception = new IllegalArgumentException("Failed");

    doThrow(exception).when(fileSystem).exists(eq("filepath"), existCaptor.capture());

    handler.handle(request);

    verify(vertx, times(1)).fileSystem();
    verify(fileSystem, times(1)).exists(eq("filepath"), existCaptor.capture());

    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE);
    verify(response, times(1)).putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL);
    verify(response, times(1)).setStatusCode(SERVICE_UNAVAILABLE.code());
    verify(response, times(1)).setStatusMessage(SERVICE_UNAVAILABLE.reasonPhrase());
    verify(response, times(1)).end(SERVICE_UNAVAILABLE.reasonPhrase() + ": " + exception.getMessage());
}
项目:vertx-utils    文件:HealthcheckHandlerTest.java   
@Test
public void testSyncHandleExsistsException() {
    IllegalArgumentException exception = new IllegalArgumentException("Failed");

    doThrow(exception).when(fileSystem).existsBlocking(eq("filepath"));

    handler = new SyncHealthcheckHandler(vertx, "filepath");
    stub(vertx.fileSystem()).toReturn(fileSystem);

    handler.handle(request);

    verify(vertx, times(1)).fileSystem();
    verify(fileSystem, times(1)).existsBlocking(eq("filepath"));

    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE);
    verify(response, times(1)).putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL);
    verify(response, times(1)).setStatusCode(SERVICE_UNAVAILABLE.code());
    verify(response, times(1)).setStatusMessage(SERVICE_UNAVAILABLE.reasonPhrase());
    verify(response, times(1)).end(SERVICE_UNAVAILABLE.reasonPhrase() + ": " + exception.getMessage());
}
项目:vertx-utils    文件:HealthcheckHandlerTest.java   
@Test
public void testSyncHandleHead() {
    stub(request.method()).toReturn(HttpMethod.HEAD);
    stub(existsResult.result()).toReturn(true);

    handler = new SyncHealthcheckHandler(vertx, "filepath");
    stub(fileSystem.existsBlocking(eq("filepath"))).toReturn(true);
    stub(vertx.fileSystem()).toReturn(fileSystem);

    handler.handle(request);


    verify(vertx, times(1)).fileSystem();

    verify(fileSystem, times(1)).existsBlocking(eq("filepath"));

    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE);
    verify(response, times(1)).putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL);
    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_LENGTH, "" + OK.reasonPhrase().length());
    verify(response, times(1)).setStatusCode(OK.code());
    verify(response, times(1)).setStatusMessage(OK.reasonPhrase());
    verify(response, times(1)).end();
}
项目:vertx-utils    文件:HealthcheckHandlerTest.java   
@Test
public void testHandleNotExistsHead() {
    stub(request.method()).toReturn(HttpMethod.HEAD);
    stub(existsResult.result()).toReturn(false);

    handler.handle(request);

    verify(vertx, times(1)).fileSystem();

    verify(fileSystem, times(1)).exists(eq("filepath"), existCaptor.capture());

    existCaptor.getValue().handle(existsResult);

    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE);
    verify(response, times(1)).putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL);
    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_LENGTH, "" + SERVICE_UNAVAILABLE.reasonPhrase().length());
    verify(response, times(1)).setStatusCode(SERVICE_UNAVAILABLE.code());
    verify(response, times(1)).setStatusMessage(SERVICE_UNAVAILABLE.reasonPhrase());
    verify(response, times(1)).end();
}
项目:nomulus    文件:TestUtils.java   
public static FullHttpRequest makeEppHttpRequest(
    String content,
    String host,
    String path,
    String accessToken,
    String sslClientCertificateHash,
    String serverHostname,
    String clientAddress,
    Cookie... cookies) {
  FullHttpRequest request = makeHttpPostRequest(content, host, path);
  request
      .headers()
      .set(HttpHeaderNames.AUTHORIZATION, "Bearer " + accessToken)
      .set(HttpHeaderNames.CONTENT_TYPE, EPP_CONTENT_TYPE)
      .set(HttpHeaderNames.ACCEPT, EPP_CONTENT_TYPE)
      .set(SSL_CLIENT_CERTIFICATE_HASH_FIELD, sslClientCertificateHash)
      .set(REQUESTED_SERVERNAME_VIA_SNI_FIELD, serverHostname)
      .set(FORWARDED_FOR_FIELD, clientAddress);
  if (cookies.length != 0) {
    request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT.encode(cookies));
  }
  return request;
}
项目:vertx-utils    文件:HealthcheckHandlerTest.java   
@Test
public void testHandleExistsExceptionHead() {
    stub(request.method()).toReturn(HttpMethod.HEAD);

    IllegalArgumentException exception = new IllegalArgumentException("Failed");
    String body = SERVICE_UNAVAILABLE.reasonPhrase() + ": " + exception.getMessage();

    doThrow(exception).when(fileSystem).exists(eq("filepath"), existCaptor.capture());

    handler.handle(request);

    verify(vertx, times(1)).fileSystem();
    verify(fileSystem, times(1)).exists(eq("filepath"), existCaptor.capture());

    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE);
    verify(response, times(1)).putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL);
    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_LENGTH, "" + body.length());
    verify(response, times(1)).setStatusCode(SERVICE_UNAVAILABLE.code());
    verify(response, times(1)).setStatusMessage(SERVICE_UNAVAILABLE.reasonPhrase());
    verify(response, times(1)).end();
}
项目:vertx-utils    文件:HealthcheckHandlerTest.java   
@Test
public void testSyncHandleExistsExceptionHead() {
    stub(request.method()).toReturn(HttpMethod.HEAD);

    IllegalArgumentException exception = new IllegalArgumentException("Failed");
    String body = SERVICE_UNAVAILABLE.reasonPhrase() + ": " + exception.getMessage();

    doThrow(exception).when(fileSystem).existsBlocking(eq("filepath"));

    handler = new SyncHealthcheckHandler(vertx, "filepath");
    stub(vertx.fileSystem()).toReturn(fileSystem);

    handler.handle(request);

    verify(vertx, times(1)).fileSystem();
    verify(fileSystem, times(1)).existsBlocking(eq("filepath"));

    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_TYPE, CONTENT_TYPE);
    verify(response, times(1)).putHeader(HttpHeaderNames.CACHE_CONTROL, CACHE_CONTROL);
    verify(response, times(1)).putHeader(HttpHeaderNames.CONTENT_LENGTH, "" + body.length());
    verify(response, times(1)).setStatusCode(SERVICE_UNAVAILABLE.code());
    verify(response, times(1)).setStatusMessage(SERVICE_UNAVAILABLE.reasonPhrase());
    verify(response, times(1)).end();
}
项目:reactor-netty    文件:HttpClient.java   
static Function<? super HttpClientRequest, ? extends Publisher<Void>> handler(Function<? super HttpClientRequest, ? extends Publisher<Void>> h,
        HttpClientOptions opts) {
    if (opts.acceptGzip()) {
        if (h != null) {
            return req -> h.apply(req.header(HttpHeaderNames.ACCEPT_ENCODING,
                    HttpHeaderValues.GZIP));
        }
        else {
            return req -> req.header(HttpHeaderNames.ACCEPT_ENCODING,
                    HttpHeaderValues.GZIP);
        }
    }
    else {
        return h;
    }
}
项目:reactor-netty    文件:HttpClientOperations.java   
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);
}
项目:reactor-netty    文件:HttpClientOperations.java   
@Override
public NettyOutbound send(Publisher<? extends ByteBuf> source) {
    if (method() == HttpMethod.GET || method() == HttpMethod.HEAD) {
        ByteBufAllocator alloc = channel().alloc();
        return then(Flux.from(source)
            .doOnNext(ByteBuf::retain)
            .collect(alloc::buffer, ByteBuf::writeBytes)
            .flatMapMany(agg -> {
                if (!hasSentHeaders() && !HttpUtil.isTransferEncodingChunked(
                        outboundHttpMessage()) && !HttpUtil.isContentLengthSet(
                        outboundHttpMessage())) {
                    outboundHttpMessage().headers()
                                         .setInt(HttpHeaderNames.CONTENT_LENGTH,
                                                 agg.readableBytes());
                }
                return send(Mono.just(agg)).then();
            }));
    }
    return super.send(source);
}
项目:reactor-netty    文件:HttpServerRoutes.java   
/**
 * Listen for WebSocket on the passed path to be used as a routing condition. Incoming
 * connections will query the internal registry to invoke the matching handlers. <p>
 * Additional regex matching is available e.g. "/test/{param}".
 * Params are resolved using {@link HttpServerRequest#param(CharSequence)}
 * They are not accessible in the handler provided as parameter.
 *
 * @param path The websocket path used by clients
 * @param handler an handler to invoke for the given condition
 * @param protocols sub-protocol to use in WS handshake signature
 *
 * @return a new handler
 */
@SuppressWarnings("unchecked")
default HttpServerRoutes ws(String path,
        BiFunction<? super WebsocketInbound, ? super WebsocketOutbound, ? extends
                Publisher<Void>> handler,
        String protocols) {
    Predicate<HttpServerRequest> condition = HttpPredicate.get(path);

    return route(condition, (req, resp) -> {
        if (req.requestHeaders()
               .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE, true)) {

            HttpServerOperations ops = (HttpServerOperations) req;
            return ops.withWebsocketSupport(req.uri(), protocols,
                    handler);
        }
        return resp.sendNotFound();
    });
}
项目:reactor-netty    文件:HttpServerOperations.java   
@Override
protected void onOutboundError(Throwable err) {

    if (!channel().isActive()) {
        super.onOutboundError(err);
        return;
    }

    discreteRemoteClose(err);
    if (markSentHeaders()) {
        log.error("Error starting response. Replying error status", err);

        HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.INTERNAL_SERVER_ERROR);
        response.headers()
                .setInt(HttpHeaderNames.CONTENT_LENGTH, 0)
                .set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        channel().writeAndFlush(response)
                 .addListener(ChannelFutureListener.CLOSE);
        return;
    }

    markSentBody();
    channel().writeAndFlush(EMPTY_BUFFER)
             .addListener(ChannelFutureListener.CLOSE);
}
项目:reactor-netty    文件:HttpOperations.java   
@Override
public Mono<Void> then() {
    if (markSentHeaders()) {
        if (HttpUtil.isContentLengthSet(outboundHttpMessage())) {
            outboundHttpMessage().headers()
                                 .remove(HttpHeaderNames.TRANSFER_ENCODING);
        }

        if (!HttpUtil.isTransferEncodingChunked(outboundHttpMessage())
                && !HttpUtil.isContentLengthSet(outboundHttpMessage())) {
            markPersistent(false);
        }

        return FutureMono.deferFuture(() -> channel().writeAndFlush(outboundHttpMessage()));
    }
    else {
        return Mono.empty();
    }
}
项目:reactor-netty    文件:HttpOperations.java   
@Override
public final NettyOutbound sendFile(Path file, long position, long count) {
    Objects.requireNonNull(file);

    if (hasSentHeaders()) {
        return super.sendFile(file, position, count);
    }

    if (!HttpUtil.isTransferEncodingChunked(outboundHttpMessage()) && !HttpUtil.isContentLengthSet(
            outboundHttpMessage()) && count < Integer.MAX_VALUE) {
        outboundHttpMessage().headers()
                             .setInt(HttpHeaderNames.CONTENT_LENGTH, (int) count);
    }
    else if (!HttpUtil.isContentLengthSet(outboundHttpMessage())) {
        outboundHttpMessage().headers()
                             .remove(HttpHeaderNames.CONTENT_LENGTH)
                             .remove(HttpHeaderNames.TRANSFER_ENCODING);
        HttpUtil.setTransferEncodingChunked(outboundHttpMessage(), true);
    }

    return super.sendFile(file, position, count);
}
项目:reactor-netty    文件:HttpClientTest.java   
private void doTestGzip(boolean gzipEnabled) {
    String expectedResponse = gzipEnabled ? "gzip" : "no gzip";
    NettyContext server = HttpServer.create(0)
            .newHandler((req,res) -> res.sendString(
                    Mono.just(req.requestHeaders().get(HttpHeaderNames.ACCEPT_ENCODING, "no gzip"))))
            .block(Duration.ofSeconds(30));
    StepVerifier.create(
            HttpClient.create(ops -> ops.port(server.address().getPort()).compression(gzipEnabled))
                      .get("/")
                      .flatMap(r -> r.receive()
                                     .asString()
                                     .elementAt(0)
                                     .zipWith(Mono.just(r)))
            )
                .expectNextMatches(tuple -> {
                    tuple.getT2().dispose();
                    return expectedResponse.equals(tuple.getT1());
                })
                .expectComplete()
                .verify(Duration.ofSeconds(30));

    server.dispose();
}