Example usage for com.google.common.base Optional or

List of usage examples for com.google.common.base Optional or

Introduction

In this page you can find the example usage for com.google.common.base Optional or.

Prototype

@Beta
public abstract T or(Supplier<? extends T> supplier);

Source Link

Document

Returns the contained instance if it is present; supplier.get() otherwise.

Usage

From source file:brooklyn.location.jclouds.JcloudsLocation.java

protected void waitForReachable(final ComputeService computeService, final NodeMetadata node,
        Optional<HostAndPort> hostAndPortOverride, final LoginCredentials expectedCredentials,
        ConfigBag setup) {//from w  ww  . ja va 2 s . c  o  m
    String waitForSshable = setup.get(WAIT_FOR_SSHABLE);
    checkArgument(!"false".equalsIgnoreCase(waitForSshable),
            "waitForReachable called despite waitForSshable=%s", waitForSshable);

    String vmIp = hostAndPortOverride.isPresent() ? hostAndPortOverride.get().getHostText()
            : JcloudsUtil.getFirstReachableAddress(computeService.getContext(), node);
    if (vmIp == null)
        LOG.warn("Unable to extract IP for " + node + " (" + setup.getDescription()
                + "): subsequent connection attempt will likely fail");

    int vmPort = hostAndPortOverride.isPresent() ? hostAndPortOverride.get().getPortOrDefault(22) : 22;

    long delayMs = -1;
    try {
        delayMs = Time.parseTimeString("" + waitForSshable);
    } catch (Exception e) {
        // normal if 'true'; just fall back to default
    }
    if (delayMs < 0)
        delayMs = Time.parseTimeString(WAIT_FOR_SSHABLE.getDefaultValue());

    String user = expectedCredentials.getUser();
    if (LOG.isDebugEnabled()) {
        Optional<String> password;
        Optional<String> key;
        if (Boolean.TRUE.equals(setup.get(LOG_CREDENTIALS))) {
            password = expectedCredentials.getOptionalPassword();
            key = expectedCredentials.getOptionalPrivateKey();
        } else {
            password = expectedCredentials.getOptionalPassword().isPresent() ? Optional.of("******")
                    : Optional.<String>absent();
            key = expectedCredentials.getOptionalPrivateKey().isPresent() ? Optional.of("******")
                    : Optional.<String>absent();
        }
        LOG.debug(
                "VM {}: reported online, now waiting {} for it to be sshable on {}@{}:{}{}; using credentials password={}; key={}",
                new Object[] { setup.getDescription(), Time.makeTimeStringRounded(delayMs), user, vmIp, vmPort,
                        Objects.equal(user, getUser(setup)) ? ""
                                : " (setup user is different: " + getUser(setup) + ")",
                        password.or("<absent>"), key.or("<absent>") });
    }

    Callable<Boolean> checker;
    if (hostAndPortOverride.isPresent()) {
        final SshMachineLocation machine = createTemporarySshMachineLocation(hostAndPortOverride.get(),
                expectedCredentials, setup);
        checker = new Callable<Boolean>() {
            public Boolean call() {
                int exitstatus = machine.execScript("check-connectivity", ImmutableList.of("hostname"));
                return exitstatus == 0;
            }
        };
    } else {
        checker = new Callable<Boolean>() {
            public Boolean call() {
                Statement statement = Statements.newStatementList(exec("hostname"));
                ExecResponse response = computeService.runScriptOnNode(node.getId(), statement,
                        overrideLoginCredentials(expectedCredentials).runAsRoot(false));
                return response.getExitStatus() == 0;
            }
        };
    }

    Stopwatch stopwatch = Stopwatch.createStarted();

    ReferenceWithError<Boolean> reachable = new Repeater().every(1, SECONDS).until(checker)
            .limitTimeTo(delayMs, MILLISECONDS).runKeepingError();

    if (!reachable.getWithoutError()) {
        throw new IllegalStateException("SSH failed for " + user + "@" + vmIp + " (" + setup.getDescription()
                + ") after waiting " + Time.makeTimeStringRounded(delayMs), reachable.getError());
    }

    LOG.debug("VM {}: is sshable after {} on {}@{}",
            new Object[] { setup.getDescription(), Time.makeTimeStringRounded(stopwatch), user, vmIp });
}

From source file:com.google.devtools.build.lib.rules.objc.ObjcRuleTestCase.java

protected void checkBundleIdFlagsInPlistMergeAction(Optional<String> specifiedBundleId,
        Map<String, String> variableSubstitutions, String defaultBundleId) throws Exception {
    String targetName = "//x:x";
    PlMergeProtos.Control control = plMergeControl(targetName);
    ConfiguredTarget target = getConfiguredTarget(targetName);
    Artifact mergedPlist = getMergedInfoPlist(target);
    String bundleIdToCheck = specifiedBundleId.or(defaultBundleId);
    Artifact versionInfoplist = getBinArtifact("plists/x" + artifactName("-version.plist"), target);
    Artifact environmentInfoplist = getBinArtifact("plists/x" + artifactName("-environment.plist"), target);
    Artifact automaticInfoplist = getBinArtifact("plists/x" + artifactName("-automatic.plist"), target);

    assertPlistMergeControlUsesSourceFiles(control,
            ImmutableList.<String>of("x/Info.plist", versionInfoplist.getExecPathString(),
                    environmentInfoplist.getExecPathString(), automaticInfoplist.getExecPathString()));
    assertThat(control.getOutFile()).isEqualTo(mergedPlist.getExecPathString());
    assertThat(control.getVariableSubstitutionMapMap()).containsExactlyEntriesIn(variableSubstitutions);

    if (specifiedBundleId.isPresent()) {
        assertThat(control.hasPrimaryBundleId()).isTrue();
        assertThat(control.getPrimaryBundleId()).isEqualTo(bundleIdToCheck);
    } else {//from  w  ww  .  ja v  a  2s . co m
        assertThat(control.hasFallbackBundleId()).isTrue();
        assertThat(control.getFallbackBundleId()).isEqualTo(bundleIdToCheck);
    }
}