private Object[] buildParamList(Invokable<?, ?> invokable, int indexOfParamToSetToNull) { ImmutableList<Parameter> params = invokable.getParameters(); Object[] args = new Object[params.size()]; for (int i = 0; i < args.length; i++) { Parameter param = params.get(i); if (i != indexOfParamToSetToNull) { args[i] = getDefaultValue(param.getType()); Assert.assertTrue( "Can't find or create a sample instance for type '" + param.getType() + "'; please provide one using NullPointerTester.setDefault()", args[i] != null || isNullable(param)); } } return args; }
/** * Returns dummy factory arguments that are equal to {@code args} but may be different instances, * to be used to construct a second instance of the same equality group. */ private List<Object> generateEqualFactoryArguments( Invokable<?, ?> factory, List<Parameter> params, List<Object> args) throws ParameterNotInstantiableException, FactoryMethodReturnsNullException, InvocationTargetException, IllegalAccessException { List<Object> equalArgs = Lists.newArrayList(args); for (int i = 0; i < args.size(); i++) { Parameter param = params.get(i); Object arg = args.get(i); // Use new fresh value generator because 'args' were populated with new fresh generator each. // Two newFreshValueGenerator() instances should normally generate equal value sequence. Object shouldBeEqualArg = generateDummyArg(param, newFreshValueGenerator()); if (arg != shouldBeEqualArg && Objects.equal(arg, shouldBeEqualArg) && hashCodeInsensitiveToArgReference(factory, args, i, shouldBeEqualArg) && hashCodeInsensitiveToArgReference( factory, args, i, generateDummyArg(param, newFreshValueGenerator()))) { // If the implementation uses identityHashCode(), referential equality is // probably intended. So no point in using an equal-but-different factory argument. // We check twice to avoid confusion caused by accidental hash collision. equalArgs.set(i, shouldBeEqualArg); } } return equalArgs; }
private List<Object> getDummyArguments(Invokable<?, ?> invokable) throws ParameterNotInstantiableException { List<Object> args = Lists.newArrayList(); for (Parameter param : invokable.getParameters()) { if (param.isAnnotationPresent(Nullable.class)) { args.add(null); continue; } Object defaultValue = getDummyValue(param.getType()); if (defaultValue == null) { throw new ParameterNotInstantiableException(param); } args.add(defaultValue); } return args; }
@Override protected void bind(Object target, String key, FixtureMap fixtureMap) { List<Method> candidates = findSetterCandidates(target, key); for (Method candidate : candidates) { ImmutableList<Parameter> paramTypes = Invokable.from(candidate).getParameters(); if (paramTypes.size() != 1) continue; TypeToken<?> paramType = paramTypes.get(0).getType(); try { Object candidateParam = getFixtureConverter().convert(fixtureMap, paramType); if (candidateParam != null) { candidate.invoke(target, candidateParam); return; } } catch (Exception e) { throw new FixtureMappingException(e); } } bindByField(target, key, fixtureMap); }
@Override protected void bind(Object target, String key, FixtureList fixtureList) { List<Method> candidates = findSetterCandidates(target, key); for (Method candidate :candidates) { try { ImmutableList<Parameter> paramTypes = Invokable.from(candidate).getParameters(); if (paramTypes.size() != 1) continue; TypeToken<?> paramType = paramTypes.get(0).getType(); Object candidateParam = getFixtureConverter().convert(fixtureList, paramType); if (candidateParam != null) { candidate.invoke(target, candidateParam); return; } } catch (Exception e) { throw new FixtureMappingException(e); } } bindByField(target, key, fixtureList); }
@Override protected void bind(Object target, String key, FixtureValue fixtureValue) { if (fixtureValue == null || fixtureValue.isNull()) return; List<Method> candidates = findSetterCandidates(target, key); for (Method candidate : candidates) { ImmutableList<Parameter> paramTypes = Invokable.from(candidate).getParameters(); if (paramTypes == null || paramTypes.size() != 1) continue; TypeToken<?> paramType = paramTypes.get(0).getType(); Object param = getFixtureConverter().convert(fixtureValue, paramType); if (param == null) continue; try { candidate.invoke(target, param); } catch (Exception e) { throw new FixtureMappingException(e); } } bindByField(target, key, fixtureValue); }
@Test public void testAllAuroraSchedulerManagerIfaceMethodsHaveAuthorizingParam() throws Exception { for (Method declaredMethod : AuroraSchedulerManager.Iface.class.getDeclaredMethods()) { Invokable<?, ?> invokable = Invokable.from(declaredMethod); Collection<Parameter> parameters = invokable.getParameters(); Invokable<?, ?> annotatedInvokable = Invokable.from( AnnotatedAuroraAdmin.class.getDeclaredMethod( invokable.getName(), FluentIterable.from(parameters) .transform(input -> input.getType().getRawType()) .toList() .toArray(new Class<?>[0]))); Collection<Parameter> annotatedParameters = Collections2.filter( annotatedInvokable.getParameters(), input -> input.getAnnotation(AuthorizingParam.class) != null); assertFalse( "Method " + invokable + " should have at least 1 " + AuthorizingParam.class.getName() + " annotation but none were found.", annotatedParameters.isEmpty()); } }
private void addExposedTypes(Invokable<?, ?> invokable, Class<?> cause) { addExposedTypes(invokable.getReturnType(), cause); for (Annotation annotation : invokable.getAnnotations()) { LOG.debug( "Adding exposed types from {}, which is an annotation on invokable {}", annotation, invokable); addExposedTypes(annotation.annotationType(), cause); } for (Parameter parameter : invokable.getParameters()) { LOG.debug( "Adding exposed types from {}, which is a parameter on invokable {}", parameter, invokable); addExposedTypes(parameter, cause); } for (TypeToken<?> exceptionType : invokable.getExceptionTypes()) { LOG.debug( "Adding exposed types from {}, which is an exception type on invokable {}", exceptionType, invokable); addExposedTypes(exceptionType, cause); } }
private boolean eligibilityVerified(Invokable<T, Object> method, Errors errors) { List<TypeToken<?>> primitiveTypes = Lists.newArrayList(); for (Parameter parameter : method.getParameters()) { if (parameter.getType().isPrimitive()) { primitiveTypes.add(parameter.getType()); } } if (method.getReturnType().isPrimitive() && !isVoid(method)) { primitiveTypes.add(method.getReturnType()); } if (!primitiveTypes.isEmpty()) { errors.addMessage("Incompartible eventual provider method '%s'" + "\n\tSignature has primitive types: %s." + " Please use boxed types instead", method.getName(), Joiner.on(", ").join(primitiveTypes)); } return primitiveTypes.isEmpty(); }
private List<Object> getDummyArguments(Invokable<?, ?> invokable) throws ParameterNotInstantiableException { List<Object> args = Lists.newArrayList(); for (Parameter param : invokable.getParameters()) { if (isNullable(param)) { args.add(null); continue; } Object defaultValue = getDummyValue(param.getType()); if (defaultValue == null) { throw new ParameterNotInstantiableException(param); } args.add(defaultValue); } return args; }
@Override protected Object handleInvocation( Object proxy, Method method, Object[] args) { Invokable<?, ?> invokable = interfaceType.method(method); ImmutableList<Parameter> params = invokable.getParameters(); for (int i = 0; i < args.length; i++) { Parameter param = params.get(i); if (!param.isAnnotationPresent(Nullable.class)) { checkNotNull(args[i]); } } return dummyReturnValue(interfaceType.resolveType(method.getGenericReturnType())); }
private boolean hasInstanceMethodToTestNulls(Class<?> c, Visibility visibility) { for (Method method : nullPointerTester.getInstanceMethodsToTest(c, visibility)) { for (Parameter param : Invokable.from(method).getParameters()) { if (!NullPointerTester.isPrimitiveOrNullable(param)) { return true; } } } return false; }
private void testEqualsUsing(final Invokable<?, ?> factory) throws ParameterNotInstantiableException, ParameterHasNoDistinctValueException, IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException { List<Parameter> params = factory.getParameters(); List<FreshValueGenerator> argGenerators = Lists.newArrayListWithCapacity(params.size()); List<Object> args = Lists.newArrayListWithCapacity(params.size()); for (Parameter param : params) { FreshValueGenerator generator = newFreshValueGenerator(); argGenerators.add(generator); args.add(generateDummyArg(param, generator)); } Object instance = createInstance(factory, args); List<Object> equalArgs = generateEqualFactoryArguments(factory, params, args); // Each group is a List of items, each item has a list of factory args. final List<List<List<Object>>> argGroups = Lists.newArrayList(); argGroups.add(ImmutableList.of(args, equalArgs)); EqualsTester tester = new EqualsTester(new ItemReporter() { @Override String reportItem(Item<?> item) { List<Object> factoryArgs = argGroups.get(item.groupNumber).get(item.itemNumber); return factory.getName() + "(" + Joiner.on(", ").useForNull("null").join(factoryArgs) + ")"; } }); tester.addEqualityGroup(instance, createInstance(factory, equalArgs)); for (int i = 0; i < params.size(); i++) { List<Object> newArgs = Lists.newArrayList(args); Object newArg = argGenerators.get(i).generateFresh(params.get(i).getType()); if (newArg == null || Objects.equal(args.get(i), newArg)) { if (params.get(i).getType().getRawType().isEnum()) { continue; // Nothing better we can do if it's single-value enum } throw new ParameterHasNoDistinctValueException(params.get(i)); } newArgs.set(i, newArg); tester.addEqualityGroup(createInstance(factory, newArgs)); argGroups.add(ImmutableList.of(newArgs)); } tester.testEquals(); }
@Nullable private static Object generateDummyArg(Parameter param, FreshValueGenerator generator) throws ParameterNotInstantiableException { if (param.isAnnotationPresent(Nullable.class)) { return null; } Object arg = generator.generateFresh(param.getType()); if (arg == null) { throw new ParameterNotInstantiableException(param); } return arg; }
public static GenericMethodType<?> of(Invokable<?, ?> invokable) { return new GenericMethodType<>(invokable.getReturnType(), invokable.getParameters() .stream() .map(Parameter::getType) .collect(Collectors.toImmutableList())); }
/** * Returns a list of argument types for the given method, which must * be a part of the class. */ public List<TypeDescriptor<?>> getArgumentTypes(Method method) { Invokable<?, ?> typedMethod = token.method(method); List<TypeDescriptor<?>> argTypes = Lists.newArrayList(); for (Parameter parameter : typedMethod.getParameters()) { argTypes.add(new SimpleTypeDescriptor<>(parameter.getType())); } return argTypes; }
private void addExposedTypes(Parameter parameter, Class<?> cause) { LOG.debug( "Adding exposed types from {}, which is the type of parameter {}", parameter.getType(), parameter); addExposedTypes(parameter.getType(), cause); for (Annotation annotation : parameter.getAnnotations()) { LOG.debug( "Adding exposed types from {}, which is an annotation on parameter {}", annotation, parameter); addExposedTypes(annotation.annotationType(), cause); } }
private EventualProvider<?> providerFor(Invokable<T, ?> method, Errors methodErrors) { Annotation[] annotations = method.getAnnotations(); verifyMethodAccessibility(methodErrors, method, source); @Nullable Annotation bindingAnnotation = Annotations.findBindingAnnotation(methodErrors, method, annotations); verifyAbsenseOfScopeAnnotation(methodErrors, annotations, source); List<Dependency<ListenableFuture<?>>> dependencies = Lists.newArrayListWithCapacity(method.getParameters().size()); for (Parameter parameter : method.getParameters()) { dependencies.add(extractDependency(methodErrors, parameter)); } Key<ListenableFuture<?>> bindingKey; boolean exposedBinding = method.isAnnotationPresent(Exposed.class); if (isVoid(method)) { bindingKey = futureKey(TypeToken.of(Boolean.class), new BlackholedAnnotation()); exposedBinding = false; } else { bindingKey = futureKey(method.getReturnType(), bindingAnnotation); } return new EventualProvider<>( method, exposedBinding, dependencies, bindingKey, scopeAnnotation, source); }
Dependency<ListenableFuture<?>> extractDependency(Errors methodErrors, Parameter parameter) { @Nullable Annotation bindingAnnotation = Annotations.findBindingAnnotation( methodErrors, parameter.getDeclaringInvokable(), parameter.getAnnotations()); return Dependency.get(futureKey( parameter.getType(), bindingAnnotation)); }
public MethodBinder(Invokable<T, R> from) { this.method = from; int positional = 0; for (Parameter p : from.getParameters()) { if (p.getAnnotation(GQLContext.class) != null) { this.contextual.put(p.getType(), p); args.add((generator) -> generator.context(p)); } else if (p.getAnnotation(GQLArg.class) != null) { final GQLArg arg = p.getAnnotation(GQLArg.class); named.put(arg.value(), p); args.add((generator) -> generator.named(arg.value(), p)); } else { final int mpos = positional; this.positional.add(p); args.add((generator) -> generator.positional(mpos, p)); } } }
private static @Nullable Object generateDummyArg(Parameter param, FreshValueGenerator generator) throws ParameterNotInstantiableException { if (param.isAnnotationPresent(Nullable.class)) { return null; } Object arg = generator.generateFresh(param.getType()); if (arg == null) { throw new ParameterNotInstantiableException(param); } return arg; }
@Override public Request intercept(Request request, List<Parameter> params, Object[] args) { request.setEntity(EMPTY_OBJECT_BODY); request.setContentType(ContentType.APPLICATION_JSON_PATCH); return request; }