Example usage for io.netty.buffer Unpooled copiedBuffer

List of usage examples for io.netty.buffer Unpooled copiedBuffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled copiedBuffer.

Prototype

private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset) 

Source Link

Usage

From source file:com.zz.learning.netty5.chap10.xml.codec.AbstractHttpXmlEncoder.java

License:Apache License

protected ByteBuf encode0(ChannelHandlerContext ctx, Object order) throws Exception {
    /*/*www  .  j av  a 2s. c  om*/
     * factory = BindingDirectory.getFactory(body.getClass()); writer = new
     * StringWriter(); IMarshallingContext mctx =
     * factory.createMarshallingContext(); mctx.setIndent(2);
     * mctx.marshalDocument(body, CHARSET_NAME, null, writer); String xmlStr
     * = writer.toString(); writer.close(); writer = null; ByteBuf encodeBuf
     * = Unpooled.copiedBuffer(xmlStr, UTF_8); return encodeBuf;
     */

    /*        String xmlStr = stream.toXML(order);
            ByteBuf encodeBuf = Unpooled.copiedBuffer(xmlStr, UTF_8);
            return encodeBuf;*/

    String s = JSON.toJSONString(order);
    System.out.println(s);
    ByteBuf encodeBuf = Unpooled.copiedBuffer(s, UTF_8);
    return encodeBuf;
}

From source file:de.cubeisland.engine.core.webapi.HttpRequestHandler.java

License:Open Source License

private void success(ChannelHandlerContext context, ApiResponse apiResponse) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.copiedBuffer(this.serialize(apiResponse.getContent()), this.UTF8));
    response.headers().set(CONTENT_TYPE, JSON.toString());
    context.writeAndFlush(response).addListener(CLOSE);
}

From source file:de.cubeisland.engine.core.webapi.HttpRequestHandler.java

License:Open Source License

private void error(ChannelHandlerContext context, RequestStatus error, ApiRequestException e) {
    Map<String, Object> data = new HashMap<>();
    data.put("id", error.getCode());
    data.put("desc", error.getDescription());

    if (e != null) {
        Map<String, Object> reason = new HashMap<>();
        reason.put("id", e.getCode());
        reason.put("desc", e.getMessage());
        data.put("reason", reason);
    }//  w ww. j  a  va  2s .  c  o m

    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, error.getRepsonseStatus(),
            Unpooled.copiedBuffer(this.serialize(data), this.UTF8));
    response.headers().set(CONTENT_TYPE, JSON.toString());
    context.writeAndFlush(response).addListener(CLOSE).addListener(CLOSE_ON_FAILURE);
}

From source file:deathcap.wsmc.web.HTTPHandler.java

License:Apache License

public void sendHttpResponse(ChannelHandlerContext context, FullHttpRequest request,
        FullHttpResponse response) {//from  w w w .ja  v  a  2 s . c o m
    if (response.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(response.getStatus().toString(), CharsetUtil.UTF_8);
        response.content().writeBytes(buf);
        buf.release();
    }
    setContentLength(response, response.content().readableBytes());

    ChannelFuture future = context.channel().writeAndFlush(response);
    if (!isKeepAlive(request) || response.getStatus().code() != 200) {
        future.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:divconq.api.internal.ClientHandler.java

License:Open Source License

public void send(Message msg) {
    Logger.debug("Sending message: " + msg);

    try {//from   ww w.j  a v a2 s. co m
        if (this.chan != null) {
            if (this.info.getKind() == ConnectorKind.WebSocket)
                this.chan.writeAndFlush(new TextWebSocketFrame(msg.toString()));
            else {
                DefaultFullHttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
                        this.info.getPath());

                req.headers().set(Names.HOST, this.info.getHost());
                req.headers().set(Names.USER_AGENT, "DivConq HyperAPI Client 1.0");
                req.headers().set(Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                req.headers().set(Names.CONTENT_ENCODING, "UTF-8");
                req.headers().set(Names.CONTENT_TYPE, "application/json; charset=utf-8");
                req.headers().set(Names.COOKIE, ClientCookieEncoder.encode(this.cookies.values()));

                // TODO make more efficient - UTF8 encode directly to buffer
                ByteBuf buf = Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8);
                int clen = buf.readableBytes();
                req.content().writeBytes(buf);
                buf.release();

                // Add 'Content-Length' header only for a keep-alive connection.
                req.headers().set(Names.CONTENT_LENGTH, clen);

                this.chan.writeAndFlush(req);
            }
        }
    } catch (Exception x) {
        Logger.error("Send HTTP Message error: " + x);
    }
}

From source file:divconq.bus.net.ServerHandler.java

License:Open Source License

public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);//from   ww w. j  a v a 2 s  .  co m
        buf.release();
        HttpHeaders.setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);

    if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200)
        f.addListener(ChannelFutureListener.CLOSE);
}

