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);
	}
}