List of usage examples for io.netty.channel FileRegion transferTo
long transferTo(WritableByteChannel target, long position) throws IOException;
From source file:com.heliosapm.webrpc.jsonservice.services.InvocationChannel.java
License:Apache License
/** * {@inheritDoc}// w ww.jav a 2s. c o m * @see io.netty.channel.ChannelOutboundInvoker#write(java.lang.Object) */ @Override public ChannelFuture write(Object message) { if (message != null) { if (message instanceof FileRegion) { try { Pipe pipe = Pipe.open(); FileRegion fr = (FileRegion) message; long bytesToRead = fr.count(); fr.transferTo(pipe.sink(), 0L); byte[] content = new byte[(int) bytesToRead]; pipe.source().read(ByteBuffer.wrap(content)); channelWrites.add(content); } catch (Exception ex) { log.error("Failed to read content from pipe", ex); channelWrites.add(ex); } } else { channelWrites.add(message); } log.info("Received Channel Write [{}] type:[{}]", message, message.getClass().getName()); } return null; }
From source file:org.apache.rocketmq.remoting.netty.FileRegionEncoder.java
License:Apache License
/** * Encode a message into a {@link io.netty.buffer.ByteBuf}. This method will be called for each written message that * can be handled by this encoder.//from w w w .j a va 2s.c o m * * @param ctx the {@link io.netty.channel.ChannelHandlerContext} which this {@link * io.netty.handler.codec.MessageToByteEncoder} belongs to * @param msg the message to encode * @param out the {@link io.netty.buffer.ByteBuf} into which the encoded message will be written * @throws Exception is thrown if an error occurs */ @Override protected void encode(ChannelHandlerContext ctx, FileRegion msg, final ByteBuf out) throws Exception { WritableByteChannel writableByteChannel = new WritableByteChannel() { @Override public int write(ByteBuffer src) throws IOException { out.writeBytes(src); return out.capacity(); } @Override public boolean isOpen() { return true; } @Override public void close() throws IOException { } }; long toTransfer = msg.count(); while (true) { long transferred = msg.transfered(); if (toTransfer - transferred <= 0) { break; } msg.transferTo(writableByteChannel, transferred); } }
From source file:org.apache.spark.network.crypto.AuthEngineSuite.java
License:Apache License
@Test public void testEncryptedMessageWhenTransferringZeroBytes() throws Exception { AuthEngine client = new AuthEngine("appId", "secret", conf); AuthEngine server = new AuthEngine("appId", "secret", conf); try {//from w w w. j av a2 s . c o m ClientChallenge clientChallenge = client.challenge(); ServerResponse serverResponse = server.respond(clientChallenge); client.validate(serverResponse); TransportCipher cipher = server.sessionCipher(); TransportCipher.EncryptionHandler handler = new TransportCipher.EncryptionHandler(cipher); int testDataLength = 4; FileRegion region = mock(FileRegion.class); when(region.count()).thenReturn((long) testDataLength); // Make `region.transferTo` do nothing in first call and transfer 4 bytes in the second one. when(region.transferTo(any(), anyLong())).thenAnswer(new Answer<Long>() { private boolean firstTime = true; @Override public Long answer(InvocationOnMock invocationOnMock) throws Throwable { if (firstTime) { firstTime = false; return 0L; } else { WritableByteChannel channel = invocationOnMock.getArgument(0); channel.write(ByteBuffer.wrap(new byte[testDataLength])); return (long) testDataLength; } } }); TransportCipher.EncryptedMessage emsg = handler.createEncryptedMessage(region); ByteArrayWritableChannel channel = new ByteArrayWritableChannel(testDataLength); // "transferTo" should act correctly when the underlying FileRegion transfers 0 bytes. assertEquals(0L, emsg.transferTo(channel, emsg.transfered())); assertEquals(testDataLength, emsg.transferTo(channel, emsg.transfered())); assertEquals(emsg.transfered(), emsg.count()); assertEquals(4, channel.length()); } finally { client.close(); server.close(); } }
From source file:org.opendaylight.tcpmd5.netty.MD5NioSocketChannel.java
License:Open Source License
@Override protected long doWriteFileRegion(final FileRegion region) throws IOException { return region.transferTo(javaChannel(), region.transfered()); }
From source file:reactor.ipc.netty.NettyOutboundTest.java
License:Open Source License
@Test public void sendFileWithoutTlsUsesFileRegion() throws URISyntaxException, IOException { List<Class<?>> messageClasses = new ArrayList<>(2); EmbeddedChannel channel = new EmbeddedChannel(new MessageToMessageEncoder<FileRegion>() { @Override/*ww w . j a va 2 s .c om*/ protected void encode(ChannelHandlerContext ctx, FileRegion msg, List<Object> out) throws Exception { ByteArrayOutputStream bais = new ByteArrayOutputStream(); WritableByteChannel wbc = Channels.newChannel(bais); msg.transferTo(wbc, msg.position()); out.add(new String(bais.toByteArray())); } }, new MessageToMessageEncoder<Object>() { @Override protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { messageClasses.add(msg.getClass()); ReferenceCountUtil.retain(msg); out.add(msg); } }); NettyContext mockContext = () -> channel; NettyOutbound outbound = new NettyOutbound() { @Override public NettyContext context() { return mockContext; } @Override public FileChunkedStrategy getFileChunkedStrategy() { return FILE_CHUNKED_STRATEGY_1024_NOPIPELINE; } }; channel.writeOneOutbound(1); outbound.sendFile(Paths.get(getClass().getResource("/largeFile.txt").toURI())).then().block(); assertThat(channel.inboundMessages()).isEmpty(); assertThat(channel.outboundMessages()).hasSize(2); assertThat(messageClasses).containsExactly(Integer.class, DefaultFileRegion.class); assertThat(channel.outboundMessages()).element(1).asString().startsWith( "This is an UTF-8 file that is larger than 1024 bytes.\nIt contains accents like .\nGARBAGE") .endsWith("GARBAGE\nEnd of File"); }