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:eu.europa.ec.markt.dss.validation102853.pades.PAdESSignature.java

private boolean hasDocumentTimestamp() {
    boolean levelReached;
    final PDFSignatureService pdfTimestampSignatureService = PdfObjFactory.getInstance()
            .newTimestampSignatureService();
    try {//w w  w.j a v  a 2s. c o m
        final AtomicBoolean atomicLevelReached = new AtomicBoolean(false);
        pdfTimestampSignatureService.validateSignatures(document.openStream(),
                new SignatureValidationCallback() {
                    @Override
                    public void validate(PdfDict catalog, PdfDict outerCatalog, X509Certificate signingCert,
                            Date signingDate, Certificate[] certs, PdfDict signatureDictionary,
                            PdfSignatureInfo pk) {
                        try {
                            final byte[] subFilters = signatureDictionary.get("SubFilter");
                            if (subFilters != null) {
                                String pdfSubFilter = new String(subFilters); //
                                if (StringUtils.equals("/ETSI.RFC3161", pdfSubFilter)) {
                                    atomicLevelReached.set(true);
                                }
                            }
                        } catch (IOException e) {
                            throw new DSSException(e);
                        }
                    }
                });
        levelReached = atomicLevelReached.get();
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (SignatureException e) {
        throw new DSSException(e);
    }
    return levelReached;
}

From source file:com.android.tools.idea.tests.gui.gradle.GradleSyncTest.java

@Test
public void shouldUseLibrary() throws IOException {
    guiTest.importSimpleApplication();/*from  w w w  . j a v a2s . co m*/
    IdeFrameFixture ideFrame = guiTest.ideFrame();

    Project project = ideFrame.getProject();

    // Make sure the library was added.
    LibraryTable libraryTable = ProjectLibraryTable.getInstance(project);
    String libraryName = "org.apache.http.legacy-" + TestUtils.getLatestAndroidPlatform();
    Library library = libraryTable.getLibraryByName(libraryName);

    // Verify that the library has the right j
    VirtualFile[] jarFiles = library.getFiles(CLASSES);
    assertThat(jarFiles).asList().hasSize(1);
    VirtualFile jarFile = jarFiles[0];
    assertEquals("org.apache.http.legacy.jar", jarFile.getName());

    // Verify that the module depends on the library
    Module appModule = ideFrame.getModule("app");
    AtomicBoolean dependencyFound = new AtomicBoolean();
    new ReadAction() {
        @Override
        protected void run(@NotNull Result result) throws Throwable {
            ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(appModule).getModifiableModel();
            try {
                for (OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
                    if (orderEntry instanceof LibraryOrderEntry) {
                        LibraryOrderEntry libraryDependency = (LibraryOrderEntry) orderEntry;
                        if (libraryDependency.getLibrary() == library) {
                            dependencyFound.set(true);
                        }
                    }
                }
            } finally {
                modifiableModel.dispose();
            }
        }
    }.execute();
    assertTrue("Module app should depend on library '" + library.getName() + "'", dependencyFound.get());
}

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

@Test
public void should_dsl_update_value_if_exists() throws Exception {
    //Given//ww w.  ja  v a2  s  .co  m
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    final Date date = buildDateKey();
    final AtomicBoolean error = new AtomicBoolean(false);

    //When
    manager.dsl().update().fromBaseTable().value_Set("new value").where().id_Eq(id).date_Eq(date).ifExists()
            .withLwtResultListener(new LWTResultListener() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onError(LWTResult lwtResult) {
                    error.getAndSet(true);
                }
            }).withResultSetAsyncListener(rs -> {
                assertThat(rs.wasApplied()).isFalse();
                return rs;
            }).execute();

    //Then
    final Row row = session.execute("SELECT simplemap FROM simple WHERE id = " + id).one();
    assertThat(row).isNull();
    assertThat(error.get()).isTrue();
}

From source file:org.lendingclub.mercator.docker.SwarmScanner.java

