Java Code Examples for io.netty.handler.codec.http.FullHttpRequest

The following examples show how to use io.netty.handler.codec.http.FullHttpRequest. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: netty-4.1.22   Source File: HelloWorldHttp1Handler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    if (HttpUtil.is100ContinueExpected(req)) {
        ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
    }
    boolean keepAlive = HttpUtil.isKeepAlive(req);

    ByteBuf content = ctx.alloc().buffer();
    content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate());
    ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")");

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes());

    if (!keepAlive) {
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        ctx.write(response);
    }
}
 
Example 2
Source Project: ThinkMap   Source File: ChunkEndPoint.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, context.alloc().buffer());
    response.headers().add("Access-Control-Allow-Origin", "*");
    response.headers().add("Access-Control-Allow-Methods", "POST");
    if (request.getMethod() == OPTIONS) {
        response.headers().add("Access-Control-Allow-Headers", "origin, content-type, accept");
    }

    if (request.getMethod() == POST) {
        String[] args = request.content().toString(Charsets.UTF_8).split(":");
        ByteBuf out = response.content();
        if (plugin.getChunkManager(plugin.getTargetWorld()).getChunkBytes(Integer.parseInt(args[0]), Integer.parseInt(args[1]), out)) {
            response.headers().add("Content-Encoding", "gzip");
        } else {
            out.writeBytes(new byte[1]);
        }
    }
    sendHttpResponse(context, request, response);
}
 
Example 3
Source Project: netty-4.1.22   Source File: WebSocketRequestBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public FullHttpRequest build() {
    FullHttpRequest req = new DefaultFullHttpRequest(httpVersion, method, uri);
    HttpHeaders headers = req.headers();

    if (host != null) {
        headers.set(HttpHeaderNames.HOST, host);
    }
    if (upgrade != null) {
        headers.set(HttpHeaderNames.UPGRADE, upgrade);
    }
    if (connection != null) {
        headers.set(HttpHeaderNames.CONNECTION, connection);
    }
    if (key != null) {
        headers.set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key);
    }
    if (origin != null) {
        headers.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, origin);
    }
    if (version != null) {
        headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, version.toHttpHeaderValue());
    }
    return req;
}
 
Example 4
Source Project: JavaQuarkBBS   Source File: UserAuthHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * HTTP握手反馈
 */
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request){
    //判断是否是WebSocket协议
    if (!request.decoderResult().isSuccess() || !"websocket".equals(request.headers().get("Upgrade"))) {
        logger.warn("protobuf don't support WebSocket");
        ctx.channel().close();
        return;
    }
    WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory(
            WEBSOCKET_URL, null, true);
    handshaker = handshakerFactory.newHandshaker(request);
    if (handshaker == null){
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    }else {
        // 动态加入websocket的编解码处理
        handshaker.handshake(ctx.channel(), request);
        // 存储已经连接的Channel
        manager.addChannel(ctx.channel());
    }
}
 
Example 5
Source Project: socketio   Source File: WebSocketHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void handshake(final ChannelHandlerContext ctx, final FullHttpRequest req, final String requestPath) {
  WebSocketServerHandshakerFactory wsFactory =
      new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true, maxWebSocketFrameSize);
  WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
  if (handshaker != null) {
    handshaker.handshake(ctx.channel(), req).addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            final String sessionId = PipelineUtils.getSessionId(requestPath);
            if (future.isSuccess()) {
              ctx.channel().pipeline().addBefore(
                  SocketIOChannelInitializer.SOCKETIO_WEBSOCKET_HANDLER,
                  SocketIOChannelInitializer.WEBSOCKET_FRAME_AGGREGATOR,
                  new WebSocketFrameAggregator(maxWebSocketFrameSize));
              connect(ctx, req, sessionId);
            } else {
              log.error("Can't handshake: {}", sessionId, future.cause());
            }
          }
        });
  } else {
    WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
  }
}
 
