org.jboss.netty.handler.codec.http.HttpRequest Java Examples

The following examples show how to use org.jboss.netty.handler.codec.http.HttpRequest. 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: HttpServerHandler.java    From netty-servlet with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception {
    if (event.getMessage() instanceof HttpRequest) {
        try {
            HttpServletRequest httpServletRequest = new NettyHttpServletRequestAdaptor((HttpRequest) event.getMessage(), ctx.getChannel());
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            response.setContent(new DynamicChannelBuffer(200));
            HttpServletResponse httpServletResponse = new NettyHttpServletResponseAdaptor(response, ctx.getChannel());
            dispatcher.dispatch(httpServletRequest,httpServletResponse);
            response.headers().set(HttpHeaders.Names.CONTENT_LENGTH,response.getContent().writerIndex());
            ChannelFuture future = ctx.getChannel().write(response);
            future.addListener(ChannelFutureListener.CLOSE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example #2
Source File: HttpServerHandler.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (!readingChunks) {
        request = (HttpRequest) e.getMessage();
        String uri = request.getUri();
        if (uri.equals("/exception")) {
            throw new Exception("Test");
        }
        if (request.isChunked()) {
            readingChunks = true;
        } else {
            writeResponse(e);
        }
    } else {
        HttpChunk chunk = (HttpChunk) e.getMessage();
        if (chunk.isLast()) {
            readingChunks = false;
            writeResponse(e);
        }
    }
}
 
Example #3
Source File: HttpRequestFrameworkHandler.java    From zuul-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) e.getMessage();
        InterruptsImpl callback = new InterruptsImpl(request, e.getChannel());
        LOG.debug("handler: {} is calling request-handler: {}", tag, requestHandler.getClass().getSimpleName());
        requestHandler.requestReceived(new HttpRequestFrameworkAdapter(request));


        if (callback.isInterrupted()) {
            //plugin requested that execution is interrupted i.e. not passed down the pipeline
            return;
        }
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("encountered a chunk, not passed to handler");
    }

    super.messageReceived(ctx, e);
}
 
Example #4
Source File: DirectoryRetriever.java    From incubator-tajo with Apache License 2.0 6 votes vote down vote up
@Override
public FileChunk [] handle(ChannelHandlerContext ctx, HttpRequest request)
    throws IOException {
  final String path = HttpDataServerHandler.sanitizeUri(request.getUri());
  if (path == null) {
    throw new IllegalArgumentException("Wrong path: " +path);
  }

  File file = new File(baseDir, path);
  if (file.isHidden() || !file.exists()) {
    throw new FileNotFoundException("No such file: " + baseDir + "/" + path);
  }
  if (!file.isFile()) {
    throw new FileAccessForbiddenException("No such file: "
        + baseDir + "/" + path); 
  }
  
  return new FileChunk[] {new FileChunk(file, 0, file.length())};
}
 
Example #5
Source File: CorsHandler.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static void setCorsResponseHeaders(HttpRequest request, HttpResponse resp, CorsConfig config) {
    if (!config.isCorsSupportEnabled()) {
        return;
    }
    String originHeader = request.headers().get(ORIGIN);
    if (!Strings.isNullOrEmpty(originHeader)) {
        final String originHeaderVal;
        if (config.isAnyOriginSupported()) {
            originHeaderVal = ANY_ORIGIN;
        } else if (config.isOriginAllowed(originHeader) || isSameOrigin(originHeader, request.headers().get(HOST))) {
            originHeaderVal = originHeader;
        } else {
            originHeaderVal = null;
        }
        if (originHeaderVal != null) {
            resp.headers().add(ACCESS_CONTROL_ALLOW_ORIGIN, originHeaderVal);
        }
    }
    if (config.isCredentialsAllowed()) {
        resp.headers().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    }
}
 
Example #6
Source File: HttpResponseFrameworkHandler.java    From zuul-netty with Apache License 2.0 6 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) e.getMessage();
        HttpRequest request = (HttpRequest) ctx.getAttachment();

        LOG.debug("handler: {} is calling response-handler: {}", tag, responseHandler.getClass().getSimpleName());
        responseHandler.responseReceived(new HttpRequestFrameworkAdapter(request), new HttpResponseFrameworkAdapter(response));

        ctx.setAttachment(null);
    } else if (e.getMessage() instanceof HttpChunk) {
        LOG.debug("encountered a chunk, not passed to handler");
    }

    super.writeRequested(ctx, e);
}
 
