com.google.common.util.concurrent.Callables Java Examples

The following examples show how to use com.google.common.util.concurrent.Callables. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PackageSplitAbi.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
@NonNull
public synchronized ImmutableList<ApkOutputFile> getOutputSplitFiles() {

    if (outputFiles == null) {
        ImmutableList.Builder<ApkOutputFile> builder = ImmutableList.builder();
        for (String split : splits) {
            String apkName = getApkName(split);
            ApkOutputFile apkOutput = new ApkOutputFile(
                    OutputFile.OutputType.SPLIT,
                    ImmutableList.of(FilterDataImpl.build(OutputFile.ABI, apkName)),
                    Callables.returning(new File(outputDirectory, apkName)));
            builder.add(apkOutput);
        }

        outputFiles = builder.build();
    }
    return outputFiles;
}
 
Example #2
Source File: RepeaterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/**
 * Check that the {@link Repeater} will stop after a time limit.
 *
 * The repeater is configured to run every 100ms and never stop until the limit is reached.
 * This is given as {@link Repeater#limitTimeTo(org.apache.brooklyn.util.time.Duration)} and the execution time
 * is then checked to ensure it is between 100% and 400% of the specified value. Due to scheduling
 * delays and other factors in a non RTOS system it is expected that the repeater will take much
 * longer to exit occasionally.
 *
 * @see #runRespectsMaximumIterationLimitAndReturnsFalseIfReached()
 */
@Test(groups="Integration")
public void runRespectsTimeLimitAndReturnsFalseIfReached() {
    final long LIMIT = 2000l;
    Repeater repeater = new Repeater("runRespectsTimeLimitAndReturnsFalseIfReached")
        .every(Duration.millis(100))
        .until(Callables.returning(false))
        .limitTimeTo(LIMIT, TimeUnit.MILLISECONDS);

    Stopwatch stopwatch = Stopwatch.createStarted();
    boolean result = repeater.run();
    stopwatch.stop();

    assertFalse(result);

    long difference = stopwatch.elapsed(TimeUnit.MILLISECONDS);
    assertTrue(difference >= LIMIT, "Difference was: " + difference);
    assertTrue(difference < 4 * LIMIT, "Difference was: " + difference);
}
 
Example #3
Source File: XmlMementoSerializerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testTask() throws Exception {
    final TestApplication app = TestApplication.Factory.newManagedInstanceForTests();
    mgmt = app.getManagementContext();
    Task<String> completedTask = app.getExecutionContext().submit("return myval", Callables.returning("myval"));
    completedTask.get();
    
    String loggerName = UnwantedStateLoggingMapper.class.getName();
    ch.qos.logback.classic.Level logLevel = ch.qos.logback.classic.Level.WARN;
    Predicate<ILoggingEvent> filter = EventPredicates.containsMessage("Task object serialization is not supported or recommended"); 
    String serializedForm;
    try (LogWatcher watcher = new LogWatcher(loggerName, logLevel, filter)) {
        serializedForm = serializer.toString(completedTask);
        watcher.assertHasEvent();
    }

    assertEquals(serializedForm.trim(), "<"+BasicTask.class.getName()+">myval</"+BasicTask.class.getName()+">");
    Object deserialized = serializer.fromString(serializedForm);
    assertEquals(deserialized, null, "serializedForm="+serializedForm+"; deserialized="+deserialized);
}
 
Example #4
Source File: RebindFeedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    super.init();
    addFeed(FunctionFeed.builder()
            .entity(this)
            .poll(FunctionPollConfig.forSensor(SENSOR_INT)
                    .period(POLL_PERIOD)
                    .callable(Callables.returning(1)))
            .build());
    addFeed(FunctionFeed.builder()
            .entity(this)
            .poll(FunctionPollConfig.forSensor(SENSOR_STRING)
                    .period(POLL_PERIOD)
                    .callable(Callables.returning("OK")))
            .build());
}
 
Example #5
Source File: PluggableJobTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Test
public void testStaleFiresFutureListener() throws InterruptedException {
  Object obj = new Object();
  final PluggableJob<Object> job =
      new PluggableJob<>("name", Callables.returning(obj), unused -> true);
  assertFalse(job.getFuture().isDone());
  final boolean[] listenerRun = new boolean[] {false};
  job.getFuture().addListener(() -> {
    listenerRun[0] = true;
    assertTrue(job.getFuture().isCancelled());
  }, MoreExecutors.directExecutor());
  assertFalse(listenerRun[0]);
  job.schedule();
  job.join();
  assertTrue(listenerRun[0]);
  assertEquals("Should be CANCEL", IStatus.CANCEL, job.getResult().getSeverity());
}
 
