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:com.netflix.spinnaker.orca.clouddriver.tasks.providers.aws.AmazonImageTagger.java

/**
 * Return true iff the tags on the current machine image match the desired.
 */// ww w. ja  v  a  2  s . c  om
@Override
public boolean areImagesTagged(Collection<Image> targetImages, Stage stage) {
    Collection<MatchedImage> matchedImages = findImages(
            targetImages.stream().map(targetImage -> targetImage.imageName).collect(Collectors.toList()),
            stage);

    AtomicBoolean isUpserted = new AtomicBoolean(true);
    for (Image targetImage : targetImages) {
        targetImage.regions.forEach(region -> {
            MatchedImage matchedImage = matchedImages.stream()
                    .filter(m -> m.imageName.equals(targetImage.imageName)).findFirst().orElse(null);

            if (matchedImage == null) {
                isUpserted.set(false);
                return;
            }

            List<String> imagesForRegion = matchedImage.amis.get(region);
            imagesForRegion.forEach(image -> {
                Map<String, String> allImageTags = matchedImage.tagsByImageId.get(image);
                targetImage.tags.entrySet().forEach(entry -> {
                    // assert tag equality
                    isUpserted
                            .set(isUpserted.get() && entry.getValue().equals(allImageTags.get(entry.getKey())));
                });
            });
        });
    }

    return isUpserted.get();
}

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

/**
 * Tests if an interceptor can be used to manipulate a request before
 * it is sent/*from   w  ww . j  a v  a2s .  c o m*/
 * @throws Exception if anything goes wrong
 */
@Test
public void interceptRequest() throws Exception {
    final AtomicBoolean interceptorCalled = new AtomicBoolean(false);

    Download t = makeProjectAndTask();
    t.src(makeSrc(INTERCEPTOR));
    File dst = folder.newFile();
    t.dest(dst);
    t.requestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            assertFalse(interceptorCalled.get());
            interceptorCalled.set(true);
            request.addHeader(ADDITIONAL_REQUEST_HEADER_KEY, ADDITIONAL_REQUEST_HEADER_VALUE);
        }
    });
    t.execute();

    assertTrue(interceptorCalled.get());

    String dstContents = FileUtils.readFileToString(dst);
    assertEquals(UNINTERCEPTED + ":" + ADDITIONAL_REQUEST_HEADER_VALUE, dstContents);
}

From source file:net.mwplay.cocostudio.ui.junit.LibgdxRunner.java

@Override
protected void runChild(final FrameworkMethod method, final RunNotifier notifier) {
    final Description description = describeChild(method);
    if (description.getAnnotation(NeedGL.class) != null) {
        final AtomicBoolean running = new AtomicBoolean(true);
        Gdx.app.postRunnable(new Runnable() {
            @Override/*from   www  . j a  va 2 s.  com*/
            public void run() {
                if (LibgdxRunner.this.isIgnored(method)) {
                    notifier.fireTestIgnored(description);
                } else {
                    LibgdxRunner.this.runLeaf(methodBlock(method), description, notifier);
                }
                running.set(false);
            }
        });
        ConditionWaiter.wait(new Condition() {
            @Override
            public Boolean check() {
                return !running.get();
            }
        }, description, 30, new Runnable() {
            @Override
            public void run() {
                LibgdxRunner.this.closeGdxApplication();
            }
        });
    } else {
        runLeaf(methodBlock(method), description, notifier);
    }
}

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  .  j a v a  2s .  c  o  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:ch.cyberduck.core.sds.SDSMissingFileKeysSchedulerFeatureTest.java

@Test(expected = LoginCanceledException.class)
public void testWrongPassword() throws Exception {
    final Host host = new Host(new SDSProtocol(), "duck.ssp-europe.eu", new Credentials(
            System.getProperties().getProperty("sds.user"), System.getProperties().getProperty("sds.key")));
    final SDSSession session = new SDSSession(host, new DisabledX509TrustManager(),
            new DefaultX509KeyManager());
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final SDSMissingFileKeysSchedulerFeature background = new SDSMissingFileKeysSchedulerFeature(session);
    final AtomicBoolean prompt = new AtomicBoolean();
    final List<UserFileKeySetRequest> processed = background.operate(new PasswordCallback() {
        @Override/*w ww.j  a  v  a  2  s .c o m*/
        public Credentials prompt(final Host bookmark, final String title, final String reason,
                final LoginOptions options) throws LoginCanceledException {
            if (prompt.get()) {
                throw new LoginCanceledException();
            }
            prompt.set(true);
            return new VaultCredentials("n");
        }
    }, null);
    assertTrue(prompt.get());
    session.close();
}

From source file:dk.netarkivet.common.utils.ProcessUtils.java

/** Wait for the end of a process, but only for a limited time.  This
 * method takes care of the ways waitFor can get interrupted.
 *
 * @param p Process to wait for//from  www.  j a v  a 2 s. c o  m
 * @param maxWait The maximum number of milliseconds to wait for the
 * process to exit.
 * @return Exit value for process, or null if the process didn't exit
 * within the expected time.
 */
