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: 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 #2
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 #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: 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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
Source File: HtmlXmlTokenListProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public TokenList findTokenList(Document doc) {
    if (!(doc instanceof BaseDocument)) {
        Logger.getLogger(HtmlXmlTokenListProvider.class.getName()).log(Level.INFO, null,
                new IllegalStateException("The given document is not an instance of the BaseDocument, is just " +  //NOI18N
                doc.getClass().getName()));
        return null;
    }

    //html
    final BaseDocument bdoc = (BaseDocument) doc;
    final String docMimetype = NbEditorUtilities.getMimeType(doc);
    final AtomicReference<TokenList> ret = new AtomicReference<TokenList>();
    doc.render(new Runnable() {
        public void run() {
            TokenHierarchy<?> th = TokenHierarchy.get(bdoc);
            Set<LanguagePath> paths = th.languagePaths();
            for(LanguagePath path : paths) {
                if(path.innerLanguage() == HTMLTokenId.language()) {
                    String settingName = MIME_TO_SETTING_NAME.get(docMimetype);
                    ret.set(new HtmlTokenList(bdoc, settingName));
                    break;
                }
            }
        }
    });
    if(ret.get() != null) {
        return ret.get();
    }

    //xml
    if ((docMimetype != null) && (docMimetype.contains("xml"))) { //NOI18N
        return new XmlTokenList(bdoc);
    }

    return null;
}
 
Example #23
Source File: EndPointKeyStoreManagerTest.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
@Test
public void testRequestKeyStore() {
    Context context = InstrumentationRegistry.getInstrumentation().getContext();
    String keyStoreFile = "keystore.p12";
    ComponentName authorityName = new ComponentName("org.deviceconnect.android.test",
            "org.deviceconnect.android.ssl.TestCertificateAuthorityService");

    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<KeyStore> result = new AtomicReference<>();
    final String keyStorePassword = "0000";

    KeyStoreManager mgr = new EndPointKeyStoreManager(context, keyStoreFile, keyStorePassword, context.getPackageName(), authorityName);
    mgr.requestKeyStore("0.0.0.0", new KeyStoreCallback() {
        @Override
        public void onSuccess(final KeyStore keyStore, final Certificate cert, final Certificate rootCert) {
            result.set(keyStore);
            latch.countDown();
        }

        @Override
        public void onError(final KeyStoreError error) {
            latch.countDown();
        }
    });
    try {
        if (latch.getCount() > 0) {
            latch.await(20, TimeUnit.SECONDS);
        }
        Assert.assertNotNull(result.get());
    } catch (InterruptedException e) {
        Assert.assertTrue(false);
    }
}
 
Example #24
Source File: AggregationsEvaluator.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Make an instance of {@link AggregationsEvaluator} based on a {@link Group} node.
 *
 * @param aggStateStore - The mechanism for storing aggregation state. (not null)
 * @param aggNode - Defines which aggregation functions need to be performed.
 * @param groupByVars - The names of the binding whose values are used to group aggregation results. (not null)
 * @return The evaluator that handles the node's aggregations.
 */
public static  AggregationsEvaluator make(final AggregationStateStore aggStateStore, final Group aggNode, final List<String> groupByVars) {
    requireNonNull(aggStateStore);
    requireNonNull(aggNode);
    requireNonNull(groupByVars);

    // The aggregations that need to be performed are the Group Elements.
    final List<AggregationElement> aggregations = new ArrayList<>();
    for(final GroupElem groupElem : aggNode.getGroupElements()) {
        // Figure out the type of the aggregation.
        final AggregateOperator operator = groupElem.getOperator();
        final Optional<AggregationType> type = AggregationType.byOperatorClass( operator.getClass() );

        // If the type is one we support, create the AggregationElement.
        if(type.isPresent()) {
            final String resultBindingName = groupElem.getName();

            final AtomicReference<String> aggregatedBindingName = new AtomicReference<>();
            groupElem.visitChildren(new AbstractQueryModelVisitor<RuntimeException>() {
                @Override
                public void meet(final Var node) {
                    aggregatedBindingName.set( node.getName() );
                }
            });

            aggregations.add( new AggregationElement(type.get(), aggregatedBindingName.get(), resultBindingName) );
        }
    }

    return new AggregationsEvaluator(aggStateStore, aggregations, groupByVars);
}
 
Example #25
Source File: Phaser.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Variant of releaseWaiters that additionally tries to remove any
 * nodes no longer waiting for advance due to timeout or
 * interrupt. Currently, nodes are removed only if they are at
 * head of queue, which suffices to reduce memory footprint in
 * most usages.
 *
 * @return current phase on exit
 */
private int abortWait(int phase) {
    AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
    for (;;) {
        Thread t;
        QNode q = head.get();
        int p = (int)(root.state >>> PHASE_SHIFT);
        if (q == null || ((t = q.thread) != null && q.phase == p))
            return p;
        if (head.compareAndSet(q, q.next) && t != null) {
            q.thread = null;
            LockSupport.unpark(t);
        }
    }
}
 
