Java Code Examples for org.jboss.netty.handler.codec.http.HttpResponse

The following are top voted examples for showing how to use org.jboss.netty.handler.codec.http.HttpResponse. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: my-dev   File: WebSocketClientUpstreamHandler.java   Source Code and License 7 votes vote down vote up
private void handleHandshake(ChannelHandlerContext ctx, HttpResponse response)
        throws Exception {
    this.dump(response);
    boolean validStatus = response.getStatus().equals(SUCCESS);
    boolean validUpgrade = (response.getHeader(Names.UPGRADE) != null)
            && response.getHeader(Names.UPGRADE).equalsIgnoreCase(Values.WEBSOCKET);
    boolean validConnection = (response.getHeader(Names.CONNECTION) != null)
            && response.getHeader(Names.CONNECTION).equalsIgnoreCase(Values.UPGRADE);

    if (!validStatus || !validUpgrade || !validConnection) {
        throw new LinkException(response.getStatus().getCode(),
                String.format(Text.WS_HANDSHAKE_INVALID, response.getContent().readable()
                        ? response.getContent().toString(Charset.forName("UTF-8")) : ""));
    }

    this.handshaker.finishHandshake(ctx.getChannel(), response);
    if (this.haveHandler()) {
        this.getHandler().onConnect(this.createContext(response));
    }
}
 
Example 2
Project: traccar-service   File: PathAwayProtocolDecoder.java   Source Code and License 6 votes vote down vote up
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    HttpRequest request = (HttpRequest) msg;
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());

    DeviceSession deviceSession = getDeviceSession(
            channel, remoteAddress, decoder.getParameters().get("UserName").get(0));
    if (deviceSession == null) {
        return null;
    }

    Parser parser = new Parser(PATTERN, decoder.getParameters().get("LOC").get(0));
    if (!parser.matches()) {
        return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    position.setTime(parser.nextDateTime(Parser.DateTimeFormat.DMY_HMS));

    position.setValid(true);
    position.setLatitude(parser.nextDouble(0));
    position.setLongitude(parser.nextDouble(0));
    position.setAltitude(parser.nextDouble(0));
    position.setSpeed(parser.nextDouble(0));
    position.setCourse(parser.nextDouble(0));

    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        channel.write(response).addListener(ChannelFutureListener.CLOSE);
    }

    return position;
}
 
Example 3
Project: Elasticsearch   File: CorsHandler.java   Source Code and License 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 4
Project: Elasticsearch   File: CorsHandler.java   Source Code and License 6 votes vote down vote up
private boolean setOrigin(final HttpResponse response) {
    final String origin = request.headers().get(ORIGIN);
    if (!Strings.isNullOrEmpty(origin)) {
        if ("null".equals(origin) && config.isNullOriginAllowed()) {
            setAnyOrigin(response);
            return true;
        }
        if (config.isAnyOriginSupported()) {
            if (config.isCredentialsAllowed()) {
                echoRequestOrigin(response);
                setVaryHeader(response);
            } else {
                setAnyOrigin(response);
            }
            return true;
        }
        if (config.isOriginAllowed(origin)) {
            setOrigin(response, origin);
            setVaryHeader(response);
            return true;
        }
    }
    return false;
}
 
Example 5
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 6 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 6
Project: aliyun-oss-hadoop-fs   File: ShuffleHandler.java   Source Code and License 6 votes vote down vote up
protected void setResponseHeaders(HttpResponse response,
    boolean keepAliveParam, long contentLength) {
  if (!connectionKeepAliveEnabled && !keepAliveParam) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Setting connection close header...");
    }
    response.setHeader(HttpHeaders.CONNECTION, CONNECTION_CLOSE);
  } else {
    response.setHeader(HttpHeaders.CONTENT_LENGTH,
      String.valueOf(contentLength));
    response.setHeader(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE);
    response.setHeader(HttpHeaders.KEEP_ALIVE, "timeout="
        + connectionKeepAliveTimeOut);
    LOG.info("Content Length in shuffle : " + contentLength);
  }
}
 
