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.helome.messagecenter.master.HttpServerHandler.java

License:Apache License

private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
    // Decide whether to close the connection or not.
    boolean keepAlive = isKeepAlive(request);
    // Build the response object.
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
            Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));

    response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");

    if (keepAlive) {
        // Add 'Content-Length' header only for a keep-alive connection.
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        // Add keep alive header as per:
        // -//from www .  j  a  v  a 2s.  co m
        // http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the response.
    ctx.write(response);

    return keepAlive;
}

From source file:com.hop.hhxx.example.http.file.HttpStaticFileServerHandler.java

License:Apache License

private static void sendListing(ChannelHandlerContext ctx, File dir) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");

    String dirPath = dir.getPath();
    StringBuilder buf = new StringBuilder().append("<!DOCTYPE html>\r\n").append("<html><head><title>")
            .append("Listing of: ").append(dirPath).append("</title></head><body>\r\n")

            .append("<h3>Listing of: ").append(dirPath).append("</h3>\r\n")

            .append("<ul>").append("<li><a href=\"../\">..</a></li>\r\n");

    for (File f : dir.listFiles()) {
        if (f.isHidden() || !f.canRead()) {
            continue;
        }/*www. ja  v a 2s . c  o m*/

        String name = f.getName();
        if (!ALLOWED_FILE_NAME.matcher(name).matches()) {
            continue;
        }

        buf.append("<li><a href=\"").append(name).append("\">").append(name).append("</a></li>\r\n");
    }

    buf.append("</ul></body></html>\r\n");
    ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8);
    response.content().writeBytes(buffer);
    buffer.release();

    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:com.hop.hhxx.example.qotm.QuoteOfTheMomentClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    EventLoopGroup group = new NioEventLoopGroup();
    try {//from   w  ww . j  a  va2  s . c  o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new QuoteOfTheMomentClientHandler());

        Channel ch = b.bind(0).sync().channel();

        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", PORT))).sync();

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
        // response is received.  If the channel is not closed within 5 seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.hxr.javatone.concurrency.netty.official.qotm.QuoteOfTheMomentClient.java

License:Apache License

public void run() throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from w  ww.  j  a va  2  s.  c  o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true)
                .handler(new QuoteOfTheMomentClientHandler());

        Channel ch = b.bind(0).sync().channel();

        // Broadcast the QOTM request to port 8080.
        ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("QOTM?", CharsetUtil.UTF_8),
                new InetSocketAddress("255.255.255.255", port))).sync();

        // QuoteOfTheMomentClientHandler will close the DatagramChannel when a
        // response is received.  If the channel is not closed within 5 seconds,
        // print an error message and quit.
        if (!ch.closeFuture().await(5000)) {
            System.err.println("QOTM request timed out.");
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.hxr.javatone.concurrency.netty.official.qotm.QuoteOfTheMomentServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    System.err.println(packet);//from  w w w  . j  a va  2 s .  c o  m
    if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) {
        ctx.write(new DatagramPacket(Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8),
                packet.sender()));
    }
}

From source file:com.ibm.mqlight.api.security.PemFile.java

License:Apache License

/**
 * Obtains the list of certificates stored in the PEM file.
 * // w ww .  ja v a  2s .  c  o m
 * @return The list of certificates stored in the PEM file.
 * @throws CertificateException If a parsing error occurs.
 * @throws IOException If the PEM file cannot be read for any reason.
 */
public List<Certificate> getCertificates() throws CertificateException, IOException {
    final String methodName = "getCertificates";
    logger.entry(this, methodName);

    final String fileData = getPemFileData();

    final List<ByteBuf> certDataList = new ArrayList<ByteBuf>();
    final Matcher m = CERTIFICATE_PATTERN.matcher(fileData);
    int start = 0;
    while (m.find(start)) {
        final ByteBuf base64CertData = Unpooled.copiedBuffer(m.group(1), Charset.forName("US-ASCII"));
        final ByteBuf certData = Base64.decode(base64CertData);
        base64CertData.release();
        certDataList.add(certData);
        start = m.end();
    }

    if (certDataList.isEmpty()) {
        final CertificateException exception = new CertificateException(
                "No certificates found in PEM file: " + pemFile);
        logger.throwing(this, methodName, exception);
        throw exception;
    }

    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final List<Certificate> certificates = new ArrayList<Certificate>();

    try {
        for (ByteBuf certData : certDataList) {
            certificates.add(cf.generateCertificate(new ByteBufInputStream(certData)));
        }
    } finally {
        for (ByteBuf certData : certDataList)
            certData.release();
    }

    logger.exit(this, methodName, certificates);

    return certificates;
}

