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.kixeye.chassis.support.test.hystrix.ChassisHystrixTest.java

@Test
public void testBasicHystrixCommand() throws Exception {

    final AtomicBoolean done = new AtomicBoolean(false);
    final AtomicReference<String> result = new AtomicReference<>(null);

    // kick off async command
    Observable<String> observable = new TestCommand().observe();

    // Sleep to test what happens if command finishes before subscription
    Thread.sleep(2000);/*from   w  w  w  .j  a v a 2s.  co m*/

    // Add handler
    observable.subscribe(new Observer<String>() {
        @Override
        public void onCompleted() {
            done.set(true);
        }

        @Override
        public void onError(Throwable e) {
            result.set("error!!");
            done.set(true);
        }

        @Override
        public void onNext(String args) {
            result.set(args);
            done.set(true);
        }
    });

    // spin until done
    while (!done.get()) {
        Thread.sleep(100);
    }

    Assert.assertEquals(resultString, result.get());
}

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//  w w w  .  j  a v  a 2  s  .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:org.apache.hadoop.yarn.applications.mapred.TestDistributedShell.java

@Test(timeout = 90000)
public void testDSShell() throws Exception {

    String[] args = { "--jar", APPMASTER_JAR, "--num_containers", "2", "--shell_command",
            Shell.WINDOWS ? "dir" : "ls", "--master_memory", "512", "--master_vcores", "2",
            "--container_memory", "128", "--container_vcores", "1" };

    LOG.info("Initializing DS Client");
    final Client client = new Client(new Configuration(yarnCluster.getConfig()));
    boolean initSuccess = client.init(args);
    Assert.assertTrue(initSuccess);/*  ww w .  j a  va 2  s  .  co  m*/
    LOG.info("Running DS Client");
    final AtomicBoolean result = new AtomicBoolean(false);
    Thread t = new Thread() {
        public void run() {
            try {
                result.set(client.run());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
    t.start();

    YarnClient yarnClient = YarnClient.createYarnClient();
    yarnClient.init(new Configuration(yarnCluster.getConfig()));
    yarnClient.start();
    String hostName = NetUtils.getHostname();
    boolean verified = false;
    while (!verified) {
        List<ApplicationReport> apps = yarnClient.getApplications();
        if (apps.size() == 0) {
            Thread.sleep(10);
            continue;
        }
        ApplicationReport appReport = apps.get(0);
        if (appReport.getHost().startsWith(hostName) && appReport.getRpcPort() == -1) {
            verified = true;
        }
        if (appReport.getYarnApplicationState() == YarnApplicationState.FINISHED) {
            break;
        }
    }
    Assert.assertTrue(verified);
    t.join();
    LOG.info("Client run completed. Result=" + result);
    Assert.assertTrue(result.get());

    TimelineEntities entitiesAttempts = yarnCluster.getApplicationHistoryServer().getTimelineStore()
            .getEntities(ApplicationMaster.DSEntity.DS_APP_ATTEMPT.toString(), null, null, null, null, null,
                    null, null, null);
    Assert.assertNotNull(entitiesAttempts);
    Assert.assertEquals(1, entitiesAttempts.getEntities().size());
    Assert.assertEquals(2, entitiesAttempts.getEntities().get(0).getEvents().size());
    Assert.assertEquals(entitiesAttempts.getEntities().get(0).getEntityType().toString(),
            ApplicationMaster.DSEntity.DS_APP_ATTEMPT.toString());
    TimelineEntities entities = yarnCluster.getApplicationHistoryServer().getTimelineStore().getEntities(
            ApplicationMaster.DSEntity.DS_CONTAINER.toString(), null, null, null, null, null, null, null, null);
    Assert.assertNotNull(entities);
    Assert.assertEquals(2, entities.getEntities().size());
    Assert.assertEquals(entities.getEntities().get(0).getEntityType().toString(),
            ApplicationMaster.DSEntity.DS_CONTAINER.toString());
}

From source file:org.piraso.server.spring.web.PirasoServletTest.java

@Test
public void testStartStopSuccess()
        throws IOException, ServletException, ExecutionException, InterruptedException {
    final AtomicBoolean fail = new AtomicBoolean(false);
    request.addParameter("service", "start");
    request.addParameter("preferences", mapper.writeValueAsString(new Preferences()));

    ExecutorService executor = Executors.newFixedThreadPool(2);

    Runnable startServiceRunnable = new Runnable() {
        public void run() {
            try {
                servlet.handleRequest(request, response);
            } catch (Exception e) {
                fail.set(true);
                e.printStackTrace();/*from  w  w  w  .j  a  va  2  s. com*/
            }
        }
    };

    Runnable logMessagesRunnable = new Runnable() {
        public void run() {
            try {
                MockHttpServletRequest request = CommonMockObjects.mockRequest(MONITORED_ADDR);
                request.addParameter("activity_uuid", "1");
                request.addParameter("service", "stop");

                // wait till service is available
                while (registry.getLogger(registry.createOrGetUser(pirasoRequest)) == null) {
                    Thread.sleep(100l);
                }

                servlet.handleRequest(request, new MockHttpServletResponse());
            } catch (Exception e) {
                fail.set(true);
                e.printStackTrace();
            }
        }
    };

    Future future = executor.submit(startServiceRunnable);
    executor.submit(logMessagesRunnable);

    future.get();
    executor.shutdown();
}

From source file:com.impetus.client.kudu.schemamanager.KuduDBSchemaManager.java

/**
 * Alter column./*from  w  w  w .  j av  a2s  .  c o  m*/
 * 
 * @param alterTableOptions
 *            the alter table options
 * @param schema
 *            the schema
 * @param columnInfo
 *            the column info
 * @param updated
 *            the updated
 */
private void alterColumn(AlterTableOptions alterTableOptions, Schema schema, ColumnInfo columnInfo,
        AtomicBoolean updated) {
    if (!KuduDBDataHandler.hasColumn(schema, columnInfo.getColumnName())) {
        // add if column is not in schema
        alterTableOptions.addNullableColumn(columnInfo.getColumnName(),
                KuduDBValidationClassMapper.getValidTypeForClass(columnInfo.getType()));
        updated.set(true);
    } else {
        // check for type, drop and add if not consistent TODO: throw
        // exception or override?
        if (!schema.getColumn(columnInfo.getColumnName()).getType()
                .equals(KuduDBValidationClassMapper.getValidTypeForClass(columnInfo.getType()))) {
            alterTableOptions.dropColumn(columnInfo.getColumnName());
            alterTableOptions.addNullableColumn(columnInfo.getColumnName(),
                    KuduDBValidationClassMapper.getValidTypeForClass(columnInfo.getType()));
            updated.set(true);
        }
    }
}

From source file:biz.ganttproject.impex.csv.CsvImportTest.java

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

From source file:org.apache.metron.maas.service.MaasIntegrationTest.java

public void testDSShell(boolean haveDomain) throws Exception {
    MaaSConfig config = new MaaSConfig() {
        {/*from  w w w.ja  v a  2 s .co  m*/
            setServiceRoot("/maas/service");
            setQueueConfig(new HashMap<String, Object>() {
                {
                    put(ZKQueue.ZK_PATH, "/maas/queue");
                }
            });
        }
    };
    String configRoot = "/maas/config";
    byte[] configData = ConfigUtil.INSTANCE.toBytes(config);
    try {
        client.setData().forPath(configRoot, configData);
    } catch (KeeperException.NoNodeException e) {
        client.create().creatingParentsIfNeeded().forPath(configRoot, configData);
    }
    String[] args = { "--jar", yarnComponent.getAppMasterJar(), "--zk_quorum",
            zkServerComponent.getConnectionString(), "--zk_root", configRoot, "--master_memory", "512",
            "--master_vcores", "2", };
    if (haveDomain) {
        String[] domainArgs = { "--domain", "TEST_DOMAIN", "--view_acls", "reader_user reader_group",
                "--modify_acls", "writer_user writer_group", "--create" };
        List<String> argsList = new ArrayList<String>(Arrays.asList(args));
        argsList.addAll(Arrays.asList(domainArgs));
        args = argsList.toArray(new String[argsList.size()]);
    }

    YarnConfiguration conf = yarnComponent.getConfig();
    LOG.info("Initializing DS Client");
    final Client client = new Client(new Configuration(conf));
    boolean initSuccess = client.init(args);
    Assert.assertTrue(initSuccess);
    LOG.info("Running DS Client");
    final AtomicBoolean result = new AtomicBoolean(false);
    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                result.set(client.run());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
    t.start();

    YarnClient yarnClient = YarnClient.createYarnClient();
    yarnClient.init(new Configuration(conf));
    yarnClient.start();
    String hostName = NetUtils.getHostname();

    boolean verified = false;
    String errorMessage = "";
    while (!verified) {
        List<ApplicationReport> apps = yarnClient.getApplications();
        if (apps.size() == 0) {
            Thread.sleep(10);
            continue;
        }
        ApplicationReport appReport = apps.get(0);
        if (appReport.getHost().equals("N/A")) {
            Thread.sleep(10);
            continue;
        }
        errorMessage = "Expected host name to start with '" + hostName + "', was '" + appReport.getHost()
                + "'. Expected rpc port to be '-1', was '" + appReport.getRpcPort() + "'.";
        if (checkHostname(appReport.getHost()) && appReport.getRpcPort() == -1) {
            verified = true;
        }
        if (appReport.getYarnApplicationState() == YarnApplicationState.FINISHED) {
            break;
        }
    }
    Assert.assertTrue(errorMessage, verified);
    FileSystem fs = FileSystem.get(conf);
    try {
        new ModelSubmission().execute(FileSystem.get(conf),
                new String[] { "--name", "dummy", "--version", "1.0", "--zk_quorum",
                        zkServerComponent.getConnectionString(), "--zk_root", configRoot, "--local_model_path",
                        "src/test/resources/maas", "--hdfs_model_path",
                        new Path(fs.getHomeDirectory(), "maas/dummy").toString(), "--num_instances", "1",
                        "--memory", "100", "--mode", "ADD", "--log4j", "src/test/resources/log4j.properties"

                });
        ServiceDiscoverer discoverer = new ServiceDiscoverer(this.client, config.getServiceRoot());
        discoverer.start();
        {
            boolean passed = false;
            for (int i = 0; i < 100; ++i) {
                try {
                    List<ModelEndpoint> endpoints = discoverer.getEndpoints(new Model("dummy", "1.0"));
                    if (endpoints != null && endpoints.size() == 1) {
                        LOG.trace("Found endpoints: " + endpoints.get(0));
                        String output = makeRESTcall(
                                new URL(endpoints.get(0).getEndpoint().getUrl() + "/echo/casey"));
                        if (output.contains("casey")) {
                            passed = true;
                            break;
                        }
                    }
                } catch (Exception e) {
                }
                Thread.sleep(2000);
            }
            Assert.assertTrue(passed);
        }

        {
            List<ModelEndpoint> endpoints = discoverer.getEndpoints(new Model("dummy", "1.0"));
            Assert.assertNotNull(endpoints);
            Assert.assertEquals(1, endpoints.size());
        }
        new ModelSubmission().execute(FileSystem.get(conf),
                new String[] { "--name", "dummy", "--version", "1.0", "--zk_quorum",
                        zkServerComponent.getConnectionString(), "--zk_root", configRoot, "--num_instances",
                        "1", "--mode", "REMOVE",

                });
        {
            boolean passed = false;
            for (int i = 0; i < 100; ++i) {
                try {
                    List<ModelEndpoint> endpoints = discoverer.getEndpoints(new Model("dummy", "1.0"));
                    //ensure that the endpoint is dead.
                    if (endpoints == null || endpoints.size() == 0) {
                        passed = true;
                        break;
                    }
                } catch (Exception e) {
                }
                Thread.sleep(2000);
            }
            Assert.assertTrue(passed);
        }
    } finally {
        cleanup();
    }
}

From source file:com.navercorp.pinpoint.profiler.sender.UdpDataSenderTest.java

private boolean sendMessage_getLimit(TBase tbase, long waitTimeMillis) throws InterruptedException {
    final AtomicBoolean limitCounter = new AtomicBoolean(false);
    final CountDownLatch latch = new CountDownLatch(1);
    final MessageConverter<TBase<?, ?>> messageConverter = new BypassMessageConverter<TBase<?, ?>>();
    final MessageSerializer<ByteMessage> thriftMessageSerializer = new ThriftUdpMessageSerializer(
            messageConverter, ThriftUdpMessageSerializer.UDP_MAX_PACKET_LENGTH) {
        @Override//from  ww w .  j a  v  a  2 s.  com
        protected boolean isLimit(int interBufferSize) {
            final boolean limit = super.isLimit(interBufferSize);
            limitCounter.set(limit);
            latch.countDown();
            return limit;
        }
    };

    UdpDataSender sender = new UdpDataSender("localhost", PORT, "test", 128, 1000, 1024 * 64 * 100,
            thriftMessageSerializer);
    try {
        sender.send(tbase);
        latch.await(waitTimeMillis, TimeUnit.MILLISECONDS);
    } finally {
        sender.stop();
    }
    return limitCounter.get();
}

From source file:com.github.nethad.clustermeister.provisioning.jppf.LocalDriverBuilder.java

@Override
protected ClustermeisterLauncher doBuild() {
    JPPFDriverConfigurationSource.serverPort = serverPort;
    JPPFDriverConfigurationSource.managementPort = managementPort;
    JPPFDriverConfigurationSource.jvmOptions = configuration
            .getString(ConfigurationKeys.JVM_OPTIONS_LOCAL_DRIVER, "");
    Map<String, String> loadBalancingConfigValues = new DriverLoadBalancing(configuration)
            .getLoadBalancingConfigValues();
    if (loadBalancingConfigValues.isEmpty()) {
        //                logger.info("No load balancing settings set.");
    } else {//from   w w  w  .ja  v a2s .  c om
        for (Map.Entry<String, String> entry : loadBalancingConfigValues.entrySet()) {
            //                    logger.info("{} => {}", entry.getKey(), entry.getValue());
        }
    }
    JPPFDriverConfigurationSource.loadBalancing = new DriverLoadBalancing(configuration)
            .getLoadBalancingConfigValues();
    final ClustermeisterLauncher launcher = new ClustermeisterDriverLauncher(true);
    final AtomicBoolean initialized = new AtomicBoolean(false);
    final Monitor initializationMonitor = new Monitor(false);
    final Monitor.Guard isInitialized = new Monitor.Guard(initializationMonitor) {
        @Override
        public boolean isSatisfied() {
            return initialized.get();
        }
    };
    launcher.addObserver(new Observer() {
        @Override
        public void update(Observable o, Object arg) {
            initializationMonitor.enter();
            try {
                initialized.set(true);
            } finally {
                initializationMonitor.leave();
            }
        }
    });
    Thread driverThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                launcher.doLaunch(true, ClustermeisterProcessLauncher.StreamSink.LOG);
            } catch (Throwable ex) {
                logger.warn("Execption from local driver thread.", ex);
            }
        }
    });
    driverThread.setName(String.format("%s-%s", DRIVER_THREAD_NAME, driverThread.getId()));
    driverThread.start();

    //wait for driver to initialize.
    initializationMonitor.enter();
    try {
        try {
            initializationMonitor.waitFor(isInitialized);
        } catch (InterruptedException ex) {
            logger.warn("Interrupted while waiting for local driver to initialize! "
                    + "Initialization may not be complete.", ex);
        }
    } finally {
        initializationMonitor.leave();
    }
    return launcher;
}