Example 7
Project: big-c   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 6 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 8
Project: opentsdb-flume   File: LegacyHttpSource.java   Source Code and License 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
  try {
    final HttpRequest req = (HttpRequest) e.getMessage();
    if (req.getMethod().equals(HttpMethod.POST)) {
      doPost(ctx, e, req);
    } else if (req.getMethod().equals(HttpMethod.GET)) {
      doGet(ctx, e, req);
    } else {
      writeResponseAndClose(e, new DefaultHttpResponse(
              HttpVersion.HTTP_1_1,
              HttpResponseStatus.BAD_REQUEST));
    }
  } catch (Exception ex) {
    if (logger.isDebugEnabled())
      logger.debug("Failed to process message", ex);
    HttpResponse response = new DefaultHttpResponse(
            HttpVersion.HTTP_1_1,
            HttpResponseStatus.INTERNAL_SERVER_ERROR);
    response.setContent(
            ChannelBuffers.copiedBuffer(ex.getMessage().getBytes()));
    writeResponseAndClose(e, response);
  }
}
 
Example 9
Project: opentsdb-flume   File: LegacyHttpSource.java   Source Code and License 6 votes vote down vote up
private void doPost(ChannelHandlerContext ctx, MessageEvent e, HttpRequest req)
        throws IOException {

  final QueryStringDecoder decoded = new QueryStringDecoder(req.getUri());
  if (!decoded.getPath().equalsIgnoreCase("/write")) {
    writeResponseAndClose(e,
            new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND));
    return;
  }

  try {
    metricParser.parse(req);
  } catch (IllegalArgumentException iae) {
    logger.warn("Metric parser failed: " + iae.getMessage());
  }

  HttpResponse response = new DefaultHttpResponse(
          HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  response.setContent(ChannelBuffers.copiedBuffer(
          ("Seen events").getBytes()
  ));
  writeResponseAndClose(e, response);
}
 
Example 10
Project: Android-Airplay-Server   File: RaopRtspChallengeResponseHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt)
	throws Exception
{
	final HttpResponse resp = (HttpResponse)evt.getMessage();

	synchronized(this) {
		if (m_challenge != null) {
			try {
				/* Get appropriate response to challenge and
				 * add to the response base-64 encoded. XXX
				 */
				final String sig = Base64.encodePadded(getSignature());

				resp.setHeader(HeaderSignature, sig);
			}
			finally {
				/* Forget last challenge */
				m_challenge = null;
				m_localAddress = null;
			}
		}
	}

	super.writeRequested(ctx, evt);
}
 
Example 11
Project: elasticsearch-client-http   File: HttpClient.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpContext<R, T> httpContext = httpContextMap.get(ctx.getChannel());
    if (httpContext == null) {
        throw new IllegalStateException("no context for channel?");
    }
    try {
        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse httpResponse = (HttpResponse) e.getMessage();
            HttpAction<R, T> action = httpContext.getHttpAction();
            ActionListener<T> listener = httpContext.getListener();
            httpContext.setHttpResponse(httpResponse);
            if (httpResponse.getContent().readable() && listener != null && action != null) {
                listener.onResponse(action.createResponse(httpContext));
            }
        }
    } finally {
        ctx.getChannel().close();
        httpContextMap.remove(ctx.getChannel());
    }
}
 
Example 12
Project: elasticsearch-client-http   File: HttpSearchAction.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected SearchResponse createResponse(HttpContext<SearchRequest, SearchResponse> httpContext) throws IOException {
    if (httpContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpContext.getHttpResponse();
    logger.info("{}", httpResponse.getContent().toString(CharsetUtil.UTF_8));
    BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
    Map<String, Object> map = JsonXContent.jsonXContent.createParser(ref).map();

    logger.info("{}", map);

    InternalSearchResponse internalSearchResponse = parseInternalSearchResponse(map);
    String scrollId = (String) map.get(SCROLL_ID);
    int totalShards = 0;
    int successfulShards = 0;
    if (map.containsKey(SHARDS)) {
        Map<String, ?> shards = (Map<String, ?>) map.get(SHARDS);
        totalShards = shards.containsKey(TOTAL) ? (Integer) shards.get(TOTAL) : -1;
        successfulShards = shards.containsKey(SUCCESSFUL) ? (Integer) shards.get(SUCCESSFUL) : -1;
    }
    int tookInMillis = map.containsKey(TOOK) ? (Integer) map.get(TOOK) : -1;
    ShardSearchFailure[] shardFailures = null;
    return new SearchResponse(internalSearchResponse, scrollId, totalShards, successfulShards, tookInMillis, shardFailures);
}
 
Example 13
Project: Camel   File: DefaultNettyHttpBinding.java   Source Code and License 6 votes vote down vote up
@Override
public void populateCamelHeaders(HttpResponse response, Map<String, Object> headers, Exchange exchange, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("populateCamelHeaders: {}", response);

    headers.put(Exchange.HTTP_RESPONSE_CODE, response.getStatus().getCode());
    headers.put(Exchange.HTTP_RESPONSE_TEXT, response.getStatus().getReasonPhrase());

    for (String name : response.headers().names()) {
        // mapping the content-type
        if (name.toLowerCase().equals("content-type")) {
            name = Exchange.CONTENT_TYPE;
        }
        // add the headers one by one, and use the header filter strategy
        List<String> values = response.headers().getAll(name);
        Iterator<?> it = ObjectHelper.createIterator(values);
        while (it.hasNext()) {
            Object extracted = it.next();
            LOG.trace("HTTP-header: {}", extracted);
            if (headerFilterStrategy != null
                    && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, exchange)) {
                NettyHttpHelper.appendHeader(headers, name, extracted);
            }
        }
    }
}
 
