com.google.common.base.Equivalence Java Examples

The following examples show how to use com.google.common.base.Equivalence. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Maps.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static <K, V> void doDifference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence, Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, MapDifference.ValueDifference<V>> differences) {
  for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
    K leftKey = entry.getKey();
    V leftValue = entry.getValue();
    if (right.containsKey(leftKey)) {
      V rightValue = onlyOnRight.remove(leftKey);
      if (valueEquivalence.equivalent(leftValue, rightValue)) {
        onBoth.put(leftKey, leftValue);
      } else {
        differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
      }
    } else {
      onlyOnLeft.put(leftKey, leftValue);
    }
  }
}
 
Example #2
Source File: QueryCollectionBase.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
private Set<ReasonerQueryImpl> getAllNeighbours(ReasonerQueryImpl entryQuery) {
    Set<ReasonerQueryImpl> neighbours = new HashSet<>();
    Set<Equivalence.Wrapper<ReasonerQueryImpl>> visitedQueries = new HashSet<>();
    Stack<Equivalence.Wrapper<ReasonerQueryImpl>> queryStack = new Stack<>();

    Multimap<ReasonerQueryImpl, ReasonerQueryImpl> neighbourMap = immediateNeighbourMap();

    neighbourMap.get(entryQuery).stream().map(q -> equality().wrap(q)).forEach(queryStack::push);
    while (!queryStack.isEmpty()) {
        Equivalence.Wrapper<ReasonerQueryImpl> wrappedQuery = queryStack.pop();
        ReasonerQueryImpl query = wrappedQuery.get();
        if (!visitedQueries.contains(wrappedQuery) && query != null) {
            neighbourMap.get(query).stream()
                    .peek(neighbours::add)
                    .flatMap(q -> neighbourMap.get(q).stream())
                    .map(q -> equality().wrap(q))
                    .filter(q -> !visitedQueries.contains(q))
                    .filter(q -> !queryStack.contains(q))
                    .forEach(queryStack::add);
            visitedQueries.add(wrappedQuery);
        }
    }
    return neighbours;
}
 
Example #3
Source File: Maps.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static <K, V> void doDifference(
    Map<? extends K, ? extends V> left,
    Map<? extends K, ? extends V> right,
    Equivalence<? super V> valueEquivalence,
    Map<K, V> onlyOnLeft,
    Map<K, V> onlyOnRight,
    Map<K, V> onBoth,
    Map<K, MapDifference.ValueDifference<V>> differences) {
  for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
    K leftKey = entry.getKey();
    V leftValue = entry.getValue();
    if (right.containsKey(leftKey)) {
      V rightValue = onlyOnRight.remove(leftKey);
      if (valueEquivalence.equivalent(leftValue, rightValue)) {
        onBoth.put(leftKey, leftValue);
      } else {
        differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
      }
    } else {
      onlyOnLeft.put(leftKey, leftValue);
    }
  }
}
 
Example #4
Source File: ComputingConcurrentHashMap.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
ComputingSerializationProxy(
    Strength keyStrength,
    Strength valueStrength,
    Equivalence<Object> keyEquivalence,
    Equivalence<Object> valueEquivalence,
    int concurrencyLevel,
    ConcurrentMap<K, V> delegate,
    Function<? super K, ? extends V> computingFunction) {
  super(
      keyStrength,
      valueStrength,
      keyEquivalence,
      valueEquivalence,
      concurrencyLevel,
      delegate);
  this.computingFunction = computingFunction;
}
 
Example #5
Source File: Maps.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static <K, V> void doDifference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence, Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, MapDifference.ValueDifference<V>> differences) {
  for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
    K leftKey = entry.getKey();
    V leftValue = entry.getValue();
    if (right.containsKey(leftKey)) {
      V rightValue = onlyOnRight.remove(leftKey);
      if (valueEquivalence.equivalent(leftValue, rightValue)) {
        onBoth.put(leftKey, leftValue);
      } else {
        differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
      }
    } else {
      onlyOnLeft.put(leftKey, leftValue);
    }
  }
}
 
