Example usage for io.netty.buffer ByteBufAllocator DEFAULT

List of usage examples for io.netty.buffer ByteBufAllocator DEFAULT

Introduction

In this page you can find the example usage for io.netty.buffer ByteBufAllocator DEFAULT.

Prototype

ByteBufAllocator DEFAULT

To view the source code for io.netty.buffer ByteBufAllocator DEFAULT.

Click Source Link

Usage

From source file:TestTCP.java

License:Open Source License

public static void main(String... args) throws Throwable {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    JFrame ventanica = new JFrame("HTTP test");
    ventanica.setBounds((width - 500) / 2, (height - 400) / 2, 500, 400);

    resultado = new JTextPane();
    resultado.setEditable(true);/*from  w w w  . j ava2s .  com*/
    resultado.setContentType("text/txt");
    resultado.setEditable(false);

    final JTextField direccion = new JTextField();
    JScrollPane scrollPane = new JScrollPane(resultado);
    final JLabel bytesSentLabel = new JLabel("Bytes Sent: 0B");
    final JLabel bytesReceivedLabel = new JLabel("Bytes Received: 0B");
    final JLabel timeSpent = new JLabel("Time: 0ms");
    timeSpent.setHorizontalAlignment(SwingConstants.CENTER);
    JPanel bottomPanel = new JPanel(new BorderLayout(1, 3));
    bottomPanel.add(bytesSentLabel, BorderLayout.WEST);
    bottomPanel.add(timeSpent, BorderLayout.CENTER);
    bottomPanel.add(bytesReceivedLabel, BorderLayout.EAST);

    ventanica.setLayout(new BorderLayout(3, 1));
    ventanica.add(direccion, BorderLayout.NORTH);
    ventanica.add(scrollPane, BorderLayout.CENTER);
    ventanica.add(bottomPanel, BorderLayout.SOUTH);

    ventanica.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    ventanica.setVisible(true);

    final IOService service = new IOService();

    direccion.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final TCPSocket socket = new TCPSocket(service);
            resultado.setText("");
            bytesSentLabel.setText("Bytes Sent: 0B");
            bytesReceivedLabel.setText("Bytes Received: 0B");
            timeSpent.setText("Time: 0ms");
            direccion.setEnabled(false);

            String addr = direccion.getText();
            String host, path = "/";
            int puerto = 80;
            try {
                URL url = new URL((addr.startsWith("http://") ? "" : "http://") + addr);
                host = url.getHost();
                path = url.getPath().isEmpty() ? "/" : url.getPath();
                puerto = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
            } catch (MalformedURLException e1) {
                String as[] = addr.split(":");
                host = as[0];
                if (as.length > 1) {
                    puerto = Integer.parseInt(as[1]);
                }
            }
            final String request = "GET " + path + " HTTP/1.1\r\n" + "Accept-Charset: utf-8\r\n"
                    + "User-Agent: JavaNettyMelchor629\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n"
                    + "\r\n";

            Callback<Future<Void>> l = new Callback<Future<Void>>() {
                @Override
                public void call(Future<Void> arg) {
                    final long start = System.currentTimeMillis();
                    final ByteBuf b = ByteBufAllocator.DEFAULT.buffer(16 * 1024).retain();
                    socket.onClose().whenDone(new Callback<Future<Void>>() {
                        @Override
                        public void call(Future<Void> arg) {
                            direccion.setEnabled(true);

                            long spent = System.currentTimeMillis() - start;
                            timeSpent.setText(String.format("Time spent: %dms", spent));
                            b.release();
                        }
                    });
                    socket.setOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                    socket.setOption(ChannelOption.SO_TIMEOUT, 5000);

                    socket.sendAsync(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, request))
                            .whenDone(new Callback<Future<Void>>() {
                                @Override
                                public void call(Future<Void> arg) {
                                    bytesSentLabel.setText("Bytes Sent: " + socket.sendBytes() + "B");
                                    final Callback<Future<Long>> cbk = new Callback<Future<Long>>() {
                                        @Override
                                        public void call(Future<Long> arg) {
                                            bytesReceivedLabel
                                                    .setText("Bytes Received: " + socket.receivedBytes() + "B");
                                            if (!arg.isSuccessful())
                                                return;

                                            byte b1[] = new byte[(int) (long) arg.getValueNow()];
                                            b.getBytes(0, b1);
                                            resultado.setText(resultado.getText()
                                                    + new String(b1).replace("\r", "\\r").replace("\n", "\\n\n")
                                                    + "");
                                            b.setIndex(0, 0);
                                            socket.receiveAsync(b).whenDone(this);
                                        }
                                    };
                                    socket.receiveAsync(b).whenDone(cbk);
                                }
                            });
                }
            };

            try {
                socket.connectAsync(host, puerto, new OracleJREServerProvider()).whenDone(l);
            } catch (Throwable ignore) {
            }
        }
    });

    ventanica.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            service.cancel();
        }
    });
}

