当前位置: 首页>>代码示例>>Java>>正文


Java Context.attach方法代码示例

本文整理汇总了Java中io.grpc.Context.attach方法的典型用法代码示例。如果您正苦于以下问题:Java Context.attach方法的具体用法?Java Context.attach怎么用?Java Context.attach使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在io.grpc.Context的用法示例。


在下文中一共展示了Context.attach方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: start_Runnable

import io.grpc.Context; //导入方法依赖的package包/类
@Test(timeout = 60000)
public void start_Runnable() throws Exception {
  final Context context = Context.current().withValue(KEY, "myvalue");
  previousContext = context.attach();

  final AtomicBoolean tested = new AtomicBoolean(false);

  Runnable runnable =
      new Runnable() {
        @Override
        public void run() {
          assertThat(Context.current()).isSameAs(context);
          assertThat(KEY.get()).isEqualTo("myvalue");
          tested.set(true);
        }
      };
  Thread thread = new Thread(runnable);

  thread.start();
  thread.join();

  assertThat(tested.get()).isTrue();
}
 
开发者ID:census-instrumentation,项目名称:opencensus-java,代码行数:24,代码来源:ThreadInstrumentationIT.java

示例2: start_Subclass

import io.grpc.Context; //导入方法依赖的package包/类
@Test(timeout = 60000)
public void start_Subclass() throws Exception {
  final Context context = Context.current().withValue(KEY, "myvalue");
  previousContext = context.attach();

  final AtomicBoolean tested = new AtomicBoolean(false);

  class MyThread extends Thread {

    @Override
    public void run() {
      assertThat(Context.current()).isSameAs(context);
      assertThat(KEY.get()).isEqualTo("myvalue");
      tested.set(true);
    }
  }

  Thread thread = new MyThread();

  thread.start();
  thread.join();

  assertThat(tested.get()).isTrue();
}
 
开发者ID:census-instrumentation,项目名称:opencensus-java,代码行数:25,代码来源:ThreadInstrumentationIT.java

示例3: execute

import io.grpc.Context; //导入方法依赖的package包/类
@Test(timeout = 60000)
public void execute() throws Exception {
  final Thread callerThread = Thread.currentThread();
  final Context context = Context.current().withValue(KEY, "myvalue");
  previousContext = context.attach();

  final Semaphore tested = new Semaphore(0);

  executor.execute(
      new Runnable() {
        @Override
        public void run() {
          assertThat(Thread.currentThread()).isNotSameAs(callerThread);
          assertThat(Context.current()).isSameAs(context);
          assertThat(KEY.get()).isEqualTo("myvalue");
          tested.release();
        }
      });

  tested.acquire();
}
 
开发者ID:census-instrumentation,项目名称:opencensus-java,代码行数:22,代码来源:ExecutorInstrumentationIT.java

示例4: submit_Callable

import io.grpc.Context; //导入方法依赖的package包/类
@Test(timeout = 60000)
public void submit_Callable() throws Exception {
  final Thread callerThread = Thread.currentThread();
  final Context context = Context.current().withValue(KEY, "myvalue");
  previousContext = context.attach();

  final AtomicBoolean tested = new AtomicBoolean(false);

  executor
      .submit(
          new Callable<Void>() {
            @Override
            public Void call() throws Exception {
              assertThat(Thread.currentThread()).isNotSameAs(callerThread);
              assertThat(Context.current()).isSameAs(context);
              assertThat(KEY.get()).isEqualTo("myvalue");
              tested.set(true);

              return null;
            }
          })
      .get();

  assertThat(tested.get()).isTrue();
}
 
开发者ID:census-instrumentation,项目名称:opencensus-java,代码行数:26,代码来源:ExecutorInstrumentationIT.java

示例5: submit_Runnable

import io.grpc.Context; //导入方法依赖的package包/类
@Test(timeout = 60000)
public void submit_Runnable() throws Exception {
  final Thread callerThread = Thread.currentThread();
  final Context context = Context.current().withValue(KEY, "myvalue");
  previousContext = context.attach();

  final AtomicBoolean tested = new AtomicBoolean(false);

  executor
      .submit(
          new Runnable() {
            @Override
            public void run() {
              assertThat(Thread.currentThread()).isNotSameAs(callerThread);
              assertThat(Context.current()).isSameAs(context);
              assertThat(KEY.get()).isEqualTo("myvalue");
              tested.set(true);
            }
          })
      .get();

  assertThat(tested.get()).isTrue();
}
 
