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

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

Introduction

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

Prototype

@Override
public abstract boolean equals(@Nullable Object object);

Source Link

Document

Returns true if object is an Optional instance, and either the contained references are Object#equals equal to each other or both are absent.

Usage

From source file:org.locationtech.geogig.plumbing.merge.ReportCommitConflictsOp.java

@Override
protected MergeScenarioReport _call() {

    Preconditions.checkArgument(consumer != null, "No consumer provided.");

    MergeScenarioReport report = new MergeScenarioReport();

    ObjectId parentCommitId = ObjectId.NULL;
    if (commit.getParentIds().size() > 0) {
        parentCommitId = commit.getParentIds().get(0);
    }/*from  ww w  .j a  v  a 2 s  .  c om*/
    ObjectId parentTreeId = ObjectId.NULL;
    Repository repository = repository();
    if (repository.commitExists(parentCommitId)) {
        parentTreeId = repository.getCommit(parentCommitId).getTreeId();
    }
    // get changes
    try (AutoCloseableIterator<DiffEntry> diffs = command(DiffTree.class).setOldTree(parentTreeId)
            .setNewTree(commit.getTreeId()).setReportTrees(true).call()) {
        while (diffs.hasNext()) {
            DiffEntry diff = diffs.next();
            String path = diff.oldPath() == null ? diff.newPath() : diff.oldPath();
            Optional<RevObject> obj = command(RevObjectParse.class).setRefSpec(Ref.HEAD + ":" + path).call();
            switch (diff.changeType()) {
            case ADDED:
                if (obj.isPresent()) {
                    TYPE type = command(ResolveObjectType.class).setObjectId(diff.getNewObject().getObjectId())
                            .call();
                    if (TYPE.TREE.equals(type)) {
                        NodeRef headVersion = command(FindTreeChild.class).setChildPath(path)
                                .setParent(repository.getOrCreateHeadTree()).call().get();
                        if (!headVersion.getMetadataId().equals(diff.getNewObject().getMetadataId())) {
                            consumer.conflicted(new Conflict(path, ObjectId.NULL,
                                    diff.getNewObject().getMetadataId(), headVersion.getMetadataId()));
                            report.addConflict();
                        }
                    } else {
                        if (!obj.get().getId().equals(diff.newObjectId())) {
                            consumer.conflicted(
                                    new Conflict(path, ObjectId.NULL, diff.newObjectId(), obj.get().getId()));
                            report.addConflict();
                        }
                    }
                } else {
                    consumer.unconflicted(diff);
                    report.addUnconflicted();
                }
                break;
            case REMOVED:
                if (obj.isPresent()) {
                    if (obj.get().getId().equals(diff.oldObjectId())) {
                        consumer.unconflicted(diff);
                        report.addUnconflicted();
                    } else {
                        consumer.conflicted(
                                new Conflict(path, diff.oldObjectId(), ObjectId.NULL, obj.get().getId()));
                        report.addConflict();
                    }
                }
                break;
            case MODIFIED:
                TYPE type = command(ResolveObjectType.class).setObjectId(diff.getNewObject().getObjectId())
                        .call();
                if (TYPE.TREE.equals(type)) {
                    // TODO:see how to do this. For now, we will pass any change as a conflicted
                    // one
                    if (!diff.isChange()) {
                        consumer.unconflicted(diff);
                        report.addUnconflicted();
                    }
                } else {
                    String refSpec = Ref.HEAD + ":" + path;
                    obj = command(RevObjectParse.class).setRefSpec(refSpec).call();
                    if (!obj.isPresent()) {
                        // git reports this as a conflict but does not mark as conflicted, just
                        // adds
                        // the missing file.
                        // We add it and consider it unconflicted
                        consumer.unconflicted(diff);
                        report.addUnconflicted();
                        break;
                    }
                    RevFeature feature = (RevFeature) obj.get();
                    DepthSearch depthSearch = new DepthSearch(repository.objectDatabase());
                    Optional<NodeRef> noderef = depthSearch.find(this.workingTree().getTree(), path);
                    RevFeatureType featureType = command(RevObjectParse.class)
                            .setObjectId(noderef.get().getMetadataId()).call(RevFeatureType.class).get();
                    ImmutableList<PropertyDescriptor> descriptors = featureType.descriptors();
                    FeatureDiff featureDiff = command(DiffFeature.class)
                            .setOldVersion(Suppliers.ofInstance(diff.getOldObject()))
                            .setNewVersion(Suppliers.ofInstance(diff.getNewObject())).call();
                    Set<Entry<PropertyDescriptor, AttributeDiff>> attrDiffs = featureDiff.getDiffs().entrySet();
                    RevFeature newFeature = command(RevObjectParse.class).setObjectId(diff.newObjectId())
                            .call(RevFeature.class).get();
                    boolean ok = true;
                    for (Iterator<Entry<PropertyDescriptor, AttributeDiff>> iterator = attrDiffs
                            .iterator(); iterator.hasNext() && ok;) {
                        Entry<PropertyDescriptor, AttributeDiff> entry = iterator.next();
                        AttributeDiff attrDiff = entry.getValue();
                        PropertyDescriptor descriptor = entry.getKey();
                        switch (attrDiff.getType()) {
                        case ADDED:
                            if (descriptors.contains(descriptor)) {
                                ok = false;
                            }
                            break;
                        case REMOVED:
                        case MODIFIED:
                            if (!descriptors.contains(descriptor)) {
                                ok = false;
                                break;
                            }
                            for (int i = 0; i < descriptors.size(); i++) {
                                if (descriptors.get(i).equals(descriptor)) {
                                    Optional<Object> value = feature.get(i);
                                    Optional<Object> newValue = newFeature.get(i);
                                    if (!newValue.equals(value)) { // if it's going to end up
                                                                   // setting the same value, it
                                                                   // is
                                                                   // compatible, so no need to
                                                                   // check
                                        if (!attrDiff.canBeAppliedOn(value.orNull())) {
                                            ok = false;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (ok) {
                        consumer.unconflicted(diff);
                        report.addUnconflicted();
                    } else {
                        consumer.conflicted(
                                new Conflict(path, diff.oldObjectId(), diff.newObjectId(), obj.get().getId()));
                        report.addConflict();
                    }
                }

                break;
            }

        }
    }
    consumer.finished();

    return report;

}

From source file:org.geogit.api.plumbing.diff.FeatureDiff.java

/**
 * /*from  w ww. ja  v a2  s . c  o  m*/
 * @param path the full path to the feature, including its name
 * @param newRevFeature the new version of the feature
 * @param oldRevFeature the old version of the feature
 * @param newRevFeatureType the new version of the feature type
 * @param oldRevFeatureType the old version of the feature type
 * @param all - true if all attributes should be added regardless of change
 */
public FeatureDiff(String path, RevFeature newRevFeature, RevFeature oldRevFeature,
        RevFeatureType newRevFeatureType, RevFeatureType oldRevFeatureType, boolean all) {

    this.path = path;
    this.newFeatureType = newRevFeatureType;
    this.oldFeatureType = oldRevFeatureType;
    diffs = new HashMap<PropertyDescriptor, AttributeDiff>();

    ImmutableList<PropertyDescriptor> oldAttributes = oldRevFeatureType.sortedDescriptors();
    ImmutableList<PropertyDescriptor> newAttributes = newRevFeatureType.sortedDescriptors();
    ImmutableList<Optional<Object>> oldValues = oldRevFeature.getValues();
    ImmutableList<Optional<Object>> newValues = newRevFeature.getValues();
    BitSet updatedAttributes = new BitSet(newValues.size());
    for (int i = 0; i < oldAttributes.size(); i++) {
        Optional<Object> oldValue = oldValues.get(i);
        int idx = newAttributes.indexOf(oldAttributes.get(i));
        if (idx != -1) {
            Optional<Object> newValue = newValues.get(idx);
            if (!oldValue.equals(newValue) || all) {
                if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) {
                    diffs.put(oldAttributes.get(i),
                            new GeometryAttributeDiff(Optional.fromNullable((Geometry) oldValue.orNull()),
                                    Optional.fromNullable((Geometry) newValue.orNull())));
                } else {
                    diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue, newValue));
                }
            }
            updatedAttributes.set(idx);
        } else {
            if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) {
                diffs.put(oldAttributes.get(i),
                        new GeometryAttributeDiff(Optional.fromNullable((Geometry) oldValue.orNull()),
                                Optional.fromNullable((Geometry) null)));
            } else {
                diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue, null));
            }
        }
    }
    updatedAttributes.flip(0, newValues.size());
    for (int i = updatedAttributes.nextSetBit(0); i >= 0; i = updatedAttributes.nextSetBit(i + 1)) {
        if (Geometry.class.isAssignableFrom(newAttributes.get(i).getType().getBinding())) {
            diffs.put(oldAttributes.get(i), new GeometryAttributeDiff(Optional.fromNullable((Geometry) null),
                    Optional.fromNullable((Geometry) newValues.get(i).orNull())));
        } else {
            diffs.put(newAttributes.get(i), new GenericAttributeDiffImpl(null, newValues.get(i)));
        }
    }

}