Example 6
Source Project: momo-cloud-permission   Source File: ChatHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //首次连接是FullHttpRequest,处理参数
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap = getUrlParams(uri);
            //如果url包含参数,需要处理
            if (uri.contains("?")) {
                String newUri = uri.substring(0, uri.indexOf("?"));
                request.setUri(newUri);
            }
            Object obj = paramMap.get("token");
            if (null == obj || "undefined".equals(obj)) {
                ctx.channel().close();
                return;
            }
            ChannelManager.putChannel(ChannelManager.channelLongText(ctx), ctx.channel());
        } else if (msg instanceof TextWebSocketFrame) {
            //正常的TEXT消息类型
//            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
        }
        super.channelRead(ctx, msg);
    }
 
Example 7
Source Project: activemq-artemis   Source File: ProtocolHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
   if (msg instanceof FullHttpRequest) {
      FullHttpRequest request = (FullHttpRequest) msg;
      HttpHeaders headers = request.headers();
      String upgrade = headers.get("upgrade");
      if (upgrade != null && upgrade.equalsIgnoreCase("websocket")) {
         ctx.pipeline().addLast("websocket-handler", new WebSocketServerHandler(websocketSubprotocolIds, ConfigurationHelper.getIntProperty(TransportConstants.STOMP_MAX_FRAME_PAYLOAD_LENGTH, TransportConstants.DEFAULT_STOMP_MAX_FRAME_PAYLOAD_LENGTH, nettyAcceptor.getConfiguration())));
         ctx.pipeline().addLast(new ProtocolDecoder(false, false));
         ctx.pipeline().remove(this);
         ctx.pipeline().remove("http-handler");
         ctx.fireChannelRead(msg);
      } else if (upgrade != null && upgrade.equalsIgnoreCase(NettyConnector.ACTIVEMQ_REMOTING)) { // HORNETQ-1391
         // Send the response and close the connection if necessary.
         ctx.writeAndFlush(new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)).addListener(ChannelFutureListener.CLOSE);
      }
   } else {
      super.channelRead(ctx, msg);
   }
}
 
Example 8
Source Project: digdag   Source File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Starts a proxy that fails all requests except every {@code failures}'th request per unique (method, uri) pair.
 */
public static HttpProxyServer startRequestFailingProxy(int defaultFailures, ConcurrentMap<String, List<FullHttpRequest>> requests, HttpResponseStatus error,
        BiFunction<FullHttpRequest, Integer, Optional<Boolean>> customFailDecider)
{
    return startRequestFailingProxy(request -> {
        String key = request.getMethod() + " " + request.getUri();
        List<FullHttpRequest> keyedRequests = requests.computeIfAbsent(key, k -> new ArrayList<>());
        int n;
        synchronized (keyedRequests) {
            keyedRequests.add(request.copy());
            n = keyedRequests.size();
        }
        boolean fail = customFailDecider.apply(request, n).or(() -> n % defaultFailures != 0);
        if (fail) {
            return Optional.of(error);
        }
        else {
            return Optional.absent();
        }
    });
}
 
Example 9
Source Project: HappyChat   Source File: UserAuthHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) {
    if (!request.decoderResult().isSuccess() || !"websocket".equals(request.headers().get("Upgrade"))) {
        logger.warn("protobuf don't support websocket");
        ctx.channel().close();
        return;
    }
    WebSocketServerHandshakerFactory handshakerFactory = new WebSocketServerHandshakerFactory(
            Constants.WEBSOCKET_URL, null, true);
    handshaker = handshakerFactory.newHandshaker(request);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
    } else {
        // 动态加入websocket的编解码处理
        handshaker.handshake(ctx.channel(), request);
        UserInfo userInfo = new UserInfo();
        userInfo.setAddr(NettyUtil.parseChannelRemoteAddr(ctx.channel()));
        // 存储已经连接的Channel
        UserInfoManager.addChannel(ctx.channel());
    }
}
 
