Java Code Examples for java.util.concurrent.atomic.AtomicReference

The following are top voted examples for showing how to use java.util.concurrent.atomic.AtomicReference. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: GitHub   File: MaybeThrowingTest.java   Source Code and License 7 votes vote down vote up
@Test public void resultThrowingInOnSuccessDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!throwableRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable);
      }
    }
  });

  RecordingMaybeObserver<Result<String>> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.result().subscribe(new ForwardingObserver<Result<String>>(observer) {
    @Override public void onSuccess(Result<String> value) {
      throw e;
    }
  });

  assertThat(throwableRef.get()).isSameAs(e);
}
 
Example 2
Project: incubator-netbeans   File: ClassPathProviderImpl.java   Source Code and License 6 votes vote down vote up
FilteredClassPathImplementation(
    @NonNull final ClassPathImplementation delegate,
    @NonNull final AntProjectHelper helper,
    @NonNull final PropertyEvaluator eval,
    @NonNull final String filteredProp) {
    Parameters.notNull("delegate", delegate);   //NOI18N
    Parameters.notNull("helper", helper);       //NOI18N
    Parameters.notNull("eval", eval);   //NOI18N
    Parameters.notNull("filteredProp", filteredProp);   //NOI18N
    this.delegate = delegate;
    this.helper = helper;
    this.eval = eval;
    this.filteredProp = filteredProp;
    this.cache = new AtomicReference<List<PathResourceImplementation>>();
    this.listeners = new PropertyChangeSupport(this);
    this.delegate.addPropertyChangeListener(WeakListeners.propertyChange(this, this.delegate));
    this.eval.addPropertyChangeListener(WeakListeners.propertyChange(this, this.eval));
}
 
Example 3
Project: RxJava3-preview   File: ObservableSingleTest.java   Source Code and License 6 votes vote down vote up
@Test
public void singleElementOperatorDoNotSwallowExceptionWhenDone() {
    final Throwable exception = new RuntimeException("some error");
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

    try {
        RxJavaCommonPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override public void accept(final Throwable throwable) throws Exception {
                error.set(throwable);
            }
        });

        Observable.unsafeCreate(new ObservableSource<Integer>() {
            @Override public void subscribe(final Observer<? super Integer> observer) {
                observer.onComplete();
                observer.onError(exception);
            }
        }).singleElement().test().assertComplete();

        assertSame(exception, error.get().getCause());
    } finally {
        RxJavaCommonPlugins.reset();
    }
}
 
Example 4
Project: GitHub   File: ObservableThrowingTest.java   Source Code and License 6 votes vote down vote up
@Test public void responseThrowingInOnCompleteDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> pluginRef = new AtomicReference<>();
  RxJavaPlugins.getInstance().registerErrorHandler(new RxJavaErrorHandler() {
    @Override public void handleError(Throwable throwable) {
      if (!pluginRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable); // Don't swallow secondary errors!
      }
    }
  });

  RecordingSubscriber<Response<String>> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.response().unsafeSubscribe(new ForwardingSubscriber<Response<String>>(observer) {
    @Override public void onCompleted() {
      throw e;
    }
  });

  observer.assertAnyValue();
  assertThat(pluginRef.get()).isSameAs(e);
}
 
Example 5
Project: incubator-netbeans   File: ProvidedExtensionsProxy.java   Source Code and License 6 votes vote down vote up
@Override
public Object getAttribute(final File file, final String attrName) {
    final AtomicReference<Object> value = new AtomicReference();
    for (BaseAnnotationProvider provider : annotationProviders) {
        final InterceptionListener iListener = (provider != null) ? provider.getInterceptionListener() : null;
        if (iListener instanceof ProvidedExtensions) {
            runCheckCode(new Runnable() {
                public void run() {
                    value.set(((ProvidedExtensions) iListener).getAttribute(file, attrName));
                }
            });
        }
        if (value.get() != null) {
           return value.get();
        }
    }
    return null;
}
 
Example 6
Project: jdk8u-jdk   File: Phaser.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new phaser with the given parent and number of
 * registered unarrived parties.  When the given parent is non-null
 * and the given number of parties is greater than zero, this
 * child phaser is registered with its parent.
 *
 * @param parent the parent phaser
 * @param parties the number of parties required to advance to the
 * next phase
 * @throws IllegalArgumentException if parties less than zero
 * or greater than the maximum number of parties supported
 */
public Phaser(Phaser parent, int parties) {
    if (parties >>> PARTIES_SHIFT != 0)
        throw new IllegalArgumentException("Illegal number of parties");
    int phase = 0;
    this.parent = parent;
    if (parent != null) {
        final Phaser root = parent.root;
        this.root = root;
        this.evenQ = root.evenQ;
        this.oddQ = root.oddQ;
        if (parties != 0)
            phase = parent.doRegister(1);
    }
    else {
        this.root = this;
        this.evenQ = new AtomicReference<QNode>();
        this.oddQ = new AtomicReference<QNode>();
    }
    this.state = (parties == 0) ? (long)EMPTY :
        ((long)phase << PHASE_SHIFT) |
        ((long)parties << PARTIES_SHIFT) |
        ((long)parties);
}
 
Example 7
Project: NiuBi   File: HttpRequestTest.java   Source Code and License 6 votes vote down vote up
/**
 * Make a GET request with an empty body response
 *
 * @throws Exception
 */
@Test
public void getUrlEmpty() throws Exception {
  final AtomicReference<String> method = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      method.set(request.getMethod());
      response.setStatus(HTTP_OK);
    }
  };
  HttpRequest request = get(new URL(url));
  assertNotNull(request.getConnection());
  int code = request.code();
  assertTrue(request.ok());
  assertFalse(request.created());
  assertFalse(request.noContent());
  assertFalse(request.badRequest());
  assertFalse(request.serverError());
  assertFalse(request.notFound());
  assertEquals("GET", method.get());
  assertEquals("OK", request.message());
  assertEquals(HTTP_OK, code);
  assertEquals("", request.body());
}
 
Example 8
Project: openjdk-jdk10   File: Phaser.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new phaser with the given parent and number of
 * registered unarrived parties.  When the given parent is non-null
 * and the given number of parties is greater than zero, this
 * child phaser is registered with its parent.
 *
 * @param parent the parent phaser
 * @param parties the number of parties required to advance to the
 * next phase
 * @throws IllegalArgumentException if parties less than zero
 * or greater than the maximum number of parties supported
 */
