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

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

Introduction

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

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFailedFuture(Throwable throwable) 

Source Link

Document

Returns a ListenableFuture which has an exception set immediately upon construction.

Usage

From source file:com.android.tools.idea.avdmanager.AvdManagerConnection.java

/**
 * Launch the given AVD in the emulator.
 * @return a future with the device that was launched
 *//*  ww w  .ja v  a 2 s  .  co m*/
@NotNull
public ListenableFuture<IDevice> startAvd(@Nullable final Project project, @NotNull final AvdInfo info) {
    if (!initIfNecessary()) {
        return Futures.immediateFailedFuture(new RuntimeException("No Android SDK Found"));
    }
    AccelerationErrorCode error = checkAcceleration();
    ListenableFuture<IDevice> errorResult = handleAccelerationError(project, info, error);
    if (errorResult != null) {
        return errorResult;
    }

    final File emulatorBinary = getEmulatorBinary();
    if (!emulatorBinary.isFile()) {
        IJ_LOG.error("No emulator binary found!");
        return Futures.immediateFailedFuture(new RuntimeException("No emulator binary found"));
    }

    final String avdName = info.getName();

    // TODO: The emulator stores pid of the running process inside the .lock file (userdata-qemu.img.lock in Linux and
    // userdata-qemu.img.lock/pid on Windows). We should detect whether those lock files are stale and if so, delete them without showing
    // this error. Either the emulator provides a command to do that, or we learn about its internals (qemu/android/utils/filelock.c) and
    // perform the same action here. If it is not stale, then we should show this error and if possible, bring that window to the front.
    if (myAvdManager.isAvdRunning(info, SDK_LOG)) {
        String baseFolder;
        try {
            baseFolder = myAvdManager.getBaseAvdFolder().getAbsolutePath();
        } catch (AndroidLocation.AndroidLocationException e) {
            baseFolder = "$HOME";
        }

        String message = String
                .format("AVD %1$s is already running.\n" + "If that is not the case, delete the files at\n"
                        + "   %2$s/%1$s.avd/*.lock\n" + "and try again.", avdName, baseFolder);
        Messages.showErrorDialog(project, message, "AVD Manager");
        return Futures.immediateFailedFuture(new RuntimeException(message));
    }

    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.setExePath(emulatorBinary.getPath());

    addParameters(info, commandLine);

    EmulatorRunner runner = new EmulatorRunner(commandLine, info);
    EmulatorRunner.ProcessOutputCollector collector = new EmulatorRunner.ProcessOutputCollector();
    runner.addProcessListener(collector);

    final ProcessHandler processHandler;
    try {
        processHandler = runner.start();
    } catch (ExecutionException e) {
        IJ_LOG.error("Error launching emulator", e);
        return Futures.immediateFailedFuture(
                new RuntimeException(String.format("Error launching emulator %1$s ", avdName), e));
    }

    // If we're using qemu2, it has its own progress bar, so put ours in the background. Otherwise show it.
    final ProgressWindow p = hasQEMU2Installed()
            ? new BackgroundableProcessIndicator(project, "Launching Emulator",
                    PerformInBackgroundOption.ALWAYS_BACKGROUND, "", "", false)
            : new ProgressWindow(false, true, project);
    p.setIndeterminate(false);
    p.setDelayInMillis(0);

    // It takes >= 8 seconds to start the Emulator. Display a small progress indicator otherwise it seems like
    // the action wasn't invoked and users tend to click multiple times on it, ending up with several instances of the emulator
    ApplicationManager.getApplication().executeOnPooledThread(() -> {
        try {
            p.start();
            p.setText("Starting AVD...");
            for (double d = 0; d < 1; d += 1.0 / 80) {
                p.setFraction(d);
                //noinspection BusyWait
                Thread.sleep(100);
                if (processHandler.isProcessTerminated()) {
                    break;
                }
            }
        } catch (InterruptedException ignore) {
        } finally {
            p.stop();
            p.processFinish();
        }

        processHandler.removeProcessListener(collector);
        String message = limitErrorMessage(collector.getText());

        if (message.toLowerCase(Locale.ROOT).contains("error")
                || processHandler.isProcessTerminated() && !message.trim().isEmpty()) {
            ApplicationManager.getApplication().invokeLater(() -> Messages.showErrorDialog(project,
                    "Cannot launch AVD in emulator.\nOutput:\n" + message, avdName));
        }
    });

    return EmulatorConnectionListener.getDeviceForEmulator(project, info.getName(), processHandler, 5,
            TimeUnit.MINUTES);
}

