java.util.concurrent.atomic.AtomicReference Java Examples

The following examples show how to use java.util.concurrent.atomic.AtomicReference. 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: MulticastRegistryTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for
 * {@link com.alibaba.dubbo.registry.support.injvm.InjvmRegistry#subscribe(java.util.Map, com.alibaba.dubbo.registry.support.NotifyListener)}
 * .
 */
@Test
public void testSubscribe() {
    // verify lisener.
    final AtomicReference<URL> args = new AtomicReference<URL>();
    registry.subscribe(consumerUrl, new NotifyListener() {

        public void notify(List<URL> urls) {
            // FIXME assertEquals(MulticastRegistry.this.service, service);
            args.set(urls.get(0));
        }
    });
    assertEquals(serviceUrl.toFullString(), args.get().toFullString());
    Map<URL, Set<NotifyListener>> arg = registry.getSubscribed();
    assertEquals(consumerUrl, arg.keySet().iterator().next());

}
 
Example #2
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void exchangeMetadataUnaryCall() throws Exception {
  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub;

  // Capture the metadata exchange
  Metadata fixedHeaders = new Metadata();
  // Send a context proto (as it's in the default extension registry)
  Messages.SimpleContext contextValue =
      Messages.SimpleContext.newBuilder().setValue("dog").build();
  fixedHeaders.put(Util.METADATA_KEY, contextValue);
  stub = MetadataUtils.attachHeaders(stub, fixedHeaders);
  // .. and expect it to be echoed back in trailers
  AtomicReference<Metadata> trailersCapture = new AtomicReference<>();
  AtomicReference<Metadata> headersCapture = new AtomicReference<>();
  stub = MetadataUtils.captureMetadata(stub, headersCapture, trailersCapture);

  assertNotNull(stub.emptyCall(EMPTY));

  // Assert that our side channel object is echoed back in both headers and trailers
  Assert.assertEquals(contextValue, headersCapture.get().get(Util.METADATA_KEY));
  Assert.assertEquals(contextValue, trailersCapture.get().get(Util.METADATA_KEY));
}
 
Example #3
Source File: LoadBalancerReadyHttpClientTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
private void verifyFailsAction(Function<StreamingHttpClient, Single<?>> action,
                               Consumer<Throwable> errorConsumer, Throwable error) throws InterruptedException {
    StreamingHttpClient client = TestStreamingHttpClient.from(reqRespFactory, mockExecutionCtx,
            newAutomaticRetryFilterFactory(loadBalancerPublisher, sdStatusCompletable).append(testHandler));

    CountDownLatch latch = new CountDownLatch(1);
    AtomicReference<Throwable> causeRef = new AtomicReference<>();

    action.apply(client)
            .whenOnError(causeRef::set)
            .afterFinally(latch::countDown)
            .toCompletable()
            .subscribe();

    // We don't expect the request to complete until onInitialized completes.
    assertThat(latch.await(100, MILLISECONDS), is(false));

    // When a failure occurs that should also fail the action!
    errorConsumer.accept(error);
    latch.await();
    assertThat(causeRef.get(), is(error));
}
 
Example #4
Source File: ClientCallsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void blockingResponseStreamFailed() throws Exception {
  final AtomicReference<ClientCall.Listener<String>> listener =
      new AtomicReference<>();
  NoopClientCall<Integer, String> call = new NoopClientCall<Integer, String>() {
    @Override
    public void start(io.grpc.ClientCall.Listener<String> responseListener, Metadata headers) {
      listener.set(responseListener);
    }
  };

  Integer req = 2;
  Iterator<String> iter = ClientCalls.blockingServerStreamingCall(call, req);

  Metadata trailers = new Metadata();
  listener.get().onClose(Status.INTERNAL, trailers);
  try {
    iter.next();
    fail("Should fail");
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    assertEquals(Status.INTERNAL, status);
    Metadata metadata = Status.trailersFromThrowable(e);
    assertSame(trailers, metadata);
  }
}
 
Example #5
Source File: Http2Client.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * This method is used to call the service corresponding to the uri and obtain a response, connection pool is embedded.
 * @param uri URI of target service
 * @param request request
 * @param requestBody request body
 * @return client response
 */
public CompletableFuture<ClientResponse> callService(URI uri, ClientRequest request, Optional<String> requestBody) {
    addHostHeader(request);
    CompletableFuture<ClientResponse> futureClientResponse;
    AtomicReference<ClientConnection> currentConnection = new AtomicReference<>(http2ClientConnectionPool.getConnection(uri));
    if (currentConnection.get() != null && currentConnection.get().isOpen()) {
        logger.debug("Reusing the connection: {} to {}", currentConnection.toString(), uri.toString());
        futureClientResponse = getFutureClientResponse(currentConnection.get(), uri, request, requestBody);
    } else {
        CompletableFuture<ClientConnection> futureConnection = this.connectAsync(uri);
        futureClientResponse = futureConnection.thenComposeAsync(clientConnection -> {
            currentConnection.set(clientConnection);
            return getFutureClientResponse(clientConnection, uri, request, requestBody);
        });
    }
    futureClientResponse.thenAcceptAsync(clientResponse -> http2ClientConnectionPool.resetConnectionStatus(currentConnection.get()));
    return futureClientResponse;
}
 
Example #6
Source File: TrieMap_Heterogeneous_BleedingEdge_Specializations.java    From capsule with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected Map4To8Node_Heterogeneous_BleedingEdge(final AtomicReference<Thread> mutator,
    final byte nodeMap, final byte dataMap, final int key1, final int val1, final int key2,
    final int val2, final int key3, final int val3, final int key4, final int val4,
    final Object slot0, final Object slot1, final Object slot2, final Object slot3,
    final Object slot4, final Object slot5, final Object slot6, final Object slot7) {
  super(mutator, nodeMap, dataMap);
  this.key1 = key1;
  this.val1 = val1;
  this.key2 = key2;
  this.val2 = val2;
  this.key3 = key3;
  this.val3 = val3;
  this.key4 = key4;
  this.val4 = val4;
  this.slot0 = slot0;
  this.slot1 = slot1;
  this.slot2 = slot2;
  this.slot3 = slot3;
  this.slot4 = slot4;
  this.slot5 = slot5;
  this.slot6 = slot6;
  this.slot7 = slot7;
}
 
Example #7
Source File: AbstractTcConfigMapper.java    From terracotta-platform with Apache License 2.0 6 votes vote down vote up
private Set<String> validateAllConfigurationFilesHaveSamePluginTypes(Map<Path, Map<String, Node>> configAndServiceNodesPerConfigFile) {
  AtomicReference<Set<String>> previousSetReference = new AtomicReference<>();
  AtomicReference<Path> previousPath = new AtomicReference<>();
  configAndServiceNodesPerConfigFile.forEach((path, nodeMap) -> {
    if (previousSetReference.get() == null) {
      previousSetReference.set(nodeMap.keySet());
      previousPath.set(path);
      return;
    }
    Set<String> currentSet = nodeMap.keySet();
    if (!previousSetReference.get().equals(currentSet)) {
      throw new InvalidInputConfigurationContentException(
          ErrorCode.MISMATCHED_SERVICE_CONFIGURATION,
          "Mismatched Service Configuration",
          tuple2(ErrorParamKey.CONFIG_FILE.name(), path.toString()),
          tuple2(ErrorParamKey.CONFIG_FILE.name(), previousPath.get().toString())
      );
    }
    previousSetReference.set(nodeMap.keySet());
  });
  return previousSetReference.get();
}
 
Example #8
Source File: FragmentDisabledNoRestartTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void testSelf() throws Exception {
    UpdateUnit hostUnit = UpdateManagerImpl.getInstance().getUpdateUnit("org.yourorghere.engine");
    installModule(hostUnit, null);
    
    OperationContainer<OperationSupport> container = OperationContainer.createForDirectDisable ();
    container.add(hostUnit.getInstalled());
    OperationSupport support = container.getSupport ();
    support.doOperation (null);

    UpdateUnit toInstall = UpdateManagerImpl.getInstance().getUpdateUnit(moduleCodeNameBaseForTest());
    
    AtomicReference<OperationSupport.Restarter> restarter = new AtomicReference<>();
    installModuleWithRestart(toInstall, null, restarter);
    
    assertNull ("Module must not cause restart, host is disabled", restarter.get());
}
 
Example #9
Source File: ZKSegmentContainerMonitor.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of ZKSegmentContainerMonitor.
 *
 * @param containerRegistry      The registry used to control the container state.
 * @param zkClient               The curator client.
 * @param pravegaServiceEndpoint The pravega endpoint for which we need to fetch the container assignment.
 */
ZKSegmentContainerMonitor(SegmentContainerRegistry containerRegistry, CuratorFramework zkClient,
                          Host pravegaServiceEndpoint, int parallelContainerStarts, ScheduledExecutorService executor) {
    Preconditions.checkNotNull(zkClient, "zkClient");
    Preconditions.checkArgument(parallelContainerStarts > 0, "parallelContainerStarts");

    this.registry = Preconditions.checkNotNull(containerRegistry, "containerRegistry");
    this.host = Preconditions.checkNotNull(pravegaServiceEndpoint, "pravegaServiceEndpoint");
    this.executor = Preconditions.checkNotNull(executor, "executor");
    this.handles = new ConcurrentHashMap<>();
    this.pendingTasks = new ConcurrentSkipListSet<>();
    String clusterPath = ZKPaths.makePath("cluster", "segmentContainerHostMapping");
    this.hostContainerMapNode = new NodeCache(zkClient, clusterPath);
    this.assignmentTask = new AtomicReference<>();
    this.lastReportTime = new AtomicLong(CURRENT_TIME_MILLIS.get());
    this.parallelContainerStartsSemaphore = new Semaphore(parallelContainerStarts);
}
 
Example #10
Source File: RecastMeshDetail.java    From recast4j with zlib License 6 votes vote down vote up
private static boolean circumCircle(float[] verts, int p1, int p2, int p3, float[] c, AtomicReference<Float> r) {
    float EPS = 1e-6f;
    // Calculate the circle relative to p1, to avoid some precision issues.
    float v1[] = new float[3];
    float v2[] = new float[3];
    float v3[] = new float[3];
    RecastVectors.sub(v2, verts, p2, p1);
    RecastVectors.sub(v3, verts, p3, p1);

    float cp = vcross2(v1, v2, v3);
    if (Math.abs(cp) > EPS) {
        float v1Sq = vdot2(v1, v1);
        float v2Sq = vdot2(v2, v2);
        float v3Sq = vdot2(v3, v3);
        c[0] = (v1Sq * (v2[2] - v3[2]) + v2Sq * (v3[2] - v1[2]) + v3Sq * (v1[2] - v2[2])) / (2 * cp);
        c[1] = 0;
        c[2] = (v1Sq * (v3[0] - v2[0]) + v2Sq * (v1[0] - v3[0]) + v3Sq * (v2[0] - v1[0])) / (2 * cp);
        r.set(vdist2(c, v1));
        RecastVectors.add(c, c, verts, p1);
        return true;
    }
    RecastVectors.copy(c, verts, p1);
    r.set(0f);
    return false;
}
 
Example #11
Source File: AbstractTest.java    From hibernate-master-class with Apache License 2.0 6 votes vote down vote up
protected <T> T doInJDBC(ConnectionCallable<T> callable) {
    AtomicReference<T> result = new AtomicReference<>();
    Session session = null;
    Transaction txn = null;
    try {
        session = getSessionFactory().openSession();
        txn = session.beginTransaction();
        session.doWork(connection -> {
            result.set(callable.execute(connection));
        });
        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive() ) txn.rollback();
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return result.get();
}
 
Example #12
Source File: UniformNodeSelector.java    From presto with Apache License 2.0 6 votes vote down vote up
public UniformNodeSelector(
        InternalNodeManager nodeManager,
        NodeTaskMap nodeTaskMap,
        boolean includeCoordinator,
        Supplier<NodeMap> nodeMap,
        int minCandidates,
        int maxSplitsPerNode,
        int maxPendingSplitsPerTask,
        boolean optimizedLocalScheduling)
{
    this.nodeManager = requireNonNull(nodeManager, "nodeManager is null");
    this.nodeTaskMap = requireNonNull(nodeTaskMap, "nodeTaskMap is null");
    this.includeCoordinator = includeCoordinator;
    this.nodeMap = new AtomicReference<>(nodeMap);
    this.minCandidates = minCandidates;
    this.maxSplitsPerNode = maxSplitsPerNode;
    this.maxPendingSplitsPerTask = maxPendingSplitsPerTask;
    this.optimizedLocalScheduling = optimizedLocalScheduling;
}
 
Example #13
Source File: StubInstanceTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void findMissingBlobsCallsFindMissingBlobs()
    throws ExecutionException, InterruptedException {
  AtomicReference<FindMissingBlobsRequest> reference = new AtomicReference<>();
  serviceRegistry.addService(
      new ContentAddressableStorageImplBase() {
        @Override
        public void findMissingBlobs(
            FindMissingBlobsRequest request,
            StreamObserver<FindMissingBlobsResponse> responseObserver) {
          reference.set(request);
          responseObserver.onNext(FindMissingBlobsResponse.getDefaultInstance());
          responseObserver.onCompleted();
        }
      });
  Instance instance = newStubInstance("findMissingBlobs-test");
  Iterable<Digest> digests =
      ImmutableList.of(Digest.newBuilder().setHash("present").setSizeBytes(1).build());
  assertThat(
          instance
              .findMissingBlobs(
                  digests, newDirectExecutorService(), RequestMetadata.getDefaultInstance())
              .get())
      .isEmpty();
  instance.stop();
}
 
Example #14
Source File: LimitWhileClosedOperatorTest.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@Test
public void takeWhile1Async() {
    AtomicReference<Vector<Integer>> data = new AtomicReference(Vector.empty());
    AtomicBoolean complete = new AtomicBoolean(false);
    AtomicReference<Throwable> error = new AtomicReference<Throwable>(null);

    Spouts.async(ReactiveSeq.of(1,2,3,4,5),ex)
        .takeWhileInclusive(i -> i<1)
        .forEach(n->{
            assertFalse(complete.get());
            data.updateAndGet(s->s.plus(n));
        },e->{
            error.set(e);
        },()->{
            complete.set(true);
        });

    while(!complete.get()){
        LockSupport.parkNanos(10l);
    }

    assertThat(data.get(),equalTo(Vector.of(1)));
    assertThat(complete.get(),equalTo(true));
    assertNull(error.get());

}
 
Example #15
Source File: FlakyCaseResultTest.java    From flaky-test-handler-plugin with Apache License 2.0 6 votes vote down vote up
public void testLocalizationOfStatus() throws Exception {
    LocaleProvider old = LocaleProvider.getProvider();
    try {
        final AtomicReference<Locale> locale = new AtomicReference<Locale>();
        LocaleProvider.setProvider(new LocaleProvider() {
            public @Override Locale get() {
                return locale.get();
            }
        });
        locale.set(Locale.GERMANY);
        assertEquals("Erfolg", FlakyCaseResult.Status.PASSED.getMessage());
        locale.set(Locale.US);
        assertEquals("Passed", FlakyCaseResult.Status.PASSED.getMessage());
    } finally {
        LocaleProvider.setProvider(old);
    }
}
 
Example #16
Source File: MonoDoOnEachTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void usesFluxDoOnEachConditionalSubscriber() {
	AtomicReference<Scannable> ref = new AtomicReference<>();
	Mono<String> source = Mono.just("foo")
	                          .doOnSubscribe(sub -> ref.set(Scannable.from(sub)))
	                          .hide()
	                          .filter(t -> true);

	final MonoDoOnEach<String> test =
			new MonoDoOnEach<>(source, s -> { });

	test.filter(t -> true)
	    .subscribe();

	Class<?> expected = FluxDoOnEach.DoOnEachConditionalSubscriber.class;
	Stream<Class<?>> streamOfClasses = ref.get().actuals().map(Object::getClass);

	assertThat(streamOfClasses).contains(expected);
}
 
Example #17
Source File: StatsAggregator.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize all counters to 0;
 */
private void initAggregateMap() {
  Iterator<String> it = typeMap.keySet().iterator();
  while (it.hasNext()) {
    AtomicReference<Number> ref = null;
    String attribute = it.next();
    Class<?> classzz = typeMap.get(attribute);
    if (classzz == Long.TYPE) {
      ref = new AtomicReference<Number>(new Long(0L));
    } else if (classzz == Integer.TYPE) {
      ref = new AtomicReference<Number>(new Integer(0));
    } else if (classzz == Float.TYPE) {
      ref = new AtomicReference<Number>(new Float(0F));
    } else if (classzz == Double.TYPE) {
      ref = new AtomicReference<Number>(new Double(0D));

    }

    aggregateMap.put(attribute, ref);
  }
}
 
Example #18
Source File: LoggingRepository.java    From Carbonado with Apache License 2.0 6 votes vote down vote up
LoggingRepository(AtomicReference<Repository> rootRef,
                  Repository actual, Log log)
{
    mRootRef = rootRef;
    mRepo = actual;
    mLog = log;

    mStoragePool = new StoragePool() {
        @Override
        protected <S extends Storable> Storage<S> createStorage(Class<S> type)
            throws RepositoryException
        {
            return new LoggingStorage(LoggingRepository.this, mRepo.storageFor(type));
        }
    };
}
 
Example #19
Source File: ElementPropertyMapTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Test
public void deferredUpdateFromClient_clientFiltersOutUpdate_noOpRunnable()
        throws PropertyChangeDeniedException {
    ElementPropertyMap map = createSimplePropertyMap();
    map.setUpdateFromClientFilter(name -> !name.equals("foo"));

    AtomicReference<PropertyChangeEvent> eventCapture = new AtomicReference<>();
    map.addPropertyChangeListener("foo", eventCapture::set);

    Runnable runnable = map.deferredUpdateFromClient("foo", "value");
    Assert.assertThat(runnable.getClass().getName(),
            CoreMatchers.not(CoreMatchers.equalTo(
                    ElementPropertyMap.class.getName() + "$PutResult")));
    runnable.run();
    Assert.assertNull(eventCapture.get());
}
 
Example #20
Source File: RedissonSubscribeTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubscribe() {
    RedissonConnection connection = new RedissonConnection(redisson);
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    connection.subscribe(new MessageListener() {
        @Override
        public void onMessage(Message message, byte[] pattern) {
            msg.set(message.getBody());
        }
    }, "test".getBytes());
    
    connection.publish("test".getBytes(), "msg".getBytes());
    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    connection.getSubscription().unsubscribe();
    
    connection.publish("test".getBytes(), "msg".getBytes());
}
 
Example #21
Source File: RpcSearchInvokerTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void testProtobufSerialization() throws IOException {
    var compressionTypeHolder = new AtomicReference<CompressionType>();
    var payloadHolder = new AtomicReference<byte[]>();
    var lengthHolder = new AtomicInteger();
    var mockClient = parameterCollectorClient(compressionTypeHolder, payloadHolder, lengthHolder);
    var mockPool = new RpcResourcePool(ImmutableMap.of(7, mockClient.createConnection("foo", 123)));
    var invoker = new RpcSearchInvoker(mockSearcher(), new Node(7, "seven", 1), mockPool, 1000);

    Query q = new Query("search/?query=test&hits=10&offset=3");
    invoker.sendSearchRequest(q);

    var bytes = mockPool.compressor().decompress(payloadHolder.get(), compressionTypeHolder.get(), lengthHolder.get());
    var request = SearchProtocol.SearchRequest.newBuilder().mergeFrom(bytes).build();

    assertEquals(10, request.getHits());
    assertEquals(3, request.getOffset());
    assertTrue(request.getQueryTreeBlob().size() > 0);
}
 
Example #22
Source File: ParseEvtx.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    ComponentLog logger = getLogger();
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    String basename = getBasename(flowFile, logger);
    String granularity = context.getProperty(GRANULARITY).getValue();
    if (FILE.equals(granularity)) {
        // File granularity will emit a FlowFile for each input
        FlowFile original = session.clone(flowFile);
        AtomicReference<Exception> exceptionReference = new AtomicReference<>(null);
        FlowFile updated = session.write(flowFile, (in, out) -> {
            processFileGranularity(session, logger, original, basename, exceptionReference, in, out);
        });
        session.transfer(original, REL_ORIGINAL);
        resultProcessor.process(session, logger, updated, exceptionReference.get(), getName(basename, null, null, XML_EXTENSION));
    } else {
        session.read(flowFile, in -> {
            if (RECORD.equals(granularity)) {
                // Record granularity will emit a FlowFile for every record (event)
                processRecordGranularity(session, logger, flowFile, basename, in);
            } else if (CHUNK.equals(granularity)) {
                // Chunk granularity will emit a FlowFile for each chunk of the file
                processChunkGranularity(session, logger, flowFile, basename, in);
            }
        });
        session.transfer(flowFile, REL_ORIGINAL);
    }
}
 
