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.auraframework.util.ServiceLocator.java

@Override
@SuppressWarnings("unchecked")
public <T extends AuraServiceProvider> T get(Class<T> type) {
    try {//w  w  w  .jav  a  2s  . c o m
        Optional<Object> o = instanceCache.get(type);
        if (o == null) {
            o = loadInstance(type);
            instanceCache.putIfAbsent(type, o);
        }
        return (T) o.orNull();
    } catch (Exception e) {
        throw new ServiceLocatorException(e);
    }
}

From source file:org.locationtech.geogig.porcelain.ApplyPatchOp.java

private void applyPatch(Patch patch) {
    final WorkingTree workTree = workingTree();
    final ObjectStore indexDb = objectDatabase();
    if (reverse) {
        patch = patch.reversed();//from w w  w.  j  av a  2  s .  c  om
    }

    objectDatabase().putAll(patch.getFeatureTypes().iterator());

    List<FeatureInfo> removed = patch.getRemovedFeatures();
    for (FeatureInfo feature : removed) {
        workTree.delete(feature.getPath());
    }
    List<FeatureInfo> added = patch.getAddedFeatures();
    for (FeatureInfo feature : added) {
        workTree.insert(feature);
    }
    List<FeatureDiff> diffs = patch.getModifiedFeatures();
    for (FeatureDiff diff : diffs) {
        String path = diff.getPath();
        DepthSearch depthSearch = new DepthSearch(indexDb);
        Optional<NodeRef> noderef = depthSearch.find(workTree.getTree(), path);
        RevFeatureType oldRevFeatureType = command(RevObjectParse.class)
                .setObjectId(noderef.get().getMetadataId()).call(RevFeatureType.class).get();
        String refSpec = Ref.WORK_HEAD + ":" + path;
        RevFeature feature = command(RevObjectParse.class).setRefSpec(refSpec).call(RevFeature.class).get();

        RevFeatureType newRevFeatureType = getFeatureType(diff, feature, oldRevFeatureType);
        ImmutableList<PropertyDescriptor> oldDescriptors = oldRevFeatureType.descriptors();
        ImmutableList<PropertyDescriptor> newDescriptors = newRevFeatureType.descriptors();
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
                (SimpleFeatureType) newRevFeatureType.type());
        Map<Name, Object> attrs = Maps.newHashMap();
        for (int i = 0; i < oldDescriptors.size(); i++) {
            PropertyDescriptor descriptor = oldDescriptors.get(i);
            if (newDescriptors.contains(descriptor)) {
                Optional<Object> value = feature.get(i);
                attrs.put(descriptor.getName(), value.orNull());
            }
        }
        Set<Entry<PropertyDescriptor, AttributeDiff>> featureDiffs = diff.getDiffs().entrySet();
        for (Iterator<Entry<PropertyDescriptor, AttributeDiff>> iterator = featureDiffs.iterator(); iterator
                .hasNext();) {
            Entry<PropertyDescriptor, AttributeDiff> entry = iterator.next();
            if (!entry.getValue().getType().equals(TYPE.REMOVED)) {
                Object oldValue = attrs.get(entry.getKey().getName());
                attrs.put(entry.getKey().getName(), entry.getValue().applyOn(oldValue));
            }
        }
        Set<Entry<Name, Object>> entries = attrs.entrySet();
        for (Iterator<Entry<Name, Object>> iterator = entries.iterator(); iterator.hasNext();) {
            Entry<Name, Object> entry = iterator.next();
            featureBuilder.set(entry.getKey(), entry.getValue());

        }

        SimpleFeature f = featureBuilder.buildFeature(NodeRef.nodeFromPath(path));
        RevFeature featureToInsert = RevFeatureBuilder.build(f);
        FeatureInfo featureInfo = FeatureInfo.insert(featureToInsert, newRevFeatureType.getId(), path);
        workTree.insert(featureInfo);

    }
    ImmutableList<FeatureTypeDiff> alteredTrees = patch.getAlteredTrees();
    for (FeatureTypeDiff diff : alteredTrees) {
        Optional<RevFeatureType> featureType;
        if (diff.getOldFeatureType().isNull()) {
            featureType = patch.getFeatureTypeFromId(diff.getNewFeatureType());
            workTree.createTypeTree(diff.getPath(), featureType.get().type());
        } else if (diff.getNewFeatureType().isNull()) {
            workTree.delete(diff.getPath());
        } else {
            featureType = patch.getFeatureTypeFromId(diff.getNewFeatureType());
            workTree.updateTypeTree(diff.getPath(), featureType.get().type());
        }
    }

}

