Java 类com.google.common.base.Defaults 实例源码

项目:firebase-admin-java    文件:FirebaseAuthTest.java   
@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());
    }
  }
}
项目:twill    文件:Instances.java   
/**
 * 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;
}
项目:emodb    文件:OstrichAccessors.java   
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());
                }
            });
        }
    };
}
项目:immutable    文件:Immutable.java   
@Override
protected Object handleInvocation(List<String> path, Method method) throws Throwable
{
    if (method.getName().equals("values"))
    {
        return path.isEmpty()
            ? values
            : nextImmutable.getInPath(values, path);
    }

    final List<String> pathWithMethod = pathWith(method);
    final Class<?> returnType = method.getReturnType();

    final Object value = nextImmutable.getInPath(values, pathWithMethod);
    final Object returnValue = value == null
        ? Defaults.defaultValue(returnType)
        : value;
    final boolean isCastable = returnValue == null || isAssignable(returnValue.getClass(), returnType);

    return isCastable
        ? returnValue
        : immutableFor(returnType, pathWithMethod);
}
项目:salta    文件:DefaultFixedConstructorInstantiationRule.java   
public static ArrayList<SupplierRecipe> resolveArguments(StandardInjectorConfiguration config,
        TypeToken<?> typeToken, RecipeCreationContext ctx, Constructor<?> constructor) {
    ArrayList<SupplierRecipe> args = new ArrayList<>();

    Parameter[] parameters = constructor.getParameters();
    for (int i = 0; i < parameters.length; i++) {
        Parameter parameter = parameters[i];
        @SuppressWarnings({ "unchecked", "rawtypes" })
        CoreDependencyKey<Object> dependency = new InjectionPoint(
                typeToken.resolveType(parameter.getParameterizedType()), constructor, parameter, i);
        Optional<SupplierRecipe> argRecipe = ctx.tryGetRecipe(dependency);
        if (argRecipe.isPresent())
            args.add(argRecipe.get());
        else {
            if (config.isInjectionOptional(parameter)) {
                args.add(new SupplierRecipeImpl(() -> Defaults.defaultValue(parameter.getType())));
            } else {
                throw new SaltaException(
                        "Cannot resolve constructor parameter of " + constructor + ":\n" + parameter);
            }
        }
    }
    return args;
}
项目:benayn    文件:Arrays2.java   
private static <T> Object doUnwrap(Exchanging<T> exch, T... target) {
    if (null == target) {
        return null;
    }

    Class<?> clazz = Primitives.unwrap(target.getClass().getComponentType());
    Object r = Array.newInstance(clazz, target.length);
    if (0 == target.length) {
        return r;
    }

    T el = null;
    Object defaultVal = Defaults.defaultValue(clazz);
    for (int i = 0; i < target.length; i++) {
        Array.set(r, i, (null == (el = target[i])) ? defaultVal : exch.unwraps(el));
    }

    return r;
}
项目:appformer    文件:CallerProxy.java   
public Object invoke(final Object proxy,
                     final Method m,
                     final Object[] args) throws Throwable {
    Object result = null;
    try {
        result = m.invoke(target,
                          args);
    } catch (Exception e) {
        if (errorCallBack != null) {
            errorCallBack.error(result,
                                e);
        }
        if (m.getReturnType().isPrimitive()) {
            return Defaults.defaultValue(m.getReturnType());
        } else {
            return result;
        }
    }
    if (successCallBack != null) {
        successCallBack.callback(result);
    }
    return result;
}
项目:data-prep    文件:InMemoryDataSetMetadataRepository.java   
/**
 * 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(@Nullable 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
}
项目:incubator-twill    文件:Instances.java   
/**
 * 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;
}
项目:grpc-java    文件:ForwardingChannelBuilderTest.java   
@Test
public void allBuilderMethodsForwarded() throws Exception {
  for (Method method : ManagedChannelBuilder.class.getDeclaredMethods()) {
    if (Modifier.isStatic(method.getModifiers()) || Modifier.isPrivate(method.getModifiers())) {
      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]);
    }

    method.invoke(testChannelBuilder, args);
    method.invoke(verify(mockDelegate), args);
  }
}
项目:grpc-java    文件:ForwardingChannelBuilderTest.java   
@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]);
    }

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

    assertThat(returnedValue).isSameAs(testChannelBuilder);
  }
}
项目:cherimodata    文件:EntityInvocationHandler.java   
/**
 * Returns the currently assigned value for the given Property or null if the property currently isn't set
 *
 * @param property to get value from
 * @return value of the property or null if the property isn't set. Might return null if the property is computed
 *         and the computer returns null
 */
