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

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

Introduction

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

Prototype

@Nullable
public abstract T orNull();

Source Link

Document

Returns the contained instance if it is present; null otherwise.

Usage

From source file:org.multibit.hd.core.store.ContactsProtobufSerializer.java

/**
 * <p>Loads contacts data from the given protocol buffer and inserts it into the given Set of Contact object.
 *
 * <p>A contact db can be unreadable for various reasons, such as inability to present the file, corrupt data, internally
 * inconsistent data, a wallet extension marked as mandatory that cannot be handled and so on. You should always
 * handle {@link ContactsLoadException} and communicate failure to the user in an appropriate manner.</p>
 *
 * @throws ContactsLoadException thrown in various error conditions (see description).
 *//*from   www  . j  a v  a  2 s .co m*/
private void readContacts(MBHDContactsProtos.Contacts contactsProto, Set<Contact> contacts)
        throws ContactsLoadException {
    Set<Contact> readContacts = Sets.newHashSet();

    List<MBHDContactsProtos.Contact> contactProtos = contactsProto.getContactList();

    if (contactProtos != null) {
        for (MBHDContactsProtos.Contact contactProto : contactProtos) {
            String idAsString = contactProto.getId();
            UUID id = UUID.fromString(idAsString);

            String name = contactProto.getName();

            Contact contact = new Contact(id, name);

            contact.setEmail(contactProto.getEmail());
            Optional<Address> address = Addresses.parse(contactProto.getBitcoinAddress());
            contact.setBitcoinAddress(address.orNull());
            contact.setImagePath(contactProto.getImagePath());
            contact.setExtendedPublicKey(contactProto.getExtendedPublicKey());
            contact.setNotes(contactProto.getNotes());

            // Create tags
            List<String> tags = Lists.newArrayList();
            List<MBHDContactsProtos.Tag> tagProtos = contactProto.getTagList();
            if (tagProtos != null) {
                for (MBHDContactsProtos.Tag tagProto : tagProtos) {
                    tags.add(tagProto.getTagValue());
                }
            }
            contact.setTags(tags);
            readContacts.add(contact);
        }
    }

    // Everything read ok - put the new contacts into the passed in contacts object
    contacts.clear();
    contacts.addAll(readContacts);
}

From source file:org.nmdp.service.epitope.guice.CachingFunction.java

/**
 * notify listeners about a cache refresh
 * @param future the future of the async cache refresh
 * @param key the key of the refresh/*from  w w w .  j  a  va  2  s.  c  om*/
 * @param oldValue the old value
 */
private void notifyListeners(final ListenableFuture<Optional<V>> future, final K key,
        final Optional<V> oldValue) {
    for (final CachingFunctionListener<K, V> listener : listenerList) {
        future.addListener(() -> {
            try {
                listener.reloaded(key, oldValue.orNull(), future.get().orNull());
            } catch (Exception e) {
                throw new RuntimeException("caught exception while notifying listener (key: " + key
                        + ", oldValue: " + oldValue + ")");
            }
        }, MoreExecutors.directExecutor());
    }
}

From source file:org.locationtech.geogig.osm.cli.commands.OSMExport.java

