java.util.concurrent.atomic.AtomicReference

Here are the examples of the java api class java.util.concurrent.atomic.AtomicReference taken from open source projects.

1. ServiceDiscoveryImplTest#setup()

Project: qbit
Source File: ServiceDiscoveryImplTest.java
View license
@Before
public void setup() {
    servicePoolChangedCalled = new AtomicInteger();
    serviceAdded = new AtomicInteger();
    serviceRemoved = new AtomicInteger();
    servicePoolChangedServiceName = new AtomicReference<>();
    servicePoolChangedServiceNameFromListener = new AtomicReference<>();
    registeredEndpointDefinitions = new ConcurrentHashSet<>(100);
    healthCheckIns = new ConcurrentHashSet<>(100);
    serviceDiscovery = new ServiceDiscoveryImpl(createPeriodicScheduler(10), eventChannel, provider, null, servicePoolListener, null, 5, 5);
    healthyServices = new AtomicReference<>();
    serviceDiscovery.start();
}

2. ViewInteractionTest#setUp()

View license
@Override
public void setUp() throws Exception {
    super.setUp();
    initMocks(this);
    realLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance();
    rootView = new View(getContext());
    targetView = new View(getContext());
    viewMatcher = is(targetView);
    actionConstraint = Matchers.<View>notNullValue();
    rootMatcherRef = new AtomicReference<Matcher<Root>>(RootMatchers.DEFAULT);
    when(mockAction.getDescription()).thenReturn("A Mock!");
    failureHandler = new FailureHandler() {

        @Override
        public void handle(Throwable error, Matcher<View> viewMatcher) {
            propagate(error);
        }
    };
}

3. AbstractConfiguration#cloneInterpolator()

View license
/**
     * Creates a clone of the {@code ConfigurationInterpolator} used by this
     * instance. This method can be called by {@code clone()} implementations of
     * derived classes. Normally, the {@code ConfigurationInterpolator} of a
     * configuration instance must not be shared with other instances because it
     * contains a specific {@code Lookup} object pointing to the owning
     * configuration. This has to be taken into account when cloning a
     * configuration. This method creates a new
     * {@code ConfigurationInterpolator} for this configuration instance which
     * contains all lookup objects from the original
     * {@code ConfigurationInterpolator} except for the configuration specific
     * lookup pointing to the passed in original configuration. This one is
     * replaced by a corresponding {@code Lookup} referring to this
     * configuration.
     *
     * @param orgConfig the original configuration from which this one was
     *        cloned
     * @since 2.0
     */
protected void cloneInterpolator(AbstractConfiguration orgConfig) {
    interpolator = new AtomicReference<ConfigurationInterpolator>();
    ConfigurationInterpolator orgInterpolator = orgConfig.getInterpolator();
    List<Lookup> defaultLookups = orgInterpolator.getDefaultLookups();
    Lookup lookup = findConfigurationLookup(orgInterpolator, orgConfig);
    if (lookup != null) {
        defaultLookups.remove(lookup);
    }
    installInterpolator(orgInterpolator.getLookups(), defaultLookups);
}

4. DeleteManagerTest#init()

Project: ambry
Source File: DeleteManagerTest.java
View license
/**
   * Initializes ClusterMap, Router, mock servers, and an {@code BlobId} to be deleted.
   */
@Before
public void init() throws Exception {
    VerifiableProperties vProps = new VerifiableProperties(getNonBlockingRouterProperties());
    operationCompleteLatch = new CountDownLatch(1);
    mockTime = new MockTime();
    mockSelectorState = new AtomicReference<MockSelectorState>(MockSelectorState.Good);
    clusterMap = new MockClusterMap();
    serverLayout = new MockServerLayout(clusterMap);
    router = new NonBlockingRouter(new RouterConfig(vProps), new NonBlockingRouterMetrics(clusterMap), new MockNetworkClientFactory(vProps, mockSelectorState, MAX_PORTS_PLAIN_TEXT, MAX_PORTS_SSL, CHECKOUT_TIMEOUT_MS, serverLayout, mockTime), new LoggingNotificationSystem(), clusterMap, mockTime);
    List<PartitionId> mockPartitions = clusterMap.getWritablePartitionIds();
    partition = mockPartitions.get(ThreadLocalRandom.current().nextInt(mockPartitions.size()));
    blobId = new BlobId(partition);
    blobIdString = blobId.getID();
}

5. AtomicReferenceTest#testCompareAndSetInMultipleThreads()

Project: openjdk
Source File: AtomicReferenceTest.java
View license
/**
     * compareAndSet in one thread enables another waiting for value
     * to succeed
     */
public void testCompareAndSetInMultipleThreads() throws Exception {
    final AtomicReference ai = new AtomicReference(one);
    Thread t = new Thread(new CheckedRunnable() {

        public void realRun() {
            while (!ai.compareAndSet(two, three)) Thread.yield();
        }
    });
    t.start();
    assertTrue(ai.compareAndSet(one, two));
    t.join(LONG_DELAY_MS);
    assertFalse(t.isAlive());
    assertSame(three, ai.get());
}

6. BasicKeyChainTest#setup()

Project: bitcoinj
Source File: BasicKeyChainTest.java
View license
@Before
public void setup() {
    chain = new BasicKeyChain();
    onKeysAdded = new AtomicReference<List<ECKey>>();
    onKeysAddedRan = new AtomicBoolean();
    chain.addEventListener(new AbstractKeyChainEventListener() {

        @Override
        public void onKeysAdded(List<ECKey> keys2) {
            onKeysAdded.set(keys2);
            onKeysAddedRan.set(true);
        }
    }, Threading.SAME_THREAD);
}

7. ClusteredStatReplicatorTest#setup()

View license
@Before
public void setup() throws Exception {
    services = new AtomicReference<>();
    statReplicatorMap = new ConcurrentHashMap<>();
    timer.setTime();
    clusteredStatReplicator = new ClusteredStatReplicator(serviceName, serviceDiscovery, provider, localServiceId, timer, 100, 333);
}

8. GlobFunctionTest#setUp()

Project: bazel
Source File: GlobFunctionTest.java
View license
@Before
public final void setUp() throws Exception {
    fs = new CustomInMemoryFs(new ManualClock());
    root = fs.getRootDirectory().getRelative("root/workspace");
    writableRoot = fs.getRootDirectory().getRelative("writableRoot/workspace");
    outputBase = fs.getRootDirectory().getRelative("output_base");
    pkgPath = root.getRelative(PKG_ID.getPackageFragment());
    pkgLocator = new AtomicReference<>(new PathPackageLocator(outputBase, ImmutableList.of(writableRoot, root)));
    differencer = new RecordingDifferencer();
    evaluator = new InMemoryMemoizingEvaluator(createFunctionMap(), differencer);
    driver = new SequentialBuildDriver(evaluator);
    PrecomputedValue.BUILD_ID.set(differencer, UUID.randomUUID());
    PrecomputedValue.PATH_PACKAGE_LOCATOR.set(differencer, pkgLocator.get());
    PrecomputedValue.BLACKLISTED_PACKAGE_PREFIXES_FILE.set(differencer, PathFragment.EMPTY_FRAGMENT);
    createTestFiles();
}