Example #6
Source File: LocalCache.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private ManualSerializationProxy(
    Strength keyStrength,
    Strength valueStrength,
    Equivalence<Object> keyEquivalence,
    Equivalence<Object> valueEquivalence,
    long expireAfterWriteNanos,
    long expireAfterAccessNanos,
    long maxWeight,
    Weigher<K, V> weigher,
    int concurrencyLevel,
    RemovalListener<? super K, ? super V> removalListener,
    Ticker ticker,
    CacheLoader<? super K, V> loader) {
  this.keyStrength = keyStrength;
  this.valueStrength = valueStrength;
  this.keyEquivalence = keyEquivalence;
  this.valueEquivalence = valueEquivalence;
  this.expireAfterWriteNanos = expireAfterWriteNanos;
  this.expireAfterAccessNanos = expireAfterAccessNanos;
  this.maxWeight = maxWeight;
  this.weigher = weigher;
  this.concurrencyLevel = concurrencyLevel;
  this.removalListener = removalListener;
  this.ticker = (ticker == Ticker.systemTicker() || ticker == NULL_TICKER) ? null : ticker;
  this.loader = loader;
}
 
Example #7
Source File: Mirrors.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps an {@link Optional} of a type in an {@code Optional} of a {@link Equivalence.Wrapper} for
 * that type.
 */
// TODO(ronshapiro): this is used in AutoFactory and Dagger, consider moving it into auto-common.
static <T> Optional<Equivalence.Wrapper<T>> wrapOptionalInEquivalence(
    Equivalence<T> equivalence, Optional<T> optional) {
  return optional.isPresent()
      ? Optional.of(equivalence.wrap(optional.get()))
      : Optional.<Equivalence.Wrapper<T>>absent();
}
 
Example #8
Source File: RealNumberEquivalenceTest.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void checkEquivalence(boolean result, double expectedValue, double actualValue, int tolerance){
	Equivalence<Object> equivalence = new RealNumberEquivalence(tolerance);

	assertEquals(result, equivalence.equivalent(expectedValue, actualValue));
	assertEquals(result, equivalence.equivalent(Double.toString(expectedValue), actualValue));
}
 
Example #9
Source File: GoogleCloudStorageTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
static <K, V> void assertMapsEqual(
    Map<K, V> expected, Map<K, V> result, Equivalence<V> valueEquivalence) {
  MapDifference<K, V> diff = Maps.difference(expected, result, valueEquivalence);
  if (!diff.areEqual()) {
    fail(
        String.format(
            "Maps differ. Entries differing: %s%nMissing entries: %s%nExtra entries: %s%n",
            diff.entriesDiffering(), diff.entriesOnlyOnLeft(), diff.entriesOnlyOnRight()));
  }
}
 
Example #10
Source File: AttributeAtom.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isBaseEquivalent(Object obj, Equivalence<Atomic> equivalence){
    if (obj == null || this.getClass() != obj.getClass()) return false;
    if (obj == this) return true;
    AttributeAtom that = (AttributeAtom) obj;
    return equivalence.equivalent(this.attributeIsa(), that.attributeIsa())
            && equivalence.equivalent(this.ownerIsa(), that.ownerIsa());
}
 
Example #11
Source File: VariablePredicate.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean predicateBindingsEquivalent(VariablePredicate that, Equivalence<Atomic> equiv){
    IdPredicate thisPredicate = this.getIdPredicate(this.getVarName());
    IdPredicate thatPredicate = that.getIdPredicate(that.getVarName());
    IdPredicate thisRefPredicate = this.getIdPredicate(this.getPredicate());
    IdPredicate thatRefPredicate = that.getIdPredicate(that.getPredicate());
    return (
            (thisPredicate == null) ?
            thisPredicate == thatPredicate :
            equiv.equivalent(thisPredicate, thatPredicate)
    ) && (
            (thisRefPredicate == null) ?
            (thisRefPredicate == thatRefPredicate) :
            equiv.equivalent(thisRefPredicate, thatRefPredicate)
    );
}
 