Example #7
Source File: DirectoryRetriever.java    From incubator-tajo with Apache License 2.0 6 votes vote down vote up
@Override
public FileChunk [] handle(ChannelHandlerContext ctx, HttpRequest request)
    throws IOException {
  final String path = HttpDataServerHandler.sanitizeUri(request.getUri());
  if (path == null) {
    throw new IllegalArgumentException("Wrong path: " +path);
  }

  File file = new File(baseDir, path);
  if (file.isHidden() || !file.exists()) {
    throw new FileNotFoundException("No such file: " + baseDir + "/" + path);
  }
  if (!file.isFile()) {
    throw new FileAccessForbiddenException("No such file: " 
        + baseDir + "/" + path); 
  }
  
  return new FileChunk[] {new FileChunk(file, 0, file.length())};
}
 
Example #8
Source File: HttpAction.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
protected HttpRequest newRequest(HttpMethod method, URL url, String path, ChannelBuffer buffer) {
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, path);
    request.headers().add(HttpHeaders.Names.HOST, url.getHost());
    request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    request.headers().add(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    if (buffer != null) {
        request.setContent(buffer);
        int length = request.getContent().readableBytes();
        request.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json");
        request.headers().add(HttpHeaders.Names.CONTENT_LENGTH, length);
    }
    return request;
}
 
Example #9
Source File: HttpClusterUpdateSettingsAction.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpRequest createHttpRequest(URL url, ClusterUpdateSettingsRequest request) throws IOException {
    XContentBuilder builder = jsonBuilder();
    builder.startObject().startObject("persistent");
    request.persistentSettings().toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();
    builder.startObject("transient");
    request.transientSettings().toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject().endObject();
    return newRequest(HttpMethod.PUT, url, "/_cluster/settings", builder.string());
}
 
Example #10
Source File: ParamsService.java    From ob1k with Apache License 2.0 5 votes vote down vote up
public ComposableFuture<Map<String, String>> handle(final HttpRequest request) {
  final QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri());
  final Map<String,List<String>> params = queryStringDecoder.getParameters();
  final Map<String, String> res = new HashMap<>();
  for (final String key: params.keySet()) {
    res.put(key, params.get(key).get(0));
  }

  return ComposableFutures.fromValue(res);
}
 
Example #11
Source File: NoVncSecuredTargetResolver.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public InetSocketAddress resolveTarget(MessageEvent messageEvent) {
    if (messageEvent == null) {
        return null; // websockify switched to direct proxy handler, not supported here
    }
    Map<String, String> parameters = getQueryMap(((HttpRequest) messageEvent.getMessage()).getUri());

    String sessionId = parameters.get("sessionId");
    String jobId = parameters.get("jobId");
    String taskName = parameters.get("taskName");

    return doResolve(sessionId, jobId, taskName);
}
 
Example #12
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 5 votes vote down vote up
private final static int computeAndSetContentLength(Request request, HttpRequest r) {
	int lenght = (int) request.getLength();
	if (lenght == -1 && r.getHeader(HttpHeaders.Names.CONTENT_LENGTH) != null) {
		lenght = Integer.valueOf(r.getHeader(HttpHeaders.Names.CONTENT_LENGTH));
	}

	if (lenght != -1) {
		r.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(lenght));
	}
	return lenght;
}
 
Example #13
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 5 votes vote down vote up
private final static <T> void executeRequest(final Channel channel,
                                             final AsyncHttpClientConfig config,
                                             final NettyResponseFuture<T> future,
                                             final HttpRequest nettyRequest) throws ConnectException {

	if (!channel.isConnected()){
		String url = channel.getRemoteAddress() != null ? channel.getRemoteAddress().toString() : null;
		if (url == null) {
			try {
				url = future.getURI().toString();
			} catch (MalformedURLException e) {
				log.debug(e);
			}
		}
		throw new ConnectException(String.format("Connection refused to %s", url));
	}

	channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(future);
	channel.write(nettyRequest);

	try{
		future.setReaperFuture(config.reaper().schedule(new Callable<Object>() {
			public Object call() {
				if (!future.isDone() && !future.isCancelled()) {
					future.abort(new TimeoutException());
					channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(ClosedEvent.class);
				}
				return null;
			}

		}, config.getRequestTimeoutInMs(), TimeUnit.MILLISECONDS));
	} catch (RejectedExecutionException ex){
		future.abort(ex);
	}
}
 
Example #14
Source File: HttpPipeliningHandler.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) {
    final Object msg = e.getMessage();
    if (msg instanceof HttpRequest) {
        ctx.sendUpstream(new OrderedUpstreamMessageEvent(sequence++, e.getChannel(), msg, e.getRemoteAddress()));
    } else {
        ctx.sendUpstream(e);
    }
}
 
