Java Code Examples for org.jboss.netty.util.CharsetUtil

The following are top voted examples for showing how to use org.jboss.netty.util.CharsetUtil. 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: 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 2
Project: ACaZoo   File: CBUtil.java   Source Code and License 6 votes vote down vote up
private static String readString(ChannelBuffer cb, int length)
{
    try
    {
        String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8);
        cb.readerIndex(cb.readerIndex() + length);
        return str;
    }
    catch (IllegalStateException e)
    {
        // That's the way netty encapsulate a CCE
        if (e.getCause() instanceof CharacterCodingException)
            throw new ProtocolException("Cannot decode string as UTF8");
        else
            throw e;
    }
}
 
Example 3
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 4
Project: Cassandra-Wasef   File: CBUtil.java   Source Code and License 6 votes vote down vote up
private static String readString(ChannelBuffer cb, int length)
{
    try
    {
        String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8);
        cb.readerIndex(cb.readerIndex() + length);
        return str;
    }
    catch (IllegalStateException e)
    {
        // That's the way netty encapsulate a CCE
        if (e.getCause() instanceof CharacterCodingException)
            throw new ProtocolException("Cannot decode string as UTF8");
        else
            throw e;
    }
}
 
Example 5
Project: simple-netty-source   File: ChannelBuffers.java   Source Code and License 6 votes vote down vote up
static ByteBuffer encodeString(CharBuffer src, Charset charset) {
    final CharsetEncoder encoder = CharsetUtil.getEncoder(charset);
    final ByteBuffer dst = ByteBuffer.allocate(
            (int) ((double) src.remaining() * encoder.maxBytesPerChar()));
    try {
        CoderResult cr = encoder.encode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = encoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    dst.flip();
    return dst;
}
 
Example 6
Project: simple-netty-source   File: ChannelBuffers.java   Source Code and License 6 votes vote down vote up
static String decodeString(ByteBuffer src, Charset charset) {
    final CharsetDecoder decoder = CharsetUtil.getDecoder(charset);
    final CharBuffer dst = CharBuffer.allocate(
            (int) ((double) src.remaining() * decoder.maxCharsPerByte()));
    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = decoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    return dst.flip().toString();
}
 
Example 7
Project: cassandra-cqlMod   File: CBUtil.java   Source Code and License 6 votes vote down vote up
private static String readString(ChannelBuffer cb, int length)
{
    try
    {
        String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8);
        cb.readerIndex(cb.readerIndex() + length);
        return str;
    }
    catch (IllegalStateException e)
    {
        // That's the way netty encapsulate a CCE
        if (e.getCause() instanceof CharacterCodingException)
            throw new ProtocolException("Cannot decode string as UTF8");
        else
            throw e;
    }
}
 
Example 8
Project: wso2-cassandra   File: CBUtil.java   Source Code and License 6 votes vote down vote up
private static String readString(ChannelBuffer cb, int length)
{
    try
    {
        String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8);
        cb.readerIndex(cb.readerIndex() + length);
        return str;
    }
    catch (IllegalStateException e)
    {
        // That's the way netty encapsulate a CCE
        if (e.getCause() instanceof CharacterCodingException)
            throw new ProtocolException("Cannot decode string as UTF8");
        else
            throw e;
    }
}
 
Example 9
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 10
Project: tools-idea   File: Responses.java   Source Code and License 6 votes vote down vote up
private static void sendStatus(HttpResponse response, @Nullable HttpRequest request, Channel channel, @Nullable String description) {
  response.setHeader(CONTENT_TYPE, "text/html");
  if (request == null || request.getMethod() != HttpMethod.HEAD) {
    String message = response.getStatus().toString();

    StringBuilder builder = new StringBuilder();
    builder.append("<!doctype html><title>").append(message).append("</title>").append("<h1 style=\"text-align: center\">").append(message).append("</h1>");
    if (description != null) {
      builder.append("<p>").append(description).append("</p>");
    }
    builder.append("<hr/><p style=\"text-align: center\">").append(StringUtil.notNullize(getServerHeaderValue(), "")).append("</p>");

    response.setContent(ChannelBuffers.copiedBuffer(builder, CharsetUtil.UTF_8));
  }
  send(response, channel, request);
}
 