From source file:com.arpnetworking.tsdcore.statistics.MeanStatistic.java

/**
 * {@inheritDoc}/*from  w  w w.ja v  a  2s.  co m*/
 */
@Override
public Quantity calculate(final List<Quantity> orderedValues) {
    // TODO(vkoskela): Statistic calculation should be allowed to either fail or not return a quantity. [MAI-?]
    if (orderedValues.size() == 0) {
        return ZERO;
    }
    double sum = 0;
    Optional<Unit> unit = Optional.absent();
    for (final Quantity sample : orderedValues) {
        sum += sample.getValue();
        unit = unit.or(sample.getUnit());
    }
    return new Quantity.Builder().setValue(sum / orderedValues.size()).setUnit(unit.orNull()).build();
}

From source file:com.streamsets.pipeline.stage.lib.hive.HMSCache.java

/**
 * Returns if the {@link HMSCache} has the corresponding {@link HMSCacheSupport.HMSCacheInfo}
 * and qualified table name.<br>/*from w w  w  .j  ava  2 s .  c om*/
 * If it is not there load it using corresponding {@link HMSCacheSupport.HMSCacheLoader}
 * @param <T> {@link HMSCacheSupport.HMSCacheInfo}
 * @param hmsCacheType {@link HMSCacheType}
 * @param jdbcUrl JDBC Url.
 * @param qualifiedTableName qualified table name
 * @param auxiliaryInfo Any auxiliary Info for {@link HMSCacheSupport.HMSCacheLoader}
 * @return Corresponding {@link HMSCacheSupport.HMSCacheInfo} for the qualified table name.
 * @throws StageException if the {@link HMSCacheType} is not supported by {@link HMSCache}
 */
@SuppressWarnings("unchecked")
public <T extends HMSCacheSupport.HMSCacheInfo> T getOrLoad(HMSCacheType hmsCacheType, String jdbcUrl,
        String qualifiedTableName, Object... auxiliaryInfo) throws StageException {
    if (!cacheMap.containsKey(hmsCacheType)) {
        throw new StageException(Errors.HIVE_16, hmsCacheType);
    }
    try {
        Optional<HMSCacheSupport.HMSCacheInfo> ret = cacheMap.get(hmsCacheType).get(qualifiedTableName,
                hmsCacheType.getSupport().newHMSCacheLoader(jdbcUrl, qualifiedTableName, auxiliaryInfo));
        return ret == null ? null : (T) ret.orNull();
    } catch (ExecutionException e) {
        throw new StageException(Errors.HIVE_01, e);
    }
}

From source file:org.basepom.mojo.propertyhelper.AbstractPropertyHelperMojo.java

protected void loadPropertyElements() throws Exception {
    final ImmutableList.Builder<PropertyElement> propertyElements = ImmutableList.builder();

    numberFields = NumberField.createNumbers(valueCache, numbers);
    propertyElements.addAll(numberFields);
    propertyElements.addAll(StringField.createStrings(valueCache, strings));
    propertyElements.addAll(DateField.createDates(valueCache, dates));
    propertyElements.addAll(MacroField.createMacros(valueCache, macros, this));
    propertyElements.addAll(UuidField.createUuids(valueCache, uuids));

    for (final PropertyElement pe : propertyElements.build()) {
        final Optional<String> value = pe.getPropertyValue();
        values.put(pe.getPropertyName(), value.orNull());

        if (pe.isExport()) {
            final String result = value.or("");
            project.getProperties().setProperty(pe.getPropertyName(), result);
            LOG.debug("Exporting Property name: %s, value: %s", pe.getPropertyName(), result);
        } else {//from  w  w  w.j  a va  2s. c  o m
            LOG.debug("Property name: %s, value: %s", pe.getPropertyName(), value.or("<null>"));
        }
    }

    // Now generate the property groups.
    final ImmutableMap.Builder<String, Map.Entry<PropertyGroup, List<PropertyElement>>> builder = ImmutableMap
            .builder();

    final Set<String> propertyNames = Sets.newHashSet();

    if (propertyGroups != null) {
        for (final PropertyGroup propertyGroup : propertyGroups) {
            final List<PropertyElement> propertyFields = PropertyField.createProperties(project.getModel(),
                    values, propertyGroup);
            builder.put(propertyGroup.getId(),
                    new AbstractMap.SimpleImmutableEntry<>(propertyGroup, propertyFields));
        }
    }

    final Map<String, Map.Entry<PropertyGroup, List<PropertyElement>>> propertyPairs = builder.build();

    if (activeGroups != null) {
        for (final String activeGroup : activeGroups) {
            final Map.Entry<PropertyGroup, List<PropertyElement>> propertyElement = propertyPairs
                    .get(activeGroup);
            checkState(propertyElement != null, "activated group '%s' does not exist", activeGroup);

            final PropertyGroup propertyGroup = propertyElement.getKey();
            if ((propertyGroup.isActiveOnRelease() && !isSnapshot)
                    || (propertyGroup.isActiveOnSnapshot() && isSnapshot)) {
                for (final PropertyElement pe : propertyElement.getValue()) {
                    final Optional<String> value = pe.getPropertyValue();
                    final String propertyName = pe.getPropertyName();
                    IgnoreWarnFail.checkState(propertyGroup.getOnDuplicateProperty(),
                            !propertyNames.contains(propertyName), "property name '" + propertyName + "'");
                    propertyNames.add(propertyName);

                    project.getProperties().setProperty(propertyName, value.or(""));
                }
            } else {
                LOG.debug("Skipping property group %s: Snapshot: %b, activeOnSnapshot: %b, activeOnRelease: %b",
                        activeGroup, isSnapshot, propertyGroup.isActiveOnSnapshot(),
                        propertyGroup.isActiveOnRelease());
            }
        }
    }
}