9. CallbackManagerWithTimeoutTest#setUp()

View license
@Before
public void setUp() throws Exception {
    testTimer = new TestTimer();
    testTimer.setTime();
    callbackManager = CallbackManagerBuilder.callbackManagerBuilder().setTimer(testTimer).setName("testBuilder").build();
    callbackManagerWithTimeout = ((CallbackManagerWithTimeout) callbackManager);
    methodCallBuilder = MethodCallBuilder.methodCallBuilder();
    callbackBuilder = CallbackBuilder.newCallbackBuilder();
    result = new AtomicReference<>("none");
    continueMethod = new CountDownLatch(1);
}

10. ContainingPackageLookupFunctionTest#setUp()

View license
@Before
public final void setUp() throws Exception {
    AtomicReference<PathPackageLocator> pkgLocator = new AtomicReference<>(new PathPackageLocator(outputBase, ImmutableList.of(rootDirectory)));
    deletedPackages = new AtomicReference<>(ImmutableSet.<PackageIdentifier>of());
    ExternalFilesHelper externalFilesHelper = new ExternalFilesHelper(pkgLocator, false, new BlazeDirectories(rootDirectory, rootDirectory, rootDirectory, TestConstants.PRODUCT_NAME));
    Map<SkyFunctionName, SkyFunction> skyFunctions = new HashMap<>();
    skyFunctions.put(SkyFunctions.PACKAGE_LOOKUP, new PackageLookupFunction(deletedPackages));
    skyFunctions.put(SkyFunctions.CONTAINING_PACKAGE_LOOKUP, new ContainingPackageLookupFunction());
    skyFunctions.put(SkyFunctions.BLACKLISTED_PACKAGE_PREFIXES, new BlacklistedPackagePrefixesFunction());
    skyFunctions.put(SkyFunctions.FILE_STATE, new FileStateFunction(new AtomicReference<TimestampGranularityMonitor>(), externalFilesHelper));
    skyFunctions.put(SkyFunctions.FILE, new FileFunction(pkgLocator));
    RecordingDifferencer differencer = new RecordingDifferencer();
    evaluator = new InMemoryMemoizingEvaluator(skyFunctions, differencer);
    driver = new SequentialBuildDriver(evaluator);
    PrecomputedValue.BUILD_ID.set(differencer, UUID.randomUUID());
    PrecomputedValue.PATH_PACKAGE_LOCATOR.set(differencer, pkgLocator.get());
    PrecomputedValue.BLACKLISTED_PACKAGE_PREFIXES_FILE.set(differencer, PathFragment.EMPTY_FRAGMENT);
}

11. HttpClientVertxTest#connect()

Project: qbit
Source File: HttpClientVertxTest.java
View license
public void connect() {
    port = PortUtils.findOpenPortStartAt(port);
    server = new HttpServerBuilder().setPort(port).build();
    client = new HttpClientBuilder().setPoolSize(1).setPort(port).build();
    requestReceived = new AtomicBoolean();
    responseReceived = new AtomicBoolean();
    messageBody = new AtomicReference<>();
    responseCode = new AtomicInteger();
    port++;
}

12. AbruptClientDisconnectTest#createTunneledConnection()

View license
private Connection createTunneledConnection(final ClientMonitor clientMonitor) throws URLSyntaxException, JMSException {
    final ConnectionURL url = new AMQConnectionURL(String.format(CONNECTION_URL_TEMPLATE, _tcpTunneler.getLocalPort()));
    Connection tunneledConnection = getConnection(url);
    _tcpTunneler.addClientListener(clientMonitor);
    final AtomicReference _exception = new AtomicReference();
    tunneledConnection.setExceptionListener(new ExceptionListener() {

        @Override
        public void onException(final JMSException exception) {
            _exception.set(exception);
            _tcpTunneler.disconnect(clientMonitor.getClientAddress());
        }
    });
    return tunneledConnection;
}

13. ServerStatusChangeListenerTest#setupLoadbalancerAndListener()

View license
@Before
public void setupLoadbalancerAndListener() {
    lb = new NoPingTaskLoadBalancer();
    lb.setServersList(asList(server1, server2));
    serversReceivedByListener = new AtomicReference<List<Server>>();
    lb.addServerStatusChangeListener(new ServerStatusChangeListener() {

        @Override
        public void serverStatusChanged(final Collection<Server> servers) {
            serversReceivedByListener.set(new ArrayList<Server>(servers));
        }
    });
}

14. AbstractReconciler#setup()

Project: apex-malhar
Source File: AbstractReconciler.java
View license
@Override
public void setup(Context.OperatorContext context) {
    if (context != null) {
        spinningTime = context.getValue(Context.OperatorContext.SPIN_MILLIS);
    }
    execute = true;
    cause = new AtomicReference<Throwable>();
    waitingTuples.addAll(committedTuples);
    executorService = Executors.newSingleThreadExecutor(new NameableThreadFactory("Reconciler-Helper"));
    executorService.submit(processEnqueuedData());
}

15. SimpleKafkaConsumer#start()

View license
@Override
public void start() {
    monitorException = new AtomicReference<Throwable>(null);
    monitorExceptionCount = new AtomicInteger(0);
    super.start();
    // thread to consume the kafka data
    kafkaConsumerExecutor = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("kafka-consumer-" + topic + "-%d").build());
    if (metadataRefreshInterval <= 0 || CollectionUtils.isEmpty(kps)) {
        return;
    }
    // background thread to monitor the kafka metadata change
    metadataRefreshExecutor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setNameFormat("kafka-consumer-monitor-" + topic + "-%d").setDaemon(true).build());
    // start one monitor thread to monitor the leader broker change and trigger some action
    metadataRefreshExecutor.scheduleAtFixedRate(new MetaDataMonitorTask(this), 0, metadataRefreshInterval, TimeUnit.MILLISECONDS);
}

16. AtomicReferenceTest#testSerialization()

Project: openjdk
Source File: AtomicReferenceTest.java
View license
/**
     * a deserialized serialized atomic holds same value
     */
public void testSerialization() throws Exception {
    AtomicReference x = new AtomicReference();
    AtomicReference y = serialClone(x);
    assertNotSame(x, y);
    x.set(one);
    AtomicReference z = serialClone(x);
    assertNotSame(y, z);
    assertEquals(one, x.get());
    assertEquals(null, y.get());
    assertEquals(one, z.get());
}