Example 14
Project: Camel   File: HttpServerMultiplexChannelHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent messageEvent) throws Exception {
    // store request, as this channel handler is created per pipeline
    HttpRequest request = (HttpRequest) messageEvent.getMessage();

    LOG.debug("Message received: {}", request);

    HttpServerChannelHandler handler = getHandler(request);
    if (handler != null) {
        // store handler as attachment
        ctx.setAttachment(handler);
        handler.messageReceived(ctx, messageEvent);
    } else {
        // this resource is not found, so send empty response back
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND);
        response.headers().set(Exchange.CONTENT_TYPE, "text/plain");
        response.headers().set(Exchange.CONTENT_LENGTH, 0);
        response.setContent(ChannelBuffers.copiedBuffer(new byte[]{}));
        messageEvent.getChannel().write(response).syncUninterruptibly();
        // close the channel after send error message
        messageEvent.getChannel().close();
    }
}
 
Example 15
Project: Camel   File: NettyHttpProducer.java   Source Code and License 6 votes vote down vote up
@Override
public void done(boolean doneSync) {
    try {
        NettyHttpMessage nettyMessage = exchange.hasOut() ? exchange.getOut(NettyHttpMessage.class) : exchange.getIn(NettyHttpMessage.class);
        if (nettyMessage != null) {
            HttpResponse response = nettyMessage.getHttpResponse();
            if (response != null) {
                // the actual url is stored on the IN message in the getRequestBody method as its accessed on-demand
                String actualUrl = exchange.getIn().getHeader(Exchange.HTTP_URL, String.class);
                int code = response.getStatus() != null ? response.getStatus().getCode() : -1;
                log.debug("Http responseCode: {}", code);

                // if there was a http error code then check if we should throw an exception
                boolean ok = NettyHttpHelper.isStatusCodeOk(code, configuration.getOkStatusCodeRange());
                if (!ok && getConfiguration().isThrowExceptionOnFailure()) {
                    // operation failed so populate exception to throw
                    Exception cause = NettyHttpHelper.populateNettyHttpOperationFailedException(exchange, actualUrl, response, code, getConfiguration().isTransferException());
                    exchange.setException(cause);
                }
            }
        }
    } finally {
        // ensure we call the delegated callback
        callback.done(doneSync);
    }
}
 
Example 16
Project: Camel   File: NettyHttpConverter.java   Source Code and License 6 votes vote down vote up
/**
 * A fallback converter that allows us to easily call Java beans and use the raw Netty {@link HttpRequest} as parameter types.
 */
@FallbackConverter
public static Object convertToHttpResponse(Class<?> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
    // if we want to covert to convertToHttpResponse
    if (value != null && HttpResponse.class.isAssignableFrom(type)) {

        // okay we may need to cheat a bit when we want to grab the HttpRequest as its stored on the NettyHttpMessage
        // so if the message instance is a NettyHttpMessage and its body is the value, then we can grab the
        // HttpRequest from the NettyHttpMessage
        NettyHttpMessage msg;
        if (exchange.hasOut()) {
            msg = exchange.getOut(NettyHttpMessage.class);
        } else {
            msg = exchange.getIn(NettyHttpMessage.class);
        }
        if (msg != null && msg.getBody() == value) {
            return msg.getHttpResponse();
        }
    }

    return null;
}
 
Example 17
Project: Camel   File: NettyUseRawHttpResponseTest.java   Source Code and License 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("netty-http:http://0.0.0.0:{{port}}/foo")
                .to("mock:input")
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
                        response.setContent(ChannelBuffers.copiedBuffer("Bye World".getBytes()));
                        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 9);

                        exchange.getOut().setBody(response);
                    }
                });
        }
    };
}
 