开发者ID:census-instrumentation,项目名称:opencensus-java,代码行数:24,代码来源:ExecutorInstrumentationIT.java

示例6: submit_RunnableWithResult

import io.grpc.Context; //导入方法依赖的package包/类
@Test(timeout = 60000)
public void submit_RunnableWithResult() throws Exception {
  final Thread callerThread = Thread.currentThread();
  final Context context = Context.current().withValue(KEY, "myvalue");
  previousContext = context.attach();

  final AtomicBoolean tested = new AtomicBoolean(false);
  Object result = new Object();

  Future<Object> future =
      executor.submit(
          new Runnable() {
            @Override
            public void run() {
              assertThat(Thread.currentThread()).isNotSameAs(callerThread);
              assertThat(Context.current()).isNotSameAs(Context.ROOT);
              assertThat(Context.current()).isSameAs(context);
              assertThat(KEY.get()).isEqualTo("myvalue");
              tested.set(true);
            }
          },
          result);

  assertThat(future.get()).isSameAs(result);
  assertThat(tested.get()).isTrue();
}
 
开发者ID:census-instrumentation,项目名称:opencensus-java,代码行数:27,代码来源:ExecutorInstrumentationIT.java

示例7: doesPropagateContext

import io.grpc.Context; //导入方法依赖的package包/类
@Test
public void doesPropagateContext() throws Exception {
  final Context oldContext = Context.current();
  final Context newContext = oldContext.withValues(KEY_1, VAL_1, KEY_2, VAL_2);

  newContext.attach();

  final TestSubscriber<Object> subscriber = new TestSubscriber<Object>();
  Observable.create(subscriber1 -> {
    subscriber1.onNext(KEY_1.get());
    subscriber1.onNext(KEY_2.get());
    subscriber1.onCompleted();
  }).subscribeOn(Schedulers.computation()).subscribe(subscriber);

  newContext.detach(oldContext);

  subscriber.awaitTerminalEvent();
  subscriber.assertValues(VAL_1, VAL_2);
}
 
开发者ID:bmcstdio,项目名称:rxjava-grpc-context-hook,代码行数:20,代码来源:GrpcContextPropagatingOnScheduleActionTests.java

示例8: setUp

import io.grpc.Context; //导入方法依赖的package包/类
@Before
public final void setUp() throws Exception {
  Chunker.setDefaultChunkSizeForTesting(1000); // Enough for everything to be one chunk.
  fs = new InMemoryFileSystem(new JavaClock(), HashFunction.SHA256);
  execRoot = fs.getPath("/exec/root");
  FileSystemUtils.createDirectoryAndParents(execRoot);
  fakeFileCache = new FakeActionInputFileCache(execRoot);

  Path stdout = fs.getPath("/tmp/stdout");
  Path stderr = fs.getPath("/tmp/stderr");
  FileSystemUtils.createDirectoryAndParents(stdout.getParentDirectory());
  FileSystemUtils.createDirectoryAndParents(stderr.getParentDirectory());
  Context withEmptyMetadata =
      TracingMetadataUtils.contextWithMetadata(
          "none", "none", DIGEST_UTIL.asActionKey(Digest.getDefaultInstance()));
  withEmptyMetadata.attach();
}
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:18,代码来源:SimpleBlobStoreActionCacheTest.java

示例9: setUp

