List of usage examples for io.netty.buffer ByteBuf retain
@Override public abstract ByteBuf retain();
From source file:com.chat.common.netty.handler.encode.LengthFieldPrepender.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { int length = msg.readableBytes() + lengthAdjustment; if (lengthIncludesLengthFieldLength) { length += lengthFieldLength;/*w w w . ja v a 2 s. c om*/ } if (length < 0) { throw new IllegalArgumentException("Adjusted frame length (" + length + ") is less than zero"); } switch (lengthFieldLength) { case 1: if (length >= 256) { throw new IllegalArgumentException("length does not fit into a byte: " + length); } out.add(ctx.alloc().buffer(1).order(byteOrder).writeByte((byte) length)); break; case 2: if (length >= 65536) { throw new IllegalArgumentException("length does not fit into a short integer: " + length); } out.add(ctx.alloc().buffer(2).order(byteOrder).writeShort((short) length)); break; case 3: if (length >= 16777216) { throw new IllegalArgumentException("length does not fit into a medium integer: " + length); } out.add(ctx.alloc().buffer(3).order(byteOrder).writeMedium(length)); break; case 4: out.add(ctx.alloc().buffer(4).order(byteOrder).writeInt(length)); break; case 8: out.add(ctx.alloc().buffer(8).order(byteOrder).writeLong(length)); break; default: throw new Error("should not reach here"); } out.add(msg.retain()); }
From source file:com.chiorichan.http.HttpResponseWrapper.java
License:Mozilla Public License
/** * Writes a ByteBuf to the buffered output * * @param buf// ww w . j av a2 s . co m * byte buffer to print * @throws IOException * if there was a problem with the output buffer. */ public void write(ByteBuf buf) throws IOException { if (stage != HttpResponseStage.MULTIPART) stage = HttpResponseStage.WRITTING; output.writeBytes(buf.retain()); }
From source file:com.cisco.oss.foundation.http.netlifx.netty.NettyNetflixHttpClient.java
License:Apache License
@Override public void executeWithLoadBalancer(HttpRequest request, final ResponseCallback<NettyNetflixHttpResponse> responseCallback) { HttpClientRequest<ByteBuf> httpRequest = buildNetflixHttpRequest(request, joiner); rx.Observable<HttpClientResponse<ByteBuf>> responseObservable = httpClient.submit(httpRequest, retryHandler, clientConfig);// w ww . j a va 2s . c o m responseObservable.subscribe(new Subscriber<HttpClientResponse<ByteBuf>>() { @Override public void onCompleted() { LOGGER.debug("Http Response Completed"); } @Override public void onError(Throwable e) { LOGGER.error("error serving request: {}", e, e); responseCallback.failed(e); } @Override public void onNext(HttpClientResponse<ByteBuf> httpClientResponse) { httpClientResponse.getContent().subscribe(new Subscriber<ByteBuf>() { private ByteBuf responseContent = null; @Override public void onCompleted() { responseCallback .completed(new NettyNetflixHttpResponse(httpClientResponse, responseContent)); } @Override public void onError(Throwable e) { LOGGER.error("error serving request: {}", e, e); responseCallback.failed(e); } @Override public void onNext(ByteBuf content) { content.retain(); this.responseContent = content; } }); } }); }
From source file:com.couchbase.client.core.cluster.SubdocumentMessageTest.java
License:Apache License
@Test public void shouldFailSomeMultiMutationsAndReleaseCommandFragments() { ByteBuf counterFragment = Unpooled.copiedBuffer("-404", CharsetUtil.UTF_8); counterFragment.retain(); ByteBuf stringFragment = Unpooled.copiedBuffer("\"mutated\"", CharsetUtil.UTF_8); stringFragment.retain(2);//from w w w . j av a2 s .c o m ByteBuf arrayInsertedFragment = Unpooled.copiedBuffer("\"inserted\"", CharsetUtil.UTF_8); ByteBuf arrayFirstFragment = Unpooled.copiedBuffer("\"first\"", CharsetUtil.UTF_8); ByteBuf arrayLastFragment = Unpooled.copiedBuffer("\"last\"", CharsetUtil.UTF_8); ByteBuf uniqueFragment = Unpooled.copiedBuffer("\"unique\"", CharsetUtil.UTF_8); SubMultiMutationRequest request = new SubMultiMutationRequest(testSubKey, bucket(), new MutationCommand(Mutation.COUNTER, "counter", counterFragment, false), new MutationCommand(Mutation.COUNTER, "another.counter", counterFragment, true), new MutationCommand(Mutation.DICT_ADD, "sub.value2", stringFragment), new MutationCommand(Mutation.DICT_UPSERT, "sub.value3", stringFragment), new MutationCommand(Mutation.REPLACE, "value", stringFragment), //this one fails new MutationCommand(Mutation.ARRAY_INSERT, "sub.array[5]", arrayInsertedFragment), new MutationCommand(Mutation.ARRAY_PUSH_FIRST, "sub.array", arrayFirstFragment), new MutationCommand(Mutation.ARRAY_PUSH_LAST, "sub.array", arrayLastFragment), new MutationCommand(Mutation.ARRAY_ADD_UNIQUE, "sub.array", uniqueFragment), //this one would also fail, but server stops at first failure new MutationCommand(Mutation.DELETE, "path.not.found")); MultiMutationResponse response = cluster().<MultiMutationResponse>send(request).toBlocking().single(); assertEquals(ResponseStatus.SUBDOC_MULTI_PATH_FAILURE, response.status()); assertEquals(Unpooled.EMPTY_BUFFER, response.content()); assertEquals(5, response.firstErrorIndex()); assertEquals(ResponseStatus.SUBDOC_PATH_NOT_FOUND, response.firstErrorStatus()); assertEquals(0, response.responses().size()); assertEquals(0, stringFragment.refCnt()); assertEquals(0, counterFragment.refCnt()); assertEquals(0, arrayInsertedFragment.refCnt()); assertEquals(0, arrayFirstFragment.refCnt()); assertEquals(0, arrayLastFragment.refCnt()); assertEquals(0, uniqueFragment.refCnt()); //no mutation happened String expected = jsonContent; assertMutation(testSubKey, expected); }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAsymmetricHandler.java
License:Apache License
private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize long secureChannelId = buffer.readUnsignedInt(); secureChannel.setChannelId(secureChannelId); AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer); if (!headerRef.compareAndSet(null, securityHeader)) { if (!securityHeader.equals(headerRef.get())) { throw new UaRuntimeException(StatusCodes.Bad_SecurityChecksFailed, "subsequent AsymmetricSecurityHeader did not match"); }// ww w. j a v a 2s .co m } int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); } chunkBuffers.add(buffer.retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } char chunkType = (char) buffer.getByte(3); if (chunkType == 'A' || chunkType == 'F') { final List<ByteBuf> buffersToDecode = chunkBuffers; chunkBuffers = new ArrayList<>(maxChunkCount); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { ByteBuf decodedBuffer = null; try { decodedBuffer = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode); UaResponseMessage responseMessage = binaryDecoder.setBuffer(decodedBuffer).decodeMessage(null); StatusCode serviceResult = responseMessage.getResponseHeader().getServiceResult(); if (serviceResult.isGood()) { OpenSecureChannelResponse response = (OpenSecureChannelResponse) responseMessage; secureChannel.setChannelId(response.getSecurityToken().getChannelId().longValue()); logger.debug("Received OpenSecureChannelResponse."); installSecurityToken(ctx, response); } else { ServiceFault serviceFault = (responseMessage instanceof ServiceFault) ? (ServiceFault) responseMessage : new ServiceFault(responseMessage.getResponseHeader()); throw new UaServiceFaultException(serviceFault); } } catch (MessageAbortedException e) { logger.error("Received message abort chunk; error={}, reason={}", e.getStatusCode(), e.getMessage()); ctx.close(); } catch (Throwable t) { logger.error("Error decoding OpenSecureChannelResponse: {}", t.getMessage(), t); ctx.close(); } finally { if (decodedBuffer != null) { decodedBuffer.release(); } buffersToDecode.clear(); } }); } }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java
License:Apache License
private boolean accumulateChunk(ByteBuf buffer) throws UaException { int maxChunkCount = serializationQueue.getParameters().getLocalMaxChunkCount(); int maxChunkSize = serializationQueue.getParameters().getLocalReceiveBufferSize(); int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); }/* ww w.java 2s .c om*/ chunkBuffers.add(buffer.retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } char chunkType = (char) buffer.getByte(3); return (chunkType == 'A' || chunkType == 'F'); }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java
License:Apache License
private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { buffer.skipBytes(3 + 1 + 4); // skip messageType, chunkType, messageSize long secureChannelId = buffer.readUnsignedInt(); if (secureChannelId != secureChannel.getChannelId()) { throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid, "invalid secure channel id: " + secureChannelId); }/* w ww . j ava 2s . c o m*/ int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); } chunkBuffers.add(buffer.retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } char chunkType = (char) buffer.getByte(3); if (chunkType == 'A' || chunkType == 'F') { final List<ByteBuf> buffersToDecode = chunkBuffers; chunkBuffers = new ArrayList<>(maxChunkCount); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { ByteBuf decodedBuffer = null; try { validateChunkHeaders(buffersToDecode); decodedBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode); binaryDecoder.setBuffer(decodedBuffer); UaResponseMessage response = binaryDecoder.decodeMessage(null); UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId()); if (request != null) { client.getExecutorService().execute(() -> request.getFuture().complete(response)); } else { logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId()); } } catch (MessageAbortedException e) { logger.debug("Received message abort chunk; error={}, reason={}", e.getStatusCode(), e.getMessage()); UaRequestFuture request = pending.remove(chunkDecoder.getLastRequestId()); if (request != null) { client.getExecutorService().execute(() -> request.getFuture().completeExceptionally(e)); } else { logger.warn("No UaRequestFuture for requestId={}", chunkDecoder.getLastRequestId()); } } catch (Throwable t) { logger.error("Error decoding symmetric message: {}", t.getMessage(), t); ctx.close(); serializationQueue.pause(); } finally { if (decodedBuffer != null) { decodedBuffer.release(); } buffersToDecode.clear(); } }); } }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerAsymmetricHandler.java
License:Apache License
private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { buffer.skipBytes(3); // Skip messageType char chunkType = (char) buffer.readByte(); if (chunkType == 'A') { chunkBuffers.forEach(ByteBuf::release); chunkBuffers.clear();// ww w.ja va 2 s. c o m headerRef.set(null); } else { buffer.skipBytes(4); // Skip messageSize long secureChannelId = buffer.readUnsignedInt(); AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer); if (secureChannelId == 0) { // Okay, this is the first OpenSecureChannelRequest... carry on. String endpointUrl = ctx.channel().attr(UaTcpServerHelloHandler.ENDPOINT_URL_KEY).get(); String securityPolicyUri = securityHeader.getSecurityPolicyUri(); EndpointDescription endpointDescription = Arrays.stream(server.getEndpointDescriptions()) .filter(e -> { String s1 = pathOrUrl(endpointUrl); String s2 = pathOrUrl(e.getEndpointUrl()); boolean uriMatch = s1.equals(s2); boolean policyMatch = e.getSecurityPolicyUri().equals(securityPolicyUri); return uriMatch && policyMatch; }).findFirst().orElse(null); if (endpointDescription == null && !server.getConfig().isStrictEndpointUrlsEnabled()) { endpointDescription = Arrays.stream(server.getEndpointDescriptions()) .filter(e -> e.getSecurityPolicyUri().equals(securityPolicyUri)).findFirst() .orElse(null); } if (endpointDescription == null) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "SecurityPolicy URI did not match"); } secureChannel = server.openSecureChannel(); secureChannel.setEndpointDescription(endpointDescription); } else { secureChannel = server.getSecureChannel(secureChannelId); if (secureChannel == null) { throw new UaException(StatusCodes.Bad_TcpSecureChannelUnknown, "unknown secure channel id: " + secureChannelId); } if (!secureChannel.getRemoteCertificateBytes().equals(securityHeader.getSenderCertificate())) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "certificate requesting renewal did not match existing certificate."); } Channel boundChannel = secureChannel.attr(UaTcpStackServer.BoundChannelKey).get(); if (boundChannel != null && boundChannel != ctx.channel()) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "received a renewal request from channel other than the bound channel."); } } if (!headerRef.compareAndSet(null, securityHeader)) { if (!securityHeader.equals(headerRef.get())) { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "subsequent AsymmetricSecurityHeader did not match"); } } SecurityPolicy securityPolicy = SecurityPolicy.fromUri(securityHeader.getSecurityPolicyUri()); secureChannel.setSecurityPolicy(securityPolicy); if (!securityHeader.getSenderCertificate().isNull() && securityPolicy != SecurityPolicy.None) { secureChannel.setRemoteCertificate(securityHeader.getSenderCertificate().bytes()); try { CertificateValidator certificateValidator = server.getCertificateValidator(); certificateValidator.validate(secureChannel.getRemoteCertificate()); certificateValidator.verifyTrustChain(secureChannel.getRemoteCertificate(), secureChannel.getRemoteCertificateChain()); } catch (UaException e) { try { UaException cause = new UaException(e.getStatusCode(), "security checks failed"); ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause); logger.debug("[remote={}] {}.", ctx.channel().remoteAddress(), errorMessage.getReason(), cause); } catch (Exception ignored) { } } } if (!securityHeader.getReceiverThumbprint().isNull()) { CertificateManager certificateManager = server.getCertificateManager(); Optional<X509Certificate> localCertificate = certificateManager .getCertificate(securityHeader.getReceiverThumbprint()); Optional<KeyPair> keyPair = certificateManager.getKeyPair(securityHeader.getReceiverThumbprint()); if (localCertificate.isPresent() && keyPair.isPresent()) { secureChannel.setLocalCertificate(localCertificate.get()); secureChannel.setKeyPair(keyPair.get()); } else { throw new UaException(StatusCodes.Bad_SecurityChecksFailed, "no certificate for provided thumbprint"); } } int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); } chunkBuffers.add(buffer.retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } if (chunkType == 'F') { final List<ByteBuf> buffersToDecode = chunkBuffers; chunkBuffers = new ArrayList<>(maxChunkCount); headerRef.set(null); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { ByteBuf messageBuffer = null; try { messageBuffer = chunkDecoder.decodeAsymmetric(secureChannel, buffersToDecode); OpenSecureChannelRequest request = binaryDecoder.setBuffer(messageBuffer) .decodeMessage(null); logger.debug("Received OpenSecureChannelRequest ({}, id={}).", request.getRequestType(), secureChannelId); long requestId = chunkDecoder.getLastRequestId(); installSecurityToken(ctx, request, requestId); } catch (UaException e) { logger.error("Error decoding asymmetric message: {}", e.getMessage(), e); ctx.close(); } finally { if (messageBuffer != null) { messageBuffer.release(); } buffersToDecode.clear(); } }); } } }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerSymmetricHandler.java
License:Apache License
private void onSecureMessage(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws UaException { buffer.skipBytes(3); // Skip messageType char chunkType = (char) buffer.readByte(); if (chunkType == 'A') { chunkBuffers.forEach(ByteBuf::release); chunkBuffers.clear();//from w ww . ja v a 2 s.c o m } else { buffer.skipBytes(4); // Skip messageSize long secureChannelId = buffer.readUnsignedInt(); if (secureChannelId != secureChannel.getChannelId()) { throw new UaException(StatusCodes.Bad_SecureChannelIdInvalid, "invalid secure channel id: " + secureChannelId); } int chunkSize = buffer.readerIndex(0).readableBytes(); if (chunkSize > maxChunkSize) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk size exceeded (%s)", maxChunkSize)); } chunkBuffers.add(buffer.retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } if (chunkType == 'F') { final List<ByteBuf> buffersToDecode = chunkBuffers; chunkBuffers = new ArrayList<>(maxChunkCount); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { try { validateChunkHeaders(buffersToDecode); ByteBuf messageBuffer = chunkDecoder.decodeSymmetric(secureChannel, buffersToDecode); binaryDecoder.setBuffer(messageBuffer); UaRequestMessage request = binaryDecoder.decodeMessage(null); ServiceRequest<UaRequestMessage, UaResponseMessage> serviceRequest = new ServiceRequest<>( request, chunkDecoder.getLastRequestId(), server, secureChannel); server.getExecutorService().execute(() -> server.receiveRequest(serviceRequest)); messageBuffer.release(); buffersToDecode.clear(); } catch (UaException e) { logger.error("Error decoding symmetric message: {}", e.getMessage(), e); ctx.close(); } }); } } }
From source file:com.eightkdata.mongowp.server.decoder.InsertMessageDecoder.java
License:Open Source License
@Override @SuppressFBWarnings(value = {//from www . j av a 2s . c o m "RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT" }, justification = "Findbugs thinks ByteBuf#readerIndex(...) has no" + "side effect") public InsertMessage decode(ByteBuf buffer, RequestBaseMessage requestBaseMessage) throws InvalidNamespaceException, InvalidBsonException { try { MyBsonContext context = new MyBsonContext(buffer); int flags = buffer.readInt(); String fullCollectionName = stringReader.readCString(buffer, true); ByteBuf docBuf = buffer.slice(buffer.readerIndex(), buffer.readableBytes()); docBuf.retain(); buffer.readerIndex(buffer.writerIndex()); ByteBufIterableDocumentProvider documents = new ByteBufIterableDocumentProvider(docBuf, docReader); //TODO: improve the way database and cache are pooled return new InsertMessage(requestBaseMessage, context, getDatabase(fullCollectionName).intern(), getCollection(fullCollectionName).intern(), EnumInt32FlagsUtil.isActive(Flag.CONTINUE_ON_ERROR, flags), documents); } catch (NettyBsonReaderException ex) { throw new InvalidBsonException(ex); } }