Example usage for com.google.common.util.concurrent Futures getUnchecked

List of usage examples for com.google.common.util.concurrent Futures getUnchecked

Introduction

In this page you can find the example usage for com.google.common.util.concurrent Futures getUnchecked.

Prototype

@GwtIncompatible("TODO")
public static <V> V getUnchecked(Future<V> future) 

Source Link

Document

Returns the result of calling Future#get() uninterruptibly on a task known not to throw a checked exception.

Usage

From source file:co.cask.cdap.data.runtime.main.MasterServiceMain.java

/**
 * Creates an unstarted {@link LeaderElection} for the master service.
 */// w ww .j av a2 s.c o  m
private LeaderElection createLeaderElection() {
    String electionPath = "/election/" + Constants.Service.MASTER_SERVICES;
    return new LeaderElection(zkClient, electionPath, new ElectionHandler() {

        private final AtomicReference<TwillController> controller = new AtomicReference<>();
        private final List<Service> services = new ArrayList<>();
        private Cancellable secureStoreUpdateCancellable;
        // Executor for re-running master twill app if it gets terminated.
        private ScheduledExecutorService executor;

        @Override
        public void leader() {
            LOG.info("Became leader for master services");

            final Injector injector = baseInjector.createChildInjector(
                    new AppFabricServiceRuntimeModule().getDistributedModules(),
                    new ProgramRunnerRuntimeModule().getDistributedModules());

            // Schedule secure store update.
            if (User.isHBaseSecurityEnabled(hConf) || UserGroupInformation.isSecurityEnabled()) {
                secureStoreUpdateCancellable = twillRunner.scheduleSecureStoreUpdate(secureStoreUpdater, 30000L,
                        secureStoreUpdater.getUpdateInterval(), TimeUnit.MILLISECONDS);
            }

            // Create app-fabric and dataset services
            services.add(new RetryOnStartFailureService(new Supplier<Service>() {
                @Override
                public Service get() {
                    return injector.getInstance(DatasetService.class);
                }
            }, RetryStrategies.exponentialDelay(200, 5000, TimeUnit.MILLISECONDS)));
            services.add(injector.getInstance(AppFabricServer.class));

            executor = Executors
                    .newSingleThreadScheduledExecutor(Threads.createDaemonThreadFactory("master-runner"));

            // Start monitoring twill application
            monitorTwillApplication(executor, 0, controller);

            // Start app-fabric and dataset services
            for (Service service : services) {
                LOG.info("Starting service in master: {}", service);
                service.startAndWait();
            }
        }

        @Override
        public void follower() {
            LOG.info("Became follower for master services");
            // Shutdown the retry executor so that no re-run of the twill app will be attempted
            if (executor != null) {
                executor.shutdownNow();
            }
            // Stop secure store update
            if (secureStoreUpdateCancellable != null) {
                secureStoreUpdateCancellable.cancel();
            }
            // If the master process has been explcitly stopped, stop the twill application as well.
            if (stopped) {
                LOG.info("Stopping master twill application");
                TwillController twillController = controller.get();
                if (twillController != null) {
                    Futures.getUnchecked(twillController.terminate());
                }
            }
            // Stop local services last since DatasetService is running locally
            // and remote services need it to preserve states.
            for (Service service : Lists.reverse(services)) {
                LOG.info("Stopping service in master: {}", service);
                stopQuietly(service);
            }
            services.clear();
        }
    });
}

From source file:org.onosproject.store.device.impl.ECDeviceStore.java

@Override
public List<DeviceEvent> updatePorts(ProviderId providerId, DeviceId deviceId,
        List<PortDescription> descriptions) {
    NodeId master = mastershipService.getMasterFor(deviceId);
    List<DeviceEvent> deviceEvents = null;
    if (localNodeId.equals(master)) {
        descriptions.forEach(description -> {
            PortKey portKey = new PortKey(providerId, deviceId, description.portNumber());
            portDescriptions.put(portKey, description);
        });/*  w  w  w  .  j av  a  2 s  .  c  om*/
        deviceEvents = refreshDevicePortCache(providerId, deviceId, Optional.empty());
    } else {
        if (master == null) {
            return Collections.emptyList();
        }
        PortInjectedEvent portInjectedEvent = new PortInjectedEvent(providerId, deviceId, descriptions);
        deviceEvents = Futures.getUnchecked(clusterCommunicator.sendAndReceive(portInjectedEvent, PORT_INJECTED,
                SERIALIZER::encode, SERIALIZER::decode, master));
    }
    return deviceEvents == null ? Collections.emptyList() : deviceEvents;
}