17. AtomicReferenceTest#testGetLazySet()

Project: openjdk
Source File: AtomicReferenceTest.java
View license
/**
     * get returns the last value lazySet in same thread
     */
public void testGetLazySet() {
    AtomicReference ai = new AtomicReference(one);
    assertSame(one, ai.get());
    ai.lazySet(two);
    assertSame(two, ai.get());
    ai.lazySet(m3);
    assertSame(m3, ai.get());
}

18. AtomicReferenceTest#testGetSet()

Project: openjdk
Source File: AtomicReferenceTest.java
View license
/**
     * get returns the last value set
     */
public void testGetSet() {
    AtomicReference ai = new AtomicReference(one);
    assertSame(one, ai.get());
    ai.set(two);
    assertSame(two, ai.get());
    ai.set(m3);
    assertSame(m3, ai.get());
}

19. ReaktInterfaceWebSocketRPCTest#before()

View license
@Before
public void before() {
    port = PortUtils.findOpenPortStartAt(9000);
    latch = new CountDownLatch(1);
    returnValue = new AtomicReference<>();
    errorRef = new AtomicReference<>();
    impl = new ServiceDiscoveryImpl();
    empURI = URI.create("marathon://default/employeeService?env=staging");
    server = EndpointServerBuilder.endpointServerBuilder().addService("/myservice", impl).setPort(port).build().startServer();
    Sys.sleep(25);
    client = ClientBuilder.clientBuilder().setPort(port).build();
    serviceDiscoveryWebSocket = client.createProxy(ServiceDiscovery.class, "/myservice");
    client.start();
}

20. ServiceDiscoveryWithFileSystemTest#setup()

View license
@Before
public void setup() throws Exception {
    dir = File.createTempFile("testSome", "testSome").getParentFile();
    servicePoolChangedCalled = new AtomicInteger();
    serviceAdded = new AtomicInteger();
    serviceRemoved = new AtomicInteger();
    servicePoolChangedServiceName = new AtomicReference<>();
    servicePoolChangedServiceNameFromListener = new AtomicReference<>();
    ServiceDiscoveryFileSystemProvider provider = new ServiceDiscoveryFileSystemProvider(dir, 50);
    serviceDiscovery = ServiceDiscoveryBuilder.serviceDiscoveryBuilder().setPeriodicScheduler(createPeriodicScheduler(10)).setServiceChangedEventChannel(eventChannel).setServicePoolListener(servicePoolListener).setServiceDiscoveryProvider(provider).setPollForServicesIntervalSeconds(1).build();
    serviceDiscovery.start();
}

21. ServiceBundleAndEvents#setup()

Project: qbit
Source File: ServiceBundleAndEvents.java
View license
@Before
public void setup() {
    method = new AtomicReference<>();
    event = new AtomicReference<>();
    eventManager = EventManagerBuilder.eventManagerBuilder().build("localtest");
    eventServiceQueue = ServiceBuilder.serviceBuilder().setServiceObject(eventManager).buildAndStartAll();
    eventManager = eventServiceQueue.createProxy(EventManager.class);
    testServiceImpl = new TestServiceImpl();
    ServiceBuilder serviceBuilder = ServiceBuilder.serviceBuilder().setEventManager(eventManager);
    serviceBuilder.getRequestQueueBuilder().setBatchSize(100);
    this.serviceQueue = serviceBuilder.setServiceObject(testServiceImpl).buildAndStart();
    serviceBundle = serviceBundleBuilder().buildAndStart();
    eventBusProxyCreator = QBit.factory().eventBusProxyCreator();
    sender = eventBusProxyCreator.createProxy(eventManager, EventChannel1.class);
    serviceBundle.addServiceQueue(serviceName, this.serviceQueue);
    testService = serviceBundle.createLocalProxy(TestService.class, serviceName);
}

22. ReaktInterfaceTest#before()

Project: qbit
Source File: ReaktInterfaceTest.java
View license
@Before
public void before() {
    latch = new CountDownLatch(1);
    returnValue = new AtomicReference<>();
    errorRef = new AtomicReference<>();
    impl = new ServiceDiscoveryImpl();
    empURI = URI.create("marathon://default/employeeService?env=staging");
    ServiceBuilder serviceBuilder = ServiceBuilder.serviceBuilder();
    serviceBuilder.getRequestQueueBuilder().setArrayBlockingQueue().setBatchSize(10);
    serviceQueue = serviceBuilder.setServiceObject(impl).buildAndStartAll();
    ServiceBundleBuilder serviceBundleBuilder = ServiceBundleBuilder.serviceBundleBuilder();
    serviceBundleBuilder.getRequestQueueBuilder().setArrayBlockingQueue().setBatchSize(10);
    serviceBundle = serviceBundleBuilder.build();
    serviceBundle.addServiceObject("myservice", impl);
    serviceQueue2 = ServiceBuilder.serviceBuilder().setInvokeDynamic(false).setServiceObject(impl).buildAndStartAll();
    serviceDiscoveryServiceBundle = serviceBundle.createLocalProxy(ServiceDiscovery.class, "myservice");
    serviceBundle.start();
    serviceDiscovery = serviceQueue.createProxyWithAutoFlush(ServiceDiscovery.class, Duration.TEN_MILLIS);
    serviceDiscoveryStrongTyped = serviceQueue2.createProxyWithAutoFlush(ServiceDiscovery.class, Duration.TEN_MILLIS);
}

23. RefCountedTest#testWeakRef()

Project: cassandra
Source File: RefCountedTest.java
View license
//Make sure a weak ref is ignored by the visitor looking for strong ref leaks
@Test
public void testWeakRef() throws Exception {
    AtomicReference dontRefMe = new AtomicReference();
    WeakReference<Object> weakRef = new WeakReference(dontRefMe);
    RefCounted.Tidy tidier = new RefCounted.Tidy() {

        WeakReference<Object> ref = weakRef;

        @Override
        public void tidy() throws Exception {
        }

        @Override
        public String name() {
            return "42";
        }
    };
    Ref<Object> ref = new Ref(dontRefMe, tidier);
    dontRefMe.set(ref);
    Visitor visitor = new Visitor();
    visitor.haveLoops = new HashSet<>();
    visitor.run();
    ref.close();
    Assert.assertTrue(visitor.haveLoops.isEmpty());
}

24. SupportingGetAndPostForSameServicesUnderSameURI#setup()

