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

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

Introduction

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

Prototype

public AtomicBoolean(boolean initialValue) 

Source Link

Document

Creates a new AtomicBoolean with the given initial value.

Usage

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/*www  .  j  av a2 s.c o m*/
            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:ductive.console.shell.EmbeddedGroovyShell.java

@Override
public void execute(InteractiveTerminal terminal, TerminalUser user) throws IOException {
    Binding binding = new Binding();

    if (context != null)
        for (Entry<String, Object> e : context.entrySet())
            binding.setVariable(e.getKey(), e.getValue());

    CompilerConfiguration config = new CompilerConfiguration();
    binding.setProperty("out", new PrintStream(terminal.output(), true));
    // binding.setProperty("in",new BufferedReader(new InputStreamReader(terminal.input()))); FIXME:
    GroovyInterpreter interpreter = new GroovyInterpreter(binding, config);

    try (ShellHistory history = historyProvider.history(HISTORY_KEY)) {

        final AtomicBoolean pending = new AtomicBoolean(false);
        ShellSettings settings = new StaticShellSettings(new Provider<Ansi>() {
            @Override/*from ww  w .ja va  2s .  c  o  m*/
            public Ansi get() {
                return pending.get() ? pendingPrompt : standardPrompt;
            }
        }, new ReflectionCompleter(interpreter), history);
        terminal.updateSettings(settings);

        while (true) {
            pending.set(false);

            final String code;
            try {
                code = new CodeReader(terminal, pending).read();
            } catch (UserInterruptException e) {

                continue;
            }

            if (code == null) {
                terminal.println("");
                break;
            }

            if (StringUtils.isBlank(code))
                continue;

            try {
                Object result = interpreter.interpret(code);
                terminal.println(String.format(resultMarker.toString(), result));
            } catch (Throwable e) {
                // Unroll invoker exceptions
                if (e instanceof InvokerInvocationException) {
                    e = e.getCause();
                }

                PrintStream ps = new PrintStream(terminal.error());
                e.printStackTrace(ps);
                ps.flush();
            }
        }

    }
}

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