Example 10
Source Project: arcusplatform   Source File: TwilioScriptHandler.java    License: Apache License 2.0 6 votes vote down vote up
private Map<String, Object> initializeContext(FullHttpRequest request)
{
   HttpRequestParameters requestParams = new HttpRequestParameters(request);

   Map<String, Object> context = new HashMap<>();

   context.put(SCRIPT_PARAM,                       requestParams.getParameter(SCRIPT_PARAM));
   context.put(STEP_PARAM,                         requestParams.getParameter(STEP_PARAM, getInitialStep()));
   context.put(PLACE_ID_PARAM_NAME,                requestParams.getParameter(PLACE_ID_PARAM_NAME, ""));
   context.put(PERSON_ID_PARAM_NAME,               requestParams.getParameter(PERSON_ID_PARAM_NAME));
   context.put(TWILIO_DIGITS_PARAM,                requestParams.getParameter(TWILIO_DIGITS_PARAM, ""));
   context.put(NOTIFICATION_ID_PARAM_NAME,         requestParams.getParameter(NOTIFICATION_ID_PARAM_NAME));
   context.put(NOTIFICATION_EVENT_TIME_PARAM_NAME, requestParams.getParameter(NOTIFICATION_EVENT_TIME_PARAM_NAME));
   context.put(CUSTOM_MESSAGE_PARAM,               requestParams.getParameter(CUSTOM_MESSAGE_PARAM, ""));
   context.put(CUSTOM_PARAMETERS_KEY,              getCustomParameters(requestParams));

   customizeContext(context, requestParams);

   return context;
}
 
Example 11
@Test
public void testDowngradeHeaders() throws Exception {
    EmbeddedChannel ch = new EmbeddedChannel(new Http2StreamFrameToHttpObjectCodec(true));
    Http2Headers headers = new DefaultHttp2Headers();
    headers.path("/");
    headers.method("GET");

    assertTrue(ch.writeInbound(new DefaultHttp2HeadersFrame(headers)));

    HttpRequest request = ch.readInbound();
    assertThat(request.uri(), is("/"));
    assertThat(request.method(), is(HttpMethod.GET));
    assertThat(request.protocolVersion(), is(HttpVersion.HTTP_1_1));
    assertFalse(request instanceof FullHttpRequest);
    assertTrue(HttpUtil.isTransferEncodingChunked(request));

    assertThat(ch.readInbound(), is(nullValue()));
    assertFalse(ch.finish());
}
 
Example 12
Source Project: ThinkMap   Source File: EndPointManager.java    License: Apache License 2.0 6 votes vote down vote up
public void handle(ChannelHandlerContext context, URI uri, FullHttpRequest request) throws Exception {
    if (endPoints.containsKey(uri.getPath())) {
        endPoints.get(uri.getPath()).handle(context, uri, request);
        return;
    }
    for (Map.Entry<Pattern, EndPoint> e : specialPoints.entrySet()) {
        if (e.getKey().matcher(uri.getPath()).find()) {
            e.getValue().handle(context, uri, request);
            return;
        }
    }
    if (def != null) {
        def.handle(context, uri, request);
    } else {
        HTTPHandler.sendHttpResponse(context, request,
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND)
        );
    }
}
 
Example 13
Source Project: lannister   Source File: HttpRequest.java    License: Apache License 2.0 5 votes vote down vote up
protected HttpRequest(FullHttpRequest fullHttpRequest) throws URISyntaxException {
	super(fullHttpRequest.protocolVersion(), fullHttpRequest.method(), fullHttpRequest.uri(),
			fullHttpRequest.content().copy());

	this.headers().set(fullHttpRequest.headers());
	this.trailingHeaders().set(fullHttpRequest.trailingHeaders());
	this.setDecoderResult(fullHttpRequest.decoderResult());
	this.uri = createUriWithNormalizing(fullHttpRequest.uri());

	this.parameters = parameters();
	this.cookies = cookies();
	this.pathParameters = Maps.newHashMap();
}
 
Example 14
@Test
public void testAuthorityFormRequestTargetHandled() throws Exception {
    bootstrapEnv(2, 1, 0);
    final FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, CONNECT, "http://www.example.com:80");
    final HttpHeaders httpHeaders = request.headers();
    httpHeaders.setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 5);
    final Http2Headers http2Headers =
            new DefaultHttp2Headers().method(new AsciiString("CONNECT")).path(new AsciiString("/"))
            .scheme(new AsciiString("http")).authority(new AsciiString("www.example.com:80"));

    ChannelPromise writePromise = newPromise();
    verifyHeadersOnly(http2Headers, writePromise, clientChannel.writeAndFlush(request, writePromise));
}
 