Example #6
Source File: SingleThreadedSchedulerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetResultOfQueuedTaskBeforeItExecutes() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    em.submit(MutableMap.of("tag", "category1"), newLatchAwaiter(latch));
    
    BasicTask<Integer> t = new BasicTask<Integer>(Callables.returning(123));
    Future<Integer> future = em.submit(MutableMap.of("tag", "category1"), t);

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            latch.countDown();
        }});
    thread.start();
    assertEquals(future.get(), (Integer)123);
}
 
Example #7
Source File: TasksTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRepeaterDescription() throws Exception{
    final String description = "task description";
    Repeater repeater = Repeater.create(description)
        .repeat(Callables.returning(null))
        .every(Duration.ONE_MILLISECOND)
        .limitIterationsTo(1)
        .until(new Callable<Boolean>() {
            @Override
            public Boolean call() {
                TaskInternal<?> current = (TaskInternal<?>)Tasks.current();
                assertEquals(current.getBlockingDetails(), description);
                return true;
            }
        });
    Task<Boolean> t = Tasks.testing(repeater).build();
    app.getExecutionContext().submit(t);
    assertTrue(t.get(Duration.TEN_SECONDS));
}
 
Example #8
Source File: FunctionFeedTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unused")
public void testFunctionPollConfigBuilding() throws Exception {
    FunctionPollConfig<Integer, Integer> typeFromCallable = FunctionPollConfig.forSensor(SENSOR_INT)
            .period(1)
            .callable(Callables.returning(1))
            .onSuccess(Functions.constant(-1));

    FunctionPollConfig<Integer, Integer> typeFromSupplier = FunctionPollConfig.forSensor(SENSOR_INT)
            .period(1)
            .supplier(Suppliers.ofInstance(1))
            .onSuccess(Functions.constant(-1));

    FunctionPollConfig<Integer, Integer> usingConstructor = new FunctionPollConfig<Integer, Integer>(SENSOR_INT)
            .period(1)
            .supplier(Suppliers.ofInstance(1))
            .onSuccess(Functions.constant(-1));

    FunctionPollConfig<Integer, Integer> usingConstructorWithFailureOrException = new FunctionPollConfig<Integer, Integer>(SENSOR_INT)
            .period(1)
            .supplier(Suppliers.ofInstance(1))
            .onFailureOrException(Functions.<Integer>constant(null));
}
 
Example #9
Source File: SkyframeAwareActionTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void assertActionWithContentChangingInput(final boolean unconditionalExecution)
    throws Exception {
  // Assert that a simple, non-skyframe-aware action is executed twice
  // if its input's content changes between builds.
  assertActionExecutions(
      new ExecutionCountingActionFactory() {
        @Override
        public ExecutionCountingAction create(
            Artifact input, Artifact output, AtomicInteger executionCounter) {
          return unconditionalExecution
              ? new ExecutionCountingCacheBypassingAction(input, output, executionCounter)
              : new ExecutionCountingAction(input, output, executionCounter);
        }
      },
      ChangeArtifact.CHANGE_MTIME_AND_CONTENT,
      Callables.<Void>returning(null),
      ExpectActionIs.REEXECUTED);
}
 
Example #10
Source File: SkyframeAwareActionTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void assertActionWithMtimeChangingInput(final boolean unconditionalExecution)
    throws Exception {
  // Assert that a simple, non-skyframe-aware action is executed only once
  // if its input's mtime changes but its contents stay the same between builds.
  assertActionExecutions(
      new ExecutionCountingActionFactory() {
        @Override
        public ExecutionCountingAction create(
            Artifact input, Artifact output, AtomicInteger executionCounter) {
          return unconditionalExecution
              ? new ExecutionCountingCacheBypassingAction(input, output, executionCounter)
              : new ExecutionCountingAction(input, output, executionCounter);
        }
      },
      ChangeArtifact.CHANGE_MTIME,
      Callables.<Void>returning(null),
      unconditionalExecution
          ? ExpectActionIs.REEXECUTED
          : ExpectActionIs.DIRTIED_BUT_VERIFIED_CLEAN);
}
 
