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.ryan.ryanreader.fragments.AddAccountDialog.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {

    if (alreadyCreated)
        return getDialog();
    alreadyCreated = true;/*from   w  ww  .j  ava2 s.  c om*/

    super.onCreateDialog(savedInstanceState);

    final AlertDialog.Builder builder = new AlertDialog.Builder(getSupportActivity());
    builder.setTitle(R.string.accounts_add);

    final View view = getSupportActivity().getLayoutInflater().inflate(R.layout.dialog_login, null);
    builder.setView(view);
    builder.setCancelable(true);

    final EditText usernameBox = ((EditText) view.findViewById(R.id.login_username));
    usernameBox.setText(lastUsername);
    usernameBox.requestFocus();
    usernameBox.requestFocusFromTouch();

    builder.setPositiveButton(R.string.accounts_login, new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialogInterface, final int i) {

            final String username = ((EditText) getDialog().findViewById(R.id.login_username)).getText()
                    .toString().trim();
            final String password = ((EditText) getDialog().findViewById(R.id.login_password)).getText()
                    .toString();

            lastUsername = username;

            final ProgressDialog progressDialog = new ProgressDialog(getSupportActivity());
            final Thread thread;
            progressDialog.setTitle(R.string.accounts_loggingin);
            progressDialog.setMessage(getString(R.string.accounts_loggingin_msg));
            progressDialog.setIndeterminate(true);

            final AtomicBoolean cancelled = new AtomicBoolean(false);

            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(false);

            progressDialog.show();

            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(final DialogInterface dialogInterface) {
                    cancelled.set(true);
                    progressDialog.dismiss();
                }
            });

            progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                public boolean onKey(final DialogInterface dialogInterface, final int keyCode,
                        final KeyEvent keyEvent) {

                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        cancelled.set(true);
                        progressDialog.dismiss();
                    }

                    return true;
                }
            });

            thread = new Thread() {
                @Override
                public void run() {

                    // TODO better HTTP client
                    final RedditAccount.LoginResultPair result = RedditAccount.login(getSupportActivity(),
                            username, password, new DefaultHttpClient());

                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        public void run() {

                            if (cancelled.get())
                                return; // safe, since we're in the UI thread

                            progressDialog.dismiss();

                            final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(
                                    getSupportActivity());
                            alertBuilder.setNeutralButton(R.string.dialog_close,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            new AccountListDialog().show(getSupportActivity());
                                        }
                                    });

                            // TODO handle errors better
                            switch (result.result) {
                            case CONNECTION_ERROR:
                                alertBuilder.setTitle(R.string.error_connection_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case INTERNAL_ERROR:
                                alertBuilder.setTitle(R.string.error_unknown_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case JSON_ERROR:
                                alertBuilder.setTitle(R.string.error_parse_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case REQUEST_ERROR:
                                alertBuilder.setTitle(R.string.error_connection_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case UNKNOWN_REDDIT_ERROR:
                                alertBuilder.setTitle(R.string.error_unknown_title);
                                alertBuilder.setMessage(R.string.message_cannotlogin);
                                break;
                            case WRONG_PASSWORD:
                                alertBuilder.setTitle(R.string.error_invalid_password_title);
                                alertBuilder.setMessage(R.string.error_invalid_password_message);
                                break;
                            case RATELIMIT:
                                alertBuilder.setTitle(R.string.error_ratelimit_title);
                                alertBuilder.setMessage(String.format("%s \"%s\"",
                                        getString(R.string.error_ratelimit_message), result.extraMessage));
                                break;
                            case SUCCESS:
                                RedditAccountManager.getInstance(getSupportActivity())
                                        .addAccount(result.account);
                                RedditAccountManager.getInstance(getSupportActivity())
                                        .setDefaultAccount(result.account);
                                alertBuilder.setTitle(R.string.general_success);
                                alertBuilder.setMessage(R.string.message_nowloggedin);
                                lastUsername = "";
                                break;
                            default:
                                throw new RuntimeException();
                            }

                            final AlertDialog alertDialog = alertBuilder.create();
                            alertDialog.show();
                        }
                    });
                }
            };

            thread.start();
        }
    });

    builder.setNegativeButton(R.string.dialog_cancel, null);

    return builder.create();
}