private Iterator<EntityContainer> getFeatures(String ref) {
    Optional<ObjectId> id = geogig.command(RevParse.class).setRefSpec(ref).call();
    if (!id.isPresent()) {
        return Iterators.emptyIterator();
    }/*w w  w . ja v  a  2 s . c  o m*/
    LsTreeOp op = geogig.command(LsTreeOp.class).setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES)
            .setReference(ref);
    if (bbox != null) {
        final Envelope env;
        try {
            env = new Envelope(Double.parseDouble(bbox.get(0)), Double.parseDouble(bbox.get(2)),
                    Double.parseDouble(bbox.get(1)), Double.parseDouble(bbox.get(3)));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Wrong bbox definition");
        }
        Predicate<Bounded> filter = new Predicate<Bounded>() {
            @Override
            public boolean apply(final Bounded bounded) {
                boolean intersects = bounded.intersects(env);
                return intersects;
            }
        };
        op.setBoundsFilter(filter);
    }
    Iterator<NodeRef> iterator = op.call();
    final EntityConverter converter = new EntityConverter();
    Function<NodeRef, EntityContainer> function = new Function<NodeRef, EntityContainer>() {

        @Override
        @Nullable
        public EntityContainer apply(@Nullable NodeRef ref) {
            RevFeature revFeature = geogig.command(RevObjectParse.class).setObjectId(ref.objectId())
                    .call(RevFeature.class).get();
            SimpleFeatureType featureType;
            if (ref.path().startsWith(OSMUtils.NODE_TYPE_NAME)) {
                featureType = OSMUtils.nodeType();
            } else {
                featureType = OSMUtils.wayType();
            }
            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
            RevFeatureType revFeatureType = RevFeatureTypeImpl.build(featureType);
            List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors();
            ImmutableList<Optional<Object>> values = revFeature.getValues();
            for (int i = 0; i < descriptors.size(); i++) {
                PropertyDescriptor descriptor = descriptors.get(i);
                Optional<Object> value = values.get(i);
                featureBuilder.set(descriptor.getName(), value.orNull());
            }
            SimpleFeature feature = featureBuilder.buildFeature(ref.name());
            Entity entity = converter.toEntity(feature, null);
            EntityContainer container;
            if (entity instanceof Node) {
                container = new NodeContainer((Node) entity);
            } else {
                container = new WayContainer((Way) entity);
            }

            return container;

        }

    };
    return Iterators.transform(iterator, function);
}

From source file:domainapp.dom.menu.Menu.java

@Programmatic
public MenuItem findItem(final String menuItemName) {
    final Optional<MenuItem> menuItemIfAny = Iterables.tryFind(getItems(),
            menuItem -> Objects.equal(menuItem.getName(), menuItemName));
    return menuItemIfAny.orNull();
}

From source file:org.geogit.osm.out.cli.OSMExport.java

private Iterator<EntityContainer> getFeatures(String ref) {
    Optional<ObjectId> id = geogit.command(RevParse.class).setRefSpec(ref).call();
    if (!id.isPresent()) {
        return Iterators.emptyIterator();
    }/*from  w  w  w  .j a  va 2  s.  c  om*/
    LsTreeOp op = geogit.command(LsTreeOp.class).setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES)
            .setReference(ref);
    if (bbox != null) {
        final Envelope env;
        try {
            env = new Envelope(Double.parseDouble(bbox.get(0)), Double.parseDouble(bbox.get(2)),
                    Double.parseDouble(bbox.get(1)), Double.parseDouble(bbox.get(3)));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Wrong bbox definition");
        }
        Predicate<Bounded> filter = new Predicate<Bounded>() {
            @Override
            public boolean apply(final Bounded bounded) {
                boolean intersects = bounded.intersects(env);
                return intersects;
            }
        };
        op.setBoundsFilter(filter);
    }
    Iterator<NodeRef> iterator = op.call();
    final EntityConverter converter = new EntityConverter();
    Function<NodeRef, EntityContainer> function = new Function<NodeRef, EntityContainer>() {

        @Override
        @Nullable
        public EntityContainer apply(@Nullable NodeRef ref) {
            RevFeature revFeature = geogit.command(RevObjectParse.class).setObjectId(ref.objectId())
                    .call(RevFeature.class).get();
            SimpleFeatureType featureType;
            if (ref.path().startsWith(OSMUtils.NODE_TYPE_NAME)) {
                featureType = OSMUtils.nodeType();
            } else {
                featureType = OSMUtils.wayType();
            }
            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
            RevFeatureType revFeatureType = RevFeatureType.build(featureType);
            List<PropertyDescriptor> descriptors = revFeatureType.sortedDescriptors();
            ImmutableList<Optional<Object>> values = revFeature.getValues();
            for (int i = 0; i < descriptors.size(); i++) {
                PropertyDescriptor descriptor = descriptors.get(i);
                Optional<Object> value = values.get(i);
                featureBuilder.set(descriptor.getName(), value.orNull());
            }
            SimpleFeature feature = featureBuilder.buildFeature(ref.name());
            Entity entity = converter.toEntity(feature);
            EntityContainer container;
            if (entity instanceof Node) {
                container = new NodeContainer((Node) entity);
            } else {
                container = new WayContainer((Way) entity);
            }

            return container;

        }

    };
    return Iterators.transform(iterator, function);
}

