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

项目:libcwfincore    文件:GdaxExchangeSession.java   
private String computeAccessSignature(String timestamp, HttpMethod method, String urlTxt, ByteBuffer body)
        throws GeneralSecurityException {
    if (conn == null) {
        throw new IllegalStateException("cannot generate exchange request post-disconnect()");
    }

    String prehash = timestamp + method.name() + urlTxt;

    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(signingKey);
    mac.update(prehash.getBytes());
    if (body != null) {
        mac.update(body);
    }
    return new String(Base64.encodeBase64(mac.doFinal()));
}
项目:redant    文件:RouterContext.java   
public static void main(String[] args) {
    int loopTimes = 200;

    class Runner implements Runnable{

        private Logger logger = LoggerFactory.getLogger(Runner.class);

        @Override
        public void run() {
            RouteResult<RenderType> result = RouterContext.getRouteResult(HttpMethod.GET,"/user/info");
            logger.info("routeResult={},currentThread={}",result,Thread.currentThread().getName());
        }
    }

    for(int i=0;i<loopTimes;i++){
        new Thread(new Runner()).start();
    }

}
项目:redant    文件:Router.java   
/**
 * Returns allowed methods for a specific URI.
 * <p>
 * For {@code OPTIONS *}, use {@link #allAllowedMethods()} instead of this method.
 */
public Set<HttpMethod> allowedMethods(String uri) {
    QueryStringDecoder decoder = new QueryStringDecoder(uri);
    String[] tokens = PathPattern.removeSlashesAtBothEnds(decoder.path()).split("/");

    if (anyMethodRouter.anyMatched(tokens)) {
        return allAllowedMethods();
    }

    Set<HttpMethod> ret = new HashSet<HttpMethod>(routers.size());
    for (Entry<HttpMethod, MethodlessRouter<T>> entry : routers.entrySet()) {
        MethodlessRouter<T> router = entry.getValue();
        if (router.anyMatched(tokens)) {
            HttpMethod method = entry.getKey();
            ret.add(method);
        }
    }

    return ret;
}
项目:redant    文件:Router.java   
/**
 * Given a target and params, this method tries to do the reverse routing
 * and returns the URI.
 *
 * <p>Placeholders in the path pattern will be filled with the params.
 * The params can be a map of {@code placeholder name -> value}
 * or ordered values.
 *
 * <p>If a param doesn't have a corresponding placeholder, it will be put
 * to the query part of the result URI.
 *
 * @return {@code null} if there's no match
 */