Example 18
Project: Camel   File: NettyHttpProducerSimpleTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testHttpSimpleExchange() throws Exception {
    getMockEndpoint("mock:input").expectedBodiesReceived("Hello World");

    Exchange out = template.request("netty-http:http://localhost:{{port}}/foo", new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody("Hello World");
        }
    });
    assertNotNull(out);
    assertTrue(out.hasOut());

    NettyHttpMessage response = out.getOut(NettyHttpMessage.class);
    assertNotNull(response);
    assertEquals(200, response.getHttpResponse().getStatus().getCode());

    // we can also get the response as body
    HttpResponse body = out.getOut().getBody(HttpResponse.class);
    assertNotNull(body);
    assertEquals(200, body.getStatus().getCode());

    assertMockEndpointsSatisfied();
}
 
Example 19
Project: hadoop-2.6.0-cdh5.4.3   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 6 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 20
Project: finagle-java-example-master-slave   File: VideoCache.java   Source Code and License 6 votes vote down vote up
public VideoCache(ExecutorService pool, PropertyPlaceholder propsHolder, Service<HttpRequest, HttpResponse> client) {
    this.pool = pool;
    this.client = client;
    this.propsHolder = propsHolder;
    propsHolder.generatePropertyMap();
    
    this.productReader = new ProductFileReader(propsHolder.getPropertyMap().get("campaignProductListLocation"));
   
    JedisPoolConfig jedisConfig = new JedisPoolConfig();
    jedisConfig.setMaxTotal(Integer.parseInt(propsHolder.getPropertyMap().get("maxJedisPoolSize")));
    jedisConfig.setTestOnBorrow(true);
    jedisConfig.setLifo(false);
    String redisHost = propsHolder.getPropertyMap().get("redisServer");
    int redisPort = Integer.parseInt(propsHolder.getPropertyMap().get("redisPort"));
    this.jedisPool = new JedisPool(jedisConfig, redisHost, redisPort);
}
 
Example 21
Project: FlexMap   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 6 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 22
Project: AirSpeakerMobile   File: RaopRtspChallengeResponseHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent evt)
	throws Exception
{
	final HttpResponse resp = (HttpResponse)evt.getMessage();

	synchronized(this) {
		if (m_challenge != null) {
			try {
				/* Get appropriate response to challenge and
				 * add to the response base-64 encoded. XXX
				 */
				final String sig = Base64.encodePadded(getSignature());

				resp.setHeader(HeaderSignature, sig);
			}
			finally {
				/* Forget last challenge */
				m_challenge = null;
				m_localAddress = null;
			}
		}
	}

	super.writeRequested(ctx, evt);
}
 
Example 23
Project: hops   File: ShuffleHandler.java   Source Code and License 6 votes vote down vote up
protected void setResponseHeaders(HttpResponse response,
    boolean keepAliveParam, long contentLength) {
  if (!connectionKeepAliveEnabled && !keepAliveParam) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Setting connection close header...");
    }
    response.setHeader(HttpHeaders.CONNECTION, CONNECTION_CLOSE);
  } else {
    response.setHeader(HttpHeaders.CONTENT_LENGTH,
      String.valueOf(contentLength));
    response.setHeader(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE);
    response.setHeader(HttpHeaders.KEEP_ALIVE, "timeout="
        + connectionKeepAliveTimeOut);
    LOG.info("Content Length in shuffle : " + contentLength);
  }
}
 
Example 24
Project: trap   File: WebServerSocketHandler.java   Source Code and License 6 votes vote down vote up
private static 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 25
Project: rest4j   File: RAPClientCodec.java   Source Code and License 6 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg)
        throws Exception
{
  HttpResponse nettyResponse = (HttpResponse) msg;

  RestResponseBuilder builder = new RestResponseBuilder();

  HttpResponseStatus status = nettyResponse.getStatus();
  builder.setStatus(status.getCode());

  for (Map.Entry<String, String> e : nettyResponse.getHeaders())
  {
    builder.unsafeAddHeaderValue(e.getKey(), e.getValue());
  }

  ChannelBuffer buf = nettyResponse.getContent();
  byte[] array = new byte[buf.readableBytes()];
  buf.readBytes(array);
  builder.setEntity(array);

  return builder.build();
}
 
