Java Code Examples for java.util.concurrent.Callable#call()

The following examples show how to use java.util.concurrent.Callable#call() . 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: BoundaryFlakeSequenceGeneratorTest.java    From terracotta-platform with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void test_generation_in_different_isolated_classloaders() throws Exception {
  URL[] cp = new URL[]{
      new File("target/classes").toURI().toURL(),
      new File("target/test-classes").toURI().toURL(),
  };
  URLClassLoader cl1 = new URLClassLoader(cp, this.getClass().getClassLoader());
  URLClassLoader cl2 = new URLClassLoader(cp, this.getClass().getClassLoader());

  Callable<String> runner1 = (Callable<String>) cl1.loadClass("org.terracotta.management.sequence.Runner").newInstance();
  Callable<String> runner2 = (Callable<String>) cl2.loadClass("org.terracotta.management.sequence.Runner").newInstance();

  String seq1 = runner1.call();
  String seq2 = runner2.call();

  System.out.println(seq1);
  System.out.println(seq2);

  assertNotEquals(seq1, seq2);
}
 
Example 2
Source File: PolicyResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Queries the server for a permission with the given {@code id}.
 *
 * @param id the permission id
 * @return the permission with the given id
 */
public UmaPermissionRepresentation findById(final String id) {
    if (id == null) {
        throw new IllegalArgumentException("Permission id must not be null");
    }

    Callable<UmaPermissionRepresentation> callable = new Callable<UmaPermissionRepresentation>() {
        @Override
        public UmaPermissionRepresentation call() {
            return http.<UmaPermissionRepresentation>get(serverConfiguration.getPolicyEndpoint() + "/" + id)
                    .authorizationBearer(pat.call())
                    .response().json(UmaPermissionRepresentation.class).execute();
        }
    };
    try {
        return callable.call();
    } catch (Exception cause) {
        return Throwables.retryAndWrapExceptionIfNecessary(callable, pat, "Error creating policy for resource [" + resourceId + "]", cause);
    }
}
 
Example 3
Source File: SaltOrchestrator.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void callBackupRestore(GatewayConfig primaryGateway, Set<String> target, Set<Node> allNodes, SaltConfig saltConfig,
        ExitCriteriaModel exitModel, String state) throws CloudbreakOrchestratorFailedException {
    try (SaltConnector sc = createSaltConnector(primaryGateway)) {
        for (Entry<String, SaltPillarProperties> propertiesEntry : saltConfig.getServicePillarConfig().entrySet()) {
            OrchestratorBootstrap pillarSave = new PillarSave(sc, Sets.newHashSet(primaryGateway.getPrivateAddress()), propertiesEntry.getValue());
            Callable<Boolean> saltPillarRunner = saltRunner.runner(pillarSave, exitCriteria, exitModel, maxRetry, true);
            saltPillarRunner.call();
        }

        StateRunner stateRunner = new StateRunner(target, allNodes, state);
        OrchestratorBootstrap saltJobIdTracker = new SaltJobIdTracker(sc, stateRunner);
        Callable<Boolean> saltJobRunBootstrapRunner = saltRunner.runner(saltJobIdTracker, exitCriteria, exitModel, maxRetry, true);
        saltJobRunBootstrapRunner.call();
    } catch (Exception e) {
        LOGGER.error("Error occurred during database backup/restore", e);
        throw new CloudbreakOrchestratorFailedException(e);
    }
}
 
Example 4
Source File: WorkflowParametersHelper.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> T convertOrNull(Object value, Class<T> type, Callable<T> handleStringValue) {
       if (value == null) {
           return null;
       }
       
       if (value instanceof String) {
           try {
               return handleStringValue.call();
           } catch (Exception e) {
               logger.error("Could not convert value to " + type.getName() + " type", e);
               return null;
           }
       }
       
       if (type.isInstance(value)) {
           return (T) value;
       }
       
       return null;
   }
 
Example 5
Source File: CountLatch.java    From totallylazy with Apache License 2.0 5 votes vote down vote up
public static <A> Function0<A> monitor(final Callable<? extends A> callable, final CountLatch latch) {
    return () -> {
        latch.countUp();
        try {
            return callable.call();
        } finally {
            latch.countDown();
        }
    };
}
 
Example 6
Source File: CallableUtils.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a composed Callable that first executes the Callable and optionally recovers from a specific result.
 *
 * @param <T>              return type of after
 * @param callable the callable
 * @param resultPredicate the result predicate
 * @param resultHandler the result handler
 * @return a function composed of supplier and exceptionHandler
 */
public static <T> Callable<T> recover(Callable<T> callable,
    Predicate<T> resultPredicate, UnaryOperator<T> resultHandler) {
    return () -> {
        T result = callable.call();
        if(resultPredicate.test(result)){
            return resultHandler.apply(result);
        }
        return result;
    };
}
 
Example 7
Source File: HadoopAbstractMapTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <T> T runAsJobOwner(Callable<T> c) throws IgniteCheckedException {
    try {
        return c.call();
    }
    catch (Exception e) {
        throw new IgniteCheckedException(e);
    }
}
 
