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

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

Introduction

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

Prototype

public abstract <V> Optional<V> transform(Function<? super T, V> function);

Source Link

Document

If the instance is present, it is transformed with the given Function ; otherwise, Optional#absent is returned.

Usage

From source file:org.opendaylight.netconf.topology.singleton.impl.tx.NetconfReadOnlyTransaction.java

@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
        final YangInstanceIdentifier path) {

    LOG.trace("{}: Read {} via NETCONF: {}", id, store, path);

    final Future<Optional<NormalizedNodeMessage>> future = delegate.read(store, path);
    final SettableFuture<Optional<NormalizedNode<?, ?>>> settableFuture = SettableFuture.create();
    final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> checkedFuture;
    checkedFuture = Futures.makeChecked(settableFuture, new Function<Exception, ReadFailedException>() {
        @Nullable/*from  ww w.j ava 2 s.co m*/
        @Override
        public ReadFailedException apply(Exception cause) {
            return new ReadFailedException("Read from transaction failed", cause);
        }
    });
    future.onComplete(new OnComplete<Optional<NormalizedNodeMessage>>() {
        @Override
        public void onComplete(final Throwable throwable,
                final Optional<NormalizedNodeMessage> normalizedNodeMessage) throws Throwable {
            if (throwable == null) {
                if (normalizedNodeMessage.isPresent()) {
                    settableFuture.set(normalizedNodeMessage
                            .transform(new Function<NormalizedNodeMessage, NormalizedNode<?, ?>>() {

                                @Nullable
                                @Override
                                public NormalizedNode<?, ?> apply(final NormalizedNodeMessage input) {
                                    return input.getNode();
                                }
                            }));
                } else {
                    settableFuture.set(Optional.absent());
                }
            } else {
                settableFuture.setException(throwable);
            }
        }
    }, actorSystem.dispatcher());
    return checkedFuture;
}

From source file:org.robotninjas.barge.log.journalio.JournalRaftLog.java

@Override
protected void recordVote(Optional<Replica> vote) {
    write(LogProto.JournalEntry.newBuilder()
            .setVote(LogProto.Vote.newBuilder().setVotedFor(vote.transform(toStringFunction()).or("")))
            .build());//from w w w  . j av  a2s. c o m
}

From source file:org.opendaylight.yangtools.yang.data.impl.schema.tree.OperationWithModification.java

/**
 * Read a particular child. If the child has been modified and does not have a stable
 * view, one will we instantiated with specified version.
 *
 * @param child/* w  w  w .j a  v  a2  s  .  com*/
 * @param version
 * @return
 */
Optional<NormalizedNode<?, ?>> read(final PathArgument child, final Version version) {
    final Optional<ModifiedNode> maybeChild = modification.getChild(child);
    if (maybeChild.isPresent()) {
        final ModifiedNode childNode = maybeChild.get();

        Optional<TreeNode> snapshot = childNode.getSnapshot();
        if (snapshot == null) {
            // Snapshot is not present, force instantiation
            snapshot = applyOperation.getChild(child).get().apply(childNode, childNode.getOriginal(), version);
        }

        return snapshot.transform(TreeNode::getData);
    }

    Optional<TreeNode> snapshot = modification.getSnapshot();
    if (snapshot == null) {
        snapshot = apply(modification.getOriginal(), version);
    }

    if (snapshot.isPresent()) {
        return snapshot.get().getChild(child).transform(TreeNode::getData);
    }

    return Optional.absent();
}

From source file:org.apache.james.imap.processor.GetAnnotationProcessor.java

private List<MailboxAnnotation> filterItemsBySize(Responder responder, String mailboxName,
        List<MailboxAnnotation> mailboxAnnotations, final Optional<Integer> maxsize) {
    Predicate<MailboxAnnotation> lowerPredicate = new Predicate<MailboxAnnotation>() {
        @Override// ww w  .  java  2 s.c om
        public boolean apply(final MailboxAnnotation input) {
            return maxsize.transform(new Function<Integer, Boolean>() {
                @Override
                public Boolean apply(Integer maxSizeInput) {
                    return (input.size() <= maxSizeInput);
                }
            }).or(true);
        }
    };

    return FluentIterable.from(mailboxAnnotations).filter(lowerPredicate).toList();
}

From source file:org.apache.aurora.scheduler.TaskVars.java