From source file:TestSSL.java

License:Open Source License

public static void main(String[] args) {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    int width = (int) screenSize.getWidth();
    int height = (int) screenSize.getHeight();
    JFrame ventanica = new JFrame("HTTPS test");
    ventanica.setBounds((width - 500) / 2, (height - 400) / 2, 500, 400);

    resultado = new JTextPane();
    resultado.setEditable(true);// w  w w  .  j a v  a  2s . c om
    resultado.setContentType("text/txt");
    resultado.setEditable(false);

    final JTextField direccion = new JTextField();
    JScrollPane scrollPane = new JScrollPane(resultado);
    final JLabel bytesSentLabel = new JLabel("Bytes Sent: 0B");
    final JLabel bytesReceivedLabel = new JLabel("Bytes Received: 0B");
    final JLabel timeSpent = new JLabel("Time: 0ms");
    timeSpent.setHorizontalAlignment(SwingConstants.CENTER);
    JPanel bottomPanel = new JPanel(new BorderLayout(1, 3));
    bottomPanel.add(bytesSentLabel, BorderLayout.WEST);
    bottomPanel.add(timeSpent, BorderLayout.CENTER);
    bottomPanel.add(bytesReceivedLabel, BorderLayout.EAST);

    ventanica.setLayout(new BorderLayout(3, 1));
    ventanica.add(direccion, BorderLayout.NORTH);
    ventanica.add(scrollPane, BorderLayout.CENTER);
    ventanica.add(bottomPanel, BorderLayout.SOUTH);

    ventanica.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    ventanica.setVisible(true);

    final IOService service = new IOService();

    direccion.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final SSLSocket socket = new SSLSocket(service);
            resultado.setText("");
            bytesSentLabel.setText("Bytes Sent: 0B");
            bytesReceivedLabel.setText("Bytes Received: 0B");
            timeSpent.setText("Time: 0ms");
            direccion.setEnabled(false);

            String addr = direccion.getText();
            String host, path = "/";
            int puerto = 80;
            try {
                URL url = new URL((addr.startsWith("https://") ? "" : "https://") + addr);
                host = url.getHost();
                path = url.getPath().isEmpty() ? "/" : url.getPath();
                puerto = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
            } catch (MalformedURLException e1) {
                String as[] = addr.split(":");
                host = as[0];
                if (as.length > 1) {
                    puerto = Integer.parseInt(as[1]);
                }
            }
            final String request = "GET " + path + " HTTP/1.1\r\n" + "Accept-Charset: utf-8\r\n"
                    + "User-Agent: JavaNettyMelchor629\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n"
                    + "\r\n";

            Callback<Future<Void>> l = new Callback<Future<Void>>() {
                @Override
                public void call(Future<Void> arg) {
                    final long start = System.currentTimeMillis();
                    final ByteBuf b = ByteBufAllocator.DEFAULT.buffer(16 * 1024).retain();
                    socket.onClose().whenDone(new Callback<Future<Void>>() {
                        @Override
                        public void call(Future<Void> arg) {
                            direccion.setEnabled(true);

                            long spent = System.currentTimeMillis() - start;
                            timeSpent.setText(String.format("Time spent: %dms", spent));
                            b.release();
                        }
                    });
                    socket.setOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
                    socket.setOption(ChannelOption.SO_TIMEOUT, 5000);

                    socket.sendAsync(ByteBufUtil.writeUtf8(ByteBufAllocator.DEFAULT, request))
                            .whenDone(new Callback<Future<Void>>() {
                                @Override
                                public void call(Future<Void> arg) {
                                    bytesSentLabel.setText("Bytes Sent: " + socket.sendBytes() + "B");
                                    final Callback<Future<Long>> cbk = new Callback<Future<Long>>() {
                                        @Override
                                        public void call(Future<Long> arg) {
                                            bytesReceivedLabel
                                                    .setText("Bytes Received: " + socket.receivedBytes() + "B");
                                            if (!arg.isSuccessful())
                                                return;

                                            byte b1[] = new byte[(int) (long) arg.getValueNow()];
                                            b.getBytes(0, b1);
                                            resultado.setText(resultado.getText()
                                                    + new String(b1).replace("\r", "\\r").replace("\n", "\\n\n")
                                                    + "");
                                            b.setIndex(0, 0);
                                            socket.receiveAsync(b).whenDone(this);
                                        }
                                    };
                                    socket.receiveAsync(b).whenDone(cbk);
                                }
                            });
                }
            };

            try {
                socket.connectAsync(host, puerto, new OracleJREServerProvider()).whenDone(l);
            } catch (Throwable ignore) {
            }
        }
    });

    ventanica.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            service.cancel();
        }
    });
}

