Java Code Examples for com.google.common.primitives.Primitives

The following examples show how to use com.google.common.primitives.Primitives. These examples are extracted from open source projects. 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 Project: presto   Source File: ArrayReduceFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    Type inputType = boundVariables.getTypeVariable("T");
    Type intermediateType = boundVariables.getTypeVariable("S");
    Type outputType = boundVariables.getTypeVariable("R");
    MethodHandle methodHandle = METHOD_HANDLE.bindTo(inputType);
    return new ScalarFunctionImplementation(
            true,
            ImmutableList.of(
                    valueTypeArgumentProperty(RETURN_NULL_ON_NULL),
                    valueTypeArgumentProperty(USE_BOXED_TYPE),
                    functionTypeArgumentProperty(BinaryFunctionInterface.class),
                    functionTypeArgumentProperty(UnaryFunctionInterface.class)),
            methodHandle.asType(
                    methodHandle.type()
                            .changeParameterType(1, Primitives.wrap(intermediateType.getJavaType()))
                            .changeReturnType(Primitives.wrap(outputType.getJavaType()))));
}
 
Example 2
Source Project: buck   Source File: BuckStarlarkParam.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param parameter the parameter type class
 * @param namedParameter the name of the parameter, if any
 * @param defaultSkylarkValue the string represetnation of the default skylark value
 * @param noneable whether this parameter can accept `None`
 * @return an instance of the skylark annotation representing a parameter of the given type and
 *     name
 */
static BuckStarlarkParam fromParam(
    Class<?> parameter,
    @Nullable String namedParameter,
    @Nullable String defaultSkylarkValue,
    boolean noneable) {
  if (namedParameter == null) {
    namedParameter = "";
  }
  if (defaultSkylarkValue == null) {
    defaultSkylarkValue = "";
  }
  Class<?> type = parameter;
  if (type.isPrimitive()) {
    type = Primitives.wrap(type);
  }
  return new BuckStarlarkParam(namedParameter, type, defaultSkylarkValue, noneable);
}
 
Example 3
Source Project: presto   Source File: TryCastFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    Type fromType = boundVariables.getTypeVariable("F");
    Type toType = boundVariables.getTypeVariable("T");

    Class<?> returnType = Primitives.wrap(toType.getJavaType());

    // the resulting method needs to return a boxed type
    ResolvedFunction resolvedFunction = metadata.getCoercion(fromType, toType);
    MethodHandle coercion = metadata.getScalarFunctionInvoker(resolvedFunction, Optional.empty()).getMethodHandle();
    coercion = coercion.asType(methodType(returnType, coercion.type()));

    MethodHandle exceptionHandler = dropArguments(constant(returnType, null), 0, RuntimeException.class);
    MethodHandle tryCastHandle = catchException(coercion, RuntimeException.class, exceptionHandler);

    boolean nullable = metadata.getFunctionMetadata(resolvedFunction).getArgumentDefinitions().get(0).isNullable();
    List<ArgumentProperty> argumentProperties = ImmutableList.of(nullable ? valueTypeArgumentProperty(USE_BOXED_TYPE) : valueTypeArgumentProperty(RETURN_NULL_ON_NULL));
    return new ScalarFunctionImplementation(true, argumentProperties, tryCastHandle);
}
 
Example 4
Source Project: buck   Source File: ValueTypeInfoFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A simple type includes no input/output path/data and is either a very simple type (primitives,
 * strings, etc) or one of the supported generic types composed of other simple types.
 */
static boolean isSimpleType(Type type) {
  if (type instanceof Class) {
    Class<?> rawClass = Primitives.wrap((Class<?>) type);
    // These types need no processing for
    return rawClass.equals(String.class)
        || rawClass.equals(Character.class)
        || rawClass.equals(Boolean.class)
        || rawClass.equals(Byte.class)
        || rawClass.equals(Short.class)
        || rawClass.equals(Integer.class)
        || rawClass.equals(Long.class)
        || rawClass.equals(Float.class)
        || rawClass.equals(Double.class)
        || rawClass.equals(OptionalInt.class);
  } else if (type instanceof WildcardType) {
    WildcardType wildcardType = (WildcardType) type;
    Type[] upperBounds = wildcardType.getUpperBounds();
    Preconditions.checkState(upperBounds.length == 1);
    return false;
  }
  return false;
}
 