Example 11
Project: cassandra-1.2.16   File: CBUtil.java   Source Code and License 6 votes vote down vote up
private static String readString(ChannelBuffer cb, int length)
{
    try
    {
        String str = cb.toString(cb.readerIndex(), length, CharsetUtil.UTF_8);
        cb.readerIndex(cb.readerIndex() + length);
        return str;
    }
    catch (IllegalStateException e)
    {
        // That's the way netty encapsulate a CCE
        if (e.getCause() instanceof CharacterCodingException)
            throw new ProtocolException("Cannot decode string as UTF8");
        else
            throw e;
    }
}
 
Example 12
Project: andy   File: ChannelBuffers.java   Source Code and License 6 votes vote down vote up
static ByteBuffer encodeString(CharBuffer src, Charset charset) {
    final CharsetEncoder encoder = CharsetUtil.getEncoder(charset);
    final ByteBuffer dst = ByteBuffer.allocate(
            (int) ((double) src.remaining() * encoder.maxBytesPerChar()));
    try {
        CoderResult cr = encoder.encode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = encoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    dst.flip();
    return dst;
}
 
Example 13
Project: andy   File: ChannelBuffers.java   Source Code and License 6 votes vote down vote up
static String decodeString(ByteBuffer src, Charset charset) {
    final CharsetDecoder decoder = CharsetUtil.getDecoder(charset);
    final CharBuffer dst = CharBuffer.allocate(
            (int) ((double) src.remaining() * decoder.maxCharsPerByte()));
    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = decoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    return dst.flip().toString();
}
 
Example 14
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 15
Project: android-netty   File: ChannelBuffers.java   Source Code and License 6 votes vote down vote up
static ByteBuffer encodeString(CharBuffer src, Charset charset) {
    final CharsetEncoder encoder = CharsetUtil.getEncoder(charset);
    final ByteBuffer dst = ByteBuffer.allocate(
            (int) ((double) src.remaining() * encoder.maxBytesPerChar()));
    try {
        CoderResult cr = encoder.encode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = encoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    dst.flip();
    return dst;
}
 
Example 16
Project: android-netty   File: ChannelBuffers.java   Source Code and License 6 votes vote down vote up
static String decodeString(ByteBuffer src, Charset charset) {
    final CharsetDecoder decoder = CharsetUtil.getDecoder(charset);
    final CharBuffer dst = CharBuffer.allocate(
            (int) ((double) src.remaining() * decoder.maxCharsPerByte()));
    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
        cr = decoder.flush(dst);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new IllegalStateException(x);
    }
    return dst.flip().toString();
}
 
Example 17
Project: elasterix   File: ByePacket.java   Source Code and License 6 votes vote down vote up
public static ByePacket decode(ChannelBuffer buffer, boolean hasPadding, byte innerBlocks, int length) {
    ByePacket packet = new ByePacket();
    int read = 0;
    for (int i = 0; i < innerBlocks; i++) {
        packet.addSsrc(buffer.readUnsignedInt());
        read += 4;
    }

    // Length is written in 32bit words, not octet count.
    int lengthInOctets = (length * 4);
    if (read < lengthInOctets) {
        byte[] reasonBytes = new byte[buffer.readUnsignedByte()];
        buffer.readBytes(reasonBytes);
        packet.reasonForLeaving = new String(reasonBytes, CharsetUtil.UTF_8);
        read += (1 + reasonBytes.length);
        if (read < lengthInOctets) {
            // Skip remaining bytes (used for padding). This takes care of both the null termination bytes (padding
            // of the 'reason for leaving' string and the packet padding bytes.
            buffer.skipBytes(lengthInOctets - read);
        }
    }

    return packet;
}
 
Example 18
Project: elasterix   File: SipClient.java   Source Code and License 6 votes vote down vote up
public void sendMessage(SipRequest request) throws Exception {

        // initial line
        StringBuffer buf = new StringBuffer(String.format("%s %s %s", request.getMethod().name(),
                request.getUri(), request.getVersion().toString()));
        buf.append(StringUtil.NEWLINE);

        // headers
        for (Map.Entry<String, List<String>> header : request.getHeaders().entrySet()) {
            buf.append(header.getKey());
            buf.append(": ");
            buf.append(StringUtils.arrayToDelimitedString(header.getValue().toArray(), "\n"));
            buf.append(StringUtil.NEWLINE);
        }
        buf.append(StringUtil.NEWLINE);

        // content
        ChannelBuffer content = request.getContent();
        if (content.readable()) {
            buf.append(content.toString(CharsetUtil.UTF_8)).append(StringUtil.NEWLINE);
        }

        sendMessage(null, buf.toString());
    }
 
Example 19
Project: usergrid   File: WebSocketServerIndexPage.java   Source Code and License 6 votes vote down vote up
public static ChannelBuffer getContent( String webSocketLocation ) {
    return ChannelBuffers.copiedBuffer(
            "<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>" + NEWLINE
                    + "<script type=\"text/javascript\">" + NEWLINE + "var socket;" + NEWLINE
                    + "if (window.WebSocket) {" + NEWLINE + "  socket = new WebSocket(\"" + webSocketLocation
                    + "/00000000-0000-0000-0000-000000000001/users/00000000-0000-0000-0000-000000000002?a=1\");"
                    + NEWLINE + "  socket.onmessage = function(event) { alert(event.data); };" + NEWLINE
                    + "  socket.onopen = function(event) { alert(\"Web Socket opened!\"); };" + NEWLINE
                    + "  socket.onclose = function(event) { alert(\"Web Socket closed.\"); };" + NEWLINE
                    + "} else {" + NEWLINE + "  alert(\"Your browser does not support Web Socket.\");" + NEWLINE
                    + "}" + NEWLINE + "" + NEWLINE + "function send(message) {" + NEWLINE
                    + "  if (!window.WebSocket) { return; }" + NEWLINE + "  if (socket.readyState == 1) {" + NEWLINE
                    + "    socket.send(message);" + NEWLINE + "  } else {" + NEWLINE
                    + "    alert(\"The socket is not open.\");" + NEWLINE + "  }" + NEWLINE + "}" + NEWLINE
                    + "</script>" + NEWLINE + "<form onsubmit=\"return false;\">" + NEWLINE
                    + "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>"
                    + "<input type=\"button\" value=\"Send Web Socket Data\" onclick=\"send(this.form.message" +
                    ".value)\" />" + NEWLINE + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE,
            CharsetUtil.US_ASCII );
}
 
Example 20
Project: jmx-daemon   File: JmxDaemon.java   Source Code and License 6 votes vote down vote up
public void start() {
    ExecutorService bossPool = Executors.newCachedThreadPool();
    log.info("Creating worker thread pool with " + workers + " threads.");
    ExecutorService workerPool = Executors.newFixedThreadPool(workers);
    bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(bossPool, workerPool));
    jmxRequestHandler = new JmxRequestHandler();
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() throws Exception {
            return Channels.pipeline(
                    new DelimiterBasedFrameDecoder(1024 * 1024, ChannelBuffers
                            .copiedBuffer("\n", CharsetUtil.UTF_8)), new StringDecoder(), new StringEncoder(),
                    jmxRequestHandler);
        };
    });
    bootstrap.bind(listenAddress);
    log.info("Starting listening to {}", listenAddress);
}
 
