io.netty.handler.codec.http.HttpHeaderNames Java Examples

The following examples show how to use io.netty.handler.codec.http.HttpHeaderNames. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProxyTunnelInitHandlerTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void handledAdded_writesRequest() {
    Promise<Channel> promise = GROUP.next().newPromise();
    ProxyTunnelInitHandler handler = new ProxyTunnelInitHandler(mockChannelPool, REMOTE_HOST, promise);
    handler.handlerAdded(mockCtx);

    ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
    verify(mockChannel).writeAndFlush(requestCaptor.capture());

    String uri = REMOTE_HOST.getHost() + ":" + REMOTE_HOST.getPort();
    HttpRequest expectedRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.CONNECT, uri,
                                                             Unpooled.EMPTY_BUFFER, false);
    expectedRequest.headers().add(HttpHeaderNames.HOST, uri);

    assertThat(requestCaptor.getValue()).isEqualTo(expectedRequest);
}
 
Example #2
Source File: ThrottlingTestCase.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
@Test(description = "test throttling with non exist subscription policy")
public void testThrottlingWithNonExistSubscriptionPolicy() throws Exception {
    Map<String, String> headers = new HashMap<>();
    headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + noSubPolicyJWT);
    org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
            .doGet(getServiceURLHttp("/pizzashack/1.0.0/menu"), headers);
    Assert.assertNotNull(response);
    Assert.assertEquals(response.getResponseCode(), 500, "Request should not successful with JWT.");
    Assert.assertTrue(response.getData().contains("\"code\":900809"),
            "Error response should have errorcode 900809 in JWT.");

    headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + noSubPolicyToken);
    response = HttpClientRequest.doGet(getServiceURLHttp("/pizzashack/1.0.0/menu"), headers);
    Assert.assertNotNull(response);
    Assert.assertEquals(response.getResponseCode(), 500, "Request should not successful with oauth.");
    Assert.assertTrue(response.getData().contains("\"code\":900809"),
            "Error response should have errorcode 900809 in oauth.");
}
 
Example #3
Source File: PublicAccessLogHandlerTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies either the expected request headers are found or not found (based on the parameter passed) in the
 * public access log entry
 * @param logEntry the public access log entry
 * @param headers expected headers
 * @param httpMethod HttpMethod type
 * @param expected, true if the headers are expected, false otherwise
 */
private void verifyPublicAccessLogEntryForRequestHeaders(String logEntry, HttpHeaders headers, HttpMethod httpMethod,
    boolean expected) {
  Iterator<Map.Entry<String, String>> itr = headers.iteratorAsString();
  while (itr.hasNext()) {
    Map.Entry<String, String> entry = itr.next();
    if (!entry.getKey().startsWith(NOT_LOGGED_HEADER_KEY) && !entry.getKey()
        .startsWith(EchoMethodHandler.RESPONSE_HEADER_KEY_PREFIX)) {
      if (httpMethod == HttpMethod.GET && !entry.getKey().equalsIgnoreCase(HttpHeaderNames.CONTENT_TYPE.toString())) {
        String subString = "[" + entry.getKey() + "=" + entry.getValue() + "]";
        boolean actual = logEntry.contains(subString);
        if (expected) {
          Assert.assertTrue("Public Access log entry does not have expected header " + entry.getKey(), actual);
        } else {
          Assert.assertFalse("Public Access log entry has unexpected header " + entry.getKey(), actual);
        }
      }
    }
  }
}
 
Example #4
Source File: HttpProxyHandler.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
protected Object newInitialMessage(ChannelHandlerContext ctx) throws Exception {
    InetSocketAddress raddr = destinationAddress();
    final String host = NetUtil.toSocketAddressString(raddr);
    FullHttpRequest req = new DefaultFullHttpRequest(
            HttpVersion.HTTP_1_1, HttpMethod.CONNECT,
            host,
            Unpooled.EMPTY_BUFFER, false);

    req.headers().set(HttpHeaderNames.HOST, host);

    if (authorization != null) {
        req.headers().set(HttpHeaderNames.PROXY_AUTHORIZATION, authorization);
    }

    if (headers != null) {
        req.headers().add(headers);
    }

    return req;
}
 
