Example usage for java.util.concurrent.atomic AtomicBoolean AtomicBoolean

List of usage examples for java.util.concurrent.atomic AtomicBoolean AtomicBoolean

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicBoolean AtomicBoolean.

Prototype

public AtomicBoolean(boolean initialValue) 

Source Link

Document

Creates a new AtomicBoolean with the given initial value.

Usage

From source file:com.sixt.service.framework.kafka.messaging.KafkaFailoverIntegrationTest.java

@Test
public void manualKafkaTest() throws InterruptedException {

    ServiceProperties serviceProperties = fillServiceProperties();

    // Topics are created with 3 partitions - see docker-compose-kafkafailover-integrationtest.yml
    Topic ping = new Topic("ping");
    Topic pong = new Topic("pong");

    AtomicInteger sentMessages = new AtomicInteger(0);
    AtomicInteger sendFailures = new AtomicInteger(0);
    AtomicInteger recievedMessages = new AtomicInteger(0);

    Producer producer = new ProducerFactory(serviceProperties).createProducer();

    final AtomicBoolean produceMessages = new AtomicBoolean(true);

    // Produce messages until test tells producer to stop.
    ExecutorService producerExecutor = Executors.newSingleThreadExecutor();
    producerExecutor.submit(new Runnable() {
        @Override/*from ww  w . j  a  va2 s .c o m*/
        public void run() {
            OrangeContext context = new OrangeContext();
            Sleeper sleeper = new Sleeper();

            while (produceMessages.get()) {
                try {

                    String key = RandomStringUtils.randomAscii(5);
                    SayHelloToCmd payload = SayHelloToCmd.newBuilder().setName(key).build();

                    Message request = Messages.requestFor(ping, pong, key, payload, context);
                    producer.send(request);
                    sentMessages.incrementAndGet();

                    sleeper.sleepNoException(1000);
                } catch (Throwable t) {
                    sendFailures.incrementAndGet();
                    logger.error("Caught exception in producer loop", t);
                }
            }
        }
    });

    Consumer consumer = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class,
            new MessageHandler<SayHelloToCmd>() {
                @Override
                public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) {
                    recievedMessages.incrementAndGet();
                }
            }).consumerForTopic(ping, new DiscardFailedMessages());

    // Wait to allow manual fiddling with Kafka. Sync with global test timeout above.
    Thread.sleep(2 * 60 * 1000);

    produceMessages.set(false);
    producer.shutdown();

    Thread.sleep(10_000);

    consumer.shutdown();

    logger.info("sentMessages: " + sentMessages.get());
    logger.info("sendFailures: " + sendFailures.get());
    logger.info("recievedMessages: " + recievedMessages.get());
}

From source file:de.speexx.jira.jan.command.transition.IssueTransitionFetcher.java

@Override
public void execute() {

    int count = 0;
    int startIndex = 0;
    int total = -1;

    final List<IssueInfo> issueInfos = new ArrayList<>();

    final AtomicBoolean header = new AtomicBoolean(false);
    try (final JiraRestClient restClient = this.execCtx.newJiraClient()) {
        do {/*from  w  ww  .jav  a2s  .co m*/
            final String q = getQuery()
                    .orElseThrow(() -> new JiraAnalyzeException("No query given for fetching transitions"));
            final SearchResult searchResult = fetchIssues(restClient, q, startIndex);
            total = total == -1 ? searchResult.getTotal() : total;
            startIndex += getFetchLimit();

            for (final Issue searchResultIssue : searchResult.getIssues()) {
                count++;
                final Issue issue = fetchIssueForSearchResult(restClient, searchResultIssue);
                final Iterable<ChangelogGroup> changeLogs = issue.getChangelog();

                final Optional<IssueInfo> issueInfo = handleChangeLog(changeLogs, issue);
                issueInfo.ifPresent(info -> {
                    info.issueType = fetchIssueType(issue);
                    info.key = issue.getKey();
                    info.resolution = fetchResolution(issue);
                    info.priority = fetchPriority(issue);
                    info.created = fetchCreationDateTime(issue);
                    issueInfos.add(info);
                    this.execCtx.log("ISSUE INFO: {}", info);
                });
            }
            this.execCtx.log("total: {} - count: {}", total, count);
        } while (total != count);
    } catch (final IOException e) {
        throw new JiraAnalyzeException(e);
    }
    exportAsCsv(issueInfos, header);
}

From source file:com.rapleaf.hank.ZkTestCase.java