Example #23
Source File: FailbackRegistryTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Test
    public void testDoRetry_register() throws Exception {

        final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false);
        final CountDownLatch latch = new CountDownLatch(1);//全部共调用4次。成功才会减1. subscribe的失败尝试不会在做了

        NotifyListener listner = new NotifyListener() {
            public void notify(List<URL> urls) {
                notified.set(Boolean.TRUE);
            }
        };
        registry = new MockRegistry(registryUrl, latch);
        registry.setBad(true);
        registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner);

        //失败的情况不能调用到listener.
        assertEquals(false, notified.get());
        assertEquals(1, latch.getCount());

        registry.setBad(false);

        for (int i = 0; i < trytimes; i++) {
            System.out.println("failback registry retry ,times:" + i);
            //System.out.println(latch.getCount());
            if (latch.getCount() == 0)
                break;
            Thread.sleep(sleeptime);
        }
//        Thread.sleep(100000);
        assertEquals(0, latch.getCount());
        //unsubscribe时会清除failedsubcribe对应key
        assertEquals(true, notified.get());
    }
 
Example #24
Source File: MultiModuleClassPathProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
TranslateBuildModules(
        @NonNull final ClassPath delegate,
        @NonNull final String... props) {
    this.delegate = delegate;
    this.props = new HashSet<>();
    Collections.addAll(this.props, props);
    this.cache = new AtomicReference<>();
    this.listeners = new PropertyChangeSupport(this);
    this.delegate.addPropertyChangeListener(WeakListeners.propertyChange(this, this.delegate));
    eval.addPropertyChangeListener(WeakListeners.propertyChange(this, eval));
}
 