Example #11
Source File: SkyframeAwareActionTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void assertActionWithNonChangingInput(final boolean unconditionalExecution)
    throws Exception {
  // Assert that a simple, non-skyframe-aware action is executed only once
  // if its input does not change at all between builds.
  assertActionExecutions(
      new ExecutionCountingActionFactory() {
        @Override
        public ExecutionCountingAction create(
            Artifact input, Artifact output, AtomicInteger executionCounter) {
          return unconditionalExecution
              ? new ExecutionCountingCacheBypassingAction(input, output, executionCounter)
              : new ExecutionCountingAction(input, output, executionCounter);
        }
      },
      ChangeArtifact.DONT_CHANGE,
      Callables.<Void>returning(null),
      ExpectActionIs.NOT_DIRTIED);
}
 
Example #12
Source File: TasksTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testRepeater() throws Exception {
    Task<?> t;
    
    t = Tasks.requiring(Repeater.create().until(Callables.returning(true)).every(Duration.millis(1))).build();
    app.getExecutionContext().submit(t);
    t.get(Duration.TEN_SECONDS);
    
    t = Tasks.testing(Repeater.create().until(Callables.returning(true)).every(Duration.millis(1))).build();
    app.getExecutionContext().submit(t);
    Assert.assertEquals(t.get(Duration.TEN_SECONDS), true);
    
    t = Tasks.requiring(Repeater.create().until(Callables.returning(false)).limitIterationsTo(2).every(Duration.millis(1))).build();
    app.getExecutionContext().submit(t);
    try {
        t.get(Duration.TEN_SECONDS);
        Assert.fail("Should have failed");
    } catch (Exception e) {
        // expected
    }

    t = Tasks.testing(Repeater.create().until(Callables.returning(false)).limitIterationsTo(2).every(Duration.millis(1))).build();
    app.getExecutionContext().submit(t);
    Assert.assertEquals(t.get(Duration.TEN_SECONDS), false);
}
 
Example #13
Source File: MapListAndOtherStructuredConfigKeyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testMapConfigKeyCanStoreAndRetrieveFutureValsPutAsMap() throws Exception {
    final AtomicReference<String> bval = new AtomicReference<String>("bval-too-early");
    entity.config().set(TestEntity.CONF_MAP_THING, (Map) MutableMap.of(
            "akey", DependentConfiguration.whenDone(Callables.returning("aval")),
            "bkey", DependentConfiguration.whenDone(new Callable<String>() {
                @Override
                public String call() {
                    return bval.get();
                }})));
    app.start(locs);
    bval.set("bval");
    
    assertEquals(entity.getConfig(TestEntity.CONF_MAP_THING), ImmutableMap.of("akey","aval","bkey","bval"));
}
 
Example #14
Source File: MapListAndOtherStructuredConfigKeyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnstructuredConfigKeyCanStoreAndRetrieveFutureValsPutAsMap() throws Exception {
    final AtomicReference<String> bval = new AtomicReference<String>("bval-too-early");
    final AtomicInteger bref = new AtomicInteger(0);
    
    entity.config().set(ConfigKeys.newConfigKey(Object.class, TestEntity.CONF_MAP_THING.getName()), 
        MutableMap.of("akey", DependentConfiguration.whenDone(Callables.returning("aval")),
            "bkey", new DeferredSupplier<String>() {
                @Override public String get() {
                    bref.incrementAndGet();
                    return bval.get();
                }}));
    app.start(locs);
    assertEquals(bref.get(), 0);
    bval.set("bval");
  
    assertEquals(entity.getConfig(TestEntity.CONF_MAP_THING.subKey("akey")), "aval");
    assertEquals(bref.get(), 0);
    assertEquals(entity.getConfig(TestEntity.CONF_MAP_THING.subKey("bkey")), "bval");
    assertEquals(bref.get(), 1);
    
    assertEquals(entity.getConfig(TestEntity.CONF_MAP_THING), ImmutableMap.of("akey","aval","bkey","bval"));
    assertEquals(bref.get(), 2);
    
    // and changes are also visible
    bval.set("bval2");
    assertEquals(entity.getConfig(TestEntity.CONF_MAP_THING), ImmutableMap.of("akey","aval","bkey","bval2"));
    assertEquals(bref.get(), 3);
}
 