From source file:com.google.cloud.bigtable.grpc.async.AsyncExecutor.java

private <ResponseT, RequestT extends GeneratedMessageV3> ListenableFuture<ResponseT> call(
        AsyncCall<RequestT, ResponseT> rpc, RequestT request, long id) {
    ListenableFuture<ResponseT> future;
    try {/*ww  w .  ja  v  a2 s  .co m*/
        future = rpc.call(client, request);
    } catch (Exception e) {
        future = Futures.immediateFailedFuture(e);
    }
    rpcThrottler.addCallback(future, id);
    return future;
}

From source file:org.opendaylight.netvirt.natservice.internal.VpnFloatingIpHandler.java

@Override
public void onAddFloatingIp(final BigInteger dpnId, final String routerId, final Uuid networkId,
        final String interfaceName, final InternalToExternalPortMap mapping) {
    String externalIp = mapping.getExternalIp();
    String internalIp = mapping.getInternalIp();
    Uuid floatingIpId = mapping.getExternalId();
    Uuid subnetId = NatUtil.getFloatingIpPortSubnetIdFromFloatingIpId(dataBroker, floatingIpId);
    String floatingIpPortMacAddress = NatUtil.getFloatingIpPortMacFromFloatingIpId(dataBroker, floatingIpId);
    Optional<Subnets> externalSubnet = NatUtil.getOptionalExternalSubnets(dataBroker, subnetId);
    final String vpnName = externalSubnet.isPresent() ? subnetId.getValue()
            : NatUtil.getAssociatedVPN(dataBroker, networkId, LOG);
    final String subnetVpnName = externalSubnet.isPresent() ? subnetId.getValue() : null;
    if (vpnName == null) {
        LOG.info("No VPN associated with ext nw {} to handle add floating ip configuration {} in router {}",
                networkId, externalIp, routerId);
        return;//from w  ww .  j a v  a 2s  .c o  m
    }
    String rd = NatUtil.getVpnRd(dataBroker, vpnName);
    String nextHopIp = NatUtil.getEndpointIpAddressForDPN(dataBroker, dpnId);
    LOG.debug("Nexthop ip for prefix {} is {}", externalIp, nextHopIp);
    WriteTransaction writeTx = dataBroker.newWriteOnlyTransaction();
    ProviderTypes provType = NatEvpnUtil.getExtNwProvTypeFromRouterName(dataBroker, routerId);
    if (provType == null) {
        return;
    }
    if (provType == ProviderTypes.VXLAN) {
        Uuid floatingIpInterface = NatEvpnUtil.getFloatingIpInterfaceIdFromFloatingIpId(dataBroker,
                floatingIpId);
        evpnDnatFlowProgrammer.onAddFloatingIp(dpnId, routerId, vpnName, internalIp, externalIp, networkId,
                interfaceName, floatingIpInterface.getValue(), floatingIpPortMacAddress, rd, nextHopIp,
                writeTx);
        if (writeTx != null) {
            writeTx.submit();
        }
        return;
    }

    if (nvpnManager.getEnforceOpenstackSemanticsConfig()) {
        NatOverVxlanUtil.validateAndCreateVxlanVniPool(dataBroker, nvpnManager, idManager,
                NatConstants.ODL_VNI_POOL_NAME);
    }

    GenerateVpnLabelInput labelInput = new GenerateVpnLabelInputBuilder().setVpnName(vpnName)
            .setIpPrefix(externalIp).build();
    Future<RpcResult<GenerateVpnLabelOutput>> labelFuture = vpnService.generateVpnLabel(labelInput);

    ListenableFuture<RpcResult<Void>> future = Futures.transform(
            JdkFutureAdapters.listenInPoolThread(labelFuture),
            (AsyncFunction<RpcResult<GenerateVpnLabelOutput>, RpcResult<Void>>) result -> {
                if (result.isSuccessful()) {
                    GenerateVpnLabelOutput output = result.getResult();
                    long label = output.getLabel();
                    LOG.debug("Generated label {} for prefix {}", label, externalIp);
                    floatingIPListener.updateOperationalDS(routerId, interfaceName, label, internalIp,
                            externalIp);
                    //Inform BGP
                    long l3vni = 0;
                    if (nvpnManager.getEnforceOpenstackSemanticsConfig()) {
                        l3vni = NatOverVxlanUtil.getInternetVpnVni(idManager, vpnName, l3vni).longValue();
                    }
                    NatUtil.addPrefixToBGP(dataBroker, bgpManager, fibManager, vpnName, rd, subnetId,
                            externalIp + "/32", nextHopIp, networkId.getValue(), floatingIpPortMacAddress,
                            label, l3vni, LOG, RouteOrigin.STATIC, dpnId);

                    List<Instruction> instructions = new ArrayList<>();
                    List<ActionInfo> actionsInfos = new ArrayList<>();
                    actionsInfos.add(new ActionNxResubmit(NwConstants.PDNAT_TABLE));
                    instructions.add(new InstructionApplyActions(actionsInfos).buildInstruction(0));
                    makeTunnelTableEntry(vpnName, dpnId, label, instructions);

                    //Install custom FIB routes
                    List<ActionInfo> actionInfoFib = new ArrayList<>();
                    List<Instruction> customInstructions = new ArrayList<>();
                    actionInfoFib.add(
                            new ActionSetFieldEthernetDestination(new MacAddress(floatingIpPortMacAddress)));
                    customInstructions.add(new InstructionApplyActions(actionInfoFib).buildInstruction(0));
                    customInstructions
                            .add(new InstructionGotoTable(NwConstants.PDNAT_TABLE).buildInstruction(1));

                    makeLFibTableEntry(dpnId, label, NwConstants.PDNAT_TABLE);
                    CreateFibEntryInput input = new CreateFibEntryInputBuilder().setVpnName(vpnName)
                            .setSourceDpid(dpnId).setInstruction(customInstructions)
                            .setIpAddress(externalIp + "/32").setServiceId(label)
                            .setInstruction(customInstructions).build();
                    //Future<RpcResult<java.lang.Void>> createFibEntry(CreateFibEntryInput input);
                    Future<RpcResult<Void>> future1 = fibService.createFibEntry(input);
                    LOG.debug("Add Floating Ip {} , found associated to fixed port {}", externalIp,
                            interfaceName);
                    if (floatingIpPortMacAddress != null) {
                        String networkVpnName = NatUtil.getAssociatedVPN(dataBroker, networkId, LOG);
                        vpnManager.setupSubnetMacIntoVpnInstance(networkVpnName, subnetVpnName,
                                floatingIpPortMacAddress, dpnId, writeTx, NwConstants.ADD_FLOW);
                        vpnManager.setupArpResponderFlowsToExternalNetworkIps(routerId,
                                Collections.singleton(externalIp), floatingIpPortMacAddress, dpnId, networkId,
                                writeTx, NwConstants.ADD_FLOW);
                        writeTx.submit();
                    }
                    return JdkFutureAdapters.listenInPoolThread(future1);
                } else {
                    String errMsg = String.format("Could not retrieve the label for prefix %s in VPN %s, %s",
                            externalIp, vpnName, result.getErrors());
                    LOG.error(errMsg);
                    return Futures.immediateFailedFuture(new RuntimeException(errMsg));
                }
            });

    Futures.addCallback(future, new FutureCallback<RpcResult<Void>>() {

        @Override
        public void onFailure(Throwable error) {
            LOG.error("Error in generate label or fib install process", error);
        }

        @Override
        public void onSuccess(RpcResult<Void> result) {
            if (result.isSuccessful()) {
                LOG.info("Successfully installed custom FIB routes for prefix {}", externalIp);
            } else {
                LOG.error("Error in rpc call to create custom Fib entries for prefix {} in DPN {}, {}",
                        externalIp, dpnId, result.getErrors());
            }
        }
    });

    // Handle GARP transmission
    final IpAddress extrenalAddress = IpAddressBuilder.getDefaultInstance(externalIp);
    sendGarpOnInterface(dpnId, networkId, extrenalAddress, floatingIpPortMacAddress);

}