View license
@Before
public void setup() throws Exception {
    super.setupLatch();
    port = PortUtils.findOpenPortStartAt(8888);
    pongValue = new AtomicReference<>();
    headers = new AtomicReference<>();
    httpClient = new HttpClientBuilder().setPort(port).build();
    client = new ClientBuilder().setPort(port).build();
    EndpointServerBuilder endpointServerBuilder = EndpointServerBuilder.endpointServerBuilder();
    endpointServerBuilder.setPort(port).getHttpServerBuilder();
    endpointServerBuilder.getHttpServerBuilder().addResponseDecorator(new HttpResponseDecorator() {

        @Override
        public boolean decorateTextResponse(HttpTextResponseHolder responseHolder, String requestPath, String method, int code, String contentType, String payload, MultiMap<String, String> responseHeaders, MultiMap<String, String> requestHeaders, MultiMap<String, String> requestParams) {
            responseHolder.setHttpTextResponse((HttpTextResponse) HttpResponseBuilder.httpResponseBuilder().setCode(code).setContentType(contentType).addHeader("TEST_HEADER", "TEST").setBody(payload).build());
            return true;
        }

        @Override
        public boolean decorateBinaryResponse(HttpBinaryResponseHolder responseHolder, String requestPath, String method, int code, String contentType, byte[] payload, MultiMap<String, String> responseHeaders, MultiMap<String, String> requestHeaders, MultiMap<String, String> requestParams) {
            return false;
        }
    });
    server = endpointServerBuilder.build();
    server.initServices(new MockService());
    server.startServerAndWait();
    clientProxy = client.createProxy(ClientServiceInterface.class, "pinger");
    client.start();
    httpClient.startClient();
    callCount = 0;
    pongValue.set(null);
    puts("STARTED..........");
}

25. MemoryVirtualFileSystemProviderTest#closesVirtualFileSystemWhenProviderIsClosed()

View license
@Test
public void closesVirtualFileSystemWhenProviderIsClosed() throws Exception {
    AtomicReference fileSystemReference = getFileSystemReference();
    VirtualFileSystem fileSystem = mock(VirtualFileSystem.class);
    fileSystemReference.set(fileSystem);
    fileSystemProvider.close();
    verify(fileSystem).close();
}

26. BaseTest#serverDownTest()

Project: wasync
Source File: BaseTest.java
View license
@Test
public void serverDownTest() throws Exception {
    final CountDownLatch latch = new CountDownLatch(3);
    final AtomicReference response = new AtomicReference();
    final AtomicReference response2 = new AtomicReference();
    Client client = ClientFactory.getDefault().newClient();
    String unreachableUrl = "http://localhost:815";
    RequestBuilder request = client.newRequestBuilder().method(Request.METHOD.GET).uri(unreachableUrl + "/suspend").transport(transport());
    final Socket socket = client.create(client.newOptionsBuilder().runtime(ahc, false).build());
    IOException ioException = null;
    try {
        socket.on(new Function<ConnectException>() {

            @Override
            public void on(ConnectException t) {
                // I close it here, remove this close, issue will not happen
                socket.close();
                response.set(t);
                latch.countDown();
            }
        }).on(new Function<IOException>() {

            @Override
            public void on(IOException t) {
                response2.set(t);
                latch.countDown();
            }
        }).open(request.build());
    } catch (IOException ex) {
        ioException = ex;
    }
    socket.fire("echo");
    latch.await(5, TimeUnit.SECONDS);
    assertEquals(response.get().getClass(), ConnectException.class);
    assertTrue(IOException.class.isAssignableFrom(response2.get().getClass()));
    assertTrue(IOException.class.isAssignableFrom(ioException.getClass()));
}

27. AbstractJettyTest#setUpBase()

Project: aurora
Source File: AbstractJettyTest.java
View license
@Before
public void setUpBase() throws Exception {
    storage = new StorageTestUtil(this);
    ServiceGroupMonitor serviceGroupMonitor = createMock(ServiceGroupMonitor.class);
    injector = Guice.createInjector(new StatsModule(), new LifecycleModule(), new SchedulerServicesModule(), new AsyncModule(), new AbstractModule() {

        <T> T bindMock(Class<T> clazz) {
            T mock = createMock(clazz);
            bind(clazz).toInstance(mock);
            return mock;
        }

        @Override
        protected void configure() {
            bind(StatsProvider.class).toInstance(new FakeStatsProvider());
            bind(Storage.class).toInstance(storage.storage);
            bind(IServerInfo.class).toInstance(IServerInfo.build(new ServerInfo().setClusterName("unittest").setStatsUrlPrefix("none")));
            bind(TaskGroupsSettings.class).toInstance(new TaskGroupsSettings(Amount.of(1L, Time.MILLISECONDS), bindMock(BackoffStrategy.class), RateLimiter.create(1000)));
            bind(ServiceGroupMonitor.class).toInstance(serviceGroupMonitor);
            bindMock(CronJobManager.class);
            bindMock(LockManager.class);
            bindMock(OfferManager.class);
            bindMock(RescheduleCalculator.class);
            bindMock(TaskScheduler.class);
            bindMock(TierManager.class);
            bindMock(Thread.UncaughtExceptionHandler.class);
            bind(ServletContextListener.class).toProvider(() -> {
                return makeServletContextListener(injector, getChildServletModule());
            });
        }
    }, new JettyServerModule(false));
    schedulers = new AtomicReference<>(ImmutableSet.of());
    serviceGroupMonitor.start();
    expectLastCall();
    expect(serviceGroupMonitor.get()).andAnswer(schedulers::get).anyTimes();
}

28. Throwables_appendCurrentThreadStackTraceToThrowable_Test#setUp()

View license
@Before
public void setUp() {
    exceptionReference = new AtomicReference<>();
}

29. PackageLookupFunctionTest#setUp()