Example 15
Source Project: couchbase-jvm-core   Source File: ConfigHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected HttpRequest encodeRequest(final ChannelHandlerContext ctx, final ConfigRequest msg) throws Exception {
    if (msg instanceof RestApiRequest) {
        return encodeRestApiRequest(ctx, (RestApiRequest) msg);
    }
    HttpMethod httpMethod = HttpMethod.GET;
    if (msg instanceof FlushRequest || msg instanceof InsertBucketRequest
            || msg instanceof UpdateBucketRequest) {
        httpMethod = HttpMethod.POST;
    } else if (msg instanceof UpsertUserRequest) {
      httpMethod = HttpMethod.PUT;
    } else if (msg instanceof RemoveBucketRequest || msg instanceof RemoveUserRequest) {
        httpMethod = HttpMethod.DELETE;
    }

    ByteBuf content;
    if (msg instanceof InsertBucketRequest) {
        content = Unpooled.copiedBuffer(((InsertBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof UpdateBucketRequest) {
        content = Unpooled.copiedBuffer(((UpdateBucketRequest) msg).payload(), CharsetUtil.UTF_8);
    } else if (msg instanceof UpsertUserRequest) {
        content = Unpooled.copiedBuffer(((UpsertUserRequest) msg).payload(), CharsetUtil.UTF_8);
    } else {
        content = Unpooled.EMPTY_BUFFER;
    }

    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, msg.path(), content);
    request.headers().set(HttpHeaders.Names.USER_AGENT, env().userAgent());
    if (msg instanceof InsertBucketRequest || msg instanceof UpdateBucketRequest || msg instanceof UpsertUserRequest) {
        request.headers().set(HttpHeaders.Names.ACCEPT, "*/*");
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded");
    }
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
    request.headers().set(HttpHeaders.Names.HOST, remoteHttpHost(ctx));

    addHttpBasicAuth(ctx, request, msg.username(), msg.password());
    return request;
}
 
Example 16
Source Project: digdag   Source File: TestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpProxyServer startRequestFailingProxy(final Function<FullHttpRequest, Optional<HttpResponseStatus>> failer)
{
    return DefaultHttpProxyServer
            .bootstrap()
            .withPort(0)
            .withFiltersSource(new HttpFiltersSourceAdapter()
            {
                @Override
                public int getMaximumRequestBufferSizeInBytes()
                {
                    return 1024 * 1024;
                }

                @Override
                public HttpFilters filterRequest(HttpRequest httpRequest, ChannelHandlerContext channelHandlerContext)
                {
                    return new HttpFiltersAdapter(httpRequest)
                    {
                        @Override
                        public HttpResponse clientToProxyRequest(HttpObject httpObject)
                        {
                            assert httpObject instanceof FullHttpRequest;
                            FullHttpRequest fullHttpRequest = (FullHttpRequest) httpObject;
                            Optional<HttpResponseStatus> error = failer.apply(fullHttpRequest);
                            if (error.isPresent()) {
                                logger.info("Simulating {} for request: {} {}", error, fullHttpRequest.getMethod(), fullHttpRequest.getUri());
                                HttpResponse response = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), error.get());
                                response.headers().set(CONNECTION, CLOSE);
                                return response;
                            }
                            else {
                                logger.info("Passing request: {} {}", fullHttpRequest.getMethod(), fullHttpRequest.getUri());
                                return null;
                            }
                        }
                    };
                }
            }).start();
}
 
Example 17
Source Project: bazel   Source File: HttpCacheClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDownloadFailsOnDigestMismatch() throws Exception {
  // Test that the download fails when a blob/file has a different content hash than expected.

  ServerChannel server = null;
  try {
    server =
        testServer.start(
            new SimpleChannelInboundHandler<FullHttpRequest>() {
              @Override
              protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
                ByteBuf data = ctx.alloc().buffer();
                ByteBufUtil.writeUtf8(data, "bar");
                DefaultFullHttpResponse response =
                    new DefaultFullHttpResponse(
                        HttpVersion.HTTP_1_1, HttpResponseStatus.OK, data);
                HttpUtil.setContentLength(response, data.readableBytes());

                ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
              }
            });

    Credentials credentials = newCredentials();
    HttpCacheClient blobStore =
        createHttpBlobStore(
            server, /* timeoutSeconds= */ 1, /* remoteVerifyDownloads= */ true, credentials);
    Digest fooDigest = DIGEST_UTIL.compute("foo".getBytes(Charsets.UTF_8));
    try (OutputStream out = new ByteArrayOutputStream()) {
      IOException e =
          assertThrows(
              IOException.class, () -> getFromFuture(blobStore.downloadBlob(fooDigest, out)));
      assertThat(e).hasMessageThat().contains(fooDigest.getHash());
      assertThat(e).hasMessageThat().contains(DIGEST_UTIL.computeAsUtf8("bar").getHash());
    }
  } finally {
    testServer.stop(server);
  }
}
 