From source file:com.mypurecloud.sdk.v2.api.LicenseApiAsync.java

/**
 * Get PureCloud license feature toggle value.
 * /* w ww  .  ja  va2s . c om*/
 * @param request the request object
 * @param callback the action to perform when the request is completed
 * @return the future indication when the request has completed
 */
public Future<LicenseOrgToggle> getLicenseToggleAsync(GetLicenseToggleRequest request,
        final AsyncApiCallback<LicenseOrgToggle> callback) {
    try {
        final SettableFuture<LicenseOrgToggle> future = SettableFuture.create();
        final boolean shouldThrowErrors = pcapiClient.getShouldThrowErrors();
        pcapiClient.invokeAsync(request.withHttpInfo(), new TypeReference<LicenseOrgToggle>() {
        }, new AsyncApiCallback<ApiResponse<LicenseOrgToggle>>() {
            @Override
            public void onCompleted(ApiResponse<LicenseOrgToggle> response) {
                notifySuccess(future, callback, response.getBody());
            }

            @Override
            public void onFailed(Throwable exception) {
                if (shouldThrowErrors) {
                    notifyFailure(future, callback, exception);
                } else {
                    notifySuccess(future, callback, null);
                }
            }
        });
        return future;
    } catch (Throwable exception) {
        return Futures.immediateFailedFuture(exception);
    }
}