Example 26
Project: rest4j   File: RAPServerCodec.java   Source Code and License 6 votes vote down vote up
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg)
        throws Exception
{
  RestResponse response = (RestResponse) msg;

  HttpResponse nettyResponse =
      new DefaultHttpResponse(HttpVersion.HTTP_1_1,
                              HttpResponseStatus.valueOf(response.getStatus()));

  for (Map.Entry<String, String> e : response.getHeaders().entrySet())
  {
    nettyResponse.setHeader(e.getKey(), e.getValue());
  }
  final ByteString entity = response.getEntity();
  ChannelBuffer buf = ChannelBuffers.wrappedBuffer(entity.asByteBuffer());
  nettyResponse.setContent(buf);
  nettyResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, entity.length());

  return nettyResponse;
}
 
Example 27
Project: netty-servlet   File: HttpServerHandler.java   Source Code and License 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 28
Project: incubator-twill   File: TrackerService.java   Source Code and License 6 votes vote down vote up
private void writeResponse(MessageEvent e) {
  HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
  response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");

  ChannelBuffer content = ChannelBuffers.dynamicBuffer();
  Writer writer = new OutputStreamWriter(new ChannelBufferOutputStream(content), CharsetUtil.UTF_8);
  reportAdapter.toJson(report.get(), writer);
  try {
    writer.close();
  } catch (IOException e1) {
    LOG.error("error writing resource report", e1);
  }
  response.setContent(content);
  ChannelFuture future = e.getChannel().write(response);
  future.addListener(ChannelFutureListener.CLOSE);
}
 
Example 29
Project: wifidogAuthServer   File: HttpHandler.java   Source Code and License 6 votes vote down vote up
/**
 * return login page,if user & password is error.return error tips!
 * */
private HttpResponse returnRegeditPage(ChannelHandlerContext ctx, QueryStringDecoder content,String tips) {
	HttpResponse response;
	String responseContent = ReadAll.readAll("web/regedit.html", "utf-8");
	responseContent = responseContent.replaceAll("<<param.gw_address>>",HttpParameterHelper.getParameters(content, "gw_address"));
	responseContent = responseContent.replaceAll("<<param.gw_port>>",HttpParameterHelper.getParameters(content, "gw_port"));
	responseContent = responseContent.replaceAll("<<param.gw_id>>",HttpParameterHelper.getParameters(content, "gw_id"));
	responseContent = responseContent.replaceAll("<<param.url>>",HttpParameterHelper.getParameters(content, "url"));
	
	if(tips==null){
		responseContent = responseContent.replaceAll("<<showtips>>","");
	}else{
		responseContent = responseContent.replaceAll("<<showtips>>","<input type='button' onclick='return;' class='get_btn' value='"+tips+"'>");
	}
	
	response = sendPrepare(ctx, responseContent);
	return response;
}
 
Example 30
Project: wifidogAuthServer   File: HttpHandler.java   Source Code and License 6 votes vote down vote up
/**
 * return login page,if user & password is error.return error tips!
 * */
private HttpResponse returnLoginPage(ChannelHandlerContext ctx, QueryStringDecoder content,String tips) {
	HttpResponse response;
	String responseContent = ReadAll.readAll("web/login.html", "utf-8");
	responseContent = responseContent.replaceAll("<<param.gw_address>>",HttpParameterHelper.getParameters(content, "gw_address"));
	responseContent = responseContent.replaceAll("<<param.gw_port>>",HttpParameterHelper.getParameters(content, "gw_port"));
	responseContent = responseContent.replaceAll("<<param.gw_id>>",HttpParameterHelper.getParameters(content, "gw_id"));
	responseContent = responseContent.replaceAll("<<param.url>>",HttpParameterHelper.getParameters(content, "url"));
	
	if(tips==null){
		responseContent = responseContent.replaceAll("<<showtips>>","");
	}else{
		responseContent = responseContent.replaceAll("<<showtips>>","<input type='button' onclick='return;' class='get_btn' value='"+tips+"'>");
	}
	
	response = sendPrepare(ctx, responseContent);
	return response;
}
 
Example 31
Project: hadoop-on-lustre2   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 6 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 32
Project: java-test-demo   File: HttpServerHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
        throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();
    String uri = request.getUri();
    
    System.out.println("uri:" + uri);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    ChannelBuffer buffer = new DynamicChannelBuffer(2048);
    buffer.writeBytes("hello!! 你好".getBytes("UTF-8"));
    response.setContent(buffer);
    response.setHeader("Content-Type", "text/html; charset=UTF-8");
    response.setHeader("Content-Length", response.getContent().writerIndex());
    Channel ch = e.getChannel();
    // Write the initial line and the header.
    ch.write(response);
    ch.disconnect();
    ch.close();

}
 