Example 21
Project: Elasticsearch   File: HttpBlobHandler.java   Source Code and License 5 votes vote down vote up
private void simpleResponse(HttpResponseStatus status, String body) {
    if (body == null) {
        simpleResponse(status);
        return;
    }
    HttpResponse response = prepareResponse(status);
    if (!body.endsWith("\n")) {
        body += "\n";
    }
    HttpHeaders.setContentLength(response, body.length());
    response.setContent(ChannelBuffers.copiedBuffer(body, CharsetUtil.UTF_8));
    sendResponse(response);
}
 
Example 22
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 23
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 24
Project: big-c   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 25
Project: OpenMobster   File: HttpServerHandler.java   Source Code and License 5 votes vote down vote up
private void writeResponse(MessageEvent e) 
{
    // Build the response object.
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    
    response.setContent(ChannelBuffers.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
    response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");

    // Write the response.
    ChannelFuture future = e.getChannel().write(response);

    // Close the non-keep-alive connection after the write operation is done.
    future.addListener(ChannelFutureListener.CLOSE);
}
 
Example 26
Project: HeliosStreams   File: WebSocketServiceHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Sends an HTTP response
 * @param ctx The channel handler context
 * @param req The HTTP request being responded to
 * @param res The HTTP response to send
 */
private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
    // Generate an error page if response status code is not OK (200).
    if (res.getStatus().getCode() != 200) {
        res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
        setContentLength(res, res.getContent().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.getChannel().write(res);
    if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 27
Project: navi   File: FaviousRequestLister.java   Source Code and License 5 votes vote down vote up
public boolean process(HttpRequest request, HttpResponse response)
    throws Exception {
    String uri = request.getUri();
    if (uri.equalsIgnoreCase(FAVICON)) {
        response.setStatus(HttpResponseStatus.NOT_FOUND);
        log.warn("favicon.ico isn't found!");
        response.setContent(ChannelBuffers.copiedBuffer(HttpResponseStatus.NOT_FOUND.toString(), CharsetUtil.UTF_8));
        return false;
    }

    return true;
}
 
Example 28
Project: Camel   File: NettyUdpConnectionlessSendTest.java   Source Code and License 5 votes vote down vote up
public void createNettyUdpReceiver() {
    bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory());
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline channelPipeline = Channels.pipeline();
            channelPipeline.addLast("StringDecoder", new StringDecoder(CharsetUtil.UTF_8));
            channelPipeline.addLast("ContentHandler", new ContentHandler());
            return channelPipeline;
        }
    });

}
 