@Override
protected void setUp() throws Exception {
    super.setUp();
    Logger.getLogger("org.apache.zookeeper").setLevel(Level.WARN);

    setupZkServer();/*from ww  w.  j a v  a 2  s.c  om*/

    final Object lock = new Object();
    final AtomicBoolean connected = new AtomicBoolean(false);

    zk = new ZooKeeperPlus("127.0.0.1:" + zkClientPort, 1000000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            switch (event.getType()) {
            case None:
                if (event.getState() == KeeperState.SyncConnected) {
                    connected.set(true);
                    synchronized (lock) {
                        lock.notifyAll();
                    }
                }
            }
            LOG.debug(event.toString());
        }
    });

    synchronized (lock) {
        lock.wait(2000);
    }
    if (!connected.get()) {
        fail("timed out waiting for the zk client connection to come online!");
    }
    LOG.debug("session timeout: " + zk.getSessionTimeout());

    zk.deleteNodeRecursively(zkRoot);
    createNodeRecursively(zkRoot);
}

From source file:com.netflix.curator.TestSessionFailRetryLoop.java

@Test
public void testRetryStatic() throws Exception {
    Timing timing = new Timing();
    final CuratorZookeeperClient client = new CuratorZookeeperClient(server.getConnectString(),
            timing.session(), timing.connection(), null, new RetryOneTime(1));
    SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(SessionFailRetryLoop.Mode.RETRY);
    retryLoop.start();/*  w w w. j  av  a2s  .co  m*/
    try {
        client.start();
        final AtomicBoolean secondWasDone = new AtomicBoolean(false);
        final AtomicBoolean firstTime = new AtomicBoolean(true);
        SessionFailRetryLoop.callWithRetry(client, SessionFailRetryLoop.Mode.RETRY, new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        if (firstTime.compareAndSet(true, false)) {
                            Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                            KillSession.kill(client.getZooKeeper(), server.getConnectString());
                            client.getZooKeeper();
                            client.blockUntilConnectedOrTimedOut();
                        }

                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        return null;
                    }
                });

                RetryLoop.callWithRetry(client, new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        Assert.assertFalse(firstTime.get());
                        Assert.assertNull(client.getZooKeeper().exists("/foo/bar", false));
                        secondWasDone.set(true);
                        return null;
                    }
                });
                return null;
            }
        });

        Assert.assertTrue(secondWasDone.get());
    } finally {
        retryLoop.close();
        IOUtils.closeQuietly(client);
    }
}

From source file:com.esri.geoevent.test.performance.PerformanceCollectorBase.java

@Override
public void start() throws RunningException {
    running = new AtomicBoolean(true);
    Thread thread = new Thread(this);
    thread.start();//from   w  w w. j  a v  a  2  s. c o  m
}

From source file:info.archinnov.achilles.test.integration.tests.LWTOperationsIT.java

@Test
public void should_insert_and_notify_LWT_listener_on_success() throws Exception {
    final AtomicBoolean LWTSuccess = new AtomicBoolean(false);
    LWTResultListener listener = new LWTResultListener() {
        @Override/* ww w. j a v  a  2s  .  c o m*/
        public void onSuccess() {
            LWTSuccess.compareAndSet(false, true);
        }

        @Override
        public void onError(LWTResult lwtResult) {

        }
    };

    //Given
    final EntityWithEnum entityWithEnum = new EntityWithEnum(10L, "name", EACH_QUORUM);

    //When
    manager.insertOrUpdate(entityWithEnum, OptionsBuilder.ifNotExists().lwtResultListener(listener));
    final EntityWithEnum found = manager.find(EntityWithEnum.class, 10L);

    //Then
    assertThat(found).isNotNull();
    assertThat(found.getName()).isEqualTo("name");
    assertThat(found.getConsistencyLevel()).isEqualTo(EACH_QUORUM);
    assertThat(LWTSuccess.get()).isTrue();
}

From source file:org.apache.streams.facebook.provider.FacebookProvider.java

@Override
public void prepare(Object configurationObject) {
    this.datums = Queues.newLinkedBlockingQueue();
    this.isComplete = new AtomicBoolean(false);
    this.executor = Executors.newFixedThreadPool(1);
}

From source file:de.undercouch.gradle.tasks.download.InterceptorTest.java

/**
 * Tests if we can manipulate a response
 * @throws Exception if anything goes wrong
 *//*from  w w w .ja v a2s  .co m*/
@Test
public void interceptResponse() throws Exception {
    final AtomicBoolean interceptorCalled = new AtomicBoolean(false);

    Download t = makeProjectAndTask();
    t.src(makeSrc(INTERCEPTOR));
    File dst = folder.newFile();
    t.dest(dst);
    t.responseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            assertFalse(interceptorCalled.get());
            interceptorCalled.set(true);
            response.setEntity(new StringEntity(INTERCEPTED));
        }
    });
    t.execute();

    assertTrue(interceptorCalled.get());

    String dstContents = FileUtils.readFileToString(dst);
    assertEquals(INTERCEPTED, dstContents);
}