Example #5
Source File: HttpPostMultipartRequestDecoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param factory
 *            the factory used to create InterfaceHttpData
 * @param request
 *            the request to decode
 * @param charset
 *            the charset to use as default
 * @throws NullPointerException
 *             for request or charset or factory
 * @throws ErrorDataDecoderException
 *             if the default charset was wrong when decoding or other
 *             errors
 */
public HttpPostMultipartRequestDecoder(HttpDataFactory factory, HttpRequest request, Charset charset) {
    this.request = checkNotNull(request, "request");
    this.charset = checkNotNull(charset, "charset");
    this.factory = checkNotNull(factory, "factory");
    // Fill default values

    setMultipart(this.request.headers().get(HttpHeaderNames.CONTENT_TYPE));
    if (request instanceof HttpContent) {
        // Offer automatically if the given request is als type of HttpContent
        // See #1089
        offer((HttpContent) request);
    } else {
        undecodedChunk = buffer();
        parseBody();
    }
}
 
Example #6
Source File: DiscordWebClient.java    From Discord4J with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Create a new {@link DiscordWebClient} wrapping HTTP, Discord and encoding/decoding resources.
 *
 * @param httpClient a Reactor Netty HTTP client
 * @param exchangeStrategies a strategy to transform requests and responses
 * @param authorizationScheme scheme to use with the authorization header, like "Bot" or "Bearer"
 * @param token a Discord token for API authorization
 * @param responseFunctions a list of {@link ResponseFunction} transformations
 */
public DiscordWebClient(HttpClient httpClient, ExchangeStrategies exchangeStrategies,
                        String authorizationScheme, String token,
                        List<ResponseFunction> responseFunctions) {
    final Properties properties = GitProperties.getProperties();
    final String version = properties.getProperty(GitProperties.APPLICATION_VERSION, "3");
    final String url = properties.getProperty(GitProperties.APPLICATION_URL, "https://discord4j.com");

    final HttpHeaders defaultHeaders = new DefaultHttpHeaders();
    defaultHeaders.add(HttpHeaderNames.CONTENT_TYPE, "application/json");
    defaultHeaders.add(HttpHeaderNames.AUTHORIZATION, authorizationScheme + " " + token);
    defaultHeaders.add(HttpHeaderNames.USER_AGENT, "DiscordBot(" + url + ", " + version + ")");
    defaultHeaders.add("X-RateLimit-Precision", "millisecond");

    this.httpClient = httpClient;
    this.defaultHeaders = defaultHeaders;
    this.exchangeStrategies = exchangeStrategies;
    this.responseFunctions = responseFunctions;
}
 
Example #7
Source File: NettyUtils.java    From gae with MIT License 6 votes vote down vote up
public static FullHttpResponse buildResponse(BidResponse bidResponse) {
    String respJson = JSON.toJSONString(bidResponse, jsonSnakeConfig);
    // byte[] buf = JSON.toJSONBytes(bidResponse, jsonSnakeConfig);

    FullHttpResponse response = new DefaultFullHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.OK,
            Unpooled.wrappedBuffer(respJson.getBytes())
    );

    response.headers().set(
            HttpHeaderNames.CONTENT_TYPE.toString(),
            "application/json;charset=utf8"
    );

    log.info("gae_response\t{}", respJson);

    return response;
}
 