@SuppressWarnings( "unchecked" )
private Object _get( ParameterProperty property )
{
    if ( property.isComputed() )
    {
        // if this property is computed we need to calculate the value for it
        return property.getComputer().compute( proxy );
    }
    else
    {
        String name = property.getMongoName();
        // add default value, in case nothing has been set yet
        if ( !data.containsKey( name ) && property.isPrimitiveType() )
        {
            data.put( name, Defaults.defaultValue( Primitives.unwrap( property.getType() ) ) );
        }
        return data.get( name );
    }
}
项目:cherimodata    文件:QueryInvocationHandler.java   
@Override
public Object invoke( Object proxy, Method method, Object[] args )
    throws Throwable
{
    ParameterProperty curProperty = properties.getProperty( method );
    if ( properties.getIdProperty() == curProperty )
    {
        // for primitives we need to return something, so return default
        if ( curProperty.isPrimitiveType() )
        {
            return Defaults.defaultValue( Primitives.unwrap( curProperty.getType() ) );
        }
        else
        {
            return null;
        }
    }
    else
    {
        throw new IllegalArgumentException(
            "Only can perform nested query on id field, but was " + curProperty );
    }
}
项目:firebase-admin-java    文件:FirebaseAppTest.java   
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());
}
项目:spanner-jdbc    文件:AbstractCloudSpannerResultSetTest.java   
private Object createDefaultParamValue(Class<?> clazz)
{
    if (clazz.isPrimitive())
        return Defaults.defaultValue(clazz);
    if (byte[].class.equals(clazz))
        return "FOO".getBytes();
    return null;
}
项目:Mastering-Mesos    文件:StorageEntityUtil.java   
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);
  }
}
项目:auto-value-gson    文件:AutoValueGsonExtension.java   
/**
 *
 * @param type
 * @return the default primitive value as a String.  Returns null if unable to determine default value
   */