public Phaser(Phaser parent, int parties) {
    if (parties >>> PARTIES_SHIFT != 0)
        throw new IllegalArgumentException("Illegal number of parties");
    int phase = 0;
    this.parent = parent;
    if (parent != null) {
        final Phaser root = parent.root;
        this.root = root;
        this.evenQ = root.evenQ;
        this.oddQ = root.oddQ;
        if (parties != 0)
            phase = parent.doRegister(1);
    }
    else {
        this.root = this;
        this.evenQ = new AtomicReference<QNode>();
        this.oddQ = new AtomicReference<QNode>();
    }
    this.state = (parties == 0) ? (long)EMPTY :
        ((long)phase << PHASE_SHIFT) |
        ((long)parties << PARTIES_SHIFT) |
        ((long)parties);
}
 
Example 9
Project: boohee_v5.6   File: BlockingObservable.java   Source Code and License 6 votes vote down vote up
public void forEach(final Action1<? super T> onNext) {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> exceptionFromOnError = new AtomicReference();
    BlockingUtils.awaitForComplete(latch, this.o.subscribe(new Subscriber<T>() {
        public void onCompleted() {
            latch.countDown();
        }

        public void onError(Throwable e) {
            exceptionFromOnError.set(e);
            latch.countDown();
        }

        public void onNext(T args) {
            onNext.call(args);
        }
    }));
    if (exceptionFromOnError.get() == null) {
        return;
    }
    if (exceptionFromOnError.get() instanceof RuntimeException) {
        throw ((RuntimeException) exceptionFromOnError.get());
    }
    throw new RuntimeException((Throwable) exceptionFromOnError.get());
}
 
Example 10
Project: n4js   File: ExternalProject.java   Source Code and License 6 votes vote down vote up
private <T extends IResource> T getResource(String name, Class<T> resourceClass) {
	final File fileCandidate = getFullPath().append(name).toFile();
	final AtomicReference<T> actualRef = new AtomicReference<>();
	if (fileCandidate.exists()) {
		acceptUnsafe(resource -> {
			if (resource instanceof IExternalResource && resourceClass.isAssignableFrom(resource.getClass())) {
				if (fileCandidate.equals(((IExternalResource) resource).getExternalResource())) {
					actualRef.set(resourceClass.cast(resource));
					return false;
				}
			}
			return true;
		});
	}

	return actualRef.get(); // TODO return with missing instance?
}
 
Example 11
Project: GitHub   File: SingleThrowingTest.java   Source Code and License 6 votes vote down vote up
@Test public void resultThrowingInOnSuccessDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!throwableRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable);
      }
    }
  });

  RecordingSingleObserver<Result<String>> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.result().subscribe(new ForwardingObserver<Result<String>>(observer) {
    @Override public void onSuccess(Result<String> value) {
      throw e;
    }
  });

  assertThat(throwableRef.get()).isSameAs(e);
}
 
Example 12
Project: NiuBi   File: HttpRequestTest.java   Source Code and License 6 votes vote down vote up
/**
 * Verify POST with numeric query parameters
 *
 * @throws Exception
 */
@Test
public void postWithNumericQueryParams() throws Exception {
  Map<Object, Object> inputParams = new HashMap<Object, Object>();
  inputParams.put(1, 2);
  inputParams.put(3, 4);
  final Map<String, String> outputParams = new HashMap<String, String>();
  final AtomicReference<String> method = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      method.set(request.getMethod());
      outputParams.put("1", request.getParameter("1"));
      outputParams.put("3", request.getParameter("3"));
      response.setStatus(HTTP_OK);
    }
  };
  HttpRequest request = post(url, inputParams, false);
  assertTrue(request.ok());
  assertEquals("POST", method.get());
  assertEquals("2", outputParams.get("1"));
  assertEquals("4", outputParams.get("3"));
}
 
Example 13
Project: validator-web   File: AbstractJackson2HttpMessageReader.java   Source Code and License 6 votes vote down vote up
@Override
protected boolean supports(Class<?> clazz) {
    JavaType javaType = getJavaType(clazz);
    AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
    if (this.objectMapper.canDeserialize(javaType, causeRef)) {
        return true;
    }
    Throwable cause = causeRef.get();
    if (cause != null) {
        String msg = "Failed to evaluate deserialization for type " + javaType;
        if (logger.isDebugEnabled()) {
            logger.warn(msg, cause);
        }
        else {
            logger.warn(msg + ": " + cause);
        }
    }
    return false;
}
 
Example 14
Project: teamcity-hashicorp-vault-plugin   File: AbstractJackson2HttpMessageConverter.java   Source Code and License 6 votes vote down vote up
@Override
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
	if (!canRead(mediaType)) {
		return false;
	}
	JavaType javaType = getJavaType(type, contextClass);
	if (!jackson23Available || !logger.isWarnEnabled()) {
		return this.objectMapper.canDeserialize(javaType);
	}
	AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
	if (this.objectMapper.canDeserialize(javaType, causeRef)) {
		return true;
	}
	Throwable cause = causeRef.get();
	if (cause != null) {
		String msg = "Failed to evaluate Jackson deserialization for type " + javaType;
		if (logger.isDebugEnabled()) {
			logger.warn(msg, cause);
		}
		else {
			logger.warn(msg + ": " + cause);
		}
	}
	return false;
}
 
Example 15
Project: GitHub   File: CacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void networkInterceptorInvokedForConditionalGet() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("ETag: v1")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));

  // Seed the cache.
  HttpUrl url = server.url("/");
  assertEquals("A", get(url).body().string());

  final AtomicReference<String> ifNoneMatch = new AtomicReference<>();
  client = client.newBuilder()
      .addNetworkInterceptor(new Interceptor() {
        @Override public Response intercept(Chain chain) throws IOException {
          ifNoneMatch.compareAndSet(null, chain.request().header("If-None-Match"));
          return chain.proceed(chain.request());
        }
      }).build();

  // Confirm the value is cached and intercepted.
  assertEquals("A", get(url).body().string());
  assertEquals("v1", ifNoneMatch.get());
}
 
Example 16
Project: RxJava3-preview   File: FlowableSingleTest.java   Source Code and License 6 votes vote down vote up
@Test
public void singleElementOperatorDoNotSwallowExceptionWhenDone() {
    final Throwable exception = new RuntimeException("some error");
    final AtomicReference<Throwable> error = new AtomicReference<Throwable>();

    try {
        RxJavaCommonPlugins.setErrorHandler(new Consumer<Throwable>() {
            @Override public void accept(final Throwable throwable) throws Exception {
                error.set(throwable);
            }
        });

        singleElement(Flowable.unsafeCreate(new Publisher<Integer>() {
            @Override public void subscribe(final Subscriber<? super Integer> observer) {
                observer.onComplete();
                observer.onError(exception);
            }
        })).test().assertComplete();

        assertSame(exception, error.get().getCause());
    } finally {
        RxJavaCommonPlugins.reset();
    }
}
 