From source file:org.opendaylight.vpnservice.natservice.internal.VpnFloatingIpHandler.java

void cleanupFibEntries(final BigInteger dpnId, final String vpnName, final String externalIp,
        final long label) {
    //Remove Prefix from BGP
    String rd = NatUtil.getVpnRd(dataBroker, vpnName);
    removePrefixFromBGP(rd, externalIp + "/32");

    //Remove custom FIB routes

    //Future<RpcResult<java.lang.Void>> removeFibEntry(RemoveFibEntryInput input);
    RemoveFibEntryInput input = new RemoveFibEntryInputBuilder().setVpnName(vpnName).setSourceDpid(dpnId)
            .setIpAddress(externalIp).setServiceId(label).build();
    Future<RpcResult<Void>> future = fibService.removeFibEntry(input);

    ListenableFuture<RpcResult<Void>> labelFuture = Futures.transform(
            JdkFutureAdapters.listenInPoolThread(future),
            new AsyncFunction<RpcResult<Void>, RpcResult<Void>>() {

                @Override//from   w w  w  .  ja  v a 2 s .c om
                public ListenableFuture<RpcResult<Void>> apply(RpcResult<Void> result) throws Exception {
                    //Release label
                    if (result.isSuccessful()) {
                        removeTunnelTableEntry(dpnId, label);
                        removeLFibTableEntry(dpnId, label);
                        RemoveVpnLabelInput labelInput = new RemoveVpnLabelInputBuilder().setVpnName(vpnName)
                                .setIpPrefix(externalIp).build();
                        Future<RpcResult<Void>> labelFuture = vpnService.removeVpnLabel(labelInput);
                        return JdkFutureAdapters.listenInPoolThread(labelFuture);
                    } else {
                        String errMsg = String.format(
                                "RPC call to remove custom FIB entries on dpn %s for prefix %s Failed - %s",
                                dpnId, externalIp, result.getErrors());
                        LOG.error(errMsg);
                        return Futures.immediateFailedFuture(new RuntimeException(errMsg));
                    }
                }
            });

    Futures.addCallback(labelFuture, new FutureCallback<RpcResult<Void>>() {

        @Override
        public void onFailure(Throwable error) {
            LOG.error("Error in removing the label or custom fib entries", error);
        }

        @Override
        public void onSuccess(RpcResult<Void> result) {
            if (result.isSuccessful()) {
                LOG.debug("Successfully removed the label for the prefix {} from VPN {}", externalIp, vpnName);
            } else {
                LOG.error("Error in removing the label for prefix {} from VPN {}, {}", externalIp, vpnName,
                        result.getErrors());
            }
        }
    });
}

