com.google.common.primitives.Booleans Java Examples

The following examples show how to use com.google.common.primitives.Booleans. 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: TensorUtil.java    From jpmml-tensorflow with GNU Affero General Public License v3.0 7 votes vote down vote up
static
public List<?> getValues(Tensor tensor){
	DataType dataType = tensor.dataType();

	switch(dataType){
		case FLOAT:
			return Floats.asList(TensorUtil.toFloatArray(tensor));
		case DOUBLE:
			return Doubles.asList(TensorUtil.toDoubleArray(tensor));
		case INT32:
			return Ints.asList(TensorUtil.toIntArray(tensor));
		case INT64:
			return Longs.asList(TensorUtil.toLongArray(tensor));
		case STRING:
			return Arrays.asList(TensorUtil.toStringArray(tensor));
		case BOOL:
			return Booleans.asList(TensorUtil.toBooleanArray(tensor));
		default:
			throw new IllegalArgumentException();
	}
}
 
Example #2
Source File: OrderBy.java    From crate with Apache License 2.0 6 votes vote down vote up
@Nullable
public OrderBy exclude(Predicate<? super Symbol> predicate) {
    ArrayList<Symbol> newOrderBySymbols = new ArrayList<>(orderBySymbols.size());
    ArrayList<Boolean> newReverseFlags = new ArrayList<>(reverseFlags.length);
    ArrayList<Boolean> newNullsFirst = new ArrayList<>(nullsFirst.length);
    for (int i = 0; i < orderBySymbols.size(); i++) {
        Symbol sortSymbol = orderBySymbols.get(i);
        if (predicate.test(sortSymbol) == false) {
            newOrderBySymbols.add(sortSymbol);
            newReverseFlags.add(reverseFlags[i]);
            newNullsFirst.add(nullsFirst[i]);
        }
    }
    if (newOrderBySymbols.size() == 0) {
        return null;
    }
    return new OrderBy(newOrderBySymbols, Booleans.toArray(newReverseFlags), Booleans.toArray(newNullsFirst));
}
 
Example #3
Source File: Ideas_2011_08_01.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@ExpectWarning(value="RV_CHECK_COMPARETO_FOR_SPECIFIC_RETURN_VALUE", num = 9)
public static int testGuavaPrimitiveCompareCalls() {
    int count = 0;
    if (Booleans.compare(false, true) == -1)
        count++;
    if (Chars.compare('a', 'b') == -1)
        count++;
    if (Doubles.compare(1, 2) == -1)
        count++;
    if (Floats.compare(1, 2) == -1)
        count++;
    if (Ints.compare(1, 2) == -1)
        count++;
    if (Longs.compare(1, 2) == -1)
        count++;
    if (Shorts.compare((short) 1, (short) 2) == -1)
        count++;
    if (SignedBytes.compare((byte) 1, (byte) 2) == -1)
        count++;
    if (UnsignedBytes.compare((byte) 1, (byte) 2) == -1)
        count++;
    return count;

}
 
Example #4
Source File: HistoryEvolutionDTO.java    From james-project with Apache License 2.0 6 votes vote down vote up
@JsonIgnore
public HistoryEvolution toHistoryEvolution() {
    Preconditions.checkState(Booleans.countTrue(
        threshold.isPresent(), instant.isPresent()) != 1,
        "threshold and instant needs to be both set, or both unset. Mixed states not allowed.");

    Optional<QuotaThresholdChange> quotaThresholdChange = threshold
        .map(QuotaThreshold::new)
        .map(value -> new QuotaThresholdChange(value, Instant.ofEpochMilli(instant.get())));

    return new HistoryEvolution(
        change,
        recentness,
        quotaThresholdChange);

}
 
Example #5
Source File: MailQueueRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Task deleteMailsTask(MailQueueName queueName, Optional<MailAddress> maybeSender, Optional<String> maybeName, Optional<MailAddress> maybeRecipient) {
    int paramCount = Booleans.countTrue(maybeSender.isPresent(), maybeName.isPresent(), maybeRecipient.isPresent());
    switch (paramCount) {
        case 0:
            return new ClearMailQueueTask(queueName, this::getQueue);
        case 1:
            return new DeleteMailsFromMailQueueTask(queueName, this::getQueue, maybeSender, maybeName, maybeRecipient);
        default:
            throw ErrorResponder.builder()
                .statusCode(HttpStatus.BAD_REQUEST_400)
                .type(ErrorType.INVALID_ARGUMENT)
                .message("You should provide only one of the query parameters 'sender', 'name', 'recipient' " +
                        "for deleting mails by condition or no parameter for deleting all mails in the mail queue.")
                .haltError();
    }
}
 