Example 33
Project: elasticsearch-helper   File: HttpInvoker.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpInvocationContext<Request, Response> httpInvocationContext = contexts.get(ctx.getChannel());
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no context for channel?");
    }
    try {
        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse httpResponse = (HttpResponse) e.getMessage();
            HttpAction<Request, Response> action = httpInvocationContext.getHttpAction();
            ActionListener<Response> listener = httpInvocationContext.getListener();
            httpInvocationContext.httpResponse = httpResponse;
            if (httpResponse.getContent().readable() && listener != null && action != null) {
                listener.onResponse(action.createResponse(httpInvocationContext));
            }
        }
    } finally {
        ctx.getChannel().close();
        contexts.remove(ctx.getChannel());
    }
}
 
Example 34
Project: elasticsearch-helper   File: HttpElasticsearchClient.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpInvocationContext<Request, Response> httpInvocationContext = contextMap.get(ctx.getChannel());
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no context for channel?");
    }
    try {
        if (e.getMessage() instanceof HttpResponse) {
            HttpResponse httpResponse = (HttpResponse) e.getMessage();
            HttpAction<Request, Response> action = httpInvocationContext.getHttpAction();
            ActionListener<Response> listener = httpInvocationContext.getListener();
            httpInvocationContext.httpResponse = httpResponse;
            if (httpResponse.getContent().readable() && listener != null && action != null) {
                listener.onResponse(action.createResponse(httpInvocationContext));
            }
        }
    } finally {
        ctx.getChannel().close();
        contextMap.remove(ctx.getChannel());
    }
}
 
Example 35
Project: elasticsearch-helper   File: HttpRefreshIndexAction.java   Source Code and License 6 votes vote down vote up
@Override
protected RefreshResponse createResponse(HttpInvocationContext<RefreshRequest,RefreshResponse> httpInvocationContext) {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    try {
        BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
        Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
        logger.info("{}", map);
        //  RefreshResponse(int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) {
        return new RefreshResponse();
    } catch (IOException e) {
        //
    }
    return null;
}
 
Example 36
Project: elasticsearch-helper   File: HttpCreateIndexAction.java   Source Code and License 6 votes vote down vote up
@Override
protected CreateIndexResponse createResponse(HttpInvocationContext<CreateIndexRequest,CreateIndexResponse> httpInvocationContext) {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    try {
        BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
        Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
        boolean acknowledged = map.containsKey("acknowledged") ? (Boolean)map.get("acknowledged") : false;
        return new CreateIndexResponse(acknowledged);
    } catch (IOException e) {
        //
    }
    return null;
}
 
Example 37
Project: elasticsearch-helper   File: HttpSearchAction.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected SearchResponse createResponse(HttpInvocationContext<SearchRequest,SearchResponse> httpInvocationContext) throws IOException {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    logger.info("{}", httpResponse.getContent().toString(CharsetUtil.UTF_8));
    BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
    Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();

    logger.info("{}", map);

    InternalSearchResponse internalSearchResponse = parseInternalSearchResponse(map);
    String scrollId = (String)map.get(SCROLL_ID);
    int totalShards = 0;
    int successfulShards = 0;
    if (map.containsKey(SHARDS)) {
        Map<String,?> shards = (Map<String,?>)map.get(SHARDS);
        totalShards =  shards.containsKey(TOTAL) ? (Integer)shards.get(TOTAL) : -1;
        successfulShards =  shards.containsKey(SUCCESSFUL) ? (Integer)shards.get(SUCCESSFUL) : -1;
    }
    int tookInMillis = map.containsKey(TOOK) ? (Integer)map.get(TOOK) : -1;
    ShardSearchFailure[] shardFailures = parseShardFailures(map);
    return new SearchResponse(internalSearchResponse, scrollId, totalShards, successfulShards, tookInMillis, shardFailures);
}
 
Example 38
Project: elasticsearch-helper   File: HttpBulkAction.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected BulkResponse createResponse(HttpInvocationContext<BulkRequest,BulkResponse> httpInvocationContext) {
    if (httpInvocationContext == null) {
        throw new IllegalStateException("no http context");
    }
    HttpResponse httpResponse = httpInvocationContext.getHttpResponse();
    try {
        BytesReference ref = new ChannelBufferBytesReference(httpResponse.getContent());
        Map<String,Object> map = JsonXContent.jsonXContent.createParser(ref).map();
        long tookInMillis = map.containsKey("took") ? (Integer)map.get("took") : -1L;
        BulkItemResponse[] responses = parseItems((List<Map<String,?>>)map.get("items"));
        return new BulkResponse(responses, tookInMillis);
    } catch (IOException e) {
        //
    }
    return null;
}
 