public static Integer waitFor(final Process p, long maxWait) {
    ArgumentNotValid.checkNotNull(p, "Process p");
    ArgumentNotValid.checkPositive(maxWait, "long maxWait");
    long startTime = System.currentTimeMillis();
    Timer timer = new Timer(true);
    final Thread waitThread = Thread.currentThread();
    boolean wakeupScheduled = false;
    final AtomicBoolean doneWaiting = new AtomicBoolean(false);
    while (System.currentTimeMillis() < startTime + maxWait) {
        try {
            if (!wakeupScheduled) {
                // First time in here, we need to start the wakup thread,
                // but be sure it doesn't notify us too early or too late.
                synchronized (waitThread) {
                    timer.schedule(new TimerTask() {
                        public void run() {
                            synchronized (waitThread) {
                                if (!doneWaiting.get()) {
                                    waitThread.interrupt();
                                }
                            }
                        }
                    }, maxWait);
                    wakeupScheduled = true;
                }
            }

            p.waitFor();
            break;
        } catch (InterruptedException e) {
            // May happen for a number of reasons.  We just check if we've
            // timed out yet when we go through the loop again.
        }
    }
    synchronized (waitThread) {
        timer.cancel();
        doneWaiting.set(true);
        Thread.interrupted(); // In case the timer task interrupted.
    }
    try {
        return p.exitValue();
    } catch (IllegalThreadStateException e) {
        log.warn("Process '" + p + "' did not exit within " + (System.currentTimeMillis() - startTime)
                + " milliseconds");
        return null;
    }
}

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

public void testSkipLinesWithEmptyMandatoryFields() throws IOException {
    String header = "A, B, C";
    String data1 = "a1,,c1";
    String data2 = "a2,b2,c2";
    String data3 = ",b3,c3";
    final AtomicBoolean wasCalled = new AtomicBoolean(false);
    GanttCSVOpen.RecordGroup recordGroup = new GanttCSVOpen.RecordGroup("ABC",
            ImmutableSet.<String>of("A", "B", "C"), ImmutableSet.<String>of("A", "B")) {
        @Override//from  w w  w. java 2 s . c o m
        protected boolean doProcess(CSVRecord record) {
            if (!hasMandatoryFields(record)) {
                return false;
            }
            wasCalled.set(true);
            assertEquals("a2", record.get("A"));
            assertEquals("b2", record.get("B"));
            return true;
        }
    };
    GanttCSVOpen importer = new GanttCSVOpen(createSupplier(Joiner.on('\n').join(header, data1, data2, data3)),
            recordGroup);
    importer.load();
    assertTrue(wasCalled.get());
    assertEquals(2, importer.getSkippedLineCount());
}

From source file:io.pravega.client.stream.impl.ReaderGroupStateManager.java

/**
 * Add this reader to the reader group so that it is able to acquire segments
 *///from  w w  w . ja v  a  2  s . c  o m
void initializeReader(long initialAllocationDelay) {
    AtomicBoolean alreadyAdded = new AtomicBoolean(false);
    sync.updateState(state -> {
        if (state.getSegments(readerId) == null) {
            return Collections.singletonList(new AddReader(readerId));
        } else {
            alreadyAdded.set(true);
            return null;
        }
    });
    if (alreadyAdded.get()) {
        throw new IllegalStateException("The requested reader: " + readerId
                + " cannot be added to the group because it is already in the group. Perhaps close() was not called?");
    }
    long randomDelay = (long) (RandomUtils.nextFloat()
            * Math.min(initialAllocationDelay, sync.getState().getConfig().getGroupRefreshTimeMillis()));
    acquireTimer.reset(Duration.ofMillis(initialAllocationDelay + randomDelay));
}

From source file:com.netflix.curator.framework.imps.TestFrameworkEdges.java

@Test
public void testSessionKilled() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();/*from   w w  w  . j  a  va  2  s.  c  o m*/
    try {
        client.create().forPath("/sessionTest");

        final AtomicBoolean sessionDied = new AtomicBoolean(false);
        Watcher watcher = new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == Event.KeeperState.Expired) {
                    sessionDied.set(true);
                }
            }
        };
        client.checkExists().usingWatcher(watcher).forPath("/sessionTest");
        KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString());
        Assert.assertNotNull(client.checkExists().forPath("/sessionTest"));
        Assert.assertTrue(sessionDied.get());
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:de.acosix.alfresco.site.hierarchy.repo.integration.ManagementViaWebScriptsTest.java

protected void checkSiteInTopLevelSites(final WebTarget webTarget, final Object ticket,
        final String siteShortName, final boolean expectation) {
    final TopLevelSites topLevelSites = webTarget.path("/acosix/api/sites/topLevelSites")
            .queryParam("alf_ticket", ticket).request(MediaType.APPLICATION_JSON).get(TopLevelSites.class);

    Assert.assertNotNull("List of top-level sites should never be null", topLevelSites.getSites());
    if (expectation) {
        Assert.assertFalse("List of top-level sites should not be empty", topLevelSites.getSites().isEmpty());
    }/*w w w  .j a  v a2  s  . c  om*/

    final AtomicBoolean containsSite = new AtomicBoolean(false);
    topLevelSites.getSites().forEach(site -> {
        if (site.getShortName().equals(siteShortName)) {
            containsSite.set(true);
        }
    });
    Assert.assertEquals("Site top-level status listing does not match expectation", expectation,
            containsSite.get());
}