Java Code Examples for com.google.common.reflect.TypeToken#of()

The following examples show how to use com.google.common.reflect.TypeToken#of() . 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: SchemaRepositoryTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Test
public void getOrAdd_recursiveSchema() throws Exception {
  TypeToken<SelfReferencingObject> type = TypeToken.of(SelfReferencingObject.class);
  // This test checks the case where a schema is added multiple times. The second time it's added
  // to an API, it recurses through the schema. If the schema is self-referencing, we must not
  // stack overflow.
  repo.getOrAdd(type, config);
  assertThat(repo.getOrAdd(type, config))
      .isEqualTo(Schema.builder()
          .setName("SelfReferencingObject")
          .setType("object")
          .addField("foo", Field.builder()
              .setName("foo")
              .setType(FieldType.OBJECT)
              .setSchemaReference(SchemaReference.create(repo, config, type))
              .build())
          .build());
}
 
Example 2
Source File: MessageRegistry.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
private static <M extends Model, N extends ModelMessage<M>> TypeToken<N> modelMessageType(TypeToken<N> messageType, TypeToken<M> modelType) {
    if(messageType.getRawType().getTypeParameters().length == 0) {
        return messageType;
    } else {
        return (TypeToken<N>) TypeToken.of(new ParameterizedType() {
            @Override
            public Type[] getActualTypeArguments() {
                return new Type[]{ modelType.getType() };
            }

            @Override
            public Type getRawType() {
                return messageType.getRawType();
            }

            @Override
            public Type getOwnerType() {
                return messageType.getRawType().getEnclosingClass();
            }
        });
    }
}
 
Example 3
Source File: FieldDelegate.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Field findField(Class<?> owner, TypeToken<?> type, String name) {
    try {
        final Field field = owner.getDeclaredField(name);
        final TypeToken<?> actualType = TypeToken.of(field.getGenericType());
        if(!type.equals(actualType)) {
            throw new NoSuchFieldError(
                "Expected field " + Members.qualifiedName(field) +
                " to have exact type " + type +
                " but the actual type is " + actualType
            );
        }
        return field;
    } catch(NoSuchFieldException e) {
        throw new NoSuchFieldError(e.getMessage());
    }
}
 
Example 4
Source File: Serializers.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the {@code Serializer} source type for a class. This resolves placeholders in generics.
 *
 * @param clazz a class, possibly implementing {@code Transformer}
 * @return the resolved source type, null if clazz is not a serializer
 */
@Nullable
public static TypeToken<?> getSourceType(Class<? extends Transformer<?, ?>> clazz) {
  try {
    TypeToken<?> token = TypeToken.of(clazz);
    return token.resolveType(
        Transformer.class.getMethod("transformFrom", Object.class).getGenericReturnType());
  } catch (NoSuchMethodException e) {
    return null;
  }
}
 
Example 5
Source File: Serializers.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the {@code Serializer} target type for a class. This resolves placeholders in generics.
 *
 * @param clazz a class, possibly implementing {@code Transformer}
 * @return the resolved target type, null if clazz is not a serializer
 */
@Nullable
public static TypeToken<?> getTargetType(Class<? extends Transformer<?, ?>> clazz) {
  try {
    TypeToken<?> token = TypeToken.of(clazz);
    return token.resolveType(
        Transformer.class.getMethod("transformTo", Object.class).getGenericReturnType());
  } catch (NoSuchMethodException e) {
    return null;
  }
}
 