private String getDefaultPrimitiveValue(TypeName type) {
  String valueString = null;
  try {
    Class<?> primitiveClass = Primitives.unwrap(Class.forName(type.box().toString()));
    if (primitiveClass != null) {
      Object defaultValue = Defaults.defaultValue(primitiveClass);
      if (defaultValue != null) {
        valueString = defaultValue.toString();
        if (!Strings.isNullOrEmpty(valueString)) {
          switch (type.toString()) {
            case "double":
              valueString = valueString + "d";
              break;
            case "float":
              valueString = valueString + "f";
              break;
            case "long":
              valueString = valueString + "L";
              break;
            case "char":
              valueString = "'" + valueString + "'";
              break;
          }
        }
      }
    }
  } catch (ClassNotFoundException ignored) {
    //Swallow and return null
  }

  return valueString;
}
项目:motech    文件:FieldProcessor.java   
private String getDefaultValueForField(Field fieldAnnotation, Class<?> fieldType) {
    if (fieldType.isPrimitive() && (fieldAnnotation == null || StringUtils.isBlank(fieldAnnotation.defaultValue()))) {
        // primitive without default val
        return String.valueOf(Defaults.defaultValue(fieldType));
    } else {
        return fieldAnnotation == null ? null : fieldAnnotation.defaultValue();
    }
}
项目:data-prep    文件:InMemoryDataSetMetadataRepositoryTest.java   
@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));
}
项目:simple-json-rpc    文件:JsonRpcServer.java   
@Nullable
private Object getDefaultValue(@NotNull Class<?> type) {
    if (type == Optional.class) {
        // If it's Guava optional then handle it as an absent value
        return Optional.absent();
    } else if (type.isPrimitive()) {
        // If parameter is a primitive set the appropriate default value
        return Defaults.defaultValue(type);
    }
    return null;
}
项目:c3java    文件:MethodInvocationRecorder.java   
@SuppressWarnings("unchecked")
public <T> T getProxy(TypeToken<T> type) {
    Class<? super T> cls = type.getRawType();

    if (isTerminal(type)) {
        return (T) Defaults.defaultValue(cls);
    }

    Enhancer e = new Enhancer();
    if (Enhancer.isEnhanced(cls)) {
        e.setSuperclass(cls.getSuperclass());
        e.setInterfaces(cls.getInterfaces());
    } else {
        e.setSuperclass(cls);
    }
    e.setCallbackFilter(FINALIZE_FILTER);
    e.setCallbacks(new Callback[] { NoOp.INSTANCE, new MethodInterceptor() {

        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            invocations.add(new MethodInvocation<Object>(type, method, Arrays.asList(args)));

            return getProxy(type.resolveType(method.getGenericReturnType()));
        }

    } });

    try {
        return (T) e.create();
    } catch (Exception ex) {
        throw new RuntimeException("Error while creating proxy of " + type, ex);
    }
}
项目:minium    文件:PrimitiveTypeCoercer.java   
@Override
public Object coerce(Object obj, Type type) {
    if (obj == null) return Defaults.defaultValue(clazzFor(type));

    Class<? extends Object> wrappedType = Primitives.wrap(clazzFor(type));
    Coercer coercer = primitiveCoercers.get(wrappedType);
    return coercer.coerce(obj, wrappedType);
}
项目:cherimodata    文件:QueryInvocationHandler.java   
@Override
public Object invoke( Object proxy, Method method, Object[] args )
    throws Throwable
{
    ParameterProperty property = getProperty( method );
    if ( Entity.class.isAssignableFrom( method.getReturnType() ) )
    {
        checkArgument( !property.isDBRef(),
            "nested search is currently not working on DBRef-References." );
        // the remembering is done nested, first remember the parent element
        parent.curQueriedProperty.add( property );
        return Proxy.newProxyInstance( this.getClass().getClassLoader(), new Class[] { method.getReturnType() },
            new InnerEntityQueryIdOnlyInvocationHandler(
                EntityFactory.getProperties( (Class<? extends Entity>) method.getReturnType() ) ) );
    }
    else
    {
        // remember which property was invoked so we can build the query condition based on it
        parent.addCurQueriedProperty( parent.getProperty( method ) );
        if ( property.isPrimitiveType() )
        {
            return Defaults.defaultValue( Primitives.unwrap( property.getType() ) );
        }
        else
        {
            return null;
        }
    }
}
项目:FreeYourCode    文件:JsonWriter.java   
private boolean writeField(Object obj, boolean first, String fieldName, Field field) throws IOException
    {
        if ((field.getModifiers() & Modifier.TRANSIENT) != 0)
        {   // Do not write transient fields
            return first;
        }

        int modifiers = field.getModifiers();
        if (field.getDeclaringClass().isEnum() && !Modifier.isPublic(modifiers) && isPublicEnumsOnly())
        {
            return first;
        }



       Object o;
        try
        {
            o = field.get(obj);
        }
        catch (Exception ignored)
        {
            o = null;
        }

//FIXME why considered useful here ?!!!
        if (!isConsidered(o) || o.equals(Defaults.defaultValue(field.getType())))
        {
            return first;
        }

        if (first)
        {
            first = false;
        }
        else
        {
            out.write(',');
            newLine();
        }

        writeJsonUtf8String(fieldName, out);
        out.write(':');

        Class type = field.getType();
        //FIXME prepare deux fois, pas très propre ?!!!
        boolean forceType = prepareToWrite(o).getClass() != type;     // If types are not exactly the same, write "@type" field

        if (JsonReader.isPrimitive(type))
        {
            writePrimitive(o);
        }
        else if (writeIfMatching(o, forceType, out)) { }
        else
        {
            writeImpl(o, forceType || alwaysShowType());
        }
        return false;
    }