From source file:com.arpnetworking.tsdcore.statistics.SumStatistic.java

/**
 * {@inheritDoc}/*from   w  ww.  j  a va 2 s  .c o  m*/
 */
@Override
public Quantity calculateAggregations(final List<AggregatedData> aggregations) {
    double sum = 0;
    Optional<Unit> unit = Optional.absent();
    for (final AggregatedData aggregation : aggregations) {
        sum += aggregation.getValue().getValue();
        unit = unit.or(aggregation.getValue().getUnit());
    }
    return new Quantity.Builder().setValue(sum).setUnit(unit.orNull()).build();
}

From source file:com.dangdang.ddframe.rdb.sharding.parsing.parser.dialect.oracle.OracleParser.java

@Override
protected boolean isRowNumberCondition(final SelectStatement selectStatement, final String columnLabel) {
    Optional<String> rowNumberAlias = Optional.absent();
    for (SelectItem each : selectStatement.getItems()) {
        if (each.getAlias().isPresent() && "rownum".equalsIgnoreCase(each.getExpression())) {
            rowNumberAlias = each.getAlias();
        }/*from   w  w w  . ja  va  2s  .  c  o m*/
    }
    return "rownum".equalsIgnoreCase(columnLabel) || columnLabel.equalsIgnoreCase(rowNumberAlias.orNull());
}

From source file:org.opendaylight.yangtools.yang.model.util.RangeConstraintImpl.java

RangeConstraintImpl(final Number min, final Number max, final Optional<String> description,
        final Optional<String> reference, final String errorAppTag, final String errorMessage) {
    this.min = Preconditions.checkNotNull(min, "min must not be null.");
    this.max = Preconditions.checkNotNull(max, "max must not be null.");
    this.description = description.orNull();
    this.reference = reference.orNull();
    this.errorAppTag = errorAppTag != null ? errorAppTag : "range-out-of-specified-bounds";
    this.errorMessage = errorMessage != null ? errorMessage
            : "The argument is out of bounds <" + min + ", " + max + ">";
}

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

RangeConstraintImpl(final Number min, final Number max, final Optional<String> description,
        final Optional<String> reference) {
    super();//from   w ww  .j a  v  a  2  s  .  c  om
    this.min = Preconditions.checkNotNull(min, "min must not be null.");
    this.max = Preconditions.checkNotNull(max, "max must not be null.");
    this.description = description.orNull();
    this.reference = reference.orNull();

    this.errorAppTag = "range-out-of-specified-bounds";
    this.errorMessage = "The argument is out of bounds <" + min + ", " + max + ">";
}

From source file:com.google.gerrit.server.auth.ldap.LdapRealm.java

@Override
public Account.Id lookup(String accountName) {
    if (Strings.isNullOrEmpty(accountName)) {
        return null;
    }/*w w w . jav a2s.  c  o  m*/
    try {
        Optional<Account.Id> id = usernameCache.get(accountName);
        return id != null ? id.orNull() : null;
    } catch (ExecutionException e) {
        log.warn(String.format("Cannot lookup account %s in LDAP", accountName), e);
        return null;
    }
}