Example #15
Source File: CorsHandler.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) {
    final HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), OK);
    if (setOrigin(response)) {
        setAllowMethods(response);
        setAllowHeaders(response);
        setAllowCredentials(response);
        setMaxAge(response);
        setPreflightHeaders(response);
        ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
    } else {
        forbidden(ctx, request);
    }
}
 
Example #16
Source File: CorsHandler.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
    if (config.isCorsSupportEnabled() && e.getMessage() instanceof HttpRequest) {
        request = (HttpRequest) e.getMessage();
        if (isPreflightRequest(request)) {
            handlePreflight(ctx, request);
            return;
        }
        if (config.isShortCircuit() && !validateOrigin()) {
            forbidden(ctx, request);
            return;
        }
    }
    super.messageReceived(ctx, e);
}
 
Example #17
Source File: ShuffleHandler.java    From big-c with Apache License 2.0 5 votes vote down vote up
protected void populateHeaders(List<String> mapIds, String outputBaseStr,
    String user, int reduce, HttpRequest request, HttpResponse response,
    boolean keepAliveParam, Map<String, MapOutputInfo> mapOutputInfoMap)
    throws IOException {

  long contentLength = 0;
  for (String mapId : mapIds) {
    String base = outputBaseStr + mapId;
    MapOutputInfo outputInfo = getMapOutputInfo(base, mapId, reduce, user);
    if (mapOutputInfoMap.size() < mapOutputMetaInfoCacheSize) {
      mapOutputInfoMap.put(mapId, outputInfo);
    }
    // Index file
    Path indexFileName =
        lDirAlloc.getLocalPathToRead(base + "/file.out.index", conf);
    IndexRecord info =
        indexCache.getIndexInformation(mapId, reduce, indexFileName, user);
    ShuffleHeader header =
        new ShuffleHeader(mapId, info.partLength, info.rawLength, reduce);
    DataOutputBuffer dob = new DataOutputBuffer();
    header.write(dob);

    contentLength += info.partLength;
    contentLength += dob.getLength();
  }

  // Now set the response headers.
  setResponseHeaders(response, keepAliveParam, contentLength);
}
 
Example #18
Source File: HttpUpdateSettingsAction.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
@Override
protected HttpRequest createHttpRequest(URL url, UpdateSettingsRequest request) throws IOException {
    XContentBuilder builder = jsonBuilder();
    builder.startObject();
    request.settings().toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();
    String index = request.indices() != null ? "/" + String.join(",", request.indices()) : "" ;
    return newRequest(HttpMethod.PUT, url, index + "/_settings", builder.string());
}
 
Example #19
Source File: AuthHandler.java    From feeyo-hlsserver with Apache License 2.0 5 votes vote down vote up
private Map<String, Cookie> getCookies(HttpRequest request) {
	// 解析 Cookie
	Map<String, Cookie> cookies = new HashMap<String, Cookie>();
	List<String> allCookieHeaders = request.headers().getAll( HttpHeaders.Names.COOKIE );
	for (String aCookieHeader : allCookieHeaders) {
		Cookie c = ClientCookieDecoder.STRICT.decode(aCookieHeader);
		if (c != null) {
			cookies.put(c.name(), c);
		}
	}
	return cookies;
}
 
Example #20
Source File: HttpKeepAliveHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpRequest && isKeepAliveSupported) {
        ctx.setAttachment(e.getMessage());
    }
    super.messageReceived(ctx, e);
}
 
Example #21
Source File: HttpAppResolvingHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    //only set this on request - proceeding chunks will be routed on same outbound connection
    if (e.getMessage() instanceof HttpRequest) {
        HttpRequest request = (HttpRequest) e.getMessage();

        request.setHeader(ROUTE_HEADER, STATIC_ROUTE);
        LOG.debug("setting header {} to {}", ROUTE_HEADER, STATIC_ROUTE);

        request.setHeader("host", new URL(STATIC_ROUTE).getHost());
    }

    super.messageReceived(ctx, e);
}
 
Example #22
Source File: ServerTimingHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof HttpRequest) {
        this.context = timer.time();
        this.start = System.nanoTime();
    }

    super.messageReceived(ctx, e);
}
 
Example #23
Source File: HttpProxyHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, final MessageEvent message) throws Exception {
    final Channel inboundChannel = message.getChannel();

    try {
        if (message.getMessage() instanceof HttpRequest) {

            final HttpRequest request = (HttpRequest) message.getMessage();
            handleRequest(request, inboundChannel);

        } else if (message.getMessage() instanceof HttpChunk) {

            if (!isChunkedRequestsSupported) {
                LOG.warn("requests with chunked transfer encoding are not supported");
                inboundChannel.close();
                return;
            }

            final HttpChunk chunk = (HttpChunk) message.getMessage();
            handleChunk(chunk, inboundChannel);

        }
    } catch (IllegalRouteException e) {
        //TODO: do something better than dropping the connection when the route is bad
        inboundChannel.close();
        LOG.warn("dropped connection for bad route: {}", e.getRoute());
    }
}
 
