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

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

Introduction

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

Prototype

public abstract boolean isPresent();

Source Link

Document

Returns true if this holder contains a (non-null) instance.

Usage

From source file:google.registry.flows.host.HostFlowUtils.java

/** Checks that a host name is valid. */
static InternetDomainName validateHostName(String name) throws EppException {
    checkArgumentNotNull(name, "Must specify host name to validate");
    if (name.length() > 253) {
        throw new HostNameTooLongException();
    }/*  w w w  .j ava  2  s. co  m*/
    String hostNameLowerCase = Ascii.toLowerCase(name);
    if (!name.equals(hostNameLowerCase)) {
        throw new HostNameNotLowerCaseException(hostNameLowerCase);
    }
    try {
        String hostNamePunyCoded = Idn.toASCII(name);
        if (!name.equals(hostNamePunyCoded)) {
            throw new HostNameNotPunyCodedException(hostNamePunyCoded);
        }
        InternetDomainName hostName = InternetDomainName.from(name);
        if (!name.equals(hostName.toString())) {
            throw new HostNameNotNormalizedException(hostName.toString());
        }
        // Checks whether a hostname is deep enough. Technically a host can be just one under a
        // public suffix (e.g. example.com) but we require by policy that it has to be at least one
        // part beyond that (e.g. ns1.example.com). The public suffix list includes all current
        // ccTlds, so this check requires 4+ parts if it's a ccTld that doesn't delegate second
        // level domains, such as .co.uk. But the list does not include new tlds, so in that case
        // we just ensure 3+ parts. In the particular case where our own tld has a '.' in it, we know
        // that there need to be 4 parts as well.
        if (hostName.isUnderPublicSuffix()) {
            if (hostName.parent().isUnderPublicSuffix()) {
                return hostName;
            }
        } else {
            // We need to know how many parts the hostname has beyond the public suffix, but we don't
            // know what the public suffix is. If the host is in bailiwick and we are hosting a
            // multipart "tld" like .co.uk the publix suffix might be 2 parts. Otherwise it's an
            // unrecognized tld that's not on the public suffix list, so assume the tld alone is the
            // public suffix.
            Optional<InternetDomainName> tldParsed = findTldForName(hostName);
            int suffixSize = tldParsed.isPresent() ? tldParsed.get().parts().size() : 1;
            if (hostName.parts().size() >= suffixSize + 2) {
                return hostName;
            }
        }
        throw new HostNameTooShallowException();
    } catch (IllegalArgumentException e) {
        throw new InvalidHostNameException();
    }
}

From source file:org.apache.gobblin.cli.JobInfoPrintUtils.java

/**
 * Print properties of a specific job/* ww  w .  j  a  v a2  s. co  m*/
 * @param jobExecutionInfoOptional
 */
public static void printJobProperties(Optional<JobExecutionInfo> jobExecutionInfoOptional) {
    if (!jobExecutionInfoOptional.isPresent()) {
        System.err.println("Job not found.");
        return;
    }
    List<List<String>> data = new ArrayList<>();
    List<String> flags = Arrays.asList("", "-");
    List<String> labels = Arrays.asList("Property Key", "Property Value");

    for (Map.Entry<String, String> entry : jobExecutionInfoOptional.get().getJobProperties().entrySet()) {
        data.add(Arrays.asList(entry.getKey(), entry.getValue()));
    }

    new CliTablePrinter.Builder().labels(labels).data(data).flags(flags).delimiterWidth(2).build().printTable();
}

From source file:org.opendaylight.netvirt.bgpmanager.BgpUtil.java

static VpnInstanceOpDataEntry getVpnInstanceOpData(DataBroker broker, String rd)
        throws InterruptedException, ExecutionException, TimeoutException {
    InstanceIdentifier<VpnInstanceOpDataEntry> id = getVpnInstanceOpDataIdentifier(rd);
    Optional<VpnInstanceOpDataEntry> vpnInstanceOpData = MDSALUtil.read(broker,
            LogicalDatastoreType.OPERATIONAL, id);
    if (vpnInstanceOpData.isPresent()) {
        return vpnInstanceOpData.get();
    }//w  ww  .j  a v  a2  s .c o m
    return null;
}

From source file:org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier.java

/**
 * Returns filename for this YANG module as specified in RFC 6020.
 *
 * Returns filename in format <code>moduleName ['@' revision] '.yang'</code>
 *
 * Where Where revision-date is in format YYYY-mm-dd.
 *
 * <p>/*  w  w  w  .j ava 2s. c om*/
 * See http://tools.ietf.org/html/rfc6020#section-5.2
 *
 * @return Filename for this source identifier.
 */
public static String toYangFileName(final String moduleName, final Optional<String> revision) {
    StringBuilder filename = new StringBuilder(moduleName);
    if (revision.isPresent()) {
        filename.append('@');
        filename.append(revision.get());
    }
    filename.append(YangConstants.RFC6020_YANG_FILE_EXTENSION);
    return filename.toString();
}

From source file:org.splevo.project.utils.SPLevoProjectUtil.java

/**
 * Loads a SPLevo project from a file resource.
 * //from   w  w  w.j av a2s.c  o m
 * @param consolidationProject
 *            The project that represents the consolidation project.
 * @return The loaded SPLevo project.
 * @throws IOException
 *             Thrown if the file could not be loaded.
 */
