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

The following examples show how to use java.util.concurrent.Callable#call() . These examples are extracted from open source projects. 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
@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 Project: keycloak   File: PolicyResource.java    License: 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
@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 4
Source Project: cloudbreak   File: SaltOrchestrator.java    License: 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 5
Source Project: resilience4j   File: CallableUtils.java    License: 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 6
void testCCE(Callable callable) {
    try {
        callable.call();
        fail("should have thrown ClosedChannelException");
    } catch (ClosedChannelException cce) {
       pass();
    } catch (Exception ioe) {
        unexpected(ioe);
    }
}
 
Example 7
Source Project: cssfx   File: CSSFX.java    License: 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 8
@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 9
Source Project: redis-rdb-cli   File: OutputStreams.java    License: 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 10
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 11
@Override
public <T> Callable<T> wrapCallable(final Callable<T> callable) {
    return new Callable<T>() {
        @Override
        public T call() throws Exception {
            return callable.call();
        }
    };
}
 
Example 12
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 13
@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 14
Source Project: youran   File: JsonUtil.java    License: 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 15
Source Project: hbase   File: PerformanceEvaluation.java    License: 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 16
Source Project: ignite   File: HadoopAbstractMapTest.java    License: 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 17
Source Project: totallylazy   File: CountLatch.java    License: 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 18
Source Project: tomee   File: Executor.java    License: 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
@Override
public <R> R call(Callable<R> callable) throws Exception {
	calls.incrementAndGet();
	return callable.call();
}
 
Example 20
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();
}