public String uri(HttpMethod method, T target, Object... params) {
    MethodlessRouter<T> router = (method == null) ? anyMethodRouter : routers.get(method);

    // Fallback to anyMethodRouter if no router is found for the method
    if (router == null) {
        router = anyMethodRouter;
    }

    String ret = router.uri(target, params);
    if (ret != null) {
        return ret;
    }

    // Fallback to anyMethodRouter if the router was not anyMethodRouter and no path is found
    return (router != anyMethodRouter) ? anyMethodRouter.uri(target, params) : null;
}
项目:azure-documentdb-rxjava    文件:RxGatewayStoreModel.java   
public Observable<DocumentServiceResponse> doQuery(RxDocumentServiceRequest request) {
    request.getHeaders().put(HttpConstants.HttpHeaders.IS_QUERY, "true");

    switch (this.queryCompatibilityMode) {
    case SqlQuery:
        request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE,
                RuntimeConstants.MediaTypes.SQL);
        break;
    case Default:
    case Query:
    default:
        request.getHeaders().put(HttpConstants.HttpHeaders.CONTENT_TYPE,
                RuntimeConstants.MediaTypes.QUERY_JSON);
        break;
    }
    return this.performRequest(request, HttpMethod.POST);
}
项目:tusRx    文件:RxNettyRequestHandlerFactory.java   
@Override
public RequestHandler makeHandler(HttpServerRequest<ByteBuf> request) {
    HttpMethod method = request.getHttpMethod();
    TusRequest tusRequest = new RxNettyTusRequestAdapter(request);
    if (method.equals(HttpMethod.OPTIONS)) {
        return new OptionHandler(options, tusRequest);
    }
    if (method.equals(HttpMethod.POST)) {
        return new PostHandler(options, tusRequest, pool);
    }
    if (method.equals(HttpMethod.HEAD)) {
        return new HeadHandler(options, tusRequest, pool);
    }
    if (method.equals(HttpMethod.PATCH)) {
        return new PatchHandler(options, tusRequest, pool);
    }
    return new NotImplementedHandler();
}
项目:nitmproxy    文件:Http1BackendHandlerTest.java   
@Test
public void shouldHandlerRequestAndResponse() {
    inboundChannel.pipeline().addLast(handler);

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    inboundChannel.write(req);

    assertEquals(1, inboundChannel.outboundMessages().size());

    Object outboundReq = inboundChannel.outboundMessages().poll();
    assertTrue(outboundReq instanceof ByteBuf);
    assertEquals("GET / HTTP/1.1\r\n\r\n", new String(readBytes((ByteBuf) outboundReq)));

    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    assertFalse(inboundChannel.writeInbound(resp));

    assertEquals(1, outboundChannel.outboundMessages().size());
    assertEquals(resp, outboundChannel.outboundMessages().poll());

    resp.release();
}
项目:nitmproxy    文件:Http1BackendHandlerTest.java   
@Test
public void shouldPendingRequests() {
    inboundChannel.pipeline().addLast(handler);

    DefaultFullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    // First request
    inboundChannel.write(req.retain());

    assertEquals(1, inboundChannel.outboundMessages().size());
    assertTrue(inboundChannel.outboundMessages().poll() instanceof ByteBuf);

    // Second request
    inboundChannel.write(req);

    // Should pending second request
    assertTrue(inboundChannel.outboundMessages().isEmpty());
}
项目:hadoop    文件:WebHdfsHandler.java   
public void handle(ChannelHandlerContext ctx, HttpRequest req)
  throws IOException, URISyntaxException {
  String op = params.op();
  HttpMethod method = req.getMethod();
  if (PutOpParam.Op.CREATE.name().equalsIgnoreCase(op)
    && method == PUT) {
    onCreate(ctx);
  } else if (PostOpParam.Op.APPEND.name().equalsIgnoreCase(op)
    && method == POST) {
    onAppend(ctx);
  } else if (GetOpParam.Op.OPEN.name().equalsIgnoreCase(op)
    && method == GET) {
    onOpen(ctx);
  } else if(GetOpParam.Op.GETFILECHECKSUM.name().equalsIgnoreCase(op)
    && method == GET) {
    onGetFileChecksum(ctx);
  } else {
    throw new IllegalArgumentException("Invalid operation " + op);
  }
}
项目:elasticsearch_my    文件:Netty4HttpServerTransportTests.java   
public void testCorsConfig() {
    final Set<String> methods = new HashSet<>(Arrays.asList("get", "options", "post"));
    final Set<String> headers = new HashSet<>(Arrays.asList("Content-Type", "Content-Length"));
    final String prefix = randomBoolean() ? " " : ""; // sometimes have a leading whitespace between comma delimited elements
    final Settings settings = Settings.builder()
                                  .put(SETTING_CORS_ENABLED.getKey(), true)
                                  .put(SETTING_CORS_ALLOW_ORIGIN.getKey(), "*")
                                  .put(SETTING_CORS_ALLOW_METHODS.getKey(), collectionToDelimitedString(methods, ",", prefix, ""))
                                  .put(SETTING_CORS_ALLOW_HEADERS.getKey(), collectionToDelimitedString(headers, ",", prefix, ""))
                                  .put(SETTING_CORS_ALLOW_CREDENTIALS.getKey(), true)
                                  .build();
    final Netty4CorsConfig corsConfig = Netty4HttpServerTransport.buildCorsConfig(settings);
    assertTrue(corsConfig.isAnyOriginSupported());
    assertEquals(headers, corsConfig.allowedRequestHeaders());
    assertEquals(methods, corsConfig.allowedRequestMethods().stream().map(HttpMethod::name).collect(Collectors.toSet()));
}
项目:elasticsearch_my    文件:Netty4HttpChannelTests.java   
public void testReleaseOnSendToClosedChannel() {
    final Settings settings = Settings.builder().build();
    final NamedXContentRegistry registry = xContentRegistry();
    try (Netty4HttpServerTransport httpServerTransport =
                 new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, registry, new NullDispatcher())) {
        final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
        final EmbeddedChannel embeddedChannel = new EmbeddedChannel();
        final Netty4HttpRequest request = new Netty4HttpRequest(registry, httpRequest, embeddedChannel);
        final HttpPipelinedRequest pipelinedRequest = randomBoolean() ? new HttpPipelinedRequest(request.request(), 1) : null;
        final Netty4HttpChannel channel =
                new Netty4HttpChannel(httpServerTransport, request, pipelinedRequest, randomBoolean(), threadPool.getThreadContext());
        final TestResponse response = new TestResponse(bigArrays);
        assertThat(response.content(), instanceOf(Releasable.class));
        embeddedChannel.close();
        channel.sendResponse(response);
        // ESTestCase#after will invoke ensureAllArraysAreReleased which will fail if the response content was not released
    }
}
项目: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);
    }
}
项目:GitHub    文件:NettyHttpClient.java   
private void sendRequest(HttpUrl url) {
  start = System.nanoTime();
  total = 0;
  HttpRequest request = new DefaultFullHttpRequest(
      HttpVersion.HTTP_1_1, HttpMethod.GET, url.encodedPath());
  request.headers().set(HttpHeaders.Names.HOST, url.host());
  request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
  channel.writeAndFlush(request);
}
项目:GitHub    文件:NettyHttpClient.java   
private void sendRequest(HttpUrl url) {
  start = System.nanoTime();
  total = 0;
  HttpRequest request = new DefaultFullHttpRequest(
      HttpVersion.HTTP_1_1, HttpMethod.GET, url.encodedPath());
  request.headers().set(HttpHeaders.Names.HOST, url.host());
  request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
  channel.writeAndFlush(request);
}
项目:HFSN    文件:HttpFileServerHandler.java   
private boolean ifConnectSuccess(ChannelHandlerContext ctx, FullHttpRequest request) {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return false;
    }
    if (request.method() != HttpMethod.GET) {
        sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return false;
    }
    return true;
}
项目:redant    文件:Router.java   
private MethodlessRouter<T> getMethodlessRouter(HttpMethod method) {
    if (method == null) {
        return anyMethodRouter;
    }

    MethodlessRouter<T> r = routers.get(method);
    if (r == null) {
        r = new MethodlessRouter<T>();
        routers.put(method, r);
    }

    return r;
}
项目:siddhi-io-http    文件:HttpSink.java   
public HTTPCarbonMessage createHttpCarbonMessage(String method) {
    HTTPCarbonMessage httpCarbonMessage = null;
    switch (method) {
        case "GET": {
            httpCarbonMessage = new HTTPCarbonMessage(
                    new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""));
            break;
        }
        case "PUT": {
            httpCarbonMessage = new HTTPCarbonMessage(
                    new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, ""));
            break;
        }
        case "PATCH": {
            httpCarbonMessage = new HTTPCarbonMessage(
                    new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PATCH, ""));
            break;
        }
        case "DELETE": {
            httpCarbonMessage = new HTTPCarbonMessage(
                    new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, ""));
            break;
        }
        case "POST": {
            httpCarbonMessage = new HTTPCarbonMessage(
                    new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, ""));
            break;
        }
        default: {
            log.error("Invalid request type.");

            break;
        }
    }
    return httpCarbonMessage;
}
项目:qonduit    文件:HttpRequestDecoderTest.java   
/**
 * Only /login requests are handled
 */
