Compare commits

...

7 Commits

37 changed files with 3241 additions and 259 deletions

View File

@ -3,8 +3,9 @@
<modelVersion>4.0.0</modelVersion>
<groupId>kangaroo-and-rabbit</groupId>
<artifactId>archidata</artifactId>
<version>0.8.9</version>
<version>0.8.10-SNAPSHOOT</version>
<properties>
<java.version>21</java.version>
<maven.compiler.version>3.1</maven.compiler.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>

View File

@ -5,14 +5,21 @@ import java.util.UUID;
import org.kar.archidata.tools.UuidUtils;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.core.Response;
public class RestErrorResponse {
@NotNull
public UUID uuid = UuidUtils.nextUUID();
@NotNull
public String name; // Mandatory for TS generic error
@NotNull
public String message; // Mandatory for TS generic error
@NotNull
public String time;
@NotNull
final public int status;
@NotNull
final public String statusMessage;
public RestErrorResponse(final Response.Status status, final String time, final String error,

View File

@ -1867,4 +1867,4 @@ public class DataAccess {
}
return outs;
}
}
}

View File

@ -5,12 +5,10 @@ import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
@ -20,27 +18,13 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.AsyncType;
import org.kar.archidata.annotation.TypeScriptProgress;
import org.kar.archidata.catcher.RestErrorResponse;
import org.kar.archidata.dataAccess.DataFactoryZod.ClassElement;
import org.kar.archidata.dataAccess.DataFactoryZod.GeneratedTypes;
import org.kar.archidata.externalRestApi.model.ApiTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@ -124,174 +108,6 @@ public class DataFactoryTsApi {
return apis;
}
public static String apiAnnotationGetPath(final Class<?> element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Path.class);
if (annotation.length == 0) {
return null;
}
return ((Path) annotation[0]).value();
}
public static List<String> apiAnnotationProduces(final Class<?> element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Produces.class);
if (annotation.length == 0) {
return null;
}
return Arrays.asList(((Produces) annotation[0]).value());
}
public static List<String> apiAnnotationProduces(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Produces.class);
if (annotation.length == 0) {
return null;
}
return Arrays.asList(((Produces) annotation[0]).value());
}
public static boolean apiAnnotationTypeScriptProgress(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(TypeScriptProgress.class);
if (annotation.length == 0) {
return false;
}
return true;
}
public static List<String> apiAnnotationProduces(final Class<?> clazz, final Method method) throws Exception {
final List<String> data = apiAnnotationProduces(method);
if (data != null) {
return data;
}
return apiAnnotationProduces(clazz);
}
public static String apiAnnotationGetOperationDescription(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Operation.class);
if (annotation.length == 0) {
return null;
}
return ((Operation) annotation[0]).description();
}
public static String apiAnnotationGetPath(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Path.class);
if (annotation.length == 0) {
return null;
}
return ((Path) annotation[0]).value();
}
public static String apiAnnotationGetTypeRequest(final Method element) throws Exception {
if (element.getDeclaredAnnotationsByType(GET.class).length == 1) {
return "GET";
}
if (element.getDeclaredAnnotationsByType(POST.class).length == 1) {
return "POST";
}
if (element.getDeclaredAnnotationsByType(PUT.class).length == 1) {
return "PUT";
}
if (element.getDeclaredAnnotationsByType(PATCH.class).length == 1) {
return "PATCH";
}
if (element.getDeclaredAnnotationsByType(DELETE.class).length == 1) {
return "DELETE";
}
return null;
}
public static String apiAnnotationGetPathParam(final Parameter element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(PathParam.class);
if (annotation.length == 0) {
return null;
}
return ((PathParam) annotation[0]).value();
}
public static String apiAnnotationGetQueryParam(final Parameter element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(QueryParam.class);
if (annotation.length == 0) {
return null;
}
return ((QueryParam) annotation[0]).value();
}
public static String apiAnnotationGetFormDataParam(final Parameter element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(FormDataParam.class);
if (annotation.length == 0) {
return null;
}
return ((FormDataParam) annotation[0]).value();
}
public static Class<?>[] apiAnnotationGetAsyncType(final Parameter element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(AsyncType.class);
if (annotation.length == 0) {
return null;
}
return ((AsyncType) annotation[0]).value();
}
public static Class<?>[] apiAnnotationGetAsyncType(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(AsyncType.class);
if (annotation.length == 0) {
return null;
}
return ((AsyncType) annotation[0]).value();
}
public static List<String> apiAnnotationGetConsumes(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Consumes.class);
if (annotation.length == 0) {
return null;
}
return Arrays.asList(((Consumes) annotation[0]).value());
}
public static List<String> apiAnnotationGetConsumes(final Class<?> element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Consumes.class);
if (annotation.length == 0) {
return null;
}
return Arrays.asList(((Consumes) annotation[0]).value());
}
public static List<String> apiAnnotationGetConsumes(final Class<?> clazz, final Method method) throws Exception {
final List<String> data = apiAnnotationGetConsumes(method);
if (data != null) {
return data;
}
return apiAnnotationGetConsumes(clazz);
}
public static boolean apiAnnotationIsContext(final Parameter element) throws Exception {
return element.getDeclaredAnnotationsByType(Context.class).length != 0;
}
public static String convertInTypeScriptType(final List<ClassElement> tmp, final boolean isList) {
String out = "";
for (final ClassElement elem : tmp) {
if (out.length() != 0) {
out += " | ";
}
out += elem.tsTypeName;
if (isList) {
out += "[]";
}
}
return out;
}
public static String convertInTypeScriptCheckType(final List<ClassElement> tmp) {
String out = "";
for (final ClassElement elem : tmp) {
if (out.length() != 0) {
out += " | ";
}
out += elem.tsCheckType;
}
return out;
}
record OrderedElement(
String methodName,
Method method) {}
@ -303,7 +119,7 @@ public class DataFactoryTsApi {
final GeneratedTypes previous) throws Exception {
final StringBuilder builder = new StringBuilder();
// the basic path has no specific elements...
final String basicPath = apiAnnotationGetPath(clazz);
final String basicPath = ApiTool.apiAnnotationGetPath(clazz);
final String classSimpleName = clazz.getSimpleName();
builder.append("export namespace ");
@ -322,22 +138,22 @@ public class DataFactoryTsApi {
for (final OrderedElement orderedElement : orderedElements) {
final Method method = orderedElement.method();
final String methodName = orderedElement.methodName();
final String methodPath = apiAnnotationGetPath(method);
final String methodType = apiAnnotationGetTypeRequest(method);
final String methodPath = ApiTool.apiAnnotationGetPath(method);
final String methodType = ApiTool.apiAnnotationGetTypeRequest(method);
if (methodType == null) {
LOGGER.error(" [{}] {} => {}/{} ==> No methode type @PATH, @GET ...", methodType, methodName,
basicPath, methodPath);
continue;
}
final String methodDescription = apiAnnotationGetOperationDescription(method);
final List<String> consumes = apiAnnotationGetConsumes(clazz, method);
List<String> produces = apiAnnotationProduces(clazz, method);
final String methodDescription = ApiTool.apiAnnotationGetOperationDescription(method);
final List<String> consumes = ApiTool.apiAnnotationGetConsumes(clazz, method);
List<String> produces = ApiTool.apiAnnotationProduces(clazz, method);
LOGGER.trace(" [{}] {} => {}/{}", methodType, methodName, basicPath, methodPath);
if (methodDescription != null) {
LOGGER.trace(" description: {}", methodDescription);
}
final boolean needGenerateProgress = apiAnnotationTypeScriptProgress(method);
Class<?>[] returnTypeModel = apiAnnotationGetAsyncType(method);
final boolean needGenerateProgress = ApiTool.apiAnnotationTypeScriptProgress(method);
Class<?>[] returnTypeModel = ApiTool.apiAnnotationGetAsyncType(method);
boolean isUnmanagedReturnType = false;
boolean returnModelIsArray = false;
List<ClassElement> tmpReturn;
@ -399,12 +215,12 @@ public class DataFactoryTsApi {
// LOGGER.info(" Parameters:");
for (final Parameter parameter : method.getParameters()) {
// Security context are internal parameter (not available from API)
if (apiAnnotationIsContext(parameter)) {
if (ApiTool.apiAnnotationIsContext(parameter)) {
continue;
}
final Class<?> parameterType = parameter.getType();
String parameterTypeString;
final Class<?>[] asyncType = apiAnnotationGetAsyncType(parameter);
final Class<?>[] asyncType = ApiTool.apiAnnotationGetAsyncType(parameter);
if (parameterType == List.class) {
if (asyncType == null) {
LOGGER.warn("Detect List param ==> not managed type ==> any[] !!!");
@ -414,7 +230,7 @@ public class DataFactoryTsApi {
for (final ClassElement elem : tmp) {
includeModel.add(elem.model[0]);
}
parameterTypeString = convertInTypeScriptType(tmp, true);
parameterTypeString = ApiTool.convertInTypeScriptType(tmp, true);
}
} else if (asyncType == null) {
final ClassElement tmp = DataFactoryZod.createTable(parameterType, previous);
@ -425,11 +241,11 @@ public class DataFactoryTsApi {
for (final ClassElement elem : tmp) {
includeModel.add(elem.model[0]);
}
parameterTypeString = convertInTypeScriptType(tmp, true);
parameterTypeString = ApiTool.convertInTypeScriptType(tmp, true);
}
final String pathParam = apiAnnotationGetPathParam(parameter);
final String queryParam = apiAnnotationGetQueryParam(parameter);
final String formDataParam = apiAnnotationGetFormDataParam(parameter);
final String pathParam = ApiTool.apiAnnotationGetPathParam(parameter);
final String queryParam = ApiTool.apiAnnotationGetQueryParam(parameter);
final String formDataParam = ApiTool.apiAnnotationGetFormDataParam(parameter);
if (queryParam != null) {
queryParams.put(queryParam, parameterTypeString);
} else if (pathParam != null) {
@ -584,7 +400,7 @@ public class DataFactoryTsApi {
|| tmpReturn.get(0).tsTypeName.equals("void")) {
builder.append("void");
} else {
builder.append(convertInTypeScriptType(tmpReturn, returnModelIsArray));
builder.append(ApiTool.convertInTypeScriptType(tmpReturn, returnModelIsArray));
}
builder.append("> {");
if (tmpReturn.size() == 0 //
@ -656,7 +472,7 @@ public class DataFactoryTsApi {
&& !tmpReturn.get(0).tsTypeName.equals("void")) {
builder.append(", ");
// TODO: correct this it is really bad ...
builder.append(convertInTypeScriptCheckType(tmpReturn));
builder.append(ApiTool.convertInTypeScriptCheckType(tmpReturn));
}
builder.append(");");
builder.append("\n\t};");

View File

@ -0,0 +1,74 @@
package org.kar.archidata.externalRestApi;
import java.util.ArrayList;
import java.util.List;
import org.kar.archidata.externalRestApi.model.ApiGroupModel;
import org.kar.archidata.externalRestApi.model.ClassModel;
import org.kar.archidata.externalRestApi.model.ModelGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AnalyzeApi {
static final Logger LOGGER = LoggerFactory.getLogger(AnalyzeApi.class);
protected final List<ApiGroupModel> apiModels = new ArrayList<>();
protected final ModelGroup modelGroup = new ModelGroup();
public void addAllModel(final List<Class<?>> classes) throws Exception {
this.modelGroup.addAll(classes);
analyzeModels();
}
public void addModel(final Class<?> clazz) throws Exception {
this.modelGroup.add(clazz);
analyzeModels();
}
public void addApi(final Class<?> clazz) throws Exception {
this.apiModels.add(new ApiGroupModel(clazz, this.modelGroup));
analyzeModels();
}
public void addAllApi(final List<Class<?>> classes) throws Exception {
for (final Class<?> clazz : classes) {
this.apiModels.add(new ApiGroupModel(clazz, this.modelGroup));
}
analyzeModels();
}
public List<ApiGroupModel> getAllApi() {
return this.apiModels;
}
public List<ClassModel> getAllModel() {
return this.modelGroup.getModels();
}
private void analyzeModels() throws Exception {
final List<ClassModel> dones = new ArrayList<>();
while (dones.size() < getAllModel().size()) {
final List<ClassModel> copyList = new ArrayList<>(this.modelGroup.getModels());
for (final ClassModel model : copyList) {
if (dones.contains(model)) {
continue;
}
LOGGER.info("Analyze: {}", model);
model.analyze(this.modelGroup);
dones.add(model);
}
}
}
public List<ClassModel> getCompatibleModels(final List<Class<?>> search) {
final List<ClassModel> out = new ArrayList<>();
for (final ClassModel model : getAllModel()) {
if (search.contains(model.getOriginClasses())) {
out.add(model);
}
}
if (out.isEmpty()) {
return null;
}
return out;
}
}

View File

@ -0,0 +1,8 @@
package org.kar.archidata.externalRestApi;
public class PythonGenerateApi {
public static void generateApi(final AnalyzeApi api) {
}
}

View File

@ -0,0 +1,433 @@
package org.kar.archidata.externalRestApi;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.kar.archidata.dataAccess.DataExport;
import org.kar.archidata.externalRestApi.TsClassElement.DefinedPosition;
import org.kar.archidata.externalRestApi.model.ApiGroupModel;
import org.kar.archidata.externalRestApi.model.ApiModel;
import org.kar.archidata.externalRestApi.model.ClassEnumModel;
import org.kar.archidata.externalRestApi.model.ClassListModel;
import org.kar.archidata.externalRestApi.model.ClassMapModel;
import org.kar.archidata.externalRestApi.model.ClassModel;
import org.kar.archidata.externalRestApi.model.ClassObjectModel;
import org.kar.archidata.externalRestApi.model.RestTypeRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.core.MediaType;
public class TsApiGeneration {
static final Logger LOGGER = LoggerFactory.getLogger(TsApiGeneration.class);
public static String getBaseHeader() {
return """
/**
* Interface of the server (auto-generated code)
*/
""";
}
public static String generateClassEnumModelTypescript(
final ClassEnumModel model,
final TsClassElementGroup tsGroup,
final Set<ClassModel> imports,
final boolean writeMode) throws IOException {
imports.add(model);
final TsClassElement tsModel = tsGroup.find(model);
return tsModel.tsTypeName;
}
public static String generateClassObjectModelTypescript(
final ClassObjectModel model,
final TsClassElementGroup tsGroup,
final Set<ClassModel> imports,
final boolean writeMode) throws IOException {
final TsClassElement tsModel = tsGroup.find(model);
if (tsModel.nativeType != DefinedPosition.NATIVE) {
imports.add(model);
}
if (tsModel.nativeType == DefinedPosition.BASIC) {
return tsModel.tsTypeName;
}
if (writeMode) {
return tsModel.tsTypeName + "Write";
}
return tsModel.tsTypeName;
}
public static String generateClassMapModelTypescript(
final ClassMapModel model,
final TsClassElementGroup tsGroup,
final Set<ClassModel> imports,
final boolean writeMode) throws IOException {
final StringBuilder out = new StringBuilder();
out.append("{[key: ");
out.append(generateClassModelTypescript(model.keyModel, tsGroup, imports, writeMode));
out.append("]: ");
out.append(generateClassModelTypescript(model.valueModel, tsGroup, imports, writeMode));
out.append(";}");
return out.toString();
}
public static String generateClassListModelTypescript(
final ClassListModel model,
final TsClassElementGroup tsGroup,
final Set<ClassModel> imports,
final boolean writeMode) throws IOException {
final StringBuilder out = new StringBuilder();
out.append(generateClassModelTypescript(model.valueModel, tsGroup, imports, writeMode));
out.append("[]");
return out.toString();
}
public static String generateClassModelTypescript(
final ClassModel model,
final TsClassElementGroup tsGroup,
final Set<ClassModel> imports,
final boolean writeMode) throws IOException {
if (model instanceof final ClassObjectModel objectModel) {
return generateClassObjectModelTypescript(objectModel, tsGroup, imports, writeMode);
}
if (model instanceof final ClassListModel listModel) {
return generateClassListModelTypescript(listModel, tsGroup, imports, writeMode);
}
if (model instanceof final ClassMapModel mapModel) {
return generateClassMapModelTypescript(mapModel, tsGroup, imports, writeMode);
}
if (model instanceof final ClassEnumModel enumModel) {
return generateClassEnumModelTypescript(enumModel, tsGroup, imports, writeMode);
}
throw new IOException("Impossible model:" + model);
}
public static String generateClassModelsTypescript(
final List<ClassModel> models,
final TsClassElementGroup tsGroup,
final Set<ClassModel> imports,
final boolean writeMode) throws IOException {
if (models.size() == 0) {
return "void";
}
final StringBuilder out = new StringBuilder();
boolean isFirst = true;
for (final ClassModel model : models) {
if (isFirst) {
isFirst = false;
} else {
out.append(" | ");
}
final String data = generateClassModelTypescript(model, tsGroup, imports, writeMode);
out.append(data);
}
return out.toString();
}
public static String capitalizeFirstLetter(final String str) {
if (str == null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
public static void generateApiFile(
final ApiGroupModel element,
final String pathPackage,
final TsClassElementGroup tsGroup) throws IOException {
final StringBuilder data = new StringBuilder();
data.append("export namespace ");
data.append(element.name);
data.append(" {\n");
final Set<ClassModel> imports = new HashSet<>();
final Set<ClassModel> zodImports = new HashSet<>();
final Set<ClassModel> isImports = new HashSet<>();
final Set<ClassModel> writeImports = new HashSet<>();
final Set<String> toolImports = new HashSet<>();
for (final ApiModel interfaceElement : element.interfaces) {
final List<String> consumes = interfaceElement.consumes;
final List<String> produces = interfaceElement.produces;
final boolean needGenerateProgress = interfaceElement.needGenerateProgress;
final String returnModelNameIfComplex = capitalizeFirstLetter(interfaceElement.name) + "TypeReturn";
final String returnComplexModel = TsClassElement.generateLocalModel(returnModelNameIfComplex,
interfaceElement.returnTypes, tsGroup);
if (returnComplexModel != null) {
data.append("\n\n");
data.append(returnComplexModel.replaceAll("(?m)^", "\t"));
for (final ClassModel elem : interfaceElement.returnTypes) {
zodImports.addAll(elem.getDependencyGroupModels());
}
}
if (interfaceElement.description != null) {
data.append("\n\t/**\n\t * ");
data.append(interfaceElement.description);
data.append("\n\t */");
}
data.append("\n\texport function ");
data.append(interfaceElement.name);
data.append("({\n\t\t\trestConfig,");
if (!interfaceElement.queries.isEmpty()) {
data.append("\n\t\t\tqueries,");
}
if (!interfaceElement.parameters.isEmpty()) {
data.append("\n\t\t\tparams,");
}
if (produces != null && produces.size() > 1) {
data.append("\n\t\t\tproduce,");
}
if (interfaceElement.unnamedElement.size() == 1 || interfaceElement.multiPartParameters.size() != 0) {
data.append("\n\t\t\tdata,");
}
if (needGenerateProgress) {
data.append("\n\t\t\tcallback,");
}
data.append("\n\t\t}: {");
data.append("\n\t\trestConfig: RESTConfig,");
toolImports.add("RESTConfig");
if (!interfaceElement.queries.isEmpty()) {
data.append("\n\t\tqueries: {");
for (final Entry<String, List<ClassModel>> queryEntry : interfaceElement.queries.entrySet()) {
data.append("\n\t\t\t");
data.append(queryEntry.getKey());
data.append("?: ");
data.append(generateClassModelsTypescript(queryEntry.getValue(), tsGroup, imports, false));
data.append(",");
}
data.append("\n\t\t},");
}
if (!interfaceElement.parameters.isEmpty()) {
data.append("\n\t\tparams: {");
for (final Entry<String, List<ClassModel>> paramEntry : interfaceElement.parameters.entrySet()) {
data.append("\n\t\t\t");
data.append(paramEntry.getKey());
data.append(": ");
data.append(generateClassModelsTypescript(paramEntry.getValue(), tsGroup, imports, false));
data.append(",");
}
data.append("\n\t\t},");
}
if (interfaceElement.unnamedElement.size() == 1) {
data.append("\n\t\tdata: ");
data.append(generateClassModelTypescript(interfaceElement.unnamedElement.get(0), tsGroup, writeImports,
true));
data.append(",");
} else if (interfaceElement.multiPartParameters.size() != 0) {
data.append("\n\t\tdata: {");
for (final Entry<String, List<ClassModel>> pathEntry : interfaceElement.multiPartParameters
.entrySet()) {
data.append("\n\t\t\t");
data.append(pathEntry.getKey());
data.append(": ");
data.append(generateClassModelsTypescript(pathEntry.getValue(), tsGroup, writeImports, true));
data.append(",");
}
data.append("\n\t\t},");
}
if (produces != null && produces.size() > 1) {
data.append("\n\t\tproduce: ");
String isFist = null;
for (final String elem : produces) {
String lastElement = null;
if (MediaType.APPLICATION_JSON.equals(elem)) {
lastElement = "HTTPMimeType.JSON";
toolImports.add("HTTPMimeType");
}
if (MediaType.MULTIPART_FORM_DATA.equals(elem)) {
lastElement = "HTTPMimeType.MULTIPART";
toolImports.add("HTTPMimeType");
}
if (DataExport.CSV_TYPE.equals(elem)) {
lastElement = "HTTPMimeType.CSV";
toolImports.add("HTTPMimeType");
}
if (lastElement != null) {
if (isFist == null) {
isFist = lastElement;
} else {
data.append(" | ");
}
data.append(lastElement);
} else {
LOGGER.error("Unmanaged model type: {}", elem);
}
}
data.append(",");
}
if (needGenerateProgress) {
data.append("\n\t\tcallback?: RESTCallbacks,");
toolImports.add("RESTCallbacks");
}
data.append("\n\t}): Promise<");
if (returnComplexModel != null) {
data.append(returnModelNameIfComplex);
data.append("> {");
data.append("\n\t\treturn RESTRequestJson({");
toolImports.add("RESTRequestJson");
} else {
final String returnType = generateClassModelsTypescript(interfaceElement.returnTypes, tsGroup, imports,
false);
data.append(returnType);
data.append("> {");
if ("void".equals(returnType)) {
data.append("\n\t\treturn RESTRequestVoid({");
toolImports.add("RESTRequestVoid");
} else {
isImports.addAll(interfaceElement.returnTypes);
data.append("\n\t\treturn RESTRequestJson({");
toolImports.add("RESTRequestJson");
}
}
data.append("\n\t\t\trestModel: {");
data.append("\n\t\t\t\tendPoint: \"");
data.append(interfaceElement.restEndPoint);
data.append("\",");
data.append("\n\t\t\t\trequestType: HTTPRequestModel.");
toolImports.add("HTTPRequestModel");
data.append(interfaceElement.restTypeRequest);
data.append(",");
if (consumes != null) {
for (final String elem : consumes) {
if (MediaType.APPLICATION_JSON.equals(elem)) {
data.append("\n\t\t\t\tcontentType: HTTPMimeType.JSON,");
toolImports.add("HTTPMimeType");
break;
} else if (MediaType.MULTIPART_FORM_DATA.equals(elem)) {
data.append("\n\t\t\t\tcontentType: HTTPMimeType.MULTIPART,");
toolImports.add("HTTPMimeType");
break;
} else if (MediaType.TEXT_PLAIN.equals(elem)) {
data.append("\n\t\t\t\tcontentType: HTTPMimeType.TEXT_PLAIN,");
toolImports.add("HTTPMimeType");
break;
}
}
} else if (RestTypeRequest.DELETE.equals(interfaceElement.restTypeRequest)) {
data.append("\n\t\t\t\tcontentType: HTTPMimeType.TEXT_PLAIN,");
toolImports.add("HTTPMimeType");
}
if (produces != null) {
if (produces.size() > 1) {
data.append("\n\t\t\t\taccept: produce,");
} else {
for (final String elem : produces) {
if (MediaType.APPLICATION_JSON.equals(elem)) {
data.append("\n\t\t\t\taccept: HTTPMimeType.JSON,");
toolImports.add("HTTPMimeType");
break;
}
}
}
}
data.append("\n\t\t\t},");
data.append("\n\t\t\trestConfig,");
if (!interfaceElement.parameters.isEmpty()) {
data.append("\n\t\t\tparams,");
}
if (!interfaceElement.queries.isEmpty()) {
data.append("\n\t\t\tqueries,");
}
if (interfaceElement.unnamedElement.size() == 1) {
data.append("\n\t\t\tdata,");
} else if (interfaceElement.multiPartParameters.size() != 0) {
data.append("\n\t\t\tdata,");
}
if (needGenerateProgress) {
data.append("\n\t\t\tcallback,");
}
data.append("\n\t\t}");
if (returnComplexModel != null) {
data.append(", is");
data.append(returnModelNameIfComplex);
} else {
final String returnType = generateClassModelsTypescript(interfaceElement.returnTypes, tsGroup, imports,
false);
if (!"void".equals(returnType)) {
data.append(", is");
data.append(returnType);
}
}
data.append(");");
data.append("\n\t};");
}
data.append("\n}\n");
final StringBuilder out = new StringBuilder();
out.append(getBaseHeader());
final List<String> toolImportsList = new ArrayList<>(toolImports);
Collections.sort(toolImportsList);
if (toolImportsList.size() != 0) {
out.append("import {");
for (final String elem : toolImportsList) {
out.append("\n\t");
out.append(elem);
out.append(",");
}
out.append("\n} from \"../rest-tools\";\n\n");
}
if (zodImports.size() != 0) {
out.append("import { z as zod } from \"zod\"\n");
}
final List<String> finalImportList = new ArrayList<>();
for (final ClassModel model : imports) {
final TsClassElement tsModel = tsGroup.find(model);
if (tsModel.nativeType == DefinedPosition.NATIVE) {
continue;
}
finalImportList.add(tsModel.tsTypeName);
}
for (final ClassModel model : isImports) {
final TsClassElement tsModel = tsGroup.find(model);
if (tsModel.nativeType == DefinedPosition.NATIVE) {
continue;
}
finalImportList.add("is" + tsModel.tsTypeName);
}
for (final ClassModel model : zodImports) {
final TsClassElement tsModel = tsGroup.find(model);
if (tsModel.nativeType == DefinedPosition.NATIVE) {
continue;
}
finalImportList.add("Zod" + tsModel.tsTypeName);
}
for (final ClassModel model : writeImports) {
final TsClassElement tsModel = tsGroup.find(model);
if (tsModel.nativeType == DefinedPosition.NATIVE) {
continue;
}
finalImportList.add(tsModel.tsTypeName + "Write");
}
Collections.sort(finalImportList);
if (finalImportList.size() != 0) {
out.append("import {");
for (final String elem : finalImportList) {
out.append("\n\t");
out.append(elem);
out.append(",");
}
out.append("\n} from \"../model\";\n\n");
}
out.append(data.toString());
final String fileName = TsClassElement.determineFileName(element.name);
final FileWriter myWriter = new FileWriter(
pathPackage + File.separator + "api" + File.separator + fileName + ".ts");
myWriter.write(out.toString());
myWriter.close();
}
}

View File

@ -0,0 +1,473 @@
package org.kar.archidata.externalRestApi;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import org.kar.archidata.externalRestApi.model.ClassEnumModel;
import org.kar.archidata.externalRestApi.model.ClassListModel;
import org.kar.archidata.externalRestApi.model.ClassMapModel;
import org.kar.archidata.externalRestApi.model.ClassModel;
import org.kar.archidata.externalRestApi.model.ClassObjectModel;
import org.kar.archidata.externalRestApi.model.ClassObjectModel.FieldProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TsClassElement {
static final Logger LOGGER = LoggerFactory.getLogger(TsClassElement.class);
public enum DefinedPosition {
NATIVE, // Native element of TS language.
BASIC, // basic wrapping for JAVA type.
NORMAL // Normal Object to interpret.
}
public List<ClassModel> models;
public String zodName;
public String tsTypeName;
public String tsCheckType;
public String declaration;
public String fileName = null;
public String comment = null;
public DefinedPosition nativeType = DefinedPosition.NORMAL;
public static String determineFileName(final String className) {
return className.replaceAll("([a-z])([A-Z])", "$1-$2").replaceAll("([A-Z])([A-Z][a-z])", "$1-$2").toLowerCase();
}
public TsClassElement(final List<ClassModel> model, final String zodName, final String tsTypeName,
final String tsCheckType, final String declaration, final DefinedPosition nativeType) {
this.models = model;
this.zodName = zodName;
this.tsTypeName = tsTypeName;
this.tsCheckType = tsCheckType;
this.declaration = declaration;
this.nativeType = nativeType;
this.fileName = determineFileName(tsTypeName);
}
public TsClassElement(final ClassModel model) {
this.models = List.of(model);
this.zodName = "Zod" + model.getOriginClasses().getSimpleName();
this.tsTypeName = model.getOriginClasses().getSimpleName();
this.tsCheckType = "is" + model.getOriginClasses().getSimpleName();
this.declaration = null;
this.fileName = determineFileName(this.tsTypeName);
}
public boolean isCompatible(final ClassModel model) {
return this.models.contains(model);
}
public String getBaseHeader() {
return """
/**
* Interface of the server (auto-generated code)
*/
import { z as zod } from "zod";
""";
}
public String generateEnum(final ClassEnumModel model, final TsClassElementGroup tsGroup) throws IOException {
final StringBuilder out = new StringBuilder();
out.append(getBaseHeader());
out.append("\n");
//out.append(generateComment(model));
if (System.getenv("ARCHIDATA_GENERATE_ZOD_ENUM") != null) {
boolean first = true;
out.append("export const ");
out.append(this.tsTypeName);
out.append(" = ");
out.append("zod.enum([");
for (final String elem : model.getListOfValues()) {
if (!first) {
out.append(",\n\t");
} else {
out.append("\n\t");
first = false;
}
out.append("'");
out.append(elem);
out.append("'");
}
if (first) {
out.append("]}");
} else {
out.append("\n\t])");
}
out.append(";\n");
out.append(generateZodInfer(this.tsTypeName, this.zodName));
} else {
boolean first = true;
out.append("export enum ");
out.append(this.tsTypeName);
out.append(" {");
for (final String elem : model.getListOfValues()) {
if (!first) {
out.append(",\n\t");
} else {
out.append("\n\t");
first = false;
}
out.append(elem);
out.append(" = '");
out.append(elem);
out.append("'");
}
if (first) {
out.append("}");
} else {
out.append(",\n\t}");
}
out.append(";\n");
out.append("\nexport const ");
out.append(this.zodName);
out.append(" = zod.nativeEnum(");
out.append(this.tsTypeName);
out.append(");\n");
}
out.append(generateExportCheckFunctionWrite(""));
return out.toString();
}
private static String generateExportCheckFunction(
final String tsCheckType,
final String tsTypeName,
final String zodName) {
final StringBuilder out = new StringBuilder();
out.append("\nexport function ");
out.append(tsCheckType);
out.append("(data: any): data is ");
out.append(tsTypeName);
out.append(" {\n\ttry {\n\t\t");
out.append(zodName);
out.append("""
.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data type='""");
out.append(zodName);
out.append("""
' error=${e}`);
return false;
}
}
""");
return out.toString();
}
private String generateExportCheckFunctionWrite(final String writeString) {
return generateExportCheckFunction(this.tsCheckType + writeString, this.tsTypeName + writeString,
this.zodName + writeString);
}
public String generateImports(final List<ClassModel> depModels, final TsClassElementGroup tsGroup)
throws IOException {
final StringBuilder out = new StringBuilder();
for (final ClassModel depModel : depModels) {
final TsClassElement tsModel = tsGroup.find(depModel);
if (tsModel.nativeType != DefinedPosition.NATIVE) {
out.append("import {");
out.append(tsModel.zodName);
out.append("} from \"./");
out.append(tsModel.fileName);
out.append("\";\n");
}
}
return out.toString();
}
private Object generateComment(final ClassObjectModel model) {
final StringBuilder out = new StringBuilder();
if (model.getDescription() != null || model.getExample() != null) {
out.append("/**\n");
if (model.getDescription() != null) {
for (final String elem : model.getDescription().split("\n")) {
out.append(" * ");
out.append(elem);
out.append("\n");
}
}
if (model.getExample() != null) {
out.append(" * Example:\n");
out.append(" * ```\n");
for (final String elem : model.getExample().split("\n")) {
out.append(" * ");
out.append(elem);
out.append("\n");
}
out.append(" * ```\n");
}
out.append(" */\n");
}
return out.toString();
}
public String optionalTypeZod(final FieldProperty field) {
if (field.model().getOriginClasses() == null || field.model().getOriginClasses().isPrimitive()) {
return "";
}
if (field.notNull()) {
return "";
}
return ".optional()";
}
public String maxSizeZod(final FieldProperty field) {
final StringBuilder builder = new StringBuilder();
final Class<?> clazz = field.model().getOriginClasses();
if (field.limitSize() > 0 && clazz == String.class) {
builder.append(".max(");
builder.append(field.limitSize());
builder.append(")");
}
return builder.toString();
}
public String readOnlyZod(final FieldProperty field) {
if (field.readOnly()) {
return ".readonly()";
}
return "";
}
public String generateBaseObject() {
final StringBuilder out = new StringBuilder();
out.append(getBaseHeader());
out.append("\n");
out.append("export const ");
out.append(this.zodName);
out.append(" = ");
out.append(this.declaration);
out.append(";");
out.append(generateZodInfer(this.tsTypeName, this.zodName));
return out.toString();
}
public String generateObject(final ClassObjectModel model, final TsClassElementGroup tsGroup) throws IOException {
final StringBuilder out = new StringBuilder();
out.append(getBaseHeader());
out.append(generateImports(model.getDependencyModels(), tsGroup));
out.append("\n");
out.append(generateComment(model));
out.append("export const ");
out.append(this.zodName);
out.append(" = ");
if (model.getExtendsClass() != null) {
final ClassModel parentClass = model.getExtendsClass();
final TsClassElement tsParentModel = tsGroup.find(parentClass);
out.append(tsParentModel.zodName);
out.append(".extend({");
} else {
out.append("zod.object({");
}
out.append("\n");
for (final FieldProperty field : model.getFields()) {
final ClassModel fieldModel = field.model();
if (field.comment() != null) {
out.append("\t/**\n");
out.append("\t * ");
out.append(field.comment());
out.append("\n\t */\n");
}
out.append("\t");
out.append(field.name());
out.append(": ");
if (fieldModel instanceof ClassEnumModel || fieldModel instanceof ClassObjectModel) {
final TsClassElement tsFieldModel = tsGroup.find(fieldModel);
out.append(tsFieldModel.zodName);
} else if (fieldModel instanceof final ClassListModel fieldListModel) {
final String data = generateTsList(fieldListModel, tsGroup);
out.append(data);
} else if (fieldModel instanceof final ClassMapModel fieldMapModel) {
final String data = generateTsMap(fieldMapModel, tsGroup);
out.append(data);
}
out.append(maxSizeZod(field));
out.append(readOnlyZod(field));
out.append(optionalTypeZod(field));
out.append(",\n");
}
final List<String> omitField = model.getReadOnlyField();
out.append("\n});\n");
out.append(generateZodInfer(this.tsTypeName, this.zodName));
out.append(generateExportCheckFunctionWrite(""));
// Generate the Write Type associated.
out.append("\nexport const ");
out.append(this.zodName);
out.append("Write = ");
out.append(this.zodName);
if (omitField.size() != 0) {
out.append(".omit({\n");
for (final String elem : omitField) {
out.append("\t");
out.append(elem);
out.append(": true,\n");
}
out.append("\n})");
}
out.append(".partial();\n");
out.append(generateZodInfer(this.tsTypeName + "Write", this.zodName + "Write"));
// Check only the input value ==> no need of the output
out.append(generateExportCheckFunctionWrite("Write"));
return out.toString();
}
private static String generateZodInfer(final String tsName, final String zodName) {
final StringBuilder out = new StringBuilder();
out.append("\nexport type ");
out.append(tsName);
out.append(" = zod.infer<typeof ");
out.append(zodName);
out.append(">;\n");
return out.toString();
}
private static String generateTsMap(final ClassMapModel model, final TsClassElementGroup tsGroup) {
final StringBuilder out = new StringBuilder();
out.append("zod.record(");
if (model.keyModel instanceof final ClassListModel fieldListModel) {
final String tmp = generateTsList(fieldListModel, tsGroup);
out.append(tmp);
} else if (model.keyModel instanceof final ClassMapModel fieldMapModel) {
final String tmp = generateTsMap(fieldMapModel, tsGroup);
out.append(tmp);
} else if (model.keyModel instanceof final ClassObjectModel fieldObjectModel) {
final String tmp = generateTsObject(fieldObjectModel, tsGroup);
out.append(tmp);
} else if (model.keyModel instanceof final ClassEnumModel fieldEnumModel) {
final String tmp = generateTsEnum(fieldEnumModel, tsGroup);
out.append(tmp);
}
out.append(", ");
if (model.valueModel instanceof final ClassListModel fieldListModel) {
final String tmp = generateTsList(fieldListModel, tsGroup);
out.append(tmp);
} else if (model.valueModel instanceof final ClassMapModel fieldMapModel) {
final String tmp = generateTsMap(fieldMapModel, tsGroup);
out.append(tmp);
} else if (model.valueModel instanceof final ClassObjectModel fieldObjectModel) {
final String tmp = generateTsObject(fieldObjectModel, tsGroup);
out.append(tmp);
} else if (model.valueModel instanceof final ClassEnumModel fieldEnumModel) {
final String tmp = generateTsEnum(fieldEnumModel, tsGroup);
out.append(tmp);
}
out.append(")");
return out.toString();
}
private static String generateTsEnum(final ClassEnumModel model, final TsClassElementGroup tsGroup) {
final TsClassElement tsParentModel = tsGroup.find(model);
return tsParentModel.zodName;
}
private static String generateTsObject(final ClassObjectModel model, final TsClassElementGroup tsGroup) {
final TsClassElement tsParentModel = tsGroup.find(model);
return tsParentModel.zodName;
}
private static String generateTsList(final ClassListModel model, final TsClassElementGroup tsGroup) {
final StringBuilder out = new StringBuilder();
out.append("zod.array(");
if (model.valueModel instanceof final ClassListModel fieldListModel) {
final String tmp = generateTsList(fieldListModel, tsGroup);
out.append(tmp);
} else if (model.valueModel instanceof final ClassMapModel fieldMapModel) {
final String tmp = generateTsMap(fieldMapModel, tsGroup);
out.append(tmp);
} else if (model.valueModel instanceof final ClassObjectModel fieldObjectModel) {
final String tmp = generateTsObject(fieldObjectModel, tsGroup);
out.append(tmp);
}
out.append(")");
return out.toString();
}
public void generateFile(final String pathPackage, final TsClassElementGroup tsGroup) throws IOException {
if (this.nativeType == DefinedPosition.NATIVE) {
return;
}
final ClassModel model = this.models.get(0);
String data = "";
if (this.nativeType == DefinedPosition.BASIC && model instanceof ClassObjectModel) {
data = generateBaseObject();
} else if (model instanceof final ClassEnumModel modelEnum) {
data = generateEnum(modelEnum, tsGroup);
} else if (model instanceof final ClassObjectModel modelObject) {
data = generateObject(modelObject, tsGroup);
}
final Path path = Paths.get(pathPackage + File.separator + "model");
if (Files.notExists(path)) {
Files.createDirectory(path);
}
final FileWriter myWriter = new FileWriter(
pathPackage + File.separator + "model" + File.separator + this.fileName + ".ts");
myWriter.write(data);
myWriter.close();
}
private static String generateLocalModelBase(final ClassModel model, final TsClassElementGroup tsGroup)
throws IOException {
if (model instanceof final ClassObjectModel objectModel) {
return generateTsObject(objectModel, tsGroup);
}
if (model instanceof final ClassEnumModel enumModel) {
return generateTsEnum(enumModel, tsGroup);
}
if (model instanceof final ClassListModel listModel) {
return generateTsList(listModel, tsGroup);
}
if (model instanceof final ClassMapModel mapModel) {
return generateTsMap(mapModel, tsGroup);
}
return "";
}
public static String generateLocalModel(
final String ModelName,
final List<ClassModel> models,
final TsClassElementGroup tsGroup) throws IOException {
if (models.size() == 1) {
if (models.get(0) instanceof ClassObjectModel) {
return null;
}
if (models.get(0) instanceof ClassEnumModel) {
return null;
}
}
final StringBuilder out = new StringBuilder();
out.append("export const Zod");
out.append(ModelName);
out.append(" = ");
if (models.size() == 1) {
out.append(generateLocalModelBase(models.get(0), tsGroup));
out.append(";");
} else {
out.append("z.union([\n");
for (final ClassModel model : models) {
out.append("\t");
out.append(generateLocalModelBase(models.get(0), tsGroup));
out.append(",\n");
}
out.append("]);");
}
//model.getDependencyModels()
out.append(generateZodInfer(ModelName, "Zod" + ModelName));
out.append(generateExportCheckFunction("is" + ModelName, ModelName, "Zod" + ModelName));
return out.toString();
}
}

View File

@ -0,0 +1,27 @@
package org.kar.archidata.externalRestApi;
import java.util.List;
import org.kar.archidata.externalRestApi.model.ClassModel;
public class TsClassElementGroup {
private final List<TsClassElement> tsElements;
public List<TsClassElement> getTsElements() {
return this.tsElements;
}
public TsClassElementGroup(final List<TsClassElement> tsElements) {
this.tsElements = tsElements;
}
public TsClassElement find(final ClassModel model) {
for (final TsClassElement elem : this.tsElements) {
if (elem.isCompatible(model)) {
return elem;
}
}
return null;
}
}

View File

@ -0,0 +1,231 @@
package org.kar.archidata.externalRestApi;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.kar.archidata.catcher.RestErrorResponse;
import org.kar.archidata.dataAccess.DataFactoryTsApi;
import org.kar.archidata.externalRestApi.TsClassElement.DefinedPosition;
import org.kar.archidata.externalRestApi.model.ApiGroupModel;
import org.kar.archidata.externalRestApi.model.ClassModel;
public class TsGenerateApi {
public static void generateApi(final AnalyzeApi api, final String pathPackage) throws Exception {
final List<TsClassElement> localModel = generateApiModel(api);
final TsClassElementGroup tsGroup = new TsClassElementGroup(localModel);
// Generates all MODEL files
for (final TsClassElement element : localModel) {
element.generateFile(pathPackage, tsGroup);
}
// Generate index of model files
createModelIndex(pathPackage, tsGroup);
for (final ApiGroupModel element : api.apiModels) {
TsApiGeneration.generateApiFile(element, pathPackage, tsGroup);
}
// Generate index of model files
createResourceIndex(pathPackage, api.apiModels);
createIndex(pathPackage);
copyResourceFile("rest-tools.ts", pathPackage + File.separator + "rest-tools.ts");
}
private static void createIndex(final String pathPackage) throws IOException {
final String out = """
/**
* Interface of the server (auto-generated code)
*/
export * from \"./model\";
export * from \"./api\";
export * from \"./rest-tools\";
""";
final FileWriter myWriter = new FileWriter(pathPackage + File.separator + "index.ts");
myWriter.write(out);
myWriter.close();
}
private static void createResourceIndex(final String pathPackage, final List<ApiGroupModel> apiModels)
throws IOException {
final StringBuilder out = new StringBuilder("""
/**
* Interface of the server (auto-generated code)
*/
""");
final List<String> files = new ArrayList<>();
for (final ApiGroupModel elem : apiModels) {
files.add(TsClassElement.determineFileName(elem.name));
}
Collections.sort(files);
for (final String elem : files) {
out.append("export * from \"./");
out.append(elem);
out.append("\"\n");
}
final FileWriter myWriter = new FileWriter(pathPackage + File.separator + "api" + File.separator + "index.ts");
myWriter.write(out.toString());
myWriter.close();
}
private static void createModelIndex(final String pathPackage, final TsClassElementGroup tsGroup)
throws IOException {
final StringBuilder out = new StringBuilder("""
/**
* Interface of the server (auto-generated code)
*/
""");
final List<String> files = new ArrayList<>();
for (final TsClassElement elem : tsGroup.getTsElements()) {
if (elem.nativeType == DefinedPosition.NATIVE) {
continue;
}
files.add(elem.fileName);
}
Collections.sort(files);
for (final String elem : files) {
out.append("export * from \"./");
out.append(elem);
out.append("\"\n");
}
final FileWriter myWriter = new FileWriter(
pathPackage + File.separator + "model" + File.separator + "index.ts");
myWriter.write(out.toString());
myWriter.close();
}
private static List<TsClassElement> generateApiModel(final AnalyzeApi api) throws Exception {
// First step is to add all specific basic elements the wrap correctly the model
final List<TsClassElement> tsModels = new ArrayList<>();
List<ClassModel> models = api.getCompatibleModels(List.of(Void.class, void.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "void", "void", null, null, DefinedPosition.NATIVE));
}
models = api.getCompatibleModels(List.of(Object.class));
if (models != null) {
tsModels.add(
new TsClassElement(models, "zod.object()", "object", null, "zod.object()", DefinedPosition.NATIVE));
}
// Map is binded to any ==> can not determine this complex model for now
models = api.getCompatibleModels(List.of(Map.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "zod.any()", "any", null, null, DefinedPosition.NATIVE));
}
models = api.getCompatibleModels(List.of(String.class));
if (models != null) {
tsModels.add(
new TsClassElement(models, "zod.string()", "string", null, "zod.string()", DefinedPosition.NATIVE));
}
models = api.getCompatibleModels(List.of(InputStream.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "z.instanceof(File)", "File", null, "z.instanceof(File)",
DefinedPosition.NATIVE));
}
models = api.getCompatibleModels(List.of(Boolean.class, boolean.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "zod.boolean()", "boolean", null, "zod.boolean()",
DefinedPosition.NATIVE));
}
models = api.getCompatibleModels(List.of(UUID.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "ZodUUID", "UUID", "isUUID", "zod.string().uuid()",
DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(Long.class, long.class));
if (models != null) {
tsModels.add(
new TsClassElement(models, "ZodLong", "Long", "isLong", "zod.number()", DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(Short.class, short.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "ZodShort", "Short", "isShort", "zod.number().safe()",
DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(Integer.class, int.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "ZodInteger", "Integer", "isInteger", "zod.number().safe()",
DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(Double.class, double.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "ZodDouble", "Double", "isDouble", "zod.number()",
DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(Float.class, float.class));
if (models != null) {
tsModels.add(
new TsClassElement(models, "ZodFloat", "Float", "isFloat", "zod.number()", DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(Instant.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "ZodInstant", "Instant", "isInstant", "zod.string()",
DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(Date.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "ZodIsoDate", "IsoDate", "isIsoDate",
"zod.string().datetime({ precision: 3 })", DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(Timestamp.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "ZodTimestamp", "Timestamp", "isTimestamp",
"zod.string().datetime({ precision: 3 })", DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(LocalDate.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "ZodLocalDate", "LocalDate", "isLocalDate", "zod.string().date()",
DefinedPosition.BASIC));
}
models = api.getCompatibleModels(List.of(LocalTime.class));
if (models != null) {
tsModels.add(new TsClassElement(models, "ZodLocalTime", "LocalTime", "isLocalTime", "zod.string().time()",
DefinedPosition.BASIC));
}
// needed for Rest interface
api.addModel(RestErrorResponse.class);
for (final ClassModel model : api.getAllModel()) {
boolean alreadyExist = false;
for (final TsClassElement elem : tsModels) {
if (elem.isCompatible(model)) {
alreadyExist = true;
break;
}
}
if (alreadyExist) {
continue;
}
tsModels.add(new TsClassElement(model));
}
return tsModels;
}
public static void copyResourceFile(final String name, final String destinationPath) throws IOException {
final InputStream ioStream = DataFactoryTsApi.class.getClassLoader().getResourceAsStream(name);
if (ioStream == null) {
throw new IllegalArgumentException("rest-tools.ts is not found");
}
final BufferedReader buffer = new BufferedReader(new InputStreamReader(ioStream));
final FileWriter myWriter = new FileWriter(destinationPath);
String line;
while ((line = buffer.readLine()) != null) {
myWriter.write(line);
myWriter.write("\n");
}
ioStream.close();
myWriter.close();
}
}

View File

@ -0,0 +1,72 @@
package org.kar.archidata.externalRestApi.model;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Temporary class that permit to order the list of API.
record OrderedElement(
String methodName,
Method method) {}
public class ApiGroupModel {
static final Logger LOGGER = LoggerFactory.getLogger(ApiGroupModel.class);
// Name of the REST end-point name
public String restEndPoint;
// Name of the Class
public String name;
// Origin class reference
public Class<?> originClass;
// List of all API
public List<ApiModel> interfaces = new ArrayList<>();
public ApiModel getInterfaceNamed(final String name) {
for (final ApiModel model : this.interfaces) {
if (name.equals(model.name)) {
return model;
}
}
return null;
}
public ApiGroupModel(final Class<?> clazz, final ModelGroup previousModel) throws Exception {
this.originClass = clazz;
// the basic path has no specific elements...
this.restEndPoint = ApiTool.apiAnnotationGetPath(clazz);
if (this.restEndPoint == null) {
this.restEndPoint = "";
}
this.name = clazz.getSimpleName();
final List<String> consumes = ApiTool.apiAnnotationGetConsumes(clazz);
final List<String> produces = ApiTool.apiAnnotationProduces(clazz);
// Get all method to order it. This permit to stabilize the generation.
// JAVA has dynamic allocation of member order, then we need to order it?.
final List<OrderedElement> orderedElements = new ArrayList<>();
for (final Method method : clazz.getDeclaredMethods()) {
final String methodName = method.getName();
orderedElements.add(new OrderedElement(methodName, method));
}
final Comparator<OrderedElement> comparator = Comparator.comparing(OrderedElement::methodName);
Collections.sort(orderedElements, comparator);
for (final OrderedElement orderedElement : orderedElements) {
// Check if the path is available
final RestTypeRequest methodType = ApiTool.apiAnnotationGetTypeRequest2(orderedElement.method());
if (methodType == null) {
LOGGER.info(" [{}] {} ==> No methode type @PATH, @GET ...", methodType, orderedElement.methodName());
continue;
}
final ApiModel model = new ApiModel(clazz, orderedElement.method(), this.restEndPoint, consumes, produces,
previousModel);
this.interfaces.add(model);
}
}
}

View File

@ -0,0 +1,164 @@
package org.kar.archidata.externalRestApi.model;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ApiModel {
static final Logger LOGGER = LoggerFactory.getLogger(ApiModel.class);
Class<?> originClass;
Method orignMethod;
// Name of the REST end-point name
public String restEndPoint;
// Type of the request:
public RestTypeRequest restTypeRequest;
// Description of the API
public String description;
// need to generate the progression of stream (if possible)
public boolean needGenerateProgress;
// List of types returned by the API
public List<ClassModel> returnTypes = new ArrayList<>();;
// Name of the API (function name)
public String name;
// list of all parameters (/{key}/...
public final Map<String, List<ClassModel>> parameters = new HashMap<>();
// list of all query (?key...)
public final Map<String, List<ClassModel>> queries = new HashMap<>();
// when request multi-part, need to separate it.
public final Map<String, List<ClassModel>> multiPartParameters = new HashMap<>();
// model of data available
public final List<ClassModel> unnamedElement = new ArrayList<>();
// Possible input type of the REST API
public List<String> consumes = new ArrayList<>();
// Possible output type of the REST API
public List<String> produces = new ArrayList<>();
private void updateReturnTypes(final Method method, final ModelGroup previousModel) throws Exception {
// get return type from the user specification:
final Class<?>[] returnTypeModel = ApiTool.apiAnnotationGetAsyncType(method);
LOGGER.info("Get return Type async = {}", returnTypeModel);
if (returnTypeModel != null) {
if (returnTypeModel.length == 0) {
throw new IOException("Create a @AsyncType with empty elements ...");
}
for (final Class<?> clazz : returnTypeModel) {
if (clazz == Void.class || clazz == void.class) {
this.returnTypes.add(previousModel.add(Void.class));
} else if (clazz == List.class) {
throw new IOException("Unmanaged List.class in @AsyncType.");
} else if (clazz == Map.class) {
throw new IOException("Unmanaged Map.class in @AsyncType.");
} else {
this.returnTypes.add(previousModel.add(clazz));
}
}
return;
}
final Class<?> returnTypeModelRaw = method.getReturnType();
LOGGER.info("Get return Type RAW = {}", returnTypeModelRaw.getCanonicalName());
if (returnTypeModelRaw == Map.class) {
LOGGER.warn("Model Map");
final Type listType = method.getGenericReturnType();
final ClassModel modelGenerated = ClassModel.getModel(listType, previousModel);
this.returnTypes.add(modelGenerated);
LOGGER.warn("Model Map ==> {}", modelGenerated);
return;
} else if (returnTypeModelRaw == List.class) {
LOGGER.warn("Model List");
final Type listType = method.getGenericReturnType();
final ClassModel modelGenerated = ClassModel.getModel(listType, previousModel);
this.returnTypes.add(modelGenerated);
LOGGER.warn("Model List ==> {}", modelGenerated);
return;
} else {
LOGGER.warn("Model Object");
this.returnTypes.add(previousModel.add(returnTypeModelRaw));
}
LOGGER.warn("List of returns elements:");
for (final ClassModel elem : this.returnTypes) {
LOGGER.warn(" - {}", elem);
}
}
public ApiModel(final Class<?> clazz, final Method method, final String baseRestEndPoint,
final List<String> consume, final List<String> produce, final ModelGroup previousModel) throws Exception {
this.originClass = clazz;
this.orignMethod = method;
String tmpPath = ApiTool.apiAnnotationGetPath(method);
if (tmpPath == null) {
tmpPath = "";
}
this.restEndPoint = baseRestEndPoint + "/" + tmpPath;
this.restTypeRequest = ApiTool.apiAnnotationGetTypeRequest2(method);
this.name = method.getName();
this.description = ApiTool.apiAnnotationGetOperationDescription(method);
this.consumes = ApiTool.apiAnnotationGetConsumes2(consume, method);
this.produces = ApiTool.apiAnnotationProduces2(produce, method);
LOGGER.trace(" [{}] {} => {}/{}", baseRestEndPoint, this.name, this.restEndPoint);
this.needGenerateProgress = ApiTool.apiAnnotationTypeScriptProgress(method);
updateReturnTypes(method, previousModel);
LOGGER.trace(" return: {}", this.returnTypes.size());
for (final ClassModel elem : this.returnTypes) {
LOGGER.trace(" - {}", elem);
}
// LOGGER.info(" Parameters:");
for (final Parameter parameter : method.getParameters()) {
// Security context are internal parameter (not available from API)
if (ApiTool.apiAnnotationIsContext(parameter)) {
continue;
}
final Class<?> parameterType = parameter.getType();
final List<ClassModel> parameterModel = new ArrayList<>();
final Class<?>[] asyncType = ApiTool.apiAnnotationGetAsyncType(parameter);
if (asyncType != null) {
for (final Class<?> elem : asyncType) {
parameterModel.add(new ClassListModel(elem, previousModel));
}
} else if (parameterType == List.class) {
final Type parameterrizedType = parameter.getParameterizedType();
final ClassModel modelGenerated = ClassModel.getModel(parameterrizedType, previousModel);
parameterModel.add(modelGenerated);
} else if (parameterType == Map.class) {
final Type parameterrizedType = parameter.getParameterizedType();
final ClassModel modelGenerated = ClassModel.getModel(parameterrizedType, previousModel);
parameterModel.add(modelGenerated);
} else {
parameterModel.add(previousModel.add(parameterType));
}
final String pathParam = ApiTool.apiAnnotationGetPathParam(parameter);
final String queryParam = ApiTool.apiAnnotationGetQueryParam(parameter);
final String formDataParam = ApiTool.apiAnnotationGetFormDataParam(parameter);
if (queryParam != null) {
this.queries.put(queryParam, parameterModel);
} else if (pathParam != null) {
this.parameters.put(pathParam, parameterModel);
} else if (formDataParam != null) {
this.multiPartParameters.put(formDataParam, parameterModel);
} else {
this.unnamedElement.addAll(parameterModel);
}
}
if (this.unnamedElement.size() > 1) {
throw new IOException("Can not parse the API, enmpty element is more than 1 in " + this.name);
}
}
}

View File

@ -0,0 +1,233 @@
package org.kar.archidata.externalRestApi.model;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.AsyncType;
import org.kar.archidata.annotation.TypeScriptProgress;
import org.kar.archidata.dataAccess.DataFactoryZod.ClassElement;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.PATCH;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.PUT;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
public class ApiTool {
public static String apiAnnotationGetPath(final Class<?> element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Path.class);
if (annotation.length == 0) {
return null;
}
return ((Path) annotation[0]).value();
}
public static List<String> apiAnnotationProduces(final Class<?> element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Produces.class);
if (annotation.length == 0) {
return null;
}
return Arrays.asList(((Produces) annotation[0]).value());
}
public static List<String> apiAnnotationProduces(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Produces.class);
if (annotation.length == 0) {
return null;
}
return Arrays.asList(((Produces) annotation[0]).value());
}
public static boolean apiAnnotationTypeScriptProgress(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(TypeScriptProgress.class);
if (annotation.length == 0) {
return false;
}
return true;
}
public static List<String> apiAnnotationProduces(final Class<?> clazz, final Method method) throws Exception {
final List<String> data = apiAnnotationProduces(method);
if (data != null) {
return data;
}
return apiAnnotationProduces(clazz);
}
public static List<String> apiAnnotationProduces2(final List<String> parentProduce, final Method method)
throws Exception {
final List<String> data = apiAnnotationProduces(method);
if (data != null) {
return data;
}
return parentProduce;
}
public static String apiAnnotationGetOperationDescription(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Operation.class);
if (annotation.length == 0) {
return null;
}
return ((Operation) annotation[0]).description();
}
public static String apiAnnotationGetPath(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Path.class);
if (annotation.length == 0) {
return null;
}
return ((Path) annotation[0]).value();
}
public static String apiAnnotationGetTypeRequest(final Method element) throws Exception {
if (element.getDeclaredAnnotationsByType(GET.class).length == 1) {
return "GET";
}
if (element.getDeclaredAnnotationsByType(POST.class).length == 1) {
return "POST";
}
if (element.getDeclaredAnnotationsByType(PUT.class).length == 1) {
return "PUT";
}
if (element.getDeclaredAnnotationsByType(PATCH.class).length == 1) {
return "PATCH";
}
if (element.getDeclaredAnnotationsByType(DELETE.class).length == 1) {
return "DELETE";
}
return null;
}
public static RestTypeRequest apiAnnotationGetTypeRequest2(final Method element) throws Exception {
if (element.getDeclaredAnnotationsByType(GET.class).length == 1) {
return RestTypeRequest.GET;
}
if (element.getDeclaredAnnotationsByType(POST.class).length == 1) {
return RestTypeRequest.POST;
}
if (element.getDeclaredAnnotationsByType(PUT.class).length == 1) {
return RestTypeRequest.PUT;
}
if (element.getDeclaredAnnotationsByType(PATCH.class).length == 1) {
return RestTypeRequest.PATCH;
}
if (element.getDeclaredAnnotationsByType(DELETE.class).length == 1) {
return RestTypeRequest.DELETE;
}
return null;
}
public static String apiAnnotationGetPathParam(final Parameter element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(PathParam.class);
if (annotation.length == 0) {
return null;
}
return ((PathParam) annotation[0]).value();
}
public static String apiAnnotationGetQueryParam(final Parameter element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(QueryParam.class);
if (annotation.length == 0) {
return null;
}
return ((QueryParam) annotation[0]).value();
}
public static String apiAnnotationGetFormDataParam(final Parameter element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(FormDataParam.class);
if (annotation.length == 0) {
return null;
}
return ((FormDataParam) annotation[0]).value();
}
public static Class<?>[] apiAnnotationGetAsyncType(final Parameter element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(AsyncType.class);
if (annotation.length == 0) {
return null;
}
return ((AsyncType) annotation[0]).value();
}
public static Class<?>[] apiAnnotationGetAsyncType(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(AsyncType.class);
if (annotation.length == 0) {
return null;
}
return ((AsyncType) annotation[0]).value();
}
public static List<String> apiAnnotationGetConsumes(final Method element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Consumes.class);
if (annotation.length == 0) {
return null;
}
return Arrays.asList(((Consumes) annotation[0]).value());
}
public static List<String> apiAnnotationGetConsumes(final Class<?> element) throws Exception {
final Annotation[] annotation = element.getDeclaredAnnotationsByType(Consumes.class);
if (annotation.length == 0) {
return null;
}
return Arrays.asList(((Consumes) annotation[0]).value());
}
public static List<String> apiAnnotationGetConsumes(final Class<?> clazz, final Method method) throws Exception {
final List<String> data = apiAnnotationGetConsumes(method);
if (data != null) {
return data;
}
return apiAnnotationGetConsumes(clazz);
}
public static List<String> apiAnnotationGetConsumes2(final List<String> parentConsume, final Method method)
throws Exception {
final List<String> data = apiAnnotationGetConsumes(method);
if (data != null) {
return data;
}
return parentConsume;
}
public static boolean apiAnnotationIsContext(final Parameter element) throws Exception {
return element.getDeclaredAnnotationsByType(Context.class).length != 0;
}
public static String convertInTypeScriptType(final List<ClassElement> tmp, final boolean isList) {
String out = "";
for (final ClassElement elem : tmp) {
if (out.length() != 0) {
out += " | ";
}
out += elem.tsTypeName;
if (isList) {
out += "[]";
}
}
return out;
}
public static String convertInTypeScriptCheckType(final List<ClassElement> tmp) {
String out = "";
for (final ClassElement elem : tmp) {
if (out.length() != 0) {
out += " | ";
}
out += elem.tsCheckType;
}
return out;
}
}

View File

@ -0,0 +1,53 @@
package org.kar.archidata.externalRestApi.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class ClassEnumModel extends ClassModel {
protected ClassEnumModel(final Class<?> clazz) {
this.originClasses = clazz;
}
@Override
public String toString() {
final StringBuilder out = new StringBuilder();
out.append("ClassEnumModel [");
out.append(this.originClasses.getCanonicalName());
out.append("]");
return out.toString();
}
final List<String> listOfValues = new ArrayList<>();
@Override
public void analyze(final ModelGroup group) throws IOException {
if (this.analyzeDone) {
return;
}
this.analyzeDone = true;
// TODO: check if we really need to have multiple type for enums ???
// TODO: manage enum with int, String and bitField ...
final Class<?> clazz = this.originClasses;
final Object[] arr = clazz.getEnumConstants();
for (final Object elem : arr) {
this.listOfValues.add(elem.toString());
}
}
public List<String> getListOfValues() {
return this.listOfValues;
}
@Override
public Set<ClassModel> getAlls() {
return Set.of(this);
}
@Override
public Set<ClassModel> getDependencyGroupModels() {
return Set.of(this);
}
}

View File

@ -0,0 +1,47 @@
package org.kar.archidata.externalRestApi.model;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Set;
public class ClassListModel extends ClassModel {
public ClassModel valueModel;
public ClassListModel(final ClassModel valueModel) {
this.valueModel = valueModel;
}
public ClassListModel(final Class<?> clazz, final ModelGroup previousModel) throws IOException {
this.valueModel = getModel(clazz, previousModel);
}
public ClassListModel(final Type model, final ModelGroup previousModel) throws IOException {
this.valueModel = getModel(model, previousModel);
}
public ClassListModel(final ParameterizedType listType, final ModelGroup previousModel) throws IOException {
final Type model = listType.getActualTypeArguments()[0];
this.valueModel = getModel(model, previousModel);
}
@Override
public String toString() {
return "ClassListModel [valueModel=" + this.valueModel + "]";
}
@Override
public void analyze(final ModelGroup group) throws IOException {
throw new IOException("Analyze can not be done at this phase for List...");
}
@Override
public Set<ClassModel> getAlls() {
return this.valueModel.getAlls();
}
@Override
public Set<ClassModel> getDependencyGroupModels() {
return this.valueModel.getDependencyGroupModels();
}
}

View File

@ -0,0 +1,52 @@
package org.kar.archidata.externalRestApi.model;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;
public class ClassMapModel extends ClassModel {
public ClassModel keyModel;
public ClassModel valueModel;
public ClassMapModel(final ClassModel keyModel, final ClassModel valueModel) {
this.keyModel = keyModel;
this.valueModel = valueModel;
}
public ClassMapModel(final Type listTypeKey, final Type listTypeValue, final ModelGroup previousModel)
throws IOException {
this.keyModel = getModel(listTypeKey, previousModel);
this.valueModel = getModel(listTypeValue, previousModel);
}
public ClassMapModel(final ParameterizedType listType, final ModelGroup previousModel) throws IOException {
this.keyModel = getModel(listType.getActualTypeArguments()[0], previousModel);
this.valueModel = getModel(listType.getActualTypeArguments()[1], previousModel);
}
@Override
public String toString() {
return "ClassMapModel [keyModel=" + this.keyModel + ", valueModel=" + this.valueModel + "]";
}
@Override
public void analyze(final ModelGroup group) throws IOException {
throw new IOException("Analyze can not be done at this phase for Map...");
}
@Override
public Set<ClassModel> getAlls() {
final Set<ClassModel> out = new HashSet<>(this.keyModel.getAlls());
out.addAll(this.valueModel.getAlls());
return out;
}
@Override
public Set<ClassModel> getDependencyGroupModels() {
final Set<ClassModel> out = new HashSet<>(this.valueModel.getDependencyGroupModels());
out.addAll(this.keyModel.getDependencyGroupModels());
return out;
}
}

View File

@ -0,0 +1,78 @@
package org.kar.archidata.externalRestApi.model;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public abstract class ClassModel {
protected boolean analyzeDone = false;
protected Class<?> originClasses = null;
protected List<ClassModel> dependencyModels = new ArrayList<>();
public Class<?> getOriginClasses() {
return this.originClasses;
}
protected boolean isCompatible(final Class<?> clazz) {
return this.originClasses == clazz;
}
public List<ClassModel> getDependencyModels() {
return this.dependencyModels;
}
public abstract Set<ClassModel> getDependencyGroupModels();
public static ClassModel getModel(final Type type, final ModelGroup previousModel) throws IOException {
if (type instanceof final ParameterizedType paramType) {
final Type[] typeArguments = paramType.getActualTypeArguments();
if (paramType.getRawType() == List.class) {
return new ClassListModel(typeArguments[0], previousModel);
}
if (paramType.getRawType() == Map.class) {
return new ClassMapModel(typeArguments[0], typeArguments[1], previousModel);
}
throw new IOException("Fail to manage parametrized type...");
}
return previousModel.add((Class<?>) type);
}
public static ClassModel getModelBase(
final Class<?> clazz,
final Type parameterizedType,
final ModelGroup previousModel) throws IOException {
/*
if (clazz == List.class) {
return new ClassListModel((ParameterizedType) parameterizedType, previousModel);
}
if (clazz == Map.class) {
return new ClassMapModel((ParameterizedType) parameterizedType, previousModel);
}
return previousModel.add(clazz);
*/
return getModel(parameterizedType, previousModel);
}
public static ClassModel getModel(final Class<?> type, final ModelGroup previousModel) throws IOException {
if (type == List.class) {
throw new IOException("Fail to manage parametrized type...");
}
if (type == Map.class) {
throw new IOException("Fail to manage parametrized type...");
}
return previousModel.add(type);
}
public abstract void analyze(final ModelGroup group) throws Exception;
public abstract Set<ClassModel> getAlls();
public List<String> getReadOnlyField() {
return List.of();
}
}

View File

@ -0,0 +1,202 @@
package org.kar.archidata.externalRestApi.model;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.kar.archidata.annotation.AnnotationTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ClassObjectModel extends ClassModel {
static final Logger LOGGER = LoggerFactory.getLogger(ClassObjectModel.class);
public ClassObjectModel(final Class<?> clazz) {
this.originClasses = clazz;
}
@Override
public String toString() {
final StringBuilder out = new StringBuilder();
out.append("ClassObjectModel [");
out.append(this.originClasses.getCanonicalName());
out.append("]");
return out.toString();
}
private static boolean isFieldFromSuperClass(final Class<?> model, final String filedName) {
final Class<?> superClass = model.getSuperclass();
if (superClass == null) {
return false;
}
for (final Field field : superClass.getFields()) {
String name;
try {
name = AnnotationTools.getFieldName(field);
if (filedName.equals(name)) {
return true;
}
} catch (final Exception e) {
// TODO Auto-generated catch block
LOGGER.trace("Catch error field name in parent create data table: {}", e.getMessage());
}
}
return false;
}
public record FieldProperty(
String name,
ClassModel model,
String comment,
int limitSize,
boolean readOnly,
boolean notNull,
boolean nullable) {
public FieldProperty(final String name, final ClassModel model, final String comment, final int limitSize,
final boolean readOnly, final boolean notNull, final boolean nullable) {
this.name = name;
this.model = model;
this.comment = comment;
this.limitSize = limitSize;
this.readOnly = readOnly;
this.notNull = notNull;
this.nullable = nullable;
}
public FieldProperty(final Field field, final ModelGroup previous) throws Exception {
this(field.getName(), //
ClassModel.getModel(field.getGenericType(), previous), //
AnnotationTools.getComment(field), //
AnnotationTools.getLimitSize(field), //
AnnotationTools.getSchemaReadOnly(field), //
AnnotationTools.getConstraintsNotNull(field), //
AnnotationTools.getColumnNotNull(field));
}
}
String name = "";
boolean isPrimitive = false;
String description = null;
String example = null;
ClassModel extendsClass = null;
List<FieldProperty> fields = new ArrayList<>();
public String getName() {
return this.name;
}
public boolean isPrimitive() {
return this.isPrimitive;
}
public String getDescription() {
return this.description;
}
public String getExample() {
return this.example;
}
public ClassModel getExtendsClass() {
return this.extendsClass;
}
public List<FieldProperty> getFields() {
return this.fields;
}
@Override
public void analyze(final ModelGroup previous) throws Exception {
if (this.analyzeDone) {
return;
}
this.analyzeDone = true;
final Class<?> clazz = this.originClasses;
this.isPrimitive = clazz.isPrimitive();
if (this.isPrimitive) {
return;
}
final List<Class<?>> basicClass = List.of(Void.class, void.class, Character.class, char.class, Short.class,
short.class, Integer.class, int.class, Long.class, long.class, Float.class, float.class, Double.class,
double.class, Date.class, Timestamp.class, LocalDate.class, LocalTime.class);
if (basicClass.contains(clazz)) {
return;
}
// Local generation of class:
LOGGER.trace("parse class: '{}'", clazz.getCanonicalName());
final List<String> alreadyAdded = new ArrayList<>();
for (final Field elem : clazz.getFields()) {
if (java.lang.reflect.Modifier.isStatic(elem.getModifiers())) {
continue;
}
final String dataName = elem.getName();
if (isFieldFromSuperClass(clazz, dataName)) {
LOGGER.trace(" SKIP: '{}'", elem.getName());
continue;
}
if (alreadyAdded.contains(dataName)) {
LOGGER.trace(" SKIP2: '{}'", elem.getName());
continue;
}
alreadyAdded.add(dataName);
LOGGER.trace(" + '{}'", elem.getName());
LOGGER.trace("Create type for: {} ==> {}", AnnotationTools.getFieldName(elem), elem.getType());
final FieldProperty porperty = new FieldProperty(elem, previous);
for (final ClassModel depModel : porperty.model().getAlls()) {
if (!this.dependencyModels.contains(depModel)) {
this.dependencyModels.add(depModel);
}
}
this.fields.add(new FieldProperty(elem, previous));
}
this.name = clazz.getName();
final String[] elems = this.name.split("\\$");
if (elems.length == 2) {
LOGGER.warn("Can have conflict in generation: {} (Remove class path) ==> {}", this.name, elems[1]);
this.name = elems[1];
}
this.description = AnnotationTools.getSchemaDescription(clazz);
this.example = AnnotationTools.getSchemaExample(clazz);
final Class<?> parentClass = clazz.getSuperclass();
// manage heritage
if (parentClass != null && parentClass != Object.class && parentClass != Record.class) {
this.extendsClass = previous.add(parentClass);
this.dependencyModels.add(this.extendsClass);
}
}
@Override
public Set<ClassModel> getDependencyGroupModels() {
return Set.of(this);
}
@Override
public Set<ClassModel> getAlls() {
return Set.of(this);
}
@Override
public List<String> getReadOnlyField() {
final List<String> out = new ArrayList<>();
for (final FieldProperty field : this.fields) {
if (field.readOnly()) {
out.add(field.name);
}
}
if (this.extendsClass != null) {
out.addAll(this.extendsClass.getReadOnlyField());
}
return out;
}
}

View File

@ -0,0 +1,53 @@
package org.kar.archidata.externalRestApi.model;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.core.Response;
public class ModelGroup {
static final Logger LOGGER = LoggerFactory.getLogger(ModelGroup.class);
public List<ClassModel> models = new ArrayList<>();
public ModelGroup() {}
public void addAll(final List<Class<?>> classes) {
for (final Class<?> clazz : classes) {
add(clazz);
}
}
public ClassModel add(Class<?> clazz) {
if (clazz == Response.class) {
clazz = Object.class;
}
if (clazz == Number.class) {
return null;
}
//LOGGER.trace("Search element {}", clazz.getCanonicalName());
for (final ClassModel value : this.models) {
if (value.isCompatible(clazz)) {
//LOGGER.trace(" ==> return {}", value);
return value;
}
}
if (clazz.isEnum()) {
final ClassModel elem = new ClassEnumModel(clazz);
this.models.add(elem);
//LOGGER.trace(" ==> return enum {}", elem);
return elem;
}
// create new model:
final ClassModel elem = new ClassObjectModel(clazz);
this.models.add(elem);
//LOGGER.trace(" ==> return object {}", elem);
return elem;
}
public List<ClassModel> getModels() {
return this.models;
}
}

View File

@ -0,0 +1,5 @@
package org.kar.archidata.externalRestApi.model;
public enum RestTypeRequest {
GET, POST, PUT, PATCH, DELETE
}

View File

@ -5,7 +5,6 @@ import org.kar.archidata.annotation.DataNotRead;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.DefaultValue;
public class GenericDataSoftDelete extends GenericData {
@ -13,7 +12,6 @@ public class GenericDataSoftDelete extends GenericData {
@Column(nullable = false)
@DefaultValue("'0'")
@DataDeleted
@NotNull
@Schema(description = "Deleted state", hidden = true, required = false, readOnly = true)
public Boolean deleted = null;
}

View File

@ -10,20 +10,17 @@ import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column;
import jakarta.validation.constraints.NotNull;
public class GenericTiming {
@DataNotRead
@CreationTimestamp
@Column(nullable = false)
@NotNull
@Schema(description = "Create time of the object", required = false, example = "2000-01-23T01:23:45.678+01:00", readOnly = true)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
public Date createdAt = null;
@DataNotRead
@UpdateTimestamp
@Column(nullable = false)
@NotNull
@Schema(description = "When update the object", required = false, example = "2000-01-23T00:23:45.678Z", readOnly = true)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
// public Instant updatedAt = null;

View File

@ -8,13 +8,13 @@ import jakarta.persistence.Column;
public class GetToken {
@Column(length = -1, nullable = false)
public String jwt;
public GetToken() {
}
public GetToken(final String jwt) {
this.jwt = jwt;
}
}

View File

@ -9,9 +9,9 @@ public class Token {
public String token;
public String createTime;
public String endValidityTime;
public Token() {}
public Token(final long id, final long userId, final String token, final String createTime,
final String endValidityTime) {
this.id = id;
@ -20,7 +20,7 @@ public class Token {
this.createTime = createTime;
this.endValidityTime = endValidityTime;
}
public Token(final ResultSet rs) {
int iii = 1;
try {
@ -33,7 +33,7 @@ public class Token {
ex.printStackTrace();
}
}
@Override
public String toString() {
return "Token{" + "id=" + this.id + ", userId=" + this.userId + ", token='" + this.token + '\''

View File

@ -5,6 +5,7 @@ import java.util.UUID;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column;
import jakarta.persistence.Id;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.DefaultValue;
public class UUIDGenericData extends GenericTiming {
@ -12,5 +13,6 @@ public class UUIDGenericData extends GenericTiming {
@DefaultValue("(UUID_TO_BIN(UUID(), TRUE))")
@Column(nullable = false, unique = true)
@Schema(description = "Unique UUID of the object", required = false, readOnly = true, example = "e6b33c1c-d24d-11ee-b616-02420a030102")
@NotNull
public UUID uuid = null;
}

View File

@ -5,7 +5,6 @@ import org.kar.archidata.annotation.DataNotRead;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.DefaultValue;
public class UUIDGenericDataSoftDelete extends UUIDGenericData {
@ -13,7 +12,6 @@ public class UUIDGenericDataSoftDelete extends UUIDGenericData {
@Column(nullable = false)
@DefaultValue("'0'")
@DataDeleted
@NotNull
@Schema(description = "Deleted state", hidden = true, required = false, readOnly = true)
public Boolean deleted = null;
}

View File

@ -50,23 +50,6 @@ export interface ModelResponseHttp {
data: any;
}
export function isArrayOf<TYPE>(
data: any,
typeChecker: (subData: any) => subData is TYPE,
length?: number
): data is TYPE[] {
if (!Array.isArray(data)) {
return false;
}
if (!data.every(typeChecker)) {
return false;
}
if (length !== undefined && data.length != length) {
return false;
}
return true;
}
function isNullOrUndefined(data: any): data is undefined | null {
return data === undefined || data === null;
}
@ -325,8 +308,6 @@ export function RESTRequest({ restModel, restConfig, data, params, queries, call
});
}
export function RESTRequestJson<TYPE>(request: RESTRequestType, checker: (data: any) => data is TYPE): Promise<TYPE> {
return new Promise((resolve, reject) => {
RESTRequest(request).then((value: ModelResponseHttp) => {
@ -349,25 +330,6 @@ export function RESTRequestJson<TYPE>(request: RESTRequestType, checker: (data:
});
});
}
export function RESTRequestJsonArray<TYPE>(request: RESTRequestType, checker: (data: any) => data is TYPE): Promise<TYPE[]> {
return new Promise((resolve, reject) => {
RESTRequest(request).then((value: ModelResponseHttp) => {
if (isArrayOf(value.data, checker)) {
resolve(value.data);
} else {
reject({
time: Date().toString(),
status: 950,
error: "REST Fail to verify the data",
statusMessage: "API cast ERROR",
message: "api.ts Check type as fail"
} as RestErrorResponse);
}
}).catch((reason: RestErrorResponse) => {
reject(reason);
});
});
}
export function RESTRequestVoid(request: RESTRequestType): Promise<void> {
return new Promise((resolve, reject) => {

View File

@ -118,4 +118,4 @@ public class TestRawQuery {
}
}
}
}

View File

@ -468,4 +468,4 @@ public class TestTypes {
DataAccess.delete(TypesTable.class, insertedData.id);
}
}
}

View File

@ -0,0 +1,47 @@
package test.kar.archidata.externalRestApi;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.kar.archidata.externalRestApi.AnalyzeApi;
import org.kar.archidata.externalRestApi.model.ApiModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.GET;
public class TestAnalyzeApiName {
final static private Logger LOGGER = LoggerFactory.getLogger(TestAnalyzeApiName.class);
public class ApiName {
@GET
public void firstName() {
}
@GET
public void SecondName() {
}
}
@Test
public void testNames() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ApiName.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals("ApiName", api.apiModels.get(0).name);
Assertions.assertEquals(2, api.apiModels.get(0).interfaces.size());
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("firstName");
Assertions.assertNotNull(model);
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("SecondName");
Assertions.assertNotNull(model);
}
}
}

View File

@ -0,0 +1,17 @@
package test.kar.archidata.externalRestApi;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestAnalyzeApiParameterParamQuery {
final static private Logger LOGGER = LoggerFactory.getLogger(TestAnalyzeApiParameterParamQuery.class);
@Test
public void testNotImplemented() throws Exception {
Assertions.assertEquals(1, 0);
}
}

View File

@ -0,0 +1,143 @@
package test.kar.archidata.externalRestApi;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.kar.archidata.externalRestApi.AnalyzeApi;
import org.kar.archidata.externalRestApi.model.ApiModel;
import org.kar.archidata.externalRestApi.model.ClassEnumModel;
import org.kar.archidata.externalRestApi.model.ClassListModel;
import org.kar.archidata.externalRestApi.model.ClassMapModel;
import org.kar.archidata.externalRestApi.model.ClassObjectModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.GET;
public class TestAnalyzeApiParameterType {
final static private Logger LOGGER = LoggerFactory.getLogger(TestAnalyzeApiParameterType.class);
public enum TestEnum {
PLOP, PLIP
}
public class TestObject {
public int value;
}
public class BasicParameter {
@GET
public void setInteger1(final int parameter) {}
@GET
public void setInteger2(final Integer parameter) {}
@GET
public void setString(final String parameter) {}
@GET
public void setObject(final TestObject parameter) {}
@GET
public void setEnum(final TestEnum parameter) {}
}
@Test
public void testBasicParameter() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(BasicParameter.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(5, api.apiModels.get(0).interfaces.size());
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("setInteger1");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.unnamedElement.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.unnamedElement.get(0));
Assertions.assertEquals(int.class, classModel.getOriginClasses());
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("setInteger2");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.unnamedElement.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.unnamedElement.get(0));
Assertions.assertEquals(Integer.class, classModel.getOriginClasses());
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("setString");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.unnamedElement.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.unnamedElement.get(0));
Assertions.assertEquals(String.class, classModel.getOriginClasses());
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("setObject");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.unnamedElement.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.unnamedElement.get(0));
Assertions.assertEquals(TestObject.class, classModel.getOriginClasses());
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("setEnum");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.unnamedElement.size());
final ClassEnumModel classModel = Assertions.assertInstanceOf(ClassEnumModel.class,
model.unnamedElement.get(0));
Assertions.assertEquals(TestEnum.class, classModel.getOriginClasses());
}
}
public class ListParameter {
@GET
public void setList(final List<Integer> parameter) {}
}
@Test
public void testListParameter() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ListParameter.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(1, api.apiModels.get(0).interfaces.size());
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("setList");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.unnamedElement.size());
final ClassListModel classModel = Assertions.assertInstanceOf(ClassListModel.class,
model.unnamedElement.get(0));
final ClassObjectModel classModelValue = Assertions.assertInstanceOf(ClassObjectModel.class,
classModel.valueModel);
Assertions.assertEquals(Integer.class, classModelValue.getOriginClasses());
}
public class MapParameter {
@GET
public void setMap(final Map<String, Integer> parameter) {}
}
@Test
public void testMapParameter() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(MapParameter.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(1, api.apiModels.get(0).interfaces.size());
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("setMap");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.unnamedElement.size());
final ClassMapModel classModel = Assertions.assertInstanceOf(ClassMapModel.class, model.unnamedElement.get(0));
final ClassObjectModel classModelKey = Assertions.assertInstanceOf(ClassObjectModel.class, classModel.keyModel);
Assertions.assertEquals(String.class, classModelKey.getOriginClasses());
final ClassObjectModel classModelValue = Assertions.assertInstanceOf(ClassObjectModel.class,
classModel.valueModel);
Assertions.assertEquals(Integer.class, classModelValue.getOriginClasses());
}
}

View File

@ -0,0 +1,17 @@
package test.kar.archidata.externalRestApi;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestAnalyzeApiParameterTypeAsync {
final static private Logger LOGGER = LoggerFactory.getLogger(TestAnalyzeApiParameterTypeAsync.class);
@Test
public void testNotImplemented() throws Exception {
Assertions.assertEquals(1, 0);
}
}

View File

@ -0,0 +1,107 @@
package test.kar.archidata.externalRestApi;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.kar.archidata.externalRestApi.AnalyzeApi;
import org.kar.archidata.externalRestApi.model.ApiModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
public class TestAnalyzeApiPath {
final static private Logger LOGGER = LoggerFactory.getLogger(TestAnalyzeApiPath.class);
public class NoPath {
@GET
public void noPath() {
}
@GET
@Path("plop")
public void withPath() {
}
@GET
@Path("/plop")
public void withPath2() {
}
}
@Test
public void testNoPath() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(NoPath.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals("", api.apiModels.get(0).restEndPoint);
Assertions.assertEquals(3, api.apiModels.get(0).interfaces.size());
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("noPath");
Assertions.assertNotNull(model);
Assertions.assertEquals("/", model.restEndPoint);
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("withPath");
Assertions.assertNotNull(model);
Assertions.assertEquals("/plop", model.restEndPoint);
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("withPath2");
Assertions.assertNotNull(model);
Assertions.assertEquals("//plop", model.restEndPoint);
}
}
@Path("/kaboom")
public class WithPath {
@GET
public void noPath() {
}
@GET
@Path("plop")
public void withPath() {
}
@GET
@Path("/plop")
public void withPath2() {
}
}
@Test
public void testWithPath() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(WithPath.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals("/kaboom", api.apiModels.get(0).restEndPoint);
Assertions.assertEquals(3, api.apiModels.get(0).interfaces.size());
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("noPath");
Assertions.assertNotNull(model);
Assertions.assertEquals("/kaboom/", model.restEndPoint);
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("withPath");
Assertions.assertNotNull(model);
Assertions.assertEquals("/kaboom/plop", model.restEndPoint);
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("withPath2");
Assertions.assertNotNull(model);
Assertions.assertEquals("/kaboom//plop", model.restEndPoint);
}
}
}

View File

@ -0,0 +1,605 @@
package test.kar.archidata.externalRestApi;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.kar.archidata.externalRestApi.AnalyzeApi;
import org.kar.archidata.externalRestApi.model.ApiModel;
import org.kar.archidata.externalRestApi.model.ClassEnumModel;
import org.kar.archidata.externalRestApi.model.ClassListModel;
import org.kar.archidata.externalRestApi.model.ClassMapModel;
import org.kar.archidata.externalRestApi.model.ClassObjectModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.core.Response;
public class TestAnalyzeApiReturn {
final static private Logger LOGGER = LoggerFactory.getLogger(TestAnalyzeApiReturn.class);
public enum TestEnum {
PLOP, PLIP
}
public class TestObject {
public int value;
}
public class ReturnValueVoid {
@GET
public void getVoid1() {}
@GET
public Void getVoid2() {
return null;
}
}
@Test
public void testReturnVoid() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueVoid.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(2, api.apiModels.get(0).interfaces.size());
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getVoid1");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(void.class, classModel.getOriginClasses());
}
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getVoid2");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(Void.class, classModel.getOriginClasses());
}
}
public class ReturnValueInteger {
@GET
public int getInteger1() {
return 0;
}
@GET
public Integer getInteger2() {
return 0;
}
}
@Test
public void testReturnInteger() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueInteger.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(2, api.apiModels.get(0).interfaces.size());
// Check int
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getInteger1");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(int.class, classModel.getOriginClasses());
}
// Check Integer
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getInteger2");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(Integer.class, classModel.getOriginClasses());
}
}
public class ReturnValueShort {
@GET
public short getShort1() {
return 0;
}
@GET
public Short getShort2() {
return 0;
}
}
@Test
public void testReturnShort() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueShort.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(2, api.apiModels.get(0).interfaces.size());
// Check short
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getShort1");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(short.class, classModel.getOriginClasses());
}
// Check Short
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getShort2");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(Short.class, classModel.getOriginClasses());
}
}
public class ReturnValueLong {
@GET
public long getLong1() {
return 0;
}
@GET
public Long getLong2() {
return 0L;
}
}
@Test
public void testReturnLong() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueLong.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(2, api.apiModels.get(0).interfaces.size());
// Check long
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getLong1");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(long.class, classModel.getOriginClasses());
}
// Check Long
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getLong2");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
Assertions.assertInstanceOf(ClassObjectModel.class, model.returnTypes.get(0));
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(Long.class, classModel.getOriginClasses());
}
}
public class ReturnValueFloat {
@GET
public float getFloat1() {
return 0;
}
@GET
public Float getFloat2() {
return 0.0f;
}
}
@Test
public void testReturnFloat() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueFloat.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(2, api.apiModels.get(0).interfaces.size());
// Check float
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getFloat1");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(float.class, classModel.getOriginClasses());
}
// Check Float
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getFloat2");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(Float.class, classModel.getOriginClasses());
}
}
public class ReturnValueDouble {
@GET
public double getDouble1() {
return 0;
}
@GET
public Double getDouble2() {
return 0.0;
}
}
@Test
public void testReturnDouble() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueDouble.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(2, api.apiModels.get(0).interfaces.size());
// Check double
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getDouble1");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(double.class, classModel.getOriginClasses());
}
// Check Double
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getDouble2");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(Double.class, classModel.getOriginClasses());
}
}
public class ReturnValueString {
@GET
public String getString() {
return "0";
}
}
@Test
public void testReturnString() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueString.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(1, api.apiModels.get(0).interfaces.size());
// Check String
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getString");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(String.class, classModel.getOriginClasses());
}
}
public class ReturnValueAny {
@GET
public Response getResponse() {
return null;
}
@GET
public Object getObject() {
return null;
}
}
@Test
public void testReturnAny() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueAny.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(2, api.apiModels.get(0).interfaces.size());
// Check Response ==> represent a Any value then it wrapped as Object
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getResponse");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(Object.class, classModel.getOriginClasses());
}
// Check Object
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getObject");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(Object.class, classModel.getOriginClasses());
}
}
public class ReturnValueEnum {
@GET
public TestEnum getEnum() {
return TestEnum.PLIP;
}
}
@Test
public void testReturnEnum() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueEnum.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(1, api.apiModels.get(0).interfaces.size());
// Check Enum
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getEnum");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
final ClassEnumModel classModel = Assertions.assertInstanceOf(ClassEnumModel.class,
model.returnTypes.get(0));
Assertions.assertEquals(TestEnum.class, classModel.getOriginClasses());
}
}
public class ReturnValueList {
@GET
public List<Integer> getListInteger() {
return null;
}
@GET
public List<TestEnum> getListEnum() {
return null;
}
@GET
public List<TestObject> getListObject() {
return null;
}
@GET
public List<List<Integer>> getListListInteger() {
return null;
}
@GET
public List<Map<String, Integer>> getListMapInteger() {
return null;
}
}
@Test
public void testReturnList() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueList.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(5, api.apiModels.get(0).interfaces.size());
// Check List<Integer>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getListInteger");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassListModel classListModel = Assertions.assertInstanceOf(ClassListModel.class,
model.returnTypes.get(0));
// Level 1
final ClassObjectModel classModelOfValue = Assertions.assertInstanceOf(ClassObjectModel.class,
classListModel.valueModel);
Assertions.assertEquals(Integer.class, classModelOfValue.getOriginClasses());
}
// Check List<TestEnum>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getListEnum");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassListModel classListModel = Assertions.assertInstanceOf(ClassListModel.class,
model.returnTypes.get(0));
// Level 1
final ClassEnumModel classModelOfValue = Assertions.assertInstanceOf(ClassEnumModel.class,
classListModel.valueModel);
Assertions.assertEquals(TestEnum.class, classModelOfValue.getOriginClasses());
}
// Check List<TestObject>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getListObject");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassListModel classListModel = Assertions.assertInstanceOf(ClassListModel.class,
model.returnTypes.get(0));
// Level 1
final ClassObjectModel classModelOfValue = Assertions.assertInstanceOf(ClassObjectModel.class,
classListModel.valueModel);
Assertions.assertEquals(Integer.class, classModelOfValue.getOriginClasses());
}
// Check List<List<Integer>>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getListListInteger");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassListModel classListModel = Assertions.assertInstanceOf(ClassListModel.class,
model.returnTypes.get(0));
// Level 1
final ClassListModel classList2Model = Assertions.assertInstanceOf(ClassListModel.class,
classListModel.valueModel);
// Level 2
final ClassObjectModel classModelOfValue = Assertions.assertInstanceOf(ClassObjectModel.class,
classList2Model.valueModel);
Assertions.assertEquals(Integer.class, classModelOfValue.getOriginClasses());
}
// Check List<Map<String, Integer>>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getListMapInteger");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassListModel classListModel = Assertions.assertInstanceOf(ClassListModel.class,
model.returnTypes.get(0));
// Level 1
final ClassMapModel classMapModel = Assertions.assertInstanceOf(ClassMapModel.class,
classListModel.valueModel);
// Level 2
final ClassObjectModel classModelOfKey = Assertions.assertInstanceOf(ClassObjectModel.class,
classMapModel.keyModel);
Assertions.assertEquals(String.class, classModelOfKey.getOriginClasses());
final ClassObjectModel classModelOfValue = Assertions.assertInstanceOf(ClassObjectModel.class,
classMapModel.valueModel);
Assertions.assertEquals(Integer.class, classModelOfValue.getOriginClasses());
}
}
// does not test other than key string, but in theory it works.
public class ReturnValueMap {
@GET
public Map<String, Integer> getMapInteger() {
return null;
}
@GET
public Map<String, TestEnum> getMapEnum() {
return null;
}
@GET
public Map<String, TestObject> getMapObject() {
return null;
}
@GET
public Map<String, Map<String, Integer>> getMapMap() {
return null;
}
@GET
public Map<String, List<Integer>> getMapList() {
return null;
}
}
@Test
public void testReturnMap() throws Exception {
final AnalyzeApi api = new AnalyzeApi();
api.addAllApi(List.of(ReturnValueMap.class));
Assertions.assertEquals(1, api.apiModels.size());
Assertions.assertEquals(5, api.apiModels.get(0).interfaces.size());
// Check Map<String, Integer>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getMapInteger");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassMapModel classMapModel = Assertions.assertInstanceOf(ClassMapModel.class,
model.returnTypes.get(0));
final ClassObjectModel classModelOfKey = Assertions.assertInstanceOf(ClassObjectModel.class,
classMapModel.keyModel);
Assertions.assertEquals(String.class, classModelOfKey.getOriginClasses());
// Level 1
final ClassObjectModel classModelOfValue = Assertions.assertInstanceOf(ClassObjectModel.class,
classMapModel.valueModel);
Assertions.assertEquals(Integer.class, classModelOfValue.getOriginClasses());
}
// Check Map<String, TestEnum>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getMapEnum");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassMapModel classMapModel = Assertions.assertInstanceOf(ClassMapModel.class,
model.returnTypes.get(0));
final ClassObjectModel classModelOfKey = Assertions.assertInstanceOf(ClassObjectModel.class,
classMapModel.keyModel);
Assertions.assertEquals(String.class, classModelOfKey.getOriginClasses());
// Level 1
final ClassEnumModel classModelOfValue = Assertions.assertInstanceOf(ClassEnumModel.class,
classMapModel.valueModel);
Assertions.assertEquals(TestEnum.class, classModelOfValue.getOriginClasses());
}
// Check Map<String, TestObject>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getMapObject");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassMapModel classMapModel = Assertions.assertInstanceOf(ClassMapModel.class,
model.returnTypes.get(0));
final ClassObjectModel classModelOfKey = Assertions.assertInstanceOf(ClassObjectModel.class,
classMapModel.keyModel);
Assertions.assertEquals(String.class, classModelOfKey.getOriginClasses());
// Level 1
final ClassObjectModel classModelOfValue = Assertions.assertInstanceOf(ClassObjectModel.class,
classMapModel.valueModel);
Assertions.assertEquals(TestObject.class, classModelOfValue.getOriginClasses());
}
// Check Map<String, Map<String, Integer>>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getMapMap");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassMapModel classMapModel = Assertions.assertInstanceOf(ClassMapModel.class,
model.returnTypes.get(0));
final ClassObjectModel classModelOfKey = Assertions.assertInstanceOf(ClassObjectModel.class,
classMapModel.keyModel);
Assertions.assertEquals(String.class, classModelOfKey.getOriginClasses());
// Level 1
final ClassMapModel classModelOfValue = Assertions.assertInstanceOf(ClassMapModel.class,
classMapModel.valueModel);
final ClassObjectModel classModelOfValueOfKey = Assertions.assertInstanceOf(ClassObjectModel.class,
classModelOfValue.keyModel);
Assertions.assertEquals(String.class, classModelOfValueOfKey.getOriginClasses());
final ClassObjectModel classSubModel = Assertions.assertInstanceOf(ClassObjectModel.class,
classModelOfValue.valueModel);
Assertions.assertEquals(Integer.class, classSubModel.getOriginClasses());
}
// Check Map<String, List<Integer>>
{
final ApiModel model = api.apiModels.get(0).getInterfaceNamed("getMapList");
Assertions.assertNotNull(model);
Assertions.assertEquals(1, model.returnTypes.size());
// Level 0
final ClassMapModel classMapModel = Assertions.assertInstanceOf(ClassMapModel.class,
model.returnTypes.get(0));
final ClassObjectModel classModelOfKey = Assertions.assertInstanceOf(ClassObjectModel.class,
classMapModel.keyModel);
Assertions.assertEquals(String.class, classModelOfKey.getOriginClasses());
// Level 1
final ClassListModel classModelOfValue = Assertions.assertInstanceOf(ClassListModel.class,
classMapModel.valueModel);
final ClassObjectModel classSubModel = Assertions.assertInstanceOf(ClassObjectModel.class,
classModelOfValue.valueModel);
Assertions.assertEquals(Integer.class, classSubModel.getOriginClasses());
}
}
}