From source file:com.matthewmitchell.nubitsj.tools.WalletTool.java

private static void rotate() throws BlockStoreException {
    setup();/* w ww. j av a 2 s .  c om*/
    peers.startAsync();
    peers.awaitRunning();
    // Set a key rotation time and possibly broadcast the resulting maintenance transactions.
    long rotationTimeSecs = Utils.currentTimeSeconds();
    if (options.has(dateFlag)) {
        rotationTimeSecs = options.valueOf(dateFlag).getTime() / 1000;
    }
    log.info("Setting wallet key rotation time to {}", rotationTimeSecs);
    wallet.setKeyRotationTime(rotationTimeSecs);
    KeyParameter aesKey = null;
    if (wallet.isEncrypted()) {
        aesKey = passwordToKey(true);
        if (aesKey == null)
            return;
    }
    Futures.getUnchecked(wallet.doMaintenance(aesKey, true));
}

From source file:com.matthewmitchell.peercoinj.tools.WalletTool.java

private static void rotate() throws BlockStoreException, IOException {
    setup();// w  w  w .  j  a v a2 s . c o m
    peers.startAsync();
    peers.awaitRunning();
    // Set a key rotation time and possibly broadcast the resulting maintenance transactions.
    long rotationTimeSecs = Utils.currentTimeSeconds();
    if (options.has(dateFlag)) {
        rotationTimeSecs = options.valueOf(dateFlag).getTime() / 1000;
    }
    log.info("Setting wallet key rotation time to {}", rotationTimeSecs);
    wallet.setKeyRotationTime(rotationTimeSecs);
    KeyParameter aesKey = null;
    if (wallet.isEncrypted()) {
        aesKey = passwordToKey(true);
        if (aesKey == null)
            return;
    }
    Futures.getUnchecked(wallet.doMaintenance(aesKey, true));
}

From source file:org.apache.twill.discovery.ZKDiscoveryService.java

/**
 * Creates a CacheLoader for creating live Iterable for watching instances changes for a given service.
 *//*from  ww w .ja va2s .  c om*/
private CacheLoader<String, ServiceDiscoveredCacheEntry> createServiceLoader() {
    return new CacheLoader<String, ServiceDiscoveredCacheEntry>() {
        @Override
        public ServiceDiscoveredCacheEntry load(String service) throws Exception {
            final DefaultServiceDiscovered serviceDiscovered = new DefaultServiceDiscovered(service);
            final String pathBase = "/" + service;

            // Watch for children changes in /service
            Cancellable cancellable = ZKOperations.watchChildren(zkClient, pathBase,
                    new ZKOperations.ChildrenCallback() {
                        @Override
                        public void updated(NodeChildren nodeChildren) {
                            // Fetch data of all children nodes in parallel.
                            List<String> children = nodeChildren.getChildren();
                            List<OperationFuture<NodeData>> dataFutures = Lists
                                    .newArrayListWithCapacity(children.size());
                            for (String child : children) {
                                dataFutures.add(zkClient.getData(pathBase + "/" + child));
                            }

                            // Update the service map when all fetching are done.
                            final ListenableFuture<List<NodeData>> fetchFuture = Futures
                                    .successfulAsList(dataFutures);
                            fetchFuture.addListener(new Runnable() {
                                @Override
                                public void run() {
                                    ImmutableSet.Builder<Discoverable> builder = ImmutableSet.builder();
                                    for (NodeData nodeData : Futures.getUnchecked(fetchFuture)) {
                                        // For successful fetch, decode the content.
                                        if (nodeData != null) {
                                            Discoverable discoverable = DiscoverableAdapter
                                                    .decode(nodeData.getData());
                                            if (discoverable != null) {
                                                builder.add(discoverable);
                                            }
                                        }
                                    }
                                    serviceDiscovered.setDiscoverables(builder.build());
                                }
                            }, Threads.SAME_THREAD_EXECUTOR);
                        }
                    });
            return new ServiceDiscoveredCacheEntry(serviceDiscovered, cancellable);
        }
    };
}