@Test(expected = QonduitException.class)
public void testVersionGet() throws Exception {
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/version");
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals("VersionRequest", results.iterator().next().getClass().getSimpleName());
}
项目:Ink    文件:RouteSetter.java   
public static void routeSetter(Route route, FullHttpRequest fullHttpRequest) throws Exception {
    String path = fullHttpRequest.uri();
    HttpMethod method = fullHttpRequest.method();


    if (route.security()) {
        CheckResult checkResult = SecurityManager.check(route);
        if (!checkResult.isOk()) {
            throw checkResult.exception();
        }
    }

    //设置@PathVariable
    routePathVariableSetter(path, route);

    if (route.httpMethod().equals(HttpMethod.GET)) {
        //设置GET @RequestParam
        GETParamsSetter(path, route);
    } else if (route.httpMethod().equals(HttpMethod.POST)) {
        //设置POST @RequestParam
        POSTParamsSetter(fullHttpRequest, route);
    }

    //设置@RequestJson
    if ("application/json".equals(fullHttpRequest.headers().get("content-Type"))) {
        routeRequestJsonSetter(fullHttpRequest.content().copy().toString(CharsetUtil.UTF_8), route);
    }

    //设置@FILE
    if (fullHttpRequest.headers().get("content-Type") != null && fullHttpRequest.headers().get("content-Type").startsWith("multipart/form-data")) {
        fileSetter(fullHttpRequest, route);
    }

    //设置model
    modelSetter(fullHttpRequest, route);

}
项目:siddhi-io-http    文件:ServerUtil.java   
static HttpURLConnection request(URI baseURI, String path, String method, boolean keepAlive)
        throws IOException {
    URL url = baseURI.resolve(path).toURL();
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    if (method.equals(HttpMethod.POST.name()) || method.equals(HttpMethod.PUT.name())) {
        urlConn.setDoOutput(true);
    }
    urlConn.setRequestMethod(method);
    if (!keepAlive) {
        urlConn.setRequestProperty("Connection", "Keep-Alive");
    }
    return urlConn;
}
项目:siddhi-io-http    文件:HttpIoUtil.java   
/**
 * Create new HTTP carbon messge.
 *
 * @param isRequest
 * @return
 */