Example 29
Project: Camel   File: NettyUdpConnectedSendTest.java   Source Code and License 5 votes vote down vote up
public void createNettyUdpReceiver() {
    bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory());
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        @Override
        public ChannelPipeline getPipeline() throws Exception {
            ChannelPipeline channelPipeline = Channels.pipeline();
            channelPipeline.addLast("StringDecoder", new StringDecoder(CharsetUtil.UTF_8));
            channelPipeline.addLast("ContentHandler", new ContentHandler());
            return channelPipeline;
        }
    });
}
 
Example 30
Project: Camel   File: NettyCustomPipelineFactorySynchTest.java   Source Code and License 5 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
    clientInvoked = true;

    ChannelPipeline channelPipeline = Channels.pipeline();

    channelPipeline.addLast("decoder-DELIM", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter()));
    channelPipeline.addLast("decoder-SD", new StringDecoder(CharsetUtil.UTF_8));
    channelPipeline.addLast("encoder-SD", new StringEncoder(CharsetUtil.UTF_8));
    channelPipeline.addLast("handler", new ClientChannelHandler(producer));

    return channelPipeline;
}
 
Example 31
Project: Camel   File: NettyCustomPipelineFactorySynchTest.java   Source Code and License 5 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
    serverInvoked = true;

    ChannelPipeline channelPipeline = Channels.pipeline();

    channelPipeline.addLast("encoder-SD", new StringEncoder(CharsetUtil.UTF_8));
    channelPipeline.addLast("decoder-DELIM", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter()));
    channelPipeline.addLast("decoder-SD", new StringDecoder(CharsetUtil.UTF_8));
    channelPipeline.addLast("handler", new ServerChannelHandler(consumer));

    return channelPipeline;
}
 