Example #15
Source File: MapListAndOtherStructuredConfigKeyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetConfigKeyCanStoreAndRetrieveFutureVals() throws Exception {
    entity.config().set(TestEntity.CONF_SET_THING.subKey(), DependentConfiguration.whenDone(Callables.returning("aval")));
    entity.config().set(TestEntity.CONF_SET_THING.subKey(), DependentConfiguration.whenDone(Callables.returning("bval")));
    app.start(locs);
    
    assertEquals(entity.getConfig(TestEntity.CONF_SET_THING), ImmutableSet.of("aval","bval"));
}
 
Example #16
Source File: MapListAndOtherStructuredConfigKeyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test // ListConfigKey deprecated, as order no longer guaranteed
public void testListConfigKeyCanStoreAndRetrieveFutureVals() throws Exception {
    entity.config().set(TestEntity.CONF_LIST_THING.subKey(), DependentConfiguration.whenDone(Callables.returning("aval")));
    entity.config().set(TestEntity.CONF_LIST_THING.subKey(), DependentConfiguration.whenDone(Callables.returning("bval")));
    app.start(locs);
    
    //assertEquals(entity.getConfig(TestEntity.CONF_LIST_THING), ["aval","bval"])
    assertEquals(ImmutableSet.copyOf(entity.getConfig(TestEntity.CONF_LIST_THING)), ImmutableSet.of("aval","bval"));
}
 
Example #17
Source File: ValueResolverTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void testTaskFactoryGetImmediately() {
    TaskFactory<TaskAdaptable<String>> taskFactory = new TaskFactory<TaskAdaptable<String>>() {
        @Override public TaskAdaptable<String> newTask() {
            return new BasicTask<>(Callables.returning("myval"));
        }
    };
    String result = Tasks.resolving(taskFactory).as(String.class).context(app).immediately(true).get();
    assertEquals(result, "myval");
}
 
Example #18
Source File: JavaccPlugin.java    From javaccPlugin with MIT License 5 votes vote down vote up
private void addTaskToProject(Project project, Class<? extends AbstractJavaccTask> type, String name, String description, String group, Configuration configuration) {
    Map<String, Object> options = new HashMap<String, Object>(3);

    options.put(Task.TASK_TYPE, type);
    options.put(Task.TASK_DESCRIPTION, description);
    options.put(Task.TASK_GROUP, group);

    AbstractJavaccTask task = (AbstractJavaccTask) project.task(options, name);
    task.getConventionMapping().map("classpath", Callables.returning(configuration));
}
 
Example #19
Source File: EntityConfigUsageTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFutureConfigWhenReady() throws Exception {
    TestEntity entity = app.createAndManageChild(EntitySpec.create(TestEntity.class)
            .configure(TestEntity.CONF_NAME, DependentConfiguration.whenDone(Callables.returning("aval"))));
    app.start(locs);
    
    assertEquals(entity.getConfig(TestEntity.CONF_NAME), "aval");
}
 
Example #20
Source File: ClassInstrumentationTest.java    From botsing with Apache License 2.0 5 votes vote down vote up
@Test
public void Instrumentable(){
    interestingClasses.clear();
    interestingClasses.add(Callables.class.getName());
    ClassPathHandler.getInstance().changeTargetCPtoTheSameAsEvoSuite();
    List<Class> instrumentedClasses = instrumentation.instrumentClasses(interestingClasses,Callables.class.getName());
}
 
Example #21
Source File: MapListAndOtherStructuredConfigKeyTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testMapConfigKeyCanStoreAndRetrieveFutureValsPutByKeys() throws Exception {
    final AtomicReference<String> bval = new AtomicReference<String>("bval-too-early");
    entity.config().set(TestEntity.CONF_MAP_THING.subKey("akey"), DependentConfiguration.whenDone(Callables.returning("aval")));
    entity.config().set(TestEntity.CONF_MAP_THING.subKey("bkey"), DependentConfiguration.whenDone(new Callable<String>() {
            @Override
            public String call() {
                return bval.get();
            }}));
    app.start(locs);
    bval.set("bval");
    
    assertEquals(entity.getConfig(TestEntity.CONF_MAP_THING), ImmutableMap.of("akey","aval","bkey","bval"));
}
 
