List of usage examples for io.netty.buffer ByteBuf writeBytes
public abstract int writeBytes(FileChannel in, long position, int length) throws IOException;
From source file:appeng.core.sync.packets.PacketMEInventoryUpdate.java
License:Open Source License
public PacketMEInventoryUpdate(final ByteBuf stream) throws IOException { this.data = null; this.compressFrame = null; this.list = new LinkedList<IAEItemStack>(); this.ref = stream.readByte(); // int originalBytes = stream.readableBytes(); final GZIPInputStream gzReader = new GZIPInputStream(new InputStream() { @Override// w w w .j a va 2 s. com public int read() throws IOException { if (stream.readableBytes() <= 0) { return -1; } return stream.readByte() & STREAM_MASK; } }); final ByteBuf uncompressed = Unpooled.buffer(stream.readableBytes()); final byte[] tmp = new byte[TEMP_BUFFER_SIZE]; while (gzReader.available() != 0) { final int bytes = gzReader.read(tmp); if (bytes > 0) { uncompressed.writeBytes(tmp, 0, bytes); } } gzReader.close(); // int uncompressedBytes = uncompressed.readableBytes(); // AELog.info( "Receiver: " + originalBytes + " -> " + uncompressedBytes ); while (uncompressed.readableBytes() > 0) { this.list.add(AEItemStack.loadItemStackFromPacket(uncompressed)); } this.empty = this.list.isEmpty(); }
From source file:buildcraft.builders.TileBlueprintLibrary.java
License:Minecraft Mod Public
@Override public void receiveCommand(String command, Side side, Object sender, ByteBuf stream) { if (side.isClient()) { if ("requestSelectedBlueprint".equals(command)) { if (isOutputConsistent()) { if (selected > -1 && selected < currentPage.size()) { // Work around 32k max limit on client->server final BlueprintBase bpt = BuildCraftBuilders.clientDB.load(currentPage.get(selected)); final byte[] bptData = bpt.getData(); final int chunks = (bptData.length + CHUNK_SIZE - 1) / CHUNK_SIZE; BuildCraftCore.instance .sendToServer(new PacketCommand(this, "uploadServerBegin", new CommandWriter() { public void write(ByteBuf data) { bpt.id.writeData(data); data.writeShort(chunks); }/* w w w . ja v a 2 s . c o m*/ })); for (int i = 0; i < chunks; i++) { final int chunk = i; final int start = CHUNK_SIZE * chunk; final int length = Math.min(CHUNK_SIZE, bptData.length - start); BuildCraftCore.instance .sendToServer(new PacketCommand(this, "uploadServerChunk", new CommandWriter() { public void write(ByteBuf data) { data.writeShort(chunk); data.writeShort(length); data.writeBytes(bptData, start, length); } })); } BuildCraftCore.instance.sendToServer(new PacketCommand(this, "uploadServerEnd", null)); } else { BuildCraftCore.instance .sendToServer(new PacketCommand(this, "uploadNothingToServer", null)); } } } else if ("downloadBlueprintToClient".equals(command)) { BlueprintId id = new BlueprintId(); id.readData(stream); byte[] data = Utils.readByteArray(stream); try { NBTTagCompound nbt = CompressedStreamTools.func_152457_a(data, NBTSizeTracker.field_152451_a); BlueprintBase bpt = BlueprintBase.loadBluePrint(nbt); bpt.setData(data); bpt.id = id; BuildCraftBuilders.clientDB.add(bpt); setCurrentPage(BuildCraftBuilders.clientDB.getPage(pageId)); } catch (IOException e) { e.printStackTrace(); } } } else if (side.isServer()) { if ("uploadNothingToServer".equals(command)) { setInventorySlotContents(3, getStackInSlot(2)); setInventorySlotContents(2, null); downloadingPlayer = null; } else if ("uploadServerBegin".equals(command)) { blueprintDownloadId = new BlueprintId(); blueprintDownloadId.readData(stream); blueprintDownload = new byte[CHUNK_SIZE * stream.readUnsignedShort()]; } else if ("uploadServerChunk".equals(command)) { int start = stream.readUnsignedShort() * CHUNK_SIZE; int length = stream.readUnsignedShort(); if (blueprintDownload != null) { stream.readBytes(blueprintDownload, start, length); } else { stream.skipBytes(length); } } else if ("uploadServerEnd".equals(command)) { try { NBTTagCompound nbt = CompressedStreamTools.func_152457_a(blueprintDownload, NBTSizeTracker.field_152451_a); BlueprintBase bpt = BlueprintBase.loadBluePrint(nbt); bpt.setData(blueprintDownload); bpt.id = blueprintDownloadId; BuildCraftBuilders.serverDB.add(bpt); setInventorySlotContents(3, bpt.getStack()); setInventorySlotContents(2, null); } catch (IOException e) { e.printStackTrace(); } blueprintDownloadId = null; blueprintDownload = null; downloadingPlayer = null; } } }
From source file:buildcraft.robotics.gui.ContainerZonePlan.java
License:Minecraft Mod Public
private void computeMap(int cx, int cz, int width, int height, float blocksPerPixel, EntityPlayer player) { final byte[] textureData = new byte[width * height]; MapWorld w = BuildCraftRobotics.manager.getWorld(map.getWorldObj()); int startX = Math.round(cx - width * blocksPerPixel / 2); int startZ = Math.round(cz - height * blocksPerPixel / 2); int mapStartX = map.chunkStartX << 4; int mapStartZ = map.chunkStartZ << 4; for (int i = 0; i < width; ++i) { for (int j = 0; j < height; ++j) { int x = Math.round(startX + i * blocksPerPixel); int z = Math.round(startZ + j * blocksPerPixel); int ix = x - mapStartX; int iz = z - mapStartZ; if (ix >= 0 && iz >= 0 && ix < TileZonePlan.RESOLUTION && iz < TileZonePlan.RESOLUTION) { textureData[i + j * width] = (byte) w.getColor(x, z); }//from w w w .j ava 2s . co m } } final int len = MAX_PACKET_LENGTH; for (int i = 0; i < textureData.length; i += len) { final int pos = i; BuildCraftCore.instance.sendToPlayer(player, new PacketCommand(this, "receiveImage", new CommandWriter() { public void write(ByteBuf data) { data.writeMedium(textureData.length); data.writeMedium(pos); data.writeBytes(textureData, pos, Math.min(textureData.length - pos, len)); } })); } }
From source file:buildcraft.robotics.TileZonePlan.java
License:Minecraft Mod Public
@Override public void writeData(ByteBuf stream) { stream.writeShort(progress);//w ww. j a va 2 s.com NetworkUtils.writeUTF(stream, mapName); stream.writeBytes(previewColors, 0, 80); }
From source file:com.addthis.meshy.ChannelState.java
License:Apache License
public ByteBuf allocateSendBuffer(int type, int session, byte[] data, int off, int len) { ByteBuf sendBuffer = allocateSendBuffer(type, session, len); sendBuffer.writeBytes(data, off, len); return sendBuffer; }
From source file:com.cc.nettytest.proxy.decoder.CCLengthFieldBasedFrameDecoder.java
License:Apache License
/** * Extract the sub-region of the specified buffer. This method is called by * {@link #decode(ChannelInboundHandlerContext, ByteBuf)} for each * frame. The default implementation returns a copy of the sub-region. * For example, you could override this method to use an alternative * {@link ByteBufFactory}.//from w w w . ja v a 2 s . c o m * <p> * If you are sure that the frame and its content are not accessed after * the current {@link #decode(ChannelInboundHandlerContext, ByteBuf)} * call returns, you can even avoid memory copy by returning the sliced * sub-region (i.e. <tt>return buffer.slice(index, length)</tt>). * It's often useful when you convert the extracted frame into an object. * Refer to the source code of {@link ObjectDecoder} to see how this method * is overridden to avoid memory copy. */ protected ByteBuf extractFrame(ByteBuf buffer, int index, int length) { ByteBuf frame = Unpooled.buffer(length); frame.writeBytes(buffer, index, length); return frame; }
From source file:com.cc.nettytest.proxy.encoder.CCLengthFieldPrepender.java
License:Apache License
@Override public void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception { int length = lengthIncludesLengthFieldLength ? msg.readableBytes() + lengthFieldLength : msg.readableBytes();/*from w ww . j a v a 2 s .c o m*/ switch (lengthFieldLength) { case 1: if (length >= 256) { throw new IllegalArgumentException("length does not fit into a byte: " + length); } out.writeByte((byte) length); break; case 2: if (length >= 65536) { throw new IllegalArgumentException("length does not fit into a short integer: " + length); } out.writeShort((short) length); break; case 3: if (length >= 16777216) { throw new IllegalArgumentException("length does not fit into a medium integer: " + length); } out.writeMedium(length); break; case 4: out.writeInt(ByteBufUtil.swapInt((int) length)); //SWAP FOR UIMANAGER break; case 8: out.writeLong(length); break; default: throw new Error("should not reach here"); } out.writeBytes(msg, msg.readerIndex(), msg.readableBytes()); }
From source file:com.chat.common.netty.handler.encode.ProtobufVarint32LengthFieldPrepender.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception { int bodyLen = msg.readableBytes(); int headerLen = computeRawVarint32Size(bodyLen); out.ensureWritable(headerLen + bodyLen); writeRawVarint32(out, bodyLen);//from ww w . j ava 2s. co m out.writeBytes(msg, msg.readerIndex(), bodyLen); }
From source file:com.couchbase.client.core.endpoint.binary.BinaryHandler.java
License:Open Source License
@Override protected CouchbaseResponse decodeResponse(final ChannelHandlerContext ctx, final FullBinaryMemcacheResponse msg) throws Exception { BinaryRequest request = currentRequest(); ResponseStatus status = convertStatus(msg.getStatus()); CouchbaseResponse response;/*from ww w .j a va 2s . c o m*/ ByteBuf content = msg.content().copy(); long cas = msg.getCAS(); String bucket = request.bucket(); if (request instanceof GetRequest || request instanceof ReplicaGetRequest) { int flags = 0; if (msg.getExtrasLength() > 0) { final ByteBuf extrasReleased = msg.getExtras(); final ByteBuf extras = ctx.alloc().buffer(msg.getExtrasLength()); extras.writeBytes(extrasReleased, extrasReleased.readerIndex(), extrasReleased.readableBytes()); flags = extras.getInt(0); extras.release(); } response = new GetResponse(status, cas, flags, bucket, content, request); } else if (request instanceof GetBucketConfigRequest) { response = new GetBucketConfigResponse(status, bucket, content, ((GetBucketConfigRequest) request).hostname()); } else if (request instanceof InsertRequest) { response = new InsertResponse(status, cas, bucket, content, request); } else if (request instanceof UpsertRequest) { response = new UpsertResponse(status, cas, bucket, content, request); } else if (request instanceof ReplaceRequest) { response = new ReplaceResponse(status, cas, bucket, content, request); } else if (request instanceof RemoveRequest) { response = new RemoveResponse(status, bucket, content, request); } else if (request instanceof CounterRequest) { response = new CounterResponse(status, bucket, msg.content().readLong(), cas, request); } else if (request instanceof UnlockRequest) { response = new UnlockResponse(status, bucket, content, request); } else if (request instanceof TouchRequest) { response = new TouchResponse(status, bucket, content, request); } else if (request instanceof ObserveRequest) { byte observed = content.getByte(content.getShort(2) + 4); response = new ObserveResponse(status, observed, ((ObserveRequest) request).master(), bucket, content, request); } else if (request instanceof AppendRequest) { response = new AppendResponse(status, cas, bucket, content, request); } else if (request instanceof PrependRequest) { response = new PrependResponse(status, cas, bucket, content, request); } else { throw new IllegalStateException( "Unhandled request/response pair: " + request.getClass() + "/" + msg.getClass()); } return response; }
From source file:com.difference.historybook.proxy.littleproxy.LittleProxyResponseTest.java
License:Apache License
private void testGetContent(String msg, ByteBuf buffer) { FullHttpResponse response = mock(FullHttpResponse.class); byte[] bytes = msg.getBytes(Charsets.UTF_8); buffer.writeBytes(bytes, 0, bytes.length); when(response.content()).thenReturn(buffer); LittleProxyResponse lpr = new LittleProxyResponse(response); assertArrayEquals(bytes, lpr.getContent()); }