View license
@Before
public final void setUp() throws Exception {
    Path emptyPackagePath = rootDirectory.getRelative("somewhere/else");
    scratch.file("parentpackage/BUILD");
    AtomicReference<PathPackageLocator> pkgLocator = new AtomicReference<>(new PathPackageLocator(outputBase, ImmutableList.of(emptyPackagePath, rootDirectory)));
    deletedPackages = new AtomicReference<>(ImmutableSet.<PackageIdentifier>of());
    BlazeDirectories directories = new BlazeDirectories(rootDirectory, outputBase, rootDirectory, TestConstants.PRODUCT_NAME);
    ExternalFilesHelper externalFilesHelper = new ExternalFilesHelper(pkgLocator, false, directories);
    Map<SkyFunctionName, SkyFunction> skyFunctions = new HashMap<>();
    skyFunctions.put(SkyFunctions.PACKAGE_LOOKUP, new PackageLookupFunction(deletedPackages));
    skyFunctions.put(SkyFunctions.PACKAGE, new PackageFunction(null, null, null, null, null, null, null));
    skyFunctions.put(SkyFunctions.FILE_STATE, new FileStateFunction(new AtomicReference<TimestampGranularityMonitor>(), externalFilesHelper));
    skyFunctions.put(SkyFunctions.FILE, new FileFunction(pkgLocator));
    skyFunctions.put(SkyFunctions.BLACKLISTED_PACKAGE_PREFIXES, new BlacklistedPackagePrefixesFunction());
    RuleClassProvider ruleClassProvider = TestRuleClassProvider.getRuleClassProvider();
    skyFunctions.put(SkyFunctions.WORKSPACE_AST, new WorkspaceASTFunction(TestRuleClassProvider.getRuleClassProvider()));
    skyFunctions.put(SkyFunctions.WORKSPACE_FILE, new WorkspaceFileFunction(ruleClassProvider, TestConstants.PACKAGE_FACTORY_FACTORY_FOR_TESTING.create(ruleClassProvider, new BazelRulesModule().getPackageEnvironmentExtension(), scratch.getFileSystem()), directories));
    skyFunctions.put(SkyFunctions.EXTERNAL_PACKAGE, new ExternalPackageFunction());
    differencer = new RecordingDifferencer();
    evaluator = new InMemoryMemoizingEvaluator(skyFunctions, differencer);
    driver = new SequentialBuildDriver(evaluator);
    PrecomputedValue.BUILD_ID.set(differencer, UUID.randomUUID());
    PrecomputedValue.PATH_PACKAGE_LOCATOR.set(differencer, pkgLocator.get());
    PrecomputedValue.BLACKLISTED_PACKAGE_PREFIXES_FILE.set(differencer, PathFragment.EMPTY_FRAGMENT);
}

30. ProfilerServerTest#setup()

View license
@Before
public void setup() throws IOException {
    MockProfiler1 profiler1 = new MockProfiler1(new HashSet<String>());
    MockProfiler2 profiler2 = new MockProfiler2(new HashSet<String>());
    activeProfilers = new HashMap<>();
    activeProfilers.put("MockProfiler1", profiler1);
    activeProfilers.put("MockProfiler2", profiler2);
    port = 8080;
    isRunning = new AtomicReference<>(true);
    errors = new ArrayList<>();
    errors.add("example error");
    Map<String, ScheduledFuture<?>> runningProfilers = new HashMap<>();
    ProfilerWorkerThread worker1 = new ProfilerWorkerThread(profiler1, errors);
    ProfilerWorkerThread worker2 = new ProfilerWorkerThread(profiler2, errors);
    ScheduledExecutorService scheduledExecutorService = MoreExecutors.getExitingScheduledExecutorService((ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(2, new ProfilerThreadFactory()));
    ScheduledFuture future1 = scheduledExecutorService.scheduleAtFixedRate(worker1, 0, profiler1.getPeriod(), profiler1.getTimeUnit());
    ScheduledFuture future2 = scheduledExecutorService.scheduleAtFixedRate(worker2, 0, profiler2.getPeriod(), profiler2.getTimeUnit());
    runningProfilers.put("MockProfiler1", future1);
    runningProfilers.put("MockProfiler2", future2);
    ProfilerServer.startServer(runningProfilers, activeProfilers, port, isRunning, errors);
    client = HttpClients.createDefault();
}

31. LoadTestingTest#setup()

Project: qbit
Source File: LoadTestingTest.java
View license
@Before
public void setup() throws Exception {
    Sys.sleep(100);
    pongValue = new AtomicReference<>();
    httpClient = new HttpClientBuilder().setPort(port).build();
    client = new ClientBuilder().setFlushInterval(200).setProtocolBatchSize(100).setPort(port).build();
    final EndpointServerBuilder endpointServerBuilder = new EndpointServerBuilder();
    endpointServerBuilder.getRequestQueueBuilder().setBatchSize(100);
    server = endpointServerBuilder.setFlushInterval(200).setTimeoutSeconds(20).setPort(port).build();
    server.initServices(new MockService());
    server.startServerAndWait();
    Sys.sleep(200);
    clientProxy = client.createProxy(ClientServiceInterface.class, "mockService");
    client.start();
    httpClient.startClient();
    callCount = 0;
    pongValue.set(null);
    Sys.sleep(200);
}

32. LeaderRedirectTest#setUp()

Project: aurora
Source File: LeaderRedirectTest.java
View license
@Before
public void setUp() throws MonitorException {
    schedulers = new AtomicReference<>(ImmutableSet.of());
    serviceGroupMonitor = createMock(ServiceGroupMonitor.class);
    HttpService http = createMock(HttpService.class);
    expect(http.getAddress()).andStubReturn(HostAndPort.fromParts("localhost", HTTP_PORT));
    leaderRedirector = new LeaderRedirect(http, serviceGroupMonitor);
}

33. GremlinDriverIntegrateTest#shouldAvoidDeadlockOnCallToResultSetDotAll()

View license
@Test
public void shouldAvoidDeadlockOnCallToResultSetDotAll() throws Exception {
    // This test arose from this issue: https://github.org/apache/tinkerpop/tinkerpop3/issues/515
    //
    // ResultSet.all returns a CompletableFuture that blocks on the worker pool until isExhausted returns false.
    // isExhausted in turn needs a thread on the worker pool to even return. So its totally possible to consume all
    // threads on the worker pool waiting for .all to finish such that you can't even get one to wait for
    // isExhausted to run.
    //
    // Note that all() doesn't work as described above anymore.  It waits for callback on readComplete rather
    // than blocking on isExhausted.
    final int workerPoolSizeForDriver = 2;
    // the number of requests 4 times the size of the worker pool as this originally did produce the problem
    // described above in the javadoc of the test (though an equivalent number also produced it), but this has
    // been tested to much higher multiples and passes.  note that the maxWaitForConnection setting is high so
    // that the client doesn't timeout waiting for an available connection. obviously this can also be fixed
    // by increasing the maxConnectionPoolSize.
    final int requests = workerPoolSizeForDriver * 4;
    final Cluster cluster = Cluster.build().workerPoolSize(workerPoolSizeForDriver).maxWaitForConnection(300000).create();
    final Client client = cluster.connect();
    final CountDownLatch latch = new CountDownLatch(requests);
    final AtomicReference[] refs = new AtomicReference[requests];
    IntStream.range(0, requests).forEach( ix -> {
        refs[ix] = new AtomicReference();
        client.submitAsync("Thread.sleep(5000);[1,2,3,4,5,6,7,8,9]").thenAccept( rs -> rs.all().thenAccept(refs[ix]::set).thenRun(latch::countDown));
    });
    // countdown should have reached zero as results should have eventually been all returned and processed
    assertTrue(latch.await(20, TimeUnit.SECONDS));
    final List<Integer> expected = IntStream.range(1, 10).boxed().collect(Collectors.toList());
    IntStream.range(0, requests).forEach( r -> assertTrue(expected.containsAll(((List<Result>) refs[r].get()).stream().map( resultItem -> new Integer(resultItem.getInt())).collect(Collectors.toList()))));
}

34. VertxEventBusBridgeTest#setup()

Project: qbit
Source File: VertxEventBusBridgeTest.java
View license
@Before
public void setup() {
    /* test service */
    testService = new TestService();
    /* service bundle builder */
    serviceBundleBuilder = serviceBundleBuilder();
    /* service bundle */
    serviceBundle = serviceBundleBuilder.build();
    serviceBundle.addServiceObject("service", testService);
    /* vertx event bus bridge to qbit. */
    vertxEventBusBridgeBuilder = VertxEventBusBridgeBuilder.vertxEventBusBridgeBuilder();
    vertxEventBusBridgeBuilder.addBridgeAddress(address, TestService.class);
    vertxEventBusBridgeBuilder.setServiceBundle(serviceBundle);
    //startall not supported yet for bridge.
    serviceBundle.start();
    vertxEventBusBridgeBuilder.build();
    /* latch so we can test results coming back from bridge. */
    countDownLatch = new CountDownLatch(1);
    /* grab vertx from the bridge. */
    vertx = vertxEventBusBridgeBuilder.getVertx();
    ref = new AtomicReference<>();
}

35. BaseTest#closedFireTest()

Project: wasync
Source File: BaseTest.java
View license
@Test
public void closedFireTest() throws Exception {
    Config config = new Config.Builder().port(port).host("127.0.0.1").resource("/suspend", new AtmosphereHandler() {

        @Override
        public void onRequest(AtmosphereResource r) throws IOException {
        }

        @Override
        public void onStateChange(AtmosphereResourceEvent r) throws IOException {
        }

        @Override
        public void destroy() {
        }
    }).build();
    server = new Nettosphere.Builder().config(config).build();
    assertNotNull(server);
    server.start();
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch ioLatch = new CountDownLatch(1);
    final AtomicInteger status = new AtomicInteger();
    final AtomicReference response2 = new AtomicReference();
    Client client = ClientFactory.getDefault().newClient();
    RequestBuilder request = client.newRequestBuilder().method(Request.METHOD.GET).uri(targetUrl + "/suspend").transport(transport());
    final Socket socket = client.create(client.newOptionsBuilder().runtime(ahc, false).build());
    socket.on(new Function<Integer>() {

        @Override
        public void on(Integer statusCode) {
            status.set(statusCode);
            socket.close();
            latch.countDown();
        }
    }).on(new Function<IOException>() {

        @Override
        public void on(IOException t) {
            response2.set(t);
            ioLatch.countDown();
        }
    }).open(request.build());
    latch.await(5, TimeUnit.SECONDS);
    socket.fire("Yo");
    ioLatch.await(5, TimeUnit.SECONDS);
    assertNotNull(response2.get());
    assertEquals(response2.get().getClass(), IOException.class);
}

36. BaseTest#shutdownServerTest()

Project: wasync
Source File: BaseTest.java
View license
@Test
public void shutdownServerTest() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    Config config = new Config.Builder().port(port).host("127.0.0.1").resource("/suspend", new AtmosphereHandler() {

        private final AtomicBoolean b = new AtomicBoolean(false);

        @Override
        public void onRequest(AtmosphereResource r) throws IOException {
            if (!b.getAndSet(true)) {
                r.suspend(-1);
            } else {
                r.getBroadcaster().broadcast(RESUME);
            }
        }

        @Override
        public void onStateChange(AtmosphereResourceEvent r) throws IOException {
            if (!r.isResuming() || !r.isCancelled()) {
                latch.countDown();
                r.getResource().getResponse().getWriter().print(r.getMessage());
                r.getResource().resume();
            }
        }

        @Override
        public void destroy() {
        }
    }).build();
    server = new Nettosphere.Builder().config(config).build();
    assertNotNull(server);
    server.start();
    final AtomicReference response = new AtomicReference();
    Client client = ClientFactory.getDefault().newClient();
    RequestBuilder request = client.newRequestBuilder().method(Request.METHOD.GET).uri(targetUrl + "/suspend").transport(transport());
    Socket socket = client.create(client.newOptionsBuilder().reconnect(false).build());
    socket.on(Event.CLOSE, new Function<String>() {

        @Override
        public void on(String t) {
            //Can I receive close message when server is stopped?
            logger.info("Function invoked {}", t);
            response.set(t);
        }
    }).on(new Function<Throwable>() {

        @Override
        public void on(Throwable t) {
            logger.error("", t);
            latch.countDown();
        }
    }).open(request.build()).fire("PING");
    latch.await(5, TimeUnit.SECONDS);
    server.stop();
    socket.close();
    //or ERROR?
    assertEquals(socket.status(), Socket.STATUS.CLOSE);
}