Example 18
Source Project: netty-4.1.22   Source File: WebSocketClientHandshaker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Begins the opening handshake
 *
 * @param channel
 *            Channel
 * @param promise
 *            the {@link ChannelPromise} to be notified when the opening handshake is sent
 */
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
    FullHttpRequest request =  newHandshakeRequest();

    HttpResponseDecoder decoder = channel.pipeline().get(HttpResponseDecoder.class);
    if (decoder == null) {
        HttpClientCodec codec = channel.pipeline().get(HttpClientCodec.class);
        if (codec == null) {
           promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                   "a HttpResponseDecoder or HttpClientCodec"));
           return promise;
        }
    }

    channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                ChannelPipeline p = future.channel().pipeline();
                ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
                if (ctx == null) {
                    ctx = p.context(HttpClientCodec.class);
                }
                if (ctx == null) {
                    promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " +
                            "a HttpRequestEncoder or HttpClientCodec"));
                    return;
                }
                p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());

                promise.setSuccess();
            } else {
                promise.setFailure(future.cause());
            }
        }
    });
    return promise;
}
 
Example 19
Source Project: netty-pubsub   Source File: HttpHandler.java    License: MIT License 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
	// TODO Auto-generated method stub
	try {
		ByteBuf content = msg.content();
		byte[] bts = new byte[content.readableBytes()];
		content.readBytes(bts);
		String result = null;
		if(msg.getMethod() == HttpMethod.GET) {
			String url = msg.getUri().toString();
			result =JSON.toJSONString(UrlUtil.parse(url).params);
			doGet(result);
			
		}else if(msg.getMethod() == HttpMethod.POST) {
			//result = "post method and paramters is "+ new String(bts);
			doPost(new String(bts,"utf-8"));
		}
		FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
		response.headers().set("content-Type","text/html;charset=UTF-8");
		StringBuilder sb = new StringBuilder();
		sb.append("OK");
		ByteBuf responseBuf = Unpooled.copiedBuffer(sb,CharsetUtil.UTF_8);
		response.content().writeBytes(responseBuf);
		responseBuf.release();
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
		}catch (Exception e) {
			e.printStackTrace();
		}
}
 
Example 20
Source Project: ambry   Source File: FrontendIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the right response code is returned for GET, HEAD, TTL update and DELETE once a blob is deleted.
 * @param blobId the ID of the blob that was deleted.
 * @param expectedHeaders the expected headers in the response if the right options are provided.
 * @param isPrivate {@code true} if the blob is expected to be private
 * @param accountName the expected account name in {@code response}.
 * @param containerName the expected container name in {@code response}.
 * @param expectedContent the expected content of the blob if the right options are provided.
 * @param usermetadata if non-null, this is expected to come as the body.
 * @throws Exception
 */
