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

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

Introduction

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

Prototype

public final void set(boolean newValue) 

Source Link

Document

Sets the value to newValue , with memory effects as specified by VarHandle#setVolatile .

Usage

From source file:fr.wseduc.webutils.email.SendInBlueSender.java

@Override
protected void sendEmail(JsonObject json, final Handler<Message<JsonObject>> handler) {
    if (json == null || json.getArray("to") == null || json.getString("from") == null
            || json.getString("subject") == null || json.getString("body") == null) {
        handler.handle(new ResultMessage().error("invalid.parameters"));
        return;/*from   w  w w.ja  va 2s .co  m*/
    }
    if (splitRecipients && json.getArray("to").size() > 1) {
        final AtomicInteger count = new AtomicInteger(json.getArray("to").size());
        final AtomicBoolean success = new AtomicBoolean(true);
        final JsonArray errors = new JsonArray();
        final Handler<Message<JsonObject>> h = new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> message) {
                if (!"ok".equals(message.body().getString("status"))) {
                    success.set(false);
                    errors.addString(message.body().getString("message"));
                }
                if (count.decrementAndGet() == 0) {
                    if (success.get()) {
                        handler.handle(new ResultMessage());
                    } else {
                        handler.handle(new ResultMessage().error(errors.encode()));
                    }
                }
            }
        };
        for (Object to : json.getArray("to")) {
            send(json.copy().putArray("to", new JsonArray().addString(to.toString())), h);
        }
    } else {
        send(json, handler);
    }
}

From source file:de.jackwhite20.japs.client.cache.impl.PubSubCacheImpl.java

@Override
public Future<Boolean> has(String key) {

    if (key == null || key.isEmpty()) {
        throw new IllegalArgumentException("key cannot be null or empty");
    }/*  w  ww .j av a 2 s  . c  o m*/

    return executorService.submit(() -> {

        int id = CALLBACK_COUNTER.getAndIncrement();

        AtomicBoolean has = new AtomicBoolean(false);

        CountDownLatch countDownLatch = new CountDownLatch(1);

        callbacks.put(id, new Consumer<JSONObject>() {

            @Override
            public void accept(JSONObject jsonObject) {

                has.set(jsonObject.getBoolean("has"));

                countDownLatch.countDown();
            }
        });

        JSONObject jsonObject = new JSONObject().put("op", OpCode.OP_CACHE_HAS.getCode()).put("key", key)
                .put("id", id);

        write(jsonObject);

        countDownLatch.await();

        return has.get();
    });
}

From source file:org.piraso.server.service.ResponseLoggerServiceImplTest.java

@Test
public void testWaitAndStop() throws Exception {
    final AtomicBoolean fail = new AtomicBoolean(false);
    ExecutorService executor = Executors.newFixedThreadPool(2);

    Runnable startServiceRunnable = new Runnable() {
        public void run() {
            try {
                service.start();//from  ww w.  j  ava  2 s. c  o m
            } catch (Exception e) {
                fail.set(true);
                e.printStackTrace();
            }
        }
    };

    Runnable logMessagesRunnable = new Runnable() {
        public void run() {
            try {

                service.stopAndWait(3000l);
            } catch (Exception e) {
                fail.set(true);
                e.printStackTrace();
            }
        }
    };

    Future future = executor.submit(startServiceRunnable);
    executor.submit(logMessagesRunnable);

    future.get();
    executor.shutdown();

    if (fail.get()) {
        fail("failure see exception trace.");
    }

    // no harm invoking it again
    service.stopAndWait(1000l);

    assertFalse(service.isAlive());
}

From source file:ch.cyberduck.core.sftp.auth.SFTPPublicKeyAuthenticationTest.java

