use of io.quarkiverse.githubapp.runtime.ConfigFileReader in project quarkus-github-app by quarkiverse.
the class GitHubAppProcessor method generateMultiplexers.
/**
* Multiplexers listen to the async events emitted by the dispatcher.
* <p>
* They are subclasses of the application classes listening to GitHub events through our annotations.
* <p>
* They are useful for several purposes:
* <ul>
* <li>A single application method can listen to multiple event types: the event types are qualifiers and CDI wouldn't allow
* that (only events matching all the qualifiers would be received by the application method). That's why this class is
* called a multiplexer: it will generate one method per event type and each generated method will delegate to the original
* method.</li>
* <li>The multiplexer also handles the resolution of config files.</li>
* <li>We can inject a properly configured instance of GitHub or DynamicGraphQLClient into the method.</li>
* </ul>
*/
private static void generateMultiplexers(ClassOutput beanClassOutput, DispatchingConfiguration dispatchingConfiguration, BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
for (Entry<DotName, TreeSet<EventDispatchingMethod>> eventDispatchingMethodsEntry : dispatchingConfiguration.getMethods().entrySet()) {
DotName declaringClassName = eventDispatchingMethodsEntry.getKey();
TreeSet<EventDispatchingMethod> eventDispatchingMethods = eventDispatchingMethodsEntry.getValue();
ClassInfo declaringClass = eventDispatchingMethods.iterator().next().getMethod().declaringClass();
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, declaringClassName.toString()));
String multiplexerClassName = declaringClassName + "_Multiplexer";
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, multiplexerClassName));
ClassCreator multiplexerClassCreator = ClassCreator.builder().classOutput(beanClassOutput).className(multiplexerClassName).superClass(declaringClassName.toString()).build();
multiplexerClassCreator.addAnnotation(Multiplexer.class);
if (!BuiltinScope.isDeclaredOn(declaringClass)) {
multiplexerClassCreator.addAnnotation(Singleton.class);
}
for (AnnotationInstance classAnnotation : declaringClass.classAnnotations()) {
multiplexerClassCreator.addAnnotation(classAnnotation);
}
// Copy the constructors
for (MethodInfo originalConstructor : declaringClass.constructors()) {
MethodCreator constructorCreator = multiplexerClassCreator.getMethodCreator(MethodDescriptor.ofConstructor(multiplexerClassName, originalConstructor.parameters().stream().map(t -> t.name().toString()).toArray(String[]::new)));
List<AnnotationInstance> originalMethodAnnotations = originalConstructor.annotations().stream().filter(ai -> ai.target().kind() == Kind.METHOD).collect(Collectors.toList());
for (AnnotationInstance originalMethodAnnotation : originalMethodAnnotations) {
constructorCreator.addAnnotation(originalMethodAnnotation);
}
Map<Short, List<AnnotationInstance>> originalConstructorParameterAnnotationMapping = originalConstructor.annotations().stream().filter(ai -> ai.target().kind() == Kind.METHOD_PARAMETER).collect(Collectors.groupingBy(ai -> ai.target().asMethodParameter().position()));
List<ResultHandle> parametersRh = new ArrayList<>();
for (short i = 0; i < originalConstructor.parameters().size(); i++) {
parametersRh.add(constructorCreator.getMethodParam(i));
AnnotatedElement parameterAnnotations = constructorCreator.getParameterAnnotations(i);
List<AnnotationInstance> originalConstructorParameterAnnotations = originalConstructorParameterAnnotationMapping.getOrDefault(i, Collections.emptyList());
for (AnnotationInstance originalConstructorParameterAnnotation : originalConstructorParameterAnnotations) {
parameterAnnotations.addAnnotation(originalConstructorParameterAnnotation);
}
}
constructorCreator.invokeSpecialMethod(MethodDescriptor.of(originalConstructor), constructorCreator.getThis(), parametersRh.toArray(ResultHandle[]::new));
constructorCreator.returnValue(null);
}
// Generate the multiplexed event dispatching methods
for (EventDispatchingMethod eventDispatchingMethod : eventDispatchingMethods) {
AnnotationInstance eventSubscriberInstance = eventDispatchingMethod.getEventSubscriberInstance();
MethodInfo originalMethod = eventDispatchingMethod.getMethod();
Map<Short, List<AnnotationInstance>> originalMethodParameterAnnotationMapping = originalMethod.annotations().stream().filter(ai -> ai.target().kind() == Kind.METHOD_PARAMETER).collect(Collectors.groupingBy(ai -> ai.target().asMethodParameter().position()));
// if the method already has an @Observes or @ObservesAsync annotation
if (originalMethod.hasAnnotation(DotNames.OBSERVES) || originalMethod.hasAnnotation(DotNames.OBSERVES_ASYNC)) {
LOG.warn("Methods listening to GitHub events may not be annotated with @Observes or @ObservesAsync. Offending method: " + originalMethod.declaringClass().name() + "#" + originalMethod);
}
List<String> parameterTypes = new ArrayList<>();
List<Type> originalMethodParameterTypes = originalMethod.parameters();
// detect the parameter that is a payload
short payloadParameterPosition = 0;
for (short i = 0; i < originalMethodParameterTypes.size(); i++) {
List<AnnotationInstance> parameterAnnotations = originalMethodParameterAnnotationMapping.getOrDefault(i, Collections.emptyList());
if (parameterAnnotations.stream().anyMatch(ai -> ai.name().equals(eventSubscriberInstance.name()))) {
payloadParameterPosition = i;
break;
}
}
short j = 0;
Map<Short, Short> parameterMapping = new HashMap<>();
for (short i = 0; i < originalMethodParameterTypes.size(); i++) {
List<AnnotationInstance> originalMethodAnnotations = originalMethodParameterAnnotationMapping.getOrDefault(i, Collections.emptyList());
if (originalMethodAnnotations.stream().anyMatch(ai -> CONFIG_FILE.equals(ai.name())) || GITHUB.equals(originalMethodParameterTypes.get(i).name()) || DYNAMIC_GRAPHQL_CLIENT.equals(originalMethodParameterTypes.get(i).name())) {
// if the parameter is annotated with @ConfigFile or is of type GitHub or DynamicGraphQLClient, we skip it
continue;
}
String parameterType;
if (i == payloadParameterPosition) {
parameterType = MultiplexedEvent.class.getName();
} else {
parameterType = originalMethodParameterTypes.get(i).name().toString();
}
parameterTypes.add(parameterType);
parameterMapping.put(i, j);
j++;
}
if (originalMethod.hasAnnotation(CONFIG_FILE)) {
parameterTypes.add(ConfigFileReader.class.getName());
}
MethodCreator methodCreator = multiplexerClassCreator.getMethodCreator(originalMethod.name() + "_" + HashUtil.sha1(eventSubscriberInstance.toString()), originalMethod.returnType().name().toString(), parameterTypes.toArray());
for (Type exceptionType : originalMethod.exceptions()) {
methodCreator.addException(exceptionType.name().toString());
}
ResultHandle[] parameterValues = new ResultHandle[originalMethod.parameters().size()];
// copy annotations except for @ConfigFile
for (short i = 0; i < originalMethodParameterTypes.size(); i++) {
List<AnnotationInstance> parameterAnnotations = originalMethodParameterAnnotationMapping.getOrDefault(i, Collections.emptyList());
if (parameterAnnotations.isEmpty()) {
continue;
}
// @ConfigFile elements are not in the mapping
Short generatedParameterIndex = parameterMapping.get(i);
if (generatedParameterIndex == null) {
continue;
}
AnnotatedElement generatedParameterAnnotations = methodCreator.getParameterAnnotations(generatedParameterIndex);
if (parameterAnnotations.stream().anyMatch(ai -> ai.name().equals(eventSubscriberInstance.name()))) {
generatedParameterAnnotations.addAnnotation(DotNames.OBSERVES_ASYNC.toString());
generatedParameterAnnotations.addAnnotation(eventSubscriberInstance);
} else {
for (AnnotationInstance annotationInstance : parameterAnnotations) {
generatedParameterAnnotations.addAnnotation(annotationInstance);
}
}
}
ResultHandle payloadRh = methodCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(MultiplexedEvent.class, "getPayload", GHEventPayload.class), methodCreator.getMethodParam(parameterMapping.get(payloadParameterPosition)));
// generate the code of the method
for (short originalMethodParameterIndex = 0; originalMethodParameterIndex < originalMethodParameterTypes.size(); originalMethodParameterIndex++) {
List<AnnotationInstance> parameterAnnotations = originalMethodParameterAnnotationMapping.getOrDefault(originalMethodParameterIndex, Collections.emptyList());
Short multiplexerMethodParameterIndex = parameterMapping.get(originalMethodParameterIndex);
if (originalMethodParameterIndex == payloadParameterPosition) {
parameterValues[originalMethodParameterIndex] = payloadRh;
} else if (GITHUB.equals(originalMethodParameterTypes.get(originalMethodParameterIndex).name())) {
parameterValues[originalMethodParameterIndex] = methodCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(MultiplexedEvent.class, "getGitHub", GitHub.class), methodCreator.getMethodParam(parameterMapping.get(payloadParameterPosition)));
} else if (DYNAMIC_GRAPHQL_CLIENT.equals(originalMethodParameterTypes.get(originalMethodParameterIndex).name())) {
parameterValues[originalMethodParameterIndex] = methodCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(MultiplexedEvent.class, "getGitHubGraphQLClient", DynamicGraphQLClient.class), methodCreator.getMethodParam(parameterMapping.get(payloadParameterPosition)));
} else if (parameterAnnotations.stream().anyMatch(ai -> ai.name().equals(CONFIG_FILE))) {
AnnotationInstance configFileAnnotationInstance = parameterAnnotations.stream().filter(ai -> ai.name().equals(CONFIG_FILE)).findFirst().get();
String configObjectType = originalMethodParameterTypes.get(originalMethodParameterIndex).name().toString();
boolean isOptional = false;
if (Optional.class.getName().equals(configObjectType)) {
if (originalMethodParameterTypes.get(originalMethodParameterIndex).kind() != Type.Kind.PARAMETERIZED_TYPE) {
throw new IllegalStateException("Optional is used but not parameterized for method " + originalMethod.declaringClass().name() + "#" + originalMethod);
}
isOptional = true;
configObjectType = originalMethodParameterTypes.get(originalMethodParameterIndex).asParameterizedType().arguments().get(0).name().toString();
}
// it's a config file, we will use the ConfigFileReader (last parameter of the method) and inject the result
ResultHandle configFileReaderRh = methodCreator.getMethodParam(parameterTypes.size() - 1);
ResultHandle ghRepositoryRh = methodCreator.invokeStaticMethod(MethodDescriptor.ofMethod(PayloadHelper.class, "getRepository", GHRepository.class, GHEventPayload.class), payloadRh);
ResultHandle configObject = methodCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(ConfigFileReader.class, "getConfigObject", Object.class, GHRepository.class, String.class, Class.class), configFileReaderRh, ghRepositoryRh, methodCreator.load(configFileAnnotationInstance.value().asString()), methodCreator.loadClass(configObjectType));
configObject = methodCreator.checkCast(configObject, configObjectType);
if (isOptional) {
configObject = methodCreator.invokeStaticMethod(MethodDescriptor.ofMethod(Optional.class, "ofNullable", Optional.class, Object.class), configObject);
}
parameterValues[originalMethodParameterIndex] = configObject;
} else {
parameterValues[originalMethodParameterIndex] = methodCreator.getMethodParam(multiplexerMethodParameterIndex);
}
}
ResultHandle returnValue = methodCreator.invokeVirtualMethod(originalMethod, methodCreator.getThis(), parameterValues);
methodCreator.returnValue(returnValue);
}
multiplexerClassCreator.close();
}
}
Aggregations