Example #25
Source File: CPlatformWindow.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override // PlatformWindow
public Insets getInsets() {
    AtomicReference<Insets> ref = new AtomicReference<>();
    execute(ptr -> {
        ref.set(nativeGetNSWindowInsets(ptr));
    });
    return ref.get() != null ? ref.get() : new Insets(0, 0, 0, 0);
}
 
Example #26
Source File: SelfTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of the SelfTest class.
 *
 * @param testConfig    The configuration to use for the test.
 * @param builderConfig The configuration to use for building the StreamSegmentStore Service.
 */
SelfTest(TestConfig testConfig, ServiceBuilderConfig builderConfig) {
    Preconditions.checkNotNull(builderConfig, "builderConfig");

    this.testConfig = Preconditions.checkNotNull(testConfig, "testConfig");
    this.closed = new AtomicBoolean();
    this.actors = new ArrayList<>();
    this.testCompletion = new AtomicReference<>();
    this.state = new TestState();
    this.executor = ExecutorServiceHelpers.newScheduledThreadPool(testConfig.getThreadPoolSize(), "self-test");
    this.store = StoreAdapter.create(testConfig, builderConfig, this.executor);
    this.dataSource = createProducerDataSource(this.testConfig, this.state, this.store);
    Services.onStop(this, this::shutdownCallback, this::shutdownCallback, this.executor);
    this.reporter = new Reporter(this.state, this.testConfig, this.store::getStorePoolSnapshot, this.executor);
}
 