import io.grpc.Context; //导入方法依赖的package包/类
@Before
public final void setUp() throws Exception {
  // Use a mutable service registry for later registering the service impl for each test case.
  fakeServer =
      InProcessServerBuilder.forName(fakeServerName)
          .fallbackHandlerRegistry(serviceRegistry)
          .directExecutor()
          .build()
          .start();
  Chunker.setDefaultChunkSizeForTesting(1000); // Enough for everything to be one chunk.
  fs = new InMemoryFileSystem(new JavaClock(), HashFunction.SHA256);
  execRoot = fs.getPath("/exec/root");
  FileSystemUtils.createDirectoryAndParents(execRoot);
  fakeFileCache = new FakeActionInputFileCache(execRoot);

  Path stdout = fs.getPath("/tmp/stdout");
  Path stderr = fs.getPath("/tmp/stderr");
  FileSystemUtils.createDirectoryAndParents(stdout.getParentDirectory());
  FileSystemUtils.createDirectoryAndParents(stderr.getParentDirectory());
  outErr = new FileOutErr(stdout, stderr);
  Context withEmptyMetadata =
      TracingMetadataUtils.contextWithMetadata(
          "none", "none", DIGEST_UTIL.asActionKey(Digest.getDefaultInstance()));
  withEmptyMetadata.attach();
}
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:26,代码来源:GrpcRemoteCacheTest.java

示例10: contextCancellationCancelsStream

import io.grpc.Context; //导入方法依赖的package包/类
@Test
public void contextCancellationCancelsStream() throws Exception {
  // Attach the context which is recorded when the call is created
  Context.CancellableContext cancellableContext = Context.current().withCancellation();
  Context previous = cancellableContext.attach();

  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      new SerializingExecutor(Executors.newSingleThreadExecutor()),
      baseCallOptions,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer)
          .setDecompressorRegistry(decompressorRegistry);

  previous.attach();

  call.start(callListener, new Metadata());

  Throwable t = new Throwable();
  cancellableContext.cancel(t);

  verify(stream, times(1)).cancel(statusArgumentCaptor.capture());
  Status streamStatus = statusArgumentCaptor.getValue();
  assertEquals(Status.Code.CANCELLED, streamStatus.getCode());
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:27,代码来源:ClientCallImplTest.java

示例11: contextDeadlineShouldBePropagatedInMetadata

import io.grpc.Context; //导入方法依赖的package包/类
@Test
public void contextDeadlineShouldBePropagatedInMetadata() {
  long deadlineNanos = TimeUnit.SECONDS.toNanos(1);
  Context context = Context.current().withDeadlineAfter(deadlineNanos, TimeUnit.NANOSECONDS,
      deadlineCancellationExecutor);
  context.attach();

  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      MoreExecutors.directExecutor(),
      baseCallOptions,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer);

  Metadata headers = new Metadata();

  call.start(callListener, headers);

  assertTrue(headers.containsKey(GrpcUtil.TIMEOUT_KEY));
  Long timeout = headers.get(GrpcUtil.TIMEOUT_KEY);
  assertNotNull(timeout);

  long deltaNanos = TimeUnit.MILLISECONDS.toNanos(400);
  assertTimeoutBetween(timeout, deadlineNanos - deltaNanos, deadlineNanos);
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:27,代码来源:ClientCallImplTest.java

示例12: attachContextForThread

import io.grpc.Context; //导入方法依赖的package包/类
@Override
public void attachContextForThread(Thread thread) {
  if (Thread.currentThread() == thread) {
    Context context = savedContexts.getIfPresent(thread);
    if (context != null) {
      savedContexts.invalidate(thread);
      context.attach();
    }
  }
}
 
开发者ID:census-instrumentation,项目名称:opencensus-java,代码行数:11,代码来源:ContextStrategyImpl.java

示例13: currentContextExecutor

import io.grpc.Context; //导入方法依赖的package包/类
@Test(timeout = 60000)
public void currentContextExecutor() throws Exception {
  final Thread callerThread = Thread.currentThread();
  final Context context = Context.current().withValue(KEY, "myvalue");
  previousContext = context.attach();

  final Semaphore tested = new Semaphore(0);

  Context.currentContextExecutor(executor)
      .execute(
          new Runnable() {
            @Override
            public void run() {
              StackTraceElement[] ste = new Exception().fillInStackTrace().getStackTrace();
              assertThat(ste[0].getClassName()).doesNotContain("Context");
              assertThat(ste[1].getClassName()).startsWith("io.grpc.Context$");
              // NB: Actually, we want the Runnable to be wrapped only once, but currently it is
              // still wrapped twice. The two places where the Runnable is wrapped are: (1) the
              // executor implementation itself, e.g. ThreadPoolExecutor, to which the Agent added
              // automatic context propagation, (2) CurrentContextExecutor.
              // ExecutorInstrumentation already avoids adding the automatic context propagation
              // to CurrentContextExecutor, but does not make it a no-op yet. Also see
              // ExecutorInstrumentation#createMatcher.
              assertThat(ste[2].getClassName()).startsWith("io.grpc.Context$");
              assertThat(ste[3].getClassName()).doesNotContain("Context");

              assertThat(Thread.currentThread()).isNotSameAs(callerThread);
              assertThat(Context.current()).isSameAs(context);
              assertThat(KEY.get()).isEqualTo("myvalue");

              tested.release();
            }
          });

  tested.acquire();
}
 