Example 6
Source File: MethodCoercions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to find a single-parameter method with a parameter compatible with (can be coerced to) the argument, and
 * invokes it.
 *
 * @param instance the object to invoke the method on
 * @param methodName the name of the method to invoke
 * @param argument the argument to the method's parameter.
 * @return the result of the method call, or {@link org.apache.brooklyn.util.guava.Maybe#absent()} if method could not be matched.
 */
public static Maybe<?> tryFindAndInvokeSingleParameterMethod(final Object instance, final String methodName, final Object argument) {
    Class<?> clazz = instance.getClass();
    Iterable<Method> methods = Arrays.asList(clazz.getMethods());
    Optional<Method> matchingMethod = Iterables.tryFind(methods, matchSingleParameterMethod(methodName, argument));
    if (matchingMethod.isPresent()) {
        Method method = matchingMethod.get();
        Method accessibleMethod = Reflections.findAccessibleMethod(method).get();
        try {
            Type paramType = method.getGenericParameterTypes()[0];
            Maybe<?> coercedArgumentM = TypeCoercions.tryCoerce(argument, TypeToken.of(paramType));
            RuntimeException exception = Maybe.getException(coercedArgumentM);
            if (coercedArgumentM.isPresent() && coercedArgumentM.get()!=null) {
                if (!Boxing.boxedTypeToken(paramType).getRawType().isAssignableFrom(coercedArgumentM.get().getClass())) {
                    exception = new IllegalArgumentException("Type mismatch after coercion; "+coercedArgumentM.get()+" is not a "+TypeToken.of(paramType));
                }
            }
            if (coercedArgumentM.isAbsent() || exception!=null) {
                return Maybe.absent("Cannot convert parameter for "+method+": "+
                    Exceptions.collapseText(Maybe.getException(coercedArgumentM)), exception);
            }
            return Maybe.of(accessibleMethod.invoke(instance, coercedArgumentM.get()));
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw Exceptions.propagate(e);
        }
    } else {
        return Maybe.absent("No method matching '"+methodName+"("+(argument==null ? argument : argument.getClass().getName())+")'");
    }
}
 
Example 7
Source File: HttpOperations.java    From riptide with MIT License 5 votes vote down vote up
@Nonnull
@Override
public <T> ResponseEntity<T> exchange(final RequestEntity<?> entity,
        final ParameterizedTypeReference<T> responseType) {
    final HttpMethod method = entity.getMethod();
    Assert.notNull(method, "HttpMethod is required");
    @SuppressWarnings("unchecked") final TypeToken<T> type = (TypeToken<T>) TypeToken.of(responseType.getType());
    return exchange(entity.getUrl(), method, entity, type);
}
 
Example 8
Source File: ModelDispatcher.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void subscribe(ModelListener listener) {
    final TypeToken<? extends ModelListener> listenerType = TypeToken.of(listener.getClass());

    Methods.declaredMethodsInAncestors(listener.getClass())
           .filter(Annotations.annotatedWith(ModelListener.HandleModel.class)).forEach(method -> {

        final TypeToken<? extends Model> model = (TypeToken<? extends Model>) listenerType.method(method).getParameters().get(0).getType();
        final ModelHandler<? extends Model> handler = Methods.lambda(handlerType(model), method, listener);
        handlers.put(model, handler);
        listeners.put(listener, Maps.immutableEntry(model, handler));

        logger.fine(() -> "Dispatching " + model + " updates to " + Methods.describe(listener.getClass(), method.getName()));
    });
}
 
Example 9
Source File: VersionMatchedCollectionTypeCoercer.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public TypeToken<Object> getUnconfiguredType() {
  return TypeToken.of(Object.class);
}
 
Example 10
Source File: SourceWithFlagsListTypeCoercer.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public TypeToken<Object> getUnconfiguredType() {
  return TypeToken.of(Object.class);
}
 
Example 11
Source File: MethodDeclaration.java    From OpenPeripheral with MIT License 4 votes vote down vote up
public MethodDeclaration(Class<?> rootClass, Method method, ScriptCallable meta, String source) {
	this.method = method;
	this.source = source;

	this.names = getNames(method, meta);

	this.description = meta.description();
	this.returnTypes = ImmutableList.copyOf(meta.returnTypes());
	this.validateReturn = meta.validateReturn();

	this.multipleReturn = method.isAnnotationPresent(MultipleReturn.class);

	this.wrappedReturn = TypeHelper.createFromReturn(returnTypes);

	if (validateReturn) validateResultCount();

	final Type methodArgs[] = method.getGenericParameterTypes();
	final boolean isVarArg = method.isVarArgs();

	ArgParseState state = ArgParseState.ENV_UNNAMED;

	TypeToken<?> scopeType = TypeToken.of(rootClass);

	final Annotation[][] argsAnnotations = method.getParameterAnnotations();
	for (int argIndex = 0; argIndex < methodArgs.length; argIndex++) {
		try {
			final TypeToken<?> argType = scopeType.resolveType(methodArgs[argIndex]);

			AnnotationMap argAnnotations = new AnnotationMap(argsAnnotations[argIndex]);

			boolean optionalStart = argAnnotations.get(Optionals.class) != null;

			Env envArg = argAnnotations.get(Env.class);
			Arg luaArg = argAnnotations.get(Arg.class);

			Preconditions.checkState(envArg == null || luaArg == null, "@Arg and @Env are mutually exclusive");
			if (luaArg != null) {

				if (state != ArgParseState.ARG_OPTIONAL) state = ArgParseState.ARG_REQUIRED;

				if (optionalStart) {
					Preconditions.checkState(state != ArgParseState.ENV_NAMED, "@Optional used more than once");
					state = ArgParseState.ARG_OPTIONAL;
				}

				boolean isLastArg = argIndex == (methodArgs.length - 1);

				ArgumentBuilder builder = new ArgumentBuilder();
				builder.setVararg(isLastArg && isVarArg);
				builder.setOptional(state == ArgParseState.ARG_OPTIONAL);
				builder.setNullable(luaArg.isNullable());

				final Argument arg = builder.build(luaArg.name(), luaArg.description(), luaArg.type(), argType, argIndex);
				callArgs.add(arg);
			} else {
				Preconditions.checkState(state == ArgParseState.ENV_NAMED || state == ArgParseState.ENV_UNNAMED, "Unannotated arg in script part (perhaps missing @Arg annotation?)");
				Preconditions.checkState(!optionalStart, "@Optionals does not work for env arguments");

				Class<?> rawArgType = argType.getRawType();
				if (envArg != null) {
					Preconditions.checkState(state == ArgParseState.ENV_NAMED || state == ArgParseState.ENV_UNNAMED, "@Env annotation used in script part of arguments");
					final String envName = envArg.value();
					EnvArg prev = envArgs.put(envName, new EnvArg(rawArgType, argIndex));
					if (prev != null) { throw new IllegalStateException(String.format("Conflict on name %s, args: %s, %s", envArg, prev.index, argIndex)); }
					state = ArgParseState.ENV_NAMED;
				} else {
					Preconditions.checkState(state == ArgParseState.ENV_UNNAMED, "Unnamed env cannot occur after named");
					unnamedEnvArg.put(argIndex, rawArgType);
				}
			}
		} catch (Throwable t) {
			throw new ArgumentDefinitionException(argIndex, t);
		}
	}

	this.argCount = unnamedEnvArg.size() + envArgs.size() + callArgs.size();
	Preconditions.checkState(this.argCount == methodArgs.length, "Internal error for method %s", method);
}
 
Example 12
Source File: PatternMatchedCollectionTypeCoercer.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public TypeToken<Object> getUnconfiguredType() {
  return TypeToken.of(Object.class);
}
 
Example 13
Source File: StringWithMacrosTypeCoercer.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public TypeToken<StringWithMacros> getOutputType() {
  return TypeToken.of(StringWithMacros.class);
}
 
Example 14
Source File: TestRunnerSpecCoercer.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public TypeToken<Object> getUnconfiguredType() {
  return TypeToken.of(Object.class);
}
 
Example 15
Source File: TypeClassifier.java    From OpenPeripheral with MIT License 4 votes vote down vote up
@Override
public IScriptType classify(ITypeClassifier classifier, Type type) {
	final TypeToken<?> token = TypeToken.of(type);
	return wrapped.classify(classifier, token.getRawType());
}
 
Example 16
Source File: Types.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static <T> TypeToken<T> box(TypeToken<T> type) {
    return type.isPrimitive() ? TypeToken.of(box((Class<T>) type.getRawType())) : type;
}
 
Example 17
Source File: GenericInboundConverterAdapter.java    From OpenPeripheral with MIT License 4 votes vote down vote up
@Override
public Object toJava(IConverter registry, Object obj, Type expected) {
	TypeToken<?> type = TypeToken.of(expected);
	return toJava(registry, obj, type.getRawType());
}
 
Example 18
Source File: SetConfigKey.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public SetConfigKey(Class<V> subType, String name) {
    this(TypeToken.of(subType), name, name, null);
}
 
Example 19
Source File: ModelType.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@SuppressWarnings("unchecked")
public <I> Builder<T> where(Parameter<I> parameter, ModelType<I> type) {
    TypeResolver resolver = new TypeResolver().where(parameter.typeVariable, type.typeToken.getType());
    typeToken = (TypeToken<T>) TypeToken.of(resolver.resolveType(typeToken.getType()));
    return this;
}
 
Example 20
Source File: PluginLoaderImpl.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
@NotNull <T extends ExtensionMain> Optional<Class<? extends T>> loadFromUrls(
        @NotNull final Collection<URL> urls,
        @NotNull final Class<T> desiredPluginClass, @NotNull final String pluginId) {

    checkNotNull(desiredPluginClass, "extension class must not be null");
    checkNotNull(urls, "urls must not be null");

    if (urls.isEmpty()) {
        return Optional.empty();
    }

    final TypeToken<T> type = TypeToken.of(desiredPluginClass);
    final ImmutableList.Builder<Class<? extends T>> desiredPlugins = ImmutableList.builder();


    /*
     * We are using a Service Loader mechanism similar to the original Java service
     * loader mechanism (e.g read from META-INF/services).
     * We are not using the default JDK Service Loader, though, because it returns direct instances of the
     * desired Extension classes.
     */

    try {
        final ImmutableList.Builder<Class<? extends ExtensionMain>> allImplementations = ImmutableList.builder();

        for (final URL pluginFileUrl : urls) {


            //We are creating an isolated extension classloader for each extension.
            final URL[] classpath = {pluginFileUrl};

            final IsolatedPluginClassloader pluginClassloader =
                    new IsolatedPluginClassloader(classpath, getClass().getClassLoader());

            pluginClassloader.loadClassesWithStaticContext();

            if (!initializeStaticContext(pluginId, pluginClassloader)) {
                return Optional.empty();
            }

            final Iterable<Class<? extends T>> allPluginModuleStartingPoints =
                    serviceLoader.load(desiredPluginClass, pluginClassloader);
            if (Iterables.size(allPluginModuleStartingPoints) > 1) {
                log.warn(
                        "Extension {} contains more than one implementation of ExtensionMain. The extension will be disabled.",
                        pluginFileUrl.toString());
                return Optional.empty();
            }
            for (final Class<? extends ExtensionMain> startingPoint : allPluginModuleStartingPoints) {
                allImplementations.add(startingPoint);
            }
        }

        for (final Class<? extends ExtensionMain> implementation : allImplementations.build()) {
            if (type.getRawType().isAssignableFrom(implementation)) {
                @SuppressWarnings("unchecked") final Class<? extends T> pluginClass =
                        (Class<? extends T>) implementation;
                desiredPlugins.add(pluginClass);
            } else {
                log.debug(
                        "Extension {} is not a {} Extension and will be ignored", implementation.getName(),
                        type.getRawType().getName());
            }
        }
    } catch (final IOException | ClassNotFoundException | SecurityException e) {
        log.error(
                "An error occurred while searching the implementations for the extension {}. The extension will be disabled. {} : {}",
                pluginId, e.getClass().getSimpleName(), e.getMessage());
        return Optional.empty();
    }

    final ImmutableList<Class<? extends T>> desired = desiredPlugins.build();

    if (desired.size() == 1) {
        return Optional.of(desired.get(0));
    }

    if (desired.size() == 0) {
        log.warn(
                "No implementation of the interface ExtensionMain found in the extension with id \"{}\". The extension will be disabled.",
                pluginId);
        return Optional.empty();
    }
    log.error(
            "More than one implementation of the interface ExtensionMain found in extension with id {}, this interface can only be implemented once. The extension will be disabled.",
            pluginId);
    return Optional.empty();
}