private void updateRackCounters(IScheduledTask task, ScheduleStatus newState) {
    final String host = task.getAssignedTask().getSlaveHost();
    Optional<String> rack;
    if (Strings.isNullOrEmpty(task.getAssignedTask().getSlaveHost())) {
        rack = Optional.absent();
    } else {/*from   ww w.j  a v a2 s.  c  o m*/
        rack = storage.read(storeProvider -> {
            Optional<IAttribute> rack1 = FluentIterable
                    .from(AttributeStore.Util.attributesOrNone(storeProvider, host)).firstMatch(IS_RACK);
            return rack1.transform(ATTR_VALUE);
        });
    }

    // Always dummy-read the lost-tasks-per-rack stat. This ensures that there is at least a zero
    // exported for all racks.
    if (rack.isPresent()) {
        counters.getUnchecked(rackStatName(rack.get()));
    }

    if (newState == ScheduleStatus.LOST) {
        if (rack.isPresent()) {
            counters.getUnchecked(rackStatName(rack.get())).increment();
        } else {
            LOG.warn("Failed to find rack attribute associated with host " + host);
        }
    }
}

From source file:org.onos.yangtools.yang.data.impl.schema.tree.OperationWithModification.java

/**
 * Read a particular child. If the child has been modified and does not have a stable
 * view, one will we instantiated with specified version.
 *
 * @param child// w  ww. j  a  v  a 2 s. co  m
 * @param version
 * @return
 */
Optional<NormalizedNode<?, ?>> read(final PathArgument child, final Version version) {
    final Optional<ModifiedNode> maybeChild = modification.getChild(child);
    if (maybeChild.isPresent()) {
        final ModifiedNode childNode = maybeChild.get();

        Optional<TreeNode> snapshot = childNode.getSnapshot();
        if (snapshot == null) {
            // Snapshot is not present, force instantiation
            snapshot = applyOperation.getChild(child).get().apply(childNode, childNode.getOriginal(), version);
        }

        return snapshot.transform(READ_DATA);
    }

    Optional<TreeNode> snapshot = modification.getSnapshot();
    if (snapshot == null) {
        snapshot = apply(modification.getOriginal(), version);
    }

    if (snapshot.isPresent()) {
        return snapshot.get().getChild(child).transform(READ_DATA);
    }

    return Optional.absent();
}

From source file:ezbake.deployer.configuration.EzDeployerConfiguration.java

/**
 * Get a configuration value as an int.//from   www. ja v a 2 s.  c  om
 * If key did not specify a default value, and its not required, will return 0 if does not exist.
 */
private int getInt(Key key) {
    Optional<String> val = get(key);
    return val.transform(new Function<String, Integer>() {
        @Override
        public Integer apply(String input) {
            return Integer.parseInt(input);
        }
    }).or(0); // or 0 is if no default was defined, but the value was null and not required.
}

From source file:ezbake.deployer.configuration.EzDeployerConfiguration.java

/**
 * Get a configuration value as a long.//from  w w w  . j  a  v  a 2  s.c o  m
 * If key did not specify a default value, and its not required, will return 0 if does not exist.
 */
private long getLong(Key key) {
    Optional<String> val = get(key);
    return val.transform(new Function<String, Long>() {
        @Override
        public Long apply(String input) {
            return Long.parseLong(input);
        }
    }).or(0L); // or 0 is if no default was defined, but the value was null and not required.
}

From source file:ezbake.deployer.configuration.EzDeployerConfiguration.java

/**
 * Get a configuration value as a boolean.
 * If key did not specify a default value, and its not required, will return false if does not exist.
 *//*from  w w w . jav a2s .  c o  m*/
private boolean getBoolean(Key key) {
    Optional<String> val = get(key);
    return val.transform(new Function<String, Boolean>() {
        @Override
        public Boolean apply(String input) {
            return Boolean.parseBoolean(input);
        }
    }).or(false); // or false is if no default was defined, but the value was null and not required.
}

From source file:springfox.documentation.schema.property.ModelPropertiesKeyGenerator.java

@Override
public Object generate(Object target, Method method, Object... params) {
    Optional<ResolvedType> type = FluentIterable.from(newArrayList(params)).filter(ResolvedType.class).first();
    Optional<ModelContext> context = FluentIterable.from(newArrayList(params)).filter(ModelContext.class)
            .first();// w  ww. j a  v  a2s .  co  m
    if (!type.isPresent()) {
        throw new IllegalArgumentException(
                "Key generator can only be used where atleast one parameter is of type " + "ResolvedType");
    }
    StringBuilder sb = new StringBuilder();
    sb.append(type.get().toString());
    sb.append(context.transform(returnTypeComponent()).or(""));
    LOG.info("Cache key generated: {}", sb.toString());
    return sb.toString();
}