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.clank.launcher.swing.SwingHelper.java

/**
 * Asks the user a binary yes or no question.
 *
 * @param parentComponent the component/*from  w  ww .  j  a  v  a2s.  co m*/
 * @param message the message to display
 * @param title the title string for the dialog
 * @return whether 'yes' was selected
 */
public static boolean confirmDialog(final Component parentComponent, @NonNull final String message,
        @NonNull final String title) {
    if (SwingUtilities.isEventDispatchThread()) {
        return JOptionPane.showConfirmDialog(parentComponent, message, title,
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
    } else {
        // Use an AtomicBoolean to pass the result back from the
        // Event Dispatcher Thread
        final AtomicBoolean yesSelected = new AtomicBoolean();

        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    yesSelected.set(confirmDialog(parentComponent, title, message));
                }
            });
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        return yesSelected.get();
    }
}

From source file:com.opinionlab.woa.WallOfAwesome.java

private static Handler<RoutingContext> makeDownloadRoute() {
    return routingContext -> EXECUTOR.execute(() -> {
        try {//from ww w  .  j a va 2s. com
            final HttpServerResponse response = routingContext.response();
            final AtomicBoolean first = new AtomicBoolean(true);
            response.putHeader("Content-Type", "text/plain");
            response.putHeader("Content-Disposition", "inline;filename=awesome.txt");

            response.setChunked(true);
            response.write("BEGIN AWESOME\n\n");
            AwesomeImap.fetchAwesome().forEach(awesome -> {
                if (!first.get()) {
                    response.write("\n\n---\n\n");
                } else {
                    first.set(false);
                }

                response.write(new ST(AWESOME_TEMPLATE).add("awesome", awesome).render());
            });
            response.write("\n\nEND AWESOME");
            response.end();
        } catch (Throwable t) {
            LOGGER.error("Unable to fetch messages.", t);
        }
    });
}

From source file:android.support.test.espresso.contrib.DrawerActions.java

/**
 * Returns true if the given matcher matches the drawer.
 *//*from w ww .  j  a  v  a2s  .  co  m*/
private static boolean checkDrawer(int drawerLayoutId, final Matcher<View> matcher) {
    final AtomicBoolean matches = new AtomicBoolean(false);
    onView(withId(drawerLayoutId)).perform(new ViewAction() {

        @Override
        public Matcher<View> getConstraints() {
            return isAssignableFrom(DrawerLayout.class);
        }

        @Override
        public String getDescription() {
            return "check drawer";
        }

        @Override
        public void perform(UiController uiController, View view) {
            matches.set(matcher.matches(view));
        }
    });
    return matches.get();
}

From source file:org.apache.accumulo.test.functional.FunctionalTestUtils.java

public static void createRFiles(final AccumuloClient c, final FileSystem fs, String path, int rows, int splits,
        int threads) throws Exception {
    fs.delete(new Path(path), true);
    ExecutorService threadPool = Executors.newFixedThreadPool(threads);
    final AtomicBoolean fail = new AtomicBoolean(false);
    for (int i = 0; i < rows; i += rows / splits) {
        TestIngest.IngestParams params = new TestIngest.IngestParams(c.properties());
        params.outputFile = String.format("%s/mf%s", path, i);
        params.random = 56;/* w  w  w  .j  a v  a2s.com*/
        params.timestamp = 1;
        params.dataSize = 50;
        params.rows = rows / splits;
        params.startRow = i;
        params.cols = 1;
        threadPool.execute(() -> {
            try {
                TestIngest.ingest(c, fs, params);
            } catch (Exception e) {
                fail.set(true);
            }
        });
    }
    threadPool.shutdown();
    threadPool.awaitTermination(1, TimeUnit.HOURS);
    assertFalse(fail.get());
}

From source file:CB_Utils.http.HttpUtils.java

/**
 * Executes a HTTP request and returns the response as a string. As a HttpRequestBase is given, a HttpGet or HttpPost be passed for
 * execution.<br>/* w  w w  . ja  v a 2s . com*/
 * <br>
 * Over the ICancel interface cycle is queried in 200 mSec, if the download should be canceled!<br>
 * Can be NULL
 * 
 * @param httprequest
 *            HttpRequestBase
 * @param icancel
 *            ICancel interface (maybe NULL)
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws ConnectTimeoutException
 */