Example 5
Source Project: presto   Source File: ScalarFunctionAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private static MethodHandle boxedToNullFlagFilter(Class<?> argumentType)
{
    // Start with identity
    MethodHandle handle = identity(argumentType);
    // if argument is a primitive, box it
    if (Primitives.isWrapperType(argumentType)) {
        handle = explicitCastArguments(handle, handle.type().changeParameterType(0, Primitives.unwrap(argumentType)));
    }
    // Add boolean null flag
    handle = dropArguments(handle, 1, boolean.class);
    // if flag is true, return null, otherwise invoke identity
    return guardWithTest(
            isTrueNullFlag(handle.type(), 0),
            returnNull(handle.type()),
            handle);
}
 
Example 6
Source Project: business   Source File: MethodMatcher.java    License: Mozilla Public License 2.0 6 votes vote down vote up
private static boolean checkParameterTypes(Type[] parameterTypes, Object[] args) {
    for (int i = 0; i < args.length; i++) {
        Object object = args[i];
        Type parameterType = parameterTypes[i];
        if (object != null) {
            Class<?> objectType = object.getClass();
            Class<?> unWrapPrimitive = null;
            if (Primitives.isWrapperType(objectType)) {
                unWrapPrimitive = Primitives.unwrap(objectType);
            }
            if (!(((Class<?>) parameterType).isAssignableFrom(
                    objectType) || (unWrapPrimitive != null && ((Class<?>) parameterType).isAssignableFrom(
                    unWrapPrimitive)))) {
                return false;
            }
        }
    }
    return true;
}
 
Example 7
Source Project: presto   Source File: ExpressionInterpreter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Object visitLambdaExpression(LambdaExpression node, Object context)
{
    if (optimize) {
        // TODO: enable optimization related to lambda expression
        // A mechanism to convert function type back into lambda expression need to exist to enable optimization
        return node;
    }

    Expression body = node.getBody();
    List<String> argumentNames = node.getArguments().stream()
            .map(LambdaArgumentDeclaration::getName)
            .map(Identifier::getValue)
            .collect(toImmutableList());
    FunctionType functionType = (FunctionType) expressionTypes.get(NodeRef.<Expression>of(node));
    checkArgument(argumentNames.size() == functionType.getArgumentTypes().size());

    return generateVarArgsToMapAdapter(
            Primitives.wrap(functionType.getReturnType().getJavaType()),
            functionType.getArgumentTypes().stream()
                    .map(Type::getJavaType)
                    .map(Primitives::wrap)
                    .collect(toImmutableList()),
            argumentNames,
            map -> process(body, new LambdaSymbolResolver(map)));
}
 
Example 8
Source Project: auto   Source File: AutoAnnotationProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the wrapper types ({@code Integer.class} etc) that are used in collection parameters
 * like {@code List<Integer>}. This is needed because we will emit a helper method for each such
 * type, for example to convert {@code Collection<Integer>} into {@code int[]}.
 */
private Set<Class<?>> wrapperTypesUsedInCollections(ExecutableElement method) {
  TypeElement javaUtilCollection = elementUtils.getTypeElement(Collection.class.getName());
  ImmutableSet.Builder<Class<?>> usedInCollections = ImmutableSet.builder();
  for (Class<?> wrapper : Primitives.allWrapperTypes()) {
    DeclaredType collectionOfWrapper =
        typeUtils.getDeclaredType(javaUtilCollection, getTypeMirror(wrapper));
    for (VariableElement parameter : method.getParameters()) {
      if (typeUtils.isAssignable(parameter.asType(), collectionOfWrapper)) {
        usedInCollections.add(wrapper);
        break;
      }
    }
  }
  return usedInCollections.build();
}
 