public void scanServicesForSwarm(String swarmClusterId) {

    JsonNode response = getRestClient().getServices();

    AtomicLong earlistUpdate = new AtomicLong(Long.MAX_VALUE);
    AtomicBoolean error = new AtomicBoolean(false);
    response.forEach(it -> {/*w ww  .j av  a  2  s.co m*/
        try {
            ObjectNode n = flattenService(it);
            n.put("swarmClusterId", swarmClusterId);
            dockerScanner.getNeoRxClient().execCypher(
                    "merge (x:DockerService {serviceId:{serviceId}}) set x+={props}, x.updateTs=timestamp() return x",
                    "serviceId", n.get("serviceId").asText(), "props", n).forEach(svc -> {
                        removeDockerLabels("DockerService", "serviceId", n.get("serviceId").asText(), n, svc);
                        earlistUpdate.set(
                                Math.min(earlistUpdate.get(), svc.path("updateTs").asLong(Long.MAX_VALUE)));
                    });
            dockerScanner.getNeoRxClient().execCypher(
                    "match (swarm:DockerSwarm {swarmClusterId:{swarmClusterId}}),(service:DockerService{serviceId:{serviceId}}) merge (swarm)-[x:CONTAINS]->(service) set x.updateTs=timestamp()",
                    "swarmClusterId", swarmClusterId, "serviceId", n.path("serviceId").asText());

        } catch (Exception e) {
            logger.warn("problem updating service", e);
            error.set(true);
        }
    });
    if (error.get() == false) {
        if (earlistUpdate.get() < System.currentTimeMillis()) {
            dockerScanner.getNeoRxClient().execCypher(
                    "match (x:DockerService) where x.swarmClusterId={swarmClusterId} and x.updateTs<{cutoff} detach delete x",
                    "cutoff", earlistUpdate.get(), "swarmClusterId", swarmClusterId);
        }
    }

}

From source file:test.java.com.spotify.docker.client.DefaultDockerClientTest.java

@Test
public void testBuildNoCache() throws Exception {
    final String dockerDirectory = Resources.getResource("dockerDirectory").getPath();
    final String usingCache = "Using cache";

    // Build once to make sure we have cached images.
    sut.build(Paths.get(dockerDirectory));

    // Build again and make sure we used cached image by parsing output.
    final AtomicBoolean usedCache = new AtomicBoolean(false);
    sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() {
        @Override//from   w  w w . jav a2  s  .  c  o m
        public void progress(ProgressMessage message) throws DockerException {
            if (message.stream().contains(usingCache)) {
                usedCache.set(true);
            }
        }
    });
    assertTrue(usedCache.get());

    // Build again with NO_CACHE set, and verify we don't use cache.
    sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() {
        @Override
        public void progress(ProgressMessage message) throws DockerException {
            assertThat(message.stream(), not(containsString(usingCache)));
        }
    }, NO_CACHE);
}

From source file:test.java.com.spotify.docker.client.DefaultDockerClientTest.java