Example 32
Project: Camel   File: NettyCustomPipelineFactoryAsynchTest.java   Source Code and License 5 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
    clientInvoked = true;

    ChannelPipeline channelPipeline = Channels.pipeline();

    channelPipeline.addLast("decoder-DELIM", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter()));
    channelPipeline.addLast("decoder-SD", new StringDecoder(CharsetUtil.UTF_8));
    channelPipeline.addLast("encoder-SD", new StringEncoder(CharsetUtil.UTF_8));
    channelPipeline.addLast("handler", new ClientChannelHandler(producer));

    return channelPipeline;
}
 
Example 33
Project: Camel   File: NettyCustomPipelineFactoryAsynchTest.java   Source Code and License 5 votes vote down vote up
@Override
public ChannelPipeline getPipeline() throws Exception {
    serverInvoked = true;

    ChannelPipeline channelPipeline = Channels.pipeline();

    channelPipeline.addLast("encoder-SD", new StringEncoder(CharsetUtil.UTF_8));
    channelPipeline.addLast("decoder-DELIM", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter()));
    channelPipeline.addLast("decoder-SD", new StringDecoder(CharsetUtil.UTF_8));
    channelPipeline.addLast("handler", new ServerChannelHandler(consumer));

    return channelPipeline;
}
 
Example 34
Project: Camel   File: NettyManualEndpointTest.java   Source Code and License 5 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            NettyConfiguration nettyConfig = new NettyConfiguration();
            nettyConfig.setProtocol("tcp");
            nettyConfig.setHost("localhost");
            nettyConfig.setPort(getPort());
            nettyConfig.setSync(false);

            // need to add encoders and decoders manually
            nettyConfig.setEncoder(ChannelHandlerFactories.newStringEncoder(CharsetUtil.UTF_8));
            List<ChannelHandler> decoders = new ArrayList<ChannelHandler>();
            decoders.add(ChannelHandlerFactories.newDelimiterBasedFrameDecoder(1000, Delimiters.lineDelimiter()));
            decoders.add(ChannelHandlerFactories.newStringDecoder(CharsetUtil.UTF_8));
            nettyConfig.setDecoders(decoders);

            // create and start component
            NettyComponent component = new NettyComponent(getContext());
            component.setConfiguration(nettyConfig);
            getContext().addComponent("netty", component);
            component.start();

            // create and start endpoint, pass in null as endpoint uri
            // as we create this endpoint manually
            endpoint = new NettyEndpoint(null, component, nettyConfig);
            endpoint.setTimer(component.getTimer());
            endpoint.start();

            from(endpoint).to("mock:result");
        }
    };
}
 
Example 35
Project: Camel   File: NettyConsumerClientModeTest.java   Source Code and License 5 votes vote down vote up
public ChannelPipeline getPipeline() {
    ChannelPipeline p = Channels.pipeline();
    Charset charset = CharsetUtil.UTF_8;
   
    ChannelBuffer[] delimiters = Delimiters.nulDelimiter();
   
    // setup the textline encoding and decoding
    p.addLast("decoder1", ChannelHandlerFactories.newDelimiterBasedFrameDecoder(1024 * 8, delimiters).newChannelHandler());
    p.addLast("decoder2", ChannelHandlerFactories.newStringDecoder(charset).newChannelHandler());
    
    p.addLast("encoder", ChannelHandlerFactories.newStringEncoder(charset).newChannelHandler());
    
    p.addLast("handler", new ServerHandler());
    return p;
}
 
Example 36
Project: hadoop-2.6.0-cdh5.4.3   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 37
Project: hadoop-EAR   File: ShuffleHandler.java   Source Code and License 5 votes vote down vote up
private 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");
  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 38
Project: hadoop-plus   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 39
Project: asynccassandra   File: HBaseRpc.java   Source Code and License 5 votes vote down vote up
/**
 * Writes a {@link String} as an HBase RPC parameter.
 * @param buf The buffer to serialize the string to.
 * @param s The string to serialize.
 */