@Test(expected = LoginFailureException.class)
public void testAuthenticateOpenSSHKeyWithPassword() throws Exception {
    final Credentials credentials = new Credentials(System.getProperties().getProperty("sftp.user"), "");
    final Local key = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    try {//from w w  w. j a v  a 2  s.c o  m
        credentials.setIdentity(key);
        new DefaultLocalTouchFeature().touch(key);
        IOUtils.copy(new StringReader(System.getProperties().getProperty("sftp.key.openssh.rsa")),
                key.getOutputStream(false), Charset.forName("UTF-8"));
        final Host host = new Host(new SFTPProtocol(), "test.cyberduck.ch", credentials);
        final SFTPSession session = new SFTPSession(host);
        session.open(new DisabledHostKeyCallback());
        final AtomicBoolean b = new AtomicBoolean();
        assertTrue(new SFTPPublicKeyAuthentication(session).authenticate(host, new DisabledPasswordStore(),
                new DisabledLoginCallback() {
                    @Override
                    public Credentials prompt(final Host bookmark, String username, String title, String reason,
                            LoginOptions options) throws LoginCanceledException {
                        b.set(true);
                        throw new LoginCanceledException();
                    }
                }, new DisabledCancelCallback()));
        assertTrue(b.get());
        session.close();
    } finally {
        key.delete();
    }
}

From source file:ch.cyberduck.core.sftp.auth.SFTPPublicKeyAuthenticationTest.java