From source file:com.facebook.buck.jvm.java.autodeps.JavaDepsFinder.java

private Symbols getJavaFileFeatures(TargetNode<?, ?> node, boolean shouldRecordRequiredSymbols) {
    // Build a JavaLibrarySymbolsFinder to create the JavaFileFeatures. By making use of Buck's
    // build cache, we can often avoid running a Java parser.
    BuildTarget buildTarget = node.getBuildTarget();
    Object argForNode = node.getConstructorArg();
    JavaSymbolsRule.SymbolsFinder symbolsFinder;
    ImmutableSortedSet<String> generatedSymbols;
    if (argForNode instanceof JavaLibraryDescription.Arg) {
        JavaLibraryDescription.Arg arg = (JavaLibraryDescription.Arg) argForNode;
        // The build target should be recorded as a provider for every symbol in its
        // generated_symbols set (if it exists). It is common to use this for symbols that are
        // generated via annotation processors.
        generatedSymbols = arg.generatedSymbols;
        symbolsFinder = new JavaLibrarySymbolsFinder(arg.srcs, javaFileParser, shouldRecordRequiredSymbols);
    } else {//from  w  w w.  jav a 2s  .  c  o  m
        PrebuiltJarDescription.Arg arg = (PrebuiltJarDescription.Arg) argForNode;
        generatedSymbols = ImmutableSortedSet.of();
        symbolsFinder = new PrebuiltJarSymbolsFinder(arg.binaryJar);
    }

    // Build the rule, leveraging Buck's build cache.
    JavaSymbolsRule buildRule = new JavaSymbolsRule(buildTarget, symbolsFinder, generatedSymbols, objectMapper,
            node.getFilesystem());
    ListenableFuture<BuildResult> future = buildEngine.build(buildContext, executionContext, buildRule);
    BuildResult result = Futures.getUnchecked(future);

    Symbols features;
    if (result.getSuccess() != null) {
        features = buildRule.getFeatures();
    } else {
        Throwable failure = result.getFailure();
        Preconditions.checkNotNull(failure);
        throw new RuntimeException("Failed to extract Java symbols for " + buildTarget, failure);
    }
    return features;
}

From source file:com.spotify.apollo.test.ServiceHelper.java

private void shutdown() {
    if (instance != null) {
        instance.getSignaller().signalShutdown();
        requestHandler = null;//from  www .j  av  a2 s  . c o  m
        instance = null;
        Futures.getUnchecked(currentHelperFuture);
        currentHelperFuture = null;
    }
}

From source file:org.onosproject.incubator.store.virtual.impl.DistributedVirtualFlowRuleStore.java

@Override
public FlowRuleEvent removeFlowRule(NetworkId networkId, FlowEntry rule) {
    final DeviceId deviceId = rule.deviceId();

    MastershipService mastershipService = vnaService.get(networkId, MastershipService.class);
    NodeId master = mastershipService.getMasterFor(deviceId);

    if (Objects.equals(local, master)) {
        // bypass and handle it locally
        return removeFlowRuleInternal(new VirtualFlowEntry(networkId, rule));
    }/*  ww w .j av  a  2 s  .  c  o m*/

    if (master == null) {
        log.warn("Failed to removeFlowRule: No master for {}", deviceId);
        // TODO: revisit if this should be null (="no-op") or Exception
        return null;
    }

    log.trace("Forwarding removeFlowRule to {}, which is the master for device {}", master, deviceId);

    return Futures.getUnchecked(clusterCommunicator.sendAndReceive(new VirtualFlowEntry(networkId, rule),
            REMOVE_FLOW_ENTRY, serializer::encode, serializer::decode, master));
}