@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {

    if (alreadyCreated)
        return getDialog();
    alreadyCreated = true;/*from   w w w  . j a  va 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:eu.stratosphere.pact.runtime.task.MapTaskTest.java

@Test
public void testCancelMapTask() {
    addInput(new InfiniteInputIterator());
    setOutput(new DiscardingOutputCollector<Record>());

    final CollectorMapDriver<Record, Record> testTask = new CollectorMapDriver<Record, Record>();

    final AtomicBoolean success = new AtomicBoolean(false);

    final Thread taskRunner = new Thread() {
        @Override// w w  w. ja  va2  s .c  om
        public void run() {
            try {
                testDriver(testTask, MockMapStub.class);
                success.set(true);
            } catch (Exception ie) {
                ie.printStackTrace();
            }
        }
    };
    taskRunner.start();

    TaskCancelThread tct = new TaskCancelThread(1, taskRunner, this);
    tct.start();

    try {
        tct.join();
        taskRunner.join();
    } catch (InterruptedException ie) {
        Assert.fail("Joining threads failed");
    }

    Assert.assertTrue("Test threw an exception even though it was properly canceled.", success.get());
}

From source file:com.flowpowered.engine.scheduler.FlowTask.java

/**
 * Creates a new task with the specified period between consecutive calls to {@link #run()}.
 *///from w  w w  . ja va  2s .  co m
public FlowTask(FlowTaskManager manager, Scheduler scheduler, Object owner, Runnable task, boolean sync,
        long delay, long period, TaskPriority priority) {
    super(task, null);
    Validate.isTrue(!sync || priority != null, "Priority cannot be null if sync!");
    this.taskId = nextTaskId.getAndIncrement();
    this.nextCallTime = new AtomicLong(manager.getUpTime() + delay);
    this.executing = new AtomicBoolean(false);
    this.owner = owner;
    this.delay = delay;
    this.period = period;
    this.sync = sync;
    this.priority = priority;
    this.manager = manager;
    this.scheduler = scheduler;
}

From source file:com.nridge.examples.oss.datatable.DataTableTask.java

/**
  * If this task is scheduled to be executed (e.g. its run/test
  * name matches the command line arguments), then this method
  * is guaranteed to be executed prior to the thread being
  * started.//from   w  w  w .j  av  a2  s .  c  o  m
  *
  * @param anAppMgr Application manager instance.
  *
  * @throws NSException Application specific exception.
  */
@Override
public void init(AppMgr anAppMgr) throws NSException {
    mAppMgr = anAppMgr;
    Logger appLogger = mAppMgr.getLogger(this, "init");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    mIsAlive = new AtomicBoolean(false);

    appLogger.info("The init method was invoked.");
    Sleep.forSeconds(1);

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    mIsAlive.set(true);
}

From source file:com.nridge.examples.oss.ds_rdbms.DSRDBMSTask.java

/**
  * If this task is scheduled to be executed (e.g. its run/test
  * name matches the command line arguments), then this method
  * is guaranteed to be executed prior to the thread being
  * started.//from ww w.j  a v a 2 s  .co  m
  *
  * @param anAppMgr Application manager instance.
  *
  * @throws NSException Application specific exception.
  */
@Override
public void init(AppMgr anAppMgr) throws NSException {
    mAppMgr = anAppMgr;
    Logger appLogger = mAppMgr.getLogger(this, "init");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    mIsAlive = new AtomicBoolean(false);

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    mIsAlive.set(true);
}

From source file:com.splout.db.integration.TestMultiThreadedQueryAndDeploy.java

@Test
@Ignore // Causes some non-deterministic problems, to be analyzed
public void test() throws Throwable {
    FileUtils.deleteDirectory(new File(TMP_FOLDER));
    new File(TMP_FOLDER).mkdirs();

    createSploutEnsemble(N_QNODES, N_DNODES);
    String[] qNodeAddresses = new String[N_QNODES];
    for (int i = 0; i < N_QNODES; i++) {
        qNodeAddresses[i] = getqNodes().get(i).getAddress();
    }//from  ww w. j  ava2s  . co  m

    final SploutClient client = new SploutClient(qNodeAddresses);
    final Tablespace testTablespace = createTestTablespace(N_DNODES);
    final Random random = new Random(SEED);
    final AtomicBoolean failed = new AtomicBoolean(false);
    final AtomicInteger iteration = new AtomicInteger(0);
    final Set<Integer> iterationsSeen = new HashSet<Integer>();

    deployIteration(0, random, client, testTablespace);

    for (QNode qnode : getqNodes()) {
        // Make sure all QNodes are aware of the the first deploy
        // There might be some delay as they have to receive notifications via Hazelcast etc
        long waitedSoFar = 0;
        QueryStatus status = null;
        SploutClient perQNodeClient = new SploutClient(qnode.getAddress());
        do {
            status = perQNodeClient.query(TABLESPACE, "0", "SELECT * FROM " + TABLE + ";", null);
            Thread.sleep(100);
            waitedSoFar += 100;
            if (waitedSoFar > 5000) {
                throw new AssertionError("Waiting too much on a test condition");
            }
        } while (status == null || status.getError() != null);
        log.info("QNode [" + qnode.getAddress() + "] is ready to serve deploy 0.");
    }

    try {
        // Business logic here
        ExecutorService service = Executors.newFixedThreadPool(N_THREADS);

        // These threads will continuously perform queries and check that the results is consistent.
        // They will also count how many deploys have happened since the beginning.
        for (int i = 0; i < N_THREADS; i++) {
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            int randomDNode = Math.abs(random.nextInt()) % N_DNODES;
                            QueryStatus status = client.query(TABLESPACE, (randomDNode * 10) + "",
                                    "SELECT * FROM " + TABLE + ";", null);
                            log.info("Query status -> " + status);
                            assertEquals(1, status.getResult().size());
                            Map<String, Object> jsonResult = (Map<String, Object>) status.getResult().get(0);
                            Integer seenIteration = (Integer) jsonResult.get("iteration");
                            synchronized (iterationsSeen) {
                                iterationsSeen.add(seenIteration);
                            }
                            assertTrue(seenIteration <= iteration.get());
                            assertEquals(randomDNode, jsonResult.get("dnode"));
                            Thread.sleep(100);
                        }
                    } catch (InterruptedException ie) {
                        // Bye bye
                        log.info("Bye bye!");
                    } catch (Throwable e) {
                        e.printStackTrace();
                        failed.set(true);
                    }
                }
            });
        }

        final SploutConfiguration config = SploutConfiguration.getTestConfig();
        final int iterationsToPerform = config.getInt(QNodeProperties.VERSIONS_PER_TABLESPACE) + 5;
        for (int i = 0; i < iterationsToPerform; i++) {
            iteration.incrementAndGet();
            log.info("Deploy iteration: " + iteration.get());
            deployIteration(iteration.get(), random, client, testTablespace);

            new TestUtils.NotWaitingForeverCondition() {
                @Override
                public boolean endCondition() {
                    synchronized (iterationsSeen) {
                        return iterationsSeen.size() == (iteration.get() + 1);
                    }
                }
            }.waitAtMost(5000);
        }

        assertEquals(false, failed.get());

        service.shutdownNow(); // will interrupt all threads
        while (!service.isTerminated()) {
            Thread.sleep(100);
        }

        CoordinationStructures coord = TestUtils.getCoordinationStructures(config);
        assertNotNull(coord.getCopyVersionsBeingServed().get(TABLESPACE));

        // Assert that there is only MAX_VERSIONS versions of the tablespace (due to old version cleanup)
        new TestUtils.NotWaitingForeverCondition() {

            @Override
            public boolean endCondition() {
                QNodeHandler handler = (QNodeHandler) qNodes.get(0).getHandler();
                int seenVersions = 0;
                for (Map.Entry<TablespaceVersion, Tablespace> tablespaceVersion : handler.getContext()
                        .getTablespaceVersionsMap().entrySet()) {
                    if (tablespaceVersion.getKey().getTablespace().equals(TABLESPACE)) {
                        seenVersions++;
                    }
                }
                return seenVersions <= config.getInt(QNodeProperties.VERSIONS_PER_TABLESPACE);
            }
        }.waitAtMost(5000);
    } finally {
        closeSploutEnsemble();
        FileUtils.deleteDirectory(new File(TMP_FOLDER));
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.TenantRoutingAuthenticationComponentFacade.java

/**
 * {@inheritDoc}//from   w w w .j a va 2  s . c o m
 */
@Override
public boolean isActive() {
    final AtomicBoolean isActive = new AtomicBoolean(false);

    LOGGER.trace("Checking isActive for enabled tenants (until first active tenant)");
    for (final String tenantDomain : this.enabledTenants) {
        if (!isActive.get()) {
            isActive.set(this.isActive(tenantDomain));
        }
    }
    LOGGER.trace("Component is active: {}", isActive.get());

    return isActive.get();
}

From source file:fr.mby.saml2.sp.opensaml.core.OpenSaml20SpProcessorTest.java

@Test
public void testTryAuthenticationPropagation() throws Exception {

    final IIncomingSaml incomingSaml = Mockito.mock(IIncomingSaml.class);
    final QueryAuthnResponse queryAuthnResponse = Mockito.mock(QueryAuthnResponse.class);
    final List<IAuthentication> authns = new ArrayList<IAuthentication>();
    final BasicSamlAuthentication basicAuth = new BasicSamlAuthentication();
    basicAuth.addAttribute(AUTH_ATTR_KEY, AUTH_ATTR_VALUES);
    authns.add(basicAuth);/*  w ww  . j  a v a2  s  .  c om*/

    Mockito.when(incomingSaml.getSamlQuery()).thenReturn(queryAuthnResponse);
    Mockito.when(queryAuthnResponse.getSamlAuthentications()).thenReturn(authns);

    final AtomicBoolean authPropagated = new AtomicBoolean(false);

    this.spProcessor.setAuthenticationHandler(new IAuthenticationHandler() {

        @Override
        public void propagateAuthentications(List<IAuthentication> authentications) {
            Assert.assertNotNull("No authentications propagated !", authentications);
            Assert.assertEquals("Bad authentications list size !", authns.size(), authentications.size());

            final IAuthentication authn = authentications.iterator().next();
            Assert.assertNotNull("Null authentication attributes list !", authn.getAttributes());
            Assert.assertEquals("Bad authentication attributes list size !", basicAuth.getAttributes().size(),
                    authn.getAttributes().size());

            final List<String> values = authn.getAttribute(AUTH_ATTR_KEY);
            Assert.assertNotNull("No attribute values found in propagated authentications !", values);
            Assert.assertEquals("Bad values list size !", AUTH_ATTR_VALUES.size(), values.size());

            final Iterator<String> valuesIt = values.iterator();
            Assert.assertEquals("Bad first propagated authentication attibutes !", AUTH_ATTR_VALUE_1,
                    valuesIt.next());
            Assert.assertEquals("Bad second propagated authentication attribute value !", AUTH_ATTR_VALUE_2,
                    valuesIt.next());

            authPropagated.set(true);
        }
    });

    this.spProcessor.tryAuthenticationPropagation(incomingSaml);

    Assert.assertTrue("Authentication wasn't propagated !", authPropagated.get());
}