@Test
public void testBuildWithPull() throws Exception {
    assumeTrue("We need Docker API >= v1.19 to run this test." + "This Docker API is "
            + sut.version().apiVersion(), versionCompare(sut.version().apiVersion(), "1.19") >= 0);

    final String dockerDirectory = Resources.getResource("dockerDirectory").getPath();
    final String pullMsg = "Pulling from";

    // Build once to make sure we have cached images.
    sut.build(Paths.get(dockerDirectory));

    // Build again with PULL set, and verify we pulled the base image
    final AtomicBoolean pulled = new AtomicBoolean(false);
    sut.build(Paths.get(dockerDirectory), "test", new ProgressHandler() {
        @Override/* w w w  . j  a  v a  2 s. c o  m*/
        public void progress(ProgressMessage message) throws DockerException {
            if (message.status().contains(pullMsg)) {
                pulled.set(true);
            }
        }
    }, PULL_NEWER_IMAGE);
    assertTrue(pulled.get());
}

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

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {

    if (alreadyCreated)
        return getDialog();
    alreadyCreated = true;//ww w. j a v a  2 s  .c om

    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:org.apache.cassandra.repair.RepairRunnable.java

protected void runMayThrow() throws Exception {
    final TraceState traceState;

    final String tag = "repair:" + cmd;

    final AtomicInteger progress = new AtomicInteger();
    final int totalProgress = 3 + options.getRanges().size(); // calculate neighbors, validation, prepare for repair + number of ranges to repair

    String[] columnFamilies = options.getColumnFamilies()
            .toArray(new String[options.getColumnFamilies().size()]);
    Iterable<ColumnFamilyStore> validColumnFamilies = storageService.getValidColumnFamilies(false, false,
            keyspace, columnFamilies);//from  w  w w .j av  a 2s .  c  om

    final long startTime = System.currentTimeMillis();
    String message = String.format("Starting repair command #%d, repairing keyspace %s with %s", cmd, keyspace,
            options);
    logger.info(message);
    fireProgressEvent(tag, new ProgressEvent(ProgressEventType.START, 0, 100, message));
    if (options.isTraced()) {
        StringBuilder cfsb = new StringBuilder();
        for (ColumnFamilyStore cfs : validColumnFamilies)
            cfsb.append(", ").append(cfs.keyspace.getName()).append(".").append(cfs.name);

        UUID sessionId = Tracing.instance.newSession(Tracing.TraceType.REPAIR);
        traceState = Tracing.instance.begin("repair",
                ImmutableMap.of("keyspace", keyspace, "columnFamilies", cfsb.substring(2)));
        Tracing.traceRepair(message);
        traceState.enableActivityNotification(tag);
        for (ProgressListener listener : listeners)
            traceState.addProgressListener(listener);
        Thread queryThread = createQueryThread(cmd, sessionId);
        queryThread.setName("RepairTracePolling");
        queryThread.start();
    } else {
        traceState = null;
    }

    final Set<InetAddress> allNeighbors = new HashSet<>();
    Map<Range, Set<InetAddress>> rangeToNeighbors = new HashMap<>();
    try {
        for (Range<Token> range : options.getRanges()) {
            Set<InetAddress> neighbors = ActiveRepairService.getNeighbors(keyspace, range,
                    options.getDataCenters(), options.getHosts());
            rangeToNeighbors.put(range, neighbors);
            allNeighbors.addAll(neighbors);
        }
        progress.incrementAndGet();
    } catch (IllegalArgumentException e) {
        logger.error("Repair failed:", e);
        fireErrorAndComplete(tag, progress.get(), totalProgress, e.getMessage());
        return;
    }

    // Validate columnfamilies
    List<ColumnFamilyStore> columnFamilyStores = new ArrayList<>();
    try {
        Iterables.addAll(columnFamilyStores, validColumnFamilies);
        progress.incrementAndGet();
    } catch (IllegalArgumentException e) {
        fireErrorAndComplete(tag, progress.get(), totalProgress, e.getMessage());
        return;
    }

    String[] cfnames = new String[columnFamilyStores.size()];
    for (int i = 0; i < columnFamilyStores.size(); i++) {
        cfnames[i] = columnFamilyStores.get(i).name;
    }

    final UUID parentSession = UUIDGen.getTimeUUID();
    SystemDistributedKeyspace.startParentRepair(parentSession, keyspace, cfnames, options.getRanges());
    long repairedAt;
    try {
        ActiveRepairService.instance.prepareForRepair(parentSession, allNeighbors, options, columnFamilyStores);
        repairedAt = ActiveRepairService.instance.getParentRepairSession(parentSession).getRepairedAt();
        progress.incrementAndGet();
    } catch (Throwable t) {
        SystemDistributedKeyspace.failParentRepair(parentSession, t);
        fireErrorAndComplete(tag, progress.get(), totalProgress, t.getMessage());
        return;
    }

    // Set up RepairJob executor for this repair command.
    final ListeningExecutorService executor = MoreExecutors.listeningDecorator(
            new JMXConfigurableThreadPoolExecutor(options.getJobThreads(), Integer.MAX_VALUE, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory("Repair#" + cmd), "internal"));

    List<ListenableFuture<RepairSessionResult>> futures = new ArrayList<>(options.getRanges().size());
    for (Range<Token> range : options.getRanges()) {
        final RepairSession session = ActiveRepairService.instance.submitRepairSession(parentSession, range,
                keyspace, options.getParallelism(), rangeToNeighbors.get(range), repairedAt, executor, cfnames);
        if (session == null)
            continue;
        // After repair session completes, notify client its result
        Futures.addCallback(session, new FutureCallback<RepairSessionResult>() {
            public void onSuccess(RepairSessionResult result) {
                String message = String.format("Repair session %s for range %s finished", session.getId(),
                        session.getRange().toString());
                logger.info(message);
                fireProgressEvent(tag, new ProgressEvent(ProgressEventType.PROGRESS, progress.incrementAndGet(),
                        totalProgress, message));
            }

            public void onFailure(Throwable t) {
                String message = String.format("Repair session %s for range %s failed with error %s",
                        session.getId(), session.getRange().toString(), t.getMessage());
                logger.error(message, t);
                fireProgressEvent(tag, new ProgressEvent(ProgressEventType.PROGRESS, progress.incrementAndGet(),
                        totalProgress, message));
            }
        });
        futures.add(session);
    }

    // After all repair sessions completes(successful or not),
    // run anticompaction if necessary and send finish notice back to client
    final Collection<Range<Token>> successfulRanges = new ArrayList<>();
    final AtomicBoolean hasFailure = new AtomicBoolean();
    final ListenableFuture<List<RepairSessionResult>> allSessions = Futures.successfulAsList(futures);
    ListenableFuture anticompactionResult = Futures.transform(allSessions,
            new AsyncFunction<List<RepairSessionResult>, Object>() {
                @SuppressWarnings("unchecked")
                public ListenableFuture apply(List<RepairSessionResult> results) throws Exception {
                    // filter out null(=failed) results and get successful ranges
                    for (RepairSessionResult sessionResult : results) {
                        if (sessionResult != null) {
                            successfulRanges.add(sessionResult.range);
                        } else {
                            hasFailure.compareAndSet(false, true);
                        }
                    }
                    return ActiveRepairService.instance.finishParentSession(parentSession, allNeighbors,
                            successfulRanges);
                }
            });
    Futures.addCallback(anticompactionResult, new FutureCallback<Object>() {
        public void onSuccess(Object result) {
            SystemDistributedKeyspace.successfulParentRepair(parentSession, successfulRanges);
            if (hasFailure.get()) {
                fireProgressEvent(tag, new ProgressEvent(ProgressEventType.ERROR, progress.get(), totalProgress,
                        "Some repair failed"));
            } else {
                fireProgressEvent(tag, new ProgressEvent(ProgressEventType.SUCCESS, progress.get(),
                        totalProgress, "Repair completed successfully"));
            }
            repairComplete();
        }

        public void onFailure(Throwable t) {
            fireProgressEvent(tag,
                    new ProgressEvent(ProgressEventType.ERROR, progress.get(), totalProgress, t.getMessage()));
            SystemDistributedKeyspace.failParentRepair(parentSession, t);
            repairComplete();
        }

        private void repairComplete() {
            String duration = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - startTime,
                    true, true);
            String message = String.format("Repair command #%d finished in %s", cmd, duration);
            fireProgressEvent(tag,
                    new ProgressEvent(ProgressEventType.COMPLETE, progress.get(), totalProgress, message));
            logger.info(message);
            if (options.isTraced() && traceState != null) {
                for (ProgressListener listener : listeners)
                    traceState.removeProgressListener(listener);
                // Because DebuggableThreadPoolExecutor#afterExecute and this callback
                // run in a nondeterministic order (within the same thread), the
                // TraceState may have been nulled out at this point. The TraceState
                // should be traceState, so just set it without bothering to check if it
                // actually was nulled out.
                Tracing.instance.set(traceState);
                Tracing.traceRepair(message);
                Tracing.instance.stopSession();
            }
            executor.shutdownNow();
        }
    });
}