Example 9
Source Project: presto   Source File: ValueBuffer.java    License: Apache License 2.0 6 votes vote down vote up
private static Object normalizeValue(Type type, @Nullable Object value)
{
    if (value == null) {
        return value;
    }

    Class<?> javaType = type.getJavaType();
    if (javaType.isPrimitive()) {
        checkArgument(Primitives.wrap(javaType).isInstance(value), "Type %s incompatible with %s", type, value);
        return value;
    }
    if (javaType == Slice.class) {
        if (value instanceof Slice) {
            return value;
        }
        if (value instanceof String) {
            return utf8Slice(((String) value));
        }
        if (value instanceof byte[]) {
            return wrappedBuffer((byte[]) value);
        }
    }
    throw new IllegalArgumentException(format("Type %s incompatible with %s", type, value));
}
 
Example 10
@Override
public void addChild(TupleFilter child) {
    if (child instanceof ColumnTupleFilter || child instanceof BuiltInFunctionTupleFilter) {
        columnContainerFilter = child;
        colPosition = methodParams.size();
        methodParams.add(null);
    } else if (child instanceof ConstantTupleFilter) {
        this.constantTupleFilter = (ConstantTupleFilter) child;
        Serializable constVal = (Serializable) child.getValues().iterator().next();
        try {
            constantPosition = methodParams.size();
            Class<?> clazz = Primitives.wrap(method.getParameterTypes()[methodParams.size()]);
            if (!Primitives.isWrapperType(clazz))
                methodParams.add(constVal);
            else
                methodParams.add((Serializable) clazz
                        .cast(clazz.getDeclaredMethod("valueOf", String.class).invoke(null, constVal)));
        } catch (Exception e) {
            logger.warn("Reflection failed for methodParams. ", e);
            isValidFunc = false;
        }
    }
    super.addChild(child);
}
 
Example 11
Source Project: Lemur   Source File: Tweens.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("unchecked")        
private static Method findMethod( Class type, String name, Object... args ) {
    for( Method m : type.getDeclaredMethods() ) {
        if( !Objects.equals(m.getName(), name) ) {
            continue;
        }
        Class[] paramTypes = m.getParameterTypes();
        if( paramTypes.length != args.length ) {
            continue;
        }
        int matches = 0;
        for( int i = 0; i < args.length; i++ ) {
            if( paramTypes[i].isInstance(args[i]) 
                || Primitives.wrap(paramTypes[i]).isInstance(args[i]) ) {
                matches++;
            }    
        }
        if( matches == args.length ) {
            return m;
        }                
    }
    if( type.getSuperclass() != null ) {
        return findMethod(type.getSuperclass(), name, args);
    }
    return null;
}
 
Example 12
Source Project: Akatsuki   Source File: SupportedTypeIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBoxedPrimitives() {
	// boxed primitives cannot be null otherwise we get NPE when unboxing
	ImmutableMap<Class<?>, String> defaultValueMap = ImmutableMap.<Class<?>, String> builder()
			.put(Byte.class, "0").put(Short.class, "0").put(Integer.class, "0")
			.put(Long.class, "0L").put(Float.class, "0.0F").put(Double.class, "0.0D")
			.put(Character.class, "\'a\'").put(Boolean.class, "false").build();

	RetainedTestField[] fields = defaultValueMap.entrySet()
			.stream().map(ent -> new RetainedTestField(ent.getKey(),
					"_" + ent.getKey().getSimpleName(), ent.getValue()))
			.toArray(RetainedTestField[]::new);
	// comparison between primitives and boxed primitives does not work,
	// manually wrap it
	testTypes(ALWAYS, (field, type, arguments) -> type.isPrimitive()
			&& field.clazz == Primitives.wrap(type), f->1, fields);

}
 
Example 13
Source Project: guice-persist-orient   Source File: RecordConverter.java    License: MIT License 6 votes vote down vote up
/**
 * @param result     orient record
 * @param targetType target conversion type
 * @param converter  converter object
 * @param <T>        target conversion type
 * @return converted object
 * @throws ResultConversionException if conversion is impossible
 */
@SuppressWarnings("unchecked")
public <T> T convert(final Object result, final Class<T> targetType, final ResultConverter converter) {
    // wrap primitive, because result will always be object
    final Class<T> target = Primitives.wrap(targetType);
    // do manual conversion to other types if required (usually this will be done automatically by connection
    // object, but async and live callbacks will always return documents)
    T res = tryConversion(result, target);
    if (res != null) {
        return res;
    }

    // use converter
    final ResultDescriptor desc = new ResultDescriptor();
    // support void case for more universal usage
    desc.returnType = target.equals(Void.class) ? ResultType.VOID : ResultType.PLAIN;
    desc.entityType = target;
    desc.expectType = target;
    desc.entityDbType = ORecord.class.isAssignableFrom(target) ? DbType.DOCUMENT : DbType.UNKNOWN;
    res = (T) converter.convert(desc, result);
    ResultUtils.check(res, target);
    return res;
}
 