public static SPLevoProject loadSPLevoProjectModel(IProject consolidationProject) throws IOException {
    Optional<IFile> projectFile = findSPLevoProjectFile(consolidationProject);
    if (projectFile.isPresent()) {
        return loadSPLevoProjectModel(projectFile.get());
    }
    return null;
}

From source file:gobblin.serde.HiveSerDeWrapper.java

/**
 * Get an instance of {@link HiveSerDeWrapper}.
 *
 * @param serDeType The SerDe type. If serDeType is one of the available {@link HiveSerDeWrapper.BuiltInHiveSerDe},
 * the other three parameters are not used. Otherwise, serDeType should be the class name of a {@link SerDe},
 * and the other three parameters must be present.
 *///from www .j a  v a  2 s.c  o m
public static HiveSerDeWrapper get(String serDeType, Optional<String> inputFormatClassName,
        Optional<String> outputFormatClassName) {
    Optional<BuiltInHiveSerDe> hiveSerDe = Enums.getIfPresent(BuiltInHiveSerDe.class, serDeType.toUpperCase());
    if (hiveSerDe.isPresent()) {
        return new HiveSerDeWrapper(hiveSerDe.get());
    } else {
        Preconditions.checkArgument(inputFormatClassName.isPresent(),
                "Missing input format class name for SerDe " + serDeType);
        Preconditions.checkArgument(outputFormatClassName.isPresent(),
                "Missing output format class name for SerDe " + serDeType);
        return new HiveSerDeWrapper(serDeType, inputFormatClassName.get(), outputFormatClassName.get());
    }
}

From source file:com.qcadoo.mes.orders.dates.OrderDates.java

public static ThreeLevelDate threeLevelDate(final Entity order, final String plannedDateFieldName,
        final String correctedDateFieldName, final String effectiveDateFieldName,
        final Optional<DateTime> defaultPlanned) {
    Optional<DateTime> plannedStart = tryExtractLocalDate(order, plannedDateFieldName);

    Preconditions.checkArgument(defaultPlanned.isPresent() || plannedStart.isPresent(),
            "You have to either pass an order with defined planned dates or provide the default values");

    Optional<DateTime> correctedStart = tryExtractLocalDate(order, correctedDateFieldName);
    Optional<DateTime> effectiveStart = tryExtractLocalDate(order, effectiveDateFieldName);

    return new ThreeLevelDate(plannedStart.or(defaultPlanned).get(), correctedStart, effectiveStart);
}

From source file:io.mesosphere.mesos.frameworks.cassandra.ZooKeeperSeedProvider.java

private static Optional<Integer> parseInt(Optional<String> stringOption, String key) {

    if (stringOption.isPresent()) {

        String string = stringOption.get();

        try {//from ww w .  j  a  v  a2s. c  o  m
            return Optional.of(Integer.parseInt(string));

        } catch (NumberFormatException nfe) {

            LOGGER.error(String.format("%s must be set to a valid integer %s provided", key, string), nfe);

            return Optional.absent();
        }
    } else {

        return Optional.absent();
    }
}

From source file:de.azapps.mirakel.model.list.SpecialListsWhereDeserializer.java

@NonNull
private static Optional<SpecialListsBaseProperty> parseSpecialListWhere(final @NonNull JsonElement obj,
        final int deep) throws IllegalArgumentException {
    if (obj.isJsonObject()) {
        return parseSpecialListsCondition(obj);
    } else if (obj.isJsonArray()) {
        final List<SpecialListsBaseProperty> childs = new ArrayList<>(obj.getAsJsonArray().size());
        for (final JsonElement el : obj.getAsJsonArray()) {
            final Optional<SpecialListsBaseProperty> child = parseSpecialListWhere(el, deep + 1);
            if (child.isPresent()) {
                childs.add(child.get());
            }/*from w  w w . ja va  2  s .co  m*/
        }
        return of((SpecialListsBaseProperty) new SpecialListsConjunctionList(
                ((deep % 2) == 0) ? SpecialListsConjunctionList.CONJUNCTION.AND
                        : SpecialListsConjunctionList.CONJUNCTION.OR,
                childs));
    } else if (obj.isJsonNull()) {
        return absent();
    } else {
        throw new IllegalArgumentException("Unknown json type");
    }
}

From source file:org.opendaylight.protocol.bgp.flowspec.ipv6.FlowspecIpv6NlriParserHelper.java

private static final List<NextHeaders> createNextHeaders(final UnkeyedListNode nextHeadersData) {
    final List<NextHeaders> nextHeaders = new ArrayList<>();

    for (final UnkeyedListEntryNode node : nextHeadersData.getValue()) {
        final NextHeadersBuilder nextHeadersBuilder = new NextHeadersBuilder();
        final Optional<DataContainerChild<? extends PathArgument, ?>> opValue = node
                .getChild(AbstractFlowspecNlriParser.OP_NID);
        if (opValue.isPresent()) {
            nextHeadersBuilder//from ww w.  jav  a  2s  .  c  o  m
                    .setOp(NumericOneByteOperandParser.INSTANCE.create((Set<String>) opValue.get().getValue()));
        }
        final Optional<DataContainerChild<? extends PathArgument, ?>> valueNode = node
                .getChild(AbstractFlowspecNlriParser.VALUE_NID);
        if (valueNode.isPresent()) {
            nextHeadersBuilder.setValue((Short) valueNode.get().getValue());
        }
        nextHeaders.add(nextHeadersBuilder.build());
    }

    return nextHeaders;
}