@Test(expected = LoginFailureException.class)
public void testAuthenticatePuTTYKeyWithWrongPassword() throws Exception {
    final Credentials credentials = new Credentials(System.getProperties().getProperty("sftp.user"), "");
    final Local key = new Local(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    try {// www .  j  a va  2s  .  c  o  m
        credentials.setIdentity(key);
        new DefaultLocalTouchFeature().touch(key);
        IOUtils.copy(new StringReader(System.getProperties().getProperty("sftp.key.putty")),
                key.getOutputStream(false), Charset.forName("UTF-8"));
        final Host host = new Host(new SFTPProtocol(), "test.cyberduck.ch", credentials);
        final SFTPSession session = new SFTPSession(host);
        session.open(new DisabledHostKeyCallback());
        final AtomicBoolean p = new AtomicBoolean();
        assertFalse(new SFTPPublicKeyAuthentication(session).authenticate(host, new DisabledPasswordStore(),
                new DisabledLoginCallback() {
                    @Override
                    public Credentials prompt(final Host bookmark, String username, String title, String reason,
                            LoginOptions options) throws LoginCanceledException {
                        p.set(true);
                        throw new LoginCanceledException();
                    }
                }, new DisabledCancelCallback()));
        assertTrue(p.get());
        session.close();
    } finally {
        key.delete();
    }
}

From source file:com.nesscomputing.jackson.datatype.TestCustomUuidModule.java

@Test
public void testCustomUUIDSerialization() throws Exception {
    final AtomicBoolean called = new AtomicBoolean(false);
    ObjectMapper mapper = getObjectMapper(new AbstractModule() {
        @Override/*from   www .  j ava 2s.co  m*/
        protected void configure() {
            bind(new TypeLiteral<JsonSerializer<UUID>>() {
            }).toInstance(new CustomUuidSerializer() {
                @Override
                public void serialize(UUID value, JsonGenerator jgen, SerializerProvider provider)
                        throws IOException, JsonGenerationException {
                    called.set(true);
                    super.serialize(value, jgen, provider);
                }
            });
        }
    });
    final UUID id = new UUID(9, 9);
    Assert.assertEquals('"' + id.toString() + '"', mapper.writeValueAsString(id));
    Assert.assertTrue(called.get());
}

From source file:org.apache.bookkeeper.metadata.etcd.Etcd64bitIdGeneratorTest.java

/**
 * Test generating id in parallel and ensure there is no duplicated id.
 *///w  w w  .  j  ava  2s.c o  m
@Test
public void testGenerateIdParallel() throws Exception {
    final int numThreads = 10;
    @Cleanup("shutdown")
    ExecutorService executor = Executors.newFixedThreadPool(numThreads);

    final int numIds = 10000;
    final AtomicLong totalIds = new AtomicLong(numIds);
    final Set<Long> ids = Collections.newSetFromMap(new ConcurrentHashMap<>());
    final RateLimiter limiter = RateLimiter.create(1000);
    final CompletableFuture<Void> doneFuture = new CompletableFuture<>();
    for (int i = 0; i < numThreads; i++) {
        executor.submit(() -> {
            Client client = Client.builder().endpoints(etcdContainer.getClientEndpoint()).build();
            Etcd64bitIdGenerator gen = new Etcd64bitIdGenerator(client.getKVClient(), scope);

            AtomicBoolean running = new AtomicBoolean(true);

            while (running.get()) {
                limiter.acquire();

                GenericCallbackFuture<Long> genFuture = new GenericCallbackFuture<>();
                gen.generateLedgerId(genFuture);

                genFuture.thenAccept(lid -> {
                    boolean duplicatedFound = !(ids.add(lid));
                    if (duplicatedFound) {
                        running.set(false);
                        doneFuture.completeExceptionally(
                                new IllegalStateException("Duplicated id " + lid + " generated : " + ids));
                        return;
                    } else {
                        if (totalIds.decrementAndGet() <= 0) {
                            running.set(false);
                            doneFuture.complete(null);
                        }
                    }
                }).exceptionally(cause -> {
                    running.set(false);
                    doneFuture.completeExceptionally(cause);
                    return null;
                });
            }
        });
    }

    FutureUtils.result(doneFuture);
    assertTrue(totalIds.get() <= 0);
    assertTrue(ids.size() >= numIds);
}

From source file:com.adaptris.core.fs.NonDeletingFsConsumerTest.java

public void testRedmine481_SubDirInConsumeDirectory() throws Exception {
    String consumeDir = new GuidGenerator().safeUUID();
    File parentDir = FsHelper/*from  w w w .  j ava  2  s. c o m*/
            .createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_KEY), true));
    File subDirectory = FsHelper.createFileReference(FsHelper.createUrlFromString(
            PROPERTIES.getProperty(BASE_KEY) + "/" + consumeDir + "/" + new GuidGenerator().safeUUID(), true));
    subDirectory.mkdirs();
    NonDeletingFsConsumer fs = createConsumer(consumeDir, "testRedmine481_SubDirInConsumeDirectory");
    fs.setReacquireLockBetweenMessages(true);
    AtomicBoolean pollFired = new AtomicBoolean(false);
    fs.setPoller(
            new FixedIntervalPoller(new TimeInterval(300L, TimeUnit.MILLISECONDS)).withPollerCallback(e -> {
                pollFired.set(true);
            }));
    MockMessageListener stub = new MockMessageListener(0);
    StandaloneConsumer sc = new StandaloneConsumer(fs);
    sc.registerAdaptrisMessageListener(stub);
    try {
        start(sc);
        waitForPollCallback(pollFired);
        assertEquals(true, subDirectory.exists());
        assertEquals(true, subDirectory.isDirectory());
    } finally {
        stop(sc);
        FileUtils.deleteQuietly(new File(parentDir, consumeDir));
    }
}

From source file:biz.ganttproject.impex.csv.CsvImportTest.java

public void testIncompleteHeader() throws IOException {
    String header = "A, B";
    String data = "a1, b1";
    final AtomicBoolean wasCalled = new AtomicBoolean(false);
    RecordGroup recordGroup = new RecordGroup("ABC", ImmutableSet.<String>of("A", "B", "C"), // all fields
            ImmutableSet.<String>of("A", "B")) { // mandatory fields
        @Override//from   w  w  w  .j  av a  2s  .c o m
        protected boolean doProcess(CSVRecord record) {
            if (!super.doProcess(record)) {
                return false;
            }
            wasCalled.set(true);
            assertEquals("a1", record.get("A"));
            assertEquals("b1", record.get("B"));
            return true;
        }
    };
    GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(header, data)), recordGroup);
    importer.load();
    assertTrue(wasCalled.get());
}

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();// w w w  .  j  av a 2  s.  c o  m

    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);
}