Example usage for io.netty.util ReferenceCountUtil safeRelease

List of usage examples for io.netty.util ReferenceCountUtil safeRelease

Introduction

In this page you can find the example usage for io.netty.util ReferenceCountUtil safeRelease.

Prototype

public static void safeRelease(Object msg) 

Source Link

Document

Try to call ReferenceCounted#release() if the specified message implements ReferenceCounted .

Usage

From source file:com.linecorp.armeria.common.HttpResponseWriter.java

License:Apache License

/**
 * Writes the HTTP response of the specified {@link HttpStatus} and closes the stream.
 *
 * @param mediaType the {@link MediaType} of the response content
 * @param content the content of the response
 * @param trailingHeaders the trailing HTTP headers
 *
 * @deprecated Use {@link HttpResponse#of(HttpStatus, MediaType, HttpData, HttpHeaders)}.
 *///from www. j av  a 2 s .  c o m
@Deprecated
default void respond(HttpStatus status, MediaType mediaType, HttpData content, HttpHeaders trailingHeaders) {
    requireNonNull(status, "status");
    requireNonNull(mediaType, "mediaType");
    requireNonNull(content, "content");
    requireNonNull(trailingHeaders, "trailingHeaders");

    final HttpHeaders headers = HttpHeaders.of(status).contentType(mediaType)
            .setInt(HttpHeaderNames.CONTENT_LENGTH, content.length());

    if (isContentAlwaysEmptyWithValidation(status, content, trailingHeaders)) {
        ReferenceCountUtil.safeRelease(content);
        write(headers);
    } else {
        write(headers);
        // Add content if not empty.
        if (!content.isEmpty()) {
            write(content);
        }
    }

    // Add trailing headers if not empty.
    if (!trailingHeaders.isEmpty()) {
        write(trailingHeaders);
    }

    close();
}

From source file:com.linecorp.armeria.common.HttpResponseWriter.java

License:Apache License

/**
 * Writes the specified HTTP response and closes the stream.
 *///from w w  w .  j  a  va  2 s.  co m
default void close(AggregatedHttpMessage res) {
    requireNonNull(res, "res");

    final HttpHeaders headers = res.headers();
    final HttpStatus status = headers.status();
    checkArgument(status != null, "res does not contain :status.");

    final HttpData content = res.content();
    final HttpHeaders trailingHeaders = res.trailingHeaders();

    if (isContentAlwaysEmptyWithValidation(status, content, trailingHeaders)) {
        ReferenceCountUtil.safeRelease(content);
        write(headers);
    } else {
        write(headers);
        // Add content if not empty.
        if (!content.isEmpty()) {
            write(content);
        }
    }

    // Add trailing headers if not empty.
    if (!trailingHeaders.isEmpty()) {
        write(trailingHeaders);
    }

    close();
}

From source file:com.linecorp.armeria.common.RequestContext.java

License:Apache License

/**
 * Resolves the specified {@code promise} with the specified {@code result} so that the {@code promise} is
 * marked as 'done'. If {@code promise} is done already, this method does the following:
 * <ul>//from w  ww .  j ava  2s .c  o m
 *   <li>Log a warning about the failure, and</li>
 *   <li>Release {@code result} if it is {@linkplain ReferenceCounted a reference-counted object},
 *       such as {@link ByteBuf} and {@link FullHttpResponse}.</li>
 * </ul>
 * Note that a {@link Promise} can be done already even if you did not call this method in the following
 * cases:
 * <ul>
 *   <li>Invocation timeout - The invocation associated with the {@link Promise} has been timed out.</li>
 *   <li>User error - A service implementation called any of the following methods more than once:
 *     <ul>
 *       <li>{@link #resolvePromise(Promise, Object)}</li>
 *       <li>{@link #rejectPromise(Promise, Throwable)}</li>
 *       <li>{@link Promise#setSuccess(Object)}</li>
 *       <li>{@link Promise#setFailure(Throwable)}</li>
 *       <li>{@link Promise#cancel(boolean)}</li>
 *     </ul>
 *   </li>
 * </ul>
 */
@Deprecated
default void resolvePromise(Promise<?> promise, Object result) {
    @SuppressWarnings("unchecked")
    final Promise<Object> castPromise = (Promise<Object>) promise;

    if (castPromise.trySuccess(result)) {
        // Resolved successfully.
        return;
    }

    try {
        if (!(promise.cause() instanceof TimeoutException)) {
            // Log resolve failure unless it is due to a timeout.
            LoggerFactory.getLogger(RequestContext.class)
                    .warn("Failed to resolve a completed promise ({}) with {}", promise, result);
        }
    } finally {
        ReferenceCountUtil.safeRelease(result);
    }
}

From source file:com.linecorp.armeria.common.ServiceInvocationContext.java

License:Apache License

/**
 * Resolves the specified {@code promise} with the specified {@code result} so that the {@code promise} is
 * marked as 'done'. If {@code promise} is done already, this method does the following:
 * <ul>//from w  w  w. j  a  va 2  s. c om
 *   <li>Log a warning about the failure, and</li>
 *   <li>Release {@code result} if it is {@linkplain ReferenceCounted a reference-counted object},
 *       such as {@link ByteBuf} and {@link FullHttpResponse}.</li>
 * </ul>
 * Note that a {@link Promise} can be done already even if you did not call this method in the following
 * cases:
 * <ul>
 *   <li>Invocation timeout - The invocation associated with the {@link Promise} has been timed out.</li>
 *   <li>User error - A service implementation called any of the following methods more than once:
 *     <ul>
 *       <li>{@link #resolvePromise(Promise, Object)}</li>
 *       <li>{@link #rejectPromise(Promise, Throwable)}</li>
 *       <li>{@link Promise#setSuccess(Object)}</li>
 *       <li>{@link Promise#setFailure(Throwable)}</li>
 *       <li>{@link Promise#cancel(boolean)}</li>
 *     </ul>
 *   </li>
 * </ul>
 */
