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

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

Introduction

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

Prototype

public abstract T get();

Source Link

Document

Returns the contained instance, which must be present.

Usage

From source file:org.opendaylight.lacp.Utils.NodePort.java

private static NodeConnector readNodeConnector(NodeConnectorRef ncRef) {
    NodeConnector nc = null;// www.  j av a  2s . com
    ReadOnlyTransaction readTx = LacpUtil.getDataBrokerService().newReadOnlyTransaction();

    try {
        Optional<NodeConnector> dataObject = readTx
                .read(LogicalDatastoreType.OPERATIONAL, (InstanceIdentifier<NodeConnector>) ncRef.getValue())
                .get();
        if (dataObject.isPresent()) {
            nc = (NodeConnector) dataObject.get();
        }
    } catch (Exception e) {
        readTx.close();
    }
    readTx.close();
    return nc;
}

From source file:alluxio.cli.validation.Utils.java

/**
 * Checks whether a path is the mounting point of a RAM disk volume.
 *
 * @param path  a string represents the path to be checked
 * @param fsTypes an array of strings represents expected file system type
 * @return true if the path is the mounting point of volume with one of the given fsTypes,
 *         false otherwise/*  w w w  .  j ava 2 s  . com*/
 * @throws IOException if the function fails to get the mount information of the system
 */
public static boolean isMountingPoint(String path, String[] fsTypes) throws IOException {
    List<UnixMountInfo> infoList = ShellUtils.getUnixMountInfo();
    for (UnixMountInfo info : infoList) {
        Optional<String> mountPoint = info.getMountPoint();
        Optional<String> fsType = info.getFsType();
        if (mountPoint.isPresent() && mountPoint.get().equals(path) && fsType.isPresent()) {
            for (String expectedType : fsTypes) {
                if (fsType.get().equalsIgnoreCase(expectedType)) {
                    return true;
                }
            }
        }
    }
    return false;
}

From source file:org.xacml4j.v30.policy.function.AttributeDesignatorFunctions.java

private static AttributeExpType getType(AnyURIExp typeUri) {
    AttributeExpType typeId = (AttributeExpType) typeUri.getEvaluatesTo();
    Optional<AttributeExpType> resolvedType = XacmlTypes.getType(typeUri.getValue().toString());
    if (!resolvedType.isPresent()) {
        throw new XacmlSyntaxException("Unknown XACML type id=\"%s\"", typeId);
    }//ww  w  .  j av  a 2s  .co m
    return resolvedType.get();
}

From source file:org.opendaylight.vpnservice.utilities.InterfaceUtils.java

public static String getEndpointIpAddressForDPN(DataBroker broker, BigInteger dpnId) {
    String nextHopIp = null;//  w ww .j  a  v  a  2s.  co  m
    InstanceIdentifier<DPNTEPsInfo> tunnelInfoId = InstanceIdentifier.builder(DpnEndpoints.class)
            .child(DPNTEPsInfo.class, new DPNTEPsInfoKey(dpnId)).build();
    Optional<DPNTEPsInfo> tunnelInfo = VpnUtil.read(broker, LogicalDatastoreType.CONFIGURATION, tunnelInfoId);
    if (tunnelInfo.isPresent()) {
        List<TunnelEndPoints> nexthopIpList = tunnelInfo.get().getTunnelEndPoints();
        if (nexthopIpList != null && !nexthopIpList.isEmpty()) {
            nextHopIp = nexthopIpList.get(0).getIpAddress().getIpv4Address().getValue();
        }
    }
    return nextHopIp;
}

From source file:org.sonar.server.computation.task.projectanalysis.measure.MeasureDtoToMeasure.java

private static Optional<Measure> toLevelMeasure(MeasureDto measureDto, @Nullable String data) {
    if (data == null) {
        return toNoValueMeasure(measureDto);
    }/*from www  . j a  v a 2 s. co m*/
    Optional<Measure.Level> level = toLevel(data);
    if (!level.isPresent()) {
        return toNoValueMeasure(measureDto);
    }
    return of(setCommonProperties(Measure.newMeasureBuilder(), measureDto).create(level.get()));
}

From source file:org.openqa.selenium.testing.drivers.ExternalDriverSupplier.java

private static Optional<Supplier<WebDriver>> createDelegate(Capabilities desiredCapabilities,
        Capabilities requiredCapabilities) {
    Optional<Class<? extends Supplier>> supplierClass = getDelegateClass();
    if (supplierClass.isPresent()) {
        Class<? extends Supplier> clazz = supplierClass.get();
        logger.info("Using delegate supplier: " + clazz.getName());
        try {/*from w w  w  .j ava 2s  .c  o  m*/
            @SuppressWarnings("unchecked")
            Constructor<Supplier<WebDriver>> ctor = (Constructor<Supplier<WebDriver>>) clazz
                    .getConstructor(Capabilities.class, Capabilities.class);
            return Optional.of(ctor.newInstance(desiredCapabilities, requiredCapabilities));
        } catch (InvocationTargetException e) {
            throw Throwables.propagate(e.getTargetException());
        } catch (Exception e) {
            throw Throwables.propagate(e);
        }
    }
    return Optional.absent();
}

From source file:org.opendaylight.tl1.impl.MDSal.java