private void verifyOperationsAfterDelete(String blobId, HttpHeaders expectedHeaders, boolean isPrivate,
    String accountName, String containerName, ByteBuffer expectedContent, byte[] usermetadata) throws Exception {
  HttpHeaders headers = new DefaultHttpHeaders().add(RestUtils.Headers.GET_OPTION, GetOption.None.toString());
  FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, blobId, null, null);
  verifyDeleted(httpRequest, HttpResponseStatus.GONE);
  httpRequest = buildRequest(HttpMethod.GET, blobId, headers, null);
  verifyDeleted(httpRequest, HttpResponseStatus.GONE);

  httpRequest = buildRequest(HttpMethod.HEAD, blobId, null, null);
  verifyDeleted(httpRequest, HttpResponseStatus.GONE);
  httpRequest = buildRequest(HttpMethod.HEAD, blobId, headers, null);
  verifyDeleted(httpRequest, HttpResponseStatus.GONE);

  headers = new DefaultHttpHeaders().set(RestUtils.Headers.BLOB_ID, blobId)
      .set(RestUtils.Headers.SERVICE_ID, "verifyOperationsAfterDelete");
  httpRequest = buildRequest(HttpMethod.PUT, "/" + Operations.UPDATE_TTL, headers, null);
  verifyDeleted(httpRequest, HttpResponseStatus.GONE);

  httpRequest = buildRequest(HttpMethod.DELETE, blobId, null, null);
  verifyDeleted(httpRequest, HttpResponseStatus.ACCEPTED);

  GetOption[] options = {GetOption.Include_Deleted_Blobs, GetOption.Include_All};
  for (GetOption option : options) {
    getBlobAndVerify(blobId, null, option, expectedHeaders, isPrivate, expectedContent, accountName, containerName);
    getNotModifiedBlobAndVerify(blobId, option, isPrivate);
    getUserMetadataAndVerify(blobId, option, expectedHeaders, usermetadata);
    getBlobInfoAndVerify(blobId, option, expectedHeaders, isPrivate, accountName, containerName, usermetadata);
    getHeadAndVerify(blobId, null, option, expectedHeaders, isPrivate, accountName, containerName);
  }
}
 
Example 21
Source Project: happor   Source File: HttpAsyncHandler.java    License: MIT License 5 votes vote down vote up
@Override
protected boolean handleRequest(FullHttpRequest request,
		FullHttpResponse response) {
	// TODO Auto-generated method stub
	handle(request, response);
	return true;
}
 
Example 22
Source Project: arcusplatform   Source File: BaseWebSocketServerHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendResponse(FullHttpRequest req, ChannelHandlerContext ctx) throws Exception {
   Client client = clientFactory.get(ctx.channel());
   // Handshake
   WebSocketServerHandshaker handshaker = createWebSocketHandshaker(ctx, req);
   if (handshaker == null) {
      WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
   } else {
      handshaker.handshake(ctx.channel(), req);

      // The chunked write handler interferes with large websocket messages
      // so it needs to be removed from the pipeline since we are setting up
      // a websocket here.
      ctx.pipeline().remove(Bridge10ChannelInitializer.CHUNKED_WRITE_HANDLER);

      // Only create the session after the handshake.
      // at this point the session is not fully initialized
      // because we haven't gotten a message from the device that
      // can identify it. We only put the session in the registry when it
      // is initialized
      metrics.incSocketCounter();
      Session socketSession = createAndSetSocketSession(client, ctx.channel(), metrics);
      updateClientInfo(req, socketSession);
      try(MdcContextReference ref = BridgeMdcUtil.captureAndInitializeContext(socketSession)) {
         logger.trace("Getting ready to call session listeners [{}]", sessionListeners);
         sessionListeners.forEach((l) -> { l.onSessionCreated(socketSession); });
         if(socketSession.isInitialized()) {
            sessionRegistry.putSession(socketSession);
         }
      }
   }
}
 
Example 23
Source Project: serve   Source File: InferenceRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void handlePredictions(
        ChannelHandlerContext ctx, FullHttpRequest req, String[] segments)
        throws ModelNotFoundException, ModelVersionNotFoundException {
    if (segments.length < 3) {
        throw new ResourceNotFoundException();
    }

    String modelVersion = null;

    if (segments.length == 4) {
        modelVersion = segments[3];
    }

    predict(ctx, req, null, segments[2], modelVersion);
}
 
Example 24
Source Project: arcusplatform   Source File: BearerAuth.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAuthorized(ChannelHandlerContext ctx, FullHttpRequest req) {
   Optional<String> token = OAuthUtil.extractTokenFromBearer(req);
   Pair<UUID, Integer> personWithTtl = null;
   if(token.isPresent()) {
      personWithTtl = dao.getPersonWithAccess(appId, token.get());
   }
   return token.isPresent() && personWithTtl != null;
}
 