Example #8
Source File: JWTGenerationTestCase.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
@Test(description = "Test JWT Generator token cache and the properties")
public void testResponseJWTGenerationToken() throws Exception {
    Map<String, String> headers = new HashMap<>();
    //test endpoint with token
    headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + jwtTokenProd);
    org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
            .doGet(getServiceURLHttp("petstore/v2/jwttoken"), headers);
    Assert.assertNotNull(response);
    Assert.assertEquals(response.getResponseCode(), 200, "Response code mismatched");

    JSONObject responseJSON = new JSONObject(response.getData());
    String tokenFull = responseJSON.get("token").toString();
    String strTokenBody = tokenFull.split("\\.")[1];
    String decodedTokenBody = new String(Base64.getUrlDecoder().decode(strTokenBody));
    JSONObject tokenBody = new JSONObject(decodedTokenBody);

    Assert.assertEquals(tokenBody.get("iss"), JWT_GENERATOR_ISSUER,
            "JWT generator issuer not set correctly");
    Assert.assertEquals(tokenBody.get("aud"), JWT_GENERATOR_AUDIENCE,
            "JWT generator audience not set correctly");
    Assert.assertTrue(tokenBody.keySet().contains("claim1"), "JWT generator custom claims not set correctly");
    Assert.assertFalse(tokenBody.keySet().contains("claim2"), "JWT generator restricted claims not removed");
}
 
Example #9
Source File: HttpClientWithTomcatTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void disableChunkForced() {
	AtomicReference<HttpHeaders> headers = new AtomicReference<>();
	Tuple2<HttpResponseStatus, String> r =
			HttpClient.newConnection()
			          .host("localhost")
			          .port(getPort())
			          .headers(h -> h.set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED))
			          .wiretap(true)
			          .doAfterRequest((req, connection) -> headers.set(req.requestHeaders()))
			          .request(HttpMethod.GET)
			          .uri("/status/400")
			          .send(ByteBufFlux.fromString(Flux.just("hello")))
			          .responseSingle((res, conn) -> Mono.just(res.status())
			                                             .zipWith(conn.asString()))
			          .block(Duration.ofSeconds(30));

	assertThat(r).isNotNull();

	assertThat(r.getT1()).isEqualTo(HttpResponseStatus.BAD_REQUEST);
	assertThat(headers.get().get("Content-Length")).isEqualTo("5");
	assertThat(headers.get().get("Transfer-Encoding")).isNull();
}
 
Example #10
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testPredictions(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/noop");
    req.content().writeCharSequence("data=test", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers()
            .set(
                    HttpHeaderNames.CONTENT_TYPE,
                    HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    channel.writeAndFlush(req);

    latch.await();
    Assert.assertEquals(result, "OK");
}
 
Example #11
Source File: HttpUploadHandlerTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void uploadsShouldWork(boolean casUpload, EmbeddedChannel ch, HttpResponseStatus status)
    throws Exception {
  ByteArrayInputStream data = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5});
  ChannelPromise writePromise = ch.newPromise();
  ch.writeOneOutbound(new UploadCommand(CACHE_URI, casUpload, "abcdef", data, 5), writePromise);

  HttpRequest request = ch.readOutbound();
  assertThat(request.method()).isEqualTo(HttpMethod.PUT);
  assertThat(request.headers().get(HttpHeaders.CONNECTION))
      .isEqualTo(HttpHeaderValues.KEEP_ALIVE.toString());

  HttpChunkedInput content = ch.readOutbound();
  assertThat(content.readChunk(ByteBufAllocator.DEFAULT).content().readableBytes()).isEqualTo(5);

  FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
  response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

  ch.writeInbound(response);

  assertThat(writePromise.isDone()).isTrue();
  assertThat(ch.isOpen()).isTrue();
}
 
Example #12
Source File: WebsocketClientOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
WebsocketClientOperations(URI currentURI,
		WebsocketClientSpec websocketClientSpec,
		HttpClientOperations replaced) {
	super(replaced);
	this.proxyPing = websocketClientSpec.handlePing();
	Channel channel = channel();
	onCloseState = MonoProcessor.create();

	String subprotocols = websocketClientSpec.protocols();
	handshaker = WebSocketClientHandshakerFactory.newHandshaker(currentURI,
				WebSocketVersion.V13,
				subprotocols != null && !subprotocols.isEmpty() ? subprotocols : null,
				true,
				replaced.requestHeaders()
				        .remove(HttpHeaderNames.HOST),
				websocketClientSpec.maxFramePayloadLength());

	handshaker.handshake(channel)
	          .addListener(f -> {
		          markPersistent(false);
		          channel.read();
	          });
}
 