From source file:im.dadoo.teak.web.controller.MediaController.java

@RequestMapping(value = "/api/upload/media", method = RequestMethod.POST)
@ResponseBody/* w  w w.  j  av  a2 s .c o  m*/
public String uploadImage(@RequestParam Integer CKEditorFuncNum, @RequestParam MultipartFile upload)
        throws IllegalStateException, IOException {
    Optional<String> path = this.fileService.save(upload);
    String result = "";
    if (path.isPresent()) {
        result = String.format(CKEDITOR_CALLBACK, CKEditorFuncNum, path.get(), "?");
    } else {
        result = String.format(CKEDITOR_CALLBACK, CKEditorFuncNum, path.orNull(), "");
    }
    return result;
}

From source file:org.onos.yangtools.yang.parser.stmt.rfc6020.ModuleStatementSupport.java

@Override
public void onLinkageDeclared(
        Mutable<String, ModuleStatement, EffectiveStatement<String, ModuleStatement>> stmt)
        throws SourceException {

    Optional<URI> moduleNs = Optional
            .fromNullable(firstAttributeOf(stmt.declaredSubstatements(), NamespaceStatement.class));
    if (!moduleNs.isPresent()) {
        throw new IllegalArgumentException(
                "Namespace of the module [" + stmt.getStatementArgument() + "] is missing.");
    }//  w  w  w  .  j av  a  2s.  c  o m

    // FIXME: this is wrong, it has to select the newest revision statement, not the first it encounters.
    //         YANG files are not required to order revisions
    Optional<Date> revisionDate = Optional
            .fromNullable(firstAttributeOf(stmt.declaredSubstatements(), RevisionStatement.class));

    qNameModule = QNameModule.cachedReference(QNameModule.create(moduleNs.get(), revisionDate.orNull()));
    ModuleIdentifier moduleIdentifier = new ModuleIdentifierImpl(stmt.getStatementArgument(),
            Optional.<URI>absent(), revisionDate);

    stmt.addContext(ModuleNamespace.class, moduleIdentifier, stmt);
    stmt.addContext(NamespaceToModule.class, qNameModule, stmt);

    String modulePrefix = firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class);
    if (modulePrefix == null) {
        throw new IllegalArgumentException(
                "Prefix of the module [" + stmt.getStatementArgument() + "] is missing.");
    }

    stmt.addToNs(PrefixToModule.class, modulePrefix, qNameModule);
    stmt.addToNs(ModuleNameToModuleQName.class, stmt.getStatementArgument(), qNameModule);
    stmt.addToNs(ModuleQNameToModuleName.class, qNameModule, stmt.getStatementArgument());
    stmt.addToNs(ModuleIdentifierToModuleQName.class, moduleIdentifier, qNameModule);

    stmt.addToNs(ImpPrefixToModuleIdentifier.class, modulePrefix, moduleIdentifier);
}

From source file:org.onos.yangtools.yang.model.util.PatternConstraintImpl.java

public PatternConstraintImpl(final String regex, final Optional<String> description,
        final Optional<String> reference) {
    super();//from  w  w  w  .j  a  v a 2  s .co  m
    this.regex = Preconditions.checkNotNull(regex, "regex must not be null.");
    this.description = description.orNull();
    this.reference = reference.orNull();

    // FIXME: Lookup better suitable error tag.
    errorAppTag = "invalid-regular-expression";
    // TODO: add erro message
    errorMessage = "";
}

From source file:org.opendaylight.ovsdb.southbound.ovsdb.transact.AutoAttachRemovedCommand.java

