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

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

Introduction

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

Prototype

public final boolean get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:info.archinnov.achilles.it.TestJSONCall.java

@Test
public void should_insert_json_if_not_exists() throws Exception {
    //Given//from   www . j  a v  a  2  s.  c o  m
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);

    //When
    String json = "{\"id\": " + id + ", \"clust\": 1, \"value\": \"val\", " + "\"liststring\": [\"one\"], "
            + "\"setstring\": [\"two\"], " + "\"mapstring\": {\"3\": \"three\"}" + "}";

    AtomicBoolean success = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    manager.crud().insertJSON(json).ifNotExists().withLwtResultListener(new LWTResultListener() {

        @Override
        public void onSuccess() {
            success.getAndSet(true);
            latch.countDown();
        }

        @Override
        public void onError(LWTResult lwtResult) {
            latch.countDown();
        }
    }).execute();

    //Then
    latch.await();
    assertThat(success.get()).isTrue();
    final Row row = session.execute(
            "SELECT * FROM achilles_embedded.entity_for_json_function_call WHERE id = " + id + "AND clust = 1")
            .one();
    assertThat(row).isNotNull();
    assertThat(row.getString("value")).isEqualTo("val");
    assertThat(row.getList("liststring", String.class)).containsExactly("one");
    assertThat(row.getSet("setstring", String.class)).containsExactly("two");
    assertThat(row.getMap("mapstring", Integer.class, String.class)).hasSize(1).containsEntry(3, "three");
}

From source file:net.sourceforge.ganttproject.io.CsvImportTest.java

public void testSkipUntilFirstHeader() throws IOException {
    String notHeader = "FOO, BAR, A";
    String header = "A, B";
    String data = "a1, b1";
    final AtomicBoolean wasCalled = new AtomicBoolean(false);
    GanttCSVOpen.RecordGroup recordGroup = new GanttCSVOpen.RecordGroup("ABC",
            ImmutableSet.<String>of("A", "B")) {
        @Override/*from  w  w w .ja  v a2  s.c  o m*/
        protected boolean doProcess(CSVRecord record) {
            wasCalled.set(true);
            assertEquals("a1", record.get("A"));
            assertEquals("b1", record.get("B"));
            return true;
        }
    };
    GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(notHeader, header, data)),
            recordGroup);
    importer.load();
    assertTrue(wasCalled.get());
    assertEquals(1, importer.getSkippedLineCount());
}

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. j a  v  a  2s  . c  o 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:io.pravega.controller.task.Stream.StreamMetadataTasks.java

private CompletionStage<Void> checkDone(Supplier<CompletableFuture<Boolean>> condition) {
    AtomicBoolean isDone = new AtomicBoolean(false);
    return Futures.loop(() -> !isDone.get(),
            () -> Futures.delayedFuture(condition, 100, executor).thenAccept(isDone::set), executor);
}

From source file:org.apache.hadoop.hbase.ipc.TestAsyncIPC.java

@Test
public void testAsyncConnectionSetup() throws Exception {
    TestRpcServer rpcServer = new TestRpcServer();
    AsyncRpcClient client = createRpcClient(CONF);
    try {//from  w  ww .  j a  v  a 2s . com
        rpcServer.start();
        InetSocketAddress address = rpcServer.getListenerAddress();
        MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
        EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();

        RpcChannel channel = client.createRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                User.getCurrent(), 0);

        final AtomicBoolean done = new AtomicBoolean(false);

        channel.callMethod(md, new PayloadCarryingRpcController(), param, md.getOutputType().toProto(),
                new RpcCallback<Message>() {
                    @Override
                    public void run(Message parameter) {
                        done.set(true);
                    }
                });

        TEST_UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
            @Override
            public boolean evaluate() throws Exception {
                return done.get();
            }
        });
    } finally {
        client.close();
        rpcServer.stop();
    }
}

From source file:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java

/**
 * Test method for executing Hadoop job.
 *//*ww w  . j  a v a  2 s.c om*/
@Test
public void executeJob_simple() {
    prepareJobflow();
    AtomicBoolean call = new AtomicBoolean();
    MockHadoopJob.callback((args, conf) -> {
        call.set(true);
        return 0;
    });

    JobExecutor executor = new InProcessJobExecutor(context);
    try {
        executor.execute(job(MockHadoopJob.class.getName()), Collections.emptyMap());
    } catch (IOException e) {
        throw new AssertionError(e);
    }
    assertThat(call.get(), is(true));
}

From source file:com.alibaba.wasp.client.TestAdmin.java

/**
 * Modify table is async so wait on completion of the table operation in
 * master.//from   w ww . j  av  a  2 s .  co m
 * 
 * @param tableName
 * @param htd
 * @throws java.io.IOException
 */