Example #13
Source File: HystrixDashboardProxyEurekaTest.java    From standalone-hystrix-dashboard with MIT License 6 votes vote down vote up
@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);
}
 
Example #14
Source File: BrpcHttpResponseEncoder.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean isContentAlwaysEmpty(HttpResponse msg) {
    // Correctly handle special cases as stated in:
    // https://tools.ietf.org/html/rfc7230#section-3.3.3
    HttpResponseStatus status = msg.status();

    if (status.codeClass() == HttpStatusClass.INFORMATIONAL) {

        if (status.code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code()) {
            // We need special handling for WebSockets version 00 as it will include an body.
            // Fortunally this version should not really be used in the wild very often.
            // See https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00#section-1.2
            return msg.headers().contains(HttpHeaderNames.SEC_WEBSOCKET_VERSION);
        }
        return true;
    }
    return status.code() == HttpResponseStatus.NO_CONTENT.code()
            || status.code() == HttpResponseStatus.NOT_MODIFIED.code()
            || status.code() == HttpResponseStatus.RESET_CONTENT.code();
}
 
Example #15
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserAgent() {
	disposableServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, resp) -> {
			                  Assert.assertTrue("" + req.requestHeaders()
			                                            .get(HttpHeaderNames.USER_AGENT),
			                                   req.requestHeaders()
			                                       .contains(HttpHeaderNames.USER_AGENT) &&
			                                   req.requestHeaders()
			                                      .get(HttpHeaderNames.USER_AGENT)
			                                      .equals(HttpClient.USER_AGENT));

			                  return req.receive().then();
			          })
			          .wiretap(true)
			          .bindNow();

	createHttpClientForContextWithPort()
	        .get()
	        .uri("/")
	        .responseContent()
	        .blockLast();
}
 
Example #16
Source File: ModelServerTest.java    From serve with Apache License 2.0 6 votes vote down vote up
private void testPredictions(String modelName, String expectedOutput, String version)
        throws InterruptedException {
    Channel channel = TestUtils.getInferenceChannel(configManager);
    TestUtils.setResult(null);
    TestUtils.setLatch(new CountDownLatch(1));
    String requestURL = "/predictions/" + modelName;
    if (version != null) {
        requestURL += "/" + version;
    }
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestURL);
    req.content().writeCharSequence("data=test", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers()
            .set(
                    HttpHeaderNames.CONTENT_TYPE,
                    HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED);
    channel.writeAndFlush(req);

    TestUtils.getLatch().await();
    Assert.assertEquals(TestUtils.getResult(), expectedOutput);
}
 
Example #17
Source File: ModelServerTest.java    From multi-model-server with Apache License 2.0 6 votes vote down vote up
private void testPredictionsNoManifest(Channel inferChannel, Channel mgmtChannel)
        throws InterruptedException, NoSuchFieldException, IllegalAccessException {
    setConfiguration("default_service_handler", "service:handle");
    loadTests(mgmtChannel, "noop-no-manifest", "nomanifest");

    result = null;
    latch = new CountDownLatch(1);
    DefaultFullHttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1, HttpMethod.POST, "/predictions/nomanifest");
    req.content().writeCharSequence("{\"data\": \"test\"}", CharsetUtil.UTF_8);
    HttpUtil.setContentLength(req, req.content().readableBytes());
    req.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
    inferChannel.writeAndFlush(req);

    latch.await();

    Assert.assertEquals(httpStatus, HttpResponseStatus.OK);
    Assert.assertEquals(result, "OK");
    unloadTests(mgmtChannel, "nomanifest");
}
 
Example #18
Source File: TrackerService.java    From twill with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #19
Source File: WebSocketIndexPageHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
    String protocol = "ws";
    if (cp.get(SslHandler.class) != null) {
        // SSL in use so use Secure WebSockets
        protocol = "wss";
    }
    return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
}
 