Example #12
Source File: TestingExample.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private Batch createBatch(Evaluator evaluator, List<? extends Map<FieldName, ?>> input, List<? extends Map<FieldName, ?>> output, Predicate<ResultField> predicate, Equivalence<Object> equivalence){
	Batch batch = new Batch(){

		@Override
		public Evaluator getEvaluator(){
			return evaluator;
		}

		@Override
		public List<? extends Map<FieldName, ?>> getInput(){
			return input;
		}

		@Override
		public List<? extends Map<FieldName, ?>> getOutput(){
			return output;
		}

		@Override
		public Predicate<ResultField> getPredicate(){
			return predicate;
		}

		@Override
		public Equivalence<Object> getEquivalence(){
			return equivalence;
		}

		@Override
		public void close(){
		}
	};

	return batch;
}
 
Example #13
Source File: FieldDescriptor.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
FieldDescriptor create(TypeElement owner, VariableElement element) {
  String name = element.getSimpleName().toString();
  TypeMirror type = types.asMemberOf((DeclaredType) owner.asType(), element);
  TypeMirror fieldType = Utils.replaceTypeVariablesWithUpperBounds(types, type);
  Equivalence.Wrapper<TypeMirror> wrappedType = MoreTypes.equivalence().wrap(fieldType);
  boolean isVisible = Visibility.ofElement(element) != Visibility.PRIVATE;
  boolean isNullable =
      Utils.getAnnotationWithSimpleName(element, NON_NULL_ANNOTATION_NAME) == null
      && Utils.getAnnotationWithSimpleName(element, NOT_NULL_ANNOTATION_NAME) == null;
  return new AutoValue_FieldDescriptor(element, name, wrappedType, isVisible, isNullable);
}
 
Example #14
Source File: MapMakerInternalMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
SerializationProxy(
    Strength keyStrength,
    Strength valueStrength,
    Equivalence<Object> keyEquivalence,
    Equivalence<Object> valueEquivalence,
    int concurrencyLevel,
    ConcurrentMap<K, V> delegate) {
  super(
      keyStrength,
      valueStrength,
      keyEquivalence,
      valueEquivalence,
      concurrencyLevel,
      delegate);
}
 
Example #15
Source File: SerializableAutoValueExtension.java    From auto with Apache License 2.0 5 votes vote down vote up
ProxyGenerator(
    TypeName outerClassTypeName,
    ImmutableList<TypeVariableName> typeVariableNames,
    ImmutableList<PropertyMirror> propertyMirrors,
    ImmutableMap<Equivalence.Wrapper<TypeMirror>, Serializer> serializersMap) {
  this.outerClassTypeName = outerClassTypeName;
  this.typeVariableNames = typeVariableNames;
  this.propertyMirrors = propertyMirrors;
  this.serializersMap = serializersMap;
}
 
Example #16
Source File: ReasonerUtils.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param a first operand
 * @param b second operand
 * @param equiv equivalence on the basis of which the collections shall be compared
 * @param <B> collection base type
 * @param <S> collection super type
 * @return true iff the given Collections contain equivalent elements with exactly the same cardinalities.
 */
public static <B, S extends B> boolean isEquivalentCollection(Collection<S> a, Collection<S> b,  Equivalence<B> equiv) {
    if (a.size() != b.size()) {
        return false;
    } else {
        Map<Equivalence.Wrapper<B>, Integer> mapA = getCardinalityMap(a, equiv);
        Map<Equivalence.Wrapper<B>, Integer> mapB = getCardinalityMap(b, equiv);
        if (mapA.size() != mapB.size()) {
            return false;
        } else {
            return mapA.keySet().stream().allMatch(k -> mapA.get(k).equals(mapB.get(k)));
        }
    }
}
 
Example #17
Source File: ConverterTest.java    From jpmml-r with GNU Affero General Public License v3.0 5 votes vote down vote up
protected ArchiveBatch createBatch(String name, String dataset, Class<? extends Converter<? extends RExp>> converterClazz){
	Predicate<ResultField> predicate = (resultField -> true);
	Equivalence<Object> equivalence = getEquivalence();

	ConverterTestBatch batch = (ConverterTestBatch)createBatch(name, dataset, predicate, equivalence);
	batch.setConverterClazz(converterClazz);

	return batch;
}
 
Example #18
Source File: BindingGraph.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
private Optional<RequestResolver> getOwningResolver(ProvisionBinding provisionBinding) {
  Optional<Equivalence.Wrapper<AnnotationMirror>> bindingScope =
      provisionBinding.wrappedScope();
  for (RequestResolver requestResolver : getResolverLineage()) {
    if (bindingScope.equals(requestResolver.targetScope)
        || requestResolver.explicitProvisionBindings.containsValue(provisionBinding)) {
      return Optional.of(requestResolver);
    }
  }
  return Optional.absent();
}
 