From source file:org.opendaylight.faas.fabricmgr.VContainerNetNodeServiceProvider.java

@Override
public Future<RpcResult<Void>> rmLneLayer2(RmLneLayer2Input input) {
    TenantId tenantId = input.getTenantId();
    VcLneId lswId = input.getLneId();//w  w w. ja  va 2  s.  c om

    VContainerConfigMgr vcMgr = FabricMgrProvider.getInstance()
            .getVcConfigDataMgr(new Uuid(tenantId.getValue()));
    if (vcMgr == null) {
        LOG.error("FABMGR: ERROR: rmLneLayer2: vcMgr is null: {}", tenantId.getValue());
        return Futures.immediateFailedFuture(new IllegalArgumentException("vcMgr is null"));
    }
    vcMgr.getLdNodeConfigDataMgr().releaseL2Resource(input.getVfabricId());

    RmLogicalSwitchInputBuilder inputBuilder = new RmLogicalSwitchInputBuilder();

    FabricId fabricId = new FabricId(input.getVfabricId());
    inputBuilder.setFabricId(fabricId);
    inputBuilder.setNodeId(new NodeId(lswId));

    LOG.debug("FABMGR: rmLneLayer2: fabricId={}, lswId={}", fabricId.getValue(), lswId.getValue());

    final RpcResultBuilder<Void> resultBuilder = RpcResultBuilder.<Void>success();
    Future<RpcResult<Void>> result = this.fabServiceService.rmLogicalSwitch(inputBuilder.build());
    try {
        RpcResult<Void> output = result.get();
        if (output.isSuccessful()) {
            LOG.debug("FABMGR: rmLneLayer2: rmLogicSwitch RPC success");
            return result;
        } else {
            return Futures.immediateFuture(
                    resultBuilder.withError(ErrorType.RPC, "rmLogicSwitch RPC failed").build());
        }
    } catch (Exception e) {
        LOG.error("FABMGR: ERROR: rmLneLayer2: rmLogicSwitch RPC failed.", e);
    }

    return Futures.immediateFailedFuture(new IllegalArgumentException("rmLogicSwitch RPC failed"));
}

From source file:org.opendaylight.faas.fabric.general.FabricServiceAPIProvider.java

