List of usage examples for java.util.concurrent.atomic AtomicBoolean set
public final void set(boolean newValue)
From source file:cc.gospy.example.google.GoogleSpider.java
public Collection<String> getResultLinks(final String keyword, final int pageFrom, final int pageTo) { if (pageFrom < 1) throw new IllegalArgumentException(pageFrom + "<" + 1); if (pageFrom >= pageTo) throw new IllegalArgumentException(pageFrom + ">=" + pageTo); final AtomicInteger currentPage = new AtomicInteger(pageFrom); final AtomicBoolean returned = new AtomicBoolean(false); final Collection<String> links = new LinkedHashSet<>(); Gospy googleSpider = Gospy.custom()/*from w w w.j a v a 2 s . c om*/ .setScheduler( Schedulers.VerifiableScheduler.custom().setExitCallback(() -> returned.set(true)).build()) .addFetcher(Fetchers.HttpFetcher.custom() .before(request -> request.setConfig( RequestConfig.custom().setProxy(new HttpHost("127.0.0.1", 8118)).build())) .build()) .addProcessor(Processors.XPathProcessor.custom() .extract("//*[@id='ires']/ol/div/h3/a/@href", (task, resultList, returnedData) -> { resultList.forEach(a -> { if (a.startsWith("/url?q=")) { String link = a.substring(7); int end = link.indexOf("&sa="); links.add(link.substring(0, end != -1 ? end : link.length())); } }); currentPage.incrementAndGet(); if (pageFrom <= currentPage.get() && currentPage.get() < pageTo) { return Arrays.asList( new Task(String.format("http://www.google.com/search?q=%s&start=%d&*", keyword, (currentPage.get() - 1) * 10))); } else { return Arrays.asList(); } }).build()) .build().addTask(String.format("http://www.google.com/search?q=%s&start=%d&*", keyword, pageFrom)); googleSpider.start(); while (!returned.get()) ; // block until spider returned googleSpider.stop(); return links; }
From source file:com.corundumstudio.socketio.annotation.SpringAnnotationScanner.java
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { final AtomicBoolean add = new AtomicBoolean(); ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() { @Override// w w w . j a v a2 s. c om public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { add.set(true); } }, new MethodFilter() { @Override public boolean matches(Method method) { for (Class<? extends Annotation> annotationClass : annotations) { if (method.isAnnotationPresent(annotationClass)) { return true; } } return false; } }); if (add.get()) { originalBeanClass = bean.getClass(); } return bean; }
From source file:gobblin.runtime.StateStoreBasedWatermarkStorageCli.java
@Override public void run(String[] args) { Options options = new Options(); options.addOption(HELP);/* ww w . ja v a 2s . c o m*/ options.addOption(ZK); options.addOption(JOB_NAME); options.addOption(ROOT_DIR); options.addOption(WATCH); CommandLine cli; try { CommandLineParser parser = new DefaultParser(); cli = parser.parse(options, Arrays.copyOfRange(args, 1, args.length)); } catch (ParseException pe) { System.out.println("Command line parse exception: " + pe.getMessage()); return; } if (cli.hasOption(HELP.getOpt())) { printUsage(options); return; } TaskState taskState = new TaskState(); String jobName; if (!cli.hasOption(JOB_NAME.getOpt())) { log.error("Need Job Name to be specified --", JOB_NAME.getLongOpt()); throw new RuntimeException("Need Job Name to be specified"); } else { jobName = cli.getOptionValue(JOB_NAME.getOpt()); log.info("Using job name: {}", jobName); } taskState.setProp(ConfigurationKeys.JOB_NAME_KEY, jobName); String zkAddress = "locahost:2181"; if (cli.hasOption(ZK.getOpt())) { zkAddress = cli.getOptionValue(ZK.getOpt()); } log.info("Using zk address : {}", zkAddress); taskState.setProp(StateStoreBasedWatermarkStorage.WATERMARK_STORAGE_TYPE_KEY, "zk"); taskState.setProp("state.store.zk.connectString", zkAddress); if (cli.hasOption(ROOT_DIR.getOpt())) { String rootDir = cli.getOptionValue(ROOT_DIR.getOpt()); taskState.setProp(StateStoreBasedWatermarkStorage.WATERMARK_STORAGE_CONFIG_PREFIX + ConfigurationKeys.STATE_STORE_ROOT_DIR_KEY, rootDir); log.info("Setting root dir to {}", rootDir); } else { log.error("Need root directory specified"); printUsage(options); return; } StateStoreBasedWatermarkStorage stateStoreBasedWatermarkStorage = new StateStoreBasedWatermarkStorage( taskState); final AtomicBoolean stop = new AtomicBoolean(true); if (cli.hasOption(WATCH.getOpt())) { stop.set(false); } try { if (!stop.get()) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { stop.set(true); } }); } do { boolean foundWatermark = false; try { for (CheckpointableWatermarkState wmState : stateStoreBasedWatermarkStorage .getAllCommittedWatermarks()) { foundWatermark = true; System.out.println(wmState.getProperties()); } } catch (IOException ie) { Throwables.propagate(ie); } if (!foundWatermark) { System.out.println("No watermarks found."); } if (!stop.get()) { Thread.sleep(1000); } } while (!stop.get()); } catch (Exception e) { Throwables.propagate(e); } }
From source file:io.dropwizard.discovery.bundle.ServiceDiscoveryBundleCustomHostPortTest.java
@Before public void setup() throws Exception { when(jerseyEnvironment.getResourceConfig()).thenReturn(new DropwizardResourceConfig()); when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthChecks); when(environment.getObjectMapper()).thenReturn(new ObjectMapper()); AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); doNothing().when(adminEnvironment).addTask(any()); when(environment.admin()).thenReturn(adminEnvironment); testingCluster.start();/*w ww .j a va2 s . co m*/ serviceDiscoveryConfiguration = ServiceDiscoveryConfiguration.builder() .zookeeper(testingCluster.getConnectString()).namespace("test").environment("testing") .connectionRetryIntervalMillis(5000).publishedHost("TestHost").publishedPort(8021) .initialRotationStatus(true).build(); bundle.initialize(bootstrap); bundle.run(configuration, environment); final AtomicBoolean started = new AtomicBoolean(false); executorService.submit(() -> lifecycleEnvironment.getManagedObjects().forEach(object -> { try { object.start(); started.set(true); } catch (Exception e) { e.printStackTrace(); } })); while (!started.get()) { Thread.sleep(1000); log.debug("Waiting for framework to start..."); } bundle.registerHealthcheck(() -> status); }
From source file:io.dropwizard.discovery.bundle.ServiceDiscoveryBundleRotationTest.java
@Before public void setup() throws Exception { when(jerseyEnvironment.getResourceConfig()).thenReturn(new DropwizardResourceConfig()); when(environment.jersey()).thenReturn(jerseyEnvironment); when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.healthChecks()).thenReturn(healthChecks); when(environment.getObjectMapper()).thenReturn(new ObjectMapper()); AdminEnvironment adminEnvironment = mock(AdminEnvironment.class); doNothing().when(adminEnvironment).addTask(any()); when(environment.admin()).thenReturn(adminEnvironment); testingCluster.start();/*from w w w . j a v a 2 s .c o m*/ serviceDiscoveryConfiguration = ServiceDiscoveryConfiguration.builder() .zookeeper(testingCluster.getConnectString()).namespace("test").environment("testing") .connectionRetryIntervalMillis(5000).publishedHost("TestHost").publishedPort(8021) .initialRotationStatus(true).build(); bundle.initialize(bootstrap); bundle.run(configuration, environment); rotationStatus = bundle.getRotationStatus(); final AtomicBoolean started = new AtomicBoolean(false); executorService.submit(() -> lifecycleEnvironment.getManagedObjects().forEach(object -> { try { object.start(); started.set(true); } catch (Exception e) { e.printStackTrace(); } })); while (!started.get()) { Thread.sleep(1000); log.debug("Waiting for framework to start..."); } }
From source file:com.adaptris.core.lms.StreamWrapperCase.java
@Test public void testInputStream_Read() throws Exception { StreamWrapper wrapper = createWrapper(false); AtomicBoolean callback = new AtomicBoolean(false); File file = writeFile(TempFileUtils.createTrackedFile(wrapper)); InputStream in = wrapper.openInputStream(file, () -> { callback.set(true); });/*w ww. j a v a 2 s . co m*/ try (InputStream closeable = in) { int read = 0; while (read != -1) { read = closeable.read(); } } tryQuietly(() -> { in.close(); }); assertTrue(callback.get()); }
From source file:com.jayway.restassured.path.json.JsonPathObjectDeserializationTest.java
@Test public void json_path_supports_custom_deserializer_with_static_configuration() { // Given//from w ww.j a v a 2 s. c o m final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false); JsonPath.config = new JsonPathConfig().defaultObjectDeserializer(new JsonPathObjectDeserializer() { public <T> T deserialize(ObjectDeserializationContext ctx) { customDeserializerUsed.set(true); final String json = ctx.getDataToDeserialize().asString(); final Greeting greeting = new Greeting(); greeting.setFirstName(StringUtils.substringBetween(json, "\"firstName\":\"", "\"")); greeting.setLastName(StringUtils.substringBetween(json, "\"lastName\":\"", "\"")); return (T) greeting; } }); final JsonPath jsonPath = new JsonPath(GREETING); // When try { final Greeting greeting = jsonPath.getObject("", Greeting.class); // Then assertThat(greeting.getFirstName(), equalTo("John")); assertThat(greeting.getLastName(), equalTo("Doe")); assertThat(customDeserializerUsed.get(), is(true)); } finally { JsonPath.reset(); } }
From source file:com.netflix.conductor.core.events.TestEventProcessor.java
@Test public void testEventProcessor() throws Exception { String event = "sqs:arn:account090:sqstest1"; String queueURI = "arn:account090:sqstest1"; EventQueueProvider provider = mock(EventQueueProvider.class); ObservableQueue queue = mock(ObservableQueue.class); Message[] messages = new Message[1]; messages[0] = new Message("t0", "{}", "t0"); Observable<Message> msgObservable = Observable.from(messages); when(queue.observe()).thenReturn(msgObservable); when(queue.getURI()).thenReturn(queueURI); when(queue.getName()).thenReturn(queueURI); when(queue.getType()).thenReturn("sqs"); when(provider.getQueue(queueURI)).thenReturn(queue); EventQueues.registerProvider(QueueType.sqs, provider); EventHandler eh = new EventHandler(); eh.setName(UUID.randomUUID().toString()); eh.setActive(false);/* ww w . j ava 2 s .c o m*/ Action action = new Action(); action.setAction(Type.start_workflow); action.setStart_workflow(new StartWorkflow()); action.getStart_workflow().setName("workflow_x"); action.getStart_workflow().setVersion(1); //TODO: Remove this to simulate the null value for version being passed! eh.getActions().add(action); eh.setEvent(event); MetadataService ms = mock(MetadataService.class); when(ms.getEventHandlers()).thenReturn(Arrays.asList(eh)); when(ms.getEventHandlersForEvent(eh.getEvent(), true)).thenReturn(Arrays.asList(eh)); //Execution Service Mock ExecutionService eservice = mock(ExecutionService.class); when(eservice.addEventExecution(any())).thenReturn(true); //Workflow Executor Mock WorkflowExecutor executor = mock(WorkflowExecutor.class); String id = UUID.randomUUID().toString(); AtomicBoolean started = new AtomicBoolean(false); doAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { started.set(true); return id; } }).when(executor).startWorkflow(action.getStart_workflow().getName(), 1, action.getStart_workflow().getCorrelationId(), action.getStart_workflow().getInput()); //Metadata Service Mock MetadataService metadata = mock(MetadataService.class); WorkflowDef def = new WorkflowDef(); def.setVersion(1); def.setName(action.getStart_workflow().getName()); when(metadata.getWorkflowDef(any(), any())).thenReturn(def); ActionProcessor ap = new ActionProcessor(executor, metadata); EventProcessor ep = new EventProcessor(eservice, ms, ap, new TestConfiguration(), new ObjectMapper()); assertNotNull(ep.getQueues()); assertEquals(1, ep.getQueues().size()); String queueEvent = ep.getQueues().keySet().iterator().next(); assertEquals(eh.getEvent(), queueEvent); String epQueue = ep.getQueues().values().iterator().next(); assertEquals(queueURI, epQueue); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); assertTrue(started.get()); }
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//from w ww. jav a 2 s. co m 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()); }