Example 14
Source Project: api-compiler   Source File: Values.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether a value is 'true', where true is interpreted depending on the values
 * type.
 */
@SuppressWarnings("rawtypes")
static boolean isTrue(Object v1) {
  if (v1 instanceof Number) {
    // For numbers, compare with  the default value (zero), which we obtain by
    // creating an array.
    return !Array.get(Array.newInstance(Primitives.unwrap(v1.getClass()), 1), 0).equals(v1);
  }
  if (v1 instanceof Boolean) {
    return (Boolean) v1;
  }
  if (v1 instanceof Doc) {
    return !((Doc) v1).isWhitespace();
  }
  if (v1 instanceof String) {
    return !Strings.isNullOrEmpty((String) v1);
  }
  if (v1 instanceof Iterable) {
    return ((Iterable) v1).iterator().hasNext();
  }
  return false;
}
 
Example 15
Source Project: monasca-common   Source File: Serialization.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@code node} deserialized to an instance of <T> with the implementation of <T>
 * being selected from the registered targets for the node's root key.
 * 
 * @throws IllegalArgumentException if {@code node} does not contain a single root key
 * @throws IllegalStateException if no target type has been registered for the {@code node}'s root
 *           key
 * @throws RuntimeException if deserialization fails
 */
public static <T> T fromJson(JsonNode node) {
  Preconditions.checkArgument(node.size() == 1, "The node must contain a single root key: %s",
      node);

  String rootKey = node.fieldNames().next();
  @SuppressWarnings("unchecked")
  Class<T> targetType = (Class<T>) targetTypes.get(rootKey);
  if (targetType == null)
    throw new IllegalStateException("No target type is registered for the root key " + rootKey);

  if (targetType.isPrimitive() || Primitives.isWrapperType(targetType)) {
    try {
      return rootMapper.reader(targetType).readValue(node);
    } catch (IOException e) {
      throw Exceptions.uncheck(e, "Failed to deserialize json: {}", node);
    }
  } else {
    T object = Injector.getInstance(targetType);
    injectMembers(object, node);
    return object;
  }
}
 
Example 16
Source Project: JGiven   Source File: JGivenMethodRule.java    License: Apache License 2.0 6 votes vote down vote up
private static List<Object> getTypeMatchingValuesInOrderOf( Class<?>[] expectedClasses, List<Object> values ) {
    List<Object> valuesCopy = Lists.newArrayList( values );
    List<Object> result = new ArrayList<Object>();
    for( Class<?> argumentClass : expectedClasses ) {
        for( Iterator<Object> iterator = valuesCopy.iterator(); iterator.hasNext(); ) {
            Object value = iterator.next();
            if( Primitives.wrap( argumentClass ).isInstance( value ) ) {
                result.add( value );
                iterator.remove();
                break;
            }
        }
    }
    if( result.size() < expectedClasses.length ) {
        log.warn( format( "Couldn't find matching values in '%s' for expected classes '%s',", valuesCopy,
            Arrays.toString( expectedClasses ) ) );
    }
    return result;
}
 
Example 17
Source Project: java-flagz   Source File: ContainerFlagField.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected static <X> X itemFromString(String value, Class<X> clazz, Flag flag)
    throws FlagException {
  // In case we get a primitive type (e.g. from Scala), get the boxed version to know
  // how to serialize.
  clazz = Primitives.wrap(clazz);
  if (Number.class.isAssignableFrom(clazz)) {
    return clazz.cast(PrimitiveFlagField.NumberFlagField.fromString(value, clazz, flag));
  } else if (Boolean.class.isAssignableFrom(clazz)) {
    return clazz.cast(Boolean.valueOf(value));
  } else if (String.class.isAssignableFrom(clazz)) {
    return clazz.cast(value);
  } else if (clazz.isEnum()) {
    return (X) PrimitiveFlagField.EnumFlagField.fromString(value, (Class<Enum>) clazz, flag);
  }
  throw new FlagException.UnsupportedType(flag, clazz);
}
 