Example 17
Project: dataflow   File: PriorityTaskQueueTest.java   Source Code and License 6 votes vote down vote up
@Test
public void korrelasjonsIdIsPreserved() {
    final int parallelTasks = 10;

    String korrelatjonsId = "TEST123";
    ThreadLocal<String> korrelasjonsId = new ThreadLocal<>();
    korrelasjonsId.set(korrelatjonsId);
    PriorityTaskQueue pq = new PriorityTaskQueue(parallelTasks, korrelasjonsId::get, korrelasjonsId::set);

    AtomicReference<String> capcturedKorrelatjonsId = new AtomicReference<>();
    pq.addTask(1, q -> capcturedKorrelatjonsId.set(korrelasjonsId.get()));

    ExecutorService executorService = Executors.newCachedThreadPool();
    Queue<Exception> exceptions = new LinkedList<>();
    assertThat(
        pq.executeTasksAndAwaitDone(executorService, exceptions::offer, 1, TimeUnit.SECONDS),
        is(true));
    assertThat(exceptions.size(), is(0));
    assertThat(capcturedKorrelatjonsId.get(), is(korrelatjonsId));
    executorService.shutdown();

}
 
Example 18
Project: reactive-grpc   File: ReactiveStreamObserverPublisherTest.java   Source Code and License 6 votes vote down vote up
@Test
public void requestDelegates() {
    CallStreamObserver<Object> obs = mock(CallStreamObserver.class);
    Subscriber<Object> sub = mock(Subscriber.class);

    final AtomicReference<Subscription> subscription = new AtomicReference<Subscription>();
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) {
            subscription.set((Subscription) invocationOnMock.getArguments()[0]);
            return null;
        }
    }).when(sub).onSubscribe(any(Subscription.class));

    ReactiveStreamObserverPublisher<Object> pub = new ReactiveStreamObserverPublisher<Object>(obs);
    pub.subscribe(sub);

    assertThat(subscription.get()).isNotNull();
    subscription.get().request(10);
    verify(obs).request(10);
}
 
Example 19
Project: elasticsearch_my   File: HeapBufferedAsyncResponseConsumerTests.java   Source Code and License 6 votes vote down vote up
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception {
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK");
    consumer.onResponseReceived(new BasicHttpResponse(statusLine));

    final AtomicReference<Long> contentLength = new AtomicReference<>();
    HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) {
        @Override
        public long getContentLength() {
            return contentLength.get();
        }
    };
    contentLength.set(randomLong(bufferLimit));
    consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);

    contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE));
    try {
        consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON);
    } catch(ContentTooLongException e) {
        assertEquals("entity content is too long [" + entity.getContentLength() +
                "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage());
    }
}
 
Example 20
Project: NiuBi   File: HttpRequestTest.java   Source Code and License 6 votes vote down vote up
/**
 * Make a DELETE request with an empty body response
 *
 * @throws Exception
 */
@Test
public void deleteEmpty() throws Exception {
  final AtomicReference<String> method = new AtomicReference<String>();
  handler = new RequestHandler() {

    @Override
    public void handle(Request request, HttpServletResponse response) {
      method.set(request.getMethod());
      response.setStatus(HTTP_OK);
    }
  };
  HttpRequest request = delete(url);
  assertNotNull(request.getConnection());
  assertTrue(request.ok());
  assertFalse(request.notFound());
  assertEquals("DELETE", method.get());
  assertEquals("", request.body());
  assertEquals("DELETE", request.method());
}
 
Example 21
Project: reactive-pg-client   File: PgPoolTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testReconnectQueued(TestContext ctx) {
  Async async = ctx.async();
  ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost());
  AtomicReference<ProxyServer.Connection> proxyConn = new AtomicReference<>();
  proxy.proxyHandler(conn -> {
    proxyConn.set(conn);
    conn.connect();
  });
  proxy.listen(8080, "localhost", ctx.asyncAssertSuccess(v1 -> {
    PgPool pool = createPool(new PgConnectOptions(options).setPort(8080).setHost("localhost"), 1);
    pool.getConnection(ctx.asyncAssertSuccess(conn -> {
      proxyConn.get().close();
    }));
    pool.getConnection(ctx.asyncAssertSuccess(conn -> {
      conn.query("SELECT id, randomnumber from WORLD", ctx.asyncAssertSuccess(v2 -> {
        async.complete();
      }));
    }));
  }));
}
 
Example 22
Project: aliyun-log-flink-connector   File: LogDataFetcher.java   Source Code and License 6 votes vote down vote up
public LogDataFetcher(SourceFunction.SourceContext<T> sourceContext,
                      RuntimeContext runtimeContext,
                      Properties configProps,
                      LogDeserializationSchema<T> deserializationSchema, LogClientProxy logClient) {
    this.sourceContext = sourceContext;
    this.runtimeContext = runtimeContext;
    this.configProps = configProps;
    this.deserializationSchema = deserializationSchema;
    this.totalNumberOfConsumerSubtasks = runtimeContext.getNumberOfParallelSubtasks();
    this.indexOfThisConsumerSubtask = runtimeContext.getIndexOfThisSubtask();
    this.checkpointLock = sourceContext.getCheckpointLock();
    this.subscribedShardsState = new LinkedList<LogstoreShardState>();
    this.shardConsumersExecutor = createShardConsumersThreadPool(runtimeContext.getTaskNameWithSubtasks());
    this.error = new AtomicReference<Throwable>();
    this.logProject = configProps.getProperty(ConfigConstants.LOG_PROJECT);
    this.logStore = configProps.getProperty(ConfigConstants.LOG_LOGSTORE);
    this.logClient = logClient;
}
 
Example 23
Project: GitHub   File: SingleThrowingTest.java   Source Code and License 6 votes vote down vote up
@Test public void resultThrowingInOnSuccessDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!throwableRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable);
      }
    }
  });

  RecordingSingleObserver<Result<String>> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.result().subscribe(new ForwardingObserver<Result<String>>(observer) {
    @Override public void onSuccess(Result<String> value) {
      throw e;
    }
  });

  assertThat(throwableRef.get()).isSameAs(e);
}
 
Example 24
Project: RxJava3-preview   File: ObservableErrorHandlingTests.java   Source Code and License 5 votes vote down vote up
/**
 * Test that an error from a user provided Observer.onNext is handled and emitted to the onError
 * @throws InterruptedException if the test is interrupted
 */
