List of usage examples for com.google.common.util.concurrent Futures getUnchecked
@GwtIncompatible("TODO") public static <V> V getUnchecked(Future<V> future)
From source file:org.apache.twill.internal.logging.KafkaAppender.java
@Override public void start() { Preconditions.checkNotNull(zkConnectStr); eventConverter = new LogEventConverter(hostname, runnableName); scheduler = Executors//from w w w .j a v a 2 s . co m .newSingleThreadScheduledExecutor(Threads.createDaemonThreadFactory(PUBLISH_THREAD_NAME)); zkClientService = ZKClientServices.delegate(ZKClients.reWatchOnExpire(ZKClients.retryOnFailure( ZKClientService.Builder.of(zkConnectStr).build(), RetryStrategies.fixDelay(1, TimeUnit.SECONDS)))); kafkaClient = new ZKKafkaClientService(zkClientService); Futures.addCallback(Services.chainStart(zkClientService, kafkaClient), new FutureCallback<List<ListenableFuture<Service.State>>>() { @Override public void onSuccess(List<ListenableFuture<Service.State>> result) { for (ListenableFuture<Service.State> future : result) { Preconditions.checkState(Futures.getUnchecked(future) == Service.State.RUNNING, "Service is not running."); } addInfo("Kafka client started: " + zkConnectStr); scheduler.scheduleWithFixedDelay(flushTask, 0, flushPeriod, TimeUnit.MILLISECONDS); } @Override public void onFailure(Throwable t) { // Fail to talk to kafka. Other than logging, what can be done? addError("Failed to start kafka appender.", t); } }, Threads.SAME_THREAD_EXECUTOR); super.start(); }
From source file:org.jclouds.virtualbox.functions.CreateAndInstallVm.java
@Override public IMachine apply(MasterSpec masterSpec) { VmSpec vmSpec = masterSpec.getVmSpec(); IsoSpec isoSpec = masterSpec.getIsoSpec(); String masterName = vmSpec.getVmName(); IMachine masterMachine = checkNotNull(createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(masterSpec), "master machine"); // Launch machine and wait for it to come online machineController.ensureMachineIsLaunched(masterName); String installationKeySequence = isoSpec.getInstallationKeySequence().replace("PRECONFIGURATION_URL", preconfigurationUrl);/* w w w. j a v a 2s . c o m*/ configureOsInstallationWithKeyboardSequence(masterName, installationKeySequence); masterMachine.setExtraData(GUEST_OS_USER, masterSpec.getLoginCredentials().getUser()); masterMachine.setExtraData(GUEST_OS_PASSWORD, masterSpec.getLoginCredentials().getPassword()); SshClient client = sshClientForIMachine.apply(masterMachine); logger.debug(">> awaiting installation to finish node(%s)", masterName); Stopwatch stopwatch = Stopwatch.createUnstarted(); stopwatch.start(); checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", masterName); stopwatch.stop(); logger.debug(String.format("Elapsed time for the OS installation: %d minutes", TimeUnit.SECONDS.convert(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS))); NodeMetadata nodeMetadata = imachineToNodeMetadata.apply(masterMachine); logger.debug(">> awaiting post-installation actions on vm: %s", masterName); ListenableFuture<ExecResponse> execCleanup = machineUtils.runScriptOnNode(nodeMetadata, call("cleanupUdevIfNeeded"), RunScriptOptions.NONE); ExecResponse cleanupResponse = Futures.getUnchecked(execCleanup); checkState(cleanupResponse.getExitStatus() == 0, "post-installation actions on vm(%s) failed", masterName); logger.debug(">> awaiting installation of guest additions on vm: %s", masterName); ListenableFuture<ExecResponse> execInstallGA = machineUtils.runScriptOnNode(nodeMetadata, new InstallGuestAdditions(vmSpec, version), RunScriptOptions.NONE); logger.debug(">> check installation of guest additions on vm: %s", masterName); ListenableFuture<ExecResponse> checkGAinstallation = machineUtils.runScriptOnNode(nodeMetadata, call("checkVBoxService"), RunScriptOptions.NONE); ExecResponse checkGAinstallationResponse = Futures.getUnchecked(checkGAinstallation); checkState(checkGAinstallationResponse.getExitStatus() == 0, "check installation of guest additions on vm(%s) " + "failed", masterName); machineController.ensureMachineIsShutdown(masterName); // detach DVD and ISOs, if needed Iterable<IMediumAttachment> mediumAttachments = Iterables.filter( masterMachine.getMediumAttachmentsOfController("IDE Controller"), new Predicate<IMediumAttachment>() { public boolean apply(IMediumAttachment in) { return in.getMedium() != null && in.getMedium().getDeviceType().equals(DeviceType.DVD); } }); for (IMediumAttachment iMediumAttachment : mediumAttachments) { logger.debug("<< iMedium(%s) detached from (%s)", iMediumAttachment.getMedium().getName(), masterMachine.getName()); machineUtils.sharedLockMachineAndApply(masterMachine.getName(), new DetachDistroMediumFromMachine( iMediumAttachment.getController(), iMediumAttachment.getPort(), iMediumAttachment.getDevice())); } return masterMachine; }
From source file:org.apache.aurora.scheduler.app.local.FakeMaster.java
private void checkState(boolean assertion, String failureMessage) { if (!assertion) { Futures.getUnchecked(schedulerFuture).error(this, failureMessage); stop();/*w w w. j ava 2 s .c o m*/ throw new IllegalStateException(failureMessage); } }
From source file:com.continuuity.loom.common.zookeeper.lib.SynchronizedZKMap.java
private T putInternal(String key, T value) { Map<String, T> current = Maps.newHashMap(currentView); T result = current.put(key, value);//from w ww.j ava2 s . c om currentView = ImmutableMap.<String, T>builder().putAll(current).build(); String itemNodePath = getItemNodePath(key); // Note: we do delete and add new node with new data VS createOrSet() so that cversion of children change (we depend // on it when checking if the current in-memory view is stale) Futures.getUnchecked(ZKClientExt.delete(zkClient, itemNodePath, true)); Futures.getUnchecked( zkClient.create(itemNodePath, serializer.serialize(value), CreateMode.PERSISTENT, true)); return result; }
From source file:org.apache.aurora.scheduler.mesos.SchedulerDriverService.java
@Override public void acknowledgeStatusUpdate(Protos.TaskStatus status) { ensureRunning();//from w w w .ja v a 2 s . c o m TaskStatus convertedStatus = ProtosConversion.convert(status); Futures.getUnchecked(driverFuture).acknowledgeStatusUpdate(convertedStatus); }
From source file:org.onosproject.store.flowext.impl.DefaultFlowRuleExtRouter.java
@Activate public void activate() { messageHandlingExecutor = Executors.newFixedThreadPool(MESSAGE_HANDLER_THREAD_POOL_SIZE, groupedThreads("onos/flow", "message-handlers")); clusterCommunicator.addSubscriber(APPLY_EXTEND_FLOWS, new ClusterMessageHandler() { @Override//from w w w. j av a 2s.c o m public void handle(ClusterMessage message) { // decode the extended flow entry and store them in memory. FlowRuleBatchRequest operation = SERIALIZER.decode(message.payload()); log.info("received batch request {}", operation); final ListenableFuture<FlowExtCompletedOperation> f = applyBatchInternal(operation); f.addListener(new Runnable() { @Override public void run() { FlowExtCompletedOperation result = Futures.getUnchecked(f); try { message.respond(SERIALIZER.encode(result)); } catch (IOException e) { log.error("Failed to respond back", e); } } }, futureListeners); } }, messageHandlingExecutor); replicaInfoManager.addListener(replicaInfoEventListener); log.info("Started"); }
From source file:co.cask.cdap.logging.run.LogSaverTwillRunnable.java
@Override public void run() { LOG.info("Starting runnable " + name); // Register shutdown hook to stop Log Saver before Hadoop Filesystem shuts down ShutdownHookManager.get().addShutdownHook(new Runnable() { @Override/* w ww . j av a 2 s.com*/ public void run() { LOG.info("Shutdown hook triggered."); stop(); } }, FileSystem.SHUTDOWN_HOOK_PRIORITY + 1); Futures.getUnchecked(Services.chainStart(zkClientService, kafkaClientService, metricsCollectionService, logSaver, multiElection, logSaverStatusService)); LOG.info("Runnable started " + name); try { completion.get(); LOG.info("Runnable stopped " + name); } catch (InterruptedException e) { LOG.error("Waiting on completion interrupted", e); Thread.currentThread().interrupt(); } catch (ExecutionException e) { // Propagate the execution exception will causes TwillRunnable terminate with error, // and AM would detect and restarts it. LOG.error("Completed with exception. Exception get propagated", e); throw Throwables.propagate(e); } }
From source file:network.bitmesh.TransactionServer.Client.BitmeshClient.java
private void waitForSufficientBalance(Coin amount) { // TODO// w w w . j a v a2s . c o m // Not enough money in the wallet. Coin amountPlusFee = amount.add(Wallet.SendRequest.DEFAULT_FEE_PER_KB); // ESTIMATED because we don't really need to wait for confirmation. ListenableFuture<Coin> balanceFuture = wallet.getBalanceFuture(amountPlusFee, Wallet.BalanceType.ESTIMATED); if (!balanceFuture.isDone()) { // TODO: Andrew put UI message here System.out.println("Please send " + amountPlusFee.toFriendlyString() + " to " + channelKey.toAddress(BitmeshConfiguration.params)); Futures.getUnchecked(balanceFuture); } }
From source file:com.facebook.buck.core.rules.resolver.impl.MultiThreadedActionGraphBuilder.java
/** Please use {@code computeIfAbsent} instead */ @Deprecated// ww w . j a v a2 s .c om @Override public <T extends BuildRule> T addToIndex(T buildRule) { Preconditions.checkState(isValid); buildRuleIndex.compute(buildRule.getBuildTarget(), (key, existing) -> { if (existing != null) { if (existing.isDone()) { BuildRule oldValue = Futures.getUnchecked(existing); Preconditions.checkState(oldValue == buildRule, "A build rule for this target has already been created: " + oldValue.getBuildTarget()); } else { // If a future already exist and is incomplete, complete it. This supports cases where // the construction of a rule is delegated to another rule, which actually constructs // the first rule. (Ex: flavors of AndroidBinary) // Ex: requireRule(foo) -> addToIndex(foo#bar) -> return foo // requireRule(foo#bar) -> requireRule(foo) -> return getRule(foo#bar) existing.complete(buildRule); } return existing; } else { return WorkThreadTrackingTask.completed(buildRule); } }); return buildRule; }
From source file:org.apache.aurora.scheduler.mesos.VersionedSchedulerDriverService.java
@Override public void killTask(String taskId) { whenRegistered(() -> {//from w w w . ja va 2 s.co m LOG.info("Killing task {}", taskId); Futures.getUnchecked(mesosFuture) .send(Call.newBuilder().setType(Call.Type.KILL).setFrameworkId(getFrameworkId()) .setKill(Call.Kill.newBuilder().setTaskId(TaskID.newBuilder().setValue(taskId))) .build()); }); }