com.google.common.base.Defaults Java Examples

The following examples show how to use com.google.common.base.Defaults. 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: TestScalarFunctionAdapter.java    From presto with Apache License 2.0 6 votes vote down vote up
private static void assertArgumentValue(
        Object actualValue,
        InvocationArgumentConvention argumentConvention,
        Type argumentType,
        boolean isNull)
{
    if (!isNull) {
        assertArgumentValue(actualValue, getTestValue(argumentType));
        return;
    }

    if (argumentConvention != NEVER_NULL) {
        assertNull(actualValue);
        return;
    }

    // the only way for a never null to be called with a null is for the undefined value null convention
    // Currently, for primitives, the value is the java default, but for all other types it could be anything
    if (argumentType.getJavaType().isPrimitive()) {
        assertArgumentValue(actualValue, Defaults.defaultValue(argumentType.getJavaType()));
    }
}
 
Example #2
Source File: ForwardingChannelBuilderTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void allBuilderMethodsReturnThis() throws Exception {
  for (Method method : ManagedChannelBuilder.class.getDeclaredMethods()) {
    if (Modifier.isStatic(method.getModifiers()) || Modifier.isPrivate(method.getModifiers())) {
      continue;
    }
    if (method.getName().equals("build")) {
      continue;
    }
    Class<?>[] argTypes = method.getParameterTypes();
    Object[] args = new Object[argTypes.length];
    for (int i = 0; i < argTypes.length; i++) {
      args[i] = Defaults.defaultValue(argTypes[i]);
    }
    if (method.getName().equals("maxInboundMetadataSize")) {
      args[0] = 1; // an arbitrary positive number
    }

    Object returnedValue = method.invoke(testChannelBuilder, args);

    assertThat(returnedValue).isSameInstanceAs(testChannelBuilder);
  }
}
 
Example #3
Source File: InMemoryDataSetMetadataRepository.java    From data-prep with Apache License 2.0 6 votes vote down vote up
/**
 * this nullifies and resets transient values that are supposed not to be stored
 *
 * @param zeObject The object where non transient fields will be nullified.
 */
void resetTransientValues(Object zeObject) {
    if (zeObject != null) {
        Field[] fields = zeObject.getClass().getDeclaredFields();
        for (Field field : fields) {
            // ignore jacoco injected field
            if (Modifier.isTransient(field.getModifiers()) && !field.getName().endsWith("jacocoData")) { //$NON-NLS-1$
                Object defaultValue = Defaults.defaultValue(field.getType());
                field.setAccessible(true);
                try {
                    field.set(zeObject, defaultValue);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    LOG.error("failed to reset the transient field [" + field + "] before storage", e);
                }
            }
        }
    } // else null so do nothing
}
 
Example #4
Source File: JaxrsOperationGenerator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
protected void fillParameter(Swagger swagger, io.swagger.models.parameters.Parameter parameter, String parameterName,
    Type type, List<Annotation> annotations) {
  super.fillParameter(swagger, parameter, parameterName, type, annotations);

  if (!(parameter instanceof AbstractSerializableParameter)) {
    return;
  }

  if (!(type instanceof Class && ((Class) type).isPrimitive())) {
    return;
  }

  AbstractSerializableParameter<?> serializableParameter = (AbstractSerializableParameter<?>) parameter;
  if (serializableParameter.getDefault() == null && !parameter.getRequired()) {
    serializableParameter.setDefaultValue(String.valueOf(Defaults.defaultValue((Class<?>) type)));
  }
}
 
Example #5
Source File: HighwayCodec.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private static Map<String, Object> addPrimitiveTypeDefaultValues(Invocation invocation,
    Map<String, Object> swaggerArguments) {
  // proto buffer never serialize default values, put it back in provider
  if (invocation.getOperationMeta().getSwaggerProducerOperation() != null && !invocation.isEdge()) {
    List<Parameter> swaggerParameters = invocation.getOperationMeta().getSwaggerOperation()
        .getParameters();
    for (Parameter parameter : swaggerParameters) {
      if (swaggerArguments.get(parameter.getName()) == null) {
        Type type = invocation.getOperationMeta().getSwaggerProducerOperation()
            .getSwaggerParameterType(parameter.getName());
        if (type instanceof Class) {
          if (((Class) type).isPrimitive()) {
            swaggerArguments.put(parameter.getName(), Defaults.defaultValue((Class) type));
          }
        }
      }
    }
  }
  return swaggerArguments;
}
 