@Test
public void testOnNextError() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<Throwable> caughtError = new AtomicReference<Throwable>();
    Observable<Long> o = Observable.interval(50, TimeUnit.MILLISECONDS);
    Observer<Long> observer = new DefaultObserver<Long>() {

        @Override
        public void onComplete() {
            System.out.println("completed");
            latch.countDown();
        }

        @Override
        public void onError(Throwable e) {
            System.out.println("error: " + e);
            caughtError.set(e);
            latch.countDown();
        }

        @Override
        public void onNext(Long args) {
            throw new RuntimeException("forced failure");
        }
    };
    o.safeSubscribe(observer);

    latch.await(2000, TimeUnit.MILLISECONDS);
    assertNotNull(caughtError.get());
}
 
Example 25
Project: GitHub   File: GetStringApiTest.java   Source Code and License 5 votes vote down vote up
public void testResponseBodyGet() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("data"));

        final AtomicReference<String> responseRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.get(server.url("/").toString())
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponse(new OkHttpResponseListener() {
                    @Override
                    public void onResponse(Response response) {
                        try {
                            responseRef.set(response.body().string());
                            latch.countDown();
                        } catch (IOException e) {
                            assertTrue(false);
                        }
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

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

        assertEquals("data", responseRef.get());
    }
 
Example 26
Project: GitHub   File: JacksonGetObjectApiTest.java   Source Code and License 5 votes vote down vote up
public void testResponseBodyAndObjectListGet404() throws InterruptedException {

        server.enqueue(new MockResponse().setResponseCode(404).setBody("data"));

        final AtomicReference<String> errorBodyRef = new AtomicReference<>();
        final AtomicReference<Integer> errorCodeRef = new AtomicReference<>();
        final AtomicReference<String> errorDetailRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.get(server.url("/").toString())
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndObjectList(User.class,
                        new OkHttpResponseAndParsedRequestListener<List<User>>() {
                            @Override
                            public void onResponse(Response okHttpResponse, List<User> userList) {
                                assertTrue(false);
                            }

                            @Override
                            public void onError(ANError anError) {
                                errorBodyRef.set(anError.getErrorBody());
                                errorDetailRef.set(anError.getErrorDetail());
                                errorCodeRef.set(anError.getErrorCode());
                                latch.countDown();
                            }
                        });

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

        assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get());

        assertEquals("data", errorBodyRef.get());

        assertEquals(404, errorCodeRef.get().intValue());
    }
 
Example 27
Project: EatDubbo   File: FailbackRegistryTest.java   Source Code and License 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 28
Project: openjdk-jdk10   File: CompletableFutureTest.java   Source Code and License 5 votes vote down vote up
/**
 * minimalCompletionStage returns a CompletableFuture that is
 * completed normally, with the same value, when source is.
 */
public void testMinimalCompletionStage() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    CompletionStage<Integer> g = f.minimalCompletionStage();
    AtomicInteger x = new AtomicInteger(0);
    AtomicReference<Throwable> r = new AtomicReference<>();
    checkIncomplete(f);
    g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
    f.complete(1);
    checkCompletedNormally(f, 1);
    assertEquals(x.get(), 1);
    assertNull(r.get());
}
 
Example 29
Project: GitHub   File: PostObjectApiTest.java   Source Code and License 5 votes vote down vote up
public void testResponseBodyAndObjectPost404() throws InterruptedException {

        server.enqueue(new MockResponse().setResponseCode(404).setBody("data"));

        final AtomicReference<String> errorBodyRef = new AtomicReference<>();
        final AtomicReference<Integer> errorCodeRef = new AtomicReference<>();
        final AtomicReference<String> errorDetailRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.post(server.url("/").toString())
                .addBodyParameter("fistName", "Amit")
                .addBodyParameter("lastName", "Shekhar")
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndObject(User.class,
                        new OkHttpResponseAndParsedRequestListener<User>() {
                            @Override
                            public void onResponse(Response okHttpResponse, User user) {
                                assertTrue(false);
                            }

                            @Override
                            public void onError(ANError anError) {
                                errorBodyRef.set(anError.getErrorBody());
                                errorDetailRef.set(anError.getErrorDetail());
                                errorCodeRef.set(anError.getErrorCode());
                                latch.countDown();
                            }
                        });

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

        assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get());

        assertEquals("data", errorBodyRef.get());

        assertEquals(404, errorCodeRef.get().intValue());
    }
 
Example 30
Project: incubator-netbeans   File: CompileOnSaveActionQuery.java   Source Code and License 5 votes vote down vote up
ProxyAction(
        @NonNull final URL root,
        @NonNull final Collection<CompileOnSaveAction> current,
        @NonNull final Lookup.Result<CompileOnSaveAction.Provider> eventSource) {
    this.root = root;
    this.active = new AtomicReference<>(current);
    this.listeners = new ChangeSupport(this);
    instances.addLookupListener(WeakListeners.create(
            LookupListener.class,
            this,
            instances));
    getActions(ALL)
            .forEach((a) -> a.addChangeListener(WeakListeners.change(this, a)));
}
 
Example 31
Project: concurrency-demo   File: Controller.java   Source Code and License 5 votes vote down vote up
private Problem getSolution() {
  return urls -> {
      AtomicReference<byte[]> result = new AtomicReference<>();
      ActorSystem system = ActorSystem.create("Search");

      for(int i = 0; i < urls.length; i++) {
        String url = urls[i];
        char c = (char) ('a' + i);
        final ActorRef q = system.actorOf(
          Actors.UrlFetcher.props(restTemplate, result), "loading_"+ c);

        Patterns.ask(q, new Actors.Url2Fetch(url), new Timeout(Duration.create(5, TimeUnit.SECONDS)));
      }
      while(result.get() == null) {
        Misc.sleep(200);
      }
      return result.get();
    };
}
 
Example 32
Project: monarch   File: ConnectionManagerJUnitTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testExclusiveConnectionAccess() throws Throwable {
  manager = new ConnectionManagerImpl("pool", factory, endpointManager, 1, 0, -1, -1, logger,
      60 * 1000, cancelCriterion, poolStats);
  manager.start(background);
  AtomicReference exception = new AtomicReference();
  AtomicBoolean haveConnection = new AtomicBoolean();
  int updaterCount = 10;
  UpdaterThread[] updaters = new UpdaterThread[updaterCount];

  for (int i = 0; i < updaterCount; i++) {
    updaters[i] = new UpdaterThread(haveConnection, exception, i);
  }

  for (int i = 0; i < updaterCount; i++) {
    updaters[i].start();
  }

  for (int i = 0; i < updaterCount; i++) {
    ThreadUtils.join(updaters[i], 30 * 1000);
  }

  if (exception.get() != null) {
    throw (Throwable) exception.get();
  }

  for (int i = 0; i < updaterCount; i++) {
    Assert.assertFalse("Updater [" + i + "] is still running", updaters[i].isAlive());
  }
}
 