Example #19
Source File: TypeVariables.java    From auto with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether a given parameter can be given to a static method like
 * {@code ImmutableMap.copyOf} to produce a value that can be assigned to the given target type.
 *
 * <p>For example, suppose we have this method in {@code ImmutableMap}:<br>
 * {@code static <K, V> ImmutableMap<K, V> copyOf(Map<? extends K, ? extends V>)}<br>
 * and we want to know if we can do this:
 *
 * <pre>
 * {@code ImmutableMap<String, Integer> actualParameter = ...;}
 * {@code ImmutableMap<String, Number> target = ImmutableMap.copyOf(actualParameter);}
 * </pre>
 *
 * We will infer {@code K=String}, {@code V=Number} based on the target type, and then rewrite the
 * formal parameter type from<br>
 * {@code Map<? extends K, ? extends V>} to<br>
 * {@code Map<? extends String, ? extends Number>}. Then we can check whether
 * {@code actualParameter} is assignable to that.
 *
 * <p>The logic makes some simplifying assumptions, which are met for the {@code copyOf} and
 * {@code of} methods that we use this for. The method must be static, it must have exactly one
 * parameter, and it must have type parameters without bounds that are the same as the type
 * parameters of its return type. We can see that these assumptions are met for the
 * {@code ImmutableMap.copyOf} example above.
 */
static boolean canAssignStaticMethodResult(
    ExecutableElement method,
    TypeMirror actualParameterType,
    TypeMirror targetType,
    Types typeUtils) {
  if (!targetType.getKind().equals(TypeKind.DECLARED)
      || !method.getModifiers().contains(Modifier.STATIC)
      || method.getParameters().size() != 1) {
    return false;
  }
  List<? extends TypeParameterElement> typeParameters = method.getTypeParameters();
  List<? extends TypeMirror> targetTypeArguments =
      MoreTypes.asDeclared(targetType).getTypeArguments();
  if (typeParameters.size() != targetTypeArguments.size()) {
    return false;
  }
  Map<Equivalence.Wrapper<TypeVariable>, TypeMirror> typeVariables = new LinkedHashMap<>();
  for (int i = 0; i < typeParameters.size(); i++) {
    TypeVariable v = MoreTypes.asTypeVariable(typeParameters.get(i).asType());
    typeVariables.put(MoreTypes.equivalence().wrap(v), targetTypeArguments.get(i));
  }
  TypeMirror formalParameterType = method.getParameters().get(0).asType();
  SubstitutionVisitor substitutionVisitor = new SubstitutionVisitor(typeVariables, typeUtils);
  TypeMirror substitutedParameterType = substitutionVisitor.visit(formalParameterType, null);
  if (substitutedParameterType.getKind().equals(TypeKind.WILDCARD)) {
    // If the target type is Optional<? extends Foo> then <T> T Optional.of(T) will give us
    // ? extends Foo here, and typeUtils.isAssignable will return false. But we can in fact
    // give a Foo as an argument, so we just replace ? extends Foo with Foo.
    WildcardType wildcard = MoreTypes.asWildcard(substitutedParameterType);
    if (wildcard.getExtendsBound() != null) {
      substitutedParameterType = wildcard.getExtendsBound();
    }
  }
  return typeUtils.isAssignable(actualParameterType, substitutedParameterType);
}
 
Example #20
Source File: QueryCollectionBase.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param entryQuery query for which candidates are to be determined
 * @param plan current plan
 * @return set of candidate queries for this query
 */