Example #6
Source File: DeleteMailsFromMailQueueTask.java    From james-project with Apache License 2.0 6 votes vote down vote up
public DeleteMailsFromMailQueueTask(MailQueueName queueName, MailQueueFactory factory,
                                    Optional<MailAddress> optionalSender,
                                    Optional<String> optionalName,
                                    Optional<MailAddress> optionalRecipient) {
    this.factory = factory;
    this.queueName = queueName;
    Preconditions.checkArgument(
        Booleans.countTrue(optionalSender.isPresent(), optionalName.isPresent(), optionalRecipient.isPresent()) == 1,
        "You should provide one and only one of the query parameters 'sender', 'name' or 'recipient'.");

    this.optionalSender = optionalSender;
    this.optionalName = optionalName;
    this.optionalRecipient = optionalRecipient;
    this.initialCount = Optional.empty();
    this.queue = Optional.empty();
    this.lastAdditionalInformation = Optional.empty();

}
 
Example #7
Source File: JavaClassProcessor.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"}) // NOTE: We assume the component type matches the list
private Object toArray(Class<?> componentType, List<Object> values) {
    if (componentType == boolean.class) {
        return Booleans.toArray((Collection) values);
    } else if (componentType == byte.class) {
        return Bytes.toArray((Collection) values);
    } else if (componentType == short.class) {
        return Shorts.toArray((Collection) values);
    } else if (componentType == int.class) {
        return Ints.toArray((Collection) values);
    } else if (componentType == long.class) {
        return Longs.toArray((Collection) values);
    } else if (componentType == float.class) {
        return Floats.toArray((Collection) values);
    } else if (componentType == double.class) {
        return Doubles.toArray((Collection) values);
    } else if (componentType == char.class) {
        return Chars.toArray((Collection) values);
    }
    return values.toArray((Object[]) Array.newInstance(componentType, values.size()));
}
 
Example #8
Source File: Message.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private Message(Builder builder) {
  this.data = builder.data.isEmpty() ? null : ImmutableMap.copyOf(builder.data);
  this.notification = builder.notification;
  this.androidConfig = builder.androidConfig;
  this.webpushConfig = builder.webpushConfig;
  this.apnsConfig = builder.apnsConfig;
  int count = Booleans.countTrue(
      !Strings.isNullOrEmpty(builder.token),
      !Strings.isNullOrEmpty(builder.topic),
      !Strings.isNullOrEmpty(builder.condition)
  );
  checkArgument(count == 1, "Exactly one of token, topic or condition must be specified");
  this.token = builder.token;
  this.topic = stripPrefix(builder.topic);
  this.condition = builder.condition;
  this.fcmOptions = builder.fcmOptions;
}
 
Example #9
Source File: StdUdfWrapper.java    From transport with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected StdUdfWrapper(StdUDF stdUDF) {
  super(new FunctionMetadata(
          new Signature(
                  ((TopLevelStdUDF) stdUDF).getFunctionName(),
                  getTypeVariableConstraintsForStdUdf(stdUDF),
                  ImmutableList.of(),
                  parseTypeSignature(stdUDF.getOutputParameterSignature(), ImmutableSet.of()),
                  stdUDF.getInputParameterSignatures().stream()
                          .map(typeSignature -> parseTypeSignature(typeSignature, ImmutableSet.of()))
                          .collect(Collectors.toList()),
                  false),
          true,
          Booleans.asList(stdUDF.getNullableArguments()).stream()
                  .map(FunctionArgumentDefinition::new)
                  .collect(Collectors.toList()),
          false,
          false,
          ((TopLevelStdUDF) stdUDF).getFunctionDescription(),
          FunctionKind.SCALAR));
}
 
Example #10
Source File: Cut.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public int compareTo(Cut<C> that) {
  if (that == belowAll()) {
    return 1;
  }
  if (that == aboveAll()) {
    return -1;
  }
  int result = Range.compareOrThrow(endpoint, that.endpoint);
  if (result != 0) {
    return result;
  }
  // same value. below comes before above
  return Booleans.compare(this instanceof AboveValue, that instanceof AboveValue);
}
 