private void modifyTable(final byte[] tableName, final FTable htd) throws IOException {
    FMasterServices services = TEST_UTIL.getMiniWaspCluster().getMaster();
    ExecutorService executor = services.getExecutorService();
    AtomicBoolean done = new AtomicBoolean(false);
    executor.registerListener(EventType.C_M_MODIFY_TABLE, new DoneListener(done));
    admin.modifyTable(tableName, htd);
    while (!done.get()) {
        synchronized (done) {
            try {
                done.wait(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    executor.unregisterListener(EventType.C_M_MODIFY_TABLE);
}

From source file:com.igormaznitsa.jcp.context.PreprocessingState.java

@Nonnull
public TextFileDataContainer openFile(@Nonnull final File file) throws IOException {
    assertNotNull("The file is null", file);

    final AtomicBoolean endedByNextLineContainer = new AtomicBoolean();

    final String[] texts = PreprocessorUtils.readWholeTextFileIntoArray(file, globalInCharacterEncoding,
            endedByNextLineContainer);//w  ww  .j  a va2s.  c  om
    final TextFileDataContainer newContainer = new TextFileDataContainer(file, texts,
            endedByNextLineContainer.get(), 0);
    includeStack.push(newContainer);
    return newContainer;
}

From source file:org.apache.nifi.processors.windows.event.log.ConsumeWindowsEventLogTest.java

@Test(timeout = 10 * 1000)
public void testProcessesBlockedEvents() throws UnsupportedEncodingException {
    testRunner.setProperty(ConsumeWindowsEventLog.MAX_EVENT_QUEUE_SIZE, "1");
    testRunner.run(1, false, true);//from   w ww .  j a v  a  2  s.  c o m
    EventSubscribeXmlRenderingCallback renderingCallback = getRenderingCallback();

    List<String> eventXmls = Arrays.asList("one", "two", "three", "four", "five", "six");
    List<WinNT.HANDLE> eventHandles = mockEventHandles(wEvtApi, kernel32, eventXmls);
    AtomicBoolean done = new AtomicBoolean(false);
    new Thread(() -> {
        for (WinNT.HANDLE eventHandle : eventHandles) {
            renderingCallback.onEvent(WEvtApi.EvtSubscribeNotifyAction.DELIVER, null, eventHandle);
        }
        done.set(true);
    }).start();

    // Wait until the thread has really started
    while (testRunner.getFlowFilesForRelationship(ConsumeWindowsEventLog.REL_SUCCESS).size() == 0) {
        testRunner.run(1, false, false);
    }

    // Process rest of events
    while (!done.get()) {
        testRunner.run(1, false, false);
    }

    testRunner.run(1, true, false);

    List<MockFlowFile> flowFilesForRelationship = testRunner
            .getFlowFilesForRelationship(ConsumeWindowsEventLog.REL_SUCCESS);
    assertEquals(eventXmls.size(), flowFilesForRelationship.size());
    for (int i = 0; i < eventXmls.size(); i++) {
        flowFilesForRelationship.get(i).assertContentEquals(eventXmls.get(i));
    }
}

From source file:org.lendingclub.mercator.solarwinds.SolarwindsScanner.java

public void getNodeInformation() {
    try {/*  w  w w  .  j  a  v  a 2  s.  c om*/
        ObjectNode response = querySolarwinds("SELECT Nodes.NodeID, Nodes.SysName, Nodes.Caption, "
                + "Nodes.Description, Nodes.IOSVersion, Nodes.CustomProperties.SerialNumber, Nodes.MachineType, "
                + "Nodes.Vendor, Nodes.IPAddress, Nodes.SysObjectID, Nodes.DNS, Nodes.ObjectSubType, "
                + "Nodes.Status, Nodes.StatusDescription, Nodes.CustomProperties.Department, Nodes.Location,"
                + " Nodes.CustomProperties.City FROM Orion.Nodes ORDER BY Nodes.SysName");

        AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE);
        AtomicBoolean error = new AtomicBoolean(false);
        response.path("results").forEach(v -> {
            try {
                //solarwindsID is the hashedURL+nodeID
                getProjector().getNeoRxClient().execCypher(
                        "merge(a: SolarwindsNode {solarwindsID:{solarwindsID}}) set a+={props}, a.updateTs=timestamp() return a",
                        "solarwindsID", solarwindsScannerBuilder.hashURL + v.path("NodeID"), "props",
                        flattenNode(v)).blockingFirst(MissingNode.getInstance());
            } catch (Exception e) {
                logger.warn("problem", e);
                error.set(true);
            }

        });
        if (error.get() == false) {
            getNeoRxClient().execCypher(
                    "match(a: SolarwindsNode) where a.solarwindsID={solarwindsID} and  a.updateTs<{cutoff} detach delete a",
                    "solarwindsID", solarwindsScannerBuilder.hashURL, "cutoff", earlistUpdate.get());
        }
    } catch (Exception e) {
        logger.info(e.toString());
    }
}