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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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());
}