QuerySet getCandidates(ReasonerQueryImpl entryQuery, QueryList plan){
    Equivalence.Wrapper<ReasonerQueryImpl> query = equality().wrap(entryQuery);
    Set<Equivalence.Wrapper<ReasonerQueryImpl>> availableQueries = this.wrappedStream()
            .filter(q -> !(plan.contains(q) || q.equals(query)))
            .collect(Collectors.toSet());

    Set<Equivalence.Wrapper<ReasonerQueryImpl>> availableImmediateNeighbours = this.getImmediateNeighbours(query).stream()
            .filter(availableQueries::contains)
            .collect(Collectors.toSet());

    Set<Variable> subbedVars = plan.stream()
            .flatMap(q -> q.getVarNames().stream())
            .collect(Collectors.toSet());

    Set<Equivalence.Wrapper<ReasonerQueryImpl>> availableImmediateNeighboursFromSubs = availableQueries.stream()
            .map(Equivalence.Wrapper::get)
            .filter(Objects::nonNull)
            .filter(q -> !Sets.intersection(q.getVarNames(), subbedVars).isEmpty())
            .map(q -> equality().wrap(q))
            .collect(Collectors.toSet());

    return QuerySet.create(
            this.isQueryDisconnected(query)?
                    availableQueries :
                    this.isQueryReachable(query, availableQueries)?
                            Sets.union(availableImmediateNeighbours, availableImmediateNeighboursFromSubs): availableQueries
    );
}
 
Example #21
Source File: RelationshipTester.java    From jrestless with Apache License 2.0 5 votes vote down vote up
RelationshipTester(Equivalence<? super T> equivalence, String relationshipName, String hashName,
		ItemReporter itemReporter) {
	this.equivalence = checkNotNull(equivalence);
	this.relationshipName = checkNotNull(relationshipName);
	this.hashName = checkNotNull(hashName);
	this.itemReporter = checkNotNull(itemReporter);
}
 
Example #22
Source File: DatastoreBrowseNodeStoreImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private Equivalence<BrowseNode<Integer>> getIdentity(final Repository repository) {
  Optional<BrowseNodeFacet> browseNodeFacet = repository.optionalFacet(BrowseNodeFacet.class);
  if (browseNodeFacet.isPresent()) {
    return Equivalence.equals().onResultOf(input -> browseNodeFacet.get().browseNodeIdentity().apply(input));
  }
  else {
    return Equivalence.equals().onResultOf(BrowseNode::getName);
  }
}
 
Example #23
Source File: MapMakerInternalMap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
AbstractSerializationProxy(
    Strength keyStrength,
    Strength valueStrength,
    Equivalence<Object> keyEquivalence,
    Equivalence<Object> valueEquivalence,
    int concurrencyLevel,
    ConcurrentMap<K, V> delegate) {
  this.keyStrength = keyStrength;
  this.valueStrength = valueStrength;
  this.keyEquivalence = keyEquivalence;
  this.valueEquivalence = valueEquivalence;
  this.concurrencyLevel = concurrencyLevel;
  this.delegate = delegate;
}
 