From source file:TestTCPServer.java

License:Open Source License

public static void main(String... args) throws Throwable {
    IOService service = new IOService();
    TCPAcceptor acceptor = new TCPAcceptor(service);
    acceptor.setOption(ChannelOption.SO_BACKLOG, 3);
    acceptor.setChildOption(ChannelOption.TCP_NODELAY, true);
    acceptor.setChildOption(ChannelOption.SO_KEEPALIVE, true);

    acceptor.bind(4321);/*w w  w  .  ja v a 2  s. c om*/
    TCPSocket con = acceptor.accept();
    ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(16 * 1000);
    byte[] bytea = new byte[buffer.capacity()];
    long bytes;

    System.out.println("Connected " + con.remoteEndpoint());
    bytes = con.receive(buffer);
    while (bytes != -1 && buffer.getByte(0) != 4) {
        buffer.readBytes(bytea, 0, (int) bytes);
        System.out.print(new String(bytea, 0, (int) bytes));
        buffer.readerIndex(0).writerIndex(0);
        con.send(buffer, (int) bytes);
        buffer.readerIndex(0).writerIndex(0);
        bytes = con.receive(buffer);
    }

    System.out.println("Connection closed");
    con.close();

    acceptor.close();
    service.cancel();
}

From source file:cc.blynk.integration.model.websocket.AppWebSocketClient.java

License:Apache License

private static WebSocketFrame produceWebSocketFrame(MessageBase msg) {
    byte[] data = msg.getBytes();
    ByteBuf bb = ByteBufAllocator.DEFAULT.buffer(3 + data.length);
    bb.writeByte(msg.command);//  ww  w  .ja  va2s.co  m
    bb.writeShort(msg.id);
    bb.writeBytes(data);
    return new BinaryWebSocketFrame(bb);
}

From source file:com.addthis.hydra.store.skiplist.SkipListCache.java

License:Apache License

/**
 * Splits a page in half. The input page must be write locked,
 * hold enough keys to satisfy the split condition, and cannot
 * be in a transient state. The skip-list cache uses the invariant
 * that each page in the cache must have some copy of the page
 * in external storage. We currently use Berkeley DB as the external
 * storage system, which is an append-only database. To conserve
 * disk space we do not store a full page to the database but instead
 * insert (new key, empty page) as a stub into the database.
 *
 * @param target page to split// w  ww .j  a  v  a  2 s. c  o m
 */
private Page<K, V> splitOnePage(Page<K, V> target) {
    assert (target.isWriteLockedByCurrentThread());
    assert (target.splitCondition());
    assert (!target.inTransientState());

    if (target.keys == null) {
        pullPageFromDisk(target, LockMode.WRITEMODE);
    }

    int newSize = target.size / 2;
    int sibSize = target.size - newSize;

    List<K> keyRange = target.keys.subList(newSize, target.size);
    List<V> valueRange = target.values.subList(newSize, target.size);
    List<byte[]> rawValueRange = target.rawValues.subList(newSize, target.size);

    ArrayList<K> sibKeys = new ArrayList<>(keyRange);
    ArrayList<V> sibValues = new ArrayList<>(valueRange);
    ArrayList<byte[]> sibRawValues = new ArrayList<>(rawValueRange);
    K sibMinKey = sibKeys.get(0);

    Page<K, V> sibling = pageFactory.generateSiblingPage(SkipListCache.this, sibMinKey, target.nextFirstKey,
            sibSize, sibKeys, sibValues, sibRawValues, target.getEncodeType());
    sibling.writeLock();

    byte[] encodeKey;
    byte[] placeHolder;

    sibling.state = ExternalMode.DISK_MEMORY_DIRTY;
    target.state = ExternalMode.DISK_MEMORY_DIRTY;

    Page<K, V> prev = cache.putIfAbsent(sibMinKey, sibling);
    if (prev != null) {
        throw new IllegalStateException("Page split " + target.firstKey.toString() + " resulted in a new page "
                + sibMinKey.toString() + " that already exists in cache.");
    }

    cacheSize.getAndIncrement();
    numPagesInMemory.getAndIncrement();

    sibling.avgEntrySize = target.avgEntrySize;
    sibling.estimates = target.estimates;
    sibling.estimateTotal = target.estimateTotal;

    target.nextFirstKey = sibMinKey;
    target.size = newSize;

    int prevMem = target.getMemoryEstimate();

    target.updateMemoryEstimate();
    sibling.updateMemoryEstimate();

    int updatedMem = target.getMemoryEstimate() + sibling.getMemoryEstimate();
    updateMemoryEstimate(updatedMem - prevMem);

    encodeKey = keyCoder.keyEncode(sibMinKey);

    ByteBufOutputStream byteBufOutputStream = new ByteBufOutputStream(ByteBufAllocator.DEFAULT.buffer());
    try {
        placeHolder = pageFactory.generateEmptyPage(SkipListCache.this, sibling.firstKey, sibling.nextFirstKey,
                sibling.getEncodeType()).encode(byteBufOutputStream, false);
    } finally {
        byteBufOutputStream.buffer().release();
    }
    externalStore.put(encodeKey, placeHolder);

    evictionQueue.offer(sibling);
    numPagesSplit.getAndIncrement();

    keyRange.clear();
    valueRange.clear();
    rawValueRange.clear();

    return sibling;
}