From source file:divconq.bus.net.WebSocketServerIndexPage.java

License:Open Source License

public static ByteBuf getContent(String webSocketLocation) {
    return Unpooled.copiedBuffer("<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>"
            + NEWLINE + "<script type=\"text/javascript\">" + NEWLINE + "var socket;" + NEWLINE
            + "if (!window.WebSocket) {" + NEWLINE + "  window.WebSocket = window.MozWebSocket;" + NEWLINE + '}'
            + NEWLINE + "if (window.WebSocket) {" + NEWLINE + "  socket = new WebSocket(\"" + webSocketLocation
            + "\");" + NEWLINE + "  socket.onmessage = function(event) {" + NEWLINE
            + "    var ta = document.getElementById('responseText');" + NEWLINE
            + "    ta.value = ta.value + '\\n' + event.data" + NEWLINE + "  };" + NEWLINE
            + "  socket.onopen = function(event) {" + NEWLINE
            + "    var ta = document.getElementById('responseText');" + NEWLINE
            + "    ta.value = \"Web Socket opened!\";" + NEWLINE + "  };" + NEWLINE
            + "  socket.onclose = function(event) {" + NEWLINE
            + "    var ta = document.getElementById('responseText');" + NEWLINE
            + "    ta.value = ta.value + \"Web Socket closed\"; " + NEWLINE + "  };" + 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 == WebSocket.OPEN) {" + 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\"" + NEWLINE
            + "       onclick=\"send(this.form.message.value)\" />" + NEWLINE + "<h3>Output</h3>" + NEWLINE
            + "<textarea id=\"responseText\" style=\"width:500px;height:300px;\"></textarea>" + NEWLINE
            + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE, CharsetUtil.UTF_8);
}

From source file:divconq.ctp.stream.UngzipStream.java

License:Open Source License

@Override
public ReturnOption handle(FileDescriptor file, ByteBuf data) {
    if (file == FileDescriptor.FINAL)
        return this.downstream.handle(file, data);

    if (this.ufile == null)
        this.initializeFileValues(file);

    // inflate the payload into 1 or more outgoing buffers set in a queue
    ByteBuf in = data;/*from  ww w  .j  a va 2  s .c o m*/

    if (in != null) {
        ByteBuf rem = this.remnant;

        ByteBuf src = ((rem != null) && rem.isReadable()) ? Unpooled.copiedBuffer(rem, in) : in;

        this.inflate(src);

        // if there are any unread bytes here we need to store them and combine with the next "handle"
        // this would be rare since the header and footer are small, but it is possible and should be handled
        // file content has its own "in progress" buffer so no need to worry about that
        this.remnant = src.isReadable() ? src.copy() : null; // TODO wrap or slice here? we need copy above

        if (in != null)
            in.release();

        if (rem != null)
            rem.release();

        if (OperationContext.get().getTaskRun().isKilled())
            return ReturnOption.DONE;
    }

    // write all buffers in the queue
    while (this.outlist.size() > 0) {
        ReturnOption ret = this.nextMessage();

        if (ret != ReturnOption.CONTINUE)
            return ret;
    }

    // if we reached done and we wrote all the buffers, then send the EOF marker if not already
    if ((this.gzipState == GzipState.DONE) && !this.eofsent)
        return this.nextMessage();

    // otherwise we need more data
    return ReturnOption.CONTINUE;
}

From source file:divconq.http.multipart.InternalAttribute.java

License:Apache License

public void addValue(String value) {
    if (value == null) {
        throw new NullPointerException("value");
    }//from  w  w w  . java2  s  .co  m
    ByteBuf buf = Unpooled.copiedBuffer(value, charset);
    this.value.add(buf);
    size += buf.readableBytes();
}

From source file:divconq.http.multipart.InternalAttribute.java

License:Apache License

public void addValue(String value, int rank) {
    if (value == null) {
        throw new NullPointerException("value");
    }//w  w w . j  a va2 s . c om
    ByteBuf buf = Unpooled.copiedBuffer(value, charset);
    this.value.add(rank, buf);
    size += buf.readableBytes();
}