Java Code Examples for com.google.common.base.Defaults#defaultValue()

The following examples show how to use com.google.common.base.Defaults#defaultValue() . 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: 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 2
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 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: 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 5
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 6
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 7
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 8
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 9
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 10
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());
}