From source file:com.ibm.mqlight.api.security.PemFile.java

License:Apache License

/**
 * Obtains the private key data as a byte array from the PEM file.
 * <p>/*www. jav a  2  s .  co  m*/
 * Within the PEM file the private key data is base 64 encoded. This method will decode the data for the returned private key
 * data.
 * <p>
 * Note that for an encrypted private key the data will remain encrypted.
 * 
 * @return The private key data.
 * @throws KeyException If a private key cannot be found in the PEM file. 
 * @throws IOException If the PEM file cannot be read for any reason.
 */
public byte[] getPrivateKeyBytes() throws KeyException, IOException {
    final String methodName = "getPrivateKeyBytes";
    logger.entry(this, methodName);

    final String fileData = getPemFileData();

    Matcher m = KEY_PATTERN.matcher(fileData);
    final byte[] keyBytes;
    final String base64KeyDataStr;
    if (m.find()) {
        base64KeyDataStr = m.group(1);
    } else {
        m = ENCRYPTED_KEY_PATTERN.matcher(fileData);
        if (m.find()) {
            base64KeyDataStr = m.group(1);
        } else {
            final KeyException exception = new KeyException("Private key not found in PEM file: " + pemFile);
            logger.throwing(this, methodName, exception);
            throw exception;
        }
    }

    final ByteBuf base64KeyData = Unpooled.copiedBuffer(base64KeyDataStr, Charset.forName("US-ASCII"));
    final ByteBuf keyData = Base64.decode(base64KeyData);
    base64KeyData.release();
    keyBytes = new byte[keyData.readableBytes()];
    keyData.readBytes(keyBytes).release();

    logger.exit(this, methodName, keyBytes);

    return keyBytes;
}

From source file:com.indigo.game.common.network.websocket.WebSocketServerIndexPage.java

License:Apache License

static ByteBuf getContent(String webSocketLocation) {
    return Unpooled.copiedBuffer("<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>"
            + NEWLINE + "<com.indigo.game.common.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 + "</com.indigo.game.common.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:com.informatica.surf.sources.http.HttpServerHandler.java

License:Apache License

private static 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);/* ww w. j  ava  2 s .c o  m*/
        buf.release();
        setContentLength(res, res.content().readableBytes());
    } else {
        setContentLength(res, 0);
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.intuit.karate.netty.FeatureServerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
    long startTime = System.currentTimeMillis();
    backend.getContext().logger.debug("handling method: {}, uri: {}", msg.method(), msg.uri());
    FullHttpResponse nettyResponse;//from   ww  w  .  j  a va  2  s. com
    if (msg.uri().startsWith(STOP_URI)) {
        backend.getContext().logger.info("stop uri invoked, shutting down");
        ByteBuf responseBuf = Unpooled.copiedBuffer("stopped", CharsetUtil.UTF_8);
        nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, responseBuf);
        stopFunction.run();
    } else {
        StringUtils.Pair url = HttpUtils.parseUriIntoUrlBaseAndPath(msg.uri());
        HttpRequest request = new HttpRequest();
        if (url.left == null) {
            String requestScheme = ssl ? "https" : "http";
            String host = msg.headers().get(HttpUtils.HEADER_HOST);
            request.setUrlBase(requestScheme + "://" + host);
        } else {
            request.setUrlBase(url.left);
        }
        request.setUri(url.right);
        request.setMethod(msg.method().name());
        msg.headers().forEach(h -> request.addHeader(h.getKey(), h.getValue()));
        QueryStringDecoder decoder = new QueryStringDecoder(url.right);
        decoder.parameters().forEach((k, v) -> request.putParam(k, v));
        HttpContent httpContent = (HttpContent) msg;
        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            byte[] bytes = new byte[content.readableBytes()];
            content.readBytes(bytes);
            request.setBody(bytes);
        }
        HttpResponse response = backend.buildResponse(request, startTime);
        HttpResponseStatus httpResponseStatus = HttpResponseStatus.valueOf(response.getStatus());
        byte[] responseBody = response.getBody();
        if (responseBody != null) {
            ByteBuf responseBuf = Unpooled.copiedBuffer(responseBody);
            nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus, responseBuf);
        } else {
            nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpResponseStatus);
        }
        MultiValuedMap karateHeaders = response.getHeaders();
        if (karateHeaders != null) {
            HttpHeaders nettyHeaders = nettyResponse.headers();
            karateHeaders.forEach((k, v) -> nettyHeaders.add(k, v));
        }
    }
    ctx.write(nettyResponse);
    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}