Example #20
Source File: IpCameraHandler.java    From IpCamera with Eclipse Public License 2.0 5 votes vote down vote up
public void hikChangeSetting(String httpGetPutURL, String findOldValue, String newValue) {
    String body;
    byte indexInLists;
    lock.lock();
    try {
        indexInLists = (byte) listOfRequests.indexOf(httpGetPutURL);
    } finally {
        lock.unlock();
    }
    if (indexInLists >= 0) {
        lock.lock();
        if (listOfReplies.get(indexInLists) != "") {
            body = listOfReplies.get(indexInLists);
            lock.unlock();
            logger.debug("An OLD reply from the camera was:{}", body);
            body = body.replace(findOldValue, newValue);
            logger.debug("Body for this PUT is going to be:{}", body);
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, new HttpMethod("PUT"),
                    httpGetPutURL);
            request.headers().set(HttpHeaderNames.HOST, ipAddress);
            request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            request.headers().add(HttpHeaderNames.CONTENT_TYPE, "application/xml; charset=\"UTF-8\"");
            ByteBuf bbuf = Unpooled.copiedBuffer(body, StandardCharsets.UTF_8);
            request.headers().set(HttpHeaderNames.CONTENT_LENGTH, bbuf.readableBytes());
            request.content().clear().writeBytes(bbuf);
            sendHttpPUT(httpGetPutURL, request);
        } else {
            lock.unlock();
        }
    } else {
        sendHttpGET(httpGetPutURL);
        logger.warn(
                "Did not have a reply stored before hikChangeSetting was run, try again shortly as a reply has just been requested.");
    }
}
 
Example #21
Source File: EndpointWithSecurityTestCase.java    From product-microgateway with Apache License 2.0 5 votes vote down vote up
@Test(description = "Test Invoking the resource which endpoint defined at API level using references")
public void testPerAPISecureEndpoint() throws Exception {
    Map<String, String> headers = new HashMap<>();
    //test endpoint with token
    headers.put(HttpHeaderNames.AUTHORIZATION.toString(), "Bearer " + jwtTokenProd);
    org.wso2.micro.gateway.tests.util.HttpResponse response = HttpClientRequest
            .doGet(getServiceURLHttp("petstore/v5/pet/1"), headers);
    Assert.assertNotNull(response);
    Assert.assertEquals(response.getData(), ResponseConstants.petByIdResponse);
    Assert.assertEquals(response.getResponseCode(), 200, "Response code mismatched");
}
 
Example #22
Source File: FrontendIntegrationTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
private void verifyUndeleteBlobResponse(ResponseParts responseParts) {
  HttpResponse response = getHttpResponse(responseParts);
  assertEquals("Unexpected response status", HttpResponseStatus.OK, response.status());
  assertTrue("No Date header", response.headers().getTimeMillis(HttpHeaderNames.DATE, -1) != -1);
  assertEquals("Content-Length is not 0", 0, HttpUtil.getContentLength(response));
  assertNoContent(responseParts.queue, 1);
  assertTrue("Channel should be active", HttpUtil.isKeepAlive(response));
  verifyTrackingHeaders(response);
}
 
Example #23
Source File: BridgeHeaders.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static String getContentType(FullHttpRequest req) {
   String contentType = req.headers().get(HttpHeaderNames.CONTENT_TYPE);
   if(contentType == null) {
      return "";
   }
   int semi = contentType.indexOf(';');
   if(semi > 0) {
      return contentType.substring(0, semi);
   }
   else {
      return contentType;
   }
}
 
Example #24
Source File: HttpUploadHandler.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private HttpRequest buildRequest(UploadCommand msg) {
  HttpRequest request =
      new DefaultHttpRequest(
          HttpVersion.HTTP_1_1,
          HttpMethod.PUT,
          constructPath(msg.uri(), msg.hash(), msg.casUpload()));
  request.headers().set(HttpHeaderNames.HOST, constructHost(msg.uri()));
  request.headers().set(HttpHeaderNames.ACCEPT, "*/*");
  request.headers().set(HttpHeaderNames.CONTENT_LENGTH, msg.contentLength());
  request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
  return request;
}
 