Example #27
Source File: ProtocolNegotiatorsTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void tlsHandler_userEventTriggeredSslEvent_unsupportedProtocol() throws Exception {
  SslHandler badSslHandler = new SslHandler(engine, false) {
    @Override
    public String applicationProtocol() {
      return "badprotocol";
    }
  };

  ChannelHandler handler = new ServerTlsHandler(grpcHandler, sslContext, null);
  pipeline.addLast(handler);

  final AtomicReference<Throwable> error = new AtomicReference<>();
  ChannelHandler errorCapture = new ChannelInboundHandlerAdapter() {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
      error.set(cause);
    }
  };

  pipeline.addLast(errorCapture);

  pipeline.replace(SslHandler.class, null, badSslHandler);
  channelHandlerCtx = pipeline.context(handler);
  Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;

  pipeline.fireUserEventTriggered(sslEvent);

  // No h2 protocol was specified, so there should be an error, (normally handled by WBAEH)
  assertThat(error.get()).hasMessageThat().contains("Unable to find compatible protocol");
  ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
  assertNull(grpcHandlerCtx);
}
 
Example #28
Source File: HeimdallDecorationFilterTest.java    From heimdall with Apache License 2.0 5 votes vote down vote up
@Test
public void matchRouteWithMultiEnvironments() {
    this.request.setRequestURI("/path/api/foo");
    this.request.setMethod(HttpMethod.GET.name());
    this.request.addHeader("host", "some-path.com");

    Map<String, ZuulRoute> routes = new LinkedHashMap<>();
    ZuulRoute route = new ZuulRoute("idFoo", "/path/api/foo", null, "my.dns.com.br", true, null, Collections.newSetFromMap(new ConcurrentHashMap<>()));
    routes.put("/path/api/foo", route);

    EnvironmentInfo environmentInfo = new EnvironmentInfo();
    environmentInfo.setId(1L);
    environmentInfo.setOutboundURL("https://some-path.com");
    environmentInfo.setVariables(new HashMap<>());

    Credential opGet = new Credential(HttpMethod.GET.name(), "/api/foo", "/path", "apiName", 10L, 88L, 10L, false);
    Credential opDelete = new Credential(HttpMethod.DELETE.name(), "/api/foo", "/path", "apiName", 10L, 88L, 10L, false);

    Mockito.when(routeLocator.getAtomicRoutes()).thenReturn(new AtomicReference<>(routes));
    Mockito.when(credentialRepository.findByPattern("/path/api/foo")).thenReturn(Lists.newArrayList(opGet, opDelete));
    Mockito.when(environmentInfoRepository.findByApiIdAndEnvironmentInboundURL(10L, "some-path.com")).thenReturn(environmentInfo);

    this.filter.run();

    assertEquals("/api/foo", this.ctx.get(REQUEST_URI_KEY));
    assertTrue(this.ctx.sendZuulResponse());
}
 