From source file:com.buildria.mocking.builder.action.RawBodyAction.java

License:Open Source License

@Nonnull
@Override/*w  ww  .  j ava 2  s  . c  om*/
public HttpResponse apply(@Nonnull HttpRequest req, @Nonnull HttpResponse res) {
    Objects.requireNonNull(req);
    Objects.requireNonNull(res);
    ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(content.length);
    buffer.writeBytes(content);
    HttpResponse r = new DefaultFullHttpResponse(res.getProtocolVersion(), res.getStatus(), buffer);
    for (Map.Entry<String, String> entry : res.headers()) {
        r.headers().add(entry.getKey(), entry.getValue());
    }
    r.headers().remove(CONTENT_LENGTH);
    r.headers().add(CONTENT_LENGTH, content.length);
    return r;
}

From source file:com.buildria.mocking.stub.CallTest.java

License:Open Source License

@Test
public void testFromRequest() throws Exception {
    DefaultFullHttpRequest req = mock(DefaultFullHttpRequest.class);

    when(req.getUri()).thenReturn("/api/p?name=%E3%81%82");
    when(req.getMethod()).thenReturn(GET);

    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add("key", "value1");
    headers.add("key", "value2");
    when(req.headers()).thenReturn(headers);

    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
    buf.writeByte((byte) 0xff);
    when(req.content()).thenReturn(buf);

    Call call = Call.fromRequest(req);//w  ww  .  j a va 2  s . co m

    assertThat(call.getPath(), is("/api/p"));
    assertThat(call.getParameters().size(), is(1));
    assertThat(call.getParameters().get(0).getName(), is("name"));
    assertThat(call.getParameters().get(0).getValue(), is("\u3042"));
    assertThat(call.getMethod(), is(equalToIgnoringCase("GET")));
    assertThat(call.getHeaders(), hasSize(2));
    assertThat(call.getHeaders().get(0).getName(), is("key"));
    assertThat(call.getHeaders().get(0).getValue(), is("value1"));
    assertThat(call.getHeaders().get(1).getName(), is("key"));
    assertThat(call.getHeaders().get(1).getValue(), is("value2"));
    assertThat(call.getBody()[0], is((byte) 0xff));
}

From source file:com.comphenix.protocol.injector.netty.NettyByteBufAdapter.java

License:Open Source License

@Override
public ByteBufAllocator alloc() {
    return ByteBufAllocator.DEFAULT;
}

From source file:com.dianping.cat.hadoop.hdfs.bucket.AbstractHdfsMessageBucket.java

License:Open Source License

@Override
public MessageTree findById(String messageId) throws IOException {
    int index = MessageId.parse(messageId).getIndex();

    try {/* www .ja  v a 2s.  c  o m*/
        byte[] data = m_reader.readMessage(index);

        if (data != null) {
            ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(data.length);

            buf.writeBytes(data);

            MessageTree tree = CodecHandler.decode(buf);

            m_lastAccessTime = System.currentTimeMillis();
            return tree;
        } else {
            return null;
        }
    } catch (EOFException e) {
        return null;
    } finally {
        CodecHandler.reset();
    }
}

From source file:com.github.ambry.rest.NettySslFactory.java

License:Open Source License

@Override
public SSLEngine createSSLEngine(String peerHost, int peerPort, Mode mode) {
    SslContext context = mode == Mode.CLIENT ? nettyClientSslContext : nettyServerSslContext;
    SSLEngine sslEngine = context.newEngine(ByteBufAllocator.DEFAULT, peerHost, peerPort);

    if (mode == Mode.CLIENT) {
        SSLParameters sslParams = sslEngine.getSSLParameters();
        sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
        sslEngine.setSSLParameters(sslParams);
    }/*from   w  ww  .j a va2  s  . c  om*/
    return sslEngine;
}