private static HTTPCarbonMessage createHttpCarbonMessage(boolean isRequest) {
    HTTPCarbonMessage httpCarbonMessage;
    if (isRequest) {
        httpCarbonMessage = new HTTPCarbonMessage(
                new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""));
        httpCarbonMessage.setEndOfMsgAdded(true);
    } else {
        httpCarbonMessage = new HTTPCarbonMessage(
                new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK));
        httpCarbonMessage.setEndOfMsgAdded(true);
    }
    return httpCarbonMessage;
}
项目:siddhi-io-http    文件:HttpServerUtil.java   
static HttpURLConnection request(URI baseURI, String path, String method)
        throws IOException {
    URL url = baseURI.resolve(path).toURL();
    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
    if (method.equals(HttpMethod.POST.name()) || method.equals(HttpMethod.PUT.name())) {
        urlConn.setDoOutput(true);
    }
    urlConn.setRequestMethod(method);
    urlConn.setRequestProperty("Connection", "Keep-Alive");
    return urlConn;
}
项目:azure-documentdb-rxjava    文件:RxGatewayStoreModel.java   
/**
 * Given the request it creates an observable which upon subscription issues HTTP call and emits one DocumentServiceResponse.
 * 
 * @param request 
 * @param method
 * @return Observable<DocumentServiceResponse> 
 */
public Observable<DocumentServiceResponse> performRequest(RxDocumentServiceRequest request, HttpMethod method) {

    URI uri = getUri(request);

    HttpClientRequest<ByteBuf> httpRequest = HttpClientRequest.create(method, uri.toString());

    this.fillHttpRequestBaseWithHeaders(request.getHeaders(), httpRequest);
    try {

        if (request.getContentObservable() != null) {

            // TODO validate this
            // convert byte[] to ByteBuf
            // why not use Observable<byte[]> directly?
            Observable<ByteBuf> byteBufObservable = request.getContentObservable()
                    .map(bytes ->  Unpooled.wrappedBuffer(bytes));

            httpRequest.withContentSource(byteBufObservable);
        } else if (request.getContent() != null){
            httpRequest.withContent(request.getContent());
        }

    } catch (Exception e) {
        return Observable.error(e);
    }

    Observable<HttpClientResponse<ByteBuf>> clientResponseObservable = this.httpClient.submit(httpRequest);

    return toDocumentServiceResponse(clientResponseObservable, request);
}
项目:xrpc    文件:Router.java   
public void serveAdmin() {
  MetricsModule metricsModule = new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true);
  ObjectMapper metricsMapper = new ObjectMapper().registerModule(metricsModule);
  ObjectMapper healthMapper = new ObjectMapper();

  /*
  '/info' -> should expose version number, git commit number, etc
  '/metrics' -> should return the metrics reporters in JSON format
  '/health' -> should expose a summary of downstream health checks
  '/ping' -> should respond with a 200-OK status code and the text 'PONG'
  '/ready' -> should expose a Kubernetes or ELB specific healthcheck for liveliness
  '/restart' -> restart service (should be restricted to approved devs / tooling)
   '/killkillkill' -> shutdown service (should be restricted to approved devs / tooling)

*/