Example #25
Source File: WebSocketServerExtensionHandler.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
        throws Exception {
    if (msg instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) msg;

        if (WebSocketExtensionUtil.isWebsocketUpgrade(request.headers())) {
            String extensionsHeader = request.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);

            if (extensionsHeader != null) {
                List<WebSocketExtensionData> extensions =
                        WebSocketExtensionUtil.extractExtensions(extensionsHeader);
                int rsv = 0;

                for (WebSocketExtensionData extensionData : extensions) {
                    Iterator<WebSocketServerExtensionHandshaker> extensionHandshakersIterator =
                            extensionHandshakers.iterator();
                    WebSocketServerExtension validExtension = null;

                    while (validExtension == null && extensionHandshakersIterator.hasNext()) {
                        WebSocketServerExtensionHandshaker extensionHandshaker =
                                extensionHandshakersIterator.next();
                        validExtension = extensionHandshaker.handshakeExtension(extensionData);
                    }

                    if (validExtension != null && ((validExtension.rsv() & rsv) == 0)) {
                        if (validExtensions == null) {
                            validExtensions = new ArrayList<WebSocketServerExtension>(1);
                        }
                        rsv = rsv | validExtension.rsv();
                        validExtensions.add(validExtension);
                    }
                }
            }
        }
    }

    super.channelRead(ctx, msg);
}
 
Example #26
Source File: HttpProxyServer.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private boolean authenticate(ChannelHandlerContext ctx, FullHttpRequest req) {
    assertThat(req.method(), is(HttpMethod.CONNECT));

    if (testMode != TestMode.INTERMEDIARY) {
        ctx.pipeline().addBefore(ctx.name(), "lineDecoder", new LineBasedFrameDecoder(64, false, true));
    }

    ctx.pipeline().remove(HttpObjectAggregator.class);
    ctx.pipeline().get(HttpServerCodec.class).removeInboundHandler();

    boolean authzSuccess = false;
    if (username != null) {
        CharSequence authz = req.headers().get(HttpHeaderNames.PROXY_AUTHORIZATION);
        if (authz != null) {
            String[] authzParts = authz.toString().split(" ", 2);
            ByteBuf authzBuf64 = Unpooled.copiedBuffer(authzParts[1], CharsetUtil.US_ASCII);
            ByteBuf authzBuf = Base64.decode(authzBuf64);

            String expectedAuthz = username + ':' + password;
            authzSuccess = "Basic".equals(authzParts[0]) &&
                           expectedAuthz.equals(authzBuf.toString(CharsetUtil.US_ASCII));

            authzBuf64.release();
            authzBuf.release();
        }
    } else {
        authzSuccess = true;
    }

    return authzSuccess;
}
 
Example #27
Source File: WebSocketServerHandler.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
private static String getWebSocketLocation(FullHttpRequest req) {
    String location =  req.headers().get(HttpHeaderNames.HOST) + WEBSOCKET_PATH;
    if (WebSocketServer.SSL) {
        return "wss://" + location;
    } else {
        return "ws://" + location;
    }
}
 
Example #28
Source File: Job.java    From multi-model-server with Apache License 2.0 5 votes vote down vote up
public void response(
        byte[] body,
        CharSequence contentType,
        int statusCode,
        String statusPhrase,
        Map<String, String> responseHeaders) {
    HttpResponseStatus status =
            (statusPhrase == null)
                    ? HttpResponseStatus.valueOf(statusCode)
                    : HttpResponseStatus.valueOf(statusCode, statusPhrase);
    FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, false);

    if (contentType != null && contentType.length() > 0) {
        resp.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
    }
    if (responseHeaders != null) {
        for (Map.Entry<String, String> e : responseHeaders.entrySet()) {
            resp.headers().set(e.getKey(), e.getValue());
        }
    }
    resp.content().writeBytes(body);

    /*
     * We can load the models based on the configuration file.Since this Job is
     * not driven by the external connections, we could have a empty context for
     * this job. We shouldn't try to send a response to ctx if this is not triggered
     * by external clients.
     */
    if (ctx != null) {
        NettyUtils.sendHttpResponse(ctx, resp, true);
    }

    logger.debug(
            "Waiting time: {}, Backend time: {}",
            scheduled - begin,
            System.currentTimeMillis() - scheduled);
}
 