static void writeHBaseString(final ChannelBuffer buf, final String s) {
  buf.writeByte(10);  // Code for String.class in HbaseObjectWritable
  final byte[] b = s.getBytes(CharsetUtil.UTF_8);
  writeVLong(buf, b.length);
  buf.writeBytes(b);
}
 
Example 40
Project: asynccassandra   File: HBaseRpc.java   Source Code and License 5 votes vote down vote up
/**
 * Reads a string encoded by {@code hadoop.io.WritableUtils#readString}.
 * @throws IllegalArgumentException if the length we read for the string
 * is out of reasonable bounds.
 */
static String readHadoopString(final ChannelBuffer buf) {
  final int length = buf.readInt();
  checkArrayLength(buf, length);
  final byte[] s = new byte[length];
  buf.readBytes(s);
  return new String(s, CharsetUtil.UTF_8);
}
 
Example 41
Project: finagle-java-example-master-slave   File: RedisCache.java   Source Code and License 5 votes vote down vote up
public Future<Long> sAdd(String key, String value, long ttl) {
    ChannelBuffer keyBuf = StringToChannelBuffer.apply(key, CharsetUtil.UTF_8);
    ChannelBuffer valueBuf = StringToChannelBuffer.apply(value, CharsetUtil.UTF_8);
    List<ChannelBuffer> li= new ArrayList<ChannelBuffer>();
    li.add(valueBuf);
    redisClient.expire(keyBuf, ttl);
    return redisClient.sAdd(keyBuf, scala.collection.JavaConversions.asScalaBuffer(li).toList());
}
 
Example 42
Project: finagle-java-example-master-slave   File: RedisCache.java   Source Code and License 5 votes vote down vote up
public Future<Long> sRem(String key, String value) {
    ChannelBuffer keyBuf = StringToChannelBuffer.apply(key, CharsetUtil.UTF_8);
    ChannelBuffer valueBuf = StringToChannelBuffer.apply(value, CharsetUtil.UTF_8);
    List<ChannelBuffer> li= new ArrayList<ChannelBuffer>();
    li.add(valueBuf);
    return redisClient.sRem(keyBuf, scala.collection.JavaConversions.asScalaBuffer(li).toList());
}
 
Example 43
Project: FlexMap   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 44
Project: finagle-6.x-java-example   File: RedisCache.java   Source Code and License 5 votes vote down vote up
public Future<Long> sAdd(String key, String value, long ttl) {
    ChannelBuffer keyBuf = StringToChannelBuffer.apply(key, CharsetUtil.UTF_8);
    ChannelBuffer valueBuf = StringToChannelBuffer.apply(value, CharsetUtil.UTF_8);
    List<ChannelBuffer> li= new ArrayList<ChannelBuffer>();
    li.add(valueBuf);
    redisClient.expire(keyBuf, ttl);
    return redisClient.sAdd(keyBuf, scala.collection.JavaConversions.asScalaBuffer(li).toList());
}
 
Example 45
Project: finagle-6.x-java-example   File: RedisCache.java   Source Code and License 5 votes vote down vote up
public Future<Long> sRem(String key, String value) {
    ChannelBuffer keyBuf = StringToChannelBuffer.apply(key, CharsetUtil.UTF_8);
    ChannelBuffer valueBuf = StringToChannelBuffer.apply(value, CharsetUtil.UTF_8);
    List<ChannelBuffer> li= new ArrayList<ChannelBuffer>();
    li.add(valueBuf);
    return redisClient.sRem(keyBuf, scala.collection.JavaConversions.asScalaBuffer(li).toList());
}
 
