List of usage examples for io.netty.buffer CompositeByteBuf addComponent
public CompositeByteBuf addComponent(ByteBuf buffer)
From source file:org.dcache.xrootd.protocol.messages.ReadVResponse.java
License:Open Source License
@Override public void writeTo(ChannelHandlerContext ctx, ChannelPromise promise) { checkState(refCnt() > 0);//ww w .j a va 2 s . c o m CompositeByteBuf buffer = ctx.alloc().compositeBuffer(2 * length + 1); ByteBuf header = ctx.alloc().buffer(8); header.writeShort(request.getStreamId()); header.writeShort(stat); header.writeInt(getDataLength()); buffer.addComponent(header); for (int i = 0; i < length; i++) { header = ctx.alloc().buffer(READ_LIST_HEADER_SIZE); header.writeInt(requests[index + i].getFileHandle()); header.writeInt(data[index + i].readableBytes()); header.writeLong(requests[index + i].getOffset()); buffer.addComponent(header); buffer.addComponent(data[index + i].retain()); } buffer.writerIndex(buffer.capacity()); ctx.write(buffer, promise); release(); }
From source file:org.eclipse.milo.opcua.sdk.client.DataTypeDictionaryReader.java
License:Open Source License
private CompletableFuture<ByteBuf> readFragments(NodeId nodeId, CompositeByteBuf fragmentBuffer, int fragmentSize, int index) { Preconditions.checkArgument(fragmentSize > 0, "fragmentSize=" + fragmentSize); String indexRange = fragmentSize <= 1 ? String.valueOf(index) : String.format("%d:%d", index, index + fragmentSize - 1); CompletableFuture<DataValue> valueFuture = readNode( new ReadValueId(nodeId, AttributeId.Value.uid(), indexRange, QualifiedName.NULL_VALUE)); return valueFuture.thenComposeAsync(value -> { StatusCode statusCode = value.getStatusCode(); if (statusCode == null || statusCode.isGood()) { ByteString fragmentBytes = (ByteString) value.getValue().getValue(); if (fragmentBytes != null) { int bytesRead = fragmentBytes.length(); if (bytesRead > 0) { fragmentBuffer.addComponent(Unpooled.wrappedBuffer(fragmentBytes.bytesOrEmpty())); fragmentBuffer.writerIndex(fragmentBuffer.writerIndex() + bytesRead); }//from w ww .j a v a2 s . c o m if (bytesRead < fragmentSize) { // A partial fragment means this is the last read that will // succeed; don't bother trying to read the next fragment. return completedFuture(fragmentBuffer); } else if (bytesRead > fragmentSize) { // Some servers don't support index range properly and just // return the entire contents. when this happens, we can assume // we've read everything there is to read. // An edge case where the dictionary size is exactly equal to the // fragment size still exists. In this case we must hope the server // properly terminates the subsequent request with something like // Bad_IndexRangeNoData or else the infinite loop could still happen. return completedFuture(fragmentBuffer); } else { return readFragments(nodeId, fragmentBuffer, fragmentSize, index + bytesRead); } } else { logger.warn("Read a null type dictionary " + "fragment at indexRange=\"%s\"", indexRange); return completedFuture(fragmentBuffer); } } else { if (statusCode.getValue() != StatusCodes.Bad_IndexRangeNoData) { logger.warn("Reading type dictionary fragments expected to " + "terminate with Bad_IndexRangeNoData but got {}", statusCode); } return completedFuture(fragmentBuffer); } }); }
From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler.java
License:Open Source License
private void sendOpenSecureChannelRequest(ChannelHandlerContext ctx, SecurityTokenRequestType requestType) { ByteString clientNonce = secureChannel.isSymmetricSigningEnabled() ? NonceUtil.generateNonce(secureChannel.getSecurityPolicy()) : ByteString.NULL_VALUE;//from ww w . j av a 2s .co m secureChannel.setLocalNonce(clientNonce); RequestHeader header = new RequestHeader(null, DateTime.now(), uint(0), uint(0), null, config.getRequestTimeout(), null); OpenSecureChannelRequest request = new OpenSecureChannelRequest(header, uint(PROTOCOL_VERSION), requestType, secureChannel.getMessageSecurityMode(), secureChannel.getLocalNonce(), config.getChannelLifetime()); serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.pooledBuffer(); try { binaryEncoder.setBuffer(messageBuffer); binaryEncoder.writeMessage(null, request); checkMessageSize(messageBuffer); chunkEncoder.encodeAsymmetric(secureChannel, requestIdSequence.getAndIncrement(), messageBuffer, MessageType.OpenSecureChannel, new ChunkEncoder.Callback() { @Override public void onEncodingError(UaException ex) { logger.error("Error encoding {}: {}", request, ex.getMessage(), ex); ctx.close(); } @Override public void onMessageEncoded(List<ByteBuf> messageChunks, long requestId) { CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer(); for (ByteBuf chunk : messageChunks) { chunkComposite.addComponent(chunk); chunkComposite .writerIndex(chunkComposite.writerIndex() + chunk.readableBytes()); } ctx.writeAndFlush(chunkComposite, ctx.voidPromise()); ChannelSecurity channelSecurity = secureChannel.getChannelSecurity(); long currentTokenId = -1L; if (channelSecurity != null) { currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue(); } long previousTokenId = -1L; if (channelSecurity != null) { previousTokenId = channelSecurity.getPreviousToken() .map(token -> token.getTokenId().longValue()).orElse(-1L); } logger.debug( "Sent OpenSecureChannelRequest ({}, id={}, currentToken={}, previousToken={}).", request.getRequestType(), secureChannel.getChannelId(), currentTokenId, previousTokenId); } }); } finally { messageBuffer.release(); } }); }
From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler.java
License:Open Source License
private void sendCloseSecureChannelRequest(ChannelHandlerContext ctx, CloseSecureChannelRequest request) { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.pooledBuffer(); try {//from w w w.j av a 2 s .c o m binaryEncoder.setBuffer(messageBuffer); binaryEncoder.writeMessage(null, request); checkMessageSize(messageBuffer); chunkEncoder.encodeSymmetric(secureChannel, requestIdSequence.getAndIncrement(), messageBuffer, MessageType.CloseSecureChannel, new ChunkEncoder.Callback() { @Override public void onEncodingError(UaException ex) { logger.error("Error encoding {}: {}", request, ex.getMessage(), ex); ctx.close(); } @Override public void onMessageEncoded(List<ByteBuf> messageChunks, long requestId) { CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer(); for (ByteBuf chunk : messageChunks) { chunkComposite.addComponent(chunk); chunkComposite .writerIndex(chunkComposite.writerIndex() + chunk.readableBytes()); } ctx.writeAndFlush(chunkComposite).addListener(future -> ctx.close()); secureChannel.setChannelId(0); } }); } catch (UaSerializationException e) { handshakeFuture.completeExceptionally(e); ctx.close(); } finally { messageBuffer.release(); } }); }
From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, UaTransportRequest request, ByteBuf buffer) { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.pooledBuffer(); try {/*from w ww. j av a 2 s . co m*/ binaryEncoder.setBuffer(messageBuffer); binaryEncoder.writeMessage(null, request.getRequest()); checkMessageSize(messageBuffer); chunkEncoder.encodeSymmetric(secureChannel, requestIdSequence.getAndIncrement(), messageBuffer, MessageType.SecureMessage, new ChunkEncoder.Callback() { @Override public void onEncodingError(UaException ex) { logger.error("Error encoding {}: {}", request.getRequest(), ex.getMessage(), ex); ctx.close(); } @Override public void onMessageEncoded(List<ByteBuf> messageChunks, long requestId) { pending.put(requestId, request); // No matter how we complete, make sure the entry in pending is removed. // This covers the case where the request fails due to a timeout in the // transport layer as well as normal completion. request.getFuture().whenComplete((r, x) -> pending.remove(requestId)); CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer(); for (ByteBuf chunk : messageChunks) { chunkComposite.addComponent(chunk); chunkComposite .writerIndex(chunkComposite.writerIndex() + chunk.readableBytes()); } ctx.writeAndFlush(chunkComposite, ctx.voidPromise()); } }); } catch (UaSerializationException e) { request.getFuture().completeExceptionally(e); } finally { messageBuffer.release(); } }); }
From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerAsymmetricHandler.java
License:Open Source License
private void sendOpenSecureChannelResponse(ChannelHandlerContext ctx, long requestId, OpenSecureChannelRequest request) { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.pooledBuffer(); try {//www . j a v a 2 s . c o m OpenSecureChannelResponse response = openSecureChannel(ctx, request); binaryEncoder.setBuffer(messageBuffer); binaryEncoder.writeMessage(null, response); checkMessageSize(messageBuffer); chunkEncoder.encodeAsymmetric(secureChannel, requestId, messageBuffer, MessageType.OpenSecureChannel, new ChunkEncoder.Callback() { @Override public void onEncodingError(UaException ex) { logger.error("Error encoding OpenSecureChannelResponse: {}", ex.getMessage(), ex); ctx.fireExceptionCaught(ex); } @Override public void onMessageEncoded(List<ByteBuf> messageChunks, long requestId) { if (!symmetricHandlerAdded) { UascServerSymmetricHandler symmetricHandler = new UascServerSymmetricHandler( stackServer, serializationQueue, secureChannel); ctx.pipeline().addBefore(ctx.name(), null, symmetricHandler); symmetricHandlerAdded = true; } CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer(); for (ByteBuf chunk : messageChunks) { chunkComposite.addComponent(chunk); chunkComposite .writerIndex(chunkComposite.writerIndex() + chunk.readableBytes()); } ctx.writeAndFlush(chunkComposite, ctx.voidPromise()); logger.debug("Sent OpenSecureChannelResponse."); } }); } catch (UaException e) { logger.error("Error installing security token: {}", e.getStatusCode(), e); ctx.close(); } catch (UaSerializationException e) { ctx.fireExceptionCaught(e); } finally { messageBuffer.release(); } }); }
From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerSymmetricHandler.java
License:Open Source License
private void sendServiceResponse(ChannelHandlerContext ctx, long requestId, UaRequestMessage request, UaResponseMessage response) {//from w w w . ja v a 2 s. co m serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.pooledBuffer(); try { binaryEncoder.setBuffer(messageBuffer); binaryEncoder.writeMessage(null, response); checkMessageSize(messageBuffer); chunkEncoder.encodeSymmetric(secureChannel, requestId, messageBuffer, MessageType.SecureMessage, new ChunkEncoder.Callback() { @Override public void onEncodingError(UaException ex) { logger.error("Error encoding {}: {}", response, ex.getMessage(), ex); UInteger requestHandle = request.getRequestHeader().getRequestHandle(); sendServiceFault(ctx, requestId, requestHandle, ex); } @Override public void onMessageEncoded(List<ByteBuf> messageChunks, long requestId) { CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer(); for (ByteBuf chunk : messageChunks) { chunkComposite.addComponent(chunk); chunkComposite .writerIndex(chunkComposite.writerIndex() + chunk.readableBytes()); } ctx.writeAndFlush(chunkComposite, ctx.voidPromise()); } }); } catch (UaSerializationException ex) { logger.error("Error encoding response: {}", ex.getStatusCode(), ex); UInteger requestHandle = request.getRequestHeader().getRequestHandle(); sendServiceFault(ctx, requestId, requestHandle, ex); } finally { messageBuffer.release(); } }); }
From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerSymmetricHandler.java
License:Open Source License
private void sendServiceFault(ChannelHandlerContext ctx, long requestId, UInteger requestHandle, Throwable fault) {//from w w w . jav a2 s . co m StatusCode statusCode = UaException.extract(fault).map(UaException::getStatusCode).orElse(StatusCode.BAD); ServiceFault serviceFault = new ServiceFault( new ResponseHeader(DateTime.now(), requestHandle, statusCode, null, null, null)); serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.pooledBuffer(); try { binaryEncoder.setBuffer(messageBuffer); binaryEncoder.writeMessage(null, serviceFault); checkMessageSize(messageBuffer); chunkEncoder.encodeSymmetric(secureChannel, requestId, messageBuffer, MessageType.SecureMessage, new ChunkEncoder.Callback() { @Override public void onEncodingError(UaException ex) { logger.error("Error encoding {}: {}", serviceFault, ex.getMessage(), ex); } @Override public void onMessageEncoded(List<ByteBuf> messageChunks, long requestId) { CompositeByteBuf chunkComposite = BufferUtil.compositeBuffer(); for (ByteBuf chunk : messageChunks) { chunkComposite.addComponent(chunk); chunkComposite .writerIndex(chunkComposite.writerIndex() + chunk.readableBytes()); } ctx.writeAndFlush(chunkComposite, ctx.voidPromise()); } }); } catch (UaSerializationException ex) { logger.error("Error encoding ServiceFault: {}", ex.getStatusCode(), ex); } finally { messageBuffer.release(); } }); }
From source file:org.vertx.java.core.http.impl.DefaultHttpClientRequest.java
License:Open Source License
private DefaultHttpClientRequest write(ByteBuf buff, boolean end) { int readableBytes = buff.readableBytes(); if (readableBytes == 0 && !end) { // nothing to write to the connection just return return this; }/*from w w w . j ava 2 s.c o m*/ if (end) { completed = true; } written += buff.readableBytes(); if (!end && !raw && !chunked && !contentLengthSet()) { throw new IllegalStateException( "You must set the Content-Length header to be the total size of the message " + "body BEFORE sending any data if you are not using HTTP chunked encoding."); } if (conn == null) { if (pendingChunks == null) { pendingChunks = buff; } else { CompositeByteBuf pending; if (pendingChunks instanceof CompositeByteBuf) { pending = (CompositeByteBuf) pendingChunks; } else { pending = Unpooled.compositeBuffer(); pending.addComponent(pendingChunks).writerIndex(pendingChunks.writerIndex()); pendingChunks = pending; } pending.addComponent(buff).writerIndex(pending.writerIndex() + buff.writerIndex()); } connect(); } else { if (!headWritten) { writeHeadWithContent(buff, end); } else { if (end) { writeEndChunk(buff); } else { sendChunk(buff); } } if (end) { conn.endRequest(); } } return this; }
From source file:org.wso2.carbon.gateway.internal.mediation.camel.CarbonMessageTypeConverter.java
License:Open Source License
private CompositeByteBuf aggregateChunks(Pipe pipe) { ByteBufInputStream byteBufInputStream = null; //Create an instance of composite byte buffer to hold the content chunks CompositeByteBuf content = new UnpooledByteBufAllocator(true).compositeBuffer(); try {//from w ww .j av a2s .c o m //Check whether the pipe is filled with HTTP content chunks up to last chunk while (pipe.isEmpty() || !pipe.isLastChunkAdded()) { Thread.sleep(10); } //Get a clone of content chunk queue from the pipe BlockingQueue<ContentChunk> clonedContent = pipe.getClonedContentQueue(); //Traverse through the http content chunks and create the composite buffer while (true) { if (!clonedContent.isEmpty()) { //Retrieve the HTTP content chunk from cloned queue HttpContent chunk = ((HTTPContentChunk) clonedContent.take()).getHttpContent(); // Append the content of the chunk to the composite buffer if (chunk.content().isReadable()) { chunk.retain(); content.addComponent(chunk.content()); content.writerIndex(content.writerIndex() + chunk.content().readableBytes()); } } else { //When all the content chunks are read, break from the loop break; } } } catch (Exception e) { log.error("Error occurred during conversion from CarbonMessage", e); } //Return the composite buffer return content; }