Example 18
Source Project: selenium   Source File: AnnotatedConfig.java    License: Apache License 2.0 6 votes vote down vote up
private String getSingleValue(Object value) {
  if (value == null) {
    return null;
  }

  if (value instanceof Map) {
    throw new ConfigException("Map fields may not be used for configuration: " + value);
  }

  if (value instanceof Collection) {
    throw new ConfigException("Collection fields may not be used for configuration: " + value);
  }

  if (Boolean.FALSE.equals(value) && !Primitives.isWrapperType(value.getClass())) {
    return null;
  }

  if (value instanceof Number && ((Number) value).floatValue() == 0f) {
    return null;
  }

  return String.valueOf(value);
}
 
Example 19
Source Project: nomulus   Source File: DiffUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a formatted listing of Set contents, using a single line format if all elements are
 * wrappers of primitive types or Strings, and a multiline (one object per line) format if they
 * are not.
 */
private static String formatSetContents(Set<?> set) {
  for (Object obj : set) {
    if (!Primitives.isWrapperType(obj.getClass()) && !(obj instanceof String)) {
      return "\n        " + Joiner.on(",\n        ").join(set);
    }
  }
  return " " + set;
}
 
Example 20
Source Project: SkyblockAddons   Source File: Reflection.java    License: MIT License 5 votes vote down vote up
/**
 * Converts any primitive classes in the given classes to their primitive types.
 *
 * @param types The classes to convert.
 * @return Converted class types.
 */
public static Class<?>[] toPrimitiveTypeArray(Class<?>[] types) {
	Class<?>[] newTypes = new Class<?>[types != null ? types.length : 0];

	for (int i = 0; i < newTypes.length; i++)
		newTypes[i] = (types[i] != null ? Primitives.unwrap(types[i]) : null);

	return newTypes;
}
 
Example 21
Source Project: SkyblockAddons   Source File: Reflection.java    License: MIT License 5 votes vote down vote up
/**
 * Converts any primitive classes in the given objects to their primitive types.
 *
 * @param objects The objects to convert.
 * @return Converted class types.
 */
public static Class<?>[] toPrimitiveTypeArray(Object[] objects) {
	Class<?>[] newTypes = new Class<?>[objects != null ? objects.length : 0];

	for (int i = 0; i < newTypes.length; i++)
		newTypes[i] = (objects[i] != null ? Primitives.unwrap(objects[i].getClass()) : null);

	return newTypes;
}
 
Example 22
Source Project: presto   Source File: AppendingRecordSet.java    License: Apache License 2.0 5 votes vote down vote up
public AppendingRecordSet(RecordSet delegate, List<Object> appendedValues, List<Type> appendedTypes)
{
    this.delegate = requireNonNull(delegate, "delegate is null");
    this.appendedValues = new ArrayList<>(requireNonNull(appendedValues, "appendedValues is null")); // May contain null elements
    this.appendedTypes = ImmutableList.copyOf(requireNonNull(appendedTypes, "appendedTypes is null"));
    checkArgument(appendedValues.size() == appendedTypes.size(), "appendedValues must have the same size as appendedTypes");
    for (int i = 0; i < appendedValues.size(); i++) {
        Object value = appendedValues.get(i);
        if (value != null) {
            checkArgument(Primitives.wrap(appendedTypes.get(i).getJavaType()).isInstance(value), "Object value does not match declared type");
        }
    }
}
 
Example 23
Source Project: presto   Source File: ApplyFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    Type argumentType = boundVariables.getTypeVariable("T");
    Type returnType = boundVariables.getTypeVariable("U");
    return new ScalarFunctionImplementation(
            true,
            ImmutableList.of(
                    valueTypeArgumentProperty(USE_BOXED_TYPE),
                    functionTypeArgumentProperty(UnaryFunctionInterface.class)),
            METHOD_HANDLE.asType(
                    METHOD_HANDLE.type()
                            .changeReturnType(Primitives.wrap(returnType.getJavaType()))
                            .changeParameterType(0, Primitives.wrap(argumentType.getJavaType()))));
}
 