Example #11
Source File: ArrayField.java    From drift with Apache License 2.0 5 votes vote down vote up
public Map<Short, List<Boolean>> getMapBooleanList()
{
    if (mapBooleanArray == null) {
        return null;
    }
    return Maps.transformValues(mapBooleanArray, Booleans::asList);
}
 
Example #12
Source File: Conversions.java    From xtext-lib with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws NullPointerException
 *             if the wrapped array was <code>null</code>.
 */
@Override
public int indexOf(Object o) {
	// Will make the method fail if array is null.
	if (size() < 1) {
		return -1;
	}
	if (o instanceof Boolean) {
		return Booleans.indexOf(array, ((Boolean) o).booleanValue());
	}
	return -1;
}
 
Example #13
Source File: Conversions.java    From xtext-lib with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws NullPointerException
 *             if the wrapped array was <code>null</code>.
 */
@Override
public int lastIndexOf(Object o) {
	// Will make the method fail if array is null.
	if (size() < 1) {
		return -1;
	}
	if (o instanceof Boolean) {
		return Booleans.lastIndexOf(array, ((Boolean) o).booleanValue());
	}
	return -1;
}
 
Example #14
Source File: Conversions.java    From xtext-lib with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @throws NullPointerException
 *             if the wrapped array was <code>null</code>.
 */
@Override
public boolean contains(Object o) {
	// Will make the method fail if array is null.
	if (size() < 1) {
		return false;
	}
	if (o instanceof Boolean) {
		return Booleans.contains(array, ((Boolean) o).booleanValue());
	}
	return false;
}
 
Example #15
Source File: JvmOptions.java    From twill with Apache License 2.0 5 votes vote down vote up
@Override
public int hashCode() {
  int hash = 17;
  hash = 31 *  hash + Booleans.hashCode(doDebug);
  hash = 31 *  hash + Booleans.hashCode(doSuspend);
  hash = 31 *  hash + Objects.hashCode(runnables);
  return hash;
}
 
Example #16
Source File: Message.java    From MixPush with Apache License 2.0 5 votes vote down vote up
/**
 * check message's parameters
 */
public void check() {

    int count = Booleans.countTrue(
            !CollectionUtils.isEmpty(this.token),
            !Strings.isNullOrEmpty(this.topic),
            !Strings.isNullOrEmpty(this.condition)
    );

    ValidatorUtils.checkArgument(count == 1, "Exactly one of token, topic or condition must be specified");

    boolean isEmptyData = StringUtils.isEmpty(data);

    if (this.notification != null) {
        this.notification.check();
    }

    if (null != this.androidConfig) {
        this.androidConfig.check(this.notification);
    }

    if (this.apns != null) {
        this.apns.check();
    }

    if (this.webpush != null) {
        this.webpush.check();
    }
}
 
Example #17
Source File: Cut.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public int compareTo(Cut<C> that) {
  if (that == belowAll()) {
    return 1;
  }
  if (that == aboveAll()) {
    return -1;
  }
  int result = Range.compareOrThrow(endpoint, that.endpoint);
  if (result != 0) {
    return result;
  }
  // same value. below comes before above
  return Booleans.compare(this instanceof AboveValue, that instanceof AboveValue);
}
 
Example #18
Source File: PBoolean.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(Object lhs, Object rhs, PDataType rhsType) {
    if (lhs == rhs) {
        return 0;
    }
    if (lhs == null) {
        return -1;
    }
    if (rhs == null) {
        return 1;
    }
    return Booleans.compare((Boolean) lhs, (Boolean) rhs);
}
 
Example #19
Source File: Cut.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public int compareTo(Cut<C> that) {
  if (that == belowAll()) {
    return 1;
  }
  if (that == aboveAll()) {
    return -1;
  }
  int result = Range.compareOrThrow(endpoint, that.endpoint);
  if (result != 0) {
    return result;
  }
  // same value. below comes before above
  return Booleans.compare(this instanceof AboveValue, that instanceof AboveValue);
}
 
Example #20
Source File: Cut.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public int compareTo(Cut<C> that) {
  if (that == belowAll()) {
    return 1;
  }
  if (that == aboveAll()) {
    return -1;
  }
  int result = Range.compareOrThrow(endpoint, that.endpoint);
  if (result != 0) {
    return result;
  }
  // same value. below comes before above
  return Booleans.compare(this instanceof AboveValue, that instanceof AboveValue);
}
 
