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:org.apache.hadoop.yarn.applications.amonly.TestDistributedShell.java

public void testDSShell(boolean haveDomain) throws Exception {
    String[] args = { "--jar", APPMASTER_JAR, "--num_containers", "2", "--shell_command",
            Shell.WINDOWS ? "dir" : "ls", "--master_memory", "512", "--master_vcores", "2",
            "--container_memory", "128", "--container_vcores", "1" };
    if (haveDomain) {
        String[] domainArgs = { "--domain", "TEST_DOMAIN", "--view_acls", "reader_user reader_group",
                "--modify_acls", "writer_user writer_group", "--create" };
        List<String> argsList = new ArrayList<String>(Arrays.asList(args));
        argsList.addAll(Arrays.asList(domainArgs));
        args = argsList.toArray(new String[argsList.size()]);
    }/* w  ww . j  av a 2  s.c om*/

    LOG.info("Initializing DS Client");
    final Client client = new Client(new Configuration(yarnCluster.getConfig()));
    boolean initSuccess = client.init(args);
    Assert.assertTrue(initSuccess);
    LOG.info("Running DS Client");
    final AtomicBoolean result = new AtomicBoolean(false);
    Thread t = new Thread() {
        public void run() {
            try {
                result.set(client.run());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
    t.start();

    YarnClient yarnClient = YarnClient.createYarnClient();
    yarnClient.init(new Configuration(yarnCluster.getConfig()));
    yarnClient.start();
    String hostName = NetUtils.getHostname();

    boolean verified = false;
    String errorMessage = "";
    while (!verified) {
        List<ApplicationReport> apps = yarnClient.getApplications();
        if (apps.size() == 0) {
            Thread.sleep(10);
            continue;
        }
        ApplicationReport appReport = apps.get(0);
        if (appReport.getHost().equals("N/A")) {
            Thread.sleep(10);
            continue;
        }
        errorMessage = "Expected host name to start with '" + hostName + "', was '" + appReport.getHost()
                + "'. Expected rpc port to be '-1', was '" + appReport.getRpcPort() + "'.";
        if (checkHostname(appReport.getHost()) && appReport.getRpcPort() == -1) {
            verified = true;
        }
        if (appReport.getYarnApplicationState() == YarnApplicationState.FINISHED) {
            break;
        }
    }
    Assert.assertTrue(errorMessage, verified);
    t.join();
    LOG.info("Client run completed. Result=" + result);
    Assert.assertTrue(result.get());

    TimelineDomain domain = null;
    if (haveDomain) {
        domain = yarnCluster.getApplicationHistoryServer().getTimelineStore().getDomain("TEST_DOMAIN");
        Assert.assertNotNull(domain);
        Assert.assertEquals("reader_user reader_group", domain.getReaders());
        Assert.assertEquals("writer_user writer_group", domain.getWriters());
    }
    TimelineEntities entitiesAttempts = yarnCluster.getApplicationHistoryServer().getTimelineStore()
            .getEntities(ApplicationMaster.DSEntity.DS_APP_ATTEMPT.toString(), null, null, null, null, null,
                    null, null, null, null);
    Assert.assertNotNull(entitiesAttempts);
    Assert.assertEquals(1, entitiesAttempts.getEntities().size());
    Assert.assertEquals(2, entitiesAttempts.getEntities().get(0).getEvents().size());
    Assert.assertEquals(entitiesAttempts.getEntities().get(0).getEntityType().toString(),
            ApplicationMaster.DSEntity.DS_APP_ATTEMPT.toString());
    if (haveDomain) {
        Assert.assertEquals(domain.getId(), entitiesAttempts.getEntities().get(0).getDomainId());
    } else {
        Assert.assertEquals("DEFAULT", entitiesAttempts.getEntities().get(0).getDomainId());
    }
    TimelineEntities entities = yarnCluster.getApplicationHistoryServer().getTimelineStore().getEntities(
            ApplicationMaster.DSEntity.DS_CONTAINER.toString(), null, null, null, null, null, null, null, null,
            null);
    Assert.assertNotNull(entities);
    Assert.assertEquals(2, entities.getEntities().size());
    Assert.assertEquals(entities.getEntities().get(0).getEntityType().toString(),
            ApplicationMaster.DSEntity.DS_CONTAINER.toString());
    if (haveDomain) {
        Assert.assertEquals(domain.getId(), entities.getEntities().get(0).getDomainId());
    } else {
        Assert.assertEquals("DEFAULT", entities.getEntities().get(0).getDomainId());
    }
}

From source file:com.adaptris.core.ftp.FtpConsumerTest.java

public void testConsumeWithNonMatchingFilter() throws Exception {
    int count = 1;
    EmbeddedFtpServer helper = new EmbeddedFtpServer();
    MockMessageListener listener = new MockMessageListener();
    FileSystem filesystem = helper.createFilesystem_DirsOnly();
    for (int i = 0; i < count; i++) {
        filesystem.add(/*from  ww w.ja  va  2s  .com*/
                new FileEntry(DEFAULT_WORK_DIR_CANONICAL + SLASH + DEFAULT_FILENAME + i + ".txt", PAYLOAD));
    }
    FakeFtpServer server = helper.createAndStart(filesystem);
    StandaloneConsumer sc = null;
    try {
        ConfiguredConsumeDestination ccd = new ConfiguredConsumeDestination(SERVER_ADDRESS, "^*.xml$",
                "testConsumeWithNonMatchingFilter");
        AtomicBoolean pollFired = new AtomicBoolean(false);
        FixedIntervalPoller poller = new FixedIntervalPoller(new TimeInterval(300L, TimeUnit.MILLISECONDS))
                .withPollerCallback(e -> {
                    log.trace("Poll Fired {}", getName());
                    if (e == 0) {
                        pollFired.set(true);
                    }
                });
        FtpConsumer ftpConsumer = createForTests(listener, ccd, poller);
        ftpConsumer.setFileFilterImp(RegexFileFilter.class.getCanonicalName());
        FtpConnection consumeConnection = create(server);
        sc = new StandaloneConsumer(consumeConnection, ftpConsumer);
        start(sc);
        long waitTime = waitForPollCallback(pollFired);
        log.trace("Waited for {}ms for == 0 poll", waitTime);
        helper.assertMessages(listener.getMessages(), 0);
        assertEquals(count, filesystem.listFiles(DEFAULT_WORK_DIR_CANONICAL).size());
    } catch (Exception e) {
        throw e;
    } finally {
        stop(sc);
        server.stop();
    }
}

From source file:com.datatorrent.stram.engine.GenericNodeTest.java

@Test
public void testPrematureTermination() throws InterruptedException {
    long maxSleep = 5000;
    long sleeptime = 25L;
    GenericOperator go = new GenericOperator();
    final GenericNode gn = new GenericNode(go,
            new com.datatorrent.stram.engine.OperatorContext(0, new DefaultAttributeMap(), null));
    gn.setId(1);//from  w  ww . ja va  2  s.  c  o  m
    AbstractReservoir reservoir1 = AbstractReservoir.newReservoir("ip1Res", 1024);
    AbstractReservoir reservoir2 = AbstractReservoir.newReservoir("ip2Res", 1024);

    gn.connectInputPort("ip1", reservoir1);
    gn.connectInputPort("ip2", reservoir2);
    gn.connectOutputPort("op", Sink.BLACKHOLE);
    gn.firstWindowMillis = 0;
    gn.windowWidthMillis = 100;

    final AtomicBoolean ab = new AtomicBoolean(false);
    Thread t = new Thread() {
        @Override
        public void run() {
            ab.set(true);
            gn.activate();
            gn.run();
            gn.deactivate();
        }

    };
    t.start();

    long interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((ab.get() == false) && (interval < maxSleep));

    int controlTupleCount = gn.controlTupleCount;
    Tuple beginWindow1 = new Tuple(MessageType.BEGIN_WINDOW, 0x1L);

    reservoir1.add(beginWindow1);
    reservoir2.add(beginWindow1);

    interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((gn.controlTupleCount == controlTupleCount) && (interval < maxSleep));
    Assert.assertTrue("Begin window called", go.endWindowId != go.beginWindowId);
    controlTupleCount = gn.controlTupleCount;

    Tuple endWindow1 = new EndWindowTuple(0x1L);

    reservoir1.add(endWindow1);
    reservoir2.add(endWindow1);

    interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((gn.controlTupleCount == controlTupleCount) && (interval < maxSleep));
    Assert.assertTrue("End window called", go.endWindowId == go.beginWindowId);
    controlTupleCount = gn.controlTupleCount;

    Tuple beginWindow2 = new Tuple(MessageType.BEGIN_WINDOW, 0x2L);

    reservoir1.add(beginWindow2);
    reservoir2.add(beginWindow2);

    interval = 0;
    do {
        Thread.sleep(sleeptime);
        interval += sleeptime;
    } while ((gn.controlTupleCount == controlTupleCount) && (interval < maxSleep));

    gn.shutdown();
    t.join();

    Assert.assertTrue("End window not called", go.endWindowId != go.beginWindowId);
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

@Test
public void testConfigurationUpdate() throws IOException, GitAPIException {
    add(git, root, new File("src/test/resources/files/a.json"), "dir");
    push(git);//from   w  w w.  j av  a2  s .  c  o  m

    retriever = ConfigRetriever.create(vertx,
            new ConfigRetrieverOptions().setScanPeriod(1000).addStore(new ConfigStoreOptions().setType("git")
                    .setConfig(new JsonObject().put("url", bareRoot.getAbsolutePath())
                            .put("path", "target/junk/work").put("filesets",
                                    new JsonArray().add(new JsonObject().put("pattern", "dir/*.json"))))));

    AtomicBoolean done = new AtomicBoolean();
    retriever.getConfig(ar -> {
        assertThat(ar.succeeded()).isTrue();
        assertThat(ar.result().getString("a.name")).isEqualTo("A");
        done.set(true);
    });
    await().untilAtomic(done, is(true));

    updateA();

    await().until(() -> "A2".equals(retriever.getCachedConfig().getString("a.name"))
            && "B".equalsIgnoreCase(retriever.getCachedConfig().getString("b.name")));
}

From source file:org.eclipse.hono.application.HonoApplication.java

/**
 * Deploys all verticles the Hono server consists of.
 * //from ww w. j a  v a 2  s.  c  om
 * @return true if deployment was successful
 */
private boolean registerVerticles() {

    if (vertx == null) {
        throw new IllegalStateException("no Vert.x instance has been configured");
    }

    final CountDownLatch startupLatch = new CountDownLatch(1);
    final AtomicBoolean startupSucceeded = new AtomicBoolean(false);

    // without creating a first instance here, deployment of the HonoServer verticles fails
    // TODO: find out why
    HonoServer firstInstance = serverFactory.getHonoServer();

    final int instanceCount = honoConfig.getMaxInstances();

    Future<Void> started = Future.future();
    started.setHandler(ar -> {
        if (ar.failed()) {
            LOG.error("cannot start up HonoServer", ar.cause());
        } else {
            startupSucceeded.set(true);
        }
        startupLatch.countDown();
    });

    CompositeFuture.all(deployAuthenticationService(), // we only need 1 authentication service
            deployAuthorizationService(), // we only need 1 authorization service
            deployCredentialsService(), deployRegistrationService()).setHandler(ar -> {
                if (ar.succeeded()) {
                    deployServer(firstInstance, instanceCount, started);
                } else {
                    started.fail(ar.cause());
                }
            });

    try {
        if (startupLatch.await(honoConfig.getStartupTimeout(), TimeUnit.SECONDS)) {
            if (startupSucceeded.get()) {
                LOG.info("Hono startup completed successfully");
            } else {
                shutdown();
            }
        } else {
            LOG.error("startup timed out after {} seconds, shutting down ...", honoConfig.getStartupTimeout());
            shutdown();
            startupSucceeded.set(false);
        }
    } catch (InterruptedException e) {
        LOG.error("startup process has been interrupted, shutting down ...");
        Thread.currentThread().interrupt();
        shutdown();
        startupSucceeded.set(false);
    }
    return startupSucceeded.get();
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

@Test
public void testUsingAnExistingRepo() throws IOException, GitAPIException {
    git.close();//from  w  w  w.j  a v  a  2s  .  c  o m
    root = new File("target/junk/work");
    git = connect(bareRoot, root);
    add(git, root, new File("src/test/resources/files/a.json"), "dir");
    push(git);

    retriever = ConfigRetriever.create(vertx,
            new ConfigRetrieverOptions().setScanPeriod(1000).addStore(new ConfigStoreOptions().setType("git")
                    .setConfig(new JsonObject().put("url", bareRoot.getAbsolutePath())
                            .put("path", "target/junk/work").put("filesets",
                                    new JsonArray().add(new JsonObject().put("pattern", "dir/*.json"))))));

    AtomicBoolean done = new AtomicBoolean();
    retriever.getConfig(ar -> {
        assertThat(ar.succeeded()).isTrue();
        assertThat(ar.result().getString("a.name")).isEqualTo("A");
        done.set(true);
    });
    await().untilAtomic(done, is(true));

    updateA();

    await().until(() -> "A2".equals(retriever.getCachedConfig().getString("a.name"))
            && "B".equalsIgnoreCase(retriever.getCachedConfig().getString("b.name")));
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

@Test
public void testWithExistingRepoOnTheWrongBranch() throws Exception {
    git.close();//from   w ww  . ja va 2  s.  c  om
    root = new File("target/junk/work");
    git = connect(bareRoot, root);
    add(git, root, new File("src/test/resources/files/a.json"), "dir");
    push(git);
    branch = "dev";
    add(git, root, new File("src/test/resources/files/b.json"), "dir");
    push(git);

    retriever = ConfigRetriever.create(vertx,
            new ConfigRetrieverOptions().setScanPeriod(1000).addStore(new ConfigStoreOptions().setType("git")
                    .setConfig(new JsonObject().put("url", bareRoot.getAbsolutePath())
                            .put("path", "target/junk/work").put("filesets",
                                    new JsonArray().add(new JsonObject().put("pattern", "dir/*.json"))))));

    AtomicBoolean done = new AtomicBoolean();
    retriever.getConfig(ar -> {
        assertThat(ar.succeeded()).isTrue();
        assertThat(ar.result().getString("a.name")).isEqualTo("A");
        done.set(true);
    });
    await().untilAtomic(done, is(true));

    updateA();

    await().until(() -> "A2".equals(retriever.getCachedConfig().getString("a.name"))
            && "B".equalsIgnoreCase(retriever.getCachedConfig().getString("b.name")));
}

From source file:org.apache.tinkerpop.gremlin.server.GremlinServerIntegrateTest.java

@Test
public void shouldReturnInvalidRequestArgsWhenInvalidReservedBindingKeyIsUsed() throws Exception {
    try (SimpleClient client = new WebSocketClient()) {
        final Map<String, Object> bindings = new HashMap<>();
        bindings.put(T.id.getAccessor(), "123");
        final RequestMessage request = RequestMessage.build(Tokens.OPS_EVAL)
                .addArg(Tokens.ARGS_GREMLIN, "[1,2,3,4,5,6,7,8,9,0]").addArg(Tokens.ARGS_BINDINGS, bindings)
                .create();// www. j a v a 2s.  c o  m
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean pass = new AtomicBoolean(false);
        client.submit(request, result -> {
            if (result.getStatus().getCode() != ResponseStatusCode.PARTIAL_CONTENT) {
                pass.set(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS == result.getStatus()
                        .getCode());
                latch.countDown();
            }
        });

        if (!latch.await(3000, TimeUnit.MILLISECONDS))
            fail("Request should have returned error, but instead timed out");
        assertTrue(pass.get());
    }
}

From source file:org.apache.tinkerpop.gremlin.server.GremlinServerIntegrateTest.java

@Test
public void shouldReturnInvalidRequestArgsWhenInvalidTypeBindingKeyIsUsed() throws Exception {
    try (SimpleClient client = new WebSocketClient()) {
        final Map<Object, Object> bindings = new HashMap<>();
        bindings.put(1, "123");
        final RequestMessage request = RequestMessage.build(Tokens.OPS_EVAL)
                .addArg(Tokens.ARGS_GREMLIN, "[1,2,3,4,5,6,7,8,9,0]").addArg(Tokens.ARGS_BINDINGS, bindings)
                .create();/*from   w w w. jav  a2 s . c  om*/
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean pass = new AtomicBoolean(false);
        client.submit(request, result -> {
            if (result.getStatus().getCode() != ResponseStatusCode.PARTIAL_CONTENT) {
                pass.set(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS == result.getStatus()
                        .getCode());
                latch.countDown();
            }
        });

        if (!latch.await(3000, TimeUnit.MILLISECONDS))
            fail("Request should have returned error, but instead timed out");
        assertTrue(pass.get());
    }
}

From source file:org.apache.tinkerpop.gremlin.server.GremlinServerIntegrateTest.java

@Test
public void shouldReturnInvalidRequestArgsWhenInvalidNullBindingKeyIsUsed() throws Exception {
    try (SimpleClient client = new WebSocketClient()) {
        final Map<String, Object> bindings = new HashMap<>();
        bindings.put(null, "123");
        final RequestMessage request = RequestMessage.build(Tokens.OPS_EVAL)
                .addArg(Tokens.ARGS_GREMLIN, "[1,2,3,4,5,6,7,8,9,0]").addArg(Tokens.ARGS_BINDINGS, bindings)
                .create();/*w  ww.  j a v a 2  s .c  om*/
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicBoolean pass = new AtomicBoolean(false);
        client.submit(request, result -> {
            if (result.getStatus().getCode() != ResponseStatusCode.PARTIAL_CONTENT) {
                pass.set(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS == result.getStatus()
                        .getCode());
                latch.countDown();
            }
        });

        if (!latch.await(3000, TimeUnit.MILLISECONDS))
            fail("Request should have returned error, but instead timed out");
        assertTrue(pass.get());
    }
}