项目:beam    文件:ProxyInvocationHandler.java   
/**
 * Returns a default value for the method based upon {@code @Default} metadata on the getter
 * to return values. If there is no {@code @Default} annotation on the getter, then a <a
 * href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">default</a> as
 * per the Java Language Specification for the expected return type is returned.
 *
 * @param proxy The proxy object for which we are attempting to get the default.
 * @param method The getter method that was invoked.
 * @return The default value from an {@link Default} annotation if present, otherwise a default
 *         value as per the Java Language Specification.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
private Object getDefault(PipelineOptions proxy, Method method) {
  if (method.getReturnType().equals(RuntimeValueProvider.class)) {
    throw new RuntimeException(String.format(
      "Method %s should not have return type "
      + "RuntimeValueProvider, use ValueProvider instead.", method.getName()));
  }
  if (method.getReturnType().equals(StaticValueProvider.class)) {
    throw new RuntimeException(String.format(
      "Method %s should not have return type "
      + "StaticValueProvider, use ValueProvider instead.", method.getName()));
  }
  @Nullable Object defaultObject = null;
  for (Annotation annotation : method.getAnnotations()) {
    defaultObject = returnDefaultHelper(annotation, proxy, method);
    if (defaultObject != null) {
      break;
    }
  }
  if (method.getReturnType().equals(ValueProvider.class)) {
    String propertyName = gettersToPropertyNames.get(method.getName());
    return defaultObject == null
      ? new RuntimeValueProvider(
        method.getName(), propertyName,
        (Class<? extends PipelineOptions>) method.getDeclaringClass(),
        proxy.getOptionsId())
      : new RuntimeValueProvider(
        method.getName(), propertyName,
        (Class<? extends PipelineOptions>) method.getDeclaringClass(),
        defaultObject, proxy.getOptionsId());
  } else if (defaultObject != null) {
    return defaultObject;
  }

  /*
   * We need to make sure that we return something appropriate for the return type. Thus we return
   * a default value as defined by the JLS.
   */
  return Defaults.defaultValue(method.getReturnType());
}
项目:salta    文件:RecipeInitializerFactoryBase.java   
@Override
public List<RecipeInitializer> getInitializers(RecipeCreationContext ctx, TypeToken<?> typeToken) {
    ArrayList<RecipeInitializer> result = new ArrayList<>();

    MethodOverrideIndex overrideIndex = new MethodOverrideIndex(typeToken);
    // iterate over super types, always processing supertypes before
    // subtypes
    for (TypeToken<?> t : overrideIndex.getAncestors()) {

        for (Method method : t.getRawType().getDeclaredMethods()) {
            if (Modifier.isStatic(method.getModifiers()) || Modifier.isAbstract(method.getModifiers()))
                continue;
            if (isInitializer(t, method, overrideIndex)) {
                method.setAccessible(true);

                // create dependencies
                ArrayList<SupplierRecipe> args = new ArrayList<>();
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    @SuppressWarnings({ "unchecked", "rawtypes" })
                    CoreDependencyKey<Object> dependency = new InjectionPoint<>(
                            (TypeToken) t.resolveType(parameter.getParameterizedType()), method, parameter, i);
                    Optional<SupplierRecipe> recipe = ctx.tryGetRecipe(dependency);

                    if (recipe.isPresent())
                        args.add(recipe.get());
                    else if (config.isInjectionOptional(parameter))
                        args.add(new SupplierRecipeImpl(() -> Defaults.defaultValue(parameter.getType())));
                    else
                        throw new SaltaException(
                                "Cannot resolve initializer parameter of " + method + ":\n" + parameter);

                }

                // add injector
                result.add(new FixedMethodRecipeInitializer(method, args));
            }
        }
    }
    return result;
}
项目:benayn    文件:Me3Test.java   
@Override protected Object primitiveIf() {
    return Defaults.defaultValue(this.clazz);
}
项目:benayn    文件:Me3Test.java   
@Override protected Object eightWrapIf() {
    return Defaults.defaultValue(Primitives.unwrap(this.clazz));
}
项目:ffmpeg-cli-wrapper    文件:NotDefaultCondition.java   
@Override
public boolean applies(MappingContext<S, D> context) {
  return !Objects.equal(context.getSource(), Defaults.defaultValue(context.getSourceType()));
}