37. FilesetEntryFunctionTest#setUp()

Project: bazel
Source File: FilesetEntryFunctionTest.java
View license
@Before
public final void setUp() throws Exception {
    pkgLocator = new AtomicReference<>(new PathPackageLocator(outputBase, ImmutableList.of(rootDirectory)));
    AtomicReference<ImmutableSet<PackageIdentifier>> deletedPackages = new AtomicReference<>(ImmutableSet.<PackageIdentifier>of());
    ExternalFilesHelper externalFilesHelper = new ExternalFilesHelper(pkgLocator, false, new BlazeDirectories(outputBase, outputBase, rootDirectory, TestConstants.PRODUCT_NAME));
    Map<SkyFunctionName, SkyFunction> skyFunctions = new HashMap<>();
    skyFunctions.put(SkyFunctions.FILE_STATE, new FileStateFunction(new AtomicReference<TimestampGranularityMonitor>(), externalFilesHelper));
    skyFunctions.put(SkyFunctions.FILE, new FileFunction(pkgLocator));
    skyFunctions.put(SkyFunctions.DIRECTORY_LISTING, new DirectoryListingFunction());
    skyFunctions.put(SkyFunctions.DIRECTORY_LISTING_STATE, new DirectoryListingStateFunction(externalFilesHelper));
    skyFunctions.put(SkyFunctions.RECURSIVE_FILESYSTEM_TRAVERSAL, new RecursiveFilesystemTraversalFunction());
    skyFunctions.put(SkyFunctions.PACKAGE_LOOKUP, new PackageLookupFunction(deletedPackages));
    skyFunctions.put(SkyFunctions.BLACKLISTED_PACKAGE_PREFIXES, new BlacklistedPackagePrefixesFunction());
    skyFunctions.put(SkyFunctions.FILESET_ENTRY, new FilesetEntryFunction());
    differencer = new RecordingDifferencer();
    evaluator = new InMemoryMemoizingEvaluator(skyFunctions, differencer);
    driver = new SequentialBuildDriver(evaluator);
    PrecomputedValue.BUILD_ID.set(differencer, UUID.randomUUID());
    PrecomputedValue.PATH_PACKAGE_LOCATOR.set(differencer, pkgLocator.get());
    PrecomputedValue.BLACKLISTED_PACKAGE_PREFIXES_FILE.set(differencer, PathFragment.EMPTY_FRAGMENT);
}