Example #29
Source File: NettyConnector.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * HTTP upgrade response will be decode by Netty as 2 objects:
 * - 1 HttpObject corresponding to the 101 SWITCHING PROTOCOL headers
 * - 1 EMPTY_LAST_CONTENT
 *
 * The HTTP upgrade is successful whne the 101 SWITCHING PROTOCOL has been received (handshakeComplete = true)
 * but the latch is count down only when the following EMPTY_LAST_CONTENT is also received.
 * Otherwise this ChannelHandler would be removed too soon and the ActiveMQChannelHandler would handle the
 * EMPTY_LAST_CONTENT (while it is expecitng only ByteBuf).
 */
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
   if (logger.isDebugEnabled()) {
      logger.debug("Received msg=" + msg);
   }
   if (msg instanceof HttpResponse) {
      HttpResponse response = (HttpResponse) msg;
      if (response.status().code() == HttpResponseStatus.SWITCHING_PROTOCOLS.code() && response.headers().get(HttpHeaderNames.UPGRADE).equals(ACTIVEMQ_REMOTING)) {
         String accept = response.headers().get(SEC_ACTIVEMQ_REMOTING_ACCEPT);
         String expectedResponse = createExpectedResponse(MAGIC_NUMBER, ctx.channel().attr(REMOTING_KEY).get());

         if (expectedResponse.equals(accept)) {
            // HTTP upgrade is successful but let's wait to receive the EMPTY_LAST_CONTENT to count down the latch
            handshakeComplete = true;
         } else {
            // HTTP upgrade failed
            ActiveMQClientLogger.LOGGER.httpHandshakeFailed(msg);
            ctx.close();
            latch.countDown();
         }
         return;
      }
   } else if (msg == LastHttpContent.EMPTY_LAST_CONTENT && handshakeComplete) {
      // remove the http handlers and flag the activemq channel handler as active
      pipeline.remove(httpClientCodec);
      pipeline.remove(this);
      ActiveMQChannelHandler channelHandler = pipeline.get(ActiveMQChannelHandler.class);
      channelHandler.active = true;
   }
   if (!handshakeComplete) {
      ActiveMQClientLogger.LOGGER.httpHandshakeFailed(msg);
      ctx.close();
   }
   latch.countDown();
}
 
Example #30
Source File: HttpServerHandler.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void writeResponse(CommandResponse response, ChannelHandlerContext ctx, boolean keepAlive)
    throws Exception {
    byte[] body;
    if (response.isSuccess()) {
        if (response.getResult() == null) {
            body = new byte[] {};
        } else {
            Encoder encoder = pickEncoder(response.getResult().getClass());
            if (encoder == null) {
                writeErrorResponse(INTERNAL_SERVER_ERROR.code(), SERVER_ERROR_MESSAGE, ctx);
                CommandCenterLog.warn("Error when encoding object",
                    new IllegalStateException("No compatible encoder"));
                return;
            }
            body = encoder.encode(response.getResult());
        }
    } else {
        body = response.getException().getMessage().getBytes(SentinelConfig.charset());
    }

    HttpResponseStatus status = response.isSuccess() ? OK : BAD_REQUEST;

    FullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
        Unpooled.copiedBuffer(body));

    httpResponse.headers().set("Content-Type", "text/plain; charset=" + SentinelConfig.charset());

    //if (keepAlive) {
    //    httpResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());
    //    httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    //}
    //ctx.write(httpResponse);
    //if (!keepAlive) {
    //    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    //}
    httpResponse.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, httpResponse.content().readableBytes());
    httpResponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
    ctx.write(httpResponse);
    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}