From source file:com.ryan.ryanreader.fragments.AddAccountDialog.java

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {

    if (alreadyCreated)
        return getDialog();
    alreadyCreated = true;/*  w w w . j ava  2 s  .c  o m*/

    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.jooq.example.TransactionTest.java

@Test
public void testjOOQTransactionsNested() {
    AtomicBoolean rollback1 = new AtomicBoolean(false);
    AtomicBoolean rollback2 = new AtomicBoolean(false);

    try {//from  w  w w.j  a  va2 s.  c  o  m

        // If using Spring transactions, we don't need the c1 reference
        dsl.transaction(c1 -> {

            // The first insertion will work
            dsl.insertInto(BOOK).set(BOOK.ID, 5).set(BOOK.AUTHOR_ID, 1).set(BOOK.TITLE, "Book 5").execute();

            assertEquals(5, dsl.fetchCount(BOOK));

            try {

                // Nest transactions using Spring. This should create a savepoint, right here
                // If using Spring transactions, we don't need the c2 reference
                dsl.transaction(c2 -> {

                    // The second insertion shouldn't work
                    for (int i = 0; i < 2; i++)
                        dsl.insertInto(BOOK).set(BOOK.ID, 6).set(BOOK.AUTHOR_ID, 1).set(BOOK.TITLE, "Book 6")
                                .execute();

                    Assert.fail();
                });
            }

            catch (DataAccessException e) {
                rollback1.set(true);
            }

            // We should've rolled back to the savepoint
            assertEquals(5, dsl.fetchCount(BOOK));

            throw new org.jooq.exception.DataAccessException("Rollback");
        });
    }

    // Upon the constraint violation, the transaction must already have been rolled back
    catch (org.jooq.exception.DataAccessException e) {
        assertEquals("Rollback", e.getMessage());
        rollback2.set(true);
    }

    assertEquals(4, dsl.fetchCount(BOOK));
    assertTrue(rollback2.get());
    assertTrue(rollback2.get());
}