38. PendingTaskBasedResourceManagementStrategyTest#setUp()

View license
@Before
public void setUp() throws Exception {
    autoScaler = EasyMock.createMock(AutoScaler.class);
    testTask = TestTasks.immediateSuccess("task1");
    config = new PendingTaskBasedWorkerResourceManagementConfig().setMaxScalingDuration(new Period(1000)).setNumEventsToTrack(10).setPendingTaskTimeout(new Period(0)).setWorkerVersion(MIN_VERSION).setMaxScalingStep(2);
    workerConfig = new AtomicReference<>(new WorkerBehaviorConfig(new FillCapacityWorkerSelectStrategy(), autoScaler));
    strategy = new PendingTaskBasedWorkerResourceManagementStrategy(config, DSuppliers.of(workerConfig), new ResourceManagementSchedulerConfig(), executorService);
}

39. RecursiveFilesystemTraversalFunctionTest#setUp()

View license
@Before
public final void setUp() throws Exception {
    pkgLocator = new AtomicReference<>(new PathPackageLocator(outputBase, ImmutableList.of(rootDirectory)));
    AtomicReference<ImmutableSet<PackageIdentifier>> deletedPackages = new AtomicReference<>(ImmutableSet.<PackageIdentifier>of());
    BlazeDirectories directories = new BlazeDirectories(rootDirectory, outputBase, rootDirectory, TestConstants.PRODUCT_NAME);
    ExternalFilesHelper externalFilesHelper = new ExternalFilesHelper(pkgLocator, false, directories);
    Map<SkyFunctionName, SkyFunction> skyFunctions = new HashMap<>();
    skyFunctions.put(SkyFunctions.FILE_STATE, new FileStateFunction(new AtomicReference<TimestampGranularityMonitor>(), externalFilesHelper));
    skyFunctions.put(SkyFunctions.FILE, new FileFunction(pkgLocator));
    skyFunctions.put(SkyFunctions.DIRECTORY_LISTING, new DirectoryListingFunction());
    skyFunctions.put(SkyFunctions.DIRECTORY_LISTING_STATE, new DirectoryListingStateFunction(externalFilesHelper));
    skyFunctions.put(SkyFunctions.RECURSIVE_FILESYSTEM_TRAVERSAL, new RecursiveFilesystemTraversalFunction());
    skyFunctions.put(SkyFunctions.PACKAGE_LOOKUP, new PackageLookupFunction(deletedPackages));
    skyFunctions.put(SkyFunctions.BLACKLISTED_PACKAGE_PREFIXES, new BlacklistedPackagePrefixesFunction());
    skyFunctions.put(SkyFunctions.PACKAGE, new PackageFunction(null, null, null, null, null, null, null));
    skyFunctions.put(SkyFunctions.PACKAGE_LOOKUP, new PackageLookupFunction(deletedPackages));
    skyFunctions.put(SkyFunctions.WORKSPACE_AST, new WorkspaceASTFunction(TestRuleClassProvider.getRuleClassProvider()));
    skyFunctions.put(SkyFunctions.WORKSPACE_FILE, new WorkspaceFileFunction(TestRuleClassProvider.getRuleClassProvider(), TestConstants.PACKAGE_FACTORY_FACTORY_FOR_TESTING.create(TestRuleClassProvider.getRuleClassProvider(), scratch.getFileSystem()), directories));
    skyFunctions.put(SkyFunctions.EXTERNAL_PACKAGE, new ExternalPackageFunction());
    progressReceiver = new RecordingEvaluationProgressReceiver();
    differencer = new RecordingDifferencer();
    evaluator = new InMemoryMemoizingEvaluator(skyFunctions, differencer, progressReceiver);
    driver = new SequentialBuildDriver(evaluator);
    PrecomputedValue.BUILD_ID.set(differencer, UUID.randomUUID());
    PrecomputedValue.PATH_PACKAGE_LOCATOR.set(differencer, pkgLocator.get());
    PrecomputedValue.BLACKLISTED_PACKAGE_PREFIXES_FILE.set(differencer, PathFragment.EMPTY_FRAGMENT);
}

40. AtomicReferenceTest#testGetAndSet()

Project: openjdk
Source File: AtomicReferenceTest.java
View license
/**
     * getAndSet returns previous value and sets to given value
     */
public void testGetAndSet() {
    AtomicReference ai = new AtomicReference(one);
    assertSame(one, ai.getAndSet(zero));
    assertSame(zero, ai.getAndSet(m10));
    assertSame(m10, ai.getAndSet(one));
}

41. AtomicReferenceTest#testWeakCompareAndSet()

Project: openjdk
Source File: AtomicReferenceTest.java
View license
/**
     * repeated weakCompareAndSet succeeds in changing value when equal
     * to expected
     */
public void testWeakCompareAndSet() {
    AtomicReference ai = new AtomicReference(one);
    do {
    } while (!ai.weakCompareAndSet(one, two));
    do {
    } while (!ai.weakCompareAndSet(two, m4));
    assertSame(m4, ai.get());
    do {
    } while (!ai.weakCompareAndSet(m4, seven));
    assertSame(seven, ai.get());
}

42. PartitionedFileSetDataset#filterInputPaths()

Project: cdap
Source File: PartitionedFileSetDataset.java
View license
/**
   * Computes the input paths given by the partition filter - if present. Stores the result in a cache and returns it.
   */
private Collection<String> filterInputPaths() {
    if (inputPathsCache != null) {
        return inputPathsCache.get();
    }
    Collection<String> inputPaths = computeFilterInputPaths();
    inputPathsCache = new AtomicReference<>(inputPaths);
    return inputPaths;
}

43. AtomicReferenceTest#testCompareAndSet()

Project: openjdk
Source File: AtomicReferenceTest.java
View license
/**
     * compareAndSet succeeds in changing value if equal to expected else fails
     */
public void testCompareAndSet() {
    AtomicReference ai = new AtomicReference(one);
    assertTrue(ai.compareAndSet(one, two));
    assertTrue(ai.compareAndSet(two, m4));
    assertSame(m4, ai.get());
    assertFalse(ai.compareAndSet(m5, seven));
    assertSame(m4, ai.get());
    assertTrue(ai.compareAndSet(m4, seven));
    assertSame(seven, ai.get());
}

44. MetaFieldUtilTest#setPerson()

View license
public void setPerson(Person p) {
    person = new AtomicReference<Person>(p);
}

45. AtomicReferenceTest#testConstructor2()