Example #6
Source File: ForwardingChannelBuilderTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void allBuilderMethodsReturnThis() throws Exception {
  for (Method method : ManagedChannelBuilder.class.getDeclaredMethods()) {
    if (Modifier.isStatic(method.getModifiers()) || Modifier.isPrivate(method.getModifiers())) {
      continue;
    }
    if (method.getName().equals("build")) {
      continue;
    }
    Class<?>[] argTypes = method.getParameterTypes();
    Object[] args = new Object[argTypes.length];
    for (int i = 0; i < argTypes.length; i++) {
      args[i] = Defaults.defaultValue(argTypes[i]);
    }
    if (method.getName().equals("maxInboundMetadataSize")) {
      args[0] = 1; // an arbitrary positive number
    }

    Object returnedValue = method.invoke(testChannelBuilder, args);

    assertThat(returnedValue).isSameAs(testChannelBuilder);
  }
}
 
Example #7
Source File: ConnectionConf.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Clears all fields that match a particular predicate. For all primitive types, the value is set
 * to zero. For object types, the value is set to null.
 *
 * @param predicate
 */
private void clear(Predicate<Field> predicate, boolean isSecret) {
  try {
    for(Field field : FieldUtils.getAllFields(getClass())) {
      if(predicate.apply(field)) {
        if (isSecret && field.getType().equals(String.class)) {
          final String value = (String) field.get(this);

          if (Strings.isNullOrEmpty(value)) {
            field.set(this, null);
          } else {
            field.set(this, USE_EXISTING_SECRET_VALUE);
          }
        } else {
          Object defaultValue = Defaults.defaultValue(field.getType());
          field.set(this, defaultValue);
        }
      }
    }
  } catch (IllegalAccessException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #8
Source File: Instances.java    From twill with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of the given using Unsafe. It also initialize all fields into default values.
 */
private static <T> T unsafeCreate(Class<T> clz) throws InvocationTargetException, IllegalAccessException {
  T instance = (T) UNSAFE_NEW_INSTANCE.invoke(UNSAFE, clz);

  for (TypeToken<?> type : TypeToken.of(clz).getTypes().classes()) {
    if (Object.class.equals(type.getRawType())) {
      break;
    }
    for (Field field : type.getRawType().getDeclaredFields()) {
      if (Modifier.isStatic(field.getModifiers())) {
        continue;
      }
      if (!field.isAccessible()) {
        field.setAccessible(true);
      }
      field.set(instance, Defaults.defaultValue(field.getType()));
    }
  }

  return instance;
}
 
Example #9
Source File: OstrichAccessors.java    From emodb with Apache License 2.0 6 votes vote down vote up
public static <S> PartitionContextValidator<S> newPartitionContextTest(final Class<S> ifc, final Class<? extends S> impl) {
    final PartitionContextSupplier supplier = new AnnotationPartitionContextSupplier(ifc, impl);
    return new PartitionContextValidator<S>() {
        @Override
        public S expect(final PartitionContext expected) {
            return Reflection.newProxy(ifc, new AbstractInvocationHandler() {
                @Override
                protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
                    PartitionContext actual = supplier.forCall(method, args);
                    assertEquals(actual, expected, "Expected=" + expected.asMap() + ", Actual=" + actual.asMap());
                    return Defaults.defaultValue(method.getReturnType());
                }
            });
        }
    };
}
 
Example #10
Source File: AbstractParamProcessor.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public AbstractParamProcessor(String paramPath, JavaType targetType, Object defaultValue, boolean required) {
  this.paramPath = paramPath;
  this.targetType = targetType;
  this.defaultValue = defaultValue;
  this.required = required;
  if (defaultValue == null &&
      targetType != null && targetType.getRawClass().isPrimitive()) {
    this.defaultValue = Defaults.defaultValue(targetType.getRawClass());
  }
}
 
Example #11
Source File: StorageEntityUtil.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
private static void validateField(
    String name,
    Object object,
    Field field,
    Set<Field> ignoredFields) {

  try {
    field.setAccessible(true);
    String fullName = name + "." + field.getName();
    Object fieldValue = field.get(object);
    boolean mustBeSet = !ignoredFields.contains(field);
    if (mustBeSet) {
      assertNotNull(fullName + " is null", fieldValue);
    }
    if (fieldValue != null) {
      if (Primitives.isWrapperType(fieldValue.getClass())) {
        // Special-case the mutable hash code field.
        if (mustBeSet && !fullName.endsWith("cachedHashCode")) {
          assertNotEquals(
              "Primitive value must not be default: " + fullName,
              Defaults.defaultValue(Primitives.unwrap(fieldValue.getClass())),
              fieldValue);
        }
      } else {
        assertFullyPopulated(fullName, fieldValue, ignoredFields);
      }
    }
  } catch (IllegalAccessException e) {
    throw Throwables.propagate(e);
  }
}
 
Example #12
Source File: JsonRpcServer.java    From simple-json-rpc with MIT License 5 votes vote down vote up
@Nullable
private Object getDefaultValue(@NotNull Class<?> type) {
    if (type == com.google.common.base.Optional.class) {
        // If it's Guava optional then handle it as an absent value
        return com.google.common.base.Optional.absent();
    } else if (type == java.util.Optional.class) {
        // If it's Java optional then handle it as an absent value
        return java.util.Optional.empty();
    } else if (type.isPrimitive()) {
        // If parameter is a primitive set the appropriate default value
        return Defaults.defaultValue(type);
    }
    return null;
}
 
Example #13
Source File: InMemoryDataSetMetadataRepositoryTest.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Test
public void testResetTransiantOnDatasetMatadataFavorites() {
    TransientTestObject obj = new TransientTestObject();
    inMemoryDataSetMetadataRepository.resetTransientValues(obj);
    // check it has been reset to the default value
    assertTrue(Defaults.defaultValue(boolean.class).equals(obj.zeBoolean));
    assertTrue(Defaults.defaultValue(char.class).equals(obj.zeChar));
    assertTrue(Defaults.defaultValue(byte.class).equals(obj.zeByte));
    assertTrue(Defaults.defaultValue(short.class).equals(obj.zeShort));
    assertTrue(Defaults.defaultValue(int.class).equals(obj.zeInt));
    assertTrue(Defaults.defaultValue(float.class).equals(obj.zeFloat));
    assertTrue(Defaults.defaultValue(double.class).equals(obj.zeDouble));
    assertTrue(obj.zeObject == Defaults.defaultValue(Object.class));// cause it is null
    assertTrue(Defaults.defaultValue(boolean.class).equals(TransientTestObject.zeStaticBoolean));
}
 
Example #14
Source File: DefaultProxySession.java    From atomix with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(Object object, Method method, Object[] args) throws Throwable {
  OperationId operationId = operations.get(method);
  if (operationId != null) {
    future.set(session.execute(PrimitiveOperation.operation(operationId, encode(args)))
        .thenApply(DefaultProxySession.this::decode));
  } else {
    throw new PrimitiveException("Unknown primitive operation: " + method.getName());
  }
  return Defaults.defaultValue(method.getReturnType());
}
 
Example #15
Source File: AbstractCloudSpannerResultSetTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
private Object createDefaultParamValue(Class<?> clazz) {
  if (clazz.isPrimitive())
    return Defaults.defaultValue(clazz);
  if (byte[].class.equals(clazz))
    return "FOO".getBytes();
  return null;
}
 
Example #16
Source File: FirebaseAuthTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeAfterAppDelete() throws Exception {
  FirebaseApp app = FirebaseApp.initializeApp(firebaseOptions, "testInvokeAfterAppDelete");
  FirebaseAuth auth = FirebaseAuth.getInstance(app);
  assertNotNull(auth);
  app.delete();

  for (Method method : auth.getClass().getDeclaredMethods()) {
    int modifiers = method.getModifiers();
    if (!Modifier.isPublic(modifiers) || Modifier.isStatic(modifiers)) {
      continue;
    }

    List<Object> parameters = new ArrayList<>(method.getParameterTypes().length);
    for (Class<?> parameterType : method.getParameterTypes()) {
      parameters.add(Defaults.defaultValue(parameterType));
    }
    try {
      method.invoke(auth, parameters.toArray());
      fail("No error thrown when invoking auth after deleting app; method: " + method.getName());
    } catch (InvocationTargetException expected) {
      String message = "FirebaseAuth instance is no longer alive. This happens when "
          + "the parent FirebaseApp instance has been deleted.";
      Throwable cause = expected.getCause();
      assertTrue(cause instanceof IllegalStateException);
      assertEquals(message, cause.getMessage());
    }
  }
}
 
Example #17
Source File: FirebaseAppTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static void invokePublicInstanceMethodWithDefaultValues(Object instance, Method method)
    throws InvocationTargetException, IllegalAccessException {
  List<Object> parameters = new ArrayList<>(method.getParameterTypes().length);
  for (Class<?> parameterType : method.getParameterTypes()) {
    parameters.add(Defaults.defaultValue(parameterType));
  }
  method.invoke(instance, parameters.toArray());
}
 
Example #18
Source File: Reflection.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * 具有一定兼容性的类型转换/切换
 * 将一个未知类型转化为你想要的那个类型,它会宽容地做转换,比如map映射成bean,bean映射成map
 * list的第一个元素映射成bean,list的第一个元素映射成map等等。
 * 如果入参是null,那么返回结果也是null
 *
 * @param nonCollectionType 目标类型,不允许是集合类型
 */
@SuppressWarnings("all")
private static <T> T toNonCollectionType(Object data, Class<T> nonCollectionType) {
    if (Collection.class.isAssignableFrom(nonCollectionType)) {
        throw new RuntimeException("API使用错误,本方法不支持将目标对象转为非集合类型");
    }
    if (data == null) {
        return Defaults.defaultValue(nonCollectionType);
    }
    if (data.getClass().isArray()) {
        data = ArrayUtil.toList(data);
    }
    if (data instanceof Collection) {
        Collection collection = (Collection) data;
        if (nonCollectionType == String.class) {
            return (T) JSON.toJSONString(collection);
        }
        if (collection.isEmpty()) {
            return null;
        }
        if (collection.size() >= 2) {
            LOG.warn(new Throwable(String.format("集合 【 %s 】  的元素个数不只一个,我们只取出第一个做转换", data)));
        }
        for (Object element : collection) {
            LOG.debug("集合的第一个元素会被转为目标类型");
            return transferNonCollection(element, nonCollectionType);
        }
    } else {
        return transferNonCollection(data, nonCollectionType);
    }
    throw castFailedException(data, nonCollectionType);
}
 
Example #19
Source File: FirebaseAppTest.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
private static void invokePublicInstanceMethodWithDefaultValues(Object instance, Method method)
    throws InvocationTargetException, IllegalAccessException {
  List<Object> parameters = new ArrayList<>(method.getParameterTypes().length);
  for (Class<?> parameterType : method.getParameterTypes()) {
    parameters.add(Defaults.defaultValue(parameterType));
  }
  method.invoke(instance, parameters.toArray());
}
 
Example #20
Source File: OutlineImpl.java    From datamill with ISC License 4 votes vote down vote up
@Override
public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {
    OutlineImpl.this.lastInvokedMethod.set(thisMethod.getName());
    return Defaults.defaultValue(thisMethod.getReturnType());
}
 
Example #21
Source File: TestScalarFunctionAdapter.java    From presto with Apache License 2.0 4 votes vote down vote up
private static List<Object> toCallArgumentValues(InvocationConvention callingConvention, BitSet nullArguments, Target target)
{
    List<Object> callArguments = new ArrayList<>();
    callArguments.add(target);
    for (int i = 0; i < callingConvention.getArgumentConventions().size(); i++) {
        Type argumentType = ARGUMENT_TYPES.get(i);
        boolean nullArgument = nullArguments.get(i);

        Object testValue;
        if (nullArgument) {
            testValue = null;
        }
        else {
            testValue = getTestValue(argumentType);
        }

        InvocationArgumentConvention argumentConvention = callingConvention.getArgumentConvention(i);
        switch (argumentConvention) {
            case NEVER_NULL:
                Verify.verify(testValue != null, "null can not be passed to a never null argument");
                callArguments.add(testValue);
                break;
            case BOXED_NULLABLE:
                callArguments.add(testValue);
                break;
            case NULL_FLAG:
                callArguments.add(testValue == null ? Defaults.defaultValue(argumentType.getJavaType()) : testValue);
                callArguments.add(testValue == null);
                break;
            case BLOCK_POSITION:
                BlockBuilder blockBuilder = argumentType.createBlockBuilder(null, 3);
                blockBuilder.appendNull();
                writeNativeValue(argumentType, blockBuilder, testValue);
                blockBuilder.appendNull();

                callArguments.add(blockBuilder.build());
                callArguments.add(1);
                break;
            default:
                throw new IllegalArgumentException("Unsupported argument convention: " + argumentConvention);
        }
    }
    return callArguments;
}