View File

@ -0,0 +1,17 @@
package test.kar.archidata.externalRestApi;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestAnalyzeApiReturnAsync {
final static private Logger LOGGER = LoggerFactory.getLogger(TestAnalyzeApiReturnAsync.class);
@Test
public void testNotImplemented() throws Exception {
Assertions.assertEquals(1, 0);
}
}

View File

@ -0,0 +1,43 @@
package test.kar.archidata.externalRestApi;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.kar.archidata.externalRestApi.AnalyzeModel;
import org.kar.archidata.externalRestApi.model.ClassModel;
import org.kar.archidata.externalRestApi.model.ClassObjectModel;
import org.kar.archidata.externalRestApi.model.ClassObjectModel.FieldProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestAnalyzeModel {
final static private Logger LOGGER = LoggerFactory.getLogger(TestAnalyzeModel.class);
public class TestObject {
public Integer value;
}
@Test
public void testNames() throws Exception {
final ClassObjectModel model = new ClassObjectModel(TestObject.class);
final List<ClassModel> models = new ArrayList<>();
models.add(model);
AnalyzeModel.fillModel(models);
Assertions.assertEquals("TestObject", model.getName());
Assertions.assertEquals(false, model.isPrimitive());
Assertions.assertNull(model.getDescription());
Assertions.assertNull(model.getExample());
Assertions.assertNull(model.getExtendsClass());
Assertions.assertEquals(1, model.getFields().size());
final FieldProperty fieldProperty = model.getFields().get(0);
Assertions.assertEquals("value", fieldProperty.name());
final ClassObjectModel classModel = Assertions.assertInstanceOf(ClassObjectModel.class, fieldProperty.model());
Assertions.assertEquals(Integer.class, classModel.getOriginClasses());
}
}