From source file:org.lol.reddit.fragments.AddAccountDialog.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {

    if (alreadyCreated)
        return getDialog();
    alreadyCreated = true;//  w w w  .j  a v  a 2 s.co m

    super.onCreateDialog(savedInstanceState);

    final Activity activity = getSupportActivity();
    final Context appContext = activity.getApplicationContext();

    final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(R.string.accounts_add);

    final View view = activity.getLayoutInflater().inflate(R.layout.dialog_login);
    builder.setView(view);
    builder.setCancelable(true);

    final EditText usernameBox = ((EditText) view.findViewById(R.id.login_username));
    usernameBox.setText(lastUsername);
    usernameBox.requestFocus();
    usernameBox.requestFocusFromTouch();

    builder.setPositiveButton(R.string.accounts_login, new DialogInterface.OnClickListener() {
        public void onClick(final DialogInterface dialogInterface, final int i) {

            final String username = ((EditText) getDialog().findViewById(R.id.login_username)).getText()
                    .toString().trim();
            final String password = ((EditText) getDialog().findViewById(R.id.login_password)).getText()
                    .toString();

            lastUsername = username;

            final ProgressDialog progressDialog = new ProgressDialog(activity);
            final Thread thread;
            progressDialog.setTitle(R.string.accounts_loggingin);
            progressDialog.setMessage(getString(R.string.accounts_loggingin_msg));
            progressDialog.setIndeterminate(true);

            final AtomicBoolean cancelled = new AtomicBoolean(false);

            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(false);

            progressDialog.show();

            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                public void onCancel(final DialogInterface dialogInterface) {
                    cancelled.set(true);
                    progressDialog.dismiss();
                }
            });

            progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                public boolean onKey(final DialogInterface dialogInterface, final int keyCode,
                        final KeyEvent keyEvent) {

                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        cancelled.set(true);
                        progressDialog.dismiss();
                    }

                    return true;
                }
            });

            thread = new Thread() {
                @Override
                public void run() {

                    // TODO better HTTP client
                    final RedditAccount.LoginResultPair result = RedditAccount.login(appContext, username,
                            password, new DefaultHttpClient());

                    General.UI_THREAD_HANDLER.post(new Runnable() {
                        public void run() {

                            if (cancelled.get())
                                return; // safe, since we're in the UI thread

                            progressDialog.dismiss();

                            final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(activity);
                            alertBuilder.setNeutralButton(R.string.dialog_close,
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            new AccountListDialog().show(activity);
                                        }
                                    });

                            // TODO handle errors better
                            switch (result.result) {
                            case CONNECTION_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_connection_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case INTERNAL_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_unknown_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case JSON_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_parse_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case REQUEST_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_connection_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case UNKNOWN_REDDIT_ERROR:
                                alertBuilder.setTitle(appContext.getString(R.string.error_unknown_title));
                                alertBuilder.setMessage(appContext.getString(R.string.message_cannotlogin));
                                break;
                            case WRONG_PASSWORD:
                                alertBuilder
                                        .setTitle(appContext.getString(R.string.error_invalid_password_title));
                                alertBuilder.setMessage(
                                        appContext.getString(R.string.error_invalid_password_message));
                                break;
                            case RATELIMIT:
                                alertBuilder.setTitle(appContext.getString(R.string.error_ratelimit_title));
                                alertBuilder.setMessage(String.format("%s \"%s\"",
                                        appContext.getString(R.string.error_ratelimit_message),
                                        result.extraMessage));
                                break;
                            case SUCCESS:
                                RedditAccountManager.getInstance(appContext).addAccount(result.account);
                                RedditAccountManager.getInstance(appContext).setDefaultAccount(result.account);
                                alertBuilder.setTitle(appContext.getString(R.string.general_success));
                                alertBuilder.setMessage(appContext.getString(R.string.message_nowloggedin));
                                lastUsername = "";
                                break;
                            default:
                                throw new RuntimeException();
                            }

                            final AlertDialog alertDialog = alertBuilder.create();
                            alertDialog.show();
                        }
                    });
                }
            };

            thread.start();
        }
    });

    builder.setNegativeButton(R.string.dialog_cancel, null);

    return builder.create();
}

