Java Code Examples for reactor.util.context.Context#getOrDefault()

The following examples show how to use reactor.util.context.Context#getOrDefault() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Operators.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * An unexpected exception is about to be dropped.
 * <p>
 * If no hook is registered for {@link Hooks#onErrorDropped(Consumer)}, the dropped
 * error is logged at ERROR level and thrown (via {@link Exceptions#bubble(Throwable)}.
 *
 * @param e the dropped exception
 * @param context a context that might hold a local error consumer
 */
public static void onErrorDropped(Throwable e, Context context) {
	Consumer<? super Throwable> hook = context.getOrDefault(Hooks.KEY_ON_ERROR_DROPPED,null);
	if (hook == null) {
		hook = Hooks.onErrorDroppedHook;
	}
	if (hook == null) {
		log.error("Operator called default onErrorDropped", e);
		throw Exceptions.bubble(e);
	}
	hook.accept(e);
}
 
Example 2
Source File: Operators.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * An unexpected event is about to be dropped.
 * <p>
 * If no hook is registered for {@link Hooks#onNextDropped(Consumer)}, the dropped
 * element is just logged at DEBUG level.
 *
 * @param <T> the dropped value type
 * @param t the dropped data
 * @param context a context that might hold a local next consumer
 */
public static <T> void onNextDropped(T t, Context context) {
	Objects.requireNonNull(t, "onNext");
	Objects.requireNonNull(context, "context");
	Consumer<Object> hook = context.getOrDefault(Hooks.KEY_ON_NEXT_DROPPED, null);
	if (hook == null) {
		hook = Hooks.onNextDroppedHook;
	}
	if (hook != null) {
		hook.accept(t);
	}
	else if (log.isDebugEnabled()) {
		log.debug("onNextDropped: " + t);
	}
}
 
Example 3
Source File: Operators.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
/**
 * Map an "operator" error given an operator parent {@link Subscription}. The
 * result error will be passed via onError to the operator downstream.
 * {@link Subscription} will be cancelled after checking for fatal error via
 * {@link Exceptions#throwIfFatal(Throwable)}. Takes an additional signal, which
 * can be added as a suppressed exception if it is a {@link Throwable} and the
 * default {@link Hooks#onOperatorError(BiFunction) hook} is in place.
 *
 * @param subscription the linked operator parent {@link Subscription}
 * @param error the callback or operator error
 * @param dataSignal the value (onNext or onError) signal processed during failure
 * @param context a context that might hold a local error consumer
 * @return mapped {@link Throwable}
 *
 */
public static Throwable onOperatorError(@Nullable Subscription subscription,
		Throwable error,
		@Nullable Object dataSignal, Context context) {

	Exceptions.throwIfFatal(error);
	if(subscription != null) {
		subscription.cancel();
	}

	Throwable t = Exceptions.unwrap(error);
	BiFunction<? super Throwable, Object, ? extends Throwable> hook =
			context.getOrDefault(Hooks.KEY_ON_OPERATOR_ERROR, null);
	if (hook == null) {
		hook = Hooks.onOperatorErrorHook;
	}
	if (hook == null) {
		if (dataSignal != null) {
			if (dataSignal != t && dataSignal instanceof Throwable) {
				t = Exceptions.addSuppressed(t, (Throwable) dataSignal);
			}
			//do not wrap original value to avoid strong references
			/*else {
			}*/
		}
		return t;
	}
	return hook.apply(error, dataSignal);
}
 
Example 4
Source File: Operators.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
static final OnNextFailureStrategy onNextErrorStrategy(Context context) {
	OnNextFailureStrategy strategy = null;

	BiFunction<? super Throwable, Object, ? extends Throwable> fn = context.getOrDefault(
			OnNextFailureStrategy.KEY_ON_NEXT_ERROR_STRATEGY, null);
	if (fn instanceof OnNextFailureStrategy) {
		strategy = (OnNextFailureStrategy) fn;
	} else if (fn != null) {
		strategy = new OnNextFailureStrategy.LambdaOnNextErrorStrategy(fn);
	}

	if (strategy == null) strategy = Hooks.onNextErrorHook;
	if (strategy == null) strategy = OnNextFailureStrategy.STOP;
	return strategy;
}
 
Example 5
Source File: OperatorsTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void discardAdapterIsAdditive() {
	List<String> discardOrder = Collections.synchronizedList(new ArrayList<>(2));

	Function<Context, Context> first = Operators.discardLocalAdapter(Number.class, i -> discardOrder.add("FIRST"));
	Function<Context, Context> second = Operators.discardLocalAdapter(Integer.class, i -> discardOrder.add("SECOND"));

	Context ctx = first.apply(second.apply(Context.empty()));
	Consumer<Object> test = ctx.getOrDefault(Hooks.KEY_ON_DISCARD, o -> {});

	assertThat(test).isNotNull();

	test.accept(1);
	assertThat(discardOrder).as("consumers were combined").containsExactly("FIRST", "SECOND");
}
 
Example 6
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
void handle(Context context, @Nullable HttpClientResponse resp,
		@Nullable Throwable error) {
	PendingSpan pendingSpan = context.getOrDefault(PendingSpan.class, null);
	if (pendingSpan == null) {
		return; // Somehow TracingMapConnect was not invoked.. skip out
	}

	Span span = pendingSpan.getAndSet(null);
	if (span == null) {
		return; // Unexpected. In the handle method, without a span to finish!
	}
	HttpClientResponseWrapper response = resp != null
			? new HttpClientResponseWrapper(resp) : null;
	handler().handleReceive(response, error, span);
}
 
Example 7
Source File: ScopeRunner.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
private <T> Flux<T> doInScope(
    Context subscriberContext,
    String scopeDescription,
    LockGuard lockGuard,
    Callable<Flux<T>> callable,
    boolean transactional
)
    throws Exception
{
    String apiCallName = subscriberContext.get(ApiModule.API_CALL_NAME);
    AccessContext accCtx = subscriberContext.get(AccessContext.class);
    Peer peer = subscriberContext.getOrDefault(Peer.class, null);
    Long apiCallId = subscriberContext.getOrDefault(ApiModule.API_CALL_ID, null);

    Flux<T> ret;

    String peerDescription;
    if (peer == null)
    {
        peerDescription = "";
    }
    else
    {
        peerDescription = "Peer " + peer + ", ";
    }

    String apiCallDescription;
    if (apiCallId == null)
    {
        apiCallDescription = "Background operation";
    }
    else
    if (apiCallId != 0L)
    {
        apiCallDescription = "API call " + apiCallId;
    }
    else
    {
        apiCallDescription = "oneway call";
    }

    errorLog.logTrace(
        "%s%s '%s' scope '%s' start", peerDescription, apiCallDescription, apiCallName, scopeDescription);

    TransactionMgr transMgr = transactional ? transactionMgrGenerator.startTransaction() : null;

    apiCallScope.enter();
    lockGuard.lock();
    try
    {
        apiCallScope.seed(Key.get(AccessContext.class, PeerContext.class), accCtx);
        apiCallScope.seed(Key.get(AccessContext.class, ErrorReporterContext.class), accCtx);
        if (peer != null)
        {
            apiCallScope.seed(Peer.class, peer);
        }
        if (apiCallId != null)
        {
            apiCallScope.seed(Key.get(Long.class, Names.named(ApiModule.API_CALL_ID)), apiCallId);
        }

        if (transMgr != null)
        {
            TransactionMgrUtil.seedTransactionMgr(apiCallScope, transMgr);
        }

        ret = callable.call();
    }
    finally
    {
        lockGuard.unlock();
        apiCallScope.exit();
        if (transMgr != null)
        {
            if (transMgr.isDirty())
            {
                try
                {
                    transMgr.rollback();
                }
                catch (TransactionException transExc)
                {
                    errorLog.reportError(
                        Level.ERROR,
                        transExc,
                        accCtx,
                        peer,
                        "A database error occurred while trying to rollback '" + apiCallName + "'"
                    );
                }
            }
            transMgr.returnConnection();
        }
        errorLog.logTrace(
            "%s%s '%s' scope '%s' end", peerDescription, apiCallDescription, apiCallName, scopeDescription);
    }

    return ret;
}
 
Example 8
Source File: SpanSubscriber.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
SpanSubscriber(
    Subscriber<? super T> subscriber,
    Context ctx,
    Tracer tracer,
    Map<String, String> tracingMetadata,
    String name,
    Tag... tags) {
  this.subscriber = subscriber;
  this.tracer = tracer;
  Span root = ctx.getOrDefault(Span.class, this.tracer.activeSpan());
  if (log.isTraceEnabled()) {
    log.trace("Span from context [{}]", root);
  }
  this.rootSpan = root;
  if (log.isTraceEnabled()) {
    log.trace("Stored context root span [{}]", this.rootSpan);
  }

  Tracer.SpanBuilder spanBuilder = this.tracer.buildSpan(name);
  if (tags != null && tags.length > 0) {
    for (Tag tag : tags) {
      spanBuilder.withTag(tag.getKey(), tag.getValue());
    }
  }

  if (root != null) {
    spanBuilder.asChildOf(root);
  }

  this.span = spanBuilder.start();

  if (tracingMetadata != null) {
    TextMapInjectAdapter adapter = new TextMapInjectAdapter(tracingMetadata);
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, adapter);
  }

  if (log.isTraceEnabled()) {
    log.trace("Created span [{}], with name [{}]", this.span, name);
  }
  this.context = ctx.put(Span.class, this.span);
}
 
Example 9
Source File: SpanSubscriber.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
SpanSubscriber(
    Subscriber<? super T> subscriber,
    Context ctx,
    Tracer tracer,
    Map<String, String> tracingMetadata,
    String name,
    Tag... tags) {
  this.subscriber = subscriber;
  this.tracer = tracer;
  Span root = ctx.getOrDefault(Span.class, this.tracer.activeSpan());
  if (log.isTraceEnabled()) {
    log.trace("Span from context [{}]", root);
  }
  this.rootSpan = root;
  if (log.isTraceEnabled()) {
    log.trace("Stored context root span [{}]", this.rootSpan);
  }

  Tracer.SpanBuilder spanBuilder = this.tracer.buildSpan(name);
  if (tags != null && tags.length > 0) {
    for (Tag tag : tags) {
      spanBuilder.withTag(tag.getKey(), tag.getValue());
    }
  }

  if (root != null) {
    spanBuilder.asChildOf(root);
  }

  this.span = spanBuilder.start();

  if (tracingMetadata != null) {
    TextMapInjectAdapter adapter = new TextMapInjectAdapter(tracingMetadata);
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, adapter);
  }

  if (log.isTraceEnabled()) {
    log.trace("Created span [{}], with name [{}]", this.span, name);
  }
  this.context = ctx.put(Span.class, this.span);
}
 
Example 10
Source File: Operators.java    From reactor-core with Apache License 2.0 3 votes vote down vote up
/**
 * Invoke a (local or global) hook that processes elements that get discarded. This
 * includes elements that are dropped (for malformed sources), but also filtered out
 * (eg. not passing a {@code filter()} predicate).
 * <p>
 * For elements that are buffered or enqueued, but subsequently discarded due to
 * cancellation or error, see {@link #onDiscardMultiple(Stream, Context)} and
 * {@link #onDiscardQueueWithClear(Queue, Context, Function)}.
 *
 * @param element the element that is being discarded
 * @param context the context in which to look for a local hook
 * @param <T> the type of the element
 * @see #onDiscardMultiple(Stream, Context)
 * @see #onDiscardMultiple(Collection, Context)
 * @see #onDiscardQueueWithClear(Queue, Context, Function)
 */
public static <T> void onDiscard(@Nullable T element, Context context) {
	Consumer<Object> hook = context.getOrDefault(Hooks.KEY_ON_DISCARD, null);
	if (element != null && hook != null) {
		try {
			hook.accept(element);
		}
		catch (Throwable t) {
			log.warn("Error in discard hook", t);
		}
	}
}
 
Example 11
Source File: WingtipsSpringWebfluxUtils.java    From wingtips with Apache License 2.0 2 votes vote down vote up
/**
 * @param context The {@link Context} that may contain a {@code TracingState.class} -> {@link TracingState}
 * key/value pair.
 * @return The {@link TracingState} pulled from the given {@link Context} (using {@code TracingState.class} as
 * the key), or null if there was no tracing state key/value pair.
 */
public static @Nullable TracingState tracingStateFromContext(@NotNull Context context) {
    return context.getOrDefault(TracingState.class, null);
}