Project: openjdk
Source File: AtomicReferenceTest.java
View license
/**
     * default constructed initializes to null
     */
public void testConstructor2() {
    AtomicReference ai = new AtomicReference();
    assertNull(ai.get());
}

46. AtomicReferenceTest#testConstructor()

Project: openjdk
Source File: AtomicReferenceTest.java
View license
/**
     * constructor initializes to given value
     */
public void testConstructor() {
    AtomicReference ai = new AtomicReference(one);
    assertSame(one, ai.get());
}

47. VisitorSteps#whenTheCompilationUnitIsVisitedByTheVariableNameCollectorVisitor()

Project: javaparser
Source File: VisitorSteps.java
View license
@When("the CompilationUnit is visited by the variable name collector visitor")
public void whenTheCompilationUnitIsVisitedByTheVariableNameCollectorVisitor() {
    CompilationUnit compilationUnit = (CompilationUnit) state.get("cu1");
    collectedVariableName = new AtomicReference<>("");
    collectVariableNameVisitor.visit(compilationUnit, collectedVariableName);
}

48. TcpDiscoveryRestartTest#testRestart()

Project: ignite
Source File: TcpDiscoveryRestartTest.java
View license
/**
     * @throws Exception If failed.
     */
public void testRestart() throws Exception {
    err = new AtomicReference<>();
    final int NODE_CNT = 3;
    startGrids(NODE_CNT);
    final ConcurrentHashSet<UUID> nodeIds = new ConcurrentHashSet<>();
    final AtomicInteger id = new AtomicInteger(NODE_CNT);
    final IgniteInternalFuture<?> fut = GridTestUtils.runMultiThreadedAsync(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            int nodeIdx = id.getAndIncrement();
            for (int i = 0; i < 10 && err.get() == null; i++) {
                Ignite ignite = startGrid(nodeIdx);
                UUID nodeId = ignite.cluster().localNode().id();
                if (!nodeIds.add(nodeId))
                    failed("Duplicated node ID: " + nodeId);
                stopGrid(nodeIdx);
            }
            return null;
        }
    }, 5, "restart-thread");
    IgniteInternalFuture<?> loadFut = GridTestUtils.runMultiThreadedAsync(new Callable<Long>() {

        @Override
        public Long call() throws Exception {
            long dummyRes = 0;
            List<String> list = new ArrayList<>();
            while (!fut.isDone()) {
                for (int i = 0; i < 100; i++) {
                    String str = new String(new byte[i]);
                    list.add(str);
                    dummyRes += str.hashCode();
                }
                if (list.size() > 1000_000) {
                    list = new ArrayList<>();
                    System.gc();
                }
            }
            return dummyRes;
        }
    }, 2, "test-load");
    fut.get();
    loadFut.get();
    assertNull(err.get());
    for (int i = 0; i < NODE_CNT; i++) {
        Ignite ignite = ignite(i);
        TestEventListener lsnr = (TestEventListener) F.firstKey(ignite.configuration().getLocalEventListeners());
        assertNotNull(lsnr);
        for (UUID nodeId : nodeIds) lsnr.checkEvents(nodeId);
    }
}

49. GenericServiceTest#testGenericImplementationWithBeanSerialization()

Project: dubbo
Source File: GenericServiceTest.java
View license
@Test
public void testGenericImplementationWithBeanSerialization() throws Exception {
    final AtomicReference reference = new AtomicReference();
    ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
    service.setApplication(new ApplicationConfig("bean-provider"));
    service.setRegistry(new RegistryConfig("N/A"));
    service.setProtocol(new ProtocolConfig("dubbo", 29581));
    service.setInterface(DemoService.class.getName());
    service.setRef(new GenericService() {

        public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
            if ("getUsers".equals(method)) {
                GenericParameter arg = new GenericParameter();
                arg.method = method;
                arg.parameterTypes = parameterTypes;
                arg.arguments = args;
                reference.set(arg);
                return args[0];
            }
            if ("sayName".equals(method)) {
                return null;
            }
            return args;
        }
    });
    service.export();
    ReferenceConfig<DemoService> ref = null;
    try {
        ref = new ReferenceConfig<DemoService>();
        ref.setApplication(new ApplicationConfig("bean-consumer"));
        ref.setInterface(DemoService.class);
        ref.setUrl("dubbo://127.0.0.1:29581?scope=remote&generic=bean");
        DemoService demoService = ref.get();
        User user = new User();
        user.setName("zhangsan");
        List<User> users = new ArrayList<User>();
        users.add(user);
        List<User> result = demoService.getUsers(users);
        Assert.assertEquals(users.size(), result.size());
        Assert.assertEquals(user.getName(), result.get(0).getName());
        GenericParameter gp = (GenericParameter) reference.get();
        Assert.assertEquals("getUsers", gp.method);
        Assert.assertEquals(1, gp.parameterTypes.length);
        Assert.assertEquals(ReflectUtils.getName(List.class), gp.parameterTypes[0]);
        Assert.assertEquals(1, gp.arguments.length);
        Assert.assertTrue(gp.arguments[0] instanceof JavaBeanDescriptor);
        JavaBeanDescriptor descriptor = (JavaBeanDescriptor) gp.arguments[0];
        Assert.assertTrue(descriptor.isCollectionType());
        Assert.assertEquals(ArrayList.class.getName(), descriptor.getClassName());
        Assert.assertEquals(1, descriptor.propertySize());
        descriptor = (JavaBeanDescriptor) descriptor.getProperty(0);
        Assert.assertTrue(descriptor.isBeanType());
        Assert.assertEquals(User.class.getName(), descriptor.getClassName());
        Assert.assertEquals(user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty());
        Assert.assertNull(demoService.sayName("zhangsan"));
    } finally {
        if (ref != null) {
            ref.destroy();
        }
        service.unexport();
    }
}

50. SimpleResourceManagementStrategyTest#setUp()

View license
@Before
public void setUp() throws Exception {
    autoScaler = EasyMock.createMock(AutoScaler.class);
    testTask = TestTasks.immediateSuccess("task1");
    final SimpleWorkerResourceManagementConfig simpleWorkerResourceManagementConfig = new SimpleWorkerResourceManagementConfig().setWorkerIdleTimeout(new Period(0)).setMaxScalingDuration(new Period(1000)).setNumEventsToTrack(1).setPendingTaskTimeout(new Period(0)).setWorkerVersion("");
    final ResourceManagementSchedulerConfig schedulerConfig = new ResourceManagementSchedulerConfig();
    workerConfig = new AtomicReference<>(new WorkerBehaviorConfig(null, autoScaler));
    simpleResourceManagementStrategy = new SimpleWorkerResourceManagementStrategy(simpleWorkerResourceManagementConfig, DSuppliers.of(workerConfig), schedulerConfig, executorService);
}