Example 33
Project: incubator-netbeans   File: ModuleClassPaths.java   Source Code and License 5 votes vote down vote up
ModuleInfoClassPathImplementation(
        @NonNull final ClassPath base,
        @NonNull final ClassPath sources,
        @NonNull final ClassPath systemModules,
        @NonNull final ClassPath userModules,
        @NonNull final ClassPath legacyClassPath,
        @NullAllowed final Function<URL,Boolean> filter) {
    super(null);
    Parameters.notNull("base", base);       //NOI18N
    Parameters.notNull("sources", sources); //NOI18N
    Parameters.notNull("systemModules", systemModules); //NOI18N
    Parameters.notNull("userModules", userModules); //NOI18N
    Parameters.notNull("legacyClassPath", legacyClassPath); //NOI18N
    this.base = base;
    this.sources = sources;
    this.systemModules = systemModules;
    this.userModules = userModules;
    this.legacyClassPath = legacyClassPath;
    this.filter = filter == null ?
            (url) -> null :
            filter;
    this.selfRes = new ThreadLocal<>();
    this.compilerOptions = new AtomicReference<>();
    this.moduleInfos = Collections.emptyList();
    this.sources.addPropertyChangeListener(WeakListeners.propertyChange(this, this.sources));
    this.systemModules.addPropertyChangeListener(WeakListeners.propertyChange(this, this.systemModules));
    this.userModules.addPropertyChangeListener(WeakListeners.propertyChange(this, this.base));
    this.legacyClassPath.addPropertyChangeListener(WeakListeners.propertyChange(this, this.legacyClassPath));
}
 
Example 34
Project: GitHub   File: PostObjectApiTest.java   Source Code and License 5 votes vote down vote up
public void testResponseBodyAndObjectListPost404() throws InterruptedException {

        server.enqueue(new MockResponse().setResponseCode(404).setBody("data"));

        final AtomicReference<String> errorBodyRef = new AtomicReference<>();
        final AtomicReference<Integer> errorCodeRef = new AtomicReference<>();
        final AtomicReference<String> errorDetailRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.post(server.url("/").toString())
                .addBodyParameter("fistName", "Amit")
                .addBodyParameter("lastName", "Shekhar")
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndObjectList(User.class,
                        new OkHttpResponseAndParsedRequestListener<List<User>>() {
                            @Override
                            public void onResponse(Response okHttpResponse, List<User> userList) {
                                assertTrue(false);
                            }

                            @Override
                            public void onError(ANError anError) {
                                errorBodyRef.set(anError.getErrorBody());
                                errorDetailRef.set(anError.getErrorDetail());
                                errorCodeRef.set(anError.getErrorCode());
                                latch.countDown();
                            }
                        });

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

        assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get());

        assertEquals("data", errorBodyRef.get());

        assertEquals(404, errorCodeRef.get().intValue());
    }
 
Example 35
Project: GitHub   File: JacksonPostObjectApiTest.java   Source Code and License 5 votes vote down vote up
public void testResponseBodyAndObjectPost404() throws InterruptedException {

        server.enqueue(new MockResponse().setResponseCode(404).setBody("data"));

        final AtomicReference<String> errorBodyRef = new AtomicReference<>();
        final AtomicReference<Integer> errorCodeRef = new AtomicReference<>();
        final AtomicReference<String> errorDetailRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.post(server.url("/").toString())
                .addBodyParameter("fistName", "Amit")
                .addBodyParameter("lastName", "Shekhar")
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndObject(User.class,
                        new OkHttpResponseAndParsedRequestListener<User>() {
                            @Override
                            public void onResponse(Response okHttpResponse, User user) {
                                assertTrue(false);
                            }

                            @Override
                            public void onError(ANError anError) {
                                errorBodyRef.set(anError.getErrorBody());
                                errorDetailRef.set(anError.getErrorDetail());
                                errorCodeRef.set(anError.getErrorCode());
                                latch.countDown();
                            }
                        });

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

        assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get());

        assertEquals("data", errorBodyRef.get());

        assertEquals(404, errorCodeRef.get().intValue());
    }
 
Example 36
Project: GitHub   File: HandlerSchedulerTest.java   Source Code and License 5 votes vote down vote up
@Test @Ignore("Implementation delegated to default RxJava implementation")
public void directSchedulePeriodicallyUsesHookOnce() {
    final CountingRunnable newCounter = new CountingRunnable();
    final AtomicReference<Runnable> runnableRef = new AtomicReference<>();
    RxJavaPlugins.setScheduleHandler(new Function<Runnable, Runnable>() {
        @Override public Runnable apply(Runnable runnable) {
            runnableRef.set(runnable);
            return newCounter;
        }
    });

    CountingRunnable counter = new CountingRunnable();
    scheduler.schedulePeriodicallyDirect(counter, 1, 1, MINUTES);

    // Verify our action was passed to the schedulers hook.
    assertSame(counter, runnableRef.get());
    runnableRef.set(null);

    idleMainLooper(1, MINUTES);
    runUiThreadTasks();
    // Verify the scheduled action was the one returned from the hook.
    assertEquals(1, newCounter.get());
    assertEquals(0, counter.get());

    // Ensure the hook was not called again when the runnable re-scheduled itself.
    assertNull(runnableRef.get());
}
 