From source file:org.locationtech.geogig.api.plumbing.diff.FeatureDiff.java

/**
 * /*from  w w  w .j a  v  a 2s  .co m*/
 * @param path the full path to the feature, including its name
 * @param newRevFeature the new version of the feature
 * @param oldRevFeature the old version of the feature
 * @param newRevFeatureType the new version of the feature type
 * @param oldRevFeatureType the old version of the feature type
 * @param all - true if all attributes should be added regardless of change
 */
public FeatureDiff(String path, RevFeature newRevFeature, RevFeature oldRevFeature,
        RevFeatureType newRevFeatureType, RevFeatureType oldRevFeatureType, boolean all) {

    this.path = path;
    this.newFeatureType = newRevFeatureType;
    this.oldFeatureType = oldRevFeatureType;
    diffs = new HashMap<PropertyDescriptor, AttributeDiff>();

    ImmutableList<PropertyDescriptor> oldAttributes = oldRevFeatureType.sortedDescriptors();
    ImmutableList<PropertyDescriptor> newAttributes = newRevFeatureType.sortedDescriptors();
    ImmutableList<Optional<Object>> oldValues = oldRevFeature.getValues();
    ImmutableList<Optional<Object>> newValues = newRevFeature.getValues();
    BitSet updatedAttributes = new BitSet(newValues.size());
    for (int i = 0; i < oldAttributes.size(); i++) {
        Optional<Object> oldValue = oldValues.get(i);
        int idx = newAttributes.indexOf(oldAttributes.get(i));
        if (idx != -1) {
            Optional<Object> newValue = newValues.get(idx);
            if (!oldValue.equals(newValue) || all) {
                if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) {
                    diffs.put(oldAttributes.get(i),
                            new GeometryAttributeDiff(Optional.fromNullable((Geometry) oldValue.orNull()),
                                    Optional.fromNullable((Geometry) newValue.orNull())));
                } else {
                    diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue, newValue));
                }
            }
            updatedAttributes.set(idx);
        } else {
            if (Geometry.class.isAssignableFrom(oldAttributes.get(i).getType().getBinding())) {
                diffs.put(oldAttributes.get(i),
                        new GeometryAttributeDiff(Optional.fromNullable((Geometry) oldValue.orNull()),
                                Optional.fromNullable((Geometry) null)));
            } else {
                diffs.put(oldAttributes.get(i), new GenericAttributeDiffImpl(oldValue, null));
            }
        }
    }
    updatedAttributes.flip(0, newValues.size());
    for (int i = updatedAttributes.nextSetBit(0); i >= 0; i = updatedAttributes.nextSetBit(i + 1)) {
        if (Geometry.class.isAssignableFrom(newAttributes.get(i).getType().getBinding())) {
            diffs.put(newAttributes.get(i), new GeometryAttributeDiff(Optional.fromNullable((Geometry) null),
                    Optional.fromNullable((Geometry) newValues.get(i).orNull())));
        } else {
            diffs.put(newAttributes.get(i), new GenericAttributeDiffImpl(null, newValues.get(i)));
        }
    }

}