public static String Execute(final HttpRequestBase httprequest, final ICancel icancel)
        throws IOException, ClientProtocolException, ConnectTimeoutException {

    httprequest.setHeader("Accept", "application/json");
    httprequest.setHeader("Content-type", "application/json");

    // Execute HTTP Post Request
    String result = "";

    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.

    HttpConnectionParams.setConnectionTimeout(httpParameters, conectionTimeout);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.

    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeout);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    final AtomicBoolean ready = new AtomicBoolean(false);
    if (icancel != null) {
        Thread cancelChekThread = new Thread(new Runnable() {
            @Override
            public void run() {
                do {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    if (icancel.cancel())
                        httprequest.abort();
                } while (!ready.get());
            }
        });
        cancelChekThread.start();// start abort chk thread
    }
    HttpResponse response = httpClient.execute(httprequest);
    ready.set(true);// cancel abort chk thread

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
        if (Plattform.used == Plattform.Server)
            line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
        result += line + "\n";
    }
    return result;
}

From source file:org.apache.hadoop.mapreduce.v2.jobhistory.JobHistoryUtils.java

private static Path[] filteredStat2Paths(List<FileStatus> stats, boolean dirs, AtomicBoolean hasMismatches) {
    int resultCount = 0;

    if (hasMismatches == null) {
        hasMismatches = new AtomicBoolean(false);
    }/*from ww  w  .  j av a 2s  .  c  om*/

    for (int i = 0; i < stats.size(); ++i) {
        if (stats.get(i).isDirectory() == dirs) {
            stats.set(resultCount++, stats.get(i));
        } else {
            hasMismatches.set(true);
        }
    }

    Path[] result = new Path[resultCount];
    for (int i = 0; i < resultCount; i++) {
        result[i] = stats.get(i).getPath();
    }

    return result;
}

From source file:ai.susi.mind.SusiSkill.java

/**
 * if no keys are given, we compute them from the given phrases
 * @param phrases// w  w  w. j  a  v  a  2  s.  c o m
 * @return
 */