private OvsdbBridgeAugmentation getBridge(InstanceIdentifier<OvsdbNodeAugmentation> key, Uuid aaUuid) {
    if (aaUuid == null) {
        return null;
    }/*  w ww.j  a v a2s . co  m*/
    OvsdbBridgeAugmentation bridge = null;
    final InstanceIdentifier<Node> nodeIid = key.firstIdentifierOf(Node.class);
    try (ReadOnlyTransaction transaction = SouthboundProvider.getDb().newReadOnlyTransaction()) {
        final Optional<Node> nodeOptional = transaction.read(LogicalDatastoreType.OPERATIONAL, nodeIid).get();
        if (nodeOptional.isPresent()) {
            final List<ManagedNodeEntry> managedNodes = nodeOptional.get()
                    .getAugmentation(OvsdbNodeAugmentation.class).getManagedNodeEntry();
            for (final ManagedNodeEntry managedNode : managedNodes) {
                final OvsdbBridgeRef ovsdbBridgeRef = managedNode.getBridgeRef();
                final InstanceIdentifier<OvsdbBridgeAugmentation> brIid = ovsdbBridgeRef.getValue()
                        .firstIdentifierOf(Node.class).augmentation(OvsdbBridgeAugmentation.class);
                final Optional<OvsdbBridgeAugmentation> optionalBridge = transaction
                        .read(LogicalDatastoreType.OPERATIONAL, brIid).get();
                bridge = optionalBridge.orNull();
                if (bridge != null && bridge.getAutoAttach() != null && bridge.getAutoAttach().equals(aaUuid)) {
                    return bridge;
                }
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        LOG.warn("Error reading from datastore", e);
    }
    return null;
}

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

@Override
public final EppResponse run() throws EppException {
    extensionManager.register(MetadataExtension.class);
    extensionManager.validate();/*from w w  w.  j  ava  2 s .com*/
    validateClientIsLoggedIn(clientId);
    Create command = (Create) resourceCommand;
    DateTime now = ofy().getTransactionTime();
    verifyResourceDoesNotExist(HostResource.class, targetId, now);
    // The superordinate domain of the host object if creating an in-bailiwick host, or null if
    // creating an external host. This is looked up before we actually create the Host object so
    // we can detect error conditions earlier.
    Optional<DomainResource> superordinateDomain = Optional
            .fromNullable(lookupSuperordinateDomain(validateHostName(targetId), now));
    verifyDomainIsSameRegistrar(superordinateDomain.orNull(), clientId);
    boolean willBeSubordinate = superordinateDomain.isPresent();
    boolean hasIpAddresses = !isNullOrEmpty(command.getInetAddresses());
    if (willBeSubordinate != hasIpAddresses) {
        // Subordinate hosts must have ip addresses and external hosts must not have them.
        throw willBeSubordinate ? new SubordinateHostMustHaveIpException()
                : new UnexpectedExternalHostIpException();
    }
    HostResource newHost = new Builder().setCreationClientId(clientId).setCurrentSponsorClientId(clientId)
            .setFullyQualifiedHostName(targetId).setInetAddresses(command.getInetAddresses())
            .setRepoId(createRepoId(ObjectifyService.allocateId(), roidSuffix)).setSuperordinateDomain(
                    superordinateDomain.isPresent() ? Key.create(superordinateDomain.get()) : null)
            .build();
    historyBuilder.setType(HistoryEntry.Type.HOST_CREATE).setModificationTime(now)
            .setParent(Key.create(newHost));
    ImmutableSet<ImmutableObject> entitiesToSave = ImmutableSet.of(newHost, historyBuilder.build(),
            ForeignKeyIndex.create(newHost, newHost.getDeletionTime()),
            EppResourceIndex.create(Key.create(newHost)));
    if (superordinateDomain.isPresent()) {
        entitiesToSave = union(entitiesToSave, superordinateDomain.get().asBuilder()
                .addSubordinateHost(command.getFullyQualifiedHostName()).build());
        // Only update DNS if this is a subordinate host. External hosts have no glue to write, so
        // they are only written as NS records from the referencing domain.
        dnsQueue.addHostRefreshTask(targetId);
    }
    ofy().save().entities(entitiesToSave);
    return responseBuilder.setResData(HostCreateData.create(targetId, now)).build();
}