Example 37
Project: GitHub   File: MultipartStringApiTest.java   Source Code and License 5 votes vote down vote up
public void testResponseBodyAndStringMultipart() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("data"));

        final AtomicReference<Boolean> responseBodySuccess = new AtomicReference<>();
        final AtomicReference<String> responseStringRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.upload(server.url("/").toString())
                .addMultipartParameter("key", "value")
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() {
                    @Override
                    public void onResponse(Response okHttpResponse, String response) {
                        responseBodySuccess.set(okHttpResponse.isSuccessful());
                        responseStringRef.set(response);
                        latch.countDown();
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

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

        assertTrue(responseBodySuccess.get());
        assertEquals("data", responseStringRef.get());
    }
 
Example 38
Project: jdk8u-jdk   File: Phaser.java   Source Code and License 5 votes vote down vote up
/**
 * Removes and signals threads from queue for phase.
 */
private void releaseWaiters(int phase) {
    QNode q;   // first element of queue
    Thread t;  // its thread
    AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
    while ((q = head.get()) != null &&
           q.phase != (int)(root.state >>> PHASE_SHIFT)) {
        if (head.compareAndSet(q, q.next) &&
            (t = q.thread) != null) {
            q.thread = null;
            LockSupport.unpark(t);
        }
    }
}
 
Example 39
Project: infxnity   File: IFXContentBindingTest.java   Source Code and License 5 votes vote down vote up
@Test
public void addElementsTest()
{
    final ObservableList<Model> collection1 = FXCollections.observableArrayList(new Model("value1"),
                                                                                new Model("value2"),
                                                                                new Model("value3"),
                                                                                new Model("value4"));
    final ObservableList<String> collection2 = FXCollections.observableArrayList();

    IFXContentBinding.bind(collection2, collection1, Model::getText);

    final AtomicReference<ListChangeListener.Change<? extends String>> change = new AtomicReference<>(null);
    collection2.addListener((ListChangeListener<String>) c -> {
        change.set(c);
    });

    collection1.addAll(2, Arrays.asList(new Model("value2bis"), new Model("value2ter")));

    assertNotNull("Change event", change.get());
    assertTrue("Has change", change.get().next());
    assertTrue("Was added", change.get().wasAdded());
    assertFalse("Was removed", change.get().wasRemoved());
    assertFalse("Was update", change.get().wasUpdated());
    assertFalse("Was permuted", change.get().wasPermutated());
    assertEquals("from", 2, change.get().getFrom());
    assertEquals("to", 4, change.get().getTo());
    assertEquals("Added sub-list", Arrays.asList("value2bis", "value2ter"), change.get().getAddedSubList());
    assertFalse("Has more change", change.get().next());

    assertEquals(Arrays.asList("value1", "value2", "value2bis", "value2ter", "value3", "value4"), collection2);
}
 
Example 40
Project: incubator-netbeans   File: RevisionSetupSupportTest.java   Source Code and License 5 votes vote down vote up
public void testDiffModifiedDifferentNames () throws Exception {
    // init
    File project = new File(wc, "project");
    File trunk = new File(project, "trunk");
    final File file = new File(trunk, "file");
    trunk.mkdirs();
    file.createNewFile();
    
    add(project);
    commit(project);
    
    RepositoryFile left = new RepositoryFile(repoUrl, wc.getName() + "/project/trunk", SVNRevision.HEAD);
    RepositoryFile right = new RepositoryFile(repoUrl, wc.getName() + "/project/branches/B", SVNRevision.HEAD);
    getClient().copy(left.getFileUrl(), right.getFileUrl(), "copying...", SVNRevision.HEAD, true);
    
    TestKit.write(file, "modification");
    commit(trunk);
    
    final RevisionSetupsSupport revSupp = new RevisionSetupsSupport(left, right, repoUrl, new Context(new File[] { trunk }));
    final AtomicReference<Setup[]> ref = new AtomicReference<>();
    new SvnProgressSupport() {
        @Override
        protected void perform () {
            ref.set(revSupp.computeSetupsBetweenRevisions(this));
        }
    }.start(RequestProcessor.getDefault(), repoUrl, "bbb").waitFinished();
    Setup[] setups = ref.get();
    assertNotNull(setups);
    assertEquals(1, setups.length);
    assertEquals(file, setups[0].getBaseFile());
    assertEquals(FileInformation.STATUS_VERSIONED_MODIFIEDLOCALLY, setups[0].getInfo().getStatus());
}
 
Example 41
Project: future   File: PromiseTest.java   Source Code and License 5 votes vote down vote up
@Test
public void applyHandlerWithLocal() {
  AtomicReference<Optional<Integer>> localValue = new AtomicReference<>();
  Local<Integer> l = Local.apply();
  l.update(1);
  Promise<Integer> p = Promise.apply((ex) -> {
  });
  l.update(2);
  p.ensure(() -> localValue.set(l.get()));
  p.setValue(1);
  assertEquals(Optional.of(1), localValue.get());
}
 
Example 42
Project: GitHub   File: GetObjectApiTest.java   Source Code and License 5 votes vote down vote up
public void testObjectGetRequest404() throws InterruptedException {

        server.enqueue(new MockResponse().setResponseCode(404).setBody("data"));

        final AtomicReference<String> errorDetailRef = new AtomicReference<>();
        final AtomicReference<String> errorBodyRef = new AtomicReference<>();
        final AtomicReference<Integer> errorCodeRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.get(server.url("/").toString())
                .build()
                .getAsObject(User.class, new ParsedRequestListener<User>() {
                    @Override
                    public void onResponse(User user) {
                        assertTrue(false);
                    }

                    @Override
                    public void onError(ANError anError) {
                        errorBodyRef.set(anError.getErrorBody());
                        errorDetailRef.set(anError.getErrorDetail());
                        errorCodeRef.set(anError.getErrorCode());
                        latch.countDown();
                    }
                });

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

        assertEquals(ANConstants.RESPONSE_FROM_SERVER_ERROR, errorDetailRef.get());

        assertEquals("data", errorBodyRef.get());

        assertEquals(404, errorCodeRef.get().intValue());

    }
 
Example 43
Project: boohee_v5.6   File: SerialSubscription.java   Source Code and License 5 votes vote down vote up
public void unsubscribe() {
    State oldState;
    AtomicReference<State> localState = this.state;
    do {
        oldState = (State) localState.get();
        if (oldState.isUnsubscribed) {
            return;
        }
    } while (!localState.compareAndSet(oldState, oldState.unsubscribe()));
    oldState.subscription.unsubscribe();
}
 
Example 44
Project: GitHub   File: MultipartStringApiTest.java   Source Code and License 5 votes vote down vote up
public void testStringMultipartRequest() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("data"));

        final AtomicReference<String> responseRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.upload(server.url("/").toString())
                .addMultipartParameter("key", "value")
                .build()
                .getAsString(new StringRequestListener() {
                    @Override
                    public void onResponse(String response) {
                        responseRef.set(response);
                        latch.countDown();
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

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

        assertEquals("data", responseRef.get());
    }
 
Example 45
Project: elasticsearch_my   File: InternalEngineTests.java   Source Code and License 5 votes vote down vote up
public void testShardNotAvailableExceptionWhenEngineClosedConcurrently() throws IOException, InterruptedException {
    AtomicReference<Exception> exception = new AtomicReference<>();
    String operation = randomFrom("optimize", "refresh", "flush");
    Thread mergeThread = new Thread() {
        @Override
        public void run() {
            boolean stop = false;
            logger.info("try with {}", operation);
            while (stop == false) {
                try {
                    switch (operation) {
                        case "optimize": {
                            engine.forceMerge(true, 1, false, false, false);
                            break;
                        }
                        case "refresh": {
                            engine.refresh("test refresh");
                            break;
                        }
                        case "flush": {
                            engine.flush(true, false);
                            break;
                        }
                    }
                } catch (Exception e) {
                    exception.set(e);
                    stop = true;
                }
            }
        }
    };
    mergeThread.start();
    engine.close();
    mergeThread.join();
    logger.info("exception caught: ", exception.get());
    assertTrue("expected an Exception that signals shard is not available", TransportActions.isShardNotAvailableException(exception.get()));
}
 
Example 46
Project: firebase-chat-android-architecture-components   File: NetworkBoundResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void dbSuccessWithReFetchSuccess() {
    Foo dbValue = new Foo(1);
    Foo dbValue2 = new Foo(2);
    AtomicReference<Foo> saved = new AtomicReference<>();
    shouldFetch = (foo) -> foo == dbValue;
    saveCallResult = foo -> {
        saved.set(foo);
        dbData.setValue(dbValue2);
        return null;
    };
    MutableLiveData<ApiResponse<Foo>> apiResponseLiveData = new MutableLiveData();
    createCall = (aVoid) -> apiResponseLiveData;

    Observer<Resource<Foo>> observer = Mockito.mock(Observer.class);
    networkBoundResource.asLiveData().observeForever(observer);
    drain();
    verify(observer).onChanged(Resource.loading(null));
    reset(observer);

    dbData.setValue(dbValue);
    drain();
    final Foo networkResult = new Foo(1);
    verify(observer).onChanged(Resource.loading(dbValue));
    apiResponseLiveData.setValue(new ApiResponse<>(Response.success(networkResult)));
    drain();
    assertThat(saved.get(), is(networkResult));
    verify(observer).onChanged(Resource.success(dbValue2));
    verifyNoMoreInteractions(observer);
}
 
Example 47
Project: future   File: PromiseTest.java   Source Code and License 5 votes vote down vote up
@Test
public void onFailureInterrupt() {
  AtomicReference<Throwable> intr = new AtomicReference<>();
  Promise<Integer> p = Promise.apply(intr::set);
  Future<Integer> f = p.onFailure(i -> {
  });
  f.raise(ex);
  assertEquals(ex, intr.get());
}
 
Example 48
Project: ndbc   File: Concurrently.java   Source Code and License 5 votes vote down vote up
public static void apply(final Duration howLong, final Runnable run,
    final Runnable checkInvariants) {
  final int threads = Runtime.getRuntime().availableProcessors() * 2;
  final ExecutorService executor = Executors.newFixedThreadPool(threads);
  final ExecutorService validator = Executors.newFixedThreadPool(1);
  final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
  final AtomicBoolean stop = new AtomicBoolean(false);
  final AtomicReference<Throwable> error = new AtomicReference<>();
  try {

    validator.submit(() -> {
      while (!stop.get())
        try {
          checkInvariants.run();
        } catch (final Throwable e) {
          error.set(e);
          stop.set(true);
        }
    });

    scheduler.schedule(() -> stop.set(true), howLong.toMillis(), TimeUnit.MILLISECONDS);

    while (!stop.get())
      executor.submit(run);

    executor.shutdownNow();

    if (error.get() != null)
      throw new RuntimeException(error.get());

  } finally {
    executor.shutdown();
    validator.shutdown();
    scheduler.shutdown();
  }
}
 
Example 49
Project: GitHub   File: MultipartStringApiTest.java   Source Code and License 5 votes vote down vote up
public void testHeaderMultipartRequest() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("data"));

        final AtomicReference<String> responseRef = new AtomicReference<>();
        final AtomicReference<String> headerRef = new AtomicReference<>();
        final AtomicReference<Boolean> responseBodySuccess = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.upload(server.url("/").toString())
                .addHeaders("headerKey", "headerValue")
                .addMultipartParameter("key", "value")
                .setExecutor(Executors.newSingleThreadExecutor())
                .build()
                .getAsOkHttpResponseAndString(new OkHttpResponseAndStringRequestListener() {
                    @Override
                    public void onResponse(Response okHttpResponse, String response) {
                        responseRef.set(response);
                        responseBodySuccess.set(okHttpResponse.isSuccessful());
                        headerRef.set(okHttpResponse.request().header("headerKey"));
                        latch.countDown();
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

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

        assertTrue(responseBodySuccess.get());
        assertEquals("data", responseRef.get());
        assertEquals("headerValue", headerRef.get());
    }
 
Example 50
Project: GitHub   File: MultipartObjectApiTest.java   Source Code and License 5 votes vote down vote up
public void testObjectMultipartRequest() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}"));

        final AtomicReference<String> firstNameRef = new AtomicReference<>();
        final AtomicReference<String> lastNameRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.upload(server.url("/").toString())
                .addMultipartParameter("key", "value")
                .build()
                .getAsObject(User.class, new ParsedRequestListener<User>() {
                    @Override
                    public void onResponse(User user) {
                        firstNameRef.set(user.firstName);
                        lastNameRef.set(user.lastName);
                        latch.countDown();
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

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

        assertEquals("Amit", firstNameRef.get());
        assertEquals("Shekhar", lastNameRef.get());
    }
 
Example 51
Project: future   File: PromiseTest.java   Source Code and License 5 votes vote down vote up
@Test
public void applyHandlersWithLocal() {
  AtomicReference<Optional<Integer>> localValue = new AtomicReference<>();
  Local<Integer> l = Local.apply();
  l.update(1);
  Promise<Integer> p = Promise.apply(Arrays.asList((ex) -> {
  }, (ex) -> {
  }));
  l.update(2);
  p.ensure(() -> localValue.set(l.get()));
  p.setValue(1);
  assertEquals(Optional.of(1), localValue.get());
}
 
Example 52
Project: future   File: PromiseTest.java   Source Code and License 5 votes vote down vote up
/*** create ***/

@Test
public void create() {
  AtomicReference<Promise<Integer>> pRef = new AtomicReference<>();
  AtomicReference<Throwable> interrupt = new AtomicReference<Throwable>();
  Promise<Integer> p = Promise.create(p2 -> {
    pRef.set(p2);
    return interrupt::set;
  });
  p.raise(ex);
  assertEquals(p, pRef.get());
  assertEquals(interrupt.get(), ex);
}
 
Example 53
Project: monarch   File: AbstractBucketRegionQueue.java   Source Code and License 5 votes vote down vote up
@Override
public Set<VersionSource> clearEntries(final RegionVersionVector rvv) {
  final AtomicReference<Set<VersionSource>> result = new AtomicReference<Set<VersionSource>>();
  OffHeapRegionEntryHelper.doWithOffHeapClear(new Runnable() {
    @Override
    public void run() {
      result.set(AbstractBucketRegionQueue.super.clearEntries(rvv));
    }
  });
  clearQueues();
  return result.get();
}
 
Example 54
Project: openjdk-jdk10   File: AtomicReference9Test.java   Source Code and License 5 votes vote down vote up
/**
 * repeated weakCompareAndSetRelease succeeds in changing value when equal
 * to expected
 */
public void testWeakCompareAndSetRelease() {
    AtomicReference<Integer> ai = new AtomicReference<>(one);
    do {} while (!ai.weakCompareAndSetRelease(one, two));
    do {} while (!ai.weakCompareAndSetRelease(two, m4));
    assertEquals(m4, ai.get());
    do {} while (!ai.weakCompareAndSetRelease(m4, seven));
    assertEquals(seven, ai.get());
}
 
Example 55
Project: java-red   File: TestRedFuture.java   Source Code and License 5 votes vote down vote up
/**
 * Tests failed following {@link RedFuture} callbacks on current thread.
 */
@Test
public void testFutureFollowFailureOnCurrentThread() throws Throwable {
    CountDownLatch lock = new CountDownLatch(2);
    AtomicReference<Throwable> failure = new AtomicReference<>();
    long time = System.currentTimeMillis();
    OpenRedFuture future = RedFuture.future();
    future.follow(failingFuture(new TestException()));
    future.addFailureCallback(throwable -> {
        if (!(throwable instanceof TestException)) {
            failure.compareAndSet(null, throwable);
        }
        if (System.currentTimeMillis() - time < FUTURE_SLEEP_TIME) {
            failure.compareAndSet(null, new RuntimeException("success too soon"));
        }
        if (!isCallbackThread()) {
            failure.compareAndSet(null, new RuntimeException("success block on unexpected thread"));
        }
        lock.countDown();
    });
    future.addFinallyCallback(() -> {
        if (System.currentTimeMillis() - time < FUTURE_SLEEP_TIME) {
            failure.compareAndSet(null, new RuntimeException("finally too soon"));
        }
        if (!isCallbackThread()) {
            failure.compareAndSet(null, new RuntimeException("finally block on unexpected thread"));
        }
        lock.countDown();
    });
    future.addSuccessCallback(() ->
            failure.compareAndSet(null, new RuntimeException("should not have reached success block")));
    lock.await(300, TimeUnit.MILLISECONDS);
    Thread.sleep(VALIDATION_SLEEP_TIME);
    if (failure.get() != null) {
        throw failure.get();
    }
}
 
Example 56
Project: Elasticsearch   File: NestedLoopOperation.java   Source Code and License 5 votes vote down vote up
private State waitForStateChange(AtomicReference<State> stateRef) {
    // loop shouldn't take long as other side has just acquired the lead and is about to change the state
    State state;
    do {
        state = stateRef.get();
    } while (state == State.LEAD_ELECTION);
    return state;
}
 
Example 57
Project: athena   File: DefaultOvsdbClient.java   Source Code and License 5 votes vote down vote up
private Uuid getBridgeUuid(DeviceId openflowDeviceId) {
    DatabaseSchema dbSchema = schema.get(OvsdbConstant.DATABASENAME);
    if (dbSchema == null) {
        return null;
    }
    OvsdbRowStore rowStore = getRowStore(OvsdbConstant.DATABASENAME,
                                         OvsdbConstant.BRIDGE);
    if (rowStore == null) {
        log.debug("There is no bridge table");
        return null;
    }

    ConcurrentMap<String, Row> bridgeTableRows = rowStore.getRowStore();
    final AtomicReference<Uuid> uuid = new AtomicReference<>();
    for (Map.Entry<String, Row> entry : bridgeTableRows.entrySet()) {
        Bridge b = (Bridge) TableGenerator.getTable(dbSchema,
                                                    entry.getValue(),
                                                    OvsdbTable.BRIDGE);
        if (matchesDpid(b, openflowDeviceId)) {
            uuid.set(Uuid.uuid(entry.getKey()));
            break;
        }
    }
    if (uuid.get() == null) {
        log.debug("There is no bridge for {}", openflowDeviceId);
    }
    return uuid.get();

}
 
Example 58
Project: GitHub   File: PostStringApiTest.java   Source Code and License 5 votes vote down vote up
public void testStringPostRequest() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("data"));

        final AtomicReference<String> responseRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.post(server.url("/").toString())
                .addBodyParameter("fistName", "Amit")
                .addBodyParameter("lastName", "Shekhar")
                .build()
                .getAsString(new StringRequestListener() {
                    @Override
                    public void onResponse(String response) {
                        responseRef.set(response);
                        latch.countDown();
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

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

        assertEquals("data", responseRef.get());
    }
 
Example 59
Project: GitHub   File: PostObjectApiTest.java   Source Code and License 5 votes vote down vote up
public void testObjectListPostRequest() throws InterruptedException {

        server.enqueue(new MockResponse().setBody("[{\"firstName\":\"Amit\", \"lastName\":\"Shekhar\"}]"));

        final AtomicReference<String> firstNameRef = new AtomicReference<>();
        final AtomicReference<String> lastNameRef = new AtomicReference<>();
        final CountDownLatch latch = new CountDownLatch(1);

        AndroidNetworking.post(server.url("/").toString())
                .addBodyParameter("fistName", "Amit")
                .addBodyParameter("lastName", "Shekhar")
                .build()
                .getAsObjectList(User.class, new ParsedRequestListener<List<User>>() {
                    @Override
                    public void onResponse(List<User> userList) {
                        firstNameRef.set(userList.get(0).firstName);
                        lastNameRef.set(userList.get(0).lastName);
                        latch.countDown();
                    }

                    @Override
                    public void onError(ANError anError) {
                        assertTrue(false);
                    }
                });

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

        assertEquals("Amit", firstNameRef.get());
        assertEquals("Shekhar", lastNameRef.get());
    }
 
Example 60
Project: jobson   File: JobExecutorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testExecuteWritesStdoutToTheStdoutListener() throws Throwable {
    final JobExecutor jobExecutor = getInstance();
    final String msgSuppliedToEcho = generateRandomString();
    final PersistedJob req =
            standardRequestWithCommand("echo", msgSuppliedToEcho);
    final AtomicReference<byte[]> bytesEchoedToStdout = new AtomicReference<>(new byte[]{});
    final Subject<byte[]> stdoutSubject = PublishSubject.create();

    stdoutSubject.subscribe(bytes ->
            bytesEchoedToStdout.getAndUpdate(existingBytes ->
                    Bytes.concat(existingBytes, bytes)));

    final Semaphore s = new Semaphore(1);
    s.acquire();
    stdoutSubject.doOnComplete(s::release).subscribe();

    final JobEventListeners listeners =
            createStdoutListener(stdoutSubject);

    jobExecutor.execute(req, listeners);

    s.tryAcquire(TestConstants.DEFAULT_TIMEOUT, MILLISECONDS);

    final String stringFromStdout = new String(bytesEchoedToStdout.get()).trim();
    assertThat(stringFromStdout).isEqualTo(msgSuppliedToEcho);
}