Example #22
Source File: TaskPredicatesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsTransient() throws Exception {
    Task<?> task = execManager.submit(TaskBuilder.<Object>builder()
            .body(Callables.<Object>returning("val"))
            .build());
    assertFalse(TaskPredicates.isTransient().apply(task));
    
    BrooklynTaskTags.setTransient(task);
    assertTrue(TaskPredicates.isTransient().apply(task));
}
 
Example #23
Source File: TaskPredicatesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsEffector() throws Exception {
    Task<?> task = app.invoke(TestApplication.START, ImmutableMap.of("locations", ImmutableList.<Location>of()));
    Task<?> otherTask = execManager.submit(TaskBuilder.<Object>builder()
            .body(Callables.<Object>returning("val"))
            .build());
    assertTrue(TaskPredicates.isEffector().apply(task));
    assertFalse(TaskPredicates.isEffector().apply(otherTask));
    
}
 
Example #24
Source File: TaskPredicatesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testHasTag() throws Exception {
    Task<?> task = execManager.submit(TaskBuilder.<Object>builder()
            .body(Callables.<Object>returning("val"))
            .tag("mytag")
            .build());
    assertTrue(TaskPredicates.hasTag("mytag").apply(task));
    assertFalse(TaskPredicates.hasTag("wrongtag").apply(task));
}
 
Example #25
Source File: TaskPredicatesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisplayNameSatisfies() throws Exception {
    Task<Object> task = execManager.submit(TaskBuilder.builder()
            .body(Callables.<Object>returning("val"))
            .displayName("myname")
            .build());
    assertTrue(TaskPredicates.displayNameSatisfies(Predicates.equalTo("myname")).apply(task));
    assertFalse(TaskPredicates.displayNameSatisfies(Predicates.equalTo("wrong")).apply(task));
}
 
Example #26
Source File: TaskPredicatesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisplayNameMatches() throws Exception {
    Task<Object> task = execManager.submit(TaskBuilder.builder()
            .body(Callables.<Object>returning("val"))
            .displayName("myname")
            .build());
    assertTrue(TaskPredicates.displayNameSatisfies(Predicates.equalTo("myname")).apply(task));
    assertFalse(TaskPredicates.displayNameSatisfies(Predicates.equalTo("wrong")).apply(task));
}
 
Example #27
Source File: TaskPredicatesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDisplayNameEqualTo() throws Exception {
    Task<Object> task = execManager.submit(TaskBuilder.builder()
            .body(Callables.<Object>returning("val"))
            .displayName("myname")
            .build());
    assertTrue(TaskPredicates.displayNameEqualTo("myname").apply(task));
    assertFalse(TaskPredicates.displayNameEqualTo("wrong").apply(task));
}
 
Example #28
Source File: SingleThreadedSchedulerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetResultOfQueuedTaskAfterItExecutes() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    em.submit(MutableMap.of("tag", "category1"), newLatchAwaiter(latch));
    
    BasicTask<Integer> t = new BasicTask<Integer>(Callables.returning(123));
    Future<Integer> future = em.submit(MutableMap.of("tag", "category1"), t);

    latch.countDown();
    assertEquals(future.get(), (Integer)123);
}
 
Example #29
Source File: SingleThreadedSchedulerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetResultOfQueuedTaskBeforeItExecutesWithTimeout() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    em.submit(MutableMap.of("tag", "category1"), newLatchAwaiter(latch));
    
    BasicTask<Integer> t = new BasicTask<Integer>(Callables.returning(123));
    Future<Integer> future = em.submit(MutableMap.of("tag", "category1"), t);

    try {
        assertEquals(future.get(10, TimeUnit.MILLISECONDS), (Integer)123);
        fail();
    } catch (TimeoutException e) {
        // success
    }
}
 
Example #30
Source File: JavaAsync.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Finds factorial of a number using Guava's Futures.submitAsync()
 * @param number
 * @return
 */
@Loggable
public static ListenableFuture<Long> factorialUsingGuavaFutures(int number) {
    ListeningExecutorService service = MoreExecutors.listeningDecorator(threadpool);
    AsyncCallable<Long> asyncCallable = Callables.asAsyncCallable(new Callable<Long>() {
        public Long call() {
            return factorial(number);
        }
    }, service);
    return Futures.submitAsync(asyncCallable, service);
}