private static JSONArray computeKeysFromPhrases(List<SusiPhrase> phrases) {
    Set<String> t = new LinkedHashSet<>();

    // create a list of token sets from the phrases
    List<Set<String>> ptl = new ArrayList<>();
    final AtomicBoolean needsCatchall = new AtomicBoolean(false);
    phrases.forEach(phrase -> {
        Set<String> s = new HashSet<>();
        for (String token : SPACE_PATTERN.split(phrase.getPattern().toString())) {
            String m = SusiPhrase.extractMeat(token.toLowerCase());
            if (m.length() > 1)
                s.add(m);
        }
        // if there is no meat inside, it will not be possible to access the skill without the catchall skill, so remember that
        if (s.size() == 0)
            needsCatchall.set(true);

        ptl.add(s);
    });

    // this is a kind of emergency case where we need a catchall skill because otherwise we cannot access one of the phrases
    JSONArray a = new JSONArray();
    if (needsCatchall.get())
        return a.put(CATCHALL_KEY);

    // collect all token
    ptl.forEach(set -> set.forEach(token -> t.add(token)));

    // if no tokens are available, return the catchall key
    if (t.size() == 0)
        return a.put(CATCHALL_KEY);

    // make a copy to make it possible to use the original key set again
    Set<String> tc = new LinkedHashSet<>();
    t.forEach(c -> tc.add(c));

    // remove all token that do not appear in all phrases
    ptl.forEach(set -> {
        Iterator<String> i = t.iterator();
        while (i.hasNext())
            if (!set.contains(i.next()))
                i.remove();
    });

    // if no token is left, use the original tc set and add all keys
    if (t.size() == 0) {
        tc.forEach(c -> a.put(c));
        return a;
    }

    // use only the first token, because that appears in all the phrases
    return new JSONArray().put(t.iterator().next());
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.BaselineFolderCollection.java

/**
 * Given a baseline file GUID, returns the full path to the baseline file in
 * a baseline folder. From the path that's returned, you can tell whether or
 * not it is compressed (compressed baselines will end in ".gz",
 * uncompressed in ".rw"), but for convenience it is also returned as an out
 * parameter./*from ww  w  . j  ava2  s. c om*/
 *
 *
 * @param workspace
 * @param baselineFolders
 * @param baselineFileGuid
 *        Baseline GUID to look up
 * @param isBaselineCompressed
 *        True if the baseline is compressed, false otherwise
 * @return The full path of the baseline file, if found
 */
public static String getBaselineLocation(final Workspace workspace, final List<BaselineFolder> baselineFolders,
        final byte[] baselineFileGuid, final AtomicBoolean isBaselineCompressed) {
    BaselineFolder.checkForValidBaselineFileGUID(baselineFileGuid);

    isBaselineCompressed.set(false);
    String baselineLocation = null;

    for (final BaselineFolder baselineFolder : baselineFolders) {
        if (null == baselineFolder.path) {
            continue;
        }

        // An example path returned by this method might be:
        // @"D:\workspace\$tf\1\408bed21-9023-47c3-8280-b1ec3ffacd94"
        final String potentialLocation = baselineFolder.getPathFromGUID(baselineFileGuid);

        if (null == potentialLocation) {
            continue;
        }

        // 1. Check the .gz extension (more common)
        final String gzPotentialLocation = potentialLocation + BaselineFolder.getGzipExtension();

        if (new File(gzPotentialLocation).exists()) {
            isBaselineCompressed.set(true);
            baselineLocation = gzPotentialLocation;
            break;
        }

        // 2. Check the .rw extension
        final String rawPotentialLocation = potentialLocation + BaselineFolder.getRawExtension();

        if (new File(rawPotentialLocation).exists()) {
            baselineLocation = rawPotentialLocation;
            break;
        }
    }

    if (null == baselineLocation) {
        // An example path returned by this method might be:
        // @"C:\ProgramData\TFS\Offline\11c92875-fac4-4277-afba-d16f6eeb2189\ws1;domain;username\1\408bed21-9023-47c3-8280-b1ec3ffacd94"
        final String programDataLocation = BaselineFolder.getPathFromGUID(workspace.getLocalMetadataDirectory(),
                baselineFileGuid);

        if (null != programDataLocation) {
            // 1. Check the .gz extension (more common)
            final String gzProgramDataLocation = programDataLocation + BaselineFolder.getGzipExtension();

            if (new File(gzProgramDataLocation).exists()) {
                isBaselineCompressed.set(true);
                baselineLocation = gzProgramDataLocation;
            }

            if (null == baselineLocation) {
                // 2. Check the .rw extension
                final String rawProgramDataLocation = programDataLocation + BaselineFolder.getRawExtension();

                if (new File(rawProgramDataLocation).exists()) {
                    baselineLocation = rawProgramDataLocation;
                }
            }
        }
    }

    return baselineLocation;
}

From source file:com.screenslicer.core.scrape.Scrape.java

private static String getHelper(final RemoteWebDriver driver, final Node urlNode, final String url,
        final boolean p_cached, final String runGuid, final HtmlNode[] clicks) {
    final String urlHash = CommonUtil.isEmpty(url) ? null : Crypto.fastHash(url);
    final long time = System.currentTimeMillis();
    if (urlHash != null) {
        synchronized (fetchLocalCacheLock) {
            if (fetchLocalCache.containsKey(urlHash)) {
                if (time - fetchLocalCache.get(urlHash) < FETCH_LOCAL_CACHE_EXPIRES) {
                    try {
                        return FileUtils.readFileToString(new File("./fetch_local_cache/" + urlHash), "utf-8");
                    } catch (Throwable t) {
                        Log.exception(t);
                        fetchLocalCache.remove(urlHash);
                    }/*w w w  . j  av  a2 s .  c o m*/
                } else {
                    fetchLocalCache.remove(urlHash);
                }
            }
        }
    }
    if (!CommonUtil.isEmpty(url)) {
        final Object resultLock = new Object();
        final String initVal;
        final String[] result;
        synchronized (resultLock) {
            initVal = Random.next();
            result = new String[] { initVal };
        }
        final AtomicBoolean started = new AtomicBoolean();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                started.set(true);
                boolean cached = p_cached;
                String newHandle = null;
                String origHandle = null;
                try {
                    origHandle = driver.getWindowHandle();
                    String content = null;
                    if (!cached) {
                        try {
                            Util.get(driver, url, urlNode, false);
                        } catch (Throwable t) {
                            if (urlNode != null) {
                                Util.newWindow(driver);
                            }
                            Util.get(driver, url, false);
                        }
                        if (urlNode != null) {
                            newHandle = driver.getWindowHandle();
                        }
                        Util.doClicks(driver, clicks, null);
                        content = driver.getPageSource();
                        if (CommonUtil.isEmpty(content)) {
                            cached = true;
                        }
                    }
                    if (cached) {
                        if (ScreenSlicerBatch.isCancelled(runGuid)) {
                            return;
                        }
                        Util.get(driver, toCacheUrl(url), false);
                        content = driver.getPageSource();
                    }
                    content = Util.clean(content, driver.getCurrentUrl()).outerHtml();
                    if (WebApp.DEBUG) {
                        try {
                            FileUtils.writeStringToFile(new File("./" + System.currentTimeMillis()), content);
                        } catch (IOException e) {
                        }
                    }
                    //TODO make iframes work
                    //            if (!CommonUtil.isEmpty(content)) {
                    //              Document doc = Jsoup.parse(content);
                    //              Elements docFrames = doc.getElementsByTag("iframe");
                    //              List<WebElement> iframes = driver.findElementsByTagName("iframe");
                    //              int cur = 0;
                    //              for (WebElement iframe : iframes) {
                    //                try {
                    //                  driver.switchTo().frame(iframe);
                    //                  String frameSrc = driver.getPageSource();
                    //                  if (!CommonUtil.isEmpty(frameSrc) && cur < docFrames.size()) {
                    //                    docFrames.get(cur).html(
                    //                        Util.outerHtml(Jsoup.parse(frameSrc).body().childNodes()));
                    //                  }
                    //                } catch (Throwable t) {
                    //                  Log.exception(t);
                    //                }
                    //                ++cur;
                    //              }
                    //              driver.switchTo().defaultContent();
                    //              content = doc.outerHtml();
                    //            }
                    synchronized (resultLock) {
                        result[0] = content;
                    }
                } catch (Throwable t) {
                    Log.exception(t);
                } finally {
                    synchronized (resultLock) {
                        if (initVal.equals(result[0])) {
                            result[0] = null;
                        }
                    }
                    Util.driverSleepRandLong();
                    if (newHandle != null && origHandle != null) {
                        try {
                            Util.cleanUpNewWindows(driver, origHandle);
                        } catch (Throwable t) {
                            Log.exception(t);
                        }
                    }
                }
            }
        });
        thread.start();
        try {
            while (!started.get()) {
                try {
                    Thread.sleep(WAIT);
                } catch (Throwable t) {
                    Log.exception(t);
                }
            }
            thread.join(HANG_TIME);
            synchronized (resultLock) {
                if (initVal.equals(result[0])) {
                    try {
                        Log.exception(new Exception("Browser is hanging"));
                        forceQuit();
                        thread.interrupt();
                    } catch (Throwable t) {
                        Log.exception(t);
                    }
                    throw new ActionFailed();
                } else if (urlHash != null && !CommonUtil.isEmpty(result[0])
                        && result[0].length() > MIN_FETCH_CACHE_PAGE_LEN) {
                    synchronized (fetchLocalCacheLock) {
                        if (fetchLocalCache.size() > MAX_FETCH_LOCAL_CACHE) {
                            try {
                                FileUtils.deleteQuietly(new File("./fetch_local_cache"));
                                FileUtils.forceMkdir(new File("./fetch_local_cache"));
                            } catch (Throwable t) {
                                Log.exception(t);
                            }
                            fetchLocalCache.clear();
                        }
                        FileUtils.writeStringToFile(new File("./fetch_local_cache/" + urlHash), result[0],
                                "utf-8", false);
                        fetchLocalCache.put(urlHash, time);
                    }
                }
                return result[0];
            }
        } catch (Throwable t) {
            Log.exception(t);
        }
    }
    return null;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.internal.localworkspace.BaselineFolderCollection.java

