List of usage examples for io.netty.buffer ByteBufUtil writeUtf8
public static int writeUtf8(ByteBuf buf, CharSequence seq)
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 ww . j ava 2 s . co m*/ 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 2 s .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:be.ordina.msdashboard.aggregators.index.IndexesAggregatorTest.java
License:Apache License
@Test @SuppressWarnings("unchecked") public void shouldReturnThreeNodes() throws InterruptedException { when(discoveryClient.getServices()).thenReturn(Collections.singletonList("service")); ServiceInstance instance = Mockito.mock(ServiceInstance.class); when(discoveryClient.getInstances("service")).thenReturn(Collections.singletonList(instance)); when(instance.getServiceId()).thenReturn("service"); when(instance.getUri()).thenReturn(URI.create("http://localhost:8089/service")); HttpClientResponse<ByteBuf> response = Mockito.mock(HttpClientResponse.class); when(RxNetty.createHttpRequest(any(HttpClientRequest.class))).thenReturn(Observable.just(response)); when(response.getStatus()).thenReturn(HttpResponseStatus.OK); ByteBuf byteBuf = (new PooledByteBufAllocator()).directBuffer(); ByteBufUtil.writeUtf8(byteBuf, "source"); when(response.getContent()).thenReturn(Observable.just(byteBuf)); Node node = new NodeBuilder().withId("service").build(); when(indexToNodeConverter.convert("service", "http://localhost:8089/service", "source")) .thenReturn(Observable.just(node)); TestSubscriber<Node> testSubscriber = new TestSubscriber<>(); indexesAggregator.aggregateNodes().toBlocking().subscribe(testSubscriber); //testSubscriber.assertNoErrors(); List<Node> nodes = testSubscriber.getOnNextEvents(); assertThat(nodes).hasSize(1);/*from w ww .j a va 2 s . c om*/ assertThat(nodes.get(0).getId()).isEqualTo("service"); }
From source file:com.flysoloing.learning.network.netty.redis.RedisClientHandler.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { String[] commands = ((String) msg).split("\\s+"); List<RedisMessage> children = new ArrayList<RedisMessage>(commands.length); for (String cmdString : commands) { children.add(new FullBulkStringRedisMessage(ByteBufUtil.writeUtf8(ctx.alloc(), cmdString))); }// w w w .j a v a 2 s .c om RedisMessage request = new ArrayRedisMessage(children); ctx.write(request, promise); }
From source file:com.lambdaworks.redis.codec.StringCodec.java
License:Apache License
public void encode(String str, ByteBuf target) { if (str == null) { return;// w w w .j a va 2 s . c o m } if (utf8) { ByteBufUtil.writeUtf8(target, str); return; } if (ascii) { ByteBufUtil.writeAscii(target, str); return; } CharsetEncoder encoder = CharsetUtil.encoder(charset); int length = (int) ((double) str.length() * encoder.maxBytesPerChar()); target.ensureWritable(length); try { final ByteBuffer dstBuf = target.nioBuffer(0, length); final int pos = dstBuf.position(); CoderResult cr = encoder.encode(CharBuffer.wrap(str), dstBuf, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = encoder.flush(dstBuf); if (!cr.isUnderflow()) { cr.throwException(); } target.writerIndex(target.writerIndex() + dstBuf.position() - pos); } catch (CharacterCodingException x) { throw new IllegalStateException(x); } }
From source file:com.turo.pushy.apns.server.ParsingMockApnsServerListenerAdapterTest.java
License:Open Source License
@Test public void testHandlePushNotificationAccepted() { final TestParsingMockApnsServerListener listener = new TestParsingMockApnsServerListener(); {/*from w ww.j a v a2 s. c o m*/ final String token = "test-token"; final Http2Headers headers = new DefaultHttp2Headers().path(APNS_PATH_PREFIX + token); listener.handlePushNotificationAccepted(headers, null); assertEquals(token, listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final String topic = "test-topic"; final Http2Headers headers = new DefaultHttp2Headers().add(APNS_TOPIC_HEADER, topic); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertEquals(topic, listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final DeliveryPriority priority = DeliveryPriority.CONSERVE_POWER; final Http2Headers headers = new DefaultHttp2Headers().addInt(APNS_PRIORITY_HEADER, priority.getCode()); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertEquals(priority, listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final Date expiration = new Date(1_000_000_000); final Http2Headers headers = new DefaultHttp2Headers().addInt(APNS_EXPIRATION_HEADER, (int) (expiration.getTime() / 1000)); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertEquals(expiration, listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final String collapseId = "collapse-id"; final Http2Headers headers = new DefaultHttp2Headers().add(APNS_COLLAPSE_ID_HEADER, collapseId); listener.handlePushNotificationAccepted(headers, null); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertEquals(collapseId, listener.mostRecentPushNotification.getCollapseId()); assertNull(listener.mostRecentPushNotification.getPayload()); } { final String payload = "A test payload!"; final Http2Headers headers = new DefaultHttp2Headers(); final ByteBuf payloadBuffer = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, payload); try { listener.handlePushNotificationAccepted(headers, payloadBuffer); assertNull(listener.mostRecentPushNotification.getToken()); assertNull(listener.mostRecentPushNotification.getTopic()); assertNull(listener.mostRecentPushNotification.getPriority()); assertNull(listener.mostRecentPushNotification.getExpiration()); assertNull(listener.mostRecentPushNotification.getCollapseId()); assertEquals(payload, listener.mostRecentPushNotification.getPayload()); } finally { payloadBuffer.release(); } } }
From source file:io.atomix.cluster.messaging.impl.MessageEncoder.java
License:Apache License
private void encodeRequest(InternalRequest request, ByteBuf out) { encodeMessage(request, out);//from w w w. j av a2s. co m final ByteBuf buf = out.alloc().buffer(ByteBufUtil.utf8MaxBytes(request.subject())); try { final int length = ByteBufUtil.writeUtf8(buf, request.subject()); // write length of message type out.writeShort(length); // write message type bytes out.writeBytes(buf); } finally { buf.release(); } }
From source file:io.crate.protocols.http.HttpBlobHandler.java
License:Apache License
private void simpleResponse(HttpResponseStatus status, String body) { if (body == null) { simpleResponse(status);//from w w w . ja v a 2 s . c o m return; } if (!body.endsWith("\n")) { body += "\n"; } ByteBuf content = ByteBufUtil.writeUtf8(ctx.alloc(), body); DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, content); HttpUtil.setContentLength(response, body.length()); maybeSetConnectionCloseHeader(response); sendResponse(response); }
From source file:io.gatling.http.client.body.string.StringRequestBody.java
License:Apache License
@Override public WritableContent build(boolean zeroCopy, ByteBufAllocator alloc) { ByteBuf bb = charset.equals(StandardCharsets.UTF_8) ? ByteBufUtil.writeUtf8(alloc, content) : ByteBufUtil.encodeString(alloc, CharBuffer.wrap(content), charset); return new WritableContent(bb, bb.readableBytes()); }
From source file:io.grpc.netty.NettyServerHandler.java
License:Apache License
private void respondWithHttpError(ChannelHandlerContext ctx, int streamId, int code, Status.Code statusCode, String msg) {//from w ww . j ava2s. c o m Metadata metadata = new Metadata(); metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus()); metadata.put(InternalStatus.MESSAGE_KEY, msg); byte[][] serialized = InternalMetadata.serialize(metadata); Http2Headers headers = new DefaultHttp2Headers(true, serialized.length / 2).status("" + code) .set(CONTENT_TYPE_HEADER, "text/plain; encoding=utf-8"); for (int i = 0; i < serialized.length; i += 2) { headers.add(new AsciiString(serialized[i], false), new AsciiString(serialized[i + 1], false)); } encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise()); ByteBuf msgBuf = ByteBufUtil.writeUtf8(ctx.alloc(), msg); encoder().writeData(ctx, streamId, msgBuf, 0, true, ctx.newPromise()); }