Example #24
Source File: MapMaker.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Sets a custom {@code Equivalence} strategy for comparing keys.
 *
 * <p>By default, the map uses {@link Equivalence#identity} to determine key equality when
 * {@link #weakKeys} is specified, and {@link Equivalence#equals()} otherwise. The only place this
 * is used is in {@link Interners.WeakInterner}.
 */

@CanIgnoreReturnValue
@GwtIncompatible // To be supported
MapMaker keyEquivalence(Equivalence<Object> equivalence) {
  checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence);
  keyEquivalence = checkNotNull(equivalence);
  this.useCustomMap = true;
  return this;
}
 
Example #25
Source File: ProvisionBinding.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
ProvisionBinding forComponent(TypeElement componentDefinitionType) {
  checkNotNull(componentDefinitionType);
  return new AutoValue_ProvisionBinding(
      keyFactory.forComponent(componentDefinitionType.asType()),
      componentDefinitionType,
      ImmutableSet.<DependencyRequest>of(),
      Optional.<String>absent(),
      false /* no non-default parameter types */,
      Optional.<DeclaredType>absent(),
      Optional.<TypeElement>absent(),
      Kind.COMPONENT,
      Provides.Type.UNIQUE,
      Optional.<Equivalence.Wrapper<AnnotationMirror>>absent(),
      Optional.<DependencyRequest>absent());
}
 
Example #26
Source File: KeyTest.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
@Test public void forInjectConstructorWithResolvedType() {
  TypeElement typeElement =
      compilationRule.getElements().getTypeElement(InjectedClass.class.getCanonicalName());
  ExecutableElement constructor =
      Iterables.getOnlyElement(ElementFilter.constructorsIn(typeElement.getEnclosedElements()));
  assertThat(
      keyFactory.forInjectConstructorWithResolvedType(constructor.getEnclosingElement().asType()))
      .isEqualTo(new AutoValue_Key(
          Optional.<Equivalence.Wrapper<AnnotationMirror>>absent(),
          MoreTypes.equivalence().wrap(typeElement.asType())));
}
 
Example #27
Source File: ConverterTest.java    From jpmml-r with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected ArchiveBatch createBatch(String name, String dataset, Predicate<ResultField> predicate, Equivalence<Object> equivalence){
	ArchiveBatch result = new ConverterTestBatch(name, dataset, predicate, equivalence){

		@Override
		public IntegrationTest getIntegrationTest(){
			return ConverterTest.this;
		}

		@Override
		public PMML getPMML() throws Exception {

			try(InputStream is = open("/rds/" + getName() + getDataset() + ".rds")){
				RExpParser parser = new RExpParser(is);

				RExp rexp = parser.parse();

				Converter<RExp> converter = createConverter(rexp);

				PMML pmml = converter.encodePMML();

				validatePMML(pmml);

				return pmml;
			}
		}
	};

	return result;
}
 
Example #28
Source File: KeyTest.java    From dagger2-sample with Apache License 2.0 5 votes vote down vote up
@Test public void forProducesMethod_sets() {
  TypeElement setElement = elements.getTypeElement(Set.class.getCanonicalName());
  TypeMirror stringType = elements.getTypeElement(String.class.getCanonicalName()).asType();
  TypeMirror setOfStringsType = types.getDeclaredType(setElement, stringType);
  TypeElement moduleElement =
      elements.getTypeElement(SetProducesMethodsModule.class.getCanonicalName());
  for (ExecutableElement producesMethod
      : ElementFilter.methodsIn(moduleElement.getEnclosedElements())) {
    assertThat(keyFactory.forProducesMethod(
        (ExecutableType) producesMethod.asType(), producesMethod))
        .isEqualTo(new AutoValue_Key(
                Optional.<Equivalence.Wrapper<AnnotationMirror>>absent(),
                MoreTypes.equivalence().wrap(setOfStringsType)));
  }
}
 
Example #29
Source File: RealNumberEquivalenceTest.java    From jpmml-evaluator with GNU Affero General Public License v3.0 5 votes vote down vote up
static
private void checkEquivalence(boolean result, float expectedValue, float actualValue, int tolerance){
	Equivalence<Object> equivalence = new RealNumberEquivalence(tolerance);

	assertEquals(result, equivalence.equivalent(expectedValue, actualValue));
	assertEquals(result, equivalence.equivalent((double)expectedValue, actualValue));
	assertEquals(result, equivalence.equivalent(Float.toString(expectedValue), actualValue));
	assertEquals(result, equivalence.equivalent(Double.toString(expectedValue), actualValue));
}
 
Example #30
Source File: PermissionServiceImpl.java    From qconfig with MIT License 5 votes vote down vote up
private List<String> setPermissionList(List<Permission> newer, List<Permission> older) {
    Timestamp now = new Timestamp(System.currentTimeMillis());
    List<String> remarks = Lists.newArrayList();
    List<Permission> changes = Lists.newArrayList();

    Map<String, Permission> infoMap = mapByRtxId(newer);
    Map<String, Permission> originInfoMap = mapByRtxId(older);

    MapDifference<String, Permission> difference = Maps.difference(infoMap, originInfoMap, new Equivalence<Permission>() {
        @Override
        protected boolean doEquivalent(Permission a, Permission b) {
            return a.getPermission() == b.getPermission() && a.getRtxId().equals(b.getRtxId());
        }

        @Override
        protected int doHash(Permission permissionInfo) {
            return Objects.hashCode(permissionInfo.getRtxId(), permissionInfo.getPermission());
        }
    });

    dealOnlyOnLeft(changes, remarks, infoMap, difference, now);
    dealDifference(changes, remarks, infoMap, originInfoMap, difference, now);

    if (!changes.isEmpty() && changes.get(0).processChange(permissionDao, changes)) {
        logger.info("change permissions successOf, {}", changes);
    }

    return remarks;
}