Example 8
Source File: PerformanceEvaluation.java    From hbase with Apache License 2.0 5 votes vote down vote up
public static <V> V propagate(Callable<V> callable) {
  try {
    return callable.call();
  } catch (Exception e) {
    throw runtime(e);
  }
}
 
Example 9
Source File: JsonUtil.java    From youran with Apache License 2.0 5 votes vote down vote up
/**
 * 将声明式异常包装成运行时异常抛出
 * @param callable
 * @param <T>
 * @return
 */
private static <T> T doConvertRuntimeException(Callable<T> callable) {
    try {
        return callable.call();
    } catch (Exception e) {
        LOGGER.error("json序列化异常", e);
        if(e instanceof RuntimeException){
            throw (RuntimeException)e;
        }else {
            throw new RuntimeException("json序列化异常", e);
        }
    }
}
 
Example 10
Source File: CamelGetComponentsCommand.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    Project project = getSelectedProject(context);
    boolean excludeProjectComponents = isValueTrue(excludeProject);
    Callable<Iterable<ComponentDto>> callable = CamelCommandsHelper.createAllComponentDtoValues(project, getCamelCatalog(), filter, excludeProjectComponents);
    Iterable<ComponentDto> results = callable.call();
    String result = formatResult(results);
    return Results.success(result);
}
 
Example 11
Source File: IndexValueRepository_Test.java    From estatio with Apache License 2.0 5 votes vote down vote up
private static Action executeCallableAndReturn() {
    return new Action() {
        @Override
        public Object invoke(Invocation invocation) throws Throwable {
            Callable<Object> callable = (Callable<Object>) invocation.getParameter(0);
            return callable.call();
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("execute arg 0 as callable and return");
        }
    };
}
 
Example 12
Source File: HystrixContextAwareConcurrencyStrategyTest.java    From hystrix-context-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Callable<T> wrapCallable(final Callable<T> callable) {
    return new Callable<T>() {
        @Override
        public T call() throws Exception {
            return callable.call();
        }
    };
}
 
Example 13
Source File: Update.java    From Java-programming-methodology-Rxjava-articles with Apache License 2.0 5 votes vote down vote up
public static Single<Integer> create(Callable<Connection> connectionFactory, List<Object> parameters, String sql) {
    Callable<PreparedStatement> resourceFactory = () -> {
        Connection con = connectionFactory.call();
        // TODO set parameters
        return con.prepareStatement(sql);
    };
    Function<PreparedStatement, Single<Integer>> singleFactory = ps -> Single.just(ps.executeUpdate());
    Consumer<PreparedStatement> disposer = Update::closeAll;
    return Single.using(resourceFactory, singleFactory, disposer);
}
 
Example 14
Source File: OutputStreams.java    From redis-rdb-cli with Apache License 2.0 5 votes vote down vote up
public static <T> T callQuietly(Callable<T> callable) {
    if (callable == null) return null;
    try {
        return callable.call();
    } catch (Throwable txt) {
        return null;
    }
}
 
Example 15
Source File: MonotonicCountedMethodBean.java    From metrics-cdi with Apache License 2.0 5 votes vote down vote up
@Counted(name = "monotonicCountedMethod", absolute = true, monotonic = true)
public T monotonicCountedMethod(Callable<T> callable) {
    try {
        return callable.call();
    } catch (Exception cause) {
        throw new RuntimeException(cause);
    }
}
 
Example 16
Source File: CSSFX.java    From cssfx with Apache License 2.0 5 votes vote down vote up
private Runnable start(Callable<CSSFXMonitor> monitorBuilder) {
    CSSFXMonitor mon;
    try {
        mon = monitorBuilder.call();
        mon.addAllConverters(converters);
        mon.start();
        return mon::stop;
    } catch (Exception e) {
        throw new RuntimeException("could not create CSSFXMonitor", e);
    }
}
 
Example 17
Source File: Connect.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void testCCE(Callable callable) {
    try {
        callable.call();
        fail("should have thrown ClosedChannelException");
    } catch (ClosedChannelException cce) {
       pass();
    } catch (Exception ioe) {
        unexpected(ioe);
    }
}
 
Example 18
Source File: Executor.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Asynchronous
public <T> Future<T> submit(Callable<T> task) throws Exception {
    return new AsyncResult<T>(task.call());
}
 
Example 19
Source File: StreamTaskExecutionDecorationTest.java    From flink with Apache License 2.0 4 votes vote down vote up
@Override
public <R> R call(Callable<R> callable) throws Exception {
	calls.incrementAndGet();
	return callable.call();
}
 
Example 20
Source File: GradleWorkerMain.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void run() throws Exception {
    // Read the main action from stdin and execute it
    ObjectInputStream instr = new ObjectInputStream(new EncodedStream.EncodedInput(System.in));
    Callable<?> main = (Callable<?>) instr.readObject();
    main.call();
}