Example 25
Source Project: karate   Source File: ProxyRemoteHandler.java    License: MIT License 5 votes vote down vote up
protected void send(FullHttpRequest request) {
    currentRequest = request;
    FullHttpRequest filtered;
    if (requestFilter != null) {
        ProxyResponse pr = requestFilter.apply(proxyContext, request);
        if (pr != null && pr.response != null) { // short circuit
            clientChannel.writeAndFlush(pr.response);
            return;
        }
        filtered = pr == null ? null : pr.request; // if not null, is transformed
    } else {
        filtered = null;
    }
    if (logger.isTraceEnabled()) {
        logger.trace(">> before: {}", request);
    }
    if (filtered == null) {
        ReferenceCountUtil.retain(request);
        filtered = request;
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace(">>>> after: {}", filtered);
        }
    }
    NettyUtils.fixHeadersForProxy(filtered);
    remoteChannel.writeAndFlush(filtered);
}
 
Example 26
Source Project: jawampa   Source File: WampServerWebsocketHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // Discard messages when we are not reading
    if (readState != ReadState.Reading) {
        ReferenceCountUtil.release(msg);
        return;
    }

    // We might receive http requests here when the whe clients sends something after the upgrade
    // request but we have not fully sent out the response and the http codec is still installed.
    // However that would be an error.
    if (msg instanceof FullHttpRequest) {
        ((FullHttpRequest) msg).release();
        WampServerWebsocketHandler.sendBadRequestAndClose(ctx, null);
        return;
    }

    if (msg instanceof PingWebSocketFrame) {
        // Respond to Pings with Pongs
        try {
            ctx.writeAndFlush(new PongWebSocketFrame());
        } finally {
            ((PingWebSocketFrame) msg).release();
        }
    } else if (msg instanceof CloseWebSocketFrame) {
        // Echo the close and close the connection
        readState = ReadState.Closed;
        ctx.writeAndFlush(msg).addListener(ChannelFutureListener.CLOSE);

    } else {
        ctx.fireChannelRead(msg);
    }
}
 
Example 27
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof FullHttpRequest) {
        FullHttpRequest request = (FullHttpRequest) msg;
        if (request.uri().equals(initUrl)) {
            if (ctx.channel().attr(SessionDao.userAttributeKey).get() == null) {
                request.setUri(mapToUrlWithoutCookie);
            } else {
                request.setUri(mapToUrlWithCookie);
            }
        }
    }

    super.channelRead(ctx, msg);
}
 
Example 28
Source Project: netty-4.1.22   Source File: CorsHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
private static FullHttpRequest optionsRequest(final String origin,
                                              final String requestHeaders,
                                              final AsciiString connection) {
    final FullHttpRequest httpRequest = createHttpRequest(OPTIONS);
    httpRequest.headers().set(ORIGIN, origin);
    httpRequest.headers().set(ACCESS_CONTROL_REQUEST_METHOD, httpRequest.method().toString());
    httpRequest.headers().set(ACCESS_CONTROL_REQUEST_HEADERS, requestHeaders);
    if (connection != null) {
        httpRequest.headers().set(CONNECTION, connection);
    }

    return httpRequest;
}
 
Example 29
private static void sendHttpResponse(
    ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }
    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 30
Source Project: arcusplatform   Source File: RecurlyCallbackHttpHandler.java    License: Apache License 2.0 5 votes vote down vote up
public TemplatedResponse doHandle(FullHttpRequest request, ChannelHandlerContext ctx) throws Exception {
   Context timer = WEBHOOK_TIMER.time();
   
   try{
      String recurlyXML = request.content().toString(CharsetUtil.UTF_8);
      Document document = XMLHelper.parse(recurlyXML);
      String transactionType = document.getDocumentElement().getTagName();
      WebhookHandler<? extends Object>handler=handlers.get(transactionType);
      
      if(transactionType.equals(TRANS_TYPE_CLOSED_INVOICE_NOTIFICATION)){
         ClosedInvoiceNotification notification = XMLHelper.unmarshall(document,ClosedInvoiceNotification.class);
        ((WebhookHandler)handler).handleWebhook(notification);
      }
      else{
         IGNORED_COUNTER.inc();
         LOGGER.info(MSG_IGNORE_NOTIFICATION);
      }
      return createTemplateResponse(HttpResponseStatus.NO_CONTENT);
   }
   catch(Exception e){
      ERRORED_COUNTER.inc();
      LOGGER.error("Unknown error processing recurly webhook",e);
      return createTemplateResponse(HttpResponseStatus.BAD_REQUEST);
   }
   finally{
      timer.stop();
   }
}