Example #24
Source File: HttpResponseFrameworkHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    LOG.debug("attaching message: {}", e.getMessage().getClass().getSimpleName());
    if (e.getMessage() instanceof HttpRequest) {
        ctx.setAttachment(e.getMessage());
    }
    super.messageReceived(ctx, e);
}
 
Example #25
Source File: WebSocketChannelHandler.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private String getWebSocketLocation( HttpRequest req ) {
    String path = req.getUri();
    if ( path.equals( "/" ) ) {
        path = null;
    }
    if ( path != null ) {
        path = removeEnd( path, "/" );
    }
    String location =
            ( ssl ? "wss://" : "ws://" ) + req.getHeader( HttpHeaders.Names.HOST ) + ( path != null ? path : "" );
    logger.info( location );
    return location;
}
 
Example #26
Source File: WebSocketChannelHandler.java    From usergrid with Apache License 2.0 5 votes vote down vote up
private void sendHttpResponse( ChannelHandlerContext ctx, HttpRequest req, HttpResponse res ) {
    // Generate an error page if response status code is not OK (200).
    if ( res.getStatus().getCode() != 200 ) {
        res.setContent( ChannelBuffers.copiedBuffer( res.getStatus().toString(), CharsetUtil.UTF_8 ) );
        setContentLength( res, res.getContent().readableBytes() );
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.getChannel().write( res );
    if ( !isKeepAlive( req ) || ( res.getStatus().getCode() != 200 ) ) {
        f.addListener( ChannelFutureListener.CLOSE );
    }
}
 
Example #27
Source File: WebSocketChannelHandler.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived( ChannelHandlerContext ctx, MessageEvent e ) throws Exception {
    Object msg = e.getMessage();
    if ( msg instanceof HttpRequest ) {
        handleHttpRequest( ctx, ( HttpRequest ) msg );
    }
    else if ( msg instanceof WebSocketFrame ) {
        handleWebSocketFrame( ctx, ( WebSocketFrame ) msg );
    }
}
 
Example #28
Source File: ShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
protected void populateHeaders(List<String> mapIds, String outputBaseStr,
    String user, int reduce, HttpRequest request, HttpResponse response,
    boolean keepAliveParam, Map<String, MapOutputInfo> mapOutputInfoMap)
    throws IOException {

  long contentLength = 0;
  for (String mapId : mapIds) {
    String base = outputBaseStr + mapId;
    MapOutputInfo outputInfo = getMapOutputInfo(base, mapId, reduce, user);
    if (mapOutputInfoMap.size() < mapOutputMetaInfoCacheSize) {
      mapOutputInfoMap.put(mapId, outputInfo);
    }
    // Index file
    Path indexFileName =
        lDirAlloc.getLocalPathToRead(base + "/file.out.index", conf);
    TezIndexRecord info =
        indexCache.getIndexInformation(mapId, reduce, indexFileName, user);
    ShuffleHeader header =
        new ShuffleHeader(mapId, info.getPartLength(), info.getRawLength(), reduce);
    DataOutputBuffer dob = new DataOutputBuffer();
    header.write(dob);

    contentLength += info.getPartLength();
    contentLength += dob.getLength();
  }

  // Now set the response headers.
  setResponseHeaders(response, keepAliveParam, contentLength);
}
 
Example #29
Source File: TestShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
@Override
protected Shuffle getShuffle(final Configuration conf) {
  return new Shuffle(conf) {
    @Override
    protected void verifyRequest(String appid, ChannelHandlerContext ctx,
        HttpRequest request, HttpResponse response, URL requestUri)
        throws IOException {
      SocketChannel channel = (SocketChannel)(ctx.getChannel());
      socketKeepAlive = channel.getConfig().isKeepAlive();
    }
  };
}
 
Example #30
Source File: TestShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
public HttpRequest createMockHttpRequest() {
  HttpRequest mockHttpRequest = mock(HttpRequest.class);
  Mockito.doReturn(HttpMethod.GET).when(mockHttpRequest).getMethod();
  Mockito.doReturn(new DefaultHttpHeaders()).when(mockHttpRequest).headers();
  Mockito.doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      String uri = "/mapOutput?job=job_12345_1&dag=1&reduce=1";
      for (int i = 0; i < 100; i++)
        uri = uri.concat("&map=attempt_12345_1_m_" + i + "_0");
      return uri;
    }
  }).when(mockHttpRequest).getUri();
  return mockHttpRequest;
}