Example 24
Source Project: presto   Source File: ArrayConstructor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    ImmutableList.Builder<Class<?>> builder = ImmutableList.builder();
    Type type = boundVariables.getTypeVariable("E");
    for (int i = 0; i < arity; i++) {
        if (type.getJavaType().isPrimitive()) {
            builder.add(Primitives.wrap(type.getJavaType()));
        }
        else {
            builder.add(type.getJavaType());
        }
    }
    ImmutableList<Class<?>> stackTypes = builder.build();
    Class<?> clazz = generateArrayConstructor(stackTypes, type);
    MethodHandle methodHandle;
    try {
        Method method = clazz.getMethod("arrayConstructor", stackTypes.toArray(new Class<?>[stackTypes.size()]));
        methodHandle = lookup().unreflect(method);
    }
    catch (ReflectiveOperationException e) {
        throw new RuntimeException(e);
    }
    return new ScalarFunctionImplementation(
            false,
            nCopies(stackTypes.size(), valueTypeArgumentProperty(USE_BOXED_TYPE)),
            methodHandle);
}
 
Example 25
Source Project: presto   Source File: ParametricScalarImplementation.java    License: Apache License 2.0 5 votes vote down vote up
private ParametricScalarImplementation(
        Signature signature,
        List<Optional<Class<?>>> argumentNativeContainerTypes,
        Map<String, Class<?>> specializedTypeParameters,
        List<ParametricScalarImplementationChoice> choices,
        Class<?> returnContainerType)
{
    this.signature = requireNonNull(signature, "signature is null");
    this.argumentNativeContainerTypes = ImmutableList.copyOf(requireNonNull(argumentNativeContainerTypes, "argumentNativeContainerTypes is null"));
    this.specializedTypeParameters = ImmutableMap.copyOf(requireNonNull(specializedTypeParameters, "specializedTypeParameters is null"));
    this.choices = requireNonNull(choices, "choices is null");
    checkArgument(!choices.isEmpty(), "choices is empty");
    this.returnNativeContainerType = requireNonNull(returnContainerType, "return native container type is null");

    for (Class<?> specializedJavaType : specializedTypeParameters.values()) {
        checkArgument(specializedJavaType != Object.class, "specializedTypeParameter must not contain Object.class entries");
        checkArgument(!Primitives.isWrapperType(specializedJavaType), "specializedTypeParameter must not contain boxed primitive types");
    }

    ParametricScalarImplementationChoice defaultChoice = choices.get(0);
    boolean expression = defaultChoice.getArgumentProperties().stream()
            .noneMatch(argumentProperty -> argumentProperty.getArgumentType() == VALUE_TYPE && argumentProperty.getNullConvention() == BLOCK_AND_POSITION);
    checkArgument(expression, "default choice cannot use the BLOCK_AND_POSITION calling convention: %s", signature);

    this.nullable = defaultChoice.isNullable();
    checkArgument(choices.stream().allMatch(choice -> choice.isNullable() == nullable), "all choices must have the same nullable flag: %s", signature);

    argumentDefinitions = defaultChoice.getArgumentProperties().stream()
            .map(argumentProperty -> argumentProperty.getArgumentType() == VALUE_TYPE && argumentProperty.getNullConvention() != RETURN_NULL_ON_NULL)
            .map(FunctionArgumentDefinition::new)
            .collect(toImmutableList());
    checkArgument(
            choices.stream().allMatch(choice -> matches(argumentDefinitions, choice.getArgumentProperties())),
            "all choices must have the same nullable parameter flags: %s",
            signature);
}
 
Example 26
Source Project: selenium   Source File: OpenTelemetrySpan.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Span setAttribute(String key, Number value) {
  Require.nonNull("Key", key);
  Require.nonNull("Value", value);

  Class<? extends Number> unwrapped = Primitives.unwrap(value.getClass());
  if (double.class.equals(unwrapped) || float.class.equals(unwrapped)) {
    span.setAttribute(key, value.doubleValue());
  } else {
    span.setAttribute(key, value.longValue());
  }

  return this;
}
 