Example #26
Source File: MultipleScenariosTest.java    From havarunner with MIT License 5 votes vote down vote up
private AtomicReference<Failure> runInvalidScenarioTestMethod() throws InitializationError {
    final AtomicReference<Failure> expectedFailure = new AtomicReference<>();
    new HavaRunner(InvalidScenarioTest.class).run(new RunNotifier() {
        @Override
        public void fireTestFailure(Failure failure) {
            expectedFailure.set(failure);
        }
    });
    return expectedFailure;
}
 
Example #27
Source File: AbstractKerberosSingleRealmTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void spnegoWithInvalidTokenTest() throws Exception {
    initHttpClient(true);

    // Update kerberos configuration with some invalid location of keytab file
    AtomicReference<String> origKeytab = new AtomicReference<>();
    updateUserStorageProvider(kerberosProviderRep -> {
        String keytab = kerberosProviderRep.getConfig().getFirst(KerberosConstants.KEYTAB);
        origKeytab.set(keytab);

        kerberosProviderRep.getConfig().putSingle(KerberosConstants.KEYTAB, keytab + "-invalid");
    });

    try {
        /*
        To do this we do a valid kerberos login on client side.  The authenticator will obtain a valid token, but user
        storage provider is incorrectly configured, so SPNEGO login will fail on server side. However the server should continue to
        the login page (username/password) and return status 200. It should not return 401 with "Kerberos unsupported" page as that
        would display some strange dialogs in the web browser on windows - see KEYCLOAK-12424
        */
        Response spnegoResponse = spnegoLogin("hnelson", "secret");

        Assert.assertEquals(200, spnegoResponse.getStatus());
        String context = spnegoResponse.readEntity(String.class);
        spnegoResponse.close();

        org.junit.Assert.assertTrue(context.contains("Log in to test"));

        events.clear();
    } finally {
        // Revert keytab configuration
        updateUserStorageProvider(kerberosProviderRep -> kerberosProviderRep.getConfig().putSingle(KerberosConstants.KEYTAB, origKeytab.get()));
    }
}
 
Example #28
Source File: TopTestUtil.java    From rolling-metrics with Apache License 2.0 5 votes vote down vote up
public static void runInParallel(Top top, long durationMillis, long minValue, long maxValue) throws InterruptedException {
    AtomicReference<Throwable> errorRef = new AtomicReference<>();

    Thread[] threads = new Thread[Runtime.getRuntime().availableProcessors() * 2];
    final CountDownLatch latch = new CountDownLatch(threads.length);
    long start = System.currentTimeMillis();
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(() -> {
            try {
                // update top 10 times and take snapshot on each cycle
                while (errorRef.get() == null && System.currentTimeMillis() - start < durationMillis) {
                    for (int j = 1; j <= 10; j++) {
                        long latency = minValue + ThreadLocalRandom.current().nextLong(maxValue - minValue);
                        top.update(System.currentTimeMillis(), latency, TimeUnit.NANOSECONDS, () -> "" + latency);
                    }
                    top.getPositionsInDescendingOrder();
                }
            } catch (Exception e){
                e.printStackTrace();
                errorRef.set(e);
            } finally {
                latch.countDown();
            }
        });
        threads[i].setDaemon(true);
        threads[i].start();
    }
    latch.await();
    //latch.await(duration.toMillis() + 4000, TimeUnit.MILLISECONDS);
    if (latch.getCount() > 0) {
        throw new IllegalStateException("" + latch.getCount() + " was not completed");
    }
    if (errorRef.get() != null) {
        throw new RuntimeException(errorRef.get());
    }
}
 
Example #29
Source File: EliminationStack.java    From multiway-pool with Apache License 2.0 5 votes vote down vote up
/**
 * Scans the arena searching for a waiting consumer to exchange with.
 *
 * @param e the element to try to exchange
 * @return if the element was successfully transfered
 */
boolean scanAndTransferToWaiter(E e, int start) {
  for (int i = 0; i < ARENA_LENGTH; i++) {
    int index = (start + i) & ARENA_MASK;
    AtomicReference<Object> slot = arena[index];
    // if some thread is waiting to receive an element then attempt to provide it
    if ((slot.get() == WAITER) && slot.compareAndSet(WAITER, e)) {
      return true;
    }
  }
  return false;
}
 
Example #30
Source File: TestableKinesisDataFetcherForShardConsumerException.java    From flink with Apache License 2.0 5 votes vote down vote up
public TestableKinesisDataFetcherForShardConsumerException(final List<String> fakeStreams,
		final SourceFunction.SourceContext<T> sourceContext,
		final Properties fakeConfiguration,
		final KinesisDeserializationSchema<T> deserializationSchema,
		final int fakeTotalCountOfSubtasks,
		final int fakeIndexOfThisSubtask,
		final AtomicReference<Throwable> thrownErrorUnderTest,
		final LinkedList<KinesisStreamShardState> subscribedShardsStateUnderTest,
		final HashMap<String, String> subscribedStreamsToLastDiscoveredShardIdsStateUnderTest,
		final KinesisProxyInterface fakeKinesis) {
	super(fakeStreams, sourceContext, fakeConfiguration, deserializationSchema, fakeTotalCountOfSubtasks,
		fakeIndexOfThisSubtask, thrownErrorUnderTest, subscribedShardsStateUnderTest,
		subscribedStreamsToLastDiscoveredShardIdsStateUnderTest, fakeKinesis);
}