From source file:com.yahoo.sql4d.indexeragent.sql.DBAccessor.java

/**
 * Suitable for CRUD operations where no result set is expected.
 * @param params/*from   ww w  . ja  v  a  2 s.c o m*/
 * @param query 
 * @return  
 */
public boolean execute(Map<String, String> params, String query) {
    final AtomicBoolean result = new AtomicBoolean(false);
    Tuple2<DataSource, Connection> conn = null;
    try {
        conn = getConnection();
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(conn._1());
        jdbcTemplate.execute(query, params, new PreparedStatementCallback<Void>() {
            @Override
            public Void doInPreparedStatement(PreparedStatement ps) {
                try {
                    result.set(ps.execute());
                } catch (SQLException e) {
                    result.set(false);
                }
                return null;
            }
        });
    } catch (Exception ex) {
        Logger.getLogger(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
        result.set(false);
    } finally {
        returnConnection(conn);
    }
    return result.get();
}

From source file:org.apache.hadoop.hbase.client.SpeculativeRequester.java

public ResultWrapper<T> request(final HBaseTableFunction<T> function, final HTableInterface primaryTable,
        final Collection<HTableInterface> failoverTables) {

    ExecutorCompletionService<ResultWrapper<T>> exeS = new ExecutorCompletionService<ResultWrapper<T>>(exe);

    final AtomicBoolean isPrimarySuccess = new AtomicBoolean(false);
    final long startTime = System.currentTimeMillis();

    ArrayList<Callable<ResultWrapper<T>>> callables = new ArrayList<Callable<ResultWrapper<T>>>();

    if (System.currentTimeMillis() - lastPrimaryFail.get() > waitTimeFromLastPrimaryFail) {
        callables.add(new Callable<ResultWrapper<T>>() {
            public ResultWrapper<T> call() throws Exception {
                try {
                    T t = function.call(primaryTable);
                    isPrimarySuccess.set(true);
                    return new ResultWrapper(true, t);
                } catch (java.io.InterruptedIOException e) {
                    Thread.currentThread().interrupt();
                } catch (Exception e) {
                    lastPrimaryFail.set(System.currentTimeMillis());
                    Thread.currentThread().interrupt();
                }/*from   www .  j ava2s . co m*/
                return null;
            }
        });
    }

    for (final HTableInterface failoverTable : failoverTables) {
        callables.add(new Callable<ResultWrapper<T>>() {

            public ResultWrapper<T> call() throws Exception {

                long waitToRequest = (System.currentTimeMillis()
                        - lastPrimaryFail.get() > waitTimeFromLastPrimaryFail)
                                ? waitTimeBeforeRequestingFailover - (System.currentTimeMillis() - startTime)
                                : 0;

                if (waitToRequest > 0) {
                    Thread.sleep(waitToRequest);
                }
                if (isPrimarySuccess.get() == false) {
                    T t = function.call(failoverTable);

                    long waitToAccept = (System.currentTimeMillis()
                            - lastPrimaryFail.get() > waitTimeFromLastPrimaryFail)
                                    ? waitTimeBeforeAcceptingResults - (System.currentTimeMillis() - startTime)
                                    : 0;
                    if (isPrimarySuccess.get() == false) {
                        if (waitToAccept > 0) {
                            Thread.sleep(waitToAccept);
                        }
                    }

                    return new ResultWrapper(false, t);
                } else {
                    throw new RuntimeException("Not needed");
                }

            }
        });
    }
    try {

        //ResultWrapper<T> t = exe.invokeAny(callables);
        for (Callable<ResultWrapper<T>> call : callables) {
            exeS.submit(call);
        }

        ResultWrapper<T> result = exeS.take().get();
        //exe.shutdownNow();

        return result;
    } catch (InterruptedException e) {
        e.printStackTrace();
        LOG.error(e);
    } catch (ExecutionException e) {
        e.printStackTrace();
        LOG.error(e);
    }
    return null;

}

From source file:org.lol.reddit.reddit.api.RedditAPIIndividualSubredditDataRequester.java

public void performRequest(final Collection<String> subredditCanonicalIds, final TimestampBound timestampBound,
        final RequestResponseHandler<HashMap<String, RedditSubreddit>, SubredditRequestFailure> handler) {

    // TODO if there's a bulk API to do this, that would be good... :)

    final HashMap<String, RedditSubreddit> result = new HashMap<String, RedditSubreddit>();
    final AtomicBoolean stillOkay = new AtomicBoolean(true);
    final AtomicInteger requestsToGo = new AtomicInteger(subredditCanonicalIds.size());
    final AtomicLong oldestResult = new AtomicLong(Long.MAX_VALUE);

    final RequestResponseHandler<RedditSubreddit, SubredditRequestFailure> innerHandler = new RequestResponseHandler<RedditSubreddit, SubredditRequestFailure>() {
        @Override/*from w w w . ja  v a2s. com*/
        public void onRequestFailed(SubredditRequestFailure failureReason) {
            synchronized (result) {
                if (stillOkay.get()) {
                    stillOkay.set(false);
                    handler.onRequestFailed(failureReason);
                }
            }
        }

        @Override
        public void onRequestSuccess(RedditSubreddit innerResult, long timeCached) {
            synchronized (result) {
                if (stillOkay.get()) {

                    result.put(innerResult.getKey(), innerResult);
                    oldestResult.set(Math.min(oldestResult.get(), timeCached));

                    if (requestsToGo.decrementAndGet() == 0) {
                        handler.onRequestSuccess(result, oldestResult.get());
                    }
                }
            }
        }
    };

    for (String subredditCanonicalId : subredditCanonicalIds) {
        performRequest(subredditCanonicalId, timestampBound, innerHandler);
    }
}

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

@Test
public void testCustomUUIDDeserialization() throws Exception {
    final UUID orig = UUID.fromString("550e8400-e29b-41d4-a716-446655440000");
    final AtomicBoolean called = new AtomicBoolean(false);
    ObjectMapper mapper = getObjectMapper(new AbstractModule() {
        @Override//  w w  w  . j a v  a 2s  .  co  m
        protected void configure() {
            bind(new TypeLiteral<JsonDeserializer<UUID>>() {
            }).toInstance(new CustomUuidDeserializer() {
                private static final long serialVersionUID = 1L;

                @Override
                protected UUID _deserialize(String value, DeserializationContext ctxt)
                        throws IOException, JsonProcessingException {
                    UUID foo = super._deserialize(value, ctxt);
                    called.set(true);
                    return foo;
                }
            });
        }
    });
    UUID uuid = mapper.readValue('"' + orig.toString() + '"', new TypeReference<UUID>() {
    });
    Assert.assertEquals(orig, uuid);
    Assert.assertTrue(called.get());
}

From source file:ch.cyberduck.core.editor.AbstractEditorTest.java

@Test
public void testOpen() throws Exception {
    final AtomicBoolean t = new AtomicBoolean();
    final NullSession session = new NullSession(new Host(new TestProtocol())) {
        @Override// ww w  . j a  va2  s . co m
        @SuppressWarnings("unchecked")
        public <T> T _getFeature(final Class<T> type) {
            if (type.equals(Read.class)) {
                return (T) new Read() {
                    @Override
                    public InputStream read(final Path file, final TransferStatus status,
                            final ConnectionCallback callback) throws BackgroundException {
                        t.set(true);
                        return IOUtils.toInputStream("content", Charset.defaultCharset());
                    }

                    @Override
                    public boolean offset(final Path file) {
                        assertEquals(new Path("/f", EnumSet.of(Path.Type.file)), file);
                        return false;
                    }
                };
            }
            return super._getFeature(type);
        }
    };
    final AtomicBoolean e = new AtomicBoolean();
    final Path file = new Path("/f", EnumSet.of(Path.Type.file));
    file.attributes().setSize("content".getBytes().length);
    final AbstractEditor editor = new AbstractEditor(new Application("com.editor"),
            new StatelessSessionPool(new TestLoginConnectionService(), session, PathCache.empty(),
                    new DisabledTranscriptListener(), new DefaultVaultRegistry(new DisabledPasswordCallback())),
            file, new DisabledProgressListener()) {
        @Override
        protected void edit(final ApplicationQuitCallback quit, final FileWatcherListener listener)
                throws IOException {
            e.set(true);
        }

        @Override
        protected void watch(final Local local, final FileWatcherListener listener) throws IOException {
            //
        }
    };
    editor.open(new DisabledApplicationQuitCallback(), new DisabledTransferErrorCallback(),
            new DisabledFileWatcherListener()).run(session);
    assertTrue(t.get());
    assertNotNull(editor.getLocal());
    assertTrue(e.get());
    assertTrue(editor.getLocal().exists());
}

From source file:com.spectralogic.ds3client.integration.DataIntegrity_Test.java

@Test
public void callerSuppliedChecksum() throws IOException, SignatureException, XmlProcessingException {
    final String bucketName = "caller_supplied_checksum_test";

    try {//from   w w w . j a  va 2s. co m
        HELPERS.ensureBucketExists(bucketName, envDataPolicyId);

        final List<Ds3Object> objs = Lists.newArrayList(new Ds3Object("beowulf.txt", 294059));
        final Ds3ClientHelpers.Job job = HELPERS.startWriteJob(bucketName, objs,
                WriteJobOptions.create().withChecksumType(ChecksumType.Type.MD5));

        final AtomicBoolean callbackCalled = new AtomicBoolean(false);

        job.withChecksum(new ChecksumFunction() {
            @Override
            public String compute(final BulkObject obj, final ByteChannel channel) {
                if (obj.getName().equals("beowulf.txt")) {
                    callbackCalled.set(true);
                    return "rCu751L6xhB5zyL+soa3fg==";
                }
                return null;
            }
        });

        final SingleChecksumListener listener = new SingleChecksumListener();

        job.attachChecksumListener(listener);

        job.transfer(new ResourceObjectPutter("books/"));

        final String checksum = listener.getChecksum();

        assertThat(checksum, is(notNullValue()));
        assertThat(checksum, is("rCu751L6xhB5zyL+soa3fg=="));
        assertTrue(callbackCalled.get());

    } finally {
        Util.deleteAllContents(client, bucketName);
    }
}

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

public void getNodeInformation() {
    try {/*  ww w. j av  a 2s.  c  o m*/
        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());
    }
}

From source file:com.google.gdt.eclipse.designer.util.Utils.java

/**
 * @return <code>true</code> if given {@link IPackageFragment} is "source" package of some GWT
 *         module./*from  w  w  w  .ja va2s  .c o  m*/
 */
public static boolean isModuleSourcePackage(IPackageFragment packageFragment) throws Exception {
    final String packageName = packageFragment.getElementName();
    // check enclosing module
    ModuleDescription module = getSingleModule(packageFragment);
    if (module != null) {
        final AtomicBoolean result = new AtomicBoolean();
        ModuleVisitor.accept(module, new ModuleVisitor() {
            @Override
            public boolean visitModule(ModuleElement moduleElement) {
                String modulePackage = CodeUtils.getPackage(moduleElement.getId()) + ".";
                if (packageName.startsWith(modulePackage)) {
                    String folderInModule = packageName.substring(modulePackage.length()).replace('.', '/');
                    if (moduleElement.isInSourceFolder(folderInModule)) {
                        result.set(true);
                        return false;
                    }
                }
                return true;
            }
        });
        return result.get();
    }
    // no enclosing module
    return false;
}