From source file:gobblin.source.extractor.extract.kafka.KafkaDeserializerExtractor.java

@VisibleForTesting
KafkaDeserializerExtractor(WorkUnitState state, Optional<Deserializers> deserializerType,
        Deserializer<?> kafkaDeserializer, KafkaSchemaRegistry<?, ?> kafkaSchemaRegistry) {
    super(state);
    this.kafkaDeserializer = kafkaDeserializer;
    this.kafkaSchemaRegistry = kafkaSchemaRegistry;
    this.latestSchema = (deserializerType.equals(Optional.of(Deserializers.CONFLUENT_AVRO)))
            ? (Schema) getSchema()
            : null;//from   w w  w.  ja va  2 s.  c o  m
}

From source file:org.geogit.gwc.TruncateTilesOnUpdateRefHook.java

@SuppressWarnings("unchecked")
@Override/*  ww w.j  a va  2s  .  c  om*/
public <T> T post(AbstractGeoGitOp<T> command, Object retVal, boolean success) throws Exception {
    checkArgument(command instanceof UpdateRef);
    final UpdateRef cmd = (UpdateRef) command;
    final String refName = (String) cmd.getClientData().get("name");
    checkState(refName != null, "refName not captured in pre-hook");
    if (Boolean.TRUE.equals(cmd.getClientData().get("ignore"))) {
        LOGGER.debug("GWC geogit truncate post-hook returning, ref '{}' is ignored.", refName);
        return (T) retVal;
    }

    if (!success) {
        LOGGER.info("GWC geogit truncate post-hook returning, UpdateRef operation failed on ref '{}'.",
                refName);
        return (T) retVal;
    }

    final GWC mediator = GWC.get();
    if (mediator == null) {
        LOGGER.debug("GWC geogit truncate post-hook returning, GWC mediator not installed?.");
        return (T) retVal;
    }

    final Optional<Ref> oldValue = (Optional<Ref>) cmd.getClientData().get("oldValue");
    final Optional<Ref> newValue = (Optional<Ref>) retVal;// == oldValue if the ref was deleted

    checkState(oldValue != null, "oldValue not captured in pre-hook");

    if (oldValue.equals(newValue)) {
        LOGGER.debug("GWC geogit truncate post-hook returning, ref '{}' didn't change ({}).", refName,
                oldValue);
        return (T) retVal;
    }

    List<LayerInfo> affectedLayers;
    final String newRefName = newValue.get().getName();
    Stopwatch sw = Stopwatch.createStarted();
    affectedLayers = findAffectedLayers(mediator, command.context(), newRefName);
    LOGGER.debug("GWC geogit truncate post-hook found {} affected layers on branch {} in {}.",
            affectedLayers.size(), refName, sw.stop());

    for (LayerInfo layer : affectedLayers) {
        truncate(mediator, command.context(), layer, oldValue, newValue);
    }
    return (T) retVal;
}