Example #21
Source File: Cut.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public int compareTo(Cut<C> that) {
  if (that == belowAll()) {
    return 1;
  }
  if (that == aboveAll()) {
    return -1;
  }
  int result = Range.compareOrThrow(endpoint, that.endpoint);
  if (result != 0) {
    return result;
  }
  // same value. below comes before above
  return Booleans.compare(this instanceof AboveValue, that instanceof AboveValue);
}
 
Example #22
Source File: RdapNameserverSearchAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the parameters and calls the appropriate search function.
 *
 * <p>The RDAP spec allows nameserver search by either name or IP address.
 */
@Override
public NameserverSearchResponse getSearchResponse(boolean isHeadRequest) {
  // RDAP syntax example: /rdap/nameservers?name=ns*.example.com.
  if (Booleans.countTrue(nameParam.isPresent(), ipParam.isPresent()) != 1) {
    throw new BadRequestException("You must specify either name=XXXX or ip=YYYY");
  }
  NameserverSearchResponse results;
  if (nameParam.isPresent()) {
    // RDAP Technical Implementation Guilde 2.2.3 - we MAY support nameserver search queries based
    // on a "nameserver search pattern" as defined in RFC7482
    //
    // syntax: /rdap/nameservers?name=exam*.com
    metricInformationBuilder.setSearchType(SearchType.BY_NAMESERVER_NAME);
    results =
        searchByName(
            recordWildcardType(
                RdapSearchPattern.createFromLdhOrUnicodeDomainName(nameParam.get())));
  } else {
    // RDAP Technical Implementation Guide 2.2.3 - we MUST support nameserver search queries based
    // on IP address as defined in RFC7482 3.2.2. Doesn't require pattern matching
    //
    // syntax: /rdap/nameservers?ip=1.2.3.4
    metricInformationBuilder.setSearchType(SearchType.BY_NAMESERVER_ADDRESS);
    InetAddress inetAddress;
    try {
      inetAddress = InetAddresses.forString(ipParam.get());
    } catch (IllegalArgumentException e) {
      throw new BadRequestException("Invalid value of ip parameter");
    }
    results = searchByIp(inetAddress);
  }
  if (results.nameserverSearchResults().isEmpty()) {
    throw new NotFoundException("No nameservers found");
  }
  return results;
}
 
Example #23
Source File: MailboxFactory.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MailboxId computeMailboxId() {
    int idCount = Booleans.countTrue(id.isPresent(), mailboxMetaData.isPresent());
    Preconditions.checkState(idCount == 1, "You need exactly one 'id' 'mailboxMetaData'");
    return id.or(
        () -> mailboxMetaData.map(MailboxMetaData::getId))
        .get();
}
 
Example #24
Source File: QueryBuilder.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Adds a predicate for the specified boolean property values and operator. */
private String createMultipleValuesPredicate(boolean[] values, String operator) {
  return String.format(
      "%s %s [%s]",
      field,
      operator,
      Joiner.on(", ")
          .join(Lists.transform(Booleans.asList(values), Functions.toStringFunction())));
}
 
Example #25
Source File: BitListTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void checkReverseTiny() {
    BitList bl = BitList.newInstance(true, false);
    Assert.assertEquals(Booleans.asList(bl.reversed().asArray()), Booleans.asList(false, true));
    Assert.assertEquals(bl.intValue(), 1);
    Assert.assertEquals(bl.reversed().intValue(), 2);
    Assert.assertEquals(bl.reversed().reversed(), bl);
}
 
Example #26
Source File: BooleanDatum.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(Datum datum) {
  switch (datum.kind()) {
  case BOOLEAN:
    return Booleans.compare(val, datum.asBool());
  default:
    throw new InvalidOperationException(datum.type());
  }
}
 