public void resolvePromise(Promise<?> promise, Object result) {
    @SuppressWarnings("unchecked")
    final Promise<Object> castPromise = (Promise<Object>) promise;

    if (castPromise.trySuccess(result)) {
        // Resolved successfully.
        return;
    }

    try {
        if (!(promise.cause() instanceof TimeoutException)) {
            // Log resolve failure unless it is due to a timeout.
            logger().warn("Failed to resolve a completed promise ({}) with {}", promise, result);
        }
    } finally {
        ReferenceCountUtil.safeRelease(result);
    }
}

From source file:com.linecorp.armeria.common.stream.AbstractStreamMessage.java

License:Apache License

/**
 * Helper method for the common case of cleaning up all elements in a queue when shutting down the stream.
 *//*from   www  .  j  a  v a  2 s .  com*/
void cleanupQueue(SubscriptionImpl subscription, Queue<Object> queue) {
    final Throwable cause = ClosedPublisherException.get();
    for (;;) {
        final Object e = queue.poll();
        if (e == null) {
            break;
        }

        try {
            if (e instanceof CloseEvent) {
                notifySubscriberOfCloseEvent(subscription, (CloseEvent) e);
                continue;
            }

            if (e instanceof CompletableFuture) {
                ((CompletableFuture<?>) e).completeExceptionally(cause);
            }

            @SuppressWarnings("unchecked")
            final T obj = (T) e;
            onRemoval(obj);
        } finally {
            ReferenceCountUtil.safeRelease(e);
        }
    }
}

From source file:com.linecorp.armeria.common.stream.AbstractStreamMessageAndWriter.java

License:Apache License

@Override
public boolean tryWrite(T obj) {
    requireNonNull(obj, "obj");
    if (obj instanceof ReferenceCounted) {
        ((ReferenceCounted) obj).touch();
        if (!(obj instanceof ByteBufHolder) && !(obj instanceof ByteBuf)) {
            throw new IllegalArgumentException(
                    "can't publish a ReferenceCounted that's not a ByteBuf or a ByteBufHolder: " + obj);
        }/*from   w  w w .j  a  v  a2 s.c  o  m*/
    }

    if (!isOpen()) {
        ReferenceCountUtil.safeRelease(obj);
        return false;
    }

    addObject(obj);
    return true;
}

From source file:com.linecorp.armeria.common.stream.OneElementFixedStreamMessage.java

License:Apache License

@Override
final void cleanupObjects() {
    if (obj != null) {
        try {//from   w w w.j  a  v  a 2  s  . c o m
            onRemoval(obj);
        } finally {
            ReferenceCountUtil.safeRelease(obj);
        }
        obj = null;
    }
}

From source file:com.linecorp.armeria.common.stream.RegularFixedStreamMessage.java

License:Apache License

@Override
final void cleanupObjects() {
    while (fulfilled < objs.length) {
        T obj = objs[fulfilled];/*from  w  w w . j a va2s  .  c  o m*/
        objs[fulfilled++] = null;
        try {
            onRemoval(obj);
        } finally {
            ReferenceCountUtil.safeRelease(obj);
        }
    }
}

From source file:com.linecorp.armeria.common.stream.TwoElementFixedStreamMessage.java

License:Apache License

@Override
final void cleanupObjects() {
    if (obj1 != null) {
        try {/*from  www  .  ja v  a  2  s  .c  o m*/
            onRemoval(obj1);
        } finally {
            ReferenceCountUtil.safeRelease(obj1);
        }
        obj1 = null;
    }
    if (obj2 != null) {
        try {
            onRemoval(obj2);
        } finally {
            ReferenceCountUtil.safeRelease(obj2);
        }
        obj2 = null;
    }
}

From source file:com.linecorp.armeria.internal.Http1ObjectEncoder.java

License:Apache License

@Override
protected ChannelFuture doWriteData(ChannelHandlerContext ctx, int id, int streamId, HttpData data,
        boolean endStream) {

    if (id >= minClosedId) {
        ReferenceCountUtil.safeRelease(data);
        return ctx.newFailedFuture(ClosedSessionException.get());
    }//from   w  ww  . jav a 2  s  .  c om

    final int length = data.length();
    if (length == 0) {
        ReferenceCountUtil.safeRelease(data);
        final HttpContent content = endStream ? LastHttpContent.EMPTY_LAST_CONTENT : EMPTY_CONTENT;
        final ChannelFuture future = write(ctx, id, content, endStream);
        ctx.flush();
        return future;
    }

    try {
        if (!isTls || length <= MAX_TLS_DATA_LENGTH) {
            // Cleartext connection or data.length() <= MAX_TLS_DATA_LENGTH
            return doWriteUnsplitData(ctx, id, data, endStream);
        } else {
            // TLS and data.length() > MAX_TLS_DATA_LENGTH
            return doWriteSplitData(ctx, id, data, endStream);
        }
    } catch (Throwable t) {
        return ctx.newFailedFuture(t);
    }
}