@Override
public Future<RpcResult<Void>> rmLogicalSwitch(RmLogicalSwitchInput input) {

    final FabricId fabricId = input.getFabricId();
    NodeId nodeid = input.getNodeId();// w  ww  .ja  va  2s  .  c  o  m

    final FabricInstance fabricObj = FabricInstanceCache.INSTANCE.retrieveFabric(fabricId);
    if (fabricObj == null) {
        return Futures.immediateFailedFuture(
                new IllegalArgumentException(String.format("fabric %s does not exist", fabricId)));
    }

    final InstanceIdentifier<Node> lswIId = MdSalUtils.createNodeIId(fabricId.getValue(), nodeid);

    ReadOnlyTransaction trans = dataBroker.newReadOnlyTransaction();

    CheckedFuture<Optional<Node>, ReadFailedException> readFuture = trans.read(LogicalDatastoreType.OPERATIONAL,
            lswIId);

    return Futures.transform(readFuture, new AsyncFunction<Optional<Node>, RpcResult<Void>>() {

        @Override
        public ListenableFuture<RpcResult<Void>> apply(Optional<Node> optional) throws Exception {

            if (optional.isPresent()) {
                Node lsw = optional.get();
                fabricObj.notifyLogicSwitchRemoved(lsw);

                WriteTransaction wt = dataBroker.newWriteOnlyTransaction();
                wt.delete(LogicalDatastoreType.OPERATIONAL, lswIId);
                MdSalUtils.wrapperSubmit(wt, executor);
            }

            return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
        }
    }, executor);
}

From source file:com.orangerhymelabs.helenus.cassandra.document.DocumentService.java

private ListenableFuture<AbstractDocumentRepository> acquireRepositoryFor(View view) {
    Identifier cacheKey = view.identifier();
    AbstractDocumentRepository repo = repoCache.get(cacheKey);

    if (repo != null) {
        return Futures.immediateFuture(repo);
    }// w  w  w .  j  av  a2s. c o  m

    try {
        repo = factory.newInstance(view);
        repoCache.put(cacheKey, repo);
        return Futures.immediateFuture(repo);
    } catch (KeyDefinitionException e) {
        return Futures.immediateFailedFuture(e);
    }
}

From source file:io.v.v23.rpc.ReflectInvoker.java

@Override
public ListenableFuture<Interface[]> getSignature(VContext ctx) {
    List<Interface> interfaces = new ArrayList<Interface>();
    for (Map.Entry<Object, Method> entry : signatureMethods.entrySet()) {
        try {/* w  ww. ja v a 2s .  c o  m*/
            interfaces.add((Interface) entry.getValue().invoke(entry.getKey()));
        } catch (IllegalAccessException e) {
            return Futures.immediateFailedFuture(
                    new VException(String.format("Could not invoke signature method for server class %s: %s",
                            server.getClass().getName(), e.toString())));
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            return Futures.immediateFailedFuture(
                    new VException(String.format("Could not invoke signature method for server class %s: %s",
                            server.getClass().getName(), e.toString())));
        }
    }
    return Futures.immediateFuture(interfaces.toArray(new Interface[interfaces.size()]));
}

From source file:com.microsoft.intellij.helpers.IDEHelperImpl.java

@NotNull
@Override/*from   ww w. ja  va  2s . co  m*/
public ListenableFuture<String> buildArtifact(@NotNull ProjectDescriptor projectDescriptor,
        @NotNull ArtifactDescriptor artifactDescriptor) {
    try {
        Project project = findOpenProject(projectDescriptor);

        final Artifact artifact = findProjectArtifact(project, artifactDescriptor);

        final SettableFuture<String> future = SettableFuture.create();

        Futures.addCallback(buildArtifact(project, artifact, false), new FutureCallback<Boolean>() {
            @Override
            public void onSuccess(@Nullable Boolean succeded) {
                if (succeded != null && succeded) {
                    future.set(artifact.getOutputFilePath());
                } else {
                    future.setException(new AzureCmdException("An error occurred while building the artifact"));
                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                if (throwable instanceof ExecutionException) {
                    future.setException(new AzureCmdException("An error occurred while building the artifact",
                            throwable.getCause()));
                } else {
                    future.setException(
                            new AzureCmdException("An error occurred while building the artifact", throwable));
                }
            }
        });

        return future;
    } catch (AzureCmdException e) {
        return Futures.immediateFailedFuture(e);
    }
}