Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[KOGITO-9861] Fixing compilation issues with nested classes and arrays #3242

Merged
merged 2 commits into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import org.kie.kogito.internal.process.runtime.KogitoWorkItemHandler;
import org.kie.kogito.internal.process.runtime.KogitoWorkItemManager;
import org.kie.kogito.jackson.utils.JsonObjectUtils;
import org.kie.kogito.jackson.utils.ObjectMapperFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -48,10 +47,13 @@ public void executeWorkItem(KogitoWorkItem workItem, KogitoWorkItemManager manag
protected static <V> V buildBody(Map<String, Object> params, Class<V> clazz) {
for (Object obj : params.values()) {
if (obj != null && clazz.isAssignableFrom(obj.getClass())) {
logger.trace("Invoking workitemhandler with value {}", obj);
Copy link
Contributor Author

@fjtirado fjtirado Oct 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is not stricly needed for this PR, but I feel it isinteresting to have a trace here.

return clazz.cast(obj);
}
}
return ObjectMapperFactory.get().convertValue(params, clazz);
V value = JsonObjectUtils.convertValue(params, clazz);
logger.trace("Invoking workitemhandler with value {}", value);
Copy link
Contributor Author

@fjtirado fjtirado Oct 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here. Also, in some circumstances, JsonObjectUtils.converValue will be faster than directly invoking Jackson converter

return value;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.kie.kogito.codegen.api.context.KogitoBuildContext;

import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.type.ClassOrInterfaceType;

import static com.github.javaparser.StaticJavaParser.parseClassOrInterfaceType;
import static com.github.javaparser.StaticJavaParser.parseType;
Expand All @@ -46,16 +47,31 @@ public Collection<WorkflowHandlerGeneratedFile> generateHandlerClasses(KogitoBui
protected abstract Stream<WorkflowHandlerGeneratedFile> generateHandler(KogitoBuildContext context, AnnotationInstance a);

protected final com.github.javaparser.ast.type.Type fromClass(Type param) {
return fromClass(param, true);
}

protected final com.github.javaparser.ast.type.Type fromClass(Type param, boolean includeGeneric) {
switch (param.kind()) {
case CLASS:
return parseClassOrInterfaceType(param.asClassType().name().toString());
return parseClassOrInterfaceType(fromDotName(param.asClassType().name()));
case PRIMITIVE:
return parseType(param.asPrimitiveType().name().toString());
return parseType(fromDotName(param.asPrimitiveType().name()));
case PARAMETERIZED_TYPE:
return parseClassOrInterfaceType(param.asParameterizedType().name().toString())
.setTypeArguments(NodeList.nodeList(param.asParameterizedType().arguments().stream().map(this::fromClass).collect(Collectors.toList())));
ClassOrInterfaceType result = parseClassOrInterfaceType(fromDotName(param.asParameterizedType().name()));
if (includeGeneric) {
Copy link
Contributor Author

@fjtirado fjtirado Oct 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And this is basically the fix (rest of clasess on this PR are for testing), we do not want to include generic when the ClassExpr is not used for casting. Since the caller knows the usage, an extra boolean parameter was added to the method

result.setTypeArguments(NodeList.nodeList(param.asParameterizedType().arguments().stream().map(this::fromClass).collect(Collectors.toList())));
}
return result;
default:
throw new UnsupportedOperationException("Kind " + param.kind() + " is not supported");
}
}

private String fromDotName(DotName dotName) {
String result = dotName.toString();
if (dotName.isInner()) {
Copy link
Contributor Author

@fjtirado fjtirado Oct 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Supporting inner classes, it is really unfortunate that DotName.toString use Class.getName rather than Class.getCanonicalName, forcing us to add this code to replace the $

result = result.replace('$', '.');
}
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ private WorkflowHandlerGeneratedFile generateHandler(KogitoBuildContext context,
if (annotation != null) {
methodCallExpr.addArgument(new CastExpr(fromClass(param), new MethodCallExpr(parameters, "remove").addArgument(new StringLiteralExpr(annotation.value().asString()))));
} else {
methodCallExpr.addArgument(new MethodCallExpr("buildBody").addArgument(parameters).addArgument(new ClassExpr(fromClass(param))));
methodCallExpr.addArgument(new MethodCallExpr("buildBody").addArgument(parameters).addArgument(new ClassExpr(fromClass(param, false))));
}
}
clazz.addMethod("getRestClass", Keyword.PROTECTED).setType(parseClassOrInterfaceType(Class.class.getCanonicalName()).setTypeArguments(classNameType))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ quarkus.flyway.clean-at-start=true

quarkus.http.test-port=0
quarkus.log.level=INFO
#quarkus.log.category."org.kie.kogito".level=DEBUG
#quarkus.log.category."org.kie.kogito.serverless.workflow".level=DEBUG

# To include the greethidden workflow
kogito.codegen.ignoreHiddenFiles=false
Expand All @@ -20,6 +20,7 @@ quarkus.kubernetes-client.devservices.enabled=false
# OpenApi client properties, see OperationsMockService, which is mocking these two services
quarkus.rest-client.multiplication.url=${multiplication-service-mock.url}
quarkus.rest-client.subtraction.url=${subtraction-service-mock.url}
quarkus.rest-client.array_yaml.url=${array-service-mock.url}

# OpenApi client properties to access the general purpose external-service, which is mocked by the ExternalServiceMock
quarkus.rest-client.external_service_yaml.url=${external-service-mock.url}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"id": "openapiarray",
"name": "Open API Array Test",
"version": "v1.0",
"start": "DoIt",
"functions": [
{
"name": "testArray",
"operation": "specs/array.yaml#testArray"
}
],
"states": [
{
"name": "DoIt",
"type": "operation",
"actions": [
{
"name": "testArray",
"functionRef": {
"refName": "testArray",
"arguments": ".inputArray"
}
}],
"end": true
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
openapi: 3.0.3
info:
title: Generated API
version: "1.0"
paths:
/testArray:
post:
operationId: testArray
requestBody:
content:
application/json:
schema:
type: array
items:
type: number
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
type: number
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kie.kogito.quarkus.workflows;

import java.util.Arrays;
import java.util.Collections;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import io.quarkus.test.common.QuarkusTestResource;
import io.quarkus.test.junit.QuarkusIntegrationTest;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;

import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;

@QuarkusTestResource(OpenAPIArrayMockService.class)
@QuarkusIntegrationTest
class OpenAPIArrayFlowIT {

@BeforeAll
static void init() {
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
}

@Test
void testArray() {
given()
.contentType(ContentType.JSON)
.when()
.body(Collections.singletonMap("inputArray", Arrays.asList(1, 2, 3, 4)))
.post("/openapiarray")
.then()
.statusCode(201)
.body("id", notNullValue())
.body("workflowdata.response", is(Arrays.asList(1, 2, 3, 4)));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.kie.kogito.quarkus.workflows;

import java.util.Map;
import java.util.function.UnaryOperator;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.MappingBuilder;

import io.quarkus.test.common.QuarkusTestResourceLifecycleManager;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;

public class OpenAPIArrayMockService implements QuarkusTestResourceLifecycleManager {

private static WireMockServer arrayService;

@Override
public Map<String, String> start() {
arrayService = startServer("[1,2,3,4]", p -> p);
return Map.of("array-service-mock.url", arrayService.baseUrl());
}

@Override
public void stop() {
if (arrayService != null) {
arrayService.stop();
}
}

private static WireMockServer startServer(final String response, UnaryOperator<MappingBuilder> function) {
final WireMockServer server = new WireMockServer(options().dynamicPort());
server.start();
server.stubFor(function.apply(post(urlEqualTo("/testArray")).withRequestBody(equalToJson("[1,2,3,4]")))
.withPort(server.port())
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody(response)));
return server;
}
}