public static List<String> getAllDevices() {

    InstanceIdentifier<DeviceRegistry> identifier = InstanceIdentifier.create(DeviceRegistry.class);
    ReadOnlyTransaction transaction = dbroker.newReadOnlyTransaction();

    ReadOnlyTransaction readTx = dbroker.newReadOnlyTransaction();
    ListenableFuture<Optional<DeviceRegistry>> dataFuture = readTx.read(LogicalDatastoreType.OPERATIONAL,
            identifier);//w ww  .j ava 2 s  .co m
    Futures.addCallback(dataFuture, new FutureCallback<Optional<DeviceRegistry>>() {
        @Override
        public void onSuccess(final Optional<DeviceRegistry> result) {
            if (result.isPresent()) {
                // data are present in data store.
                allDevices = ExtractIps(result.get().getDeviceRegistryEntry());
                //doSomething(result.get());
            } else {
                // data are not present in data store.
                allDevices = null;
            }
        }

        @Override
        public void onFailure(final Throwable t) {
            // Error during read
        }

    });

    return allDevices;
}

From source file:org.opendaylight.netconf.messagebus.eventsources.netconf.NetconfEventSourceMount.java

private static <T extends DOMService> T getService(DOMMountPoint mountPoint, Class<T> service) {
    final Optional<T> optional = mountPoint.getService(service);
    Preconditions.checkState(optional.isPresent(), "Service not present on mount point: %s", service.getName());
    return optional.get();
}

From source file:io.crate.planner.consumer.GlobalAggregateConsumer.java

private static Plan globalAggregates(Functions functions, QueriedTableRelation table, ConsumerContext context,
        RowGranularity projectionGranularity) {
    QuerySpec querySpec = table.querySpec();
    if (querySpec.groupBy().isPresent() || !querySpec.hasAggregates()) {
        return null;
    }//from   w w w .java  2s.c o  m

    Planner.Context plannerContext = context.plannerContext();
    validateAggregationOutputs(table.tableRelation(), querySpec.outputs());
    // global aggregate: collect and partial aggregate on C and final agg on H

    ProjectionBuilder projectionBuilder = new ProjectionBuilder(functions, querySpec);
    SplitPoints splitPoints = projectionBuilder.getSplitPoints();

    AggregationProjection ap = projectionBuilder.aggregationProjection(splitPoints.leaves(),
            splitPoints.aggregates(), Aggregation.Step.ITER, Aggregation.Step.PARTIAL, projectionGranularity);
    RoutedCollectPhase collectPhase = RoutedCollectPhase.forQueriedTable(plannerContext, table,
            splitPoints.leaves(), ImmutableList.of(ap));
    Collect collect = new Collect(collectPhase, TopN.NO_LIMIT, 0, ap.outputs().size(), 1, null);

    //// the handler stuff
    List<Projection> mergeProjections = new ArrayList<>();
    mergeProjections
            .add(projectionBuilder.aggregationProjection(splitPoints.aggregates(), splitPoints.aggregates(),
                    Aggregation.Step.PARTIAL, Aggregation.Step.FINAL, RowGranularity.CLUSTER));

    Optional<HavingClause> havingClause = querySpec.having();
    if (havingClause.isPresent()) {
        HavingClause having = havingClause.get();
        mergeProjections.add(ProjectionBuilder.filterProjection(splitPoints.aggregates(), having));
    }
    Limits limits = plannerContext.getLimits(querySpec);
    TopNProjection topNProjection = ProjectionBuilder.topNProjection(splitPoints.aggregates(), null,
            limits.offset(), limits.finalLimit(), querySpec.outputs());
    mergeProjections.add(topNProjection);
    MergePhase mergePhase = new MergePhase(plannerContext.jobId(), plannerContext.nextExecutionPhaseId(),
            "mergeOnHandler", collectPhase.nodeIds().size(), Collections.emptyList(),
            Symbols.extractTypes(ap.outputs()), mergeProjections, DistributionInfo.DEFAULT_SAME_NODE, null);
    return new Merge(collect, mergePhase, TopN.NO_LIMIT, 0, topNProjection.outputs().size(), 1, null);
}

From source file:org.onos.yangtools.yang.data.api.schema.tree.StoreTreeNodes.java

public static <T extends StoreTreeNode<T>> Map.Entry<YangInstanceIdentifier, T> findClosestsOrFirstMatch(
        final T tree, final YangInstanceIdentifier path, final Predicate<T> predicate) {
    Optional<T> parent = Optional.<T>of(tree);
    Optional<T> current = Optional.<T>of(tree);

    int nesting = 0;
    Iterator<PathArgument> pathIter = path.getPathArguments().iterator();
    while (current.isPresent() && pathIter.hasNext() && !predicate.apply(current.get())) {
        parent = current;//  w  w w.  j  a v  a 2s . c  o m
        current = current.get().getChild(pathIter.next());
        nesting++;
    }
    if (current.isPresent()) {
        final YangInstanceIdentifier currentPath = YangInstanceIdentifier
                .create(Iterables.limit(path.getPathArguments(), nesting));
        return new SimpleEntry<YangInstanceIdentifier, T>(currentPath, current.get());
    }

    /*
     * Subtracting 1 from nesting level at this point is safe, because we
     * cannot reach here with nesting == 0: that would mean the above check
     * for current.isPresent() failed, which it cannot, as current is always
     * present. At any rate we check state just to be on the safe side.
     */
    Preconditions.checkState(nesting > 0);
    final YangInstanceIdentifier parentPath = YangInstanceIdentifier
            .create(Iterables.limit(path.getPathArguments(), nesting - 1));
    return new SimpleEntry<YangInstanceIdentifier, T>(parentPath, parent.get());
}