Example 46
Project: finagle-6.x-java-example   File: HelperServer.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    Service<HttpRequest, HttpResponse> service = new Service<HttpRequest, HttpResponse>() {
        @Override
        public Future<HttpResponse> apply(HttpRequest request) {
            String reqContent = request.getContent().toString(CharsetUtil.UTF_8);
            System.out.println("[Helper] Request received: " + reqContent);
            
            // Parsing JSON request
            JSONObject jreq;
            try {
                jreq = (JSONObject) jsonParser.parse(reqContent);
                System.out.println("[Main] Param received - pname:" + jreq.get("pname"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            
            HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
            res.setContent(ChannelBuffers.copiedBuffer("{\"v_id\":100, \"price\":0.2}", CharsetUtil.UTF_8));
            res.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
            return Future.<HttpResponse> value(res);
        }
    };
    
    ServerBuilder.safeBuild(service,
            ServerBuilder.get().codec(Http.get()).name("HttpServer")
            .bindTo(new InetSocketAddress("localhost", 9004)));
}
 
Example 47
Project: finagle-6.x-java-example   File: MainServer.java   Source Code and License 5 votes vote down vote up
public Future<HttpResponse> apply(HttpResponse res) {
    String resContent = res.getContent().toString(CharsetUtil.UTF_8);
    System.out.println("[Main] Received helper response: " + resContent);
    
    System.out.println("[Main] Sending response to main client");
    HttpResponse finalRes = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    finalRes.setContent(ChannelBuffers.copiedBuffer("{\"bid\":" + resContent + "}", CharsetUtil.UTF_8));
    finalRes.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8");
    return Future.<HttpResponse> value(finalRes);
}
 
Example 48
Project: hops   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 49
Project: my-dev   File: WebSocketServerUpstreamHandler.java   Source Code and License 5 votes vote down vote up
private void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
    if (res.getStatus().getCode() != 200) {
        res.setContent(
                ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
        HttpHeaders.setContentLength(res, res.getContent().readableBytes());
    }

    ChannelFuture f = ctx.getChannel().write(res);

    if (res.getStatus().getCode() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}
 
Example 50
Project: openimaj   File: SimpleKestrelClient.java   Source Code and License 5 votes vote down vote up
/**
 * Get the next value from the queue
 *
 * @param queueName
 * @param waitDuration
 * @return the next value
 */
public String get(String queueName, Duration waitDuration) {
	try {
		final ChannelBuffer value = client.get(queueName, waitDuration).apply();
		return value == null ? null : value.toString(CharsetUtil.UTF_8);
	} catch (final Exception e) {
		if (THROUGH_EXCEPTIONS.contains(e.getClass())) {
			return null;
		}
		LOG.error(e.getMessage(), e);
		throw new IllegalStateException(e);
	}
}
 
Example 51
Project: tajo   File: TajoPullServerService.java   Source Code and License 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String message,
    HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
  // Put shuffle version into http header
  ChannelBuffer content = ChannelBuffers.copiedBuffer(message, CharsetUtil.UTF_8);
  response.setContent(content);
  response.setHeader(Names.CONTENT_LENGTH, content.writerIndex());

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 52
Project: incubator-tajo   File: HttpDataServerHandler.java   Source Code and License 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(ChannelBuffers.copiedBuffer(
      "Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 53
Project: incubator-tajo   File: HttpDataServerHandler.java   Source Code and License 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(ChannelBuffers.copiedBuffer(
      "Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 54
Project: incubator-tajo   File: TajoPullServerService.java   Source Code and License 5 votes vote down vote up
private 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");
  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: incubator-tajo   File: PullServerAuxService.java   Source Code and License 5 votes vote down vote up
private 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");
  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 56
Project: tajo-cdh   File: HttpDataServerHandler.java   Source Code and License 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(ChannelBuffers.copiedBuffer(
      "Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 57
Project: tajo-cdh   File: HttpDataServerHandler.java   Source Code and License 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status);
  response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
  response.setContent(ChannelBuffers.copiedBuffer(
      "Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));

  // Close the connection as soon as the error message is sent.
  ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 58
Project: tajo-cdh   File: TajoPullServerService.java   Source Code and License 5 votes vote down vote up
private 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");
  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 59
Project: tajo-cdh   File: PullServerAuxService.java   Source Code and License 5 votes vote down vote up
private 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");
  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: hadoop-TCP   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);
}