Example 39
Project: rtsp_multicast_pfc   File: ClientRTSP.java   Source Code and License 6 votes vote down vote up
/**
 * Se ejecutará cuando se reciba un response despues de enviar un DESCRIBE
 * Comprobará que todo es correcto, y si es así enviará una petición de SETUP
 * @param response
 */
public void describeResponse(HttpResponse response) {
	try {
		checkCseq(response);

		ChannelBuffer content = response.getContent();

		checkSDP(response);

		parseSDP(content);

		//Ahora enviamos el setup del primer stream y lo sacamos de la lista
		if(!streamsSetup.isEmpty()) {
			String stream = streamsSetup.get(0);
			streamsSetup.remove(0);

			sendSetup(getMedia() + "/" + stream);
		}

	} catch (Exception e) {
		createNotify("ERROR DESCRIBE RESPONSE: " + e.getMessage(),false);
	}
}
 
Example 40
Project: rtsp_multicast_pfc   File: ClientRTSP.java   Source Code and License 6 votes vote down vote up
/**
 * Se ejecutará cuando se reciba un response despues de enviar un PLAY
 * Comprobará que todo es correcto, y si es así enviará una petición de PLAY
 * si es que quedan mas stream por los que enviar PLAY, o se notificará
 * a los observadores de que ya se puede reproducir el media en el caso de que
 * fuera el último/único stream de PLAY que se esperaba.
 * @param response
 */
public void playResponse(HttpResponse response) {

	logger.trace("RESPUESTA PLAY RECIBIDA");
	try {

		if(!checkCseq(response)) {
			logger.error("error cseq");
			return;
		}

		if(!checkSession(response)){
			logger.error("error session");
			return;
		}

		createNotify("PLAY!",true);	

	}catch(Exception e) {
		createNotify("Exception setupResponse: " + e.getMessage(),false);
	}
}
 
Example 41
Project: rtsp_multicast_pfc   File: ClientRTSP.java   Source Code and License 6 votes vote down vote up
/**
 * Dado un HttpResponse, comprobará que trae la cabecera CSeq y que 
 * esta es correcta. 
 * Devolverá un booleano indicando si es verdadera, en caso contrario
 * lanzará una excepción que deberá ser controlada desde fuera indicando
 * el error.
 * 
 * @param response
 * @return
 * @throws Exception
 */
private boolean checkCseq(HttpResponse response) throws Exception {

	int cSeq_rec;
	String str_cSeq;

	str_cSeq = response.getHeader("CSeq");

	if(str_cSeq==null){
		throw new Exception("Response not contains CSeq header");
	}

	try {
		cSeq_rec = Integer.parseInt(str_cSeq);
	}
	catch(Exception e) {
		throw new Exception("CSeq header must be a number");
	}

	if(cSeq_rec != this.getcSeq()) {
		throw new Exception("CSeq not continue the order");
	}

	setcSeq(cSeq_rec +1 );
	return true;	
}
 
Example 42
Project: rtsp_multicast_pfc   File: ClientRTSP.java   Source Code and License 6 votes vote down vote up
/**
 * Dado un HttpResponse comprobará que la sesión es la esperada.
 * En caso de no tener sesión se asignará la que viene en el response, 
 * en caso contrario comprobará que las sesiones coinciden.
 * @param response
 * @return
 */
private boolean checkSession(HttpResponse response) {

	String sessionAux = response.getHeader("Session");

	if(session==null) {
		session=sessionAux;
		return true;
	}else if(session.equals(sessionAux)) {
		return true;	
	}else {
		return false;
	}


}
 
Example 43
Project: zuul-netty   File: HttpResponseFrameworkHandler.java   Source Code and License 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 44
Project: tez   File: ShuffleHandler.java   Source Code and License 6 votes vote down vote up
protected void populateHeaders(List<String> mapIds, String jobId,
                               String dagId, String user,
                               Range reduceRange,
                               HttpResponse response,
                               boolean keepAliveParam,
                               Map<String, MapOutputInfo> mapOutputInfoMap)
    throws IOException {

  long contentLength = 0;
  // Content-Length only needs calculated for keep-alive keep alive
  if (connectionKeepAliveEnabled || keepAliveParam) {
    contentLength = getContentLength(mapIds, jobId, dagId, user, reduceRange, mapOutputInfoMap);
  }

  // Now set the response headers.
  setResponseHeaders(response, keepAliveParam, contentLength);
}
 