Example #29
Source File: SimpleRequestTest.java    From jus with Apache License 2.0 5 votes vote down vote up
@Test
public void conversionProblemIncomingAsync() throws InterruptedException, IOException {
    queue.addConverterFactory(new ToNumberConverterFactory() {
        @Override
        public Converter<NetworkResponse, ?> fromResponse(Type type, Annotation[] annotations) {
            return new Converter<NetworkResponse, Number>() {
                @Override
                public Number convert(NetworkResponse value) throws IOException {
                    throw new UnsupportedOperationException("I am broken!");
                }
            };
        }
    });
    server.enqueue(new MockResponse().setBody("777"));

    final AtomicReference<Throwable> failureRef = new AtomicReference<>();
    final CountDownLatch latch = new CountDownLatch(1);


    Request<Number> request = example.postNumber(777, new
            ToNumberConverterFactory().toRequest(Number.class, null))
            .addErrorListener(new RequestListener.ErrorListener() {
                @Override
                public void onError(JusError error) {
                    failureRef.set(error.getCause());
                    latch.countDown();
                }
            })
            .addResponseListener(new RequestListener.ResponseListener<Number>() {
                @Override
                public void onResponse(Number response) {
                    throw new AssertionError();
                }
            }).enqueue();

    assertTrue(latch.await(2, SECONDS));

    assertThat(failureRef.get()).isInstanceOf(UnsupportedOperationException.class)
            .hasMessage("I am broken!");
}
 
Example #30
Source File: AbstractGelfTransport.java    From gelfclient with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new GELF transport with the given configuration and {@link java.util.concurrent.BlockingQueue}.
 *
 * @param config the client configuration
 * @param queue  the {@link BlockingQueue} used to buffer GELF messages
 */
public AbstractGelfTransport(final GelfConfiguration config, final BlockingQueue<GelfMessage> queue) {
    this.config = config;
    this.queue = queue;
    this.workerGroup = new NioEventLoopGroup(config.getThreads(), new DefaultThreadFactory(getClass(), true));
    this.senderThreadReference = new AtomicReference<>();
    createBootstrap(workerGroup);
}