From source file:com.facebook.buck.apple.AppleBundle.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> stepsBuilder = ImmutableList.builder();

    stepsBuilder.add(new MakeCleanDirectoryStep(getProjectFilesystem(), bundleRoot));

    Path resourcesDestinationPath = bundleRoot.resolve(this.destinations.getResourcesPath());
    if (assetCatalog.isPresent()) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        Path bundleDir = assetCatalog.get().getOutputDir();
        stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), bundleDir, resourcesDestinationPath,
                CopyStep.DirectoryMode.CONTENTS_ONLY));
    }/*from ww w  .j a  v a 2s  .c  o m*/

    if (coreDataModel.isPresent()) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), coreDataModel.get().getOutputDir(),
                resourcesDestinationPath, CopyStep.DirectoryMode.CONTENTS_ONLY));
    }

    if (sceneKitAssets.isPresent()) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), sceneKitAssets.get().getPathToOutput(),
                resourcesDestinationPath, CopyStep.DirectoryMode.CONTENTS_ONLY));
    }

    Path metadataPath = getMetadataPath();

    Path infoPlistInputPath = context.getSourcePathResolver().getAbsolutePath(infoPlist);
    Path infoPlistSubstitutionTempPath = BuildTargets.getScratchPath(getProjectFilesystem(), getBuildTarget(),
            "%s.plist");
    Path infoPlistOutputPath = metadataPath.resolve("Info.plist");

    stepsBuilder.add(new MkdirStep(getProjectFilesystem(), metadataPath),
            // TODO(bhamiltoncx): This is only appropriate for .app bundles.
            new WriteFileStep(getProjectFilesystem(), "APPLWRUN", metadataPath.resolve("PkgInfo"),
                    /* executable */ false),
            new MkdirStep(getProjectFilesystem(), infoPlistSubstitutionTempPath.getParent()),
            new FindAndReplaceStep(getProjectFilesystem(), infoPlistInputPath, infoPlistSubstitutionTempPath,
                    InfoPlistSubstitution.createVariableExpansionFunction(withDefaults(infoPlistSubstitutions,
                            ImmutableMap.of("EXECUTABLE_NAME", binaryName, "PRODUCT_NAME", binaryName)))),
            new PlistProcessStep(getProjectFilesystem(), infoPlistSubstitutionTempPath,
                    assetCatalog.isPresent() ? Optional.of(assetCatalog.get().getOutputPlist())
                            : Optional.empty(),
                    infoPlistOutputPath, getInfoPlistAdditionalKeys(), getInfoPlistOverrideKeys(),
                    PlistProcessStep.OutputFormat.BINARY));

    if (hasBinary) {
        appendCopyBinarySteps(stepsBuilder);
        appendCopyDsymStep(stepsBuilder, buildableContext);
    }

    if (!Iterables.isEmpty(Iterables.concat(resources.getResourceDirs(),
            resources.getDirsContainingResourceDirs(), resources.getResourceFiles()))) {
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), resourcesDestinationPath));
        for (SourcePath dir : resources.getResourceDirs()) {
            stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(),
                    context.getSourcePathResolver().getAbsolutePath(dir), resourcesDestinationPath,
                    CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
        }
        for (SourcePath dir : resources.getDirsContainingResourceDirs()) {
            stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(),
                    context.getSourcePathResolver().getAbsolutePath(dir), resourcesDestinationPath,
                    CopyStep.DirectoryMode.CONTENTS_ONLY));
        }
        for (SourcePath file : resources.getResourceFiles()) {
            // TODO(shs96c): Check that this work cross-cell
            Path resolvedFilePath = context.getSourcePathResolver().getRelativePath(file);
            Path destinationPath = resourcesDestinationPath.resolve(resolvedFilePath.getFileName());
            addResourceProcessingSteps(context.getSourcePathResolver(), resolvedFilePath, destinationPath,
                    stepsBuilder);
        }
    }

    ImmutableList.Builder<Path> codeSignOnCopyPathsBuilder = ImmutableList.builder();

    addStepsToCopyExtensionBundlesDependencies(context.getSourcePathResolver(), stepsBuilder,
            codeSignOnCopyPathsBuilder);

    for (SourcePath variantSourcePath : resources.getResourceVariantFiles()) {
        // TODO(shs96c): Ensure this works cross-cell, as relative path begins with "buck-out"
        Path variantFilePath = context.getSourcePathResolver().getRelativePath(variantSourcePath);

        Path variantDirectory = variantFilePath.getParent();
        if (variantDirectory == null || !variantDirectory.toString().endsWith(".lproj")) {
            throw new HumanReadableException(
                    "Variant files have to be in a directory with name ending in '.lproj', "
                            + "but '%s' is not.",
                    variantFilePath);
        }

        Path bundleVariantDestinationPath = resourcesDestinationPath.resolve(variantDirectory.getFileName());
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), bundleVariantDestinationPath));

        Path destinationPath = bundleVariantDestinationPath.resolve(variantFilePath.getFileName());
        addResourceProcessingSteps(context.getSourcePathResolver(), variantFilePath, destinationPath,
                stepsBuilder);
    }

    if (!frameworks.isEmpty()) {
        Path frameworksDestinationPath = bundleRoot.resolve(this.destinations.getFrameworksPath());
        stepsBuilder.add(new MkdirStep(getProjectFilesystem(), frameworksDestinationPath));
        for (SourcePath framework : frameworks) {
            Path srcPath = context.getSourcePathResolver().getAbsolutePath(framework);
            stepsBuilder.add(CopyStep.forDirectory(getProjectFilesystem(), srcPath, frameworksDestinationPath,
                    CopyStep.DirectoryMode.DIRECTORY_AND_CONTENTS));
            codeSignOnCopyPathsBuilder.add(frameworksDestinationPath.resolve(srcPath.getFileName()));
        }
    }

    if (needCodeSign()) {
        Optional<Path> signingEntitlementsTempPath;
        Supplier<CodeSignIdentity> codeSignIdentitySupplier;

        if (adHocCodeSignIsSufficient()) {
            signingEntitlementsTempPath = Optional.empty();
            codeSignIdentitySupplier = () -> CodeSignIdentity.AD_HOC;
        } else {
            // Copy the .mobileprovision file if the platform requires it, and sign the executable.
            Optional<Path> entitlementsPlist = Optional.empty();
            final Path srcRoot = getProjectFilesystem().getRootPath().resolve(getBuildTarget().getBasePath());
            Optional<String> entitlementsPlistString = InfoPlistSubstitution.getVariableExpansionForPlatform(
                    CODE_SIGN_ENTITLEMENTS, platformName, withDefaults(infoPlistSubstitutions,
                            ImmutableMap.of("SOURCE_ROOT", srcRoot.toString(), "SRCROOT", srcRoot.toString())));
            if (entitlementsPlistString.isPresent()) {
                entitlementsPlist = Optional.of(srcRoot.resolve(Paths.get(entitlementsPlistString.get())));
            }

            signingEntitlementsTempPath = Optional
                    .of(BuildTargets.getScratchPath(getProjectFilesystem(), getBuildTarget(), "%s.xcent"));

            final Path dryRunResultPath = bundleRoot.resolve(PP_DRY_RUN_RESULT_FILE);

            final ProvisioningProfileCopyStep provisioningProfileCopyStep = new ProvisioningProfileCopyStep(
                    getProjectFilesystem(), infoPlistOutputPath, Optional.empty(), // Provisioning profile UUID -- find automatically.
                    entitlementsPlist, provisioningProfileStore,
                    resourcesDestinationPath.resolve("embedded.mobileprovision"),
                    dryRunCodeSigning ? bundleRoot.resolve(CODE_SIGN_DRY_RUN_ENTITLEMENTS_FILE)
                            : signingEntitlementsTempPath.get(),
                    codeSignIdentityStore,
                    dryRunCodeSigning ? Optional.of(dryRunResultPath) : Optional.empty());
            stepsBuilder.add(provisioningProfileCopyStep);

            codeSignIdentitySupplier = () -> {
                // Using getUnchecked here because the previous step should already throw if exception
                // occurred, and this supplier would never be evaluated.
                Optional<ProvisioningProfileMetadata> selectedProfile = Futures
                        .getUnchecked(provisioningProfileCopyStep.getSelectedProvisioningProfileFuture());

                if (!selectedProfile.isPresent()) {
                    // This should only happen in dry-run codesign mode (since otherwise an exception
                    // would have been thrown already.)  Still, we need to return *something*.
                    Preconditions.checkState(dryRunCodeSigning);
                    return CodeSignIdentity.AD_HOC;
                }

                ImmutableSet<HashCode> fingerprints = selectedProfile.get()
                        .getDeveloperCertificateFingerprints();
                if (fingerprints.isEmpty()) {
                    // No constraints, pick an arbitrary identity.
                    // If no identities are available, use an ad-hoc identity.
                    return Iterables.getFirst(codeSignIdentityStore.getIdentities(), CodeSignIdentity.AD_HOC);
                }
                for (CodeSignIdentity identity : codeSignIdentityStore.getIdentities()) {
                    if (identity.getFingerprint().isPresent()
                            && fingerprints.contains(identity.getFingerprint().get())) {
                        return identity;
                    }
                }

                throw new HumanReadableException(
                        "No code sign identity available for provisioning profile: %s\n"
                                + "Profile requires an identity with one of the following SHA1 fingerprints "
                                + "available in your keychain: \n  %s",
                        selectedProfile.get().getProfilePath(), Joiner.on("\n  ").join(fingerprints));
            };
        }

        addSwiftStdlibStepIfNeeded(context.getSourcePathResolver(), bundleRoot.resolve(Paths.get("Frameworks")),
                dryRunCodeSigning ? Optional.<Supplier<CodeSignIdentity>>empty()
                        : Optional.of(codeSignIdentitySupplier),
                stepsBuilder, false /* is for packaging? */
        );

        for (Path codeSignOnCopyPath : codeSignOnCopyPathsBuilder.build()) {
            stepsBuilder.add(new CodeSignStep(getProjectFilesystem(), context.getSourcePathResolver(),
                    codeSignOnCopyPath, Optional.empty(), codeSignIdentitySupplier, codesignAllocatePath,
                    dryRunCodeSigning ? Optional.of(codeSignOnCopyPath.resolve(CODE_SIGN_DRY_RUN_ARGS_FILE))
                            : Optional.empty()));
        }

        stepsBuilder.add(new CodeSignStep(getProjectFilesystem(), context.getSourcePathResolver(), bundleRoot,
                signingEntitlementsTempPath, codeSignIdentitySupplier, codesignAllocatePath,
                dryRunCodeSigning ? Optional.of(bundleRoot.resolve(CODE_SIGN_DRY_RUN_ARGS_FILE))
                        : Optional.empty()));
    } else {
        addSwiftStdlibStepIfNeeded(context.getSourcePathResolver(), bundleRoot.resolve(Paths.get("Frameworks")),
                Optional.<Supplier<CodeSignIdentity>>empty(), stepsBuilder, false /* is for packaging? */
        );
    }

    // Ensure the bundle directory is archived so we can fetch it later.
    buildableContext.recordArtifact(getPathToOutput());

    return stepsBuilder.build();
}

From source file:com.android.tools.idea.run.AndroidRunConfigurationBase.java

private static String canDebug(@NotNull DeviceFutures deviceFutures, @NotNull AndroidFacet facet,
        @NotNull String moduleName) {
    // If we are debugging on a device, then the app needs to be debuggable
    for (ListenableFuture<IDevice> future : deviceFutures.get()) {
        if (!future.isDone()) {
            // this is an emulator, and we assume that all emulators are debuggable
            continue;
        }//from   ww w .  j  av  a  2 s  .c o  m

        IDevice device = Futures.getUnchecked(future);
        if (!LaunchUtils.canDebugAppOnDevice(facet, device)) {
            return AndroidBundle.message("android.cannot.debug.noDebugPermissions", moduleName,
                    device.getName());
        }
    }

    return null;
}