Example 27
Source Project: presto   Source File: MapElementAtFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, Metadata metadata)
{
    Type keyType = boundVariables.getTypeVariable("K");
    Type valueType = boundVariables.getTypeVariable("V");

    MethodHandle keyEqualsMethod = metadata.getScalarFunctionInvoker(metadata.resolveOperator(EQUAL, ImmutableList.of(keyType, keyType)), Optional.empty()).getMethodHandle();

    MethodHandle methodHandle;
    if (keyType.getJavaType() == boolean.class) {
        methodHandle = METHOD_HANDLE_BOOLEAN;
    }
    else if (keyType.getJavaType() == long.class) {
        methodHandle = METHOD_HANDLE_LONG;
    }
    else if (keyType.getJavaType() == double.class) {
        methodHandle = METHOD_HANDLE_DOUBLE;
    }
    else if (keyType.getJavaType() == Slice.class) {
        methodHandle = METHOD_HANDLE_SLICE;
    }
    else {
        methodHandle = METHOD_HANDLE_OBJECT;
    }
    methodHandle = methodHandle.bindTo(keyEqualsMethod).bindTo(keyType).bindTo(valueType);
    methodHandle = methodHandle.asType(methodHandle.type().changeReturnType(Primitives.wrap(valueType.getJavaType())));

    return new ScalarFunctionImplementation(
            true,
            ImmutableList.of(
                    valueTypeArgumentProperty(RETURN_NULL_ON_NULL),
                    valueTypeArgumentProperty(RETURN_NULL_ON_NULL)),
            methodHandle);
}
 
Example 28
Source Project: presto   Source File: InvokeFunctionBytecodeExpression.java    License: Apache License 2.0 5 votes vote down vote up
private InvokeFunctionBytecodeExpression(
        Scope scope,
        CallSiteBinder binder,
        ResolvedFunction resolvedFunction,
        Metadata metadata,
        List<BytecodeExpression> parameters)
{
    super(type(Primitives.unwrap(metadata.getType(resolvedFunction.getSignature().getReturnType()).getJavaType())));

    this.invocation = generateInvocation(scope, resolvedFunction, metadata, parameters.stream().map(BytecodeNode.class::cast).collect(toImmutableList()), binder);
    this.oneLineDescription = resolvedFunction.getSignature().getName() + "(" + Joiner.on(", ").join(parameters) + ")";
}
 
Example 29
Source Project: presto   Source File: BytecodeUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static BytecodeBlock unboxPrimitiveIfNecessary(Scope scope, Class<?> boxedType)
{
    BytecodeBlock block = new BytecodeBlock();
    LabelNode end = new LabelNode("end");
    Class<?> unboxedType = Primitives.unwrap(boxedType);
    Variable wasNull = scope.getVariable("wasNull");

    if (unboxedType.isPrimitive()) {
        LabelNode notNull = new LabelNode("notNull");
        block.dup(boxedType)
                .ifNotNullGoto(notNull)
                .append(wasNull.set(constantTrue()))
                .comment("swap boxed null with unboxed default")
                .pop(boxedType)
                .pushJavaDefault(unboxedType)
                .gotoLabel(end)
                .visitLabel(notNull)
                .append(unboxPrimitive(unboxedType));
    }
    else {
        block.dup(boxedType)
                .ifNotNullGoto(end)
                .append(wasNull.set(constantTrue()));
    }
    block.visitLabel(end);

    return block;
}
 
Example 30
Source Project: wicket-orientdb   Source File: AbstractPrototyper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method for obtaining default value of required property
 * @param propName name of a property
 * @param returnType type of a property
 * @return default value for particular property
 */
protected Object getDefaultValue(String propName, Class<?> returnType)
{
	Object ret = null;
	if(returnType.isPrimitive())
	{
		if(returnType.equals(boolean.class))
		{
			return false;
		}
		else if(returnType.equals(char.class))
		{
			return '\0';
		}
		else
		{
			try
			{
				Class<?> wrapperClass = Primitives.wrap(returnType);
				return wrapperClass.getMethod("valueOf", String.class).invoke(null, "0");
			} catch (Throwable e)
			{
				throw new WicketRuntimeException("Can't create default value for '"+propName+"' which should have type '"+returnType.getName()+"'");
			} 
		}
	}
	return ret;
}