Example 45
Project: traccar-service   File: DmtHttpProtocolDecoder.java   Source Code and License 5 votes vote down vote up
private void sendResponse(Channel channel, HttpResponseStatus status) {
    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
        response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
        channel.write(response);
    }
}
 
Example 46
Project: traccar-service   File: PiligrimProtocolDecoder.java   Source Code and License 5 votes vote down vote up
private void sendResponse(Channel channel, String message) {
    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(
                HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        response.setContent(ChannelBuffers.copiedBuffer(
                ByteOrder.BIG_ENDIAN, message, StandardCharsets.US_ASCII));
        channel.write(response);
    }
}
 
Example 47
Project: traccar-service   File: OsmAndProtocolDecoder.java   Source Code and License 5 votes vote down vote up
private void sendResponse(Channel channel, HttpResponseStatus status) {
    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
        response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
        channel.write(response);
    }
}
 
Example 48
Project: traccar-service   File: Mta6ProtocolDecoder.java   Source Code and License 5 votes vote down vote up
private void sendResponse(Channel channel, short packetId, short packetCount) {
    HttpResponse response = new DefaultHttpResponse(
            HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

    ChannelBuffer begin = ChannelBuffers.copiedBuffer("#ACK#", StandardCharsets.US_ASCII);
    ChannelBuffer end = ChannelBuffers.directBuffer(3);
    end.writeByte(packetId);
    end.writeByte(packetCount);
    end.writeByte(0);

    response.setContent(ChannelBuffers.wrappedBuffer(begin, end));
    channel.write(response);
}
 
Example 49
Project: traccar-service   File: OwnTracksProtocolDecoder.java   Source Code and License 5 votes vote down vote up
private void sendResponse(Channel channel, HttpResponseStatus status) {
    if (channel != null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
        response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
        channel.write(response);
    }
}
 
Example 50
Project: Elasticsearch   File: CorsHandler.java   Source Code and License 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 51
Project: Elasticsearch   File: CorsHandler.java   Source Code and License 5 votes vote down vote up
private void setAllowMethods(final HttpResponse response) {
    Set<String> strMethods = new HashSet<>();
    for (HttpMethod method : config.allowedRequestMethods()) {
        strMethods.add(method.getName().trim());
    }
    response.headers().set(ACCESS_CONTROL_ALLOW_METHODS, strMethods);
}
 
Example 52
Project: hadoop   File: ShuffleHandler.java   Source Code and License 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 53
Project: hadoop   File: ShuffleHandler.java   Source Code and License 5 votes vote down vote up
protected void setResponseHeaders(HttpResponse response,
    boolean keepAliveParam, long contentLength) {
  if (!connectionKeepAliveEnabled && !keepAliveParam) {
    LOG.info("Setting connection close header...");
    response.setHeader(HttpHeaders.CONNECTION, CONNECTION_CLOSE);
  } else {
    response.setHeader(HttpHeaders.CONTENT_LENGTH,
      String.valueOf(contentLength));
    response.setHeader(HttpHeaders.CONNECTION, HttpHeaders.KEEP_ALIVE);
    response.setHeader(HttpHeaders.KEEP_ALIVE, "timeout="
        + connectionKeepAliveTimeOut);
    LOG.info("Content Length in shuffle : " + contentLength);
  }
}
 
Example 54
Project: hadoop   File: ShuffleHandler.java   Source Code and License 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.setHeader(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.setHeader(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 55
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  byte[] bytes = EXP_DATE.getBytes();
  ChannelBuffer cbuffer = ChannelBuffers.buffer(bytes.length);
  cbuffer.writeBytes(bytes);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(bytes.length));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 56
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, 
      HttpResponseStatus.METHOD_NOT_ALLOWED);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 57
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License 5 votes vote down vote up
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 58
Project: aliyun-oss-hadoop-fs   File: ShuffleHandler.java   Source Code and License 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 59
Project: aliyun-oss-hadoop-fs   File: ShuffleHandler.java   Source Code and License 5 votes vote down vote up
protected void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  response.setHeader(ShuffleHeader.HTTP_HEADER_NAME,
      ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  response.setHeader(ShuffleHeader.HTTP_HEADER_VERSION,
      ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  response.setContent(
    ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 60
Project: aliyun-oss-hadoop-fs   File: TestShuffleHandler.java   Source Code and License 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();
    }
  };
}