开发者ID:census-instrumentation,项目名称:opencensus-java,代码行数:37,代码来源:ExecutorInstrumentationIT.java

示例14: censusContextsPropagated

import io.grpc.Context; //导入方法依赖的package包/类
@Test(timeout = 10000)
public void censusContextsPropagated() {
  Assume.assumeTrue("Skip the test because server is not in the same process.", server != null);
  Span clientParentSpan = Tracing.getTracer().spanBuilder("Test.interopTest").startSpan();
  // A valid ID is guaranteed to be unique, so we can verify it is actually propagated.
  assertTrue(clientParentSpan.getContext().getTraceId().isValid());
  Context ctx =
      Context.ROOT.withValues(
          TAG_CONTEXT_KEY,
          tagger.emptyBuilder().put(
              StatsTestUtils.EXTRA_TAG, TagValue.create("extra value")).build(),
          ContextUtils.CONTEXT_SPAN_KEY,
          clientParentSpan);
  Context origCtx = ctx.attach();
  try {
    blockingStub.unaryCall(SimpleRequest.getDefaultInstance());
    Context serverCtx = contextCapture.get();
    assertNotNull(serverCtx);

    FakeTagContext statsCtx = (FakeTagContext) TAG_CONTEXT_KEY.get(serverCtx);
    assertNotNull(statsCtx);
    Map<TagKey, TagValue> tags = statsCtx.getTags();
    boolean tagFound = false;
    for (Map.Entry<TagKey, TagValue> tag : tags.entrySet()) {
      if (tag.getKey().equals(StatsTestUtils.EXTRA_TAG)) {
        assertEquals(TagValue.create("extra value"), tag.getValue());
        tagFound = true;
      }
    }
    assertTrue("tag not found", tagFound);

    Span span = CONTEXT_SPAN_KEY.get(serverCtx);
    assertNotNull(span);
    SpanContext spanContext = span.getContext();
    assertEquals(clientParentSpan.getContext().getTraceId(), spanContext.getTraceId());
  } finally {
    ctx.detach(origCtx);
  }
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:40,代码来源:AbstractInteropTest.java

示例15: newRetriableStream

import io.grpc.Context; //导入方法依赖的package包/类
@Override
public <ReqT> RetriableStream<ReqT> newRetriableStream(
    final MethodDescriptor<ReqT, ?> method,
    final CallOptions callOptions,
    final Metadata headers,
    final Context context) {
  RetryPolicy retryPolicy = retryPolicies == null ? DEFAULT : retryPolicies.get(method);
  return new RetriableStream<ReqT>(
      method, headers, channelBufferUsed, perRpcBufferLimit, channelBufferLimit,
      getCallExecutor(callOptions), transportFactory.getScheduledExecutorService(),
      retryPolicy) {
    @Override
    Status prestart() {
      return uncommittedRetriableStreamsRegistry.add(this);
    }

    @Override
    void postCommit() {
      uncommittedRetriableStreamsRegistry.remove(this);
    }

    @Override
    ClientStream newSubstream(ClientStreamTracer.Factory tracerFactory, Metadata newHeaders) {
      // TODO(zdapeng): only add tracer when retry is enabled.
      CallOptions newOptions = callOptions.withStreamTracerFactory(tracerFactory);
      ClientTransport transport =
          get(new PickSubchannelArgsImpl(method, newHeaders, newOptions));
      Context origContext = context.attach();
      try {
        return transport.newStream(method, newHeaders, newOptions);
      } finally {
        context.detach(origContext);
      }
    }
  };
}
 
开发者ID:grpc,项目名称:grpc-java,代码行数:37,代码来源:ManagedChannelImpl.java


注:本文中的io.grpc.Context.attach方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。