From source file:org.geogig.geoserver.gwc.TruncateTilesOnUpdateRefHook.java

@SuppressWarnings("unchecked")
@Override//  w ww. j  a  v  a 2 s .com
public <T> T post(AbstractGeoGigOp<T> command, @Nullable Object retVal, @Nullable RuntimeException exception)
        throws Exception {
    checkArgument(command instanceof UpdateRef);
    final UpdateRef cmd = (UpdateRef) command;
    final String refName = (String) cmd.getClientData().get("name");
    checkState(refName != null, "refName not captured in pre-hook");
    if (Boolean.TRUE.equals(cmd.getClientData().get("ignore"))) {
        LOGGER.debug("GWC geogig truncate post-hook returning, ref '{}' is ignored.", refName);
        return (T) retVal;
    }

    boolean success = exception == null;
    if (!success) {
        LOGGER.info("GWC geogig truncate post-hook returning, UpdateRef operation failed on ref '{}'.",
                refName);
        return (T) retVal;
    }

    final GWC mediator = GWC.get();
    if (mediator == null) {
        LOGGER.debug("GWC geogig truncate post-hook returning, GWC mediator not installed?.");
        return (T) retVal;
    }

    final Optional<Ref> oldValue = (Optional<Ref>) cmd.getClientData().get("oldValue");
    final Optional<Ref> newValue = (Optional<Ref>) retVal;// == oldValue if the ref was deleted

    checkState(oldValue != null, "oldValue not captured in pre-hook");

    if (oldValue.equals(newValue)) {
        LOGGER.debug("GWC geogig truncate post-hook returning, ref '{}' didn't change ({}).", refName,
                oldValue);
        return (T) retVal;
    }

    List<LayerInfo> affectedLayers;
    final String newRefName = newValue.get().getName();
    Stopwatch sw = Stopwatch.createStarted();
    affectedLayers = findAffectedLayers(mediator, command.context(), newRefName);
    LOGGER.debug(String.format("GWC geogig truncate post-hook found %s affected layers on branch %s in %s.",
            affectedLayers.size(), refName, sw.stop()));

    for (LayerInfo layer : affectedLayers) {
        truncate(mediator, command.context(), layer, oldValue, newValue);
    }
    return (T) retVal;
}