From source file:io.cloudslang.engine.queue.services.recovery.WorkerRecoveryServiceImpl.java

@Override
@Transactional/*from w w  w .  j a  va  2  s  .  c o  m*/
public void doWorkerRecovery(String workerUuid) {

    //lock this worker to synchronize with drain action
    workerLockService.lock(workerUuid);

    logger.warn("Worker [" + workerUuid + "] is going to be recovered");
    long time = System.currentTimeMillis();
    // change status to in_recovery in separate transaction in order to make it as quickly as possible
    // so keep-alive wont be stuck and assigning won't take this worker as candidate
    workerNodeService.updateStatusInSeparateTransaction(workerUuid, WorkerStatus.IN_RECOVERY);

    final AtomicBoolean shouldContinue = new AtomicBoolean(true);

    while (shouldContinue.get()) {
        shouldContinue.set(messageRecoveryService.recoverMessagesBulk(workerUuid, DEFAULT_POLL_SIZE));
    }

    String newWRV = UUID.randomUUID().toString();
    workerNodeService.updateWRV(workerUuid, newWRV);
    workerNodeService.updateStatus(workerUuid, WorkerStatus.RECOVERED);

    logger.warn(
            "Worker [" + workerUuid + "] recovery is done in " + (System.currentTimeMillis() - time) + " ms");
}

From source file:com.netflix.conductor.core.events.TestEventProcessor.java

@Test
public void testEventProcessor() throws Exception {
    String event = "sqs:arn:account090:sqstest1";
    String queueURI = "arn:account090:sqstest1";

    EventQueueProvider provider = mock(EventQueueProvider.class);

    ObservableQueue queue = mock(ObservableQueue.class);
    Message[] messages = new Message[1];
    messages[0] = new Message("t0", "{}", "t0");
    Observable<Message> msgObservable = Observable.from(messages);
    when(queue.observe()).thenReturn(msgObservable);
    when(queue.getURI()).thenReturn(queueURI);
    when(queue.getName()).thenReturn(queueURI);
    when(queue.getType()).thenReturn("sqs");
    when(provider.getQueue(queueURI)).thenReturn(queue);

    EventQueues.registerProvider(QueueType.sqs, provider);

    EventHandler eh = new EventHandler();
    eh.setName(UUID.randomUUID().toString());
    eh.setActive(false);/*from w w  w . jav a 2 s  . c  o m*/
    Action action = new Action();
    action.setAction(Type.start_workflow);
    action.setStart_workflow(new StartWorkflow());
    action.getStart_workflow().setName("workflow_x");
    action.getStart_workflow().setVersion(1); //TODO: Remove this to simulate the null value for version being passed!
    eh.getActions().add(action);
    eh.setEvent(event);

    MetadataService ms = mock(MetadataService.class);

    when(ms.getEventHandlers()).thenReturn(Arrays.asList(eh));
    when(ms.getEventHandlersForEvent(eh.getEvent(), true)).thenReturn(Arrays.asList(eh));

    //Execution Service Mock
    ExecutionService eservice = mock(ExecutionService.class);
    when(eservice.addEventExecution(any())).thenReturn(true);

    //Workflow Executor Mock
    WorkflowExecutor executor = mock(WorkflowExecutor.class);
    String id = UUID.randomUUID().toString();
    AtomicBoolean started = new AtomicBoolean(false);
    doAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            started.set(true);
            return id;
        }
    }).when(executor).startWorkflow(action.getStart_workflow().getName(), 1,
            action.getStart_workflow().getCorrelationId(), action.getStart_workflow().getInput());

    //Metadata Service Mock
    MetadataService metadata = mock(MetadataService.class);
    WorkflowDef def = new WorkflowDef();
    def.setVersion(1);
    def.setName(action.getStart_workflow().getName());
    when(metadata.getWorkflowDef(any(), any())).thenReturn(def);

    ActionProcessor ap = new ActionProcessor(executor, metadata);

    EventProcessor ep = new EventProcessor(eservice, ms, ap, new TestConfiguration(), new ObjectMapper());
    assertNotNull(ep.getQueues());
    assertEquals(1, ep.getQueues().size());

    String queueEvent = ep.getQueues().keySet().iterator().next();
    assertEquals(eh.getEvent(), queueEvent);

    String epQueue = ep.getQueues().values().iterator().next();
    assertEquals(queueURI, epQueue);

    Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
    assertTrue(started.get());
}