/**
 * Creates and opens a file with the specified path. If the parent folder
 * does not exist, we create it and mark it and its parent as hidden -- we
 * assume that file reside in $tf\10\ and we need to mark both $tf and 10 as
 * hidden. If filePath was not specified or its creation failed, and
 * createTempOnFailure=true we will create a new temporary file, using
 * tempUniqueString.//from   w  ww  .  ja v  a  2  s  . c  om
 *
 *
 * @param filePath
 *        in: the path to create the file at, out: the path actually created
 *        (possibly a temporary file in another directory) (must not be
 *        <code>null</code>)
 * @param createTempOnFailure
 * @param tempUniqueString
 * @param tempCreated
 * @return
 * @throws IOException
 */
public static FileOutputStream createFile(final AtomicReference<String> filePath,
        final boolean createTempOnFailure, final String tempUniqueString, final AtomicBoolean tempCreated)
        throws IOException {
    Check.notNull(filePath, "filePath"); //$NON-NLS-1$

    FileOutputStream localStream = null;
    tempCreated.set(false);

    Exception createException = null;
    if (filePath.get() != null && filePath.get().length() > 0) {
        try {
            localStream = new FileOutputStream(filePath.get());
        } catch (final Exception ex) {
            createException = ex;
            if (!createTempOnFailure) {
                throw new VersionControlException(ex);
            }
        }
    }
    if (localStream == null && createTempOnFailure) {
        tempCreated.set(true);

        final File tempFile = TempStorageService.getInstance().createTempFile();
        localStream = new FileOutputStream(tempFile);

        log.info(MessageFormat.format(
                "Could not create baseline folder collection file {0}, using temporary file {1}", //$NON-NLS-1$
                filePath.get(), tempFile), createException);

        filePath.set(tempFile.getAbsolutePath());
    } else {
        Check.notNullOrEmpty(filePath.get(), "filePath.get()"); //$NON-NLS-1$
    }

    return localStream;
}