From source file:com.adaptris.core.fs.FsMessageConsumerTest.java

public void testRedmine481_SubDirInConsumeDirectory() throws Exception {
    String consumeDir = new GuidGenerator().safeUUID();
    File parentDir = FsHelper/*  ww  w .ja va 2 s.c  o m*/
            .createFileReference(FsHelper.createUrlFromString(PROPERTIES.getProperty(BASE_KEY), true));

    String subDir = parentDir.getCanonicalPath() + "/" + consumeDir + "/" + new GuidGenerator().safeUUID();
    File subDirectory = new File(subDir);
    subDirectory.mkdirs();
    FsConsumer fs = createConsumer(consumeDir);
    fs.setReacquireLockBetweenMessages(true);
    AtomicBoolean pollFired = new AtomicBoolean(false);
    fs.setPoller(
            new FixedIntervalPoller(new TimeInterval(300L, TimeUnit.MILLISECONDS)).withPollerCallback(e -> {
                pollFired.set(true);
            }));
    File wipDirectory = new File(subDir + fs.getWipSuffix());
    MockMessageListener stub = new MockMessageListener(0);
    StandaloneConsumer sc = new StandaloneConsumer(fs);
    sc.registerAdaptrisMessageListener(stub);
    try {
        start(sc);
        waitForPollCallback(pollFired);
        assertEquals(true, subDirectory.exists());
        assertEquals(true, subDirectory.isDirectory());
        assertEquals(false, wipDirectory.exists());
    } finally {
        stop(sc);
        FileUtils.deleteQuietly(new File(PROPERTIES.getProperty(BASE_KEY), consumeDir));
    }
}