List of usage examples for io.netty.buffer ByteBuf capacity
public abstract int capacity();
From source file:org.nd4j.linalg.api.buffer.DoubleDataBufferTest.java
License:Apache License
@Test public void testNettyCopy() { DataBuffer db = Nd4j.createBuffer(new double[] { 1, 2, 3, 4 }); ByteBuf buf = db.asNetty(); if (db.allocationMode() == DataBuffer.AllocationMode.HEAP) return;/*from w w w .j a v a 2s .c om*/ ByteBuf copy = buf.copy(0, buf.capacity()); for (int i = 0; i < db.length(); i++) { assertEquals(db.getDouble(i), copy.getDouble(i * 8)); } }
From source file:org.nd4j.linalg.api.buffer.FloatDataBufferTest.java
License:Apache License
@Test public void testToNio() { DataBuffer buff = Nd4j.createBuffer(new double[] { 1, 2, 3, 4 }); assertEquals(4, buff.length());/*w w w .ja v a 2 s . co m*/ if (buff.allocationMode() == DataBuffer.AllocationMode.HEAP) return; ByteBuffer nio = buff.asNio(); ByteBuf netty = buff.asNetty(); assertEquals(16, netty.capacity()); assertEquals(16, nio.capacity()); }
From source file:org.opendaylight.protocol.rsvp.parser.impl.te.DetourObjectIpv6Parser.java
License:Open Source License
@Override protected RsvpTeObject localParseObject(final ByteBuf byteBuf) { final ByteBuf plrId = byteBuf.readSlice(byteBuf.capacity() / 2); final Ipv6DetourObjectBuilder ipv6Case = new Ipv6DetourObjectBuilder(); final List<PlrId> plrIdList = new ArrayList<>(); while (plrId.isReadable()) { final PlrIdBuilder plr = new PlrIdBuilder(); plr.setPlrId(Ipv6Util.addressForByteBuf(plrId)); plrIdList.add(plr.build());//from w ww .ja v a2 s. co m } final List<AvoidNode> avoidNodeList = new ArrayList<>(); while (byteBuf.isReadable()) { final AvoidNodeBuilder plr = new AvoidNodeBuilder(); plr.setAvoidNode(Ipv6Util.addressForByteBuf(byteBuf)); avoidNodeList.add(plr.build()); } return ipv6Case.setPlrId(plrIdList).setAvoidNode(avoidNodeList).build(); }
From source file:org.opendaylight.sxp.core.service.UpdateExportTask.java
License:Open Source License
@Override public Void call() { //Generate messages for (int i = 0; i < partitions.length; i++) { BiFunction<SxpConnection, SxpBindingFilter, ByteBuf> data; synchronized (partitions) { data = partitions[i];//from ww w. j a v a 2 s.co m partitions[i] = null; } if (data != null) { ByteBuf message = data.apply(connection, connection.getFilter(FilterType.Outbound)); if (message == null) { LOG.error("{} Generated empty partition.", connection); return null; } synchronized (generatedMessages) { generatedMessages[i] = message; generatedMessages.notifyAll(); } } } //Wait for all messages to be generated and then write them to pipeline try { for (int i = 0; i < generatedMessages.length; i++) { ByteBuf message; do { synchronized (generatedMessages) { if ((message = generatedMessages[i]) == null) { generatedMessages.wait(); } } } while (message == null); if (message.capacity() == 0) { LOG.warn("{} Cannot export empty message aborting export", connection); freeReferences(); return null; } } for (int i = 0; i < generatedMessages.length; i++) { connection.getChannelHandlerContext(SxpConnection.ChannelHandlerContextType.SpeakerContext) .writeAndFlush(generatedMessages[i].duplicate().retain()); if (LOG.isTraceEnabled()) { LOG.trace("{} {} UPDATEv{} {}", connection, i, connection.getVersion().getIntValue(), MessageFactory.toString(generatedMessages[i])); } } connection.setUpdateOrKeepaliveMessageTimestamp(); } catch (ChannelHandlerContextNotFoundException | ChannelHandlerContextDiscrepancyException e) { LOG.warn("{} Cannot find context aborting bindings export.", connection); } catch (InterruptedException e) { LOG.warn("{} Bindings export canceled.", connection, e); } freeReferences(); return null; }
From source file:org.opendaylight.sxp.core.service.UpdateExportTaskTest.java
License:Open Source License
@Before public void init() throws Exception { connection = mock(SxpConnection.class); Context context = PowerMockito.mock(Context.class); when(connection.getContext()).thenReturn(context); ByteBuf byteBuf = mock(ByteBuf.class); when(byteBuf.duplicate()).thenReturn(byteBuf); when(byteBuf.capacity()).thenReturn(10); PowerMockito.when(context.executeUpdateMessageStrategy(any(SxpConnection.class), anyList(), anyList(), any(SxpBindingFilter.class))).thenReturn(byteBuf); byteBuffs = new ByteBuf[] { byteBuf }; parttions = new BiFunction[] { (c, f) -> byteBuf }; atomicInteger = new AtomicInteger(1); exportTask = new UpdateExportTask(connection, byteBuffs, parttions, atomicInteger); }
From source file:org.openremote.agent.protocol.velbus.VelbusPacketEncoderDecoder.java
License:Open Source License
public static void decode(ByteBuf buf, List<VelbusPacket> messages) { int startIndex = buf.indexOf(0, buf.capacity() - 1, VelbusPacket.STX); if (startIndex < 0) { return;/*from ww w .j ava2s. c o m*/ } if (startIndex > 0) { buf.readerIndex(startIndex); buf.discardReadBytes(); } if (buf.readableBytes() < 4) { return; } int dataSize = buf.getByte(3); if (buf.readableBytes() < 6 + dataSize) { return; } // Find end of packet int endIndex = buf.indexOf(4 + dataSize, MAX_PACKET_SIZE, VelbusPacket.ETX); if (endIndex < 0) { if (buf.readableBytes() > MAX_PACKET_SIZE) { buf.readerIndex(MAX_PACKET_SIZE); buf.discardReadBytes(); } return; } byte[] packetBytes = new byte[endIndex + 1]; buf.readBytes(packetBytes); buf.discardReadBytes(); VelbusPacket packet = new VelbusPacket(packetBytes); if (packet.isValid()) { messages.add(packet); } }
From source file:org.ratpackframework.groovy.templating.internal.TemplateCompiler.java
License:Apache License
public CompiledTemplate compile(ByteBuf templateSource, String name) throws CompilationFailedException, IOException { ByteBuf scriptSource = byteBufAllocator.buffer(templateSource.capacity()); parser.parse(templateSource, scriptSource); String scriptSourceString = scriptSource.toString(CharsetUtil.UTF_8); if (verbose && logger.isLoggable(Level.INFO)) { logger.info("\n-- script source --\n" + scriptSourceString + "\n-- script end --\n"); }/*w w w .ja v a 2s .co m*/ try { Class<DefaultTemplateScript> scriptClass = scriptEngine.compile(name, scriptSourceString); return new CompiledTemplate(name, scriptClass); } catch (Exception e) { throw new InvalidTemplateException(name, "compilation failure", e); } }
From source file:org.shelloid.vpt.agent.VPTClient.java
License:Open Source License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel();/*w w w . java 2s . c o m*/ if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); handshakeFuture.setSuccess(); onWsAuthenticated(); Platform.shelloidLogger.debug("Client connected using " + ch + ". Now sending init ACK"); sendAckMessage(ch, messenger.getLastSendAckNum()); setChannel(ch); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame; ByteBuf b = binFrame.content(); byte[] bytes = new byte[b.capacity()]; b.getBytes(0, bytes); handleShelloidClientMsg(bytes, ctx.channel()); } else if (frame instanceof TextWebSocketFrame) { throw new Exception("TextWebSocketFrame" + ((TextWebSocketFrame) frame).text()); } else if (frame instanceof PingWebSocketFrame) { ctx.channel().writeAndFlush(new PongWebSocketFrame()); } else if (frame instanceof PongWebSocketFrame) { Platform.shelloidLogger.info("WebSocket Client received pong"); } else if (frame instanceof CloseWebSocketFrame) { Platform.shelloidLogger.info("WebSocket Client received closing"); try { ch.close().sync(); ctx.close().sync(); } catch (InterruptedException ex) { Platform.shelloidLogger.error("InterruptedException while closing channel (channelInactive)"); } } else { throw new Exception("Frame type not supported: " + msg); } }
From source file:org.shelloid.vpt.rms.server.VPTServerHandler.java
License:Open Source License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); } else if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); } else if (frame instanceof BinaryWebSocketFrame) { BinaryWebSocketFrame binFrame = (BinaryWebSocketFrame) frame; ByteBuf b = binFrame.content(); byte[] bytes = new byte[b.capacity()]; b.getBytes(0, bytes);// w w w .ja v a 2 s .c o m processWebSocketTextFrame(ctx.channel(), bytes); } else if (frame instanceof PongWebSocketFrame) { /* Do nothing */ } else if (frame instanceof TextWebSocketFrame) { throw new Exception("TextWebSocketFrame" + ((TextWebSocketFrame) frame).text()); } else { throw new UnsupportedOperationException( String.format("%s frame types not supported", frame.getClass().getName())); } }
From source file:org.spoutcraft.mod.protocol.codec.DownloadLinkCodec.java
License:MIT License
@Override public DownloadLinkMessage decode(Spoutcraft game, ByteBuf buffer) throws IOException { if (game.getSide().isServer()) { throw new IOException("Server is not allowed to receive links!"); }/*from w w w. ja v a 2 s . co m*/ final String addonIdentifier = BufferUtil.readUTF8(buffer); byte[] data = new byte[buffer.capacity() - buffer.readerIndex()]; buffer.readBytes(data); final URL url = (URL) SerializationUtils.deserialize(data); return new DownloadLinkMessage(addonIdentifier, url); }