Example #27
Source File: CompilationUnitImpl.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
private Object toArrayOfType(final Iterable<?> iterable, final Class<?> componentType) {
  Collection<?> _xifexpression = null;
  if ((iterable instanceof Collection<?>)) {
    _xifexpression = ((Collection<?>)iterable);
  } else {
    _xifexpression = IterableExtensions.toList(iterable);
  }
  final Collection<?> collection = _xifexpression;
  Object _switchResult = null;
  boolean _matched = false;
  if (Objects.equal(componentType, int.class)) {
    _matched=true;
    _switchResult = Ints.toArray(((List<Integer>) collection));
  }
  if (!_matched) {
    if (Objects.equal(componentType, long.class)) {
      _matched=true;
      _switchResult = Longs.toArray(((List<Long>) collection));
    }
  }
  if (!_matched) {
    if (Objects.equal(componentType, char.class)) {
      _matched=true;
      _switchResult = Chars.toArray(((List<Character>) collection));
    }
  }
  if (!_matched) {
    if (Objects.equal(componentType, boolean.class)) {
      _matched=true;
      _switchResult = Booleans.toArray(((List<Boolean>) collection));
    }
  }
  if (!_matched) {
    if (Objects.equal(componentType, byte.class)) {
      _matched=true;
      _switchResult = Bytes.toArray(((List<Byte>) collection));
    }
  }
  if (!_matched) {
    if (Objects.equal(componentType, short.class)) {
      _matched=true;
      _switchResult = Shorts.toArray(((List<Short>) collection));
    }
  }
  if (!_matched) {
    if (Objects.equal(componentType, float.class)) {
      _matched=true;
      _switchResult = Floats.toArray(((List<Float>) collection));
    }
  }
  if (!_matched) {
    if (Objects.equal(componentType, double.class)) {
      _matched=true;
      _switchResult = Doubles.toArray(((List<Double>) collection));
    }
  }
  if (!_matched) {
    _switchResult = Iterables.<Object>toArray(collection, ((Class<Object>) componentType));
  }
  return _switchResult;
}
 
Example #28
Source File: ComparisonChain.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public ComparisonChain compareTrueFirst(boolean left, boolean right) {
  return classify(Booleans.compare(right, left)); // reversed
}
 
Example #29
Source File: RdapDomainSearchAction.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/**
 * Parses the parameters and calls the appropriate search function.
 *
 * <p>The RDAP spec allows for domain search by domain name, nameserver name or nameserver IP.
 */
@Override
public DomainSearchResponse getSearchResponse(boolean isHeadRequest) {
  // RDAP syntax example: /rdap/domains?name=exam*.com.
  if (Booleans.countTrue(nameParam.isPresent(), nsLdhNameParam.isPresent(), nsIpParam.isPresent())
      != 1) {
    throw new BadRequestException(
        "You must specify either name=XXXX, nsLdhName=YYYY or nsIp=ZZZZ");
  }
  DomainSearchResponse results;
  if (nameParam.isPresent()) {
    metricInformationBuilder.setSearchType(SearchType.BY_DOMAIN_NAME);
    // syntax: /rdap/domains?name=exam*.com
    results =
        searchByDomainName(
            recordWildcardType(
                RdapSearchPattern.createFromLdhOrUnicodeDomainName(nameParam.get())));
  } else if (nsLdhNameParam.isPresent()) {
    metricInformationBuilder.setSearchType(SearchType.BY_NAMESERVER_NAME);
    // syntax: /rdap/domains?nsLdhName=ns1.exam*.com
    // RFC 7482 appears to say that Unicode domains must be specified using punycode when
    // passed to nsLdhName, so IDN.toASCII is not called here.
    results =
        searchByNameserverLdhName(
            recordWildcardType(RdapSearchPattern.createFromLdhDomainName(nsLdhNameParam.get())));
  } else {
    metricInformationBuilder.setSearchType(SearchType.BY_NAMESERVER_ADDRESS);
    metricInformationBuilder.setWildcardType(WildcardType.NO_WILDCARD);
    metricInformationBuilder.setPrefixLength(nsIpParam.get().length());
    // syntax: /rdap/domains?nsIp=1.2.3.4
    InetAddress inetAddress;
    try {
      inetAddress = InetAddresses.forString(nsIpParam.get());
    } catch (IllegalArgumentException e) {
      throw new BadRequestException("Invalid value of nsIp parameter");
    }
    results = searchByNameserverIp(inetAddress);
  }
  if (results.domainSearchResults().isEmpty()) {
    throw new NotFoundException("No domains found");
  }
  return results;
}
 
Example #30
Source File: Quicksortables.java    From util with Apache License 2.0 4 votes vote down vote up
public static int compare(boolean[] a, int i, int j) {
    return Booleans.compare(a[i], a[j]);
}