addRoute("/info", AdminHandlers.infoHandler(), HttpMethod.GET); addRoute( "/metrics", AdminHandlers.metricsHandler(metricRegistry, metricsMapper), HttpMethod.GET); addRoute( "/health", AdminHandlers.healthCheckHandler(healthCheckRegistry, healthMapper), HttpMethod.GET); addRoute("/ping", AdminHandlers.pingHandler(), HttpMethod.GET); addRoute("/ready", AdminHandlers.readyHandler(), HttpMethod.GET); addRoute("/restart", AdminHandlers.restartHandler(this), HttpMethod.GET); addRoute("/killkillkill", AdminHandlers.killHandler(this), HttpMethod.GET);

addRoute("/gc", AdminHandlers.pingHandler(), HttpMethod.GET); }

```

项目:xrpc    文件:Recipes.java   
public static FullHttpRequest newFullRequest(
    HttpMethod method, String urlPath, ByteBuf payload, ContentType contentType) {
  FullHttpRequest request =
      new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, urlPath, payload);
  request.headers().set(CONTENT_TYPE, contentType.value);
  request.headers().setInt(CONTENT_LENGTH, payload.readableBytes());
  return request;
}
项目:aws-sdk-java-v2    文件:RequestAdapter.java   
public HttpRequest adapt(SdkHttpRequest sdkRequest) {
    String uri = sdkRequest.getUri().toString();
    HttpMethod method = toNettyHttpMethod(sdkRequest.method());
    HttpHeaders headers = new DefaultHttpHeaders();
    DefaultHttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri, headers);
    sdkRequest.headers().forEach(request.headers()::add);
    return request;
}
项目:tusRx    文件:RxNettyRequestHandlerFactoryTest.java   
@Test
public void testOptionsRequestMakesOptionsHandler() {
    // arrange
    when(request.getHttpMethod()).thenReturn(HttpMethod.OPTIONS);

    //act
    RequestHandler handler = factory.makeHandler(request);

    // assert
    assertThat(handler).isInstanceOf(OptionHandler.class);
}
项目:tusRx    文件:RxNettyRequestHandlerFactoryTest.java   
@Test
public void testPostRequestMakesPostHandler() {
    // arrange
    when(request.getHttpMethod()).thenReturn(HttpMethod.POST);

    //act
    RequestHandler handler = factory.makeHandler(request);

    // assert
    assertThat(handler).isInstanceOf(PostHandler.class);
}
项目:tusRx    文件:RxNettyRequestHandlerFactoryTest.java   
@Test
public void testPatchRequestMakesPatchHandler() {
    // arrange
    when(request.getHttpMethod()).thenReturn(HttpMethod.PATCH);

    //act
    RequestHandler handler = factory.makeHandler(request);

    // assert
    assertThat(handler).isInstanceOf(PatchHandler.class);
}
项目:tusRx    文件:RxNettyRequestHandlerFactoryTest.java   
@Test
public void testHeadRequestMakesHeadHandler() {
    // arrange
    when(request.getHttpMethod()).thenReturn(HttpMethod.HEAD);

    //act
    RequestHandler handler = factory.makeHandler(request);

    // assert
    assertThat(handler).isInstanceOf(HeadHandler.class);
}
项目:tusRx    文件:RxNettyRequestHandlerFactoryTest.java   
@Test
public void testBogusRequestMakesNotImplementedHandler() {
    // arrange
    when(request.getHttpMethod()).thenReturn(new HttpMethod("FOO"));

    //act
    RequestHandler handler = factory.makeHandler(request);

    // assert
    assertThat(handler).isInstanceOf(NotImplementedHandler.class);
}
项目:qonduit    文件:HttpRequestDecoderTest.java   
/**
 * Only /login requests are handled
 */
@Test(expected = QonduitException.class)
public void testVersionPost() throws Exception {
    decoder = new TestHttpQueryDecoder(config);
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/version");
    addCookie(request);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals("VersionRequest", results.iterator().next().getClass().getSimpleName());
}
项目:elasticsearch_my    文件:Netty4HttpServerTransport.java   
static Netty4CorsConfig buildCorsConfig(Settings settings) {
    if (SETTING_CORS_ENABLED.get(settings) == false) {
        return Netty4CorsConfigBuilder.forOrigins().disable().build();
    }
    String origin = SETTING_CORS_ALLOW_ORIGIN.get(settings);
    final Netty4CorsConfigBuilder builder;
    if (Strings.isNullOrEmpty(origin)) {
        builder = Netty4CorsConfigBuilder.forOrigins();
    } else if (origin.equals(ANY_ORIGIN)) {
        builder = Netty4CorsConfigBuilder.forAnyOrigin();
    } else {
        Pattern p = RestUtils.checkCorsSettingForRegex(origin);
        if (p == null) {
            builder = Netty4CorsConfigBuilder.forOrigins(RestUtils.corsSettingAsArray(origin));
        } else {
            builder = Netty4CorsConfigBuilder.forPattern(p);
        }
    }
    if (SETTING_CORS_ALLOW_CREDENTIALS.get(settings)) {
        builder.allowCredentials();
    }
    String[] strMethods = Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_METHODS.get(settings), ",");
    HttpMethod[] methods = Arrays.asList(strMethods)
        .stream()
        .map(HttpMethod::valueOf)
        .toArray(size -> new HttpMethod[size]);
    return builder.allowedRequestMethods(methods)
        .maxAge(SETTING_CORS_MAX_AGE.get(settings))
        .allowedRequestHeaders(Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_HEADERS.get(settings), ","))
        .shortCircuit()
        .build();
}
项目:elasticsearch_my    文件:Netty4HttpServerTransportTests.java   
public void testCorsConfigWithDefaults() {
    final Set<String> methods = Strings.commaDelimitedListToSet(SETTING_CORS_ALLOW_METHODS.getDefault(Settings.EMPTY));
    final Set<String> headers = Strings.commaDelimitedListToSet(SETTING_CORS_ALLOW_HEADERS.getDefault(Settings.EMPTY));
    final long maxAge = SETTING_CORS_MAX_AGE.getDefault(Settings.EMPTY);
    final Settings settings = Settings.builder().put(SETTING_CORS_ENABLED.getKey(), true).build();
    final Netty4CorsConfig corsConfig = Netty4HttpServerTransport.buildCorsConfig(settings);
    assertFalse(corsConfig.isAnyOriginSupported());
    assertEquals(Collections.emptySet(), corsConfig.origins().get());
    assertEquals(headers, corsConfig.allowedRequestHeaders());
    assertEquals(methods, corsConfig.allowedRequestMethods().stream().map(HttpMethod::name).collect(Collectors.toSet()));
    assertEquals(maxAge, corsConfig.maxAge());
    assertFalse(corsConfig.isCredentialsAllowed());
}
项目:qonduit    文件:BasicAuthLoginRequestHandlerTest.java   
@Test
public void testBasicAuthentication() throws Exception {
    Configuration config = TestConfiguration.createMinimalConfigurationForTest();

    BasicAuthLogin auth = new BasicAuthLogin();
    auth.setUsername("test");
    auth.setPassword("test1");
    DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/login");
    request.content().writeBytes(JsonSerializer.getObjectMapper().writeValueAsBytes(auth));

    TestHttpQueryDecoder decoder = new TestHttpQueryDecoder(config);
    decoder.decode(null, request, results);
    Assert.assertEquals(1, results.size());
    Object result = results.iterator().next();
    Assert.assertEquals(BasicAuthLoginRequest.class, result.getClass());

    BasicAuthLoginRequestHandler handler = new BasicAuthLoginRequestHandler(config);
    CaptureChannelHandlerContext ctx = new CaptureChannelHandlerContext();
    handler.channelRead(ctx, result);
    Assert.assertNotNull(ctx.msg);
    Assert.assertTrue(ctx.msg instanceof DefaultFullHttpResponse);
    DefaultFullHttpResponse response = (DefaultFullHttpResponse) ctx.msg;
    Assert.assertEquals(HttpResponseStatus.OK, response.getStatus());
    Assert.assertTrue(response.headers().contains(Names.CONTENT_TYPE));
    Assert.assertEquals(Constants.JSON_TYPE, response.headers().get(Names.CONTENT_TYPE));
    Assert.assertTrue(response.headers().contains(Names.SET_COOKIE));
    Cookie c = ClientCookieDecoder.STRICT.decode(response.headers().get(Names.SET_COOKIE));
    Assert.assertEquals(TestConfiguration.HTTP_ADDRESS_DEFAULT, c.domain());
    Assert.assertEquals(86400, c.maxAge());
    Assert.assertTrue(c.isHttpOnly());
    Assert.assertTrue(c.isSecure());
    Assert.assertEquals(Constants.COOKIE_NAME, c.name());
    UUID.fromString(c.value());
}
项目:elasticsearch_my    文件:Netty4HttpChannelTests.java   
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()));
    }
}
项目:elasticsearch_my    文件:Netty4HttpClient.java   
private Collection<FullHttpResponse> processRequestsWithBody(HttpMethod method, SocketAddress remoteAddress, Tuple<String,
    CharSequence>... urisAndBodies) throws InterruptedException {
    Collection<HttpRequest> requests = new ArrayList<>(urisAndBodies.length);
    for (Tuple<String, CharSequence> uriAndBody : urisAndBodies) {
        ByteBuf content = Unpooled.copiedBuffer(uriAndBody.v2(), StandardCharsets.UTF_8);
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, method, uriAndBody.v1(), content);
        request.headers().add(HttpHeaderNames.HOST, "localhost");
        request.headers().add(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
        request.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/json");
        requests.add(request);
    }
    return sendRequests(remoteAddress, requests);
}
项目:onedatashare    文件:HTTPBuilder.java   
/**
 * Prepares request message to be sent.
 * 
 * @param path specific file path under this host
 * @return Message to be sent
 */
protected HttpRequest prepareRequest(String method, String path) {
  HttpRequest request = new DefaultFullHttpRequest( 
      HttpVersion.HTTP_1_1, HttpMethod.valueOf(method), path);
  request.headers().set(HttpHeaders.Names.HOST, this.uri.host());
  request.headers().set(HttpHeaders.Names.USER_AGENT, "Stork");

  return request;
}
项目:qonduit    文件:Server.java   
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {

        return new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {

                ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config, sslCtx));
                ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                ch.pipeline().addLast("compressor", new HttpContentCompressor());
                ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
                ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
                final Configuration.Cors corsCfg = config.getHttp().getCors();
                final CorsConfig.Builder ccb;
                if (corsCfg.isAllowAnyOrigin()) {
                    ccb = new CorsConfig.Builder();
                } else {
                    ccb = new CorsConfig.Builder(corsCfg.getAllowedOrigins().stream().toArray(String[]::new));
                }
                if (corsCfg.isAllowNullOrigin()) {
                    ccb.allowNullOrigin();
                }
                if (corsCfg.isAllowCredentials()) {
                    ccb.allowCredentials();
                }
                corsCfg.getAllowedMethods().stream().map(HttpMethod::valueOf).forEach(ccb::allowedRequestMethods);
                corsCfg.getAllowedHeaders().forEach(ccb::allowedRequestHeaders);
                CorsConfig cors = ccb.build();
                LOG.trace("Cors configuration: {}", cors);
                ch.pipeline().addLast("cors", new CorsHandler(cors));
                ch.pipeline().addLast("queryDecoder", new qonduit.netty.http.HttpRequestDecoder(config));
                ch.pipeline().addLast("strict", new StrictTransportHandler(config));
                ch.pipeline().addLast("login", new X509LoginRequestHandler(config));
                ch.pipeline().addLast("doLogin", new BasicAuthLoginRequestHandler(config));
                ch.pipeline().addLast("error", new HttpExceptionHandler());
            }
        };
    }
项目:util4j    文件:NettyHttpClient.java   
public static void main(String[] args) {
        NettyHttpClient client=new NettyHttpClient();
        long time=System.currentTimeMillis();
        HttpRequest request=new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/baidu?tn=monline_6_dg&ie=utf-8&wd=netty+http客户端");
        HttpResponse response=client.syncRequest("www.baidu.com", 80, request);
        System.out.println(System.currentTimeMillis()-time);
        System.out.println(response);
        FullHttpResponse rsp=(FullHttpResponse) response;
        System.out.println("content:"+rsp.content().toString(CharsetUtil.UTF_8));
//      new Scanner(System.in).nextLine();
    }