From source file:org.geogit.api.plumbing.diff.GeometryAttributeDiff.java

public GeometryAttributeDiff(Optional<Geometry> oldGeom, Optional<Geometry> newGeom) {
    Preconditions.checkArgument(oldGeom != null || newGeom != null);
    oldGeometry = oldGeom;/*from w  w w .j  av a 2  s  .co m*/
    newGeometry = newGeom;
    if (newGeom == null || !newGeom.isPresent()) {
        type = TYPE.REMOVED;
    } else if (oldGeom == null || !oldGeom.isPresent()) {
        type = TYPE.ADDED;
    } else if (oldGeom.equals(newGeom)) {
        type = TYPE.NO_CHANGE;
        diff = new LCSGeometryDiffImpl(oldGeom, newGeom);
    } else {
        type = TYPE.MODIFIED;
        diff = new LCSGeometryDiffImpl(oldGeom, newGeom);
    }

}

From source file:com.google.devtools.build.android.PlaceholderIdFieldInitializerBuilder.java

public void addPublicResource(ResourceType type, String name, Optional<Integer> value) {
    SortedMap<String, Optional<Integer>> publicMappings = publicIds.get(type);
    if (publicMappings == null) {
        publicMappings = new TreeMap<>();
        publicIds.put(type, publicMappings);
    }/*w  ww  .jav a 2  s  .  co  m*/
    Optional<Integer> oldValue = publicMappings.put(name, value);
    // AAPT should issue an error, but do a bit of sanity checking here just in case.
    if (oldValue != null && !oldValue.equals(value)) {
        // Enforce a consistent ordering on the warning message.
        Integer lower = oldValue.orNull();
        Integer higher = value.orNull();
        if (Ordering.natural().compare(oldValue.orNull(), value.orNull()) > 0) {
            lower = higher;
            higher = oldValue.orNull();
        }
        logger.warning(String.format("resource %s/%s has conflicting public identifiers (0x%x vs 0x%x)", type,
                name, lower, higher));
    }
}

From source file:com.google.devtools.build.android.AndroidResourceClassWriter.java

public void writePublicValue(ResourceType type, String name, Optional<Integer> value) {
    SortedMap<String, Optional<Integer>> publicMappings = publicIds.get(type);
    if (publicMappings == null) {
        publicMappings = new TreeMap<>();
        publicIds.put(type, publicMappings);
    }//from w  w  w  .  j  a va 2  s .  c om
    Optional<Integer> oldValue = publicMappings.put(name, value);
    // AAPT should issue an error, but do a bit of sanity checking here just in case.
    if (oldValue != null && !oldValue.equals(value)) {
        // Enforce a consistent ordering on the warning message.
        Integer lower = oldValue.orNull();
        Integer higher = value.orNull();
        if (Ordering.natural().compare(oldValue.orNull(), value.orNull()) > 0) {
            lower = higher;
            higher = oldValue.orNull();
        }
        logger.warning(String.format("resource %s/%s has conflicting public identifiers (0x%x vs 0x%x)", type,
                name, lower, higher));
    }
}

From source file:com.twitter.aurora.scheduler.state.LockManagerImpl.java

@Override
public synchronized void validateIfLocked(final ILockKey context, Optional<ILock> heldLock)
        throws LockException {

    Optional<ILock> stored = storage.consistentRead(new Work.Quiet<Optional<ILock>>() {
        @Override//www  .j  a  va2s  .c o m
        public Optional<ILock> apply(StoreProvider storeProvider) {
            return storeProvider.getLockStore().fetchLock(context);
        }
    });

    // The implementation below assumes the following use cases:
    // +-----------+-----------------+----------+
    // |   eq      |     held        | not held |
    // +-----------+-----------------+----------+
    // |stored     |(stored == held)?| invalid  |
    // +-----------+-----------------+----------+
    // |not stored |    invalid      |  valid   |
    // +-----------+-----------------+----------+
    if (!stored.equals(heldLock)) {
        if (stored.isPresent()) {
            throw new LockException(
                    String.format("Unable to perform operation for: %s. Use override/cancel option.",
                            formatLockKey(context)));
        } else if (heldLock.isPresent()) {
            throw new LockException(String.format("Invalid operation context: %s", formatLockKey(context)));
        }
    }
}