Compare commits
	
		
			107 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| ab7259f726 | |||
| cdb4581799 | |||
| 7e81bfef28 | |||
| 84525fd7aa | |||
| d4eb9c2a5f | |||
| 15688f93e5 | |||
| 906216f237 | |||
| b479414bc2 | |||
| 2bc68321e3 | |||
| d77a5518ff | |||
| 5f9d13d315 | |||
|   | 0b57d8571c | ||
| 483c41914a | |||
| a1f56050bf | |||
| a41e837f21 | |||
| 5496855698 | |||
| c9cb0d043a | |||
| 09cfcfc578 | |||
| e4c56a4da5 | |||
| 22614aee98 | |||
| 5bbcf63c42 | |||
| 1c02d333a3 | |||
| 1c41ea4273 | |||
| 274767d89b | |||
| 4236dc38bd | |||
| 7d4b246d4a | |||
| f6f256c006 | |||
| d46b84c741 | |||
| 3e6b9bf77c | |||
| 007003394a | |||
| 54d4c420f9 | |||
| 0a307f3f6e | |||
| d968a2c48f | |||
| c43e283b57 | |||
| 6af6f91166 | |||
| c94f488747 | |||
| c44b726cc1 | |||
| c412daa1ca | |||
| aa700f9dc5 | |||
| a1791cf61d | |||
| 9c9da21bdb | |||
| dc6eeac008 | |||
| f3a9ebf5e1 | |||
| 1fe3cc3523 | |||
| 91849094cd | |||
| 7b72b08fc0 | |||
| ebf1b4b76a | |||
| f6aff28488 | |||
| 6ebb9eb395 | |||
| 17664f1c2f | |||
| 1373760498 | |||
| 8ffa392b2a | |||
| 6104b68a02 | |||
| 3c85af5af9 | |||
| 38d1fa9241 | |||
| 0e498c6a26 | |||
| 187ffba188 | |||
| 2a2b6b8f3b | |||
| 73770b03c3 | |||
| 5d8d4d9d2a | |||
| 745b0cb39b | |||
| 9bad883866 | |||
| f1c3b88a00 | |||
| 8c30336bdb | |||
| 6f36f98cd6 | |||
| c843d7a64b | |||
| 7059e687db | |||
| bfb6498782 | |||
| 94abf842e7 | |||
| 300ce8eab6 | |||
| c33a73a567 | |||
| 0597ba0df3 | |||
| 4dabfcf7d7 | |||
| 4f7d2d711f | |||
| 9ac3a95060 | |||
| dc022abd2d | |||
| 7a36580cce | |||
| 6031e6e557 | |||
| 6d6fbf93ca | |||
| e1f1335e89 | |||
| e914daf71b | |||
| d859c7c278 | |||
| 420ea94b42 | |||
| 604c76103f | |||
| 1fbc9e5874 | |||
| 17fdd7b83b | |||
| 4cbad1fc6a | |||
| 6e784f5f50 | |||
| 81672115c8 | |||
| 25e6972efd | |||
| 850964932f | |||
| b3364753dd | |||
| a0d96f1322 | |||
| ad3c1f4b7d | |||
| a77db1035d | |||
| f1a31fed56 | |||
| 7c087fcd8f | |||
| 183906dc97 | |||
| 94e5603380 | |||
| f06b5a1edc | |||
| f3f6cd91d0 | |||
| 6c048ac22b | |||
| 755b258ddb | |||
| 4be9f663ac | |||
| 280d86e333 | |||
| 70cbb1aae9 | |||
| 9d5c3c01db | 
| @@ -1,4 +1,14 @@ | ||||
| #!/bin/bash | ||||
| version_file="version.txt" | ||||
|  | ||||
| mvn versions:set -DnewVersion=$(cat version.txt) | ||||
|  | ||||
| # update the Maven version number | ||||
| mvn versions:set -DnewVersion=$(sed 's/dev/SNAPSHOT/g' $version_file) | ||||
| if grep -q "DEV" "$version_file"; then | ||||
|     # update all versions release of dependency | ||||
|     mvn versions:use-latest-releases | ||||
|     # update our manage dependency as snapshoot | ||||
|     mvn versions:use-latest-versions -Dincludes=kangaroo-and-rabbit | ||||
| else | ||||
|     # update our manage dependency as release (must be done before) | ||||
|     mvn versions:use-latest-releases -Dincludes=kangaroo-and-rabbit | ||||
| fi | ||||
|   | ||||
							
								
								
									
										6
									
								
								.project
									
									
									
									
									
								
							
							
						
						
									
										6
									
								
								.project
									
									
									
									
									
								
							| @@ -10,6 +10,11 @@ | ||||
| 			<arguments> | ||||
| 			</arguments> | ||||
| 		</buildCommand> | ||||
| 		<buildCommand> | ||||
| 			<name>edu.umd.cs.findbugs.plugin.eclipse.findbugsBuilder</name> | ||||
| 			<arguments> | ||||
| 			</arguments> | ||||
| 		</buildCommand> | ||||
| 		<buildCommand> | ||||
| 			<name>org.eclipse.m2e.core.maven2Builder</name> | ||||
| 			<arguments> | ||||
| @@ -19,6 +24,7 @@ | ||||
| 	<natures> | ||||
| 		<nature>org.eclipse.jdt.core.javanature</nature> | ||||
| 		<nature>org.eclipse.m2e.core.maven2Nature</nature> | ||||
| 		<nature>edu.umd.cs.findbugs.plugin.eclipse.findbugsNature</nature> | ||||
| 	</natures> | ||||
| 	<filteredResources> | ||||
| 		<filter> | ||||
|   | ||||
| @@ -93,7 +93,12 @@ Enable the pre-commit checker | ||||
|  | ||||
| > **_Note_**: You can change the code in `.git/hooks/pre-commit` by replacing `formatter:verify` with `formatter:format` to auto format the code @ every commit | ||||
|  | ||||
| Run Spot-bug: | ||||
| ------------ | ||||
|  | ||||
| ```bash | ||||
| mvn spotbugs:check | ||||
| ``` | ||||
|  | ||||
| Add Gitea in the dependency for the registry: | ||||
| ============================================= | ||||
|   | ||||
							
								
								
									
										202
									
								
								doc/SQL_wrapper.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										202
									
								
								doc/SQL_wrapper.md
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,202 @@ | ||||
| Wrapping over the DB | ||||
| ==================== | ||||
|  | ||||
| In the current version we consider 2 DB access: MySQL and SQLite, We commonly use the SQLite in test mode to permit to test is a real case. | ||||
|  | ||||
| Generic Access: | ||||
| --------------- | ||||
|  | ||||
| Some generic function are available to permit you to simply request the DB | ||||
|  | ||||
| ### Create a new Value: | ||||
|  | ||||
| ```java | ||||
| MyDataModel dataToInsert = ...; | ||||
| MyDataModel dataCreated = DataAccess.insert(dataToInsert); | ||||
| ``` | ||||
|  | ||||
|  | ||||
| ### Get a full table: | ||||
|  | ||||
| ```java | ||||
| List<MyDataModel> data = DataAccess.gets(MyDataModel.class); | ||||
| ``` | ||||
|  | ||||
| ### Get a single element in the DB: | ||||
|  | ||||
| ```java | ||||
| UUID id = ...; | ||||
| MyDataModel data = DataAccess.get(MyDataModel.class, id); | ||||
| ``` | ||||
|  | ||||
| > **_Note:_** The Id type fully managed are UUID and Long | ||||
|  | ||||
| ### Removing the Data: | ||||
|  | ||||
| ```java | ||||
| UUID id = ...; | ||||
| DataAccess.delete(MyDataModel.class, id); | ||||
| ``` | ||||
|  | ||||
| > **_Note:_** Removing the data automatically detect if it is a software remove or definitive remove | ||||
|  | ||||
| ### Updating the Data: | ||||
|  | ||||
| The update of the data can be managed by 2 way: | ||||
|   - Direct update of the Object with direct injection (Good for `PUT`) | ||||
|   - Update with input json (Good for `PATCH`) | ||||
|  | ||||
| The second way is preferable for some reasons | ||||
|   - When jakarta transform the data in you object, we can not detect the element set at null or not set (We consider user of `Optional` il all data class will create a too bug amount of unneeded code in all dev parts) | ||||
|   - Throw in the jakarta parsing are not well catch when we will generate generic error | ||||
|   - The Check will permit to explain what is wrong better than a generic Json parser. | ||||
|  | ||||
| Updating with JSON: | ||||
|  | ||||
| ```java | ||||
| UUID id = ...; | ||||
| String jsonRequest = "{...}"; | ||||
| DataAccess.updateWithJson(MyDataModel.class, id, jsonRequest); | ||||
| ``` | ||||
|  | ||||
| Updating with direct data: | ||||
|  | ||||
| ```java | ||||
| UUID id = ...; | ||||
| MyDataModel dataToUpdate = ...; | ||||
| // This update all fields: | ||||
| DataAccess.update(dataToUpdate, id); | ||||
| // Select the field to update: | ||||
| DataAccess.update(dataToUpdate, id, List.of("field1","field2")); | ||||
| ``` | ||||
|  | ||||
| Generic option of the request: | ||||
| ------------------------------ | ||||
|  | ||||
| Many API have a generic multiple option available like: | ||||
|  | ||||
| ```java | ||||
| public static <T> List<T> getsWhere(final Class<T> clazz, final QueryOption... option) throws Exception | ||||
| ``` | ||||
|  | ||||
| You just need to add your options in the list of `option`. | ||||
|  | ||||
| Filter the list of field read: | ||||
| ```java | ||||
| public FilterValue(final String... filterValue) | ||||
| public FilterValue(final List<String> filterValues) | ||||
| // example: | ||||
| new newFilterValue("field1", "field2"); | ||||
| ``` | ||||
|  | ||||
| Add a condition [more detail](#condition-models) | ||||
| ```java | ||||
| public Condition(final QueryItem items) | ||||
| ``` | ||||
|  | ||||
| Order the request: | ||||
| ```java | ||||
| public OrderBy(final OrderItem... childs); | ||||
| // example: | ||||
| new OrderBy(new OrderItem("name", Order.DESC)); | ||||
| ``` | ||||
|  | ||||
| Limit the : | ||||
| ```java | ||||
| public Limit(final long limit) | ||||
| // example: | ||||
| new Limit(50); | ||||
| ``` | ||||
|  | ||||
| Read all column like update date and create date or delete field | ||||
| ```java | ||||
| public ReadAllColumn() | ||||
| ``` | ||||
|  | ||||
| Condition models: | ||||
| ----------------- | ||||
|  | ||||
| Creating a condition independent of the DB model use need to have a little abstraction of the query model: | ||||
|  | ||||
| For this we propose some condition that update with the internal "auto" condition that is added (like the soft delete...) | ||||
|  | ||||
| ### default generic comparator | ||||
|  | ||||
| This is the base of the comparison tool. It compare a column with a value | ||||
|  | ||||
| ```java | ||||
| public QueryCondition(final String key, final String comparator, final Object value); | ||||
| ``` | ||||
|  | ||||
| Simple DB comparison element. Note the injected object is injected in the statement and not in the query directly. | ||||
|  | ||||
| Example: | ||||
| ```java | ||||
| String nameToCheck = "plop"; | ||||
| new QueryCondition("fieldName", "=", nameToCheck); | ||||
| // OR: | ||||
| UUID uuid = ...; | ||||
| new QueryCondition("uuid", "=", uuid); | ||||
| ``` | ||||
|  | ||||
| ### List comparator | ||||
|  | ||||
| It permit to check a column is (NOT) in a list of value | ||||
|  | ||||
| ```java | ||||
| public QueryInList(final String key, final List<T> value) | ||||
| public QueryInList(final String key, final T... value) | ||||
| ``` | ||||
| and his opposite: | ||||
| ```java | ||||
| public QueryNotInList(final String key, final List<T> value) | ||||
| public QueryNotInList(final String key, final T... value) | ||||
| ``` | ||||
|  | ||||
| example | ||||
| ```java | ||||
| new QueryInList("uuid", List.of(uuid1, uuid2)); | ||||
| ``` | ||||
|  | ||||
| ### NULL and NOT NULL checker | ||||
|  | ||||
| This permit to check an element is `NULL` or `not NULL` | ||||
|  | ||||
| ```java | ||||
| public QueryNull(final String key); | ||||
| public QueryNotNull(final String key); | ||||
| ``` | ||||
|  | ||||
| ### The group condition: | ||||
|  | ||||
| The generic `OR` group: | ||||
| ```java | ||||
| public QueryOr(final List<QueryItem> child); | ||||
| public QueryOr(final QueryItem... child); | ||||
| ``` | ||||
|  | ||||
| Or the generic `AND group: | ||||
| ```java | ||||
| public QueryAnd(final List<QueryItem> child); | ||||
| public QueryAnd(final QueryItem... child); | ||||
| ``` | ||||
|  | ||||
| ### Full example: | ||||
|  | ||||
| ```java | ||||
| List<MyDataModel> result = DataAccess.getsWhere(MyDataModel.class,  | ||||
|         new Limit(50), | ||||
|         new OrderBy(new OrderItem("name", Order.DESC)), | ||||
|         new Condition( | ||||
|             new QueryAnd( | ||||
|                 QueryNull("Field3") | ||||
|                 new QueryOr( | ||||
|                     new QueryInList("Field4", 5, 55, 65, 62, 27, 84), | ||||
|                     new QueryCondition("cityID", ">", 78000); | ||||
|                 ) | ||||
|             ) | ||||
|         ) | ||||
|     ); | ||||
| ``` | ||||
|  | ||||
|  | ||||
							
								
								
									
										3
									
								
								doc/TUTORIAL_01_first_install.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										3
									
								
								doc/TUTORIAL_01_first_install.md
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,3 @@ | ||||
| Basic tutorial | ||||
| ============== | ||||
|  | ||||
							
								
								
									
										16
									
								
								doc/data_model.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								doc/data_model.md
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,16 @@ | ||||
| Data Model | ||||
| ========== | ||||
|  | ||||
| The data model have 2 parts: the model of the DB and the model of the API. It is important to consider the 2 part due to the fact annotation will be manage by by a part, ot the other. Here we will study the Checking of the Data. | ||||
|  | ||||
| DB data model | ||||
| ============= | ||||
|  | ||||
|  | ||||
| API data model | ||||
| ============== | ||||
|  | ||||
|  | ||||
| Checking of the Data | ||||
| ==================== | ||||
|  | ||||
							
								
								
									
										16
									
								
								doc/index.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								doc/index.md
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,16 @@ | ||||
| Archi-data documentation | ||||
| ======================== | ||||
|  | ||||
| Archidata is base on generic Jakarta, grizzly and SQL or SQLite service. | ||||
|  | ||||
| It permit to simplify the interface of the server to concentrate on the API design. | ||||
|  | ||||
|  | ||||
| Archi-data is a group of tools that manage some parts: | ||||
|   - [Wrapping over the DB](SQL_wrapper.md) | ||||
|   - [Data Model](data_model.md) | ||||
|   - [TypeScript Api generation](typescript_api_generation.md) | ||||
|   - [Migration tool](migration.md) | ||||
|  | ||||
| Some initialization tutorials: | ||||
|   - [Basic tutorial](TUTORIAL_01_first_install.md) | ||||
							
								
								
									
										7
									
								
								doc/migration.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										7
									
								
								doc/migration.md
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,7 @@ | ||||
| Migration tool | ||||
| ============== | ||||
|  | ||||
| Migration is a big part of the Server environment, it permit to migrate an old DB to a new one, and some tool permit the opposite. | ||||
|  | ||||
| Archi-data does not permit to do a reverse migration. I implement some code for it, but is was never tested. On my professional activity, we migrate only forward (Request if if really needed). | ||||
|  | ||||
							
								
								
									
										5
									
								
								doc/typescript_api_generation.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								doc/typescript_api_generation.md
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,5 @@ | ||||
| TypeScript Api generation | ||||
| ========================= | ||||
|  | ||||
|  | ||||
|  | ||||
							
								
								
									
										61
									
								
								pom.xml
									
									
									
									
									
								
							
							
						
						
									
										61
									
								
								pom.xml
									
									
									
									
									
								
							| @@ -3,8 +3,9 @@ | ||||
| 	<modelVersion>4.0.0</modelVersion> | ||||
| 	<groupId>kangaroo-and-rabbit</groupId> | ||||
| 	<artifactId>archidata</artifactId> | ||||
| 	<version>0.8.4</version> | ||||
| 	<version>0.13.0</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> | ||||
| @@ -45,12 +46,12 @@ | ||||
| 		<dependency> | ||||
| 			<groupId>org.slf4j</groupId> | ||||
| 			<artifactId>slf4j-api</artifactId> | ||||
| 			<version>2.0.9</version> | ||||
| 			<version>2.1.0-alpha1</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>org.slf4j</groupId> | ||||
| 			<artifactId>slf4j-simple</artifactId> | ||||
| 			<version>2.0.9</version> | ||||
| 			<version>2.1.0-alpha1</version> | ||||
| 			<scope>test</scope> | ||||
| 		</dependency> | ||||
| 		<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-multipart --> | ||||
| @@ -78,12 +79,12 @@ | ||||
| 		<dependency> | ||||
| 			<groupId>org.glassfish.jaxb</groupId> | ||||
| 			<artifactId>jaxb-runtime</artifactId> | ||||
| 			<version>4.0.4</version> | ||||
| 			<version>4.0.5</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>jakarta.ws.rs</groupId> | ||||
| 			<artifactId>jakarta.ws.rs-api</artifactId> | ||||
| 			<version>3.1.0</version> | ||||
| 			<version>4.0.0</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>com.sun.xml.bind</groupId> | ||||
| @@ -107,52 +108,58 @@ | ||||
| 		<dependency> | ||||
| 			<groupId>com.fasterxml.jackson.core</groupId> | ||||
| 			<artifactId>jackson-databind</artifactId> | ||||
| 			<version>2.16.1</version> | ||||
| 			<version>2.17.1</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>com.fasterxml.jackson.dataformat</groupId> | ||||
| 			<artifactId>jackson-dataformat-csv</artifactId> | ||||
| 			<version>2.16.1</version> | ||||
| 			<version>2.17.1</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>com.fasterxml.jackson.datatype</groupId> | ||||
| 			<artifactId>jackson-datatype-jsr310</artifactId> | ||||
| 			<version>2.16.1</version> | ||||
| 			<version>2.17.1</version> | ||||
| 		</dependency> | ||||
|  | ||||
| 		<dependency> | ||||
| 			<groupId>jakarta.servlet</groupId> | ||||
| 			<artifactId>jakarta.servlet-api</artifactId> | ||||
| 			<version>6.1.0-M1</version> | ||||
| 			<version>6.1.0-M2</version> | ||||
| 			<scope>provided</scope> | ||||
| 		</dependency> | ||||
| 		<!-- Interface for My-sql & sqlite DB --> | ||||
| 		<dependency> | ||||
| 			<groupId>com.mysql</groupId> | ||||
| 			<artifactId>mysql-connector-j</artifactId> | ||||
| 			<version>8.2.0</version> | ||||
| 			<version>8.4.0</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>org.xerial</groupId> | ||||
| 			<artifactId>sqlite-jdbc</artifactId> | ||||
| 			<version>3.40.0.0</version> | ||||
| 			<version>3.46.0.0</version> | ||||
| 		</dependency> | ||||
| 		<!-- Interface for JWT token --> | ||||
| 		<dependency> | ||||
| 			<groupId>com.nimbusds</groupId> | ||||
| 			<artifactId>nimbus-jose-jwt</artifactId> | ||||
| 			<version>9.37.1</version> | ||||
| 			<version>9.39.3</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>jakarta.persistence</groupId> | ||||
| 			<artifactId>jakarta.persistence-api</artifactId> | ||||
| 			<version>3.2.0-M1</version> | ||||
| 			<version>3.2.0</version> | ||||
| 		</dependency> | ||||
| 		<!-- Swagger dependencies --> | ||||
| 		<dependency> | ||||
| 			<groupId>io.swagger.core.v3</groupId> | ||||
| 			<artifactId>swagger-jaxrs2-jakarta</artifactId> | ||||
| 			<version>2.1.10</version> | ||||
| 			<version>2.2.22</version> | ||||
| 		</dependency> | ||||
| 		<!-- spotbug tooling --> | ||||
| 		<dependency> | ||||
| 			<groupId>com.github.spotbugs</groupId> | ||||
| 			<artifactId>spotbugs-annotations</artifactId> | ||||
| 			<version>4.8.5</version> | ||||
| 			<scope>compile</scope> | ||||
| 		</dependency> | ||||
| 		<!-- | ||||
| 		************************************************************  | ||||
| @@ -162,19 +169,19 @@ | ||||
| 		<dependency> | ||||
| 			<groupId>org.junit.jupiter</groupId> | ||||
| 			<artifactId>junit-jupiter-api</artifactId> | ||||
| 			<version>5.10.1</version> | ||||
| 			<version>5.11.0-M2</version> | ||||
| 			<scope>test</scope> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>org.junit.jupiter</groupId> | ||||
| 			<artifactId>junit-jupiter-engine</artifactId> | ||||
| 			<version>5.10.1</version> | ||||
| 			<version>5.11.0-M2</version> | ||||
| 			<scope>test</scope> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>net.revelc.code.formatter</groupId> | ||||
| 			<artifactId>formatter-maven-plugin</artifactId> | ||||
| 		    <version>2.23.0</version> | ||||
| 			<version>2.24.0</version> | ||||
| 		</dependency> | ||||
| 		<dependency> | ||||
| 			<groupId>org.apache.maven.plugins</groupId> | ||||
| @@ -182,7 +189,6 @@ | ||||
| 			<version>3.3.1</version> | ||||
| 		</dependency> | ||||
| 	</dependencies> | ||||
|  | ||||
| 	<build> | ||||
| 		<sourceDirectory>src</sourceDirectory> | ||||
| 		<resources> | ||||
| @@ -304,6 +310,23 @@ | ||||
| 					</execution> | ||||
| 				</executions> | ||||
| 			</plugin> | ||||
| 			<plugin> | ||||
| 				<groupId>com.github.spotbugs</groupId> | ||||
| 				<artifactId>spotbugs-maven-plugin</artifactId> | ||||
| 				<version>4.8.5.0</version> | ||||
| 				<configuration> | ||||
| 					<includeFilterFile>spotbugs-security-include.xml</includeFilterFile> | ||||
| 					<excludeFilterFile>spotbugs-security-exclude.xml</excludeFilterFile> | ||||
| 					<!--<plugins> | ||||
| 						<plugin> | ||||
| 							<groupId>com.h3xstream.findsecbugs</groupId> | ||||
| 							<artifactId>findsecbugs-plugin</artifactId> | ||||
| 							<version>1.12.0</version> | ||||
| 						</plugin> | ||||
| 					</plugins> | ||||
| 					--> | ||||
| 				</configuration> | ||||
| 			</plugin> | ||||
| 		</plugins> | ||||
| 	</build> | ||||
| 	<!-- Generate Java-docs As Part Of Project Reports --> | ||||
|   | ||||
							
								
								
									
										126
									
								
								sample/archidata/basic/WebLauncher.java
									
									
									
									
									
										Executable file
									
								
							
							
						
						
									
										126
									
								
								sample/archidata/basic/WebLauncher.java
									
									
									
									
									
										Executable file
									
								
							| @@ -0,0 +1,126 @@ | ||||
| package sample.archidata.basic; | ||||
|  | ||||
| import java.net.URI; | ||||
|  | ||||
| import org.glassfish.grizzly.http.server.HttpServer; | ||||
| import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; | ||||
| import org.glassfish.jersey.jackson.JacksonFeature; | ||||
| import org.glassfish.jersey.media.multipart.MultiPartFeature; | ||||
| import org.glassfish.jersey.server.ResourceConfig; | ||||
| import org.kar.archidata.GlobalConfiguration; | ||||
| import org.kar.archidata.UpdateJwtPublicKey; | ||||
| import org.kar.archidata.api.DataResource; | ||||
| import org.kar.archidata.catcher.ExceptionCatcher; | ||||
| import org.kar.archidata.catcher.FailExceptionCatcher; | ||||
| import org.kar.archidata.catcher.InputExceptionCatcher; | ||||
| import org.kar.archidata.catcher.SystemExceptionCatcher; | ||||
| import org.kar.archidata.db.DBConfig; | ||||
| import org.kar.archidata.filter.CORSFilter; | ||||
| import org.kar.archidata.filter.OptionFilter; | ||||
| import org.kar.archidata.migration.MigrationEngine; | ||||
| import org.kar.archidata.tools.ConfigBaseVariable; | ||||
| import sample.archidata.basic.api.Front; | ||||
| import sample.archidata.basic.api.HealthCheck; | ||||
| import sample.archidata.basic.api.MediaResource; | ||||
| import sample.archidata.basic.api.SeasonResource; | ||||
| import sample.archidata.basic.api.SeriesResource; | ||||
| import sample.archidata.basic.api.TypeResource; | ||||
| import sample.archidata.basic.api.UserMediaAdvancementResource; | ||||
| import sample.archidata.basic.api.UserResource; | ||||
| import sample.archidata.basic.filter.KarideoAuthenticationFilter; | ||||
| import sample.archidata.basic.migration.Initialization; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import jakarta.ws.rs.core.UriBuilder; | ||||
|  | ||||
| public class WebLauncher { | ||||
| 	final static Logger LOGGER = LoggerFactory.getLogger(WebLauncher.class); | ||||
| 	public static DBConfig dbConfig; | ||||
| 	protected UpdateJwtPublicKey keyUpdater = null; | ||||
| 	protected HttpServer server = null; | ||||
|  | ||||
| 	public WebLauncher() { | ||||
| 		ConfigBaseVariable.bdDatabase = "sample_archidata_basic"; | ||||
| 	} | ||||
|  | ||||
| 	private static URI getBaseURI() { | ||||
| 		return UriBuilder.fromUri(ConfigBaseVariable.getlocalAddress()).build(); | ||||
| 	} | ||||
|  | ||||
| 	public void migrateDB() throws Exception { | ||||
| 		WebLauncher.LOGGER.info("Create migration engine"); | ||||
| 		final MigrationEngine migrationEngine = new MigrationEngine(); | ||||
| 		WebLauncher.LOGGER.info("Add initialization"); | ||||
| 		migrationEngine.setInit(new Initialization()); | ||||
| 		//WebLauncher.LOGGER.info("Add migration since last version"); | ||||
| 		//migrationEngine.add(new Migration20230810()); | ||||
| 		WebLauncher.LOGGER.info("Migrate the DB [START]"); | ||||
| 		migrationEngine.migrateWaitAdmin(GlobalConfiguration.dbConfig); | ||||
| 		WebLauncher.LOGGER.info("Migrate the DB [STOP]"); | ||||
| 	} | ||||
|  | ||||
| 	public static void main(final String[] args) throws Exception { | ||||
| 		WebLauncher.LOGGER.info("[START] application wake UP"); | ||||
| 		final WebLauncher launcher = new WebLauncher(); | ||||
| 		launcher.migrateDB(); | ||||
| 		launcher.process(); | ||||
| 		WebLauncher.LOGGER.info("end-configure the server & wait finish process:"); | ||||
| 		Thread.currentThread().join(); | ||||
| 		WebLauncher.LOGGER.info("STOP the REST server"); | ||||
| 	} | ||||
|  | ||||
| 	public void process() throws InterruptedException { | ||||
|  | ||||
| 		// =================================================================== | ||||
| 		// Configure resources | ||||
| 		// =================================================================== | ||||
| 		final ResourceConfig rc = new ResourceConfig(); | ||||
|  | ||||
| 		// Permit to accept OPTION request  | ||||
| 		rc.register(OptionFilter.class); | ||||
| 		// remove cors ==> not obviously needed ... | ||||
| 		rc.register(CORSFilter.class); | ||||
| 		// register exception catcher (this permit to format return error with a normalized JSON) | ||||
| 		rc.register(InputExceptionCatcher.class); | ||||
| 		rc.register(SystemExceptionCatcher.class); | ||||
| 		rc.register(FailExceptionCatcher.class); | ||||
| 		rc.register(ExceptionCatcher.class); | ||||
|  | ||||
| 		// add default resource: | ||||
| 		rc.register(MyModelResource.class); | ||||
|  | ||||
|  | ||||
| 		// add jackson to be discover when we are in stand-alone server | ||||
| 		rc.register(JacksonFeature.class); | ||||
|  | ||||
| 		this.server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc); | ||||
| 		final HttpServer serverLink = this.server; | ||||
| 		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { | ||||
| 			@Override | ||||
| 			public void run() { | ||||
| 				System.out.println("Stopping server.."); | ||||
| 				serverLink.shutdownNow(); | ||||
| 			} | ||||
| 		}, "shutdownHook")); | ||||
|  | ||||
|  | ||||
| 		// =================================================================== | ||||
| 		// run JERSEY | ||||
| 		// =================================================================== | ||||
| 		try { | ||||
| 			this.server.start(); | ||||
| 			LOGGER.info("Jersey app started at {}", getBaseURI()); | ||||
| 		} catch (final Exception e) { | ||||
| 			LOGGER.error("There was an error while starting Grizzly HTTP server."); | ||||
| 			e.printStackTrace(); | ||||
| 		} | ||||
| 	} | ||||
| 	// This is used for TEST (See it later) | ||||
| 	public void stop() { | ||||
| 		if (this.server != null) { | ||||
| 			this.server.shutdownNow(); | ||||
| 			this.server = null; | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										45
									
								
								sample/archidata/basic/WebLauncherLocal.java
									
									
									
									
									
										Executable file
									
								
							
							
						
						
									
										45
									
								
								sample/archidata/basic/WebLauncherLocal.java
									
									
									
									
									
										Executable file
									
								
							| @@ -0,0 +1,45 @@ | ||||
|  | ||||
| package sample.archidata.basic; | ||||
|  | ||||
| import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.api.DataResource; | ||||
| import org.kar.archidata.dataAccess.DataFactoryTsApi; | ||||
| import org.kar.archidata.tools.ConfigBaseVariable; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| public class WebLauncherLocal extends WebLauncher { | ||||
| 	private final static Logger LOGGER = LoggerFactory.getLogger(WebLauncherLocal.class); | ||||
|  | ||||
| 	private WebLauncherLocal() {} | ||||
|  | ||||
| 	public static void main(final String[] args) throws Exception { | ||||
| 		final WebLauncherLocal launcher = new WebLauncherLocal(); | ||||
| 		launcher.process(); | ||||
| 		LOGGER.info("end-configure the server & wait finish process:"); | ||||
| 		Thread.currentThread().join(); | ||||
| 		LOGGER.info("STOP the REST server:"); | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public void process() throws InterruptedException { | ||||
| 		if (true) { | ||||
| 			// for local test: | ||||
| 			ConfigBaseVariable.apiAddress = "http://0.0.0.0:9000/sample/api/"; | ||||
| 			ConfigBaseVariable.dbPort = "3906"; | ||||
| 		} | ||||
| 		try { | ||||
| 			super.migrateDB(); | ||||
| 		} catch (final Exception e) { | ||||
| 			e.printStackTrace(); | ||||
| 			while (true) { | ||||
| 				LOGGER.error("============================================================================"); | ||||
| 				LOGGER.error("== Migration fail ==> waiting intervention of administrator..."); | ||||
| 				LOGGER.error("============================================================================"); | ||||
| 				Thread.sleep(60 * 60 * 1000); | ||||
| 			} | ||||
| 		} | ||||
| 		super.process(); | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										79
									
								
								sample/archidata/basic/api/MyModelResource.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										79
									
								
								sample/archidata/basic/api/MyModelResource.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,79 @@ | ||||
| package sample.archidata.basic.api; | ||||
|  | ||||
| import java.io.IOException; | ||||
| import java.io.InputStream; | ||||
| import java.sql.SQLException; | ||||
| import java.util.List; | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.glassfish.jersey.media.multipart.FormDataContentDisposition; | ||||
| import org.glassfish.jersey.media.multipart.FormDataParam; | ||||
| import org.kar.archidata.annotation.AsyncType; | ||||
| import org.kar.archidata.annotation.TypeScriptProgress; | ||||
| import org.kar.archidata.api.DataResource; | ||||
| import org.kar.archidata.dataAccess.DataAccess; | ||||
| import org.kar.archidata.dataAccess.addOn.AddOnDataJson; | ||||
| import org.kar.archidata.exception.FailException; | ||||
| import org.kar.archidata.exception.InputException; | ||||
| import org.kar.archidata.model.Data; | ||||
| import org.kar.archidata.tools.DataTools; | ||||
| import sample.archidata.basic.model.MyModel; | ||||
| import sample.archidata.basic.model.Season; | ||||
| import sample.archidata.basic.model.Series; | ||||
| import sample.archidata.basic.model.Type; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.Operation; | ||||
| import jakarta.annotation.security.RolesAllowed; | ||||
| 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.Path; | ||||
| import jakarta.ws.rs.PathParam; | ||||
| import jakarta.ws.rs.Produces; | ||||
| import jakarta.ws.rs.core.MyModelType; | ||||
|  | ||||
| @Path("/media") | ||||
| @Produces(MyModelType.APPLICATION_JSON) | ||||
| public class MyModelResource { | ||||
|  | ||||
| 	@GET | ||||
| 	@PermitAll | ||||
| 	public List<MyModel> gets() throws Exception { | ||||
| 		return DataAccess.gets(MyModel.class); | ||||
| 	} | ||||
|  | ||||
| 	@POST | ||||
| 	@PermitAll | ||||
| 	@Consumes(MyModelType.APPLICATION_JSON) | ||||
| 	public MyModel create(final MyModel data) throws Exception { | ||||
| 		return DataAccess.insert(data); | ||||
| 	} | ||||
|  | ||||
| 	@GET | ||||
| 	@Path("{id}") | ||||
| 	@PermitAll | ||||
| 	public MyModel get(@PathParam("id") final Long id) throws Exception { | ||||
| 		return DataAccess.get(MyModel.class, id); | ||||
| 	} | ||||
|  | ||||
|  | ||||
| 	@PATCH | ||||
| 	@Path("{id}") | ||||
| 	@PermitAll | ||||
| 	@Consumes(MyModelType.APPLICATION_JSON) | ||||
| 	public MyModel patch(@PathParam("id") final Long id, final String jsonRequest) throws Exception { | ||||
| 		DataAccess.updateWithJson(MyModel.class, id, jsonRequest); | ||||
| 		return DataAccess.get(MyModel.class, id); | ||||
| 	} | ||||
|  | ||||
| 	@DELETE | ||||
| 	@Path("{id}") | ||||
| 	@PermitAll | ||||
| 	public void remove(@PathParam("id") final Long id) throws Exception { | ||||
| 		DataAccess.delete(MyModel.class, id); | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										28
									
								
								sample/archidata/basic/migration/Initialization.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										28
									
								
								sample/archidata/basic/migration/Initialization.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,28 @@ | ||||
| package sample.archidata.basic.migration; | ||||
|  | ||||
| import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.migration.MigrationSqlStep; | ||||
| import sample.archidata.basic.model.MyModel; | ||||
|  | ||||
| public class Initialization extends MigrationSqlStep { | ||||
| 	public static final List<Class<?>> CLASSES_BASE = List.of(MyModel.class); | ||||
| 	@Override | ||||
| 	public String getName() { | ||||
| 		return "Initialization"; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public void generateStep() throws Exception { | ||||
| 		for(final Class<?> clazz : CLASSES_BASE) { | ||||
| 			addClass(clazz); | ||||
| 		} | ||||
|  | ||||
| 		addAction(""" | ||||
| 				ALTER TABLE `MyModel` AUTO_INCREMENT = 1000; | ||||
| 				""",  | ||||
| 				// Only MySql support this request (fail in SQLite) | ||||
| 				"mysql"); | ||||
| 	} | ||||
|  | ||||
| } | ||||
							
								
								
									
										36
									
								
								sample/archidata/basic/model/MyModel.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										36
									
								
								sample/archidata/basic/model/MyModel.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,36 @@ | ||||
| package sample.archidata.basic.model; | ||||
|  | ||||
| import java.util.List; | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.kar.archidata.annotation.DataJson; | ||||
| import org.kar.archidata.model.Data; | ||||
| import org.kar.archidata.model.GenericDataSoftDelete; | ||||
|  | ||||
| import com.fasterxml.jackson.annotation.JsonInclude; | ||||
|  | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.persistence.Entity; | ||||
| import jakarta.persistence.FetchType; | ||||
| import jakarta.persistence.ManyToOne; | ||||
| import jakarta.persistence.Table; | ||||
|  | ||||
| // needed for Swagger interface | ||||
| @Entity | ||||
| // Do not generate Null in Json serialization ==> prefer undefined | ||||
| @JsonInclude(JsonInclude.Include.NON_NULL) | ||||
| public class MyModel extends GenericDataSoftDelete { | ||||
| 	// Can not be NULL and max length is 300 (note default is 255) | ||||
| 	@Column(nullable = false, length = 300) | ||||
| 	public String name; | ||||
| 	// Can be null and no max length | ||||
| 	@Column(length = 0) | ||||
| 	public String description; | ||||
|  | ||||
| 	@Override | ||||
| 	public String toString() { | ||||
| 		return "MyModel [name=" + this.name + ", description=" + this.description + "]"; | ||||
| 	} | ||||
|  | ||||
|  | ||||
| } | ||||
							
								
								
									
										5
									
								
								spotbugs-security-exclude.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								spotbugs-security-exclude.xml
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,5 @@ | ||||
| <FindBugsFilter> | ||||
|     <Match> | ||||
|         <Bug category="SECURITY"/> | ||||
|     </Match> | ||||
| </FindBugsFilter> | ||||
							
								
								
									
										2
									
								
								spotbugs-security-include.xml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								spotbugs-security-include.xml
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,2 @@ | ||||
| <FindBugsFilter> | ||||
| </FindBugsFilter> | ||||
| @@ -4,7 +4,7 @@ import org.kar.archidata.db.DBConfig; | ||||
| import org.kar.archidata.tools.ConfigBaseVariable; | ||||
|  | ||||
| public class GlobalConfiguration { | ||||
| 	public static DBConfig dbConfig = null; | ||||
| 	public static final DBConfig dbConfig; | ||||
|  | ||||
| 	static { | ||||
| 		dbConfig = new DBConfig(ConfigBaseVariable.getDBType(), ConfigBaseVariable.getDBHost(), | ||||
|   | ||||
| @@ -5,9 +5,9 @@ import java.sql.PreparedStatement; | ||||
| import java.sql.SQLException; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.DataAccess; | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
| import org.kar.archidata.dataAccess.QueryOptions; | ||||
| import org.kar.archidata.dataAccess.options.DBInterfaceOption; | ||||
| import org.kar.archidata.dataAccess.options.QueryOption; | ||||
| import org.kar.archidata.db.DBEntry; | ||||
| import org.kar.archidata.model.User; | ||||
|  | ||||
|   | ||||
| @@ -7,15 +7,19 @@ import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOptions; | ||||
| import org.kar.archidata.dataAccess.options.OverrideTableName; | ||||
| import org.kar.archidata.exception.DataAccessException; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.media.Schema; | ||||
| import jakarta.annotation.Nullable; | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.persistence.GeneratedValue; | ||||
| import jakarta.persistence.GenerationType; | ||||
| import jakarta.persistence.Id; | ||||
| import jakarta.persistence.ManyToMany; | ||||
| import jakarta.persistence.ManyToOne; | ||||
| import jakarta.persistence.OneToMany; | ||||
| import jakarta.persistence.Table; | ||||
| import jakarta.validation.constraints.Max; | ||||
| import jakarta.validation.constraints.Min; | ||||
| @@ -27,7 +31,7 @@ import jakarta.ws.rs.DefaultValue; | ||||
| public class AnnotationTools { | ||||
| 	static final Logger LOGGER = LoggerFactory.getLogger(AnnotationTools.class); | ||||
|  | ||||
| 	public static String getTableName(final Class<?> clazz, final QueryOptions options) throws Exception { | ||||
| 	public static String getTableName(final Class<?> clazz, final QueryOptions options) throws DataAccessException { | ||||
| 		if (options != null) { | ||||
| 			final List<OverrideTableName> data = options.get(OverrideTableName.class); | ||||
| 			if (data.size() == 1) { | ||||
| @@ -37,14 +41,15 @@ public class AnnotationTools { | ||||
| 		return AnnotationTools.getTableName(clazz); | ||||
| 	} | ||||
|  | ||||
| 	public static String getTableName(final Class<?> element) throws Exception { | ||||
| 	public static String getTableName(final Class<?> element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Table.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			// when no annotation is detected, then the table name is the class name | ||||
| 			return element.getSimpleName(); | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception("Must not have more than 1 element @Table on " + element.getClass().getCanonicalName()); | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Table on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		final String tmp = ((Table) annotation[0]).name(); | ||||
| 		if (tmp == null) { | ||||
| @@ -53,155 +58,178 @@ public class AnnotationTools { | ||||
| 		return tmp; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean getSchemaReadOnly(final Field element) throws Exception { | ||||
| 	public static boolean getSchemaReadOnly(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Schema.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((Schema) annotation[0]).readOnly(); | ||||
| 	} | ||||
|  | ||||
| 	public static String getSchemaExample(final Class<?> element) throws Exception { | ||||
| 	public static String getSchemaExample(final Class<?> element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Schema.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((Schema) annotation[0]).example(); | ||||
| 	} | ||||
|  | ||||
| 	public static String getSchemaDescription(final Class<?> element) throws Exception { | ||||
| 	public static boolean getNoWriteSpecificMode(final Class<?> element) { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(NoWriteSpecificMode.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		return true; | ||||
| 	} | ||||
|  | ||||
| 	public static String getSchemaDescription(final Class<?> element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Schema.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((Schema) annotation[0]).description(); | ||||
| 	} | ||||
|  | ||||
| 	public static String getSchemaDescription(final Field element) throws Exception { | ||||
| 	public static String getSchemaDescription(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Schema.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Schema on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((Schema) annotation[0]).description(); | ||||
| 	} | ||||
|  | ||||
| 	public static String getComment(final Field element) throws Exception { | ||||
| 	public static String getComment(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(DataComment.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return getSchemaDescription(element); | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @DataComment on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((DataComment) annotation[0]).value(); | ||||
| 	} | ||||
|  | ||||
| 	public static String getDefault(final Field element) throws Exception { | ||||
| 	public static String getDefault(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(DefaultValue.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @DataDefault on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((DefaultValue) annotation[0]).value(); | ||||
| 	} | ||||
|  | ||||
| 	public static ManyToOne getManyToOne(final Field element) throws Exception { | ||||
| 	public static ManyToOne getManyToOne(final Field element) { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(ManyToOne.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 					"Must not have more than 1 element @ManyToOne on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return (ManyToOne) annotation[0]; | ||||
| 	} | ||||
|  | ||||
| 	public static DataJson getDataJson(final Field element) throws Exception { | ||||
| 	public static ManyToMany getManyToMany(final Field element) { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(ManyToMany.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		return (ManyToMany) annotation[0]; | ||||
| 	} | ||||
|  | ||||
| 	public static OneToMany getOneToMany(final Field element) { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(OneToMany.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		return (OneToMany) annotation[0]; | ||||
| 	} | ||||
|  | ||||
| 	public static DataJson getDataJson(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(DataJson.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @ManyToOne on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return (DataJson) annotation[0]; | ||||
| 	} | ||||
|  | ||||
| 	public static Long getConstraintsMax(final Field element) throws Exception { | ||||
| 	public static Long getConstraintsMax(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Max.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception("Must not have more than 1 element @Size on " + element.getClass().getCanonicalName()); | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Size on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((Max) annotation[0]).value(); | ||||
| 	} | ||||
|  | ||||
| 	public static Long getConstraintsMin(final Field element) throws Exception { | ||||
| 	public static Long getConstraintsMin(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Min.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception("Must not have more than 1 element @Size on " + element.getClass().getCanonicalName()); | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Size on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((Min) annotation[0]).value(); | ||||
| 	} | ||||
|  | ||||
| 	public static int getLimitSize(final Field element) throws Exception { | ||||
| 	public static int getLimitSize(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Column.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return 255; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		final int length = ((Column) annotation[0]).length(); | ||||
| 		return length <= 0 ? 0 : length; | ||||
| 	} | ||||
|  | ||||
| 	public static Size getConstraintsSize(final Field element) throws Exception { | ||||
| 	public static Size getConstraintsSize(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Size.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception("Must not have more than 1 element @Size on " + element.getClass().getCanonicalName()); | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Size on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return (Size) annotation[0]; | ||||
| 	} | ||||
|  | ||||
| 	public static String getConstraintsPattern(final Field element) throws Exception { | ||||
| 	public static String getConstraintsPattern(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Pattern.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Pattern on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((Pattern) annotation[0]).regexp(); | ||||
| @@ -230,13 +258,13 @@ public class AnnotationTools { | ||||
| 		return false; | ||||
| 	} | ||||
|  | ||||
| 	public static String getFieldName(final Field element) throws Exception { | ||||
| 	public static String getFieldName(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Column.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return element.getName(); | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		final String name = ((Column) annotation[0]).name(); | ||||
| @@ -246,31 +274,39 @@ public class AnnotationTools { | ||||
| 		return name; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean getColumnNotNull(final Field element) throws Exception { | ||||
| 	public static boolean getColumnNotNull(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Column.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return !((Column) annotation[0]).nullable(); | ||||
| 	} | ||||
|  | ||||
| 	public static boolean getConstraintsNotNull(final Field element) throws Exception { | ||||
| 	public static boolean getNullable(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Nullable.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		return true; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean getConstraintsNotNull(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(NotNull.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @NotNull on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return true; | ||||
| 	} | ||||
|  | ||||
| 	public static Field getPrimaryKeyField(final Class<?> clazz) throws Exception { | ||||
| 	public static Field getPrimaryKeyField(final Class<?> clazz) throws DataAccessException { | ||||
| 		for (final Field field : clazz.getFields()) { | ||||
| 			// static field is only for internal global declaration ==> remove it .. | ||||
| 			if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { | ||||
| @@ -283,7 +319,7 @@ public class AnnotationTools { | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean isPrimaryKey(final Field element) throws Exception { | ||||
| 	public static boolean isPrimaryKey(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Id.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return false; | ||||
| @@ -291,51 +327,51 @@ public class AnnotationTools { | ||||
| 		return true; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean isUnique(final Field element) throws Exception { | ||||
| 	public static boolean isUnique(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(Column.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((Column) annotation[0]).unique(); | ||||
| 	} | ||||
|  | ||||
| 	public static GenerationType getStrategy(final Field element) throws Exception { | ||||
| 	public static GenerationType getStrategy(final Field element) throws DataAccessException { | ||||
| 		final Annotation[] annotation = element.getDeclaredAnnotationsByType(GeneratedValue.class); | ||||
| 		if (annotation.length == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (annotation.length > 1) { | ||||
| 			throw new Exception( | ||||
| 			throw new DataAccessException( | ||||
| 					"Must not have more than 1 element @Column on " + element.getClass().getCanonicalName()); | ||||
| 		} | ||||
| 		return ((GeneratedValue) annotation[0]).strategy(); | ||||
| 	} | ||||
|  | ||||
| 	public static boolean isDeletedField(final Field element) throws Exception { | ||||
| 	public static boolean isDeletedField(final Field element) throws DataAccessException { | ||||
| 		return element.getDeclaredAnnotationsByType(DataDeleted.class).length != 0; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean isCreatedAtField(final Field element) throws Exception { | ||||
| 	public static boolean isCreatedAtField(final Field element) throws DataAccessException { | ||||
| 		return element.getDeclaredAnnotationsByType(CreationTimestamp.class).length != 0; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean isUpdateAtField(final Field element) throws Exception { | ||||
| 	public static boolean isUpdateAtField(final Field element) throws DataAccessException { | ||||
| 		return element.getDeclaredAnnotationsByType(UpdateTimestamp.class).length != 0; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean isdefaultNotRead(final Field element) throws Exception { | ||||
| 	public static boolean isdefaultNotRead(final Field element) throws DataAccessException { | ||||
| 		return element.getDeclaredAnnotationsByType(DataNotRead.class).length != 0; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean isIdField(final Field element) throws Exception { | ||||
| 	public static boolean isIdField(final Field element) throws DataAccessException { | ||||
| 		return element.getDeclaredAnnotationsByType(Id.class).length != 0; | ||||
| 	} | ||||
|  | ||||
| 	public static String getDeletedFieldName(final Class<?> clazz) throws Exception { | ||||
| 	public static String getDeletedFieldName(final Class<?> clazz) throws DataAccessException { | ||||
| 		try { | ||||
| 			for (final Field elem : clazz.getFields()) { | ||||
| 				// static field is only for internal global declaration ==> remove it .. | ||||
| @@ -352,7 +388,7 @@ public class AnnotationTools { | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	public static String getUpdatedFieldName(final Class<?> clazz) throws Exception { | ||||
| 	public static String getUpdatedFieldName(final Class<?> clazz) throws DataAccessException { | ||||
| 		try { | ||||
| 			for (final Field elem : clazz.getFields()) { | ||||
| 				// static field is only for internal global declaration ==> remove it .. | ||||
| @@ -386,15 +422,16 @@ public class AnnotationTools { | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	public static List<String> getFieldsNames(final Class<?> clazz) throws Exception { | ||||
| 	public static List<String> getFieldsNames(final Class<?> clazz) throws DataAccessException { | ||||
| 		return getFieldsNamesFilter(clazz, false); | ||||
| 	} | ||||
|  | ||||
| 	public static List<String> getAllFieldsNames(final Class<?> clazz) throws Exception { | ||||
| 	public static List<String> getAllFieldsNames(final Class<?> clazz) throws DataAccessException { | ||||
| 		return getFieldsNamesFilter(clazz, true); | ||||
| 	} | ||||
|  | ||||
| 	private static List<String> getFieldsNamesFilter(final Class<?> clazz, final boolean full) throws Exception { | ||||
| 	private static List<String> getFieldsNamesFilter(final Class<?> clazz, final boolean full) | ||||
| 			throws DataAccessException { | ||||
| 		final List<String> out = new ArrayList<>(); | ||||
| 		for (final Field field : clazz.getFields()) { | ||||
| 			// static field is only for internal global declaration ==> remove it .. | ||||
| @@ -409,12 +446,12 @@ public class AnnotationTools { | ||||
| 		return out; | ||||
| 	} | ||||
|  | ||||
| 	public static boolean isGenericField(final Field elem) throws Exception { | ||||
| 	public static boolean isGenericField(final Field elem) throws DataAccessException { | ||||
| 		return AnnotationTools.isPrimaryKey(elem) || AnnotationTools.isCreatedAtField(elem) | ||||
| 				|| AnnotationTools.isUpdateAtField(elem) || AnnotationTools.isDeletedField(elem); | ||||
| 	} | ||||
|  | ||||
| 	public static Field getFieldOfId(final Class<?> clazz) throws Exception { | ||||
| 	public static Field getFieldOfId(final Class<?> clazz) throws DataAccessException { | ||||
| 		for (final Field field : clazz.getFields()) { | ||||
| 			// static field is only for internal global declaration ==> remove it .. | ||||
| 			if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { | ||||
| @@ -427,7 +464,7 @@ public class AnnotationTools { | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	public static Field getFieldNamed(final Class<?> clazz, final String name) throws Exception { | ||||
| 	public static Field getFieldNamed(final Class<?> clazz, final String name) throws DataAccessException { | ||||
| 		for (final Field field : clazz.getFields()) { | ||||
| 			// static field is only for internal global declaration ==> remove it .. | ||||
| 			if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { | ||||
|   | ||||
| @@ -5,8 +5,9 @@ import java.lang.annotation.Retention; | ||||
| import java.lang.annotation.RetentionPolicy; | ||||
| import java.lang.annotation.Target; | ||||
| 
 | ||||
| /** When we wend to have only One type for read and write mode (Wrapping API). */ | ||||
| @Target({ ElementType.TYPE }) | ||||
| @Retention(RetentionPolicy.RUNTIME) | ||||
| public @interface SQLWhere { | ||||
| 	String clause(); | ||||
| public @interface NoWriteSpecificMode { | ||||
| 
 | ||||
| } | ||||
| @@ -5,6 +5,7 @@ import java.awt.image.BufferedImage; | ||||
| import java.io.ByteArrayOutputStream; | ||||
| import java.io.File; | ||||
| import java.io.FileInputStream; | ||||
| import java.io.FileNotFoundException; | ||||
| import java.io.FileOutputStream; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStream; | ||||
| @@ -26,6 +27,7 @@ import org.kar.archidata.annotation.security.PermitTokenInURI; | ||||
| import org.kar.archidata.dataAccess.DataAccess; | ||||
| import org.kar.archidata.dataAccess.QueryCondition; | ||||
| import org.kar.archidata.dataAccess.options.Condition; | ||||
| import org.kar.archidata.exception.FailException; | ||||
| import org.kar.archidata.filter.GenericContext; | ||||
| import org.kar.archidata.model.Data; | ||||
| import org.kar.archidata.tools.ConfigBaseVariable; | ||||
| @@ -191,7 +193,8 @@ public class DataResource { | ||||
| 		LOGGER.info("Move done"); | ||||
| 	} | ||||
|  | ||||
| 	public static String saveTemporaryFile(final InputStream uploadedInputStream, final long idData) { | ||||
| 	public static String saveTemporaryFile(final InputStream uploadedInputStream, final long idData) | ||||
| 			throws FailException { | ||||
| 		return saveFile(uploadedInputStream, DataResource.getTmpFileInData(idData)); | ||||
| 	} | ||||
|  | ||||
| @@ -208,35 +211,35 @@ public class DataResource { | ||||
| 	} | ||||
|  | ||||
| 	// save uploaded file to a defined location on the server | ||||
| 	static String saveFile(final InputStream uploadedInputStream, final String serverLocation) { | ||||
| 	static String saveFile(final InputStream uploadedInputStream, final String serverLocation) throws FailException { | ||||
| 		String out = ""; | ||||
| 		try { | ||||
| 			OutputStream outpuStream = new FileOutputStream(new File(serverLocation)); | ||||
| 		MessageDigest md = null; | ||||
| 		try (OutputStream outpuStream = new FileOutputStream(new File(serverLocation))) { | ||||
| 			md = MessageDigest.getInstance("SHA-512"); | ||||
| 		} catch (final IOException ex) { | ||||
| 			throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, "Can not write in temporary file", ex); | ||||
| 		} catch (final NoSuchAlgorithmException ex) { | ||||
| 			throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, "Can not find sha512 algorithms", ex); | ||||
| 		} | ||||
| 		if (md != null) { | ||||
| 			try (OutputStream outpuStream = new FileOutputStream(new File(serverLocation))) { | ||||
| 				int read = 0; | ||||
| 				final byte[] bytes = new byte[CHUNK_SIZE_IN]; | ||||
| 			final MessageDigest md = MessageDigest.getInstance("SHA-512"); | ||||
|  | ||||
| 			outpuStream = new FileOutputStream(new File(serverLocation)); | ||||
| 				while ((read = uploadedInputStream.read(bytes)) != -1) { | ||||
| 					// logger.info("write {}", read); | ||||
| 					md.update(bytes, 0, read); | ||||
| 					outpuStream.write(bytes, 0, read); | ||||
| 				} | ||||
| 				LOGGER.info("Flush input stream ... {}", serverLocation); | ||||
| 			System.out.flush(); | ||||
| 				outpuStream.flush(); | ||||
| 			outpuStream.close(); | ||||
| 				// create the end of sha512 | ||||
| 				final byte[] sha512Digest = md.digest(); | ||||
| 				// convert in hexadecimal | ||||
| 				out = bytesToHex(sha512Digest); | ||||
| 				uploadedInputStream.close(); | ||||
| 			} catch (final IOException ex) { | ||||
| 			LOGGER.info("Can not write in temporary file ... "); | ||||
| 			ex.printStackTrace(); | ||||
| 		} catch (final NoSuchAlgorithmException ex) { | ||||
| 			LOGGER.info("Can not find sha512 algorithms"); | ||||
| 			ex.printStackTrace(); | ||||
| 				throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, "Can not write in temporary file", ex); | ||||
| 			} | ||||
| 		} | ||||
| 		return out; | ||||
| 	} | ||||
| @@ -267,7 +270,7 @@ public class DataResource { | ||||
| 	public void uploadFile( | ||||
| 			@Context final SecurityContext sc, | ||||
| 			@FormDataParam("file") final InputStream fileInputStream, | ||||
| 			@FormDataParam("file") final FormDataContentDisposition fileMetaData) { | ||||
| 			@FormDataParam("file") final FormDataContentDisposition fileMetaData) throws FailException { | ||||
| 		final GenericContext gc = (GenericContext) sc.getUserPrincipal(); | ||||
| 		LOGGER.info("==================================================="); | ||||
| 		LOGGER.info("== DATA uploadFile {}", (gc == null ? "null" : gc.userByToken)); | ||||
| @@ -277,8 +280,9 @@ public class DataResource { | ||||
| 		final String filePath = ConfigBaseVariable.getTmpDataFolder() + File.separator + tmpFolderId++; | ||||
| 		try { | ||||
| 			createFolder(ConfigBaseVariable.getTmpDataFolder() + File.separator); | ||||
| 		} catch (final IOException e) { | ||||
| 			e.printStackTrace(); | ||||
| 		} catch (final IOException ex) { | ||||
| 			throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, | ||||
| 					"Impossible to create the folder in the server", ex); | ||||
| 		} | ||||
| 		saveFile(fileInputStream, filePath); | ||||
| 	} | ||||
| @@ -293,16 +297,21 @@ public class DataResource { | ||||
| 			@Context final SecurityContext sc, | ||||
| 			@QueryParam(HttpHeaders.AUTHORIZATION) final String token, | ||||
| 			@HeaderParam("Range") final String range, | ||||
| 			@PathParam("uuid") final UUID uuid) throws Exception { | ||||
| 			@PathParam("uuid") final UUID uuid) throws FailException { | ||||
| 		final GenericContext gc = (GenericContext) sc.getUserPrincipal(); | ||||
| 		// logger.info("==================================================="); | ||||
| 		LOGGER.info("== DATA retrieveDataId ? id={} user={}", uuid, (gc == null ? "null" : gc.userByToken)); | ||||
| 		// logger.info("==================================================="); | ||||
| 		final Data value = getSmall(uuid); | ||||
| 		if (value == null) { | ||||
| 			Response.status(404).entity("media NOT FOUND: " + uuid).type("text/plain").build(); | ||||
| 			return Response.status(404).entity("media NOT FOUND: " + uuid).type("text/plain").build(); | ||||
| 		} | ||||
| 		try { | ||||
| 			return buildStream(getFileData(uuid), range, | ||||
| 					value.mimeType == null ? "application/octet-stream" : value.mimeType); | ||||
| 		} catch (final Exception ex) { | ||||
| 			throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, "Fail to build output stream", ex); | ||||
| 		} | ||||
| 		return buildStream(getFileData(uuid), range, value.mimeType); | ||||
| 	} | ||||
|  | ||||
| 	@GET | ||||
| @@ -316,7 +325,7 @@ public class DataResource { | ||||
| 			@Context final SecurityContext sc, | ||||
| 			@QueryParam(HttpHeaders.AUTHORIZATION) final String token, | ||||
| 			@HeaderParam("Range") final String range, | ||||
| 			@PathParam("uuid") final UUID uuid) throws Exception { | ||||
| 			@PathParam("uuid") final UUID uuid) throws FailException { | ||||
| 		// GenericContext gc = (GenericContext) sc.getUserPrincipal(); | ||||
| 		// logger.info("==================================================="); | ||||
| 		// logger.info("== DATA retrieveDataThumbnailId ? {}", (gc==null?"null":gc.user)); | ||||
| @@ -335,7 +344,12 @@ public class DataResource { | ||||
| 		// || value.mimeType.contentEquals("image/webp") | ||||
| 		) { | ||||
| 			// reads input image | ||||
| 			final BufferedImage inputImage = ImageIO.read(inputFile); | ||||
| 			BufferedImage inputImage; | ||||
| 			try { | ||||
| 				inputImage = ImageIO.read(inputFile); | ||||
| 			} catch (final IOException ex) { | ||||
| 				throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, "Fail to READ the image", ex); | ||||
| 			} | ||||
| 			final int scaledWidth = 250; | ||||
| 			final int scaledHeight = (int) ((float) inputImage.getHeight() / (float) inputImage.getWidth() | ||||
| 					* scaledWidth); | ||||
| @@ -368,7 +382,11 @@ public class DataResource { | ||||
| 			out.cacheControl(cc); | ||||
| 			return out.build(); | ||||
| 		} | ||||
| 		try { | ||||
| 			return buildStream(filePathName, range, value.mimeType); | ||||
| 		} catch (final Exception ex) { | ||||
| 			throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, "Fail to build output stream", ex); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	@GET | ||||
| @@ -389,17 +407,20 @@ public class DataResource { | ||||
| 		// logger.info("==================================================="); | ||||
| 		final Data value = getSmall(uuid); | ||||
| 		if (value == null) { | ||||
| 			Response.status(404).entity("media NOT FOUND: " + uuid).type("text/plain").build(); | ||||
| 			return Response.status(404).entity("media NOT FOUND: " + uuid).type("text/plain").build(); | ||||
| 		} | ||||
| 		return buildStream(getFileData(uuid), range, value.mimeType); | ||||
| 		return buildStream(getFileData(uuid), range, | ||||
| 				value.mimeType == null ? "application/octet-stream" : value.mimeType); | ||||
| 	} | ||||
|  | ||||
| 	/** Adapted from http://stackoverflow.com/questions/12768812/video-streaming-to-ipad-does-not-work-with-tapestry5/12829541#12829541 | ||||
| 	 * | ||||
| 	 * @param range range header | ||||
| 	 * @return Streaming output | ||||
| 	 * @throws FileNotFoundException | ||||
| 	 * @throws Exception IOException if an error occurs in streaming. */ | ||||
| 	private Response buildStream(final String filename, final String range, final String mimeType) throws Exception { | ||||
| 	private Response buildStream(final String filename, final String range, final String mimeType) | ||||
| 			throws FailException { | ||||
| 		final File file = new File(filename); | ||||
| 		// logger.info("request range : {}", range); | ||||
| 		// range not requested : Firefox does not send range headers | ||||
| @@ -446,7 +467,7 @@ public class DataResource { | ||||
| 		} | ||||
| 		final String responseRange = String.format("bytes %d-%d/%d", from, to, file.length()); | ||||
| 		// logger.info("responseRange: {}", responseRange); | ||||
| 		final RandomAccessFile raf = new RandomAccessFile(file, "r"); | ||||
| 		try (final RandomAccessFile raf = new RandomAccessFile(file, "r")) { | ||||
| 			raf.seek(from); | ||||
|  | ||||
| 			final long len = to - from + 1; | ||||
| @@ -459,6 +480,11 @@ public class DataResource { | ||||
| 				out.type(mimeType); | ||||
| 			} | ||||
| 			return out.build(); | ||||
| 		} catch (final FileNotFoundException ex) { | ||||
| 			throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, "Fail to find the required file.", ex); | ||||
| 		} catch (final IOException ex) { | ||||
| 			throw new FailException(Response.Status.INTERNAL_SERVER_ERROR, "Fail to access to the required file.", ex); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	public static void undelete(final Long id) throws Exception { | ||||
|   | ||||
| @@ -21,8 +21,8 @@ public class ExceptionCatcher implements ExceptionMapper<Exception> { | ||||
| 	} | ||||
|  | ||||
| 	private RestErrorResponse build(final Exception exception) { | ||||
| 		return new RestErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, "Catch Unknown Exception", | ||||
| 				exception.getMessage()); | ||||
| 		return new RestErrorResponse(Response.Status.INTERNAL_SERVER_ERROR, | ||||
| 				"Catch Unknown Exception: " + exception.getClass().getCanonicalName(), exception.getMessage()); | ||||
| 	} | ||||
|  | ||||
| } | ||||
|   | ||||
| @@ -13,11 +13,12 @@ public class FailExceptionCatcher implements ExceptionMapper<FailException> { | ||||
|  | ||||
| 	@Override | ||||
| 	public Response toResponse(final FailException exception) { | ||||
| 		LOGGER.warn("Catch FailException:"); | ||||
| 		LOGGER.warn("Catch FailException: {}", exception.getLocalizedMessage()); | ||||
| 		final RestErrorResponse ret = build(exception); | ||||
| 		LOGGER.error("Error UUID={}", ret.uuid); | ||||
| 		// Not display backtrace ==> this may be a normal case ... | ||||
| 		// exception.printStackTrace(); | ||||
| 		if (exception.exception != null) { | ||||
| 			exception.exception.printStackTrace(); | ||||
| 		} | ||||
| 		return Response.status(exception.status).entity(ret).type(MediaType.APPLICATION_JSON).build(); | ||||
| 	} | ||||
|  | ||||
|   | ||||
							
								
								
									
										24
									
								
								src/org/kar/archidata/catcher/GenericCatcher.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										24
									
								
								src/org/kar/archidata/catcher/GenericCatcher.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,24 @@ | ||||
| package org.kar.archidata.catcher; | ||||
|  | ||||
| import org.glassfish.jersey.server.ResourceConfig; | ||||
|  | ||||
| public class GenericCatcher { | ||||
|  | ||||
| 	/** | ||||
| 	 * Add All the the generic catcher to standardize returns. | ||||
| 	 * @param rc Resource exception model. | ||||
| 	 */ | ||||
| 	public static void addAll(final ResourceConfig rc) { | ||||
| 		// Generic Json parsing error | ||||
| 		rc.register(JacksonExceptionCatcher.class); | ||||
| 		// Catch jakarta generic errors | ||||
| 		rc.register(WebApplicationExceptionCatcher.class); | ||||
| 		// Archidata exceptions | ||||
| 		rc.register(InputExceptionCatcher.class); | ||||
| 		rc.register(SystemExceptionCatcher.class); | ||||
| 		rc.register(FailExceptionCatcher.class); | ||||
| 		// generic Exception catcher | ||||
| 		rc.register(ExceptionCatcher.class); | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -3,17 +3,17 @@ package org.kar.archidata.catcher; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import com.fasterxml.jackson.core.JsonProcessingException; | ||||
| import com.fasterxml.jackson.core.JacksonException; | ||||
| 
 | ||||
| import jakarta.ws.rs.core.MediaType; | ||||
| import jakarta.ws.rs.core.Response; | ||||
| import jakarta.ws.rs.ext.ExceptionMapper; | ||||
| 
 | ||||
| public class JacksonCatcher implements ExceptionMapper<JsonProcessingException> { | ||||
| 	private static final Logger LOGGER = LoggerFactory.getLogger(JacksonCatcher.class); | ||||
| public class JacksonExceptionCatcher implements ExceptionMapper<JacksonException> { | ||||
| 	private static final Logger LOGGER = LoggerFactory.getLogger(JacksonExceptionCatcher.class); | ||||
| 
 | ||||
| 	@Override | ||||
| 	public Response toResponse(final JsonProcessingException exception) { | ||||
| 	public Response toResponse(final JacksonException exception) { | ||||
| 		LOGGER.warn("Catch exception Input data parsing:"); | ||||
| 		final RestErrorResponse ret = build(exception); | ||||
| 		LOGGER.error("Error UUID={}", ret.uuid); | ||||
| @@ -3,16 +3,29 @@ package org.kar.archidata.catcher; | ||||
| import java.time.Instant; | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.kar.archidata.annotation.NoWriteSpecificMode; | ||||
| import org.kar.archidata.tools.UuidUtils; | ||||
|  | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.validation.constraints.NotNull; | ||||
| import jakarta.ws.rs.core.Response; | ||||
|  | ||||
| @NoWriteSpecificMode | ||||
| public class RestErrorResponse { | ||||
| 	public UUID uuid = UuidUtils.nextUUID(); | ||||
| 	@NotNull | ||||
| 	@Column(length = 0) | ||||
| 	public String name; // Mandatory for TS generic error | ||||
| 	@NotNull | ||||
| 	@Column(length = 0) | ||||
| 	public String message; // Mandatory for TS generic error | ||||
| 	@NotNull | ||||
| 	@Column(length = 0) | ||||
| 	public String time; | ||||
| 	@NotNull | ||||
| 	final public int status; | ||||
| 	@NotNull | ||||
| 	@Column(length = 0) | ||||
| 	final public String statusMessage; | ||||
|  | ||||
| 	public RestErrorResponse(final Response.Status status, final String time, final String error, | ||||
|   | ||||
| @@ -3,23 +3,23 @@ package org.kar.archidata.catcher; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| 
 | ||||
| import jakarta.ws.rs.ClientErrorException; | ||||
| import jakarta.ws.rs.WebApplicationException; | ||||
| import jakarta.ws.rs.core.MediaType; | ||||
| import jakarta.ws.rs.core.Response; | ||||
| import jakarta.ws.rs.ext.ExceptionMapper; | ||||
| 
 | ||||
| public class FailException404API implements ExceptionMapper<ClientErrorException> { | ||||
| 	private static final Logger LOGGER = LoggerFactory.getLogger(FailException404API.class); | ||||
| public class WebApplicationExceptionCatcher implements ExceptionMapper<WebApplicationException> { | ||||
| 	private static final Logger LOGGER = LoggerFactory.getLogger(WebApplicationExceptionCatcher.class); | ||||
| 
 | ||||
| 	@Override | ||||
| 	public Response toResponse(final ClientErrorException exception) { | ||||
| 	public Response toResponse(final WebApplicationException exception) { | ||||
| 		final RestErrorResponse ret = build(exception); | ||||
| 		LOGGER.error("Error UUID={}", ret.uuid); | ||||
| 		return Response.status(exception.getResponse().getStatusInfo().toEnum()).entity(ret) | ||||
| 				.type(MediaType.APPLICATION_JSON).build(); | ||||
| 	} | ||||
| 
 | ||||
| 	private RestErrorResponse build(final ClientErrorException exception) { | ||||
| 	private RestErrorResponse build(final WebApplicationException exception) { | ||||
| 		return new RestErrorResponse(exception.getResponse().getStatusInfo().toEnum(), "Catch system exception", | ||||
| 				exception.getMessage()); | ||||
| 	} | ||||
| @@ -25,12 +25,16 @@ import org.kar.archidata.annotation.UpdateTimestamp; | ||||
| import org.kar.archidata.dataAccess.addOn.AddOnDataJson; | ||||
| import org.kar.archidata.dataAccess.addOn.AddOnManyToMany; | ||||
| import org.kar.archidata.dataAccess.addOn.AddOnManyToOne; | ||||
| import org.kar.archidata.dataAccess.addOn.AddOnSQLTableExternalForeinKeyAsList; | ||||
| import org.kar.archidata.dataAccess.addOn.AddOnOneToMany; | ||||
| import org.kar.archidata.dataAccess.options.CheckFunction; | ||||
| import org.kar.archidata.dataAccess.options.Condition; | ||||
| import org.kar.archidata.dataAccess.options.DBInterfaceOption; | ||||
| import org.kar.archidata.dataAccess.options.DBInterfaceRoot; | ||||
| import org.kar.archidata.dataAccess.options.FilterValue; | ||||
| import org.kar.archidata.dataAccess.options.GroupBy; | ||||
| import org.kar.archidata.dataAccess.options.Limit; | ||||
| import org.kar.archidata.dataAccess.options.OrderBy; | ||||
| import org.kar.archidata.dataAccess.options.QueryOption; | ||||
| import org.kar.archidata.dataAccess.options.TransmitKey; | ||||
| import org.kar.archidata.db.DBEntry; | ||||
| import org.kar.archidata.exception.DataAccessException; | ||||
| @@ -43,6 +47,7 @@ import org.slf4j.LoggerFactory; | ||||
| import com.fasterxml.jackson.databind.JsonNode; | ||||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||||
|  | ||||
| import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; | ||||
| import jakarta.ws.rs.DefaultValue; | ||||
| import jakarta.ws.rs.InternalServerErrorException; | ||||
|  | ||||
| @@ -60,7 +65,7 @@ public class DataAccess { | ||||
| 	static { | ||||
| 		addOn.add(new AddOnManyToMany()); | ||||
| 		addOn.add(new AddOnManyToOne()); | ||||
| 		addOn.add(new AddOnSQLTableExternalForeinKeyAsList()); | ||||
| 		addOn.add(new AddOnOneToMany()); | ||||
| 		addOn.add(new AddOnDataJson()); | ||||
| 	} | ||||
|  | ||||
| @@ -246,6 +251,14 @@ public class DataAccess { | ||||
| 		return out; | ||||
| 	} | ||||
|  | ||||
| 	public static UUID getListOfRawUUID(final ResultSet rs, final int iii) throws SQLException, DataAccessException { | ||||
| 		final byte[] elem = rs.getBytes(iii); | ||||
| 		if (rs.wasNull()) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		return UuidUtils.asUuid(elem); | ||||
| 	} | ||||
|  | ||||
| 	protected static <T> void setValuedb( | ||||
| 			final Class<?> type, | ||||
| 			final T data, | ||||
| @@ -785,6 +798,7 @@ public class DataAccess { | ||||
| 		return out; | ||||
| 	} | ||||
|  | ||||
| 	@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING") | ||||
| 	public static <T> T insert(final T data, final QueryOption... option) throws Exception { | ||||
| 		final Class<?> clazz = data.getClass(); | ||||
| 		final QueryOptions options = new QueryOptions(option); | ||||
| @@ -792,7 +806,7 @@ public class DataAccess { | ||||
| 		// External checker of data: | ||||
| 		final List<CheckFunction> checks = options.get(CheckFunction.class); | ||||
| 		for (final CheckFunction check : checks) { | ||||
| 			check.getChecker().check("", data, AnnotationTools.getFieldsNames(clazz)); | ||||
| 			check.getChecker().check("", data, AnnotationTools.getFieldsNames(clazz), options); | ||||
| 		} | ||||
|  | ||||
| 		final DBEntry entry = DBInterfaceOption.getAutoEntry(options); | ||||
| @@ -891,7 +905,7 @@ public class DataAccess { | ||||
| 			for (final OrderBy order : orders) { | ||||
| 				order.generateQuery(query, tableName); | ||||
| 			} | ||||
| 			LOGGER.warn("generate the query: '{}'", query.toString()); | ||||
| 			LOGGER.debug("generate the query: '{}'", query.toString()); | ||||
| 			// prepare the request: | ||||
| 			final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), | ||||
| 					Statement.RETURN_GENERATED_KEYS); | ||||
| @@ -957,13 +971,12 @@ public class DataAccess { | ||||
| 							// uniqueSQLUUID = generatedKeys.getObject(1, UUID.class); | ||||
| 							/* final Object obj = generatedKeys.getObject(1); final BigInteger bigint = (BigInteger) generatedKeys.getObject(1); uniqueSQLUUID = UuidUtils.asUuid(bigint); final UUID | ||||
| 							 * generatedUUID = (UUID) generatedKeys.getObject(1); System.out.println("UUID généré: " + generatedUUID); */ | ||||
| 							final Object obj = generatedKeys.getObject(1); | ||||
| 							//final Object obj = generatedKeys.getObject(1); | ||||
| 							final byte[] tmpid = generatedKeys.getBytes(1); | ||||
| 							uniqueSQLUUID = UuidUtils.asUuid(tmpid); | ||||
| 						} else { | ||||
| 							uniqueSQLID = generatedKeys.getLong(1); | ||||
| 						} | ||||
|  | ||||
| 					} else { | ||||
| 						throw new SQLException("Creating node failed, no ID obtained (1)."); | ||||
| 					} | ||||
| @@ -973,6 +986,7 @@ public class DataAccess { | ||||
| 					throw new SQLException("Creating node failed, no ID obtained (2)."); | ||||
| 				} | ||||
| 			} | ||||
| 			ps.close(); | ||||
| 			if (primaryKeyField != null) { | ||||
| 				if (primaryKeyField.getType() == Long.class) { | ||||
| 					primaryKeyField.set(data, uniqueSQLID); | ||||
| @@ -1016,7 +1030,7 @@ public class DataAccess { | ||||
| 	} | ||||
|  | ||||
| 	public static <ID_TYPE> QueryCondition getTableIdCondition(final Class<?> clazz, final ID_TYPE idKey) | ||||
| 			throws Exception { | ||||
| 			throws DataAccessException { | ||||
| 		// Find the ID field type .... | ||||
| 		final Field idField = AnnotationTools.getIdField(clazz); | ||||
| 		if (idField == null) { | ||||
| @@ -1103,10 +1117,14 @@ public class DataAccess { | ||||
| 		return updateWhere(data, options); | ||||
| 	} | ||||
|  | ||||
| 	public static <T> int updateWhere(final T data, final QueryOptions options) throws Exception { | ||||
| 	@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING") | ||||
| 	public static <T> int updateWhere(final T data, QueryOptions options) throws Exception { | ||||
| 		final Class<?> clazz = data.getClass(); | ||||
| 		if (options == null) { | ||||
| 			options = new QueryOptions(); | ||||
| 		} | ||||
| 		final Condition condition = conditionFusionOrEmpty(options, true); | ||||
| 		final List<FilterValue> filters = options.get(FilterValue.class); | ||||
| 		final List<FilterValue> filters = options != null ? options.get(FilterValue.class) : new ArrayList<>(); | ||||
| 		if (filters.size() != 1) { | ||||
| 			throw new DataAccessException("request a gets without/or with more 1 filter of values"); | ||||
| 		} | ||||
| @@ -1115,7 +1133,7 @@ public class DataAccess { | ||||
| 		if (options != null) { | ||||
| 			final List<CheckFunction> checks = options.get(CheckFunction.class); | ||||
| 			for (final CheckFunction check : checks) { | ||||
| 				check.getChecker().check("", data, filter.getValues()); | ||||
| 				check.getChecker().check("", data, filter.getValues(), options); | ||||
| 			} | ||||
| 		} | ||||
| 		final List<LazyGetter> asyncActions = new ArrayList<>(); | ||||
| @@ -1181,8 +1199,8 @@ public class DataAccess { | ||||
| 			if (!firstField) { | ||||
| 				LOGGER.debug("generate update query: '{}'", query.toString()); | ||||
| 				// prepare the request: | ||||
| 				final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), | ||||
| 						Statement.RETURN_GENERATED_KEYS); | ||||
| 				try (final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), | ||||
| 						Statement.RETURN_GENERATED_KEYS)) { | ||||
| 					final CountInOut iii = new CountInOut(1); | ||||
| 					for (final Field field : clazz.getFields()) { | ||||
| 						// static field is only for internal global declaration ==> remove it .. | ||||
| @@ -1213,7 +1231,9 @@ public class DataAccess { | ||||
| 						} | ||||
| 					} | ||||
| 					condition.injectQuery(ps, iii); | ||||
| 				return ps.executeUpdate(); | ||||
| 					final int out = ps.executeUpdate(); | ||||
| 					return out; | ||||
| 				} | ||||
| 			} | ||||
| 		} catch (final SQLException ex) { | ||||
| 			ex.printStackTrace(); | ||||
| @@ -1224,7 +1244,8 @@ public class DataAccess { | ||||
| 		return 0; | ||||
| 	} | ||||
|  | ||||
| 	static void addElement(final PreparedStatement ps, final Object value, final CountInOut iii) throws Exception { | ||||
| 	public static void addElement(final PreparedStatement ps, final Object value, final CountInOut iii) | ||||
| 			throws Exception { | ||||
| 		if (value instanceof final UUID tmp) { | ||||
| 			final byte[] dataByte = UuidUtils.asBytes(tmp); | ||||
| 			ps.setBytes(iii.value, dataByte); | ||||
| @@ -1276,20 +1297,21 @@ public class DataAccess { | ||||
| 			throws SQLException, IOException { | ||||
| 		final QueryOptions options = new QueryOptions(option); | ||||
| 		final DBEntry entry = DBInterfaceOption.getAutoEntry(options); | ||||
| 		final Statement stmt = entry.connection.createStatement(); | ||||
| 		try (final Statement stmt = entry.connection.createStatement()) { | ||||
| 			return stmt.executeUpdate(query); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	public static boolean executeQuery(final String query, final QueryOption... option) | ||||
| 			throws SQLException, IOException { | ||||
| 		final QueryOptions options = new QueryOptions(option); | ||||
| 		final DBEntry entry = DBInterfaceOption.getAutoEntry(options); | ||||
| 		final Statement stmt = entry.connection.createStatement(); | ||||
| 		try (final Statement stmt = entry.connection.createStatement()) { | ||||
| 			return stmt.execute(query); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	public static <T> T getWhere(final Class<T> clazz, final QueryOption... option) throws Exception { | ||||
| 		final QueryOptions options = new QueryOptions(option); | ||||
| 	public static <T> T getWhere(final Class<T> clazz, final QueryOptions options) throws Exception { | ||||
| 		options.add(new Limit(1)); | ||||
| 		final List<T> values = getsWhere(clazz, options); | ||||
| 		if (values.size() == 0) { | ||||
| @@ -1298,6 +1320,11 @@ public class DataAccess { | ||||
| 		return values.get(0); | ||||
| 	} | ||||
|  | ||||
| 	public static <T> T getWhere(final Class<T> clazz, final QueryOption... option) throws Exception { | ||||
| 		final QueryOptions options = new QueryOptions(option); | ||||
| 		return getWhere(clazz, options); | ||||
| 	} | ||||
|  | ||||
| 	public static void generateSelectField(// | ||||
| 			final StringBuilder querySelect, // | ||||
| 			final StringBuilder query, // | ||||
| @@ -1348,6 +1375,9 @@ public class DataAccess { | ||||
|  | ||||
| 	public static Condition conditionFusionOrEmpty(final QueryOptions options, final boolean throwIfEmpty) | ||||
| 			throws DataAccessException { | ||||
| 		if (options == null) { | ||||
| 			return new Condition(); | ||||
| 		} | ||||
| 		final List<Condition> conditions = options.get(Condition.class); | ||||
| 		if (conditions.size() == 0) { | ||||
| 			if (throwIfEmpty) { | ||||
| @@ -1370,14 +1400,13 @@ public class DataAccess { | ||||
| 	} | ||||
|  | ||||
| 	@SuppressWarnings("unchecked") | ||||
| 	public static <T> List<T> getsWhere(final Class<T> clazz, final QueryOptions options) throws Exception { | ||||
| 	public static <T> List<T> getsWhere(final Class<T> clazz, final QueryOptions options) | ||||
| 			throws DataAccessException, IOException { | ||||
| 		final Condition condition = conditionFusionOrEmpty(options, false); | ||||
| 		final List<LazyGetter> lazyCall = new ArrayList<>(); | ||||
| 		final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz); | ||||
| 		final DBEntry entry = DBInterfaceOption.getAutoEntry(options); | ||||
| 		final List<T> outs = new ArrayList<>(); | ||||
| 		// real add in the BDD: | ||||
| 		try { | ||||
| 		try (final DBEntry entry = DBInterfaceOption.getAutoEntry(options)) { | ||||
| 			final CountInOut count = new CountInOut(); | ||||
| 			final StringBuilder querySelect = new StringBuilder(); | ||||
| 			StringBuilder query = new StringBuilder(); | ||||
| @@ -1405,10 +1434,10 @@ public class DataAccess { | ||||
| 			} else if (limits.size() > 1) { | ||||
| 				throw new DataAccessException("Request with multiple 'limit'..."); | ||||
| 			} | ||||
| 			LOGGER.warn("generate the query: '{}'", query.toString()); | ||||
| 			LOGGER.debug("generate the query: '{}'", query.toString()); | ||||
| 			// prepare the request: | ||||
| 			final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), | ||||
| 					Statement.RETURN_GENERATED_KEYS); | ||||
| 			try (final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), | ||||
| 					Statement.RETURN_GENERATED_KEYS)) { | ||||
| 				final CountInOut iii = new CountInOut(1); | ||||
| 				condition.injectQuery(ps, iii); | ||||
| 				if (limits.size() == 1) { | ||||
| @@ -1427,13 +1456,13 @@ public class DataAccess { | ||||
| 				for (final LazyGetter elem : lazyCall) { | ||||
| 					elem.doRequest(); | ||||
| 				} | ||||
| 			} | ||||
| 		} catch (final SQLException ex) { | ||||
| 			ex.printStackTrace(); | ||||
| 			throw ex; | ||||
| 			throw new DataAccessException("Catch a SQL Exception: " + ex.getMessage()); | ||||
| 		} catch (final Exception ex) { | ||||
| 			ex.printStackTrace(); | ||||
| 		} finally { | ||||
| 			entry.close(); | ||||
| 			throw new DataAccessException("Catch an Exception: " + ex.getMessage()); | ||||
| 		} | ||||
| 		return outs; | ||||
| 	} | ||||
| @@ -1479,12 +1508,19 @@ public class DataAccess { | ||||
| 		return data; | ||||
| 	} | ||||
|  | ||||
| 	public static <ID_TYPE> long count(final Class<?> clazz, final ID_TYPE id) throws Exception { | ||||
| 		return DataAccess.countWhere(clazz, new Condition(getTableIdCondition(clazz, id))); | ||||
| 	public static <ID_TYPE> long count(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) | ||||
| 			throws Exception { | ||||
| 		final QueryOptions options = new QueryOptions(option); | ||||
| 		options.add(new Condition(getTableIdCondition(clazz, id))); | ||||
| 		return DataAccess.countWhere(clazz, options); | ||||
| 	} | ||||
|  | ||||
| 	public static long countWhere(final Class<?> clazz, final QueryOption... option) throws Exception { | ||||
| 		final QueryOptions options = new QueryOptions(option); | ||||
| 		return countWhere(clazz, options); | ||||
| 	} | ||||
|  | ||||
| 	public static long countWhere(final Class<?> clazz, final QueryOptions options) throws Exception { | ||||
| 		final Condition condition = conditionFusionOrEmpty(options, false); | ||||
| 		final String deletedFieldName = AnnotationTools.getDeletedFieldName(clazz); | ||||
| 		DBEntry entry = DBInterfaceOption.getAutoEntry(options); | ||||
| @@ -1503,7 +1539,7 @@ public class DataAccess { | ||||
| 			} else if (limits.size() > 1) { | ||||
| 				throw new DataAccessException("Request with multiple 'limit'..."); | ||||
| 			} | ||||
| 			LOGGER.warn("generate the query: '{}'", query.toString()); | ||||
| 			LOGGER.debug("generate the query: '{}'", query.toString()); | ||||
| 			// prepare the request: | ||||
| 			final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), | ||||
| 					Statement.RETURN_GENERATED_KEYS); | ||||
| @@ -1544,10 +1580,6 @@ public class DataAccess { | ||||
| 		return getsWhere(clazz, option); | ||||
| 	} | ||||
|  | ||||
| 	public static <ID_TYPE> int delete(final Class<?> clazz, final ID_TYPE id) throws Exception { | ||||
| 		return delete(clazz, id, null); | ||||
| 	} | ||||
|  | ||||
| 	/** Delete items with the specific Id (cf @Id) and some options. If the Entity is manage as a softDeleted model, then it is flag as removed (if not already done before). | ||||
| 	 * @param <ID_TYPE> Type of the reference @Id | ||||
| 	 * @param clazz Data model that might remove element | ||||
| @@ -1644,18 +1676,18 @@ public class DataAccess { | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	public static <ID_TYPE> int unsetDelete(final Class<?> clazz, final ID_TYPE id) throws Exception { | ||||
| 	public static <ID_TYPE> int unsetDelete(final Class<?> clazz, final ID_TYPE id) throws DataAccessException { | ||||
| 		return unsetDeleteWhere(clazz, new Condition(getTableIdCondition(clazz, id))); | ||||
| 	} | ||||
|  | ||||
| 	public static <ID_TYPE> int unsetDelete(final Class<?> clazz, final ID_TYPE id, final QueryOption... option) | ||||
| 			throws Exception { | ||||
| 			throws DataAccessException { | ||||
| 		final QueryOptions options = new QueryOptions(option); | ||||
| 		options.add(new Condition(getTableIdCondition(clazz, id))); | ||||
| 		return unsetDeleteWhere(clazz, options.getAllArray()); | ||||
| 	} | ||||
|  | ||||
| 	public static int unsetDeleteWhere(final Class<?> clazz, final QueryOption... option) throws Exception { | ||||
| 	public static int unsetDeleteWhere(final Class<?> clazz, final QueryOption... option) throws DataAccessException { | ||||
| 		final QueryOptions options = new QueryOptions(option); | ||||
| 		final Condition condition = conditionFusionOrEmpty(options, true); | ||||
| 		final String tableName = AnnotationTools.getTableName(clazz, options); | ||||
| @@ -1663,7 +1695,12 @@ public class DataAccess { | ||||
| 		if (deletedFieldName == null) { | ||||
| 			throw new DataAccessException("The class " + clazz.getCanonicalName() + " has no deleted field"); | ||||
| 		} | ||||
| 		final DBEntry entry = DBInterfaceOption.getAutoEntry(options); | ||||
| 		DBEntry entry; | ||||
| 		try { | ||||
| 			entry = DBInterfaceOption.getAutoEntry(options); | ||||
| 		} catch (final IOException ex) { | ||||
| 			throw new DataAccessException("Fail to connect the DB: " + ex.getMessage()); | ||||
| 		} | ||||
| 		final StringBuilder query = new StringBuilder(); | ||||
| 		query.append("UPDATE `"); | ||||
| 		query.append(tableName); | ||||
| @@ -1673,13 +1710,14 @@ public class DataAccess { | ||||
| 		// need to disable the deleted false because the model must be unselected to be updated. | ||||
| 		options.add(QueryOptions.ACCESS_DELETED_ITEMS); | ||||
| 		condition.whereAppendQuery(query, tableName, options, deletedFieldName); | ||||
| 		try { | ||||
| 			final PreparedStatement ps = entry.connection.prepareStatement(query.toString()); | ||||
| 		try (final PreparedStatement ps = entry.connection.prepareStatement(query.toString())) { | ||||
| 			final CountInOut iii = new CountInOut(1); | ||||
| 			condition.injectQuery(ps, iii); | ||||
| 			return ps.executeUpdate(); | ||||
| 		} finally { | ||||
| 			entry.close(); | ||||
| 		} catch (final SQLException ex) { | ||||
| 			throw new DataAccessException("Catch SQL error:" + ex.getMessage()); | ||||
| 		} catch (final Exception ex) { | ||||
| 			throw new DataAccessException("Fail to excute the SQL query:" + ex.getMessage()); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| @@ -1796,7 +1834,7 @@ public class DataAccess { | ||||
| 			} else if (limits.size() > 1) { | ||||
| 				throw new DataAccessException("Request with multiple 'limit'..."); | ||||
| 			} | ||||
| 			LOGGER.warn("generate the query: '{}'", query.toString()); | ||||
| 			LOGGER.debug("generate the query: '{}'", query.toString()); | ||||
| 			// prepare the request: | ||||
| 			final PreparedStatement ps = entry.connection.prepareStatement(query.toString(), | ||||
| 					Statement.RETURN_GENERATED_KEYS); | ||||
|   | ||||
| @@ -20,6 +20,10 @@ import org.kar.archidata.dataAccess.exportTools.TableQuery; | ||||
| import org.kar.archidata.dataAccess.exportTools.TableQueryTypes; | ||||
| import org.kar.archidata.dataAccess.options.Condition; | ||||
| import org.kar.archidata.dataAccess.options.DBInterfaceOption; | ||||
| import org.kar.archidata.dataAccess.options.GroupBy; | ||||
| import org.kar.archidata.dataAccess.options.Limit; | ||||
| import org.kar.archidata.dataAccess.options.OrderBy; | ||||
| import org.kar.archidata.dataAccess.options.QueryOption; | ||||
| import org.kar.archidata.db.DBEntry; | ||||
| import org.kar.archidata.exception.DataAccessException; | ||||
| import org.kar.archidata.tools.DateTools; | ||||
|   | ||||
| @@ -1,687 +0,0 @@ | ||||
| package org.kar.archidata.dataAccess; | ||||
|  | ||||
| import java.io.BufferedReader; | ||||
| 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.HashMap; | ||||
| import java.util.HashSet; | ||||
| import java.util.List; | ||||
| 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.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; | ||||
|  | ||||
| public class DataFactoryTsApi { | ||||
| 	static final Logger LOGGER = LoggerFactory.getLogger(DataFactoryTsApi.class); | ||||
|  | ||||
| 	record APIModel( | ||||
| 			String data, | ||||
| 			String className) {} | ||||
|  | ||||
| 	/** Request the generation of the TypeScript file for the "Zod" export model | ||||
| 	 * @param classs List of class used in the model | ||||
| 	 * @throws Exception */ | ||||
| 	public static List<String> createApi( | ||||
| 			final List<Class<?>> classs, | ||||
| 			final GeneratedTypes previous, | ||||
| 			final String pathPackage) throws Exception { | ||||
| 		final List<String> apis = new ArrayList<>(); | ||||
| 		final String globalheader = """ | ||||
| 				/** | ||||
| 				 * API of the server (auto-generated code) | ||||
| 				 */ | ||||
| 				import { | ||||
| 				  HTTPMimeType, | ||||
| 				  HTTPRequestModel, | ||||
| 				  ModelResponseHttp, | ||||
| 				  RESTCallbacks, | ||||
| 				  RESTConfig, | ||||
| 				  RESTRequestJson, | ||||
| 				  RESTRequestJsonArray, | ||||
| 				  RESTRequestVoid | ||||
| 				} from "./rest-tools" | ||||
| 				import {"""; | ||||
|  | ||||
| 		for (final Class<?> clazz : classs) { | ||||
| 			final Set<Class<?>> includeModel = new HashSet<>(); | ||||
| 			final Set<Class<?>> includeCheckerModel = new HashSet<>(); | ||||
| 			final APIModel api = createSingleApi(clazz, includeModel, includeCheckerModel, previous); | ||||
| 			final StringBuilder generatedData = new StringBuilder(); | ||||
| 			generatedData.append(globalheader); | ||||
| 			for (final Class<?> elem : includeModel) { | ||||
| 				if (elem == null) { | ||||
| 					continue; | ||||
| 				} | ||||
| 				final ClassElement classElement = DataFactoryZod.createTable(elem, previous); | ||||
| 				if (classElement.nativeType) { | ||||
| 					continue; | ||||
| 				} | ||||
| 				generatedData.append("\n  "); | ||||
| 				generatedData.append(classElement.tsTypeName); | ||||
| 				generatedData.append(","); | ||||
| 			} | ||||
| 			for (final Class<?> elem : includeCheckerModel) { | ||||
| 				if (elem == null) { | ||||
| 					continue; | ||||
| 				} | ||||
| 				final ClassElement classElement = DataFactoryZod.createTable(elem, previous); | ||||
| 				if (classElement.nativeType) { | ||||
| 					continue; | ||||
| 				} | ||||
| 				generatedData.append("\n  "); | ||||
| 				generatedData.append(classElement.tsCheckType); | ||||
| 				generatedData.append(","); | ||||
| 			} | ||||
| 			generatedData.append("\n} from \"./model\"\n"); | ||||
| 			generatedData.append(api.data()); | ||||
|  | ||||
| 			String fileName = api.className(); | ||||
| 			fileName = fileName.replaceAll("([A-Z])", "-$1").toLowerCase(); | ||||
| 			fileName = fileName.replaceAll("^\\-*", ""); | ||||
| 			apis.add(fileName); | ||||
| 			final FileWriter myWriter = new FileWriter(pathPackage + File.separator + fileName + ".ts"); | ||||
| 			myWriter.write(generatedData.toString()); | ||||
| 			myWriter.close(); | ||||
| 		} | ||||
| 		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; | ||||
| 	} | ||||
|  | ||||
| 	public static APIModel createSingleApi( | ||||
| 			final Class<?> clazz, | ||||
| 			final Set<Class<?>> includeModel, | ||||
| 			final Set<Class<?>> includeCheckerModel, | ||||
| 			final GeneratedTypes previous) throws Exception { | ||||
| 		final StringBuilder builder = new StringBuilder(); | ||||
| 		// the basic path has no specific elements... | ||||
| 		final String basicPath = apiAnnotationGetPath(clazz); | ||||
| 		final String classSimpleName = clazz.getSimpleName(); | ||||
|  | ||||
| 		builder.append("export namespace "); | ||||
| 		builder.append(classSimpleName); | ||||
| 		builder.append(" {\n"); | ||||
| 		LOGGER.info("Parse Class for path: {} => {}", classSimpleName, basicPath); | ||||
| 		for (final Method method : clazz.getDeclaredMethods()) { | ||||
| 			final String methodName = method.getName(); | ||||
| 			final String methodPath = apiAnnotationGetPath(method); | ||||
| 			final String methodType = 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); | ||||
| 			LOGGER.trace("    [{}] {} => {}/{}", methodType, methodName, basicPath, methodPath); | ||||
| 			if (methodDescription != null) { | ||||
| 				LOGGER.trace("         description: {}", methodDescription); | ||||
| 			} | ||||
| 			final boolean needGenerateProgress = apiAnnotationTypeScriptProgress(method); | ||||
| 			Class<?>[] returnTypeModel = apiAnnotationGetAsyncType(method); | ||||
| 			boolean isUnmanagedReturnType = false; | ||||
| 			boolean returnModelIsArray = false; | ||||
| 			List<ClassElement> tmpReturn; | ||||
| 			if (returnTypeModel == null) { | ||||
| 				Class<?> returnTypeModelRaw = method.getReturnType(); | ||||
| 				LOGGER.info("Get type: {}", returnTypeModelRaw); | ||||
| 				if (returnTypeModelRaw == Response.class) { | ||||
| 					LOGGER.info("Get type: {}", returnTypeModelRaw); | ||||
| 				} | ||||
| 				if (returnTypeModelRaw == Response.class || returnTypeModelRaw == void.class | ||||
| 						|| returnTypeModelRaw == Void.class) { | ||||
| 					if (returnTypeModelRaw == Response.class) { | ||||
| 						isUnmanagedReturnType = true; | ||||
| 					} | ||||
| 					returnTypeModel = new Class<?>[] { Void.class }; | ||||
| 					tmpReturn = new ArrayList<>(); | ||||
| 					produces = null; | ||||
| 				} else if (returnTypeModelRaw == Map.class) { | ||||
| 					LOGGER.warn("Not manage the Map Model ... set any"); | ||||
| 					returnTypeModel = new Class<?>[] { Map.class }; | ||||
| 					tmpReturn = DataFactoryZod.createTables(returnTypeModel, previous); | ||||
| 				} else if (returnTypeModelRaw == List.class) { | ||||
| 					final ParameterizedType listType = (ParameterizedType) method.getGenericReturnType(); | ||||
| 					returnTypeModelRaw = (Class<?>) listType.getActualTypeArguments()[0]; | ||||
| 					returnModelIsArray = true; | ||||
| 					returnTypeModel = new Class<?>[] { returnTypeModelRaw }; | ||||
| 					tmpReturn = DataFactoryZod.createTables(returnTypeModel, previous); | ||||
| 				} else { | ||||
| 					returnTypeModel = new Class<?>[] { returnTypeModelRaw }; | ||||
| 					tmpReturn = DataFactoryZod.createTables(returnTypeModel, previous); | ||||
| 				} | ||||
| 			} else if (returnTypeModel.length >= 0 && (returnTypeModel[0] == Response.class | ||||
| 					|| returnTypeModel[0] == Void.class || returnTypeModel[0] == void.class)) { | ||||
| 				if (returnTypeModel[0] == Response.class) { | ||||
| 					isUnmanagedReturnType = true; | ||||
| 				} | ||||
| 				returnTypeModel = new Class<?>[] { Void.class }; | ||||
| 				tmpReturn = new ArrayList<>(); | ||||
| 				produces = null; | ||||
| 			} else if (returnTypeModel.length > 0 && returnTypeModel[0] == Map.class) { | ||||
| 				LOGGER.warn("Not manage the Map Model ..."); | ||||
| 				returnTypeModel = new Class<?>[] { Map.class }; | ||||
| 				tmpReturn = DataFactoryZod.createTables(returnTypeModel, previous); | ||||
| 			} else { | ||||
| 				tmpReturn = DataFactoryZod.createTables(returnTypeModel, previous); | ||||
| 			} | ||||
| 			for (final ClassElement elem : tmpReturn) { | ||||
| 				includeModel.add(elem.model[0]); | ||||
| 				includeCheckerModel.add(elem.model[0]); | ||||
| 			} | ||||
| 			LOGGER.trace("         return: {}", tmpReturn.size()); | ||||
| 			for (final ClassElement elem : tmpReturn) { | ||||
| 				LOGGER.trace("             - {}", elem.tsTypeName); | ||||
| 			} | ||||
| 			final Map<String, String> queryParams = new HashMap<>(); | ||||
| 			final Map<String, String> pathParams = new HashMap<>(); | ||||
| 			final Map<String, String> formDataParams = new HashMap<>(); | ||||
| 			final List<String> emptyElement = new ArrayList<>(); | ||||
| 			// LOGGER.info(" Parameters:"); | ||||
| 			for (final Parameter parameter : method.getParameters()) { | ||||
| 				// Security context are internal parameter (not available from API) | ||||
| 				if (apiAnnotationIsContext(parameter)) { | ||||
| 					continue; | ||||
| 				} | ||||
| 				final Class<?> parameterType = parameter.getType(); | ||||
| 				String parameterTypeString; | ||||
| 				final Class<?>[] asyncType = apiAnnotationGetAsyncType(parameter); | ||||
| 				if (parameterType == List.class) { | ||||
| 					if (asyncType == null) { | ||||
| 						LOGGER.warn("Detect List param ==> not managed type ==> any[] !!!"); | ||||
| 						parameterTypeString = "any[]"; | ||||
| 					} else { | ||||
| 						final List<ClassElement> tmp = DataFactoryZod.createTables(asyncType, previous); | ||||
| 						for (final ClassElement elem : tmp) { | ||||
| 							includeModel.add(elem.model[0]); | ||||
| 						} | ||||
| 						parameterTypeString = convertInTypeScriptType(tmp, true); | ||||
| 					} | ||||
| 				} else if (asyncType == null) { | ||||
| 					final ClassElement tmp = DataFactoryZod.createTable(parameterType, previous); | ||||
| 					includeModel.add(tmp.model[0]); | ||||
| 					parameterTypeString = tmp.tsTypeName; | ||||
| 				} else { | ||||
| 					final List<ClassElement> tmp = DataFactoryZod.createTables(asyncType, previous); | ||||
| 					for (final ClassElement elem : tmp) { | ||||
| 						includeModel.add(elem.model[0]); | ||||
| 					} | ||||
| 					parameterTypeString = convertInTypeScriptType(tmp, true); | ||||
| 				} | ||||
| 				final String pathParam = apiAnnotationGetPathParam(parameter); | ||||
| 				final String queryParam = apiAnnotationGetQueryParam(parameter); | ||||
| 				final String formDataParam = apiAnnotationGetFormDataParam(parameter); | ||||
| 				if (queryParam != null) { | ||||
| 					queryParams.put(queryParam, parameterTypeString); | ||||
| 				} else if (pathParam != null) { | ||||
| 					pathParams.put(pathParam, parameterTypeString); | ||||
| 				} else if (formDataParam != null) { | ||||
| 					formDataParams.put(formDataParam, parameterTypeString); | ||||
| 				} else if (asyncType != null) { | ||||
| 					final List<ClassElement> tmp = DataFactoryZod.createTables(asyncType, previous); | ||||
| 					parameterTypeString = ""; | ||||
| 					for (final ClassElement elem : tmp) { | ||||
| 						includeModel.add(elem.model[0]); | ||||
| 						if (parameterTypeString.length() != 0) { | ||||
| 							parameterTypeString += " | "; | ||||
| 						} | ||||
| 						parameterTypeString += elem.tsTypeName; | ||||
| 					} | ||||
| 					emptyElement.add(parameterTypeString); | ||||
| 				} else if (parameterType == List.class) { | ||||
| 					parameterTypeString = "any[]"; | ||||
| 					final Class<?> plop = parameterType.arrayType(); | ||||
| 					LOGGER.info("ArrayType = {}", plop); | ||||
| 					emptyElement.add(parameterTypeString); | ||||
| 				} else { | ||||
| 					final ClassElement tmp = DataFactoryZod.createTable(parameterType, previous); | ||||
| 					includeModel.add(tmp.model[0]); | ||||
| 					emptyElement.add(tmp.tsTypeName); | ||||
| 				} | ||||
| 			} | ||||
| 			if (!queryParams.isEmpty()) { | ||||
| 				LOGGER.trace("         Query parameter:"); | ||||
| 				for (final Entry<String, String> queryEntry : queryParams.entrySet()) { | ||||
| 					LOGGER.trace("             - {}: {}", queryEntry.getKey(), queryEntry.getValue()); | ||||
| 				} | ||||
| 			} | ||||
| 			if (!pathParams.isEmpty()) { | ||||
| 				LOGGER.trace("         Path parameter:"); | ||||
| 				for (final Entry<String, String> pathEntry : pathParams.entrySet()) { | ||||
| 					LOGGER.trace("             - {}: {}", pathEntry.getKey(), pathEntry.getValue()); | ||||
| 				} | ||||
| 			} | ||||
| 			if (emptyElement.size() > 1) { | ||||
| 				LOGGER.error("         Fail to parse: Too much element in the model for the data ..."); | ||||
| 				continue; | ||||
| 			} else if (emptyElement.size() == 1 && formDataParams.size() != 0) { | ||||
| 				LOGGER.error("         Fail to parse: Incompatible form data & direct data ..."); | ||||
| 				continue; | ||||
| 			} else if (emptyElement.size() == 1) { | ||||
| 				LOGGER.trace("         data type: {}", emptyElement.get(0)); | ||||
| 			} | ||||
| 			// ALL is good can generate the Elements | ||||
|  | ||||
| 			if (methodDescription != null) { | ||||
| 				builder.append("\n\t/**\n\t * "); | ||||
| 				builder.append(methodDescription); | ||||
| 				builder.append("\n\t */"); | ||||
| 			} | ||||
| 			if (isUnmanagedReturnType) { | ||||
| 				builder.append( | ||||
| 						"\n\t// TODO: unmanaged \"Response\" type: please specify @AsyncType or considered as 'void'."); | ||||
| 			} | ||||
| 			builder.append("\n\texport function "); | ||||
| 			builder.append(methodName); | ||||
| 			builder.append("({\n\t\t\trestConfig,"); | ||||
| 			if (!queryParams.isEmpty()) { | ||||
| 				builder.append("\n\t\t\tqueries,"); | ||||
| 			} | ||||
| 			if (!pathParams.isEmpty()) { | ||||
| 				builder.append("\n\t\t\tparams,"); | ||||
| 			} | ||||
| 			if (produces != null && produces.size() > 1) { | ||||
| 				builder.append("\n\t\t\tproduce,"); | ||||
| 			} | ||||
| 			if (emptyElement.size() == 1 || formDataParams.size() != 0) { | ||||
| 				builder.append("\n\t\t\tdata,"); | ||||
| 			} | ||||
| 			if (needGenerateProgress) { | ||||
| 				builder.append("\n\t\t\tcallback,"); | ||||
| 			} | ||||
| 			builder.append("\n\t\t}: {"); | ||||
| 			builder.append("\n\t\trestConfig: RESTConfig,"); | ||||
| 			if (!queryParams.isEmpty()) { | ||||
| 				builder.append("\n\t\tqueries: {"); | ||||
| 				for (final Entry<String, String> queryEntry : queryParams.entrySet()) { | ||||
| 					builder.append("\n\t\t\t"); | ||||
| 					builder.append(queryEntry.getKey()); | ||||
| 					builder.append("?: "); | ||||
| 					builder.append(queryEntry.getValue()); | ||||
| 					builder.append(","); | ||||
| 				} | ||||
| 				builder.append("\n\t\t},"); | ||||
| 			} | ||||
| 			if (!pathParams.isEmpty()) { | ||||
| 				builder.append("\n\t\tparams: {"); | ||||
| 				for (final Entry<String, String> pathEntry : pathParams.entrySet()) { | ||||
| 					builder.append("\n\t\t\t"); | ||||
| 					builder.append(pathEntry.getKey()); | ||||
| 					builder.append(": "); | ||||
| 					builder.append(pathEntry.getValue()); | ||||
| 					builder.append(","); | ||||
| 				} | ||||
| 				builder.append("\n\t\t},"); | ||||
| 			} | ||||
| 			if (emptyElement.size() == 1) { | ||||
| 				builder.append("\n\t\tdata: "); | ||||
| 				builder.append(emptyElement.get(0)); | ||||
| 				builder.append(","); | ||||
| 			} else if (formDataParams.size() != 0) { | ||||
| 				builder.append("\n\t\tdata: {"); | ||||
| 				for (final Entry<String, String> pathEntry : formDataParams.entrySet()) { | ||||
| 					builder.append("\n\t\t\t"); | ||||
| 					builder.append(pathEntry.getKey()); | ||||
| 					builder.append(": "); | ||||
| 					builder.append(pathEntry.getValue()); | ||||
| 					builder.append(","); | ||||
| 				} | ||||
| 				builder.append("\n\t\t},"); | ||||
| 			} | ||||
| 			if (produces != null && produces.size() > 1) { | ||||
| 				builder.append("\n\t\tproduce: "); | ||||
| 				String isFist = null; | ||||
| 				for (final String elem : produces) { | ||||
| 					String lastElement = null; | ||||
|  | ||||
| 					if (MediaType.APPLICATION_JSON.equals(elem)) { | ||||
| 						lastElement = "HTTPMimeType.JSON"; | ||||
| 					} | ||||
| 					if (MediaType.MULTIPART_FORM_DATA.equals(elem)) { | ||||
| 						lastElement = "HTTPMimeType.MULTIPART"; | ||||
| 					} | ||||
| 					if (DataExport.CSV_TYPE.equals(elem)) { | ||||
| 						lastElement = "HTTPMimeType.CSV"; | ||||
| 					} | ||||
| 					if (lastElement != null) { | ||||
| 						if (isFist == null) { | ||||
| 							isFist = lastElement; | ||||
| 						} else { | ||||
| 							builder.append(" | "); | ||||
| 						} | ||||
| 						builder.append(lastElement); | ||||
| 					} else { | ||||
| 						LOGGER.error("Unmanaged model type: {}", elem); | ||||
| 					} | ||||
| 				} | ||||
| 				builder.append(","); | ||||
| 			} | ||||
| 			if (needGenerateProgress) { | ||||
| 				builder.append("\n\t\tcallback?: RESTCallbacks,"); | ||||
| 			} | ||||
| 			builder.append("\n\t}): Promise<"); | ||||
| 			if (tmpReturn.size() == 0 // | ||||
| 					|| tmpReturn.get(0).tsTypeName == null // | ||||
| 					|| tmpReturn.get(0).tsTypeName.equals("void")) { | ||||
| 				builder.append("void"); | ||||
| 			} else { | ||||
| 				builder.append(convertInTypeScriptType(tmpReturn, returnModelIsArray)); | ||||
| 			} | ||||
| 			builder.append("> {"); | ||||
| 			if (tmpReturn.size() == 0 // | ||||
| 					|| tmpReturn.get(0).tsTypeName == null // | ||||
| 					|| tmpReturn.get(0).tsTypeName.equals("void")) { | ||||
| 				builder.append("\n\t\treturn RESTRequestVoid({"); | ||||
| 			} else if (returnModelIsArray) { | ||||
| 				builder.append("\n\t\treturn RESTRequestJsonArray({"); | ||||
| 			} else { | ||||
| 				builder.append("\n\t\treturn RESTRequestJson({"); | ||||
| 			} | ||||
| 			builder.append("\n\t\t\trestModel: {"); | ||||
| 			builder.append("\n\t\t\t\tendPoint: \""); | ||||
| 			builder.append(basicPath); | ||||
| 			if (methodPath != null) { | ||||
| 				builder.append("/"); | ||||
| 				builder.append(methodPath); | ||||
| 			} | ||||
| 			builder.append("\","); | ||||
| 			builder.append("\n\t\t\t\trequestType: HTTPRequestModel."); | ||||
| 			builder.append(methodType); | ||||
| 			builder.append(","); | ||||
| 			if (consumes != null) { | ||||
| 				for (final String elem : consumes) { | ||||
| 					if (MediaType.APPLICATION_JSON.equals(elem)) { | ||||
| 						builder.append("\n\t\t\t\tcontentType: HTTPMimeType.JSON,"); | ||||
| 						break; | ||||
| 					} else if (MediaType.MULTIPART_FORM_DATA.equals(elem)) { | ||||
| 						builder.append("\n\t\t\t\tcontentType: HTTPMimeType.MULTIPART,"); | ||||
| 						break; | ||||
| 					} else if (MediaType.TEXT_PLAIN.equals(elem)) { | ||||
| 						builder.append("\n\t\t\t\tcontentType: HTTPMimeType.TEXT_PLAIN,"); | ||||
| 						break; | ||||
| 					} | ||||
| 				} | ||||
| 			} else if ("DELETE".equals(methodType)) { | ||||
| 				builder.append("\n\t\t\t\tcontentType: HTTPMimeType.TEXT_PLAIN,"); | ||||
| 			} | ||||
| 			if (produces != null) { | ||||
| 				if (produces.size() > 1) { | ||||
| 					builder.append("\n\t\t\t\taccept: produce,"); | ||||
| 				} else { | ||||
| 					for (final String elem : produces) { | ||||
| 						if (MediaType.APPLICATION_JSON.equals(elem)) { | ||||
| 							builder.append("\n\t\t\t\taccept: HTTPMimeType.JSON,"); | ||||
| 							break; | ||||
| 						} | ||||
| 					} | ||||
| 				} | ||||
| 			} | ||||
| 			builder.append("\n\t\t\t},"); | ||||
| 			builder.append("\n\t\t\trestConfig,"); | ||||
| 			if (!pathParams.isEmpty()) { | ||||
| 				builder.append("\n\t\t\tparams,"); | ||||
| 			} | ||||
| 			if (!queryParams.isEmpty()) { | ||||
| 				builder.append("\n\t\t\tqueries,"); | ||||
| 			} | ||||
| 			if (emptyElement.size() == 1) { | ||||
| 				builder.append("\n\t\t\tdata,"); | ||||
| 			} else if (formDataParams.size() != 0) { | ||||
| 				builder.append("\n\t\t\tdata,"); | ||||
| 			} | ||||
| 			if (needGenerateProgress) { | ||||
| 				builder.append("\n\t\t\tcallback,"); | ||||
| 			} | ||||
| 			builder.append("\n\t\t}"); | ||||
| 			if (tmpReturn.size() != 0 && tmpReturn.get(0).tsTypeName != null | ||||
| 					&& !tmpReturn.get(0).tsTypeName.equals("void")) { | ||||
| 				builder.append(", "); | ||||
| 				// TODO: correct this it is really bad ... | ||||
| 				builder.append(convertInTypeScriptCheckType(tmpReturn)); | ||||
| 			} | ||||
| 			builder.append(");"); | ||||
| 			builder.append("\n\t};"); | ||||
| 		} | ||||
| 		builder.append("\n}\n"); | ||||
| 		return new APIModel(builder.toString(), classSimpleName); | ||||
| 	} | ||||
|  | ||||
| 	public static void generatePackage( | ||||
| 			final List<Class<?>> classApi, | ||||
| 			final List<Class<?>> classModel, | ||||
| 			final String pathPackage) throws Exception { | ||||
| 		final GeneratedTypes previous = DataFactoryZod.createBasicType(); | ||||
| 		DataFactoryZod.createTable(RestErrorResponse.class, previous); | ||||
| 		final List<String> listApi = createApi(classApi, previous, pathPackage); | ||||
| 		final String packageApi = DataFactoryZod.createTables(new ArrayList<>(classModel), previous); | ||||
| 		FileWriter myWriter = new FileWriter(pathPackage + File.separator + "model.ts"); | ||||
| 		myWriter.write(packageApi.toString()); | ||||
| 		myWriter.close(); | ||||
|  | ||||
| 		final StringBuilder index = new StringBuilder(""" | ||||
| 				/** | ||||
| 				 * Global import of the package | ||||
| 				 */ | ||||
| 				export * from "./model"; | ||||
| 				"""); | ||||
| 		for (final String api : listApi) { | ||||
| 			index.append("export * from \"./").append(api).append("\";\n"); | ||||
| 		} | ||||
| 		myWriter = new FileWriter(pathPackage + File.separator + "index.ts"); | ||||
| 		myWriter.write(index.toString()); | ||||
| 		myWriter.close(); | ||||
| 		final InputStream ioStream = DataFactoryTsApi.class.getClassLoader().getResourceAsStream("rest-tools.ts"); | ||||
| 		if (ioStream == null) { | ||||
| 			throw new IllegalArgumentException("rest-tools.ts is not found"); | ||||
| 		} | ||||
| 		final BufferedReader buffer = new BufferedReader(new InputStreamReader(ioStream)); | ||||
| 		myWriter = new FileWriter(pathPackage + File.separator + "rest-tools.ts"); | ||||
| 		String line; | ||||
| 		while ((line = buffer.readLine()) != null) { | ||||
| 			myWriter.write(line); | ||||
| 			myWriter.write("\n"); | ||||
| 		} | ||||
| 		ioStream.close(); | ||||
| 		myWriter.close(); | ||||
| 		return; | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -1,485 +0,0 @@ | ||||
| package org.kar.archidata.dataAccess; | ||||
|  | ||||
| import java.io.File; | ||||
| import java.io.FileWriter; | ||||
| import java.io.IOException; | ||||
| import java.io.InputStream; | ||||
| import java.lang.reflect.Field; | ||||
| import java.lang.reflect.ParameterizedType; | ||||
| import java.sql.Timestamp; | ||||
| import java.time.Instant; | ||||
| import java.time.LocalDate; | ||||
| import java.time.LocalTime; | ||||
| import java.util.ArrayList; | ||||
| import java.util.Date; | ||||
| import java.util.List; | ||||
| import java.util.Map; | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.glassfish.jersey.media.multipart.FormDataContentDisposition; | ||||
| import org.kar.archidata.annotation.AnnotationTools; | ||||
| import org.kar.archidata.exception.DataAccessException; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import jakarta.ws.rs.core.Response; | ||||
|  | ||||
| public class DataFactoryZod { | ||||
| 	static final Logger LOGGER = LoggerFactory.getLogger(DataFactoryZod.class); | ||||
|  | ||||
| 	static public class ClassElement { | ||||
| 		public Class<?>[] model; | ||||
| 		public String zodName; | ||||
| 		public String tsTypeName; | ||||
| 		public String tsCheckType; | ||||
| 		public String declaration; | ||||
| 		public String comment = null; | ||||
| 		public boolean isEnum = false; | ||||
| 		public boolean nativeType; | ||||
|  | ||||
| 		public ClassElement(final Class<?> model[], final String zodName, final String tsTypeName, | ||||
| 				final String tsCheckType, final String declaration, final boolean nativeType) { | ||||
| 			this.model = model; | ||||
| 			this.zodName = zodName; | ||||
| 			this.tsTypeName = tsTypeName; | ||||
| 			this.tsCheckType = tsCheckType; | ||||
| 			this.declaration = declaration; | ||||
| 			this.nativeType = nativeType; | ||||
| 		} | ||||
|  | ||||
| 		public ClassElement(final Class<?> model) { | ||||
| 			this(new Class<?>[] { model }); | ||||
| 		} | ||||
|  | ||||
| 		public ClassElement(final Class<?> model[]) { | ||||
| 			this.model = model; | ||||
| 			this.zodName = "Zod" + model[0].getSimpleName(); | ||||
| 			this.tsTypeName = model[0].getSimpleName(); | ||||
| 			this.tsCheckType = "is" + model[0].getSimpleName(); | ||||
| 			this.declaration = null; | ||||
| 			this.nativeType = false; | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	public static class GeneratedTypes { | ||||
| 		final List<ClassElement> previousGeneration = new ArrayList<>(); | ||||
| 		final List<Class<?>> order = new ArrayList<>(); | ||||
|  | ||||
| 		public ClassElement find(final Class<?> clazz) { | ||||
| 			for (final ClassElement elem : this.previousGeneration) { | ||||
| 				for (final Class<?> elemClass : elem.model) { | ||||
| 					if (elemClass == clazz) { | ||||
| 						return elem; | ||||
| 					} | ||||
| 				} | ||||
| 			} | ||||
| 			return null; | ||||
| 		} | ||||
|  | ||||
| 		public void add(final ClassElement elem) { | ||||
| 			this.previousGeneration.add(elem); | ||||
| 		} | ||||
|  | ||||
| 		public void add(final ClassElement elem, final boolean addOrder) { | ||||
| 			this.previousGeneration.add(elem); | ||||
| 			if (addOrder) { | ||||
| 				this.order.add(elem.model[0]); | ||||
| 			} | ||||
| 		} | ||||
|  | ||||
| 		public void addOrder(final ClassElement elem) { | ||||
| 			this.order.add(elem.model[0]); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	public static ClassElement convertTypeZodEnum(final Class<?> clazz, final GeneratedTypes previous) | ||||
| 			throws Exception { | ||||
| 		final ClassElement element = new ClassElement(clazz); | ||||
| 		previous.add(element); | ||||
| 		final Object[] arr = clazz.getEnumConstants(); | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		if (System.getenv("ARCHIDATA_GENERATE_ZOD_ENUM") != null) { | ||||
| 			boolean first = true; | ||||
| 			out.append("zod.enum(["); | ||||
| 			for (final Object elem : arr) { | ||||
| 				if (!first) { | ||||
| 					out.append(",\n\t"); | ||||
| 				} else { | ||||
| 					out.append("\n\t"); | ||||
| 					first = false; | ||||
| 				} | ||||
| 				out.append("'"); | ||||
| 				out.append(elem.toString()); | ||||
| 				out.append("'"); | ||||
| 			} | ||||
| 			if (first) { | ||||
| 				out.append("]}"); | ||||
| 			} else { | ||||
| 				out.append("\n\t])"); | ||||
| 			} | ||||
| 		} else { | ||||
| 			element.isEnum = true; | ||||
| 			boolean first = true; | ||||
| 			out.append("{"); | ||||
| 			for (final Object elem : arr) { | ||||
| 				if (!first) { | ||||
| 					out.append(",\n\t"); | ||||
| 				} else { | ||||
| 					out.append("\n\t"); | ||||
| 					first = false; | ||||
| 				} | ||||
| 				out.append(elem.toString()); | ||||
| 				out.append(" = '"); | ||||
| 				out.append(elem.toString()); | ||||
| 				out.append("'"); | ||||
| 			} | ||||
| 			if (first) { | ||||
| 				out.append("}"); | ||||
| 			} else { | ||||
| 				out.append(",\n\t}"); | ||||
| 			} | ||||
| 		} | ||||
| 		element.declaration = out.toString(); | ||||
| 		previous.addOrder(element); | ||||
| 		return element; | ||||
| 	} | ||||
|  | ||||
| 	public static String convertTypeZod(final Class<?> type, final GeneratedTypes previous) throws Exception { | ||||
| 		final ClassElement previousType = previous.find(type); | ||||
| 		if (previousType != null) { | ||||
| 			return previousType.zodName; | ||||
| 		} | ||||
| 		if (type.isEnum()) { | ||||
| 			return convertTypeZodEnum(type, previous).zodName; | ||||
| 		} | ||||
| 		if (type == List.class) { | ||||
| 			throw new DataAccessException("Imcompatible type of element in object for: " + type.getCanonicalName() | ||||
| 					+ " Unmanaged List of List ... "); | ||||
| 		} | ||||
| 		final ClassElement elemCreated = createTable(type, previous); | ||||
| 		if (elemCreated != null) { | ||||
| 			return elemCreated.zodName; | ||||
| 		} | ||||
| 		throw new DataAccessException("Imcompatible type of element in object for: " + type.getCanonicalName()); | ||||
| 	} | ||||
|  | ||||
| 	public static String convertTypeZod(final Field field, final GeneratedTypes previous) throws Exception { | ||||
| 		final Class<?> type = field.getType(); | ||||
| 		final ClassElement previousType = previous.find(type); | ||||
| 		if (previousType != null) { | ||||
| 			return previousType.zodName; | ||||
| 		} | ||||
| 		if (type.isEnum()) { | ||||
| 			return convertTypeZodEnum(type, previous).zodName; | ||||
| 		} | ||||
| 		if (type == List.class) { | ||||
| 			final ParameterizedType listType = (ParameterizedType) field.getGenericType(); | ||||
| 			final Class<?> listClass = (Class<?>) listType.getActualTypeArguments()[0]; | ||||
| 			final String simpleSubType = convertTypeZod(listClass, previous); | ||||
| 			return "zod.array(" + simpleSubType + ")"; | ||||
| 		} | ||||
| 		final ClassElement elemCreated = createTable(type, previous); | ||||
| 		if (elemCreated != null) { | ||||
| 			return elemCreated.zodName; | ||||
| 		} | ||||
| 		throw new DataAccessException("Imcompatible type of element in object for: " + type.getCanonicalName()); | ||||
| 	} | ||||
|  | ||||
| 	public static String optionalTypeZod(final Class<?> type) throws Exception { | ||||
| 		if (type.isPrimitive()) { | ||||
| 			return ""; | ||||
| 		} | ||||
| 		return ".optional()"; | ||||
| 	} | ||||
|  | ||||
| 	public static void createTablesSpecificType( | ||||
| 			final Field elem, | ||||
| 			final int fieldId, | ||||
| 			final StringBuilder builder, | ||||
| 			final GeneratedTypes previous) throws Exception { | ||||
| 		final String name = elem.getName(); | ||||
| 		final Class<?> classModel = elem.getType(); | ||||
| 		final int limitSize = AnnotationTools.getLimitSize(elem); | ||||
|  | ||||
| 		final String comment = AnnotationTools.getComment(elem); | ||||
|  | ||||
| 		if (fieldId != 0) { | ||||
| 			builder.append(","); | ||||
| 		} | ||||
| 		if (comment != null) { | ||||
| 			builder.append("\n\t// "); | ||||
| 			builder.append(comment); | ||||
| 		} | ||||
| 		builder.append("\n\t"); | ||||
| 		builder.append(name); | ||||
| 		builder.append(": "); | ||||
| 		builder.append(convertTypeZod(elem, previous)); | ||||
| 		if (limitSize > 0 && classModel == String.class) { | ||||
| 			builder.append(".max("); | ||||
| 			builder.append(limitSize); | ||||
| 			builder.append(")"); | ||||
| 		} | ||||
| 		if (AnnotationTools.getSchemaReadOnly(elem)) { | ||||
| 			builder.append(".readonly()"); | ||||
| 		} | ||||
| 		builder.append(optionalTypeZod(classModel)); | ||||
| 	} | ||||
|  | ||||
| 	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 static GeneratedTypes createBasicType() throws Exception { | ||||
| 		final GeneratedTypes previous = new GeneratedTypes(); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Void.class, void.class }, "void", "void", null, null, true)); | ||||
| 		// Map is binded to any ==> can not determine this complex model for now | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Map.class }, "any", "any", null, null, true)); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { String.class }, "zod.string()", "string", null, "zod.string()", | ||||
| 				true)); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { InputStream.class, FormDataContentDisposition.class }, | ||||
| 				"z.instanceof(File)", "File", null, "z.instanceof(File)", true)); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Boolean.class, boolean.class }, "zod.boolean()", "boolean", null, | ||||
| 				"zod.boolean()", true)); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { UUID.class }, "ZodUUID", "UUID", "isUUID", "zod.string().uuid()", | ||||
| 				false), true); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Long.class, long.class }, "ZodLong", "Long", "isLong", | ||||
| 				// "zod.bigint()", | ||||
| 				"zod.number()", false), true); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Integer.class, int.class }, "ZodInteger", "Integer", "isInteger", | ||||
| 				"zod.number().safe()", false), true); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Double.class, double.class }, "ZodDouble", "Double", "isDouble", | ||||
| 				"zod.number()", true), true); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Float.class, float.class }, "ZodFloat", "Float", "isFloat", | ||||
| 				"zod.number()", false), true); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Instant.class }, "ZodInstant", "Instant", "isInstant", | ||||
| 				"zod.string()", false), true); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Date.class }, "ZodDate", "Date", "isDate", "zod.date()", false), | ||||
| 				true); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { Timestamp.class }, "ZodTimestamp", "Timestamp", "isTimestamp", | ||||
| 				"zod.date()", false), true); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { LocalDate.class }, "ZodLocalDate", "LocalDate", "isLocalDate", | ||||
| 				"zod.date()", false), true); | ||||
| 		previous.add(new ClassElement(new Class<?>[] { LocalTime.class }, "ZodLocalTime", "LocalTime", "isLocalTime", | ||||
| 				"zod.date()", false), true); | ||||
| 		return previous; | ||||
| 	} | ||||
|  | ||||
| 	/** Request the generation of the TypeScript file for the "Zod" export model | ||||
| 	 * @param classs List of class used in the model | ||||
| 	 * @return A string representing the Server models | ||||
| 	 * @throws Exception */ | ||||
| 	public static String createTables(final List<Class<?>> classs) throws Exception { | ||||
| 		return createTables(classs, createBasicType()); | ||||
| 	} | ||||
|  | ||||
| 	public static String createTables(final List<Class<?>> classs, final GeneratedTypes previous) throws Exception { | ||||
| 		for (final Class<?> clazz : classs) { | ||||
| 			createTable(clazz, previous); | ||||
| 		} | ||||
|  | ||||
| 		final StringBuilder generatedData = new StringBuilder(); | ||||
| 		generatedData.append(""" | ||||
| 				/** | ||||
| 				 * Interface of the server (auto-generated code) | ||||
| 				 */ | ||||
| 				import { z as zod } from \"zod\"; | ||||
|  | ||||
| 				"""); | ||||
| 		for (final Class<?> elem : previous.order) { | ||||
| 			final ClassElement data = previous.find(elem); | ||||
| 			if (!data.nativeType) { | ||||
| 				if (data.comment != null) { | ||||
| 					generatedData.append(data.comment); | ||||
| 				} | ||||
| 				generatedData.append(createDeclaration(data)); | ||||
| 				generatedData.append("\n\n"); | ||||
| 			} | ||||
| 		} | ||||
| 		LOGGER.info("generated: {}", generatedData.toString()); | ||||
| 		return generatedData.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public static List<ClassElement> createTables(final Class<?>[] classs, final GeneratedTypes previous) | ||||
| 			throws Exception { | ||||
| 		final List<ClassElement> out = new ArrayList<>(); | ||||
| 		for (final Class<?> clazz : classs) { | ||||
| 			if (clazz == Response.class) { | ||||
| 				throw new IOException("Can not generate a Zod element for an unknow type Response"); | ||||
| 			} | ||||
| 			out.add(createTable(clazz, previous)); | ||||
| 		} | ||||
| 		return out; | ||||
| 	} | ||||
|  | ||||
| 	public static ClassElement createTable(final Class<?> clazz, final GeneratedTypes previous) throws Exception { | ||||
| 		if (clazz == null) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		if (clazz == Response.class) { | ||||
| 			throw new IOException("Can not generate a Zod element for an unknow type Response"); | ||||
| 		} | ||||
| 		final ClassElement alreadyExist = previous.find(clazz); | ||||
| 		if (previous.find(clazz) != null) { | ||||
| 			return alreadyExist; | ||||
| 		} | ||||
| 		if (clazz.isPrimitive()) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		// add the current class to prevent multiple creation | ||||
| 		final ClassElement curentElementClass = new ClassElement(clazz); | ||||
| 		previous.add(curentElementClass); | ||||
| 		// Local generation of class: | ||||
| 		final StringBuilder internalBuilder = new StringBuilder(); | ||||
| 		final List<String> alreadyAdded = new ArrayList<>(); | ||||
| 		LOGGER.trace("parse class: '{}'", clazz.getCanonicalName()); | ||||
| 		int fieldId = 0; | ||||
| 		for (final Field elem : clazz.getFields()) { | ||||
| 			// static field is only for internal global declaration ==> remove it .. | ||||
| 			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()); | ||||
| 			if (false && DataAccess.isAddOnField(elem)) { | ||||
| 				final DataAccessAddOn addOn = DataAccess.findAddOnforField(elem); | ||||
| 				LOGGER.error("Create type for: {} ==> {} (ADD-ON) ==> Not managed now ....", | ||||
| 						AnnotationTools.getFieldName(elem), elem.getType()); | ||||
| 				/* LOGGER.trace("Create type for: {} ==> {} (ADD-ON)", AnnotationTools.getFieldName(elem), elem.getType()); if (addOn != null) { addOn.createTables(tableName, elem, tmpOut, | ||||
| 				 * preActionList, postActionList, createIfNotExist, createDrop, fieldId); } else { throw new DataAccessException( "Element matked as add-on but add-on does not loaded: table:" + | ||||
| 				 * tableName + " field name=" + AnnotationTools.getFieldName(elem) + " type=" + elem.getType()); } fieldId++; */ | ||||
| 			} else { | ||||
| 				LOGGER.trace("Create type for: {} ==> {}", AnnotationTools.getFieldName(elem), elem.getType()); | ||||
| 				DataFactoryZod.createTablesSpecificType(elem, fieldId, internalBuilder, previous); | ||||
| 				fieldId++; | ||||
| 			} | ||||
|  | ||||
| 		} | ||||
| 		final String description = AnnotationTools.getSchemaDescription(clazz); | ||||
| 		final String example = AnnotationTools.getSchemaExample(clazz); | ||||
| 		final StringBuilder generatedCommentedData = new StringBuilder(); | ||||
| 		if (description != null || example != null) { | ||||
| 			generatedCommentedData.append("/**\n"); | ||||
| 			if (description != null) { | ||||
| 				for (final String elem : description.split("\n")) { | ||||
| 					generatedCommentedData.append(" * "); | ||||
| 					generatedCommentedData.append(elem); | ||||
| 					generatedCommentedData.append("\n"); | ||||
| 				} | ||||
| 			} | ||||
| 			if (example != null) { | ||||
| 				generatedCommentedData.append(" * Example:\n"); | ||||
| 				generatedCommentedData.append(" * ```\n"); | ||||
| 				for (final String elem : example.split("\n")) { | ||||
| 					generatedCommentedData.append(" * "); | ||||
| 					generatedCommentedData.append(elem); | ||||
| 					generatedCommentedData.append("\n"); | ||||
| 				} | ||||
| 				generatedCommentedData.append(" * ```\n"); | ||||
| 			} | ||||
| 			generatedCommentedData.append(" */\n"); | ||||
| 		} | ||||
| 		curentElementClass.comment = generatedCommentedData.toString(); | ||||
| 		final StringBuilder generatedData = new StringBuilder(); | ||||
| 		final Class<?> parentClass = clazz.getSuperclass(); | ||||
| 		if (parentClass != null && parentClass != Object.class && parentClass != Record.class) { | ||||
| 			final ClassElement parentDeclaration = createTable(parentClass, previous); | ||||
| 			generatedData.append(parentDeclaration.zodName); | ||||
| 			generatedData.append(".extend({"); | ||||
| 		} else { | ||||
| 			generatedData.append("zod.object({"); | ||||
| 		} | ||||
| 		generatedData.append(internalBuilder.toString()); | ||||
| 		generatedData.append("\n})"); | ||||
| 		// Remove the previous to reorder the map ==> parent must be inserted before us. | ||||
| 		curentElementClass.declaration = generatedData.toString(); | ||||
| 		previous.addOrder(curentElementClass); | ||||
| 		return curentElementClass; | ||||
| 	} | ||||
|  | ||||
| 	public static String createDeclaration(final ClassElement elem) { | ||||
| 		final StringBuilder generatedData = new StringBuilder(); | ||||
| 		if (elem.isEnum) { | ||||
| 			generatedData.append("export enum "); | ||||
| 			generatedData.append(elem.tsTypeName); | ||||
| 			generatedData.append(" "); | ||||
| 			generatedData.append(elem.declaration); | ||||
| 			generatedData.append(";"); | ||||
| 			generatedData.append("\nexport const "); | ||||
| 			generatedData.append(elem.zodName); | ||||
| 			generatedData.append(" = zod.nativeEnum("); | ||||
| 			generatedData.append(elem.tsTypeName); | ||||
| 			generatedData.append(");"); | ||||
| 		} else { | ||||
| 			generatedData.append("export const "); | ||||
| 			generatedData.append(elem.zodName); | ||||
| 			generatedData.append(" = "); | ||||
| 			generatedData.append(elem.declaration); | ||||
| 			generatedData.append(";"); | ||||
| 			generatedData.append("\nexport type "); | ||||
| 			generatedData.append(elem.tsTypeName); | ||||
| 			generatedData.append(" = zod.infer<typeof "); | ||||
| 			generatedData.append(elem.zodName); | ||||
| 			generatedData.append(">;"); | ||||
| 		} | ||||
| 		// declare generic isXXX: | ||||
| 		generatedData.append("\nexport function "); | ||||
| 		generatedData.append(elem.tsCheckType); | ||||
| 		generatedData.append("(data: any): data is "); | ||||
| 		generatedData.append(elem.tsTypeName); | ||||
| 		generatedData.append(" {\n\ttry {\n\t\t"); | ||||
| 		generatedData.append(elem.zodName); | ||||
| 		generatedData.append(""" | ||||
| 				.parse(data); | ||||
| 						return true; | ||||
| 					} catch (e: any) { | ||||
| 						console.log(`Fail to parse data ${e}`); | ||||
| 						return false; | ||||
| 					} | ||||
| 				} | ||||
| 				"""); | ||||
| 		return generatedData.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public static void generatePackage(final List<Class<?>> classs, final String pathPackage) throws Exception { | ||||
| 		final String packageApi = createTables(classs); | ||||
| 		FileWriter myWriter = new FileWriter(pathPackage + File.separator + "model.ts"); | ||||
| 		myWriter.write(packageApi.toString()); | ||||
| 		myWriter.close(); | ||||
| 		final String index = """ | ||||
| 				/** | ||||
| 				 * Global import of the package | ||||
| 				 */ | ||||
| 				export * from "./model.ts"; | ||||
|  | ||||
| 				"""; | ||||
| 		myWriter = new FileWriter(pathPackage + File.separator + "index.ts"); | ||||
| 		myWriter.write(index); | ||||
| 		myWriter.close(); | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -8,17 +8,17 @@ import java.util.List; | ||||
| public class QueryAnd implements QueryItem { | ||||
| 	protected final List<QueryItem> childs; | ||||
|  | ||||
| 	public QueryAnd(final List<QueryItem> childs) { | ||||
| 		this.childs = childs; | ||||
| 	public QueryAnd(final List<QueryItem> child) { | ||||
| 		this.childs = child; | ||||
| 	} | ||||
|  | ||||
| 	public QueryAnd(final QueryItem... items) { | ||||
| 	public QueryAnd(final QueryItem... child) { | ||||
| 		this.childs = new ArrayList<>(); | ||||
| 		Collections.addAll(this.childs, items); | ||||
| 		Collections.addAll(this.childs, child); | ||||
| 	} | ||||
|  | ||||
| 	public void add(final QueryItem... items) { | ||||
| 		Collections.addAll(this.childs, items); | ||||
| 	public void add(final QueryItem... child) { | ||||
| 		Collections.addAll(this.childs, child); | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
|   | ||||
| @@ -7,6 +7,12 @@ public class QueryCondition implements QueryItem { | ||||
| 	private final String comparator; | ||||
| 	private final Object value; | ||||
|  | ||||
| 	/** | ||||
| 	 * Simple DB comparison element. Note the injected object is injected in the statement and not in the query directly. | ||||
| 	 * @param key Field to check (the Model property name) | ||||
| 	 * @param comparator (simple comparator String) | ||||
| 	 * @param value Value that the field must be equals. | ||||
| 	 */ | ||||
| 	public QueryCondition(final String key, final String comparator, final Object value) { | ||||
| 		this.key = key; | ||||
| 		this.comparator = comparator; | ||||
|   | ||||
| @@ -1,3 +0,0 @@ | ||||
| package org.kar.archidata.dataAccess; | ||||
|  | ||||
| public class QueryOption {} | ||||
| @@ -1,11 +1,11 @@ | ||||
| package org.kar.archidata.dataAccess; | ||||
|  | ||||
| import java.util.ArrayList; | ||||
| import java.util.Collections; | ||||
| import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.options.AccessDeletedItems; | ||||
| import org.kar.archidata.dataAccess.options.CreateDropTable; | ||||
| import org.kar.archidata.dataAccess.options.QueryOption; | ||||
| import org.kar.archidata.dataAccess.options.ReadAllColumn; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| @@ -24,10 +24,16 @@ public class QueryOptions { | ||||
| 		if (elems == null || elems.length == 0) { | ||||
| 			return; | ||||
| 		} | ||||
| 		Collections.addAll(this.options, elems); | ||||
| 		for (final QueryOption elem : elems) { | ||||
| 			add(elem); | ||||
| 		} | ||||
|  | ||||
| 	} | ||||
|  | ||||
| 	public void add(final QueryOption option) { | ||||
| 		if (option == null) { | ||||
| 			return; | ||||
| 		} | ||||
| 		this.options.add(option); | ||||
| 	} | ||||
|  | ||||
|   | ||||
| @@ -4,6 +4,7 @@ import java.lang.reflect.Field; | ||||
| import java.lang.reflect.ParameterizedType; | ||||
| import java.sql.PreparedStatement; | ||||
| import java.sql.ResultSet; | ||||
| import java.sql.SQLException; | ||||
| import java.sql.Types; | ||||
| import java.util.ArrayList; | ||||
| import java.util.List; | ||||
| @@ -26,6 +27,7 @@ import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import com.fasterxml.jackson.annotation.JsonValue; | ||||
| import com.fasterxml.jackson.core.JsonProcessingException; | ||||
| import com.fasterxml.jackson.core.type.TypeReference; | ||||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||||
|  | ||||
| @@ -53,7 +55,7 @@ public class AddOnDataJson implements DataAccessAddOn { | ||||
|  | ||||
| 	@Override | ||||
| 	public void insertData(final PreparedStatement ps, final Field field, final Object rootObject, final CountInOut iii) | ||||
| 			throws Exception { | ||||
| 			throws IllegalArgumentException, IllegalAccessException, SQLException, JsonProcessingException { | ||||
| 		final Object data = field.get(rootObject); | ||||
| 		if (data == null) { | ||||
| 			ps.setNull(iii.value, Types.VARCHAR); | ||||
| @@ -70,7 +72,7 @@ public class AddOnDataJson implements DataAccessAddOn { | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public boolean isInsertAsync(final Field field) throws Exception { | ||||
| 	public boolean isInsertAsync(final Field field) { | ||||
| 		return false; | ||||
| 	} | ||||
|  | ||||
| @@ -186,9 +188,21 @@ public class AddOnDataJson implements DataAccessAddOn { | ||||
| 		DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 	} | ||||
|  | ||||
| 	/** | ||||
| 	 * Adds a remoteKey to the covers list of a data entry identified by the given class type and ID. | ||||
| 	 * If the covers list is null, it initializes it. If the remoteKey already exists in the list, | ||||
| 	 * the method returns without making any changes. | ||||
| 	 * | ||||
| 	 * @param clazz     The class type to retrieve the table name from. | ||||
| 	 * @param id        The ID of the data object to fetch. | ||||
| 	 * @param column    The name of the column (currently not used, but may be used for specifying a field name). | ||||
| 	 * @param remoteKey The UUID to add to the covers list. | ||||
| 	 * @throws Exception If an error occurs during data retrieval or update. | ||||
| 	 */ | ||||
| 	public static void addLink(final Class<?> clazz, final Long id, final String column, final UUID remoteKey) | ||||
| 			throws Exception { | ||||
| 		final String tableName = AnnotationTools.getTableName(clazz); | ||||
| 		// TODO: Get primary key name | ||||
| 		final TableCoversLongUUID data = DataAccess.get(TableCoversLongUUID.class, id, | ||||
| 				new OverrideTableName(tableName)); | ||||
| 		if (data.covers == null) { | ||||
| @@ -200,13 +214,24 @@ public class AddOnDataJson implements DataAccessAddOn { | ||||
| 			} | ||||
| 		} | ||||
| 		data.covers.add(remoteKey); | ||||
| 		DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 		DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName));// TODO:  ,new OverrideFieldName("covers", column)); | ||||
| 	} | ||||
|  | ||||
| 	public static void addLink(final Class<?> clazz, final UUID id, final String column, final UUID remoteKey) | ||||
| 	/** | ||||
| 	 * Adds a remoteKey to the covers list of a data entry identified by the given class type and ID. | ||||
| 	 * If the covers list is null, it initializes it. If the remoteKey already exists in the list, | ||||
| 	 * the method returns without making any changes. | ||||
| 	 * | ||||
| 	 * @param clazz     The class type to retrieve the table name from. | ||||
| 	 * @param id        The ID of the data object to fetch. | ||||
| 	 * @param column    The name of the column (currently not used, but may be used for specifying a field name). | ||||
| 	 * @param remoteKey The UUID to add to the covers list. | ||||
| 	 * @throws Exception If an error occurs during data retrieval or update. | ||||
| 	 */ | ||||
| 	public static void addLink(final Class<?> clazz, final UUID uuid, final String column, final UUID remoteKey) | ||||
| 			throws Exception { | ||||
| 		final String tableName = AnnotationTools.getTableName(clazz); | ||||
| 		final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, id, | ||||
| 		final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, uuid, | ||||
| 				new OverrideTableName(tableName)); | ||||
| 		if (data.covers == null) { | ||||
| 			data.covers = new ArrayList<>(); | ||||
| @@ -217,13 +242,13 @@ public class AddOnDataJson implements DataAccessAddOn { | ||||
| 			} | ||||
| 		} | ||||
| 		data.covers.add(remoteKey); | ||||
| 		DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 		DataAccess.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 	} | ||||
|  | ||||
| 	public static void addLink(final Class<?> clazz, final UUID id, final String column, final Long remoteKey) | ||||
| 	public static void addLink(final Class<?> clazz, final UUID uuid, final String column, final Long remoteKey) | ||||
| 			throws Exception { | ||||
| 		final String tableName = AnnotationTools.getTableName(clazz); | ||||
| 		final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, id, | ||||
| 		final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, uuid, | ||||
| 				new OverrideTableName(tableName)); | ||||
| 		if (data.covers == null) { | ||||
| 			data.covers = new ArrayList<>(); | ||||
| @@ -234,13 +259,13 @@ public class AddOnDataJson implements DataAccessAddOn { | ||||
| 			} | ||||
| 		} | ||||
| 		data.covers.add(remoteKey); | ||||
| 		DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 		DataAccess.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 	} | ||||
|  | ||||
| 	public static void removeLink(final Class<?> clazz, final UUID id, final String column, final Long remoteKey) | ||||
| 	public static void removeLink(final Class<?> clazz, final UUID uuid, final String column, final Long remoteKey) | ||||
| 			throws Exception { | ||||
| 		final String tableName = AnnotationTools.getTableName(clazz); | ||||
| 		final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, id, | ||||
| 		final TableCoversUUIDLong data = DataAccess.get(TableCoversUUIDLong.class, uuid, | ||||
| 				new OverrideTableName(tableName)); | ||||
| 		if (data.covers == null) { | ||||
| 			return; | ||||
| @@ -253,13 +278,13 @@ public class AddOnDataJson implements DataAccessAddOn { | ||||
| 			newList.add(elem); | ||||
| 		} | ||||
| 		data.covers = newList; | ||||
| 		DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 		DataAccess.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 	} | ||||
|  | ||||
| 	public static void removeLink(final Class<?> clazz, final UUID id, final String column, final UUID remoteKey) | ||||
| 	public static void removeLink(final Class<?> clazz, final UUID uuid, final String column, final UUID remoteKey) | ||||
| 			throws Exception { | ||||
| 		final String tableName = AnnotationTools.getTableName(clazz); | ||||
| 		final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, id, | ||||
| 		final TableCoversUUIDUUID data = DataAccess.get(TableCoversUUIDUUID.class, uuid, | ||||
| 				new OverrideTableName(tableName)); | ||||
| 		if (data.covers == null) { | ||||
| 			return; | ||||
| @@ -272,7 +297,7 @@ public class AddOnDataJson implements DataAccessAddOn { | ||||
| 			newList.add(elem); | ||||
| 		} | ||||
| 		data.covers = newList; | ||||
| 		DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 		DataAccess.update(data, data.uuid, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 	} | ||||
|  | ||||
| 	public static void removeLink(final Class<?> clazz, final Long id, final String column, final Long remoteKey) | ||||
| @@ -312,9 +337,4 @@ public class AddOnDataJson implements DataAccessAddOn { | ||||
| 		data.covers = newList; | ||||
| 		DataAccess.update(data, data.id, List.of("covers"), new OverrideTableName(tableName)); | ||||
| 	} | ||||
| 	/* public static <TYPE> void addLink(final Class<TYPE> clazz, final Object localKey, final String column, final Object remoteKey) throws Exception { final String tableName = | ||||
| 	 * AnnotationTools.getTableName(clazz); final TYPE data = DataAccess.get(clazz, localKey); // TODO: add filter of the "column" // find the field column: // add the remoteKey in the list: // post | ||||
| 	 * new data in the DB final String linkTableName = generateLinkTableName(this.tableName, this.column); final LinkTable insertElement = new LinkTable(this.localKey, this.remoteKey); | ||||
| 	 * DataAccess.insert(insertElement, new OverrideTableName(linkTableName)); } */ | ||||
|  | ||||
| } | ||||
|   | ||||
| @@ -134,7 +134,9 @@ public class AddOnManyToMany implements DataAccessAddOn { | ||||
| 		querySelect.append(" "); | ||||
| 		querySelect.append(tmpVariable); | ||||
| 		querySelect.append(" WHERE "); | ||||
| 		/* querySelect.append(tmpVariable); querySelect.append(".deleted = false AND "); */ | ||||
| 		querySelect.append(tmpVariable); | ||||
| 		querySelect.append(".deleted = false"); | ||||
| 		querySelect.append(" AND "); | ||||
| 		querySelect.append(tableName); | ||||
| 		querySelect.append("."); | ||||
| 		querySelect.append(primaryKey); | ||||
| @@ -170,6 +172,7 @@ public class AddOnManyToMany implements DataAccessAddOn { | ||||
| 		} | ||||
| 		final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) | ||||
| 				.getActualTypeArguments()[0]; | ||||
| 		// TODO: manage better the eager and lazy !! | ||||
| 		if (objectClass == Long.class || objectClass == UUID.class) { | ||||
| 			generateConcatQuery(tableName, primaryKey, field, querySelect, query, name, count, options); | ||||
| 		} | ||||
|   | ||||
| @@ -238,7 +238,11 @@ public class AddOnManyToOne implements DataAccessAddOn { | ||||
| 				if (dataNew != null && countNotNull.value != 0) { | ||||
| 					field.set(data, dataNew); | ||||
| 				} | ||||
| 			} else { | ||||
| 				return; | ||||
| 			} | ||||
| 			final Field remotePrimaryKeyField = AnnotationTools.getFieldOfId(objectClass); | ||||
| 			final Class<?> remotePrimaryKeyType = remotePrimaryKeyField.getType(); | ||||
| 			if (remotePrimaryKeyType == Long.class) { | ||||
| 				// here we have the field, the data and the the remote value ==> can create callback that generate the update of the value ... | ||||
| 				final Long foreignKey = rs.getLong(count.value); | ||||
| 				count.inc(); | ||||
| @@ -254,6 +258,22 @@ public class AddOnManyToOne implements DataAccessAddOn { | ||||
| 					}; | ||||
| 					lazyCall.add(lambda); | ||||
| 				} | ||||
| 			} else if (remotePrimaryKeyType == UUID.class) { | ||||
| 				// here we have the field, the data and the the remote value ==> can create callback that generate the update of the value ... | ||||
| 				final UUID foreignKey = DataAccess.getListOfRawUUID(rs, count.value); | ||||
| 				count.inc(); | ||||
| 				if (foreignKey != null) { | ||||
| 					// In the lazy mode, the request is done in asynchronous mode, they will be done after... | ||||
| 					final LazyGetter lambda = () -> { | ||||
| 						// TODO: update to have get with abstract types .... | ||||
| 						final Object foreignData = DataAccess.get(decorators.targetEntity(), foreignKey); | ||||
| 						if (foreignData == null) { | ||||
| 							return; | ||||
| 						} | ||||
| 						field.set(data, foreignData); | ||||
| 					}; | ||||
| 					lazyCall.add(lambda); | ||||
| 				} | ||||
| 			} | ||||
| 		} | ||||
| 	} | ||||
|   | ||||
| @@ -1,28 +1,36 @@ | ||||
| package org.kar.archidata.dataAccess.addOn; | ||||
|  | ||||
| import java.lang.reflect.Field; | ||||
| import java.lang.reflect.ParameterizedType; | ||||
| import java.sql.PreparedStatement; | ||||
| import java.sql.ResultSet; | ||||
| import java.sql.SQLException; | ||||
| import java.sql.Types; | ||||
| import java.util.ArrayList; | ||||
| import java.util.List; | ||||
| import java.util.UUID; | ||||
| import java.util.stream.Collectors; | ||||
|  | ||||
| import org.kar.archidata.annotation.AnnotationTools; | ||||
| import org.kar.archidata.dataAccess.CountInOut; | ||||
| import org.kar.archidata.dataAccess.DataAccess; | ||||
| import org.kar.archidata.dataAccess.DataAccessAddOn; | ||||
| import org.kar.archidata.dataAccess.DataFactory; | ||||
| import org.kar.archidata.dataAccess.LazyGetter; | ||||
| import org.kar.archidata.dataAccess.QueryCondition; | ||||
| import org.kar.archidata.dataAccess.QueryOptions; | ||||
| import org.kar.archidata.dataAccess.options.Condition; | ||||
| import org.kar.archidata.exception.DataAccessException; | ||||
| import org.kar.archidata.tools.ConfigBaseVariable; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import jakarta.persistence.FetchType; | ||||
| import jakarta.persistence.OneToMany; | ||||
| import jakarta.validation.constraints.NotNull; | ||||
|  | ||||
| public class AddOnOneToMany implements DataAccessAddOn { | ||||
| 	static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class); | ||||
| 	static final Logger LOGGER = LoggerFactory.getLogger(AddOnOneToMany.class); | ||||
| 	static final String SEPARATOR_LONG = "-"; | ||||
|  | ||||
| 	/** Convert the list if external id in a string '-' separated | ||||
| 	 * @param ids List of value (null are removed) | ||||
| @@ -77,15 +85,7 @@ public class AddOnOneToMany implements DataAccessAddOn { | ||||
| 	@Override | ||||
| 	public void insertData(final PreparedStatement ps, final Field field, final Object rootObject, final CountInOut iii) | ||||
| 			throws SQLException, IllegalArgumentException, IllegalAccessException { | ||||
| 		final Object data = field.get(rootObject); | ||||
| 		iii.inc(); | ||||
| 		if (data == null) { | ||||
| 			ps.setNull(iii.value, Types.BIGINT); | ||||
| 		} else { | ||||
| 			@SuppressWarnings("unchecked") | ||||
| 			final String dataTmp = getStringOfIds((List<Long>) data); | ||||
| 			ps.setString(iii.value, dataTmp); | ||||
| 		} | ||||
| 		throw new IllegalAccessException("Can not generate an inset of @OneToMany"); | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| @@ -95,13 +95,87 @@ public class AddOnOneToMany implements DataAccessAddOn { | ||||
|  | ||||
| 	@Override | ||||
| 	public boolean isInsertAsync(final Field field) throws Exception { | ||||
| 		// TODO: can be implemented later... | ||||
| 		return false; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public boolean canRetrieve(final Field field) { | ||||
| 		if (field.getType() != List.class) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) | ||||
| 				.getActualTypeArguments()[0]; | ||||
| 		if (objectClass == Long.class || objectClass == UUID.class) { | ||||
| 			return true; | ||||
| 		} | ||||
| 		final OneToMany decorators = field.getDeclaredAnnotation(OneToMany.class); | ||||
| 		if (decorators == null) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		if (decorators.targetEntity() == objectClass) { | ||||
| 			return true; | ||||
| 		} | ||||
| 		return false; | ||||
| 	} | ||||
|  | ||||
| 	public void generateConcatQuery( | ||||
| 			@NotNull final String tableName, | ||||
| 			@NotNull final String primaryKey, | ||||
| 			@NotNull final Field field, | ||||
| 			@NotNull final StringBuilder querySelect, | ||||
| 			@NotNull final StringBuilder query, | ||||
| 			@NotNull final String name, | ||||
| 			@NotNull final CountInOut count, | ||||
| 			final QueryOptions options, | ||||
| 			final Class<?> targetEntity, | ||||
| 			final String mappedBy) throws Exception { | ||||
| 		final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) | ||||
| 				.getActualTypeArguments()[0]; | ||||
| 		final String remoteTableName = AnnotationTools.getTableName(targetEntity); | ||||
| 		final String remoteTablePrimaryKeyName = AnnotationTools | ||||
| 				.getFieldName(AnnotationTools.getPrimaryKeyField(targetEntity)); | ||||
| 		final String tmpRemoteVariable = "tmp_" + Integer.toString(count.value); | ||||
| 		final String remoteDeletedFieldName = AnnotationTools.getDeletedFieldName(targetEntity); | ||||
|  | ||||
| 		querySelect.append(" (SELECT GROUP_CONCAT("); | ||||
| 		querySelect.append(tmpRemoteVariable); | ||||
| 		querySelect.append("."); | ||||
| 		querySelect.append(remoteTablePrimaryKeyName); | ||||
| 		querySelect.append(" "); | ||||
| 		if ("sqlite".equals(ConfigBaseVariable.getDBType())) { | ||||
| 			querySelect.append(", "); | ||||
| 		} else { | ||||
| 			querySelect.append("SEPARATOR "); | ||||
| 		} | ||||
| 		querySelect.append("'"); | ||||
| 		if (objectClass == Long.class) { | ||||
| 			querySelect.append(SEPARATOR_LONG); | ||||
| 		} | ||||
| 		querySelect.append("') FROM "); | ||||
| 		querySelect.append(remoteTableName); | ||||
| 		querySelect.append(" "); | ||||
| 		querySelect.append(tmpRemoteVariable); | ||||
| 		querySelect.append(" WHERE "); | ||||
| 		if (remoteDeletedFieldName != null) { | ||||
| 			querySelect.append(tmpRemoteVariable); | ||||
| 			querySelect.append("."); | ||||
| 			querySelect.append(remoteDeletedFieldName); | ||||
| 			querySelect.append(" = false"); | ||||
| 			querySelect.append(" AND "); | ||||
| 		} | ||||
| 		querySelect.append(tableName); | ||||
| 		querySelect.append("."); | ||||
| 		querySelect.append(primaryKey); | ||||
| 		querySelect.append(" = "); | ||||
| 		querySelect.append(tmpRemoteVariable); | ||||
| 		querySelect.append("."); | ||||
| 		querySelect.append(mappedBy); | ||||
| 		querySelect.append(" "); | ||||
| 		querySelect.append(") AS "); | ||||
| 		querySelect.append(name); | ||||
| 		querySelect.append(" "); | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public void generateQuery( | ||||
| @@ -112,12 +186,35 @@ public class AddOnOneToMany implements DataAccessAddOn { | ||||
| 			@NotNull final StringBuilder query, | ||||
| 			@NotNull final String name, | ||||
| 			@NotNull final CountInOut count, | ||||
| 			final QueryOptions options) { | ||||
| 			final QueryOptions options) throws Exception { | ||||
| 		if (field.getType() != List.class) { | ||||
| 			return; | ||||
| 		} | ||||
| 		final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) | ||||
| 				.getActualTypeArguments()[0]; | ||||
| 		final OneToMany decorators = field.getDeclaredAnnotation(OneToMany.class); | ||||
| 		if (decorators == null) { | ||||
| 			return; | ||||
| 		} | ||||
| 		// TODO: manage better the eager and lazy !! | ||||
| 		if (objectClass == Long.class || objectClass == UUID.class) { | ||||
| 			generateConcatQuery(tableName, primaryKey, field, querySelect, query, name, count, options, | ||||
| 					decorators.targetEntity(), decorators.mappedBy()); | ||||
| 			return; | ||||
| 		} | ||||
| 		if (objectClass == decorators.targetEntity()) { | ||||
| 			if (decorators.fetch() == FetchType.EAGER) { | ||||
| 				throw new DataAccessException("EAGER is not supported for list of element..."); | ||||
| 			} else { | ||||
| 				// Force a copy of the primaryKey to permit the async retrieve of the data | ||||
| 				querySelect.append(" "); | ||||
| 				querySelect.append(tableName); | ||||
| 				querySelect.append("."); | ||||
| 		querySelect.append(name); | ||||
| 		count.inc(); | ||||
| 				querySelect.append(primaryKey); | ||||
| 				querySelect.append(" AS tmp_"); | ||||
| 				querySelect.append(Integer.toString(count.value)); | ||||
| 			} | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| @@ -127,16 +224,86 @@ public class AddOnOneToMany implements DataAccessAddOn { | ||||
| 			final Object data, | ||||
| 			final CountInOut count, | ||||
| 			final QueryOptions options, | ||||
| 			final List<LazyGetter> lazyCall) throws SQLException, IllegalArgumentException, IllegalAccessException { | ||||
| 		final Long foreignKey = rs.getLong(count.value); | ||||
| 			final List<LazyGetter> lazyCall) throws Exception { | ||||
| 		if (field.getType() != List.class) { | ||||
| 			LOGGER.error("Can not OneToMany with other than List Model: {}", field.getType().getCanonicalName()); | ||||
| 			return; | ||||
| 		} | ||||
| 		final Class<?> objectClass = (Class<?>) ((ParameterizedType) field.getGenericType()) | ||||
| 				.getActualTypeArguments()[0]; | ||||
| 		final OneToMany decorators = field.getDeclaredAnnotation(OneToMany.class); | ||||
| 		if (decorators == null) { | ||||
| 			return; | ||||
| 		} | ||||
| 		if (objectClass == Long.class) { | ||||
| 			final List<Long> idList = DataAccess.getListOfIds(rs, count.value, SEPARATOR_LONG); | ||||
| 			field.set(data, idList); | ||||
| 			count.inc(); | ||||
| 		if (!rs.wasNull()) { | ||||
| 			return; | ||||
| 		} else if (objectClass == UUID.class) { | ||||
| 			final List<UUID> idList = DataAccess.getListOfRawUUIDs(rs, count.value); | ||||
| 			field.set(data, idList); | ||||
| 			count.inc(); | ||||
| 			return; | ||||
| 		} | ||||
| 		if (objectClass == decorators.targetEntity()) { | ||||
|  | ||||
| 			field.set(data, foreignKey); | ||||
| 			Long parentIdTmp = null; | ||||
| 			UUID parendUuidTmp = null; | ||||
| 			try { | ||||
| 				final String modelData = rs.getString(count.value); | ||||
| 				parentIdTmp = Long.valueOf(modelData); | ||||
| 				count.inc(); | ||||
| 			} catch (final NumberFormatException ex) { | ||||
| 				final List<UUID> idList = DataAccess.getListOfRawUUIDs(rs, count.value); | ||||
| 				parendUuidTmp = idList.get(0); | ||||
| 				count.inc(); | ||||
| 			} | ||||
| 			final Long parentId = parentIdTmp; | ||||
| 			final UUID parendUuid = parendUuidTmp; | ||||
| 			final String mappingKey = decorators.mappedBy(); | ||||
| 			// We get the parent ID ... ==> need to request the list of elements | ||||
| 			if (objectClass == Long.class) { | ||||
| 				LOGGER.error("Need to retreive all primary key of all elements"); | ||||
| 				//field.set(data, idList); | ||||
| 				return; | ||||
| 			} else if (objectClass == UUID.class) { | ||||
| 				LOGGER.error("Need to retreive all primary key of all elements"); | ||||
| 				//field.set(data, idList); | ||||
| 				return; | ||||
| 			} | ||||
| 			if (objectClass == decorators.targetEntity()) { | ||||
| 				if (decorators.fetch() == FetchType.EAGER) { | ||||
| 					throw new DataAccessException("EAGER is not supported for list of element..."); | ||||
| 				} else if (parentId != null) { | ||||
| 					// In the lazy mode, the request is done in asynchronous mode, they will be done after... | ||||
| 					final LazyGetter lambda = () -> { | ||||
| 						@SuppressWarnings("unchecked") | ||||
| 						final Object foreignData = DataAccess.getsWhere(decorators.targetEntity(), | ||||
| 								new Condition(new QueryCondition(mappingKey, "=", parentId))); | ||||
| 						if (foreignData == null) { | ||||
| 							return; | ||||
| 						} | ||||
| 						field.set(data, foreignData); | ||||
| 					}; | ||||
| 					lazyCall.add(lambda); | ||||
| 				} else if (parendUuid != null) { | ||||
| 					final LazyGetter lambda = () -> { | ||||
| 						@SuppressWarnings("unchecked") | ||||
| 						final Object foreignData = DataAccess.getsWhere(decorators.targetEntity(), | ||||
| 								new Condition(new QueryCondition(mappingKey, "=", parendUuid))); | ||||
| 						if (foreignData == null) { | ||||
| 							return; | ||||
| 						} | ||||
| 						field.set(data, foreignData); | ||||
| 					}; | ||||
| 					lazyCall.add(lambda); | ||||
| 				} | ||||
| 			} | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	// TODO : refacto this table to manage a generic table with dynamic name to be serializable with the default system | ||||
| 	// TODO : refacto this table to manage a generic table with dynamic name to be serialize with the default system | ||||
| 	@Override | ||||
| 	public void createTables( | ||||
| 			final String tableName, | ||||
| @@ -148,7 +315,6 @@ public class AddOnOneToMany implements DataAccessAddOn { | ||||
| 			final boolean createIfNotExist, | ||||
| 			final boolean createDrop, | ||||
| 			final int fieldId) throws Exception { | ||||
| 		DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList, | ||||
| 				postActionList, createIfNotExist, createDrop, fieldId, Long.class); | ||||
| 		// This is a remote field ==> nothing to generate (it is stored in the remote object | ||||
| 	} | ||||
| } | ||||
|   | ||||
| @@ -1,136 +0,0 @@ | ||||
| package org.kar.archidata.dataAccess.addOn; | ||||
|  | ||||
| import java.lang.reflect.Field; | ||||
| import java.sql.PreparedStatement; | ||||
| import java.sql.ResultSet; | ||||
| import java.sql.SQLException; | ||||
| import java.sql.Types; | ||||
| import java.util.ArrayList; | ||||
| import java.util.List; | ||||
| import java.util.stream.Collectors; | ||||
|  | ||||
| import org.kar.archidata.annotation.AnnotationTools; | ||||
| import org.kar.archidata.annotation.addOn.SQLTableExternalForeinKeyAsList; | ||||
| import org.kar.archidata.dataAccess.CountInOut; | ||||
| import org.kar.archidata.dataAccess.DataAccess; | ||||
| import org.kar.archidata.dataAccess.DataAccessAddOn; | ||||
| import org.kar.archidata.dataAccess.DataFactory; | ||||
| import org.kar.archidata.dataAccess.LazyGetter; | ||||
| import org.kar.archidata.dataAccess.QueryOptions; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import jakarta.validation.constraints.NotNull; | ||||
|  | ||||
| // TODO: maybe deprecated ==> use DataJson instead... | ||||
| @Deprecated | ||||
| public class AddOnSQLTableExternalForeinKeyAsList implements DataAccessAddOn { | ||||
| 	static final Logger LOGGER = LoggerFactory.getLogger(AddOnManyToMany.class); | ||||
| 	static final String SEPARATOR = "-"; | ||||
|  | ||||
| 	/** Convert the list if external id in a string '-' separated | ||||
| 	 * @param ids List of value (null are removed) | ||||
| 	 * @return '-' string separated */ | ||||
| 	protected static String getStringOfIds(final List<Long> ids) { | ||||
| 		final List<Long> tmp = new ArrayList<>(ids); | ||||
| 		return tmp.stream().map(String::valueOf).collect(Collectors.joining(SEPARATOR)); | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public Class<?> getAnnotationClass() { | ||||
| 		return SQLTableExternalForeinKeyAsList.class; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public String getSQLFieldType(final Field field) throws Exception { | ||||
| 		final String fieldName = AnnotationTools.getFieldName(field); | ||||
| 		try { | ||||
| 			return DataFactory.convertTypeInSQL(String.class, fieldName); | ||||
| 		} catch (final Exception e) { | ||||
| 			// TODO Auto-generated catch block | ||||
| 			e.printStackTrace(); | ||||
| 		} | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public boolean isCompatibleField(final Field field) { | ||||
| 		final SQLTableExternalForeinKeyAsList decorators = field | ||||
| 				.getDeclaredAnnotation(SQLTableExternalForeinKeyAsList.class); | ||||
| 		return decorators != null; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public void insertData(final PreparedStatement ps, final Field field, final Object rootObject, final CountInOut iii) | ||||
| 			throws SQLException, IllegalArgumentException, IllegalAccessException { | ||||
| 		final Object data = field.get(rootObject); | ||||
| 		iii.inc(); | ||||
| 		if (data == null) { | ||||
| 			ps.setNull(iii.value, Types.BIGINT); | ||||
| 		} else { | ||||
| 			@SuppressWarnings("unchecked") | ||||
| 			final String dataTmp = getStringOfIds((List<Long>) data); | ||||
| 			ps.setString(iii.value, dataTmp); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public boolean canInsert(final Field field) { | ||||
| 		return true; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public boolean isInsertAsync(final Field field) throws Exception { | ||||
| 		return false; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public boolean canRetrieve(final Field field) { | ||||
| 		return true; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public void generateQuery( | ||||
| 			@NotNull final String tableName, | ||||
| 			@NotNull final String primaryKey, | ||||
| 			@NotNull final Field field, | ||||
| 			@NotNull final StringBuilder querySelect, | ||||
| 			@NotNull final StringBuilder query, | ||||
| 			@NotNull final String name, | ||||
| 			@NotNull final CountInOut count, | ||||
| 			final QueryOptions options) { | ||||
| 		count.inc(); | ||||
| 		querySelect.append(" "); | ||||
| 		querySelect.append(tableName); | ||||
| 		querySelect.append("."); | ||||
| 		querySelect.append(name); | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public void fillFromQuery( | ||||
| 			final ResultSet rs, | ||||
| 			final Field field, | ||||
| 			final Object data, | ||||
| 			final CountInOut count, | ||||
| 			final QueryOptions options, | ||||
| 			final List<LazyGetter> lazyCall) throws SQLException, IllegalArgumentException, IllegalAccessException { | ||||
| 		final List<Long> idList = DataAccess.getListOfIds(rs, count.value, SEPARATOR); | ||||
| 		field.set(data, idList); | ||||
| 		count.inc(); | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public void createTables( | ||||
| 			final String tableName, | ||||
| 			final Field primaryField, | ||||
| 			final Field field, | ||||
| 			final StringBuilder mainTableBuilder, | ||||
| 			final List<String> preActionList, | ||||
| 			final List<String> postActionList, | ||||
| 			final boolean createIfNotExist, | ||||
| 			final boolean createDrop, | ||||
| 			final int fieldId) throws Exception { | ||||
| 		DataFactory.createTablesSpecificType(tableName, primaryField, field, mainTableBuilder, preActionList, | ||||
| 				postActionList, createIfNotExist, createDrop, fieldId, String.class); | ||||
| 	} | ||||
| } | ||||
| @@ -1,11 +1,11 @@ | ||||
| package org.kar.archidata.dataAccess.addOn.model; | ||||
|  | ||||
| import org.kar.archidata.model.GenericData; | ||||
| import org.kar.archidata.model.UUIDGenericDataSoftDelete; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.media.Schema; | ||||
| import jakarta.persistence.Column; | ||||
|  | ||||
| public class LinkTableLongLong extends GenericData { | ||||
| public class LinkTableLongLong extends UUIDGenericDataSoftDelete { | ||||
| 	public LinkTableLongLong() { | ||||
| 		// nothing to do... | ||||
| 	} | ||||
|   | ||||
| @@ -2,12 +2,12 @@ package org.kar.archidata.dataAccess.addOn.model; | ||||
|  | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.kar.archidata.model.GenericData; | ||||
| import org.kar.archidata.model.UUIDGenericDataSoftDelete; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.media.Schema; | ||||
| import jakarta.persistence.Column; | ||||
|  | ||||
| public class LinkTableLongUUID extends GenericData { | ||||
| public class LinkTableLongUUID extends UUIDGenericDataSoftDelete { | ||||
| 	public LinkTableLongUUID() { | ||||
| 		// nothing to do... | ||||
| 	} | ||||
|   | ||||
| @@ -2,12 +2,12 @@ package org.kar.archidata.dataAccess.addOn.model; | ||||
|  | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.kar.archidata.model.GenericData; | ||||
| import org.kar.archidata.model.UUIDGenericDataSoftDelete; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.media.Schema; | ||||
| import jakarta.persistence.Column; | ||||
|  | ||||
| public class LinkTableUUIDLong extends GenericData { | ||||
| public class LinkTableUUIDLong extends UUIDGenericDataSoftDelete { | ||||
| 	public LinkTableUUIDLong() { | ||||
| 		// nothing to do... | ||||
| 	} | ||||
|   | ||||
| @@ -2,12 +2,12 @@ package org.kar.archidata.dataAccess.addOn.model; | ||||
|  | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.kar.archidata.model.GenericData; | ||||
| import org.kar.archidata.model.UUIDGenericDataSoftDelete; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.media.Schema; | ||||
| import jakarta.persistence.Column; | ||||
|  | ||||
| public class LinkTableUUIDUUID extends GenericData { | ||||
| public class LinkTableUUIDUUID extends UUIDGenericDataSoftDelete { | ||||
| 	public LinkTableUUIDUUID() { | ||||
| 		// nothing to do... | ||||
| 	} | ||||
|   | ||||
| @@ -3,12 +3,10 @@ package org.kar.archidata.dataAccess.addOn.model; | ||||
| import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.annotation.DataJson; | ||||
| import org.kar.archidata.model.GenericData; | ||||
|  | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.persistence.Id; | ||||
|  | ||||
| public class TableCoversLongLong extends GenericData { | ||||
| public class TableCoversLongLong { | ||||
| 	public TableCoversLongLong() { | ||||
| 		// nothing to do... | ||||
| 	} | ||||
| @@ -18,11 +16,10 @@ public class TableCoversLongLong extends GenericData { | ||||
| 		this.covers = covers; | ||||
| 	} | ||||
|  | ||||
| 	@Column(nullable = false) | ||||
| 	@Id | ||||
| 	public Long id; | ||||
|  | ||||
| 	@DataJson() | ||||
| 	@Column(nullable = false) | ||||
| 	public List<Long> covers; | ||||
|  | ||||
| } | ||||
|   | ||||
| @@ -4,12 +4,10 @@ import java.util.List; | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.kar.archidata.annotation.DataJson; | ||||
| import org.kar.archidata.model.GenericData; | ||||
|  | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.persistence.Id; | ||||
|  | ||||
| public class TableCoversLongUUID extends GenericData { | ||||
| public class TableCoversLongUUID { | ||||
| 	public TableCoversLongUUID() { | ||||
| 		// nothing to do... | ||||
| 	} | ||||
| @@ -19,11 +17,10 @@ public class TableCoversLongUUID extends GenericData { | ||||
| 		this.covers = covers; | ||||
| 	} | ||||
|  | ||||
| 	@Column(nullable = false) | ||||
| 	@Id | ||||
| 	public Long id; | ||||
|  | ||||
| 	@DataJson() | ||||
| 	@Column(nullable = false) | ||||
| 	public List<UUID> covers; | ||||
|  | ||||
| } | ||||
|   | ||||
| @@ -4,26 +4,22 @@ import java.util.List; | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.kar.archidata.annotation.DataJson; | ||||
| import org.kar.archidata.model.GenericData; | ||||
|  | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.persistence.Id; | ||||
|  | ||||
| public class TableCoversUUIDLong extends GenericData { | ||||
| public class TableCoversUUIDLong { | ||||
| 	public TableCoversUUIDLong() { | ||||
| 		// nothing to do... | ||||
| 	} | ||||
|  | ||||
| 	public TableCoversUUIDLong(final UUID id, final List<Long> covers) { | ||||
| 		this.id = id; | ||||
| 	public TableCoversUUIDLong(final UUID uuid, final List<Long> covers) { | ||||
| 		this.uuid = uuid; | ||||
| 		this.covers = covers; | ||||
| 	} | ||||
|  | ||||
| 	@Column(nullable = false) | ||||
| 	@Id | ||||
| 	public UUID id; | ||||
| 	public UUID uuid; | ||||
| 	@DataJson() | ||||
| 	@Column(nullable = false) | ||||
| 	public List<Long> covers; | ||||
|  | ||||
| } | ||||
|   | ||||
| @@ -4,26 +4,22 @@ import java.util.List; | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.kar.archidata.annotation.DataJson; | ||||
| import org.kar.archidata.model.GenericData; | ||||
|  | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.persistence.Id; | ||||
|  | ||||
| public class TableCoversUUIDUUID extends GenericData { | ||||
| public class TableCoversUUIDUUID { | ||||
| 	public TableCoversUUIDUUID() { | ||||
| 		// nothing to do... | ||||
| 	} | ||||
|  | ||||
| 	public TableCoversUUIDUUID(final UUID id, final List<UUID> covers) { | ||||
| 		this.id = id; | ||||
| 	public TableCoversUUIDUUID(final UUID uuid, final List<UUID> covers) { | ||||
| 		this.uuid = uuid; | ||||
| 		this.covers = covers; | ||||
| 	} | ||||
|  | ||||
| 	@Column(nullable = false) | ||||
| 	@Id | ||||
| 	public UUID id; | ||||
| 	public UUID uuid; | ||||
| 	@DataJson() | ||||
| 	@Column(nullable = false) | ||||
| 	public List<UUID> covers; | ||||
|  | ||||
| } | ||||
|   | ||||
							
								
								
									
										137
									
								
								src/org/kar/archidata/dataAccess/exportTools/README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										137
									
								
								src/org/kar/archidata/dataAccess/exportTools/README.md
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,137 @@ | ||||
| Archi-data | ||||
| ========== | ||||
|  | ||||
| Archi-data is a framework that simplify: | ||||
|   - Creating a REST server with: | ||||
|     - Right control | ||||
|     - Swagger display interface | ||||
|     - Normalize error generate by the server | ||||
|   - Access to the DB: | ||||
|      - introspect Object and insert in the TD (SQLITE & MY-SQL) | ||||
|      - Manage migration | ||||
|   - JPA checker for many generic request | ||||
|   - simplify the request of the Test-service | ||||
|    | ||||
|  | ||||
| Documentation: | ||||
| -------------- | ||||
|  | ||||
| The documentation is available [here](doc/index.md)  | ||||
|    | ||||
| Develop in cmd-line: | ||||
| -------------------- | ||||
|  | ||||
| The first step is configuring your JAVA version (or select the JVM with the OS) | ||||
|  | ||||
| ```bash | ||||
| export PATH=$(ls -d --color=never /usr/lib/jvm/java-2*-openjdk)/bin:$PATH | ||||
| ``` | ||||
|  | ||||
| Install the dependency: | ||||
|  | ||||
| ```bash | ||||
| mvn install | ||||
| ``` | ||||
|  | ||||
| Run the test | ||||
| ```bash | ||||
| mvn test | ||||
| ``` | ||||
|  | ||||
| Install it for external use | ||||
| ```bash | ||||
| mvn install | ||||
| ``` | ||||
|  | ||||
| Develop With Eclipse: | ||||
| -------------------- | ||||
|  | ||||
| Import the project: | ||||
|   - Open a (new) project on eclipse | ||||
|   - `File` -> `Import` | ||||
|     - `Maven` -> `Existing Maven project` | ||||
|     - Select the `pom.xml` file and click on import | ||||
|  | ||||
| Run the Test: | ||||
|   - Open the package `test.kar.archidata` | ||||
|   - Click right on it | ||||
|   - Select `Debug As` -> `JUnit Test` | ||||
|  | ||||
| Install in the local maven repository: | ||||
|   - Click right on the `pom.xml` file | ||||
|   - Select `Run As` -> `Maven install` | ||||
|  | ||||
|  | ||||
| Some tools: | ||||
| ============ | ||||
|  | ||||
| Auto-update dependency: | ||||
| ----------------------- | ||||
|  | ||||
| Auto-update to the last version dependency: | ||||
|  | ||||
| ```bash | ||||
| mvn versions:use-latest-versions | ||||
| ``` | ||||
|  | ||||
| Format the code | ||||
| --------------- | ||||
|  | ||||
| Simply run the cmd-line: | ||||
|  | ||||
| ```bash | ||||
| mvn formatter:format | ||||
| ``` | ||||
|  | ||||
| Reformat XML file like the pom.xml | ||||
|  | ||||
| ```bash | ||||
| XMLLINT_INDENT="	" xmllint  --format "back/pom.xml" -o "back/pom.xml" | ||||
| ``` | ||||
|  | ||||
| Enable the pre-commit checker | ||||
| ----------------------------- | ||||
|  | ||||
| ```bash | ||||
| ./tools/configure_precommit.bash | ||||
| ``` | ||||
|  | ||||
| > **_Note_**: You can change the code in `.git/hooks/pre-commit` by replacing `formatter:verify` with `formatter:format` to auto format the code @ every commit | ||||
|  | ||||
|  | ||||
|  | ||||
| Add Gitea in the dependency for the registry: | ||||
| ============================================= | ||||
|  | ||||
| Read instruction for tocken in ~/.m2/setting.xml | ||||
|  | ||||
| edit file: ```~/.m2/settings.xml```  | ||||
|  | ||||
| ```xml | ||||
| <settings> | ||||
|   <servers> | ||||
|     <server> | ||||
|       <id>gitea</id> | ||||
|       <configuration> | ||||
|         <httpHeaders> | ||||
|           <property> | ||||
|             <name>Authorization</name> | ||||
|             <value>token xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</value> | ||||
|           </property> | ||||
|         </httpHeaders> | ||||
|       </configuration> | ||||
|     </server> | ||||
|   </servers> | ||||
| </settings> | ||||
| ``` | ||||
|  | ||||
| release: | ||||
| ======== | ||||
|  | ||||
| ```bash | ||||
| export PATH=$(ls -d --color=never /usr/lib/jvm/java-2*-openjdk)/bin:$PATH | ||||
| mvn install | ||||
| mvn deploy | ||||
| ``` | ||||
|  | ||||
|  | ||||
| @@ -1,7 +1,5 @@ | ||||
| package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
|  | ||||
| /** This option permit to access on deleted items of a table */ | ||||
| public class AccessDeletedItems extends QueryOption { | ||||
| 	public AccessDeletedItems() {} | ||||
|   | ||||
| @@ -1,7 +1,5 @@ | ||||
| package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
|  | ||||
| /** By default some element are not read like createAt and UpdatedAt. This option permit to read it. */ | ||||
| public class CheckFunction extends QueryOption { | ||||
| 	private final CheckFunctionInterface checker; | ||||
|   | ||||
| @@ -3,6 +3,7 @@ package org.kar.archidata.dataAccess.options; | ||||
| import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.annotation.AnnotationTools; | ||||
| import org.kar.archidata.dataAccess.QueryOptions; | ||||
|  | ||||
| /** By default some element are not read like createAt and UpdatedAt. This option permit to read it. */ | ||||
| public interface CheckFunctionInterface { | ||||
| @@ -11,10 +12,11 @@ public interface CheckFunctionInterface { | ||||
| 	 * @param data The object that might be injected. | ||||
| 	 * @param filterValue List of fields that might be check. If null, then all column must be checked. | ||||
| 	 * @throws Exception Exception is generate if the data are incorrect. */ | ||||
| 	void check(final String baseName, Object data, List<String> filterValue) throws Exception; | ||||
| 	void check(final String baseName, Object data, List<String> filterValue, final QueryOptions options) | ||||
| 			throws Exception; | ||||
|  | ||||
| 	default void checkAll(final String baseName, final Object data) throws Exception { | ||||
| 		check(baseName, data, AnnotationTools.getAllFieldsNames(data.getClass())); | ||||
| 	default void checkAll(final String baseName, final Object data, final QueryOptions options) throws Exception { | ||||
| 		check(baseName, data, AnnotationTools.getAllFieldsNames(data.getClass()), options); | ||||
| 	} | ||||
|  | ||||
| } | ||||
|   | ||||
| @@ -2,10 +2,16 @@ package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOptions; | ||||
|  | ||||
| /** By default some element are not read like createAt and UpdatedAt. This option permit to read it. */ | ||||
| public class CheckFunctionVoid implements CheckFunctionInterface { | ||||
| 	@Override | ||||
| 	public void check(final String baseName, Object data, List<String> filterValue) { | ||||
| 	public void check( | ||||
| 			final String baseName, | ||||
| 			final Object data, | ||||
| 			final List<String> filterValue, | ||||
| 			final QueryOptions options) { | ||||
|  | ||||
| 	} | ||||
|  | ||||
|   | ||||
| @@ -16,6 +16,7 @@ import org.kar.archidata.annotation.AnnotationTools; | ||||
| import org.kar.archidata.annotation.DataJson; | ||||
| import org.kar.archidata.dataAccess.DataAccess; | ||||
| import org.kar.archidata.dataAccess.QueryCondition; | ||||
| import org.kar.archidata.dataAccess.QueryOptions; | ||||
| import org.kar.archidata.exception.DataAccessException; | ||||
| import org.kar.archidata.exception.InputException; | ||||
| import org.slf4j.Logger; | ||||
| @@ -37,7 +38,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 		 * @param data The object that might be injected. | ||||
| 		 * @param filterValue List of fields that might be check. If null, then all column must be checked. | ||||
| 		 * @throws Exception Exception is generate if the data are incorrect. */ | ||||
| 		void check(final String baseName, final K data) throws Exception; | ||||
| 		void check(final String baseName, final K data, final QueryOptions options) throws Exception; | ||||
| 	} | ||||
|  | ||||
| 	protected Map<String, List<CheckInterface<T>>> checking = null; | ||||
| @@ -66,20 +67,20 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 			for (final Field field : this.clazz.getFields()) { | ||||
| 				final String fieldName = field.getName(); // AnnotationTools.getFieldName(field); | ||||
| 				if (AnnotationTools.isPrimaryKey(field)) { | ||||
| 					add(fieldName, (final String baseName, final T data) -> { | ||||
| 					add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 						throw new InputException(baseName + fieldName, | ||||
| 								"This is a '@Id' (primaryKey) ==> can not be change"); | ||||
| 					}); | ||||
| 				} | ||||
| 				if (AnnotationTools.getConstraintsNotNull(field)) { | ||||
| 					add(fieldName, (final String baseName, final T data) -> { | ||||
| 					add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 						if (field.get(data) == null) { | ||||
| 							throw new InputException(baseName + fieldName, "Can not be null"); | ||||
| 						} | ||||
| 					}); | ||||
| 				} | ||||
| 				if (AnnotationTools.isCreatedAtField(field) || AnnotationTools.isUpdateAtField(field)) { | ||||
| 					add(fieldName, (final String baseName, final T data) -> { | ||||
| 					add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 						throw new InputException(baseName + fieldName, "It is forbidden to change this field"); | ||||
| 					}); | ||||
| 				} | ||||
| @@ -88,7 +89,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 				if (type == Long.class || type == long.class) { | ||||
| 					final Long maxValue = AnnotationTools.getConstraintsMax(field); | ||||
| 					if (maxValue != null) { | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -101,7 +102,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					} | ||||
| 					final Long minValue = AnnotationTools.getConstraintsMin(field); | ||||
| 					if (minValue != null) { | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -114,12 +115,16 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					} | ||||
| 					final ManyToOne annotationManyToOne = AnnotationTools.getManyToOne(field); | ||||
| 					if (annotationManyToOne != null && annotationManyToOne.targetEntity() != null) { | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| 							} | ||||
| 							final long count = DataAccess.count(annotationManyToOne.targetEntity(), elem); | ||||
| 							final List<ConditionChecker> condCheckers = options.get(ConditionChecker.class); | ||||
| 							final Condition conditionCheck = condCheckers.isEmpty() ? null | ||||
| 									: condCheckers.get(0).toCondition(); | ||||
| 							final long count = DataAccess.count(annotationManyToOne.targetEntity(), elem, | ||||
| 									conditionCheck); | ||||
| 							if (count == 0) { | ||||
| 								throw new InputException(baseName + fieldName, | ||||
| 										"Foreign element does not exist in the DB:" + elem); | ||||
| @@ -131,7 +136,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					final Long maxValueRoot = AnnotationTools.getConstraintsMax(field); | ||||
| 					if (maxValueRoot != null) { | ||||
| 						final int maxValue = maxValueRoot.intValue(); | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -145,7 +150,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					final Long minValueRoot = AnnotationTools.getConstraintsMin(field); | ||||
| 					if (minValueRoot != null) { | ||||
| 						final int minValue = minValueRoot.intValue(); | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -158,7 +163,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					} | ||||
| 					final ManyToOne annotationManyToOne = AnnotationTools.getManyToOne(field); | ||||
| 					if (annotationManyToOne != null && annotationManyToOne.targetEntity() != null) { | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -173,7 +178,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 				} else if (type == UUID.class) { | ||||
| 					final ManyToOne annotationManyToOne = AnnotationTools.getManyToOne(field); | ||||
| 					if (annotationManyToOne != null && annotationManyToOne.targetEntity() != null) { | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -191,7 +196,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					final Long maxValueRoot = AnnotationTools.getConstraintsMax(field); | ||||
| 					if (maxValueRoot != null) { | ||||
| 						final float maxValue = maxValueRoot.floatValue(); | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -205,7 +210,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					final Long minValueRoot = AnnotationTools.getConstraintsMin(field); | ||||
| 					if (minValueRoot != null) { | ||||
| 						final float minValue = minValueRoot.floatValue(); | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -220,7 +225,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					final Long maxValueRoot = AnnotationTools.getConstraintsMax(field); | ||||
| 					if (maxValueRoot != null) { | ||||
| 						final double maxValue = maxValueRoot.doubleValue(); | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -234,7 +239,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					final Long minValueRoot = AnnotationTools.getConstraintsMin(field); | ||||
| 					if (minValueRoot != null) { | ||||
| 						final double minValue = minValueRoot.doubleValue(); | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -254,7 +259,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 				} else if (type == String.class) { | ||||
| 					final int maxSizeString = AnnotationTools.getLimitSize(field); | ||||
| 					if (maxSizeString > 0) { | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -268,7 +273,7 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 					} | ||||
| 					final Size limitSize = AnnotationTools.getConstraintsSize(field); | ||||
| 					if (limitSize != null) { | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -280,14 +285,14 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 							} | ||||
| 							if (elemTyped.length() < limitSize.min()) { | ||||
| 								throw new InputException(baseName + fieldName, | ||||
| 										"Too small size (constraints) must be >= " + limitSize.max()); | ||||
| 										"Too small size (constraints) must be >= " + limitSize.min()); | ||||
| 							} | ||||
| 						}); | ||||
| 					} | ||||
| 					final String patternString = AnnotationTools.getConstraintsPattern(field); | ||||
| 					if (patternString != null) { | ||||
| 						final Pattern pattern = Pattern.compile(patternString); | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							final Object elem = field.get(data); | ||||
| 							if (elem == null) { | ||||
| 								return; | ||||
| @@ -306,8 +311,8 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 						// Here if we have an error it crash at start and no new instance after creation... | ||||
| 						final CheckFunctionInterface instance = jsonAnnotation.checker().getDeclaredConstructor() | ||||
| 								.newInstance(); | ||||
| 						add(fieldName, (final String baseName, final T data) -> { | ||||
| 							instance.checkAll(baseName + fieldName + ".", field.get(data)); | ||||
| 						add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 							instance.checkAll(baseName + fieldName + ".", field.get(data), options); | ||||
| 						}); | ||||
| 					} | ||||
| 				} else if (type.isEnum()) { | ||||
| @@ -316,9 +321,17 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 				// keep this is last ==> take more time... | ||||
| 				if (AnnotationTools.isUnique(field)) { | ||||
| 					// Create the request ... | ||||
| 					add(fieldName, (final String baseName, final T data) -> { | ||||
| 						final Object other = DataAccess.getWhere(this.clazz, | ||||
| 					add(fieldName, (final String baseName, final T data, final QueryOptions options) -> { | ||||
| 						final List<ConditionChecker> condCheckers = options.get(ConditionChecker.class); | ||||
| 						Object other = null; | ||||
| 						if (condCheckers.isEmpty()) { | ||||
| 							other = DataAccess.getWhere(this.clazz, | ||||
| 									new Condition(new QueryCondition(fieldName, "==", field.get(data)))); | ||||
| 						} else { | ||||
| 							other = DataAccess.getWhere(this.clazz, | ||||
| 									new Condition(new QueryCondition(fieldName, "==", field.get(data))), | ||||
| 									condCheckers.get(0).toCondition()); | ||||
| 						} | ||||
| 						if (other != null) { | ||||
| 							throw new InputException(baseName + fieldName, "Name already exist in the DB"); | ||||
| 						} | ||||
| @@ -333,7 +346,11 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public void check(final String baseName, final Object data, final List<String> filterValue) throws Exception { | ||||
| 	public void check( | ||||
| 			final String baseName, | ||||
| 			final Object data, | ||||
| 			final List<String> filterValue, | ||||
| 			final QueryOptions options) throws Exception { | ||||
| 		if (this.checking == null) { | ||||
| 			initialize(); | ||||
| 		} | ||||
| @@ -348,13 +365,13 @@ public class CheckJPA<T> implements CheckFunctionInterface { | ||||
| 				continue; | ||||
| 			} | ||||
| 			for (final CheckInterface<T> action : actions) { | ||||
| 				action.check(baseName, dataCasted); | ||||
| 				action.check(baseName, dataCasted, options); | ||||
| 			} | ||||
| 		} | ||||
| 		checkTyped(dataCasted, filterValue); | ||||
| 		checkTyped(dataCasted, filterValue, options); | ||||
| 	} | ||||
|  | ||||
| 	public void checkTyped(final T data, final List<String> filterValue) throws Exception { | ||||
| 	public void checkTyped(final T data, final List<String> filterValue, final QueryOptions options) throws Exception { | ||||
| 		// nothing to do ... | ||||
| 	} | ||||
| } | ||||
|   | ||||
| @@ -4,7 +4,6 @@ import java.sql.PreparedStatement; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.CountInOut; | ||||
| import org.kar.archidata.dataAccess.QueryItem; | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
| import org.kar.archidata.dataAccess.QueryOptions; | ||||
|  | ||||
| /** By default some element are not read like createAt and UpdatedAt. This option permit to read it. */ | ||||
|   | ||||
| @@ -0,0 +1,25 @@ | ||||
| package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryItem; | ||||
|  | ||||
| /** Condition model apply to the check models. */ | ||||
| public class ConditionChecker extends QueryOption { | ||||
| 	public final QueryItem condition; | ||||
|  | ||||
| 	public ConditionChecker(final QueryItem items) { | ||||
| 		this.condition = items; | ||||
| 	} | ||||
|  | ||||
| 	public ConditionChecker(final Condition cond) { | ||||
| 		this.condition = cond.condition; | ||||
| 	} | ||||
|  | ||||
| 	public ConditionChecker() { | ||||
| 		this.condition = null; | ||||
| 	} | ||||
|  | ||||
| 	public Condition toCondition() { | ||||
| 		return new Condition(this.condition); | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -1,7 +1,5 @@ | ||||
| package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
|  | ||||
| /** This option permit to create the DROP `Table` IF EXIST in the generation of structure. */ | ||||
| public class CreateDropTable extends QueryOption { | ||||
| 	public CreateDropTable() {} | ||||
|   | ||||
| @@ -4,7 +4,6 @@ import java.io.IOException; | ||||
| import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.GlobalConfiguration; | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
| import org.kar.archidata.dataAccess.QueryOptions; | ||||
| import org.kar.archidata.db.DBConfig; | ||||
| import org.kar.archidata.db.DBEntry; | ||||
| @@ -37,6 +36,9 @@ public class DBInterfaceOption extends QueryOption { | ||||
| 	} | ||||
|  | ||||
| 	public static DBEntry getAutoEntry(final QueryOptions options) throws IOException { | ||||
| 		if (options == null) { | ||||
| 			return DBEntry.createInterface(GlobalConfiguration.dbConfig, false); | ||||
| 		} | ||||
| 		final List<DBInterfaceOption> dbOption = options.get(DBInterfaceOption.class); | ||||
| 		if (dbOption.size() == 0) { | ||||
| 			final List<DBInterfaceRoot> isRoot = options.get(DBInterfaceRoot.class); | ||||
|   | ||||
| @@ -1,7 +1,5 @@ | ||||
| package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
|  | ||||
| public class DBInterfaceRoot extends QueryOption { | ||||
| 	private final boolean root; | ||||
|  | ||||
|   | ||||
| @@ -2,8 +2,6 @@ package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
|  | ||||
| /** By default some element are not read like createAt and UpdatedAt. This option permit to read it. */ | ||||
| public class FilterValue extends QueryOption { | ||||
| 	public final List<String> filterValue; | ||||
|   | ||||
| @@ -1,8 +1,10 @@ | ||||
| package org.kar.archidata.dataAccess; | ||||
| package org.kar.archidata.dataAccess.options; | ||||
| 
 | ||||
| import java.sql.PreparedStatement; | ||||
| import java.util.List; | ||||
| 
 | ||||
| import org.kar.archidata.dataAccess.CountInOut; | ||||
| 
 | ||||
| public class GroupBy extends QueryOption { | ||||
| 	protected final List<String> childs; | ||||
| 
 | ||||
| @@ -1,7 +1,10 @@ | ||||
| package org.kar.archidata.dataAccess; | ||||
| package org.kar.archidata.dataAccess.options; | ||||
| 
 | ||||
| import java.sql.PreparedStatement; | ||||
| 
 | ||||
| import org.kar.archidata.dataAccess.CountInOut; | ||||
| import org.kar.archidata.dataAccess.DataAccess; | ||||
| 
 | ||||
| public class Limit extends QueryOption { | ||||
| 	protected final long limit; | ||||
| 
 | ||||
| @@ -1,8 +1,10 @@ | ||||
| package org.kar.archidata.dataAccess; | ||||
| package org.kar.archidata.dataAccess.options; | ||||
| 
 | ||||
| import java.sql.PreparedStatement; | ||||
| import java.util.List; | ||||
| 
 | ||||
| import org.kar.archidata.dataAccess.CountInOut; | ||||
| 
 | ||||
| public class OrderBy extends QueryOption { | ||||
| 	protected final List<OrderItem> childs; | ||||
| 
 | ||||
| @@ -1,4 +1,4 @@ | ||||
| package org.kar.archidata.dataAccess; | ||||
| package org.kar.archidata.dataAccess.options; | ||||
| 
 | ||||
| public class OrderItem { | ||||
| 	public enum Order { | ||||
| @@ -1,7 +1,5 @@ | ||||
| package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
|  | ||||
| /** Option that permit to access to a table structure with an other name that is define in the structure. Note: Internal use for link tables (see: | ||||
|  * org.kar.archidata.dataAccess.addOn.model.LinkTable). */ | ||||
| public class OverrideTableName extends QueryOption { | ||||
|   | ||||
| @@ -0,0 +1,3 @@ | ||||
| package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| public class QueryOption {} | ||||
| @@ -1,7 +1,5 @@ | ||||
| package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
|  | ||||
| /** By default some element are not read like createAt and UpdatedAt. This option permit to read it. */ | ||||
| public class ReadAllColumn extends QueryOption { | ||||
| 	public ReadAllColumn() {} | ||||
|   | ||||
| @@ -1,7 +1,5 @@ | ||||
| package org.kar.archidata.dataAccess.options; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.QueryOption; | ||||
|  | ||||
| /** Internal option that permit to transmit the Key when updating the ManyToMany values (first step). */ | ||||
| public class TransmitKey extends QueryOption { | ||||
| 	private final Object key; | ||||
|   | ||||
| @@ -1,19 +1,34 @@ | ||||
| package org.kar.archidata.exception; | ||||
|  | ||||
| import org.kar.archidata.api.DataResource; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import jakarta.ws.rs.core.Response; | ||||
|  | ||||
| public class FailException extends Exception { | ||||
| 	private static final Logger LOGGER = LoggerFactory.getLogger(DataResource.class); | ||||
| 	private static final long serialVersionUID = 1L; | ||||
| 	public final Response.Status status; | ||||
| 	public final Exception exception; | ||||
|  | ||||
| 	public FailException(final Response.Status status, final String message) { | ||||
| 		super(message); | ||||
| 		this.status = status; | ||||
| 		this.exception = null; | ||||
| 	} | ||||
|  | ||||
| 	public FailException(final Response.Status status, final String message, final Exception ex) { | ||||
| 		super(message); | ||||
| 		this.status = status; | ||||
| 		this.exception = ex; | ||||
| 		ex.printStackTrace(); | ||||
| 		LOGGER.error("Generate Fail exception with exceptionData: {}", ex.getMessage()); | ||||
| 	} | ||||
|  | ||||
| 	public FailException(final String message) { | ||||
| 		super(message); | ||||
| 		this.status = Response.Status.BAD_REQUEST; | ||||
|  | ||||
| 		this.exception = null; | ||||
| 	} | ||||
| } | ||||
|   | ||||
							
								
								
									
										74
									
								
								src/org/kar/archidata/externalRestApi/AnalyzeApi.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										74
									
								
								src/org/kar/archidata/externalRestApi/AnalyzeApi.java
									
									
									
									
									
										Normal 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; | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										232
									
								
								src/org/kar/archidata/externalRestApi/DotGenerateApi.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										232
									
								
								src/org/kar/archidata/externalRestApi/DotGenerateApi.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,232 @@ | ||||
| package org.kar.archidata.externalRestApi; | ||||
|  | ||||
| import java.io.FileWriter; | ||||
| import java.io.InputStream; | ||||
| import java.sql.Timestamp; | ||||
| import java.time.Instant; | ||||
| import java.time.LocalDate; | ||||
| import java.time.LocalTime; | ||||
| import java.util.ArrayList; | ||||
| import java.util.Date; | ||||
| import java.util.List; | ||||
| import java.util.Map; | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.glassfish.jersey.media.multipart.ContentDisposition; | ||||
| import org.glassfish.jersey.media.multipart.FormDataContentDisposition; | ||||
| import org.kar.archidata.catcher.RestErrorResponse; | ||||
| import org.kar.archidata.externalRestApi.dot.DotApiGeneration; | ||||
| import org.kar.archidata.externalRestApi.dot.DotClassElement; | ||||
| import org.kar.archidata.externalRestApi.dot.DotClassElement.DefinedPosition; | ||||
| import org.kar.archidata.externalRestApi.dot.DotClassElementGroup; | ||||
| import org.kar.archidata.externalRestApi.model.ApiGroupModel; | ||||
| import org.kar.archidata.externalRestApi.model.ClassModel; | ||||
|  | ||||
| public class DotGenerateApi { | ||||
|  | ||||
| 	public static void generateApi(final AnalyzeApi api, final String pathDotFile) throws Exception { | ||||
| 		final List<DotClassElement> localModel = generateApiModel(api); | ||||
| 		final DotClassElementGroup dotGroup = new DotClassElementGroup(localModel); | ||||
|  | ||||
| 		try (final FileWriter myWriter = new FileWriter(pathDotFile)) { | ||||
| 			myWriter.write(""" | ||||
| 					# Architecture auto-generated file | ||||
| 					digraph UML_Class_diagram { | ||||
| 					    #rankdir=NS; | ||||
| 						graph [ | ||||
| 							pad="0.5" | ||||
| 							nodesep="1" | ||||
| 							#ranksep="2" | ||||
| 							label="Rest API server Model" | ||||
| 							labelloc="t" | ||||
| 							fontname="FreeMono,Sans-Mono,Helvetica,Arial,sans-serif" | ||||
| 						] | ||||
| 						node [ | ||||
| 							fontname="FreeMono,Sans-Mono,Helvetica,Arial,sans-serif" | ||||
| 							shape=record | ||||
| 							style=filled | ||||
| 							fillcolor=gray95 | ||||
| 						] | ||||
| 						edge [fontname="FreeMono,Sans-Mono,Helvetica,Arial,sans-serif"] | ||||
| 					"""); | ||||
| 			/* | ||||
| 			myWriter.write(""" | ||||
| 						subgraph REST_API { | ||||
| 						style=filled; | ||||
| 						color=lightgrey; | ||||
| 						label="REST API"; | ||||
| 					    rankdir=LR; | ||||
| 					"""); | ||||
| 			*/ | ||||
| 			for (final ApiGroupModel element : api.apiModels) { | ||||
| 				final String tmp = DotApiGeneration.generateApiFile(element, dotGroup); | ||||
| 				myWriter.write(tmp); | ||||
| 				myWriter.write("\n"); | ||||
| 			} | ||||
| 			// create an invisible link to force all element to be link together: | ||||
| 			if (false) { | ||||
| 				String previous = null; | ||||
| 				for (final ApiGroupModel element : api.apiModels) { | ||||
| 					if (previous == null) { | ||||
| 						previous = element.name; | ||||
| 						continue; | ||||
| 					} | ||||
| 					myWriter.write("\t{ "); | ||||
| 					myWriter.write(previous); | ||||
| 					myWriter.write(":s -> "); | ||||
| 					previous = element.name; | ||||
| 					myWriter.write(previous); | ||||
| 					myWriter.write(":n [style=invis]}\n"); | ||||
| 				} | ||||
| 			} | ||||
| 			/* | ||||
| 			myWriter.write(""" | ||||
| 						} | ||||
| 					"""); | ||||
| 			myWriter.write(""" | ||||
| 						subgraph Models { | ||||
| 						style=filled; | ||||
| 						color=lightgrey; | ||||
| 						label="Models"; | ||||
| 					    rankdir=NS; | ||||
| 					"""); | ||||
| 			*/ | ||||
| 			// Generates all MODEL files | ||||
| 			for (final DotClassElement element : localModel) { | ||||
| 				final String tmp = element.generateFile(dotGroup); | ||||
| 				myWriter.write(tmp); | ||||
| 				myWriter.write("\n"); | ||||
| 			} | ||||
| 			/* | ||||
| 			myWriter.write(""" | ||||
| 						} | ||||
| 					"""); | ||||
| 			*/ | ||||
| 			myWriter.write(""" | ||||
| 					} | ||||
| 					"""); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	private static List<DotClassElement> generateApiModel(final AnalyzeApi api) throws Exception { | ||||
| 		// First step is to add all specific basic elements the wrap correctly the model | ||||
| 		final List<DotClassElement> dotModels = new ArrayList<>(); | ||||
| 		List<ClassModel> models = api.getCompatibleModels(List.of(Void.class, void.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "void", "void", null, null, DefinedPosition.NATIVE)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Object.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "Object", "object", null, "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) { | ||||
| 			dotModels.add(new DotClassElement(models, "Object", "any", null, null, DefinedPosition.NATIVE)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(String.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "String", "string", null, "String", DefinedPosition.NATIVE)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels( | ||||
| 				List.of(InputStream.class, FormDataContentDisposition.class, ContentDisposition.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "File", "File", null, "File", DefinedPosition.NATIVE)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Boolean.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "Boolean", "boolean", null, "Boolean", DefinedPosition.NATIVE)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(boolean.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "boolean", "boolean", null, "boolean", DefinedPosition.NATIVE)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(UUID.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "UUID", "UUID", "isUUID", "UUID", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(long.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "long", "Long", "isLong", "long", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Long.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "Long", "Long", "isLong", "Long", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(short.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "short", "Short", "isShort", "short", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Short.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "Short", "Short", "isShort", "Short", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(int.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "int", "Integer", "isInteger", "int", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Integer.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add( | ||||
| 					new DotClassElement(models, "Integer", "Integer", "isInteger", "Integer", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(double.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "Double", "Double", "isDouble", "double", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Double.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "Double", "Double", "isDouble", "Double", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(float.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "float", "Float", "isFloat", "float", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Float.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "Float", "Float", "isFloat", "Float", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Instant.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add( | ||||
| 					new DotClassElement(models, "Instant", "Instant", "isInstant", "Instant", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Date.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "Date", "IsoDate", "isIsoDate", "Date", DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(Timestamp.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "Timestamp", "Timestamp", "isTimestamp", "Timestamp", | ||||
| 					DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(LocalDate.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "LocalDate", "LocalDate", "isLocalDate", "LocalDate", | ||||
| 					DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		models = api.getCompatibleModels(List.of(LocalTime.class)); | ||||
| 		if (models != null) { | ||||
| 			dotModels.add(new DotClassElement(models, "LocalTime", "LocalTime", "isLocalTime", "LocalTime", | ||||
| 					DefinedPosition.BASIC)); | ||||
| 		} | ||||
| 		// needed for Rest interface | ||||
| 		api.addModel(RestErrorResponse.class); | ||||
| 		for (final ClassModel model : api.getAllModel()) { | ||||
| 			boolean alreadyExist = false; | ||||
| 			for (final DotClassElement elem : dotModels) { | ||||
| 				if (elem.isCompatible(model)) { | ||||
| 					alreadyExist = true; | ||||
| 					break; | ||||
| 				} | ||||
| 			} | ||||
| 			if (alreadyExist) { | ||||
| 				continue; | ||||
| 			} | ||||
| 			dotModels.add(new DotClassElement(model)); | ||||
| 		} | ||||
| 		return dotModels; | ||||
|  | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -0,0 +1,8 @@ | ||||
| package org.kar.archidata.externalRestApi; | ||||
|  | ||||
| public class PythonGenerateApi { | ||||
|  | ||||
| 	public static void generateApi(final AnalyzeApi api) { | ||||
|  | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										242
									
								
								src/org/kar/archidata/externalRestApi/TsGenerateApi.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										242
									
								
								src/org/kar/archidata/externalRestApi/TsGenerateApi.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,242 @@ | ||||
| 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.glassfish.jersey.media.multipart.ContentDisposition; | ||||
| import org.glassfish.jersey.media.multipart.FormDataContentDisposition; | ||||
| import org.kar.archidata.catcher.RestErrorResponse; | ||||
| import org.kar.archidata.externalRestApi.model.ApiGroupModel; | ||||
| import org.kar.archidata.externalRestApi.model.ClassModel; | ||||
| import org.kar.archidata.externalRestApi.typescript.TsApiGeneration; | ||||
| import org.kar.archidata.externalRestApi.typescript.TsClassElement; | ||||
| import org.kar.archidata.externalRestApi.typescript.TsClassElement.DefinedPosition; | ||||
| import org.kar.archidata.externalRestApi.typescript.TsClassElementGroup; | ||||
|  | ||||
| public class TsGenerateApi { | ||||
| 	/** | ||||
| 	 * Generate a full API tree for Typescript in a specific folder. | ||||
| 	 * This generate a folder containing a full API with "model" filder and "api" folder. | ||||
| 	 * The generation depend of Zod and can be strict compile. | ||||
| 	 * @param api Data model to generate the api | ||||
| 	 * @param pathPackage Path to store the api. | ||||
| 	 */ | ||||
| 	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.any()", "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, FormDataContentDisposition.class, ContentDisposition.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 = TsGenerateApi.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(); | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										414
									
								
								src/org/kar/archidata/externalRestApi/dot/DotApiGeneration.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										414
									
								
								src/org/kar/archidata/externalRestApi/dot/DotApiGeneration.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,414 @@ | ||||
| package org.kar.archidata.externalRestApi.dot; | ||||
|  | ||||
| import java.io.IOException; | ||||
| import java.util.ArrayList; | ||||
| import java.util.HashSet; | ||||
| import java.util.List; | ||||
| import java.util.Map.Entry; | ||||
| import java.util.Set; | ||||
|  | ||||
| import org.kar.archidata.externalRestApi.dot.DotClassElement.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.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| public class DotApiGeneration { | ||||
| 	static final Logger LOGGER = LoggerFactory.getLogger(DotApiGeneration.class); | ||||
|  | ||||
| 	public static String generateClassEnumModelTypescript( | ||||
| 			final ClassEnumModel model, | ||||
| 			final DotClassElementGroup dotGroup, | ||||
| 			final Set<ClassModel> imports) throws IOException { | ||||
| 		imports.add(model); | ||||
| 		final DotClassElement dotModel = dotGroup.find(model); | ||||
| 		return dotModel.dotTypeName; | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassObjectModelTypescript( | ||||
| 			final ClassObjectModel model, | ||||
| 			final DotClassElementGroup dotGroup, | ||||
| 			final Set<ClassModel> imports) throws IOException { | ||||
| 		final DotClassElement dotModel = dotGroup.find(model); | ||||
| 		if (dotModel.nativeType != DefinedPosition.NATIVE) { | ||||
| 			imports.add(model); | ||||
| 		} | ||||
| 		if (dotModel.nativeType != DefinedPosition.NORMAL) { | ||||
| 			return dotModel.dotTypeName; | ||||
| 		} | ||||
| 		return dotModel.dotTypeName; | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassMapModelTypescript( | ||||
| 			final ClassMapModel model, | ||||
| 			final DotClassElementGroup dotGroup, | ||||
| 			final Set<ClassModel> imports) throws IOException { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		out.append("Map<"); | ||||
| 		out.append(generateClassModelTypescript(model.keyModel, dotGroup, imports)); | ||||
| 		out.append(", "); | ||||
| 		out.append(generateClassModelTypescript(model.valueModel, dotGroup, imports)); | ||||
| 		out.append(">"); | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassListModelTypescript( | ||||
| 			final ClassListModel model, | ||||
| 			final DotClassElementGroup dotGroup, | ||||
| 			final Set<ClassModel> imports) throws IOException { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		out.append("List<"); | ||||
| 		out.append(generateClassModelTypescript(model.valueModel, dotGroup, imports)); | ||||
| 		out.append(">"); | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassModelTypescript( | ||||
| 			final ClassModel model, | ||||
| 			final DotClassElementGroup dotGroup, | ||||
| 			final Set<ClassModel> imports) throws IOException { | ||||
| 		if (model instanceof final ClassObjectModel objectModel) { | ||||
| 			return generateClassObjectModelTypescript(objectModel, dotGroup, imports); | ||||
| 		} | ||||
| 		if (model instanceof final ClassListModel listModel) { | ||||
| 			return generateClassListModelTypescript(listModel, dotGroup, imports); | ||||
| 		} | ||||
| 		if (model instanceof final ClassMapModel mapModel) { | ||||
| 			return generateClassMapModelTypescript(mapModel, dotGroup, imports); | ||||
| 		} | ||||
| 		if (model instanceof final ClassEnumModel enumModel) { | ||||
| 			return generateClassEnumModelTypescript(enumModel, dotGroup, imports); | ||||
| 		} | ||||
| 		throw new IOException("Impossible model:" + model); | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassModelsTypescript( | ||||
| 			final List<ClassModel> models, | ||||
| 			final DotClassElementGroup dotGroup) throws IOException { | ||||
| 		if (models.size() == 0) { | ||||
| 			return "void"; | ||||
| 		} | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		if (models.size() > 1) { | ||||
| 			out.append("Union<"); | ||||
| 		} | ||||
| 		boolean isFirst = true; | ||||
| 		for (final ClassModel model : models) { | ||||
| 			if (isFirst) { | ||||
| 				isFirst = false; | ||||
| 			} else { | ||||
| 				out.append(", "); | ||||
| 			} | ||||
| 			final String data = DotClassElement.generateClassModelTypescript(model, dotGroup); | ||||
| 			out.append(data); | ||||
| 		} | ||||
| 		if (models.size() > 1) { | ||||
| 			out.append(">"); | ||||
| 		} | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public static List<String> generateClassModelsLinks( | ||||
| 			final List<ClassModel> models, | ||||
| 			final DotClassElementGroup dotGroup) throws IOException { | ||||
| 		if (models.size() == 0) { | ||||
| 			return null; | ||||
| 		} | ||||
| 		final List<String> out = new ArrayList<>(); | ||||
| 		final boolean isFirst = true; | ||||
| 		for (final ClassModel model : models) { | ||||
| 			final String data = DotClassElement.generateClassModelTypescriptLink(model, dotGroup); | ||||
| 			if (data != null) { | ||||
| 				out.add(data); | ||||
| 			} | ||||
| 		} | ||||
| 		return out; | ||||
| 	} | ||||
|  | ||||
| 	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 String generateApiFile(final ApiGroupModel element, final DotClassElementGroup dotGroup) | ||||
| 			throws IOException { | ||||
| 		final StringBuilder data = new StringBuilder(); | ||||
| 		final StringBuilder outLinks = new StringBuilder(); | ||||
| 		data.append(""" | ||||
| 					%s [ | ||||
| 						shape=plain | ||||
| 						label=<<table color="#FF3333" border="2" cellborder="1" cellspacing="0" cellpadding="4"> | ||||
| 						<tr> | ||||
| 							<td><b>%s</b><br/>(REST)</td> | ||||
| 						</tr> | ||||
| 						<tr> | ||||
| 							<td> | ||||
| 								<table border="0" cellborder="0" cellspacing="0" > | ||||
| 				""".formatted(element.name, element.name)); | ||||
| 		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; | ||||
| 			/* | ||||
| 			if (returnComplexModel != null) { | ||||
| 				data.append(returnComplexModel.replaceAll("(?m)^", "\t")); | ||||
| 				for (final ClassModel elem : interfaceElement.returnTypes) { | ||||
| 					zodImports.addAll(elem.getDependencyGroupModels()); | ||||
| 				} | ||||
| 			} | ||||
| 			*/ | ||||
| 			data.append("\t\t\t\t\t<tr><td  align=\"left\" port=\""); | ||||
| 			data.append(interfaceElement.name); | ||||
| 			data.append("\"><b> + "); | ||||
| 			data.append(interfaceElement.name); | ||||
| 			data.append("("); | ||||
| 			boolean hasParam = false; | ||||
| 			/* | ||||
| 			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(), dotGroup, imports, false)); | ||||
| 					data.append(","); | ||||
| 				} | ||||
| 				data.append("\n\t\t},"); | ||||
| 			} | ||||
| 			*/ | ||||
| 			/* fonctionnel mais trop de donnée | ||||
| 			if (!interfaceElement.parameters.isEmpty()) { | ||||
| 				//data.append("params: {"); | ||||
| 				for (final Entry<String, List<ClassModel>> paramEntry : interfaceElement.parameters.entrySet()) { | ||||
| 					data.append(""); | ||||
| 					data.append(paramEntry.getKey()); | ||||
| 					data.append(": "); | ||||
| 					data.append(generateClassModelsTypescript(paramEntry.getValue(), dotGroup, imports, false)); | ||||
| 					data.append(","); | ||||
| 				} | ||||
| 				//data.append("},"); | ||||
| 			} | ||||
| 			*/ | ||||
| 			if (interfaceElement.unnamedElement.size() == 1) { | ||||
| 				if (hasParam) { | ||||
| 					data.append(", "); | ||||
| 				} | ||||
| 				hasParam = true; | ||||
| 				data.append("data: "); | ||||
| 				data.append( | ||||
| 						generateClassModelTypescript(interfaceElement.unnamedElement.get(0), dotGroup, writeImports)); | ||||
| 			} else if (interfaceElement.multiPartParameters.size() != 0) { | ||||
| 				if (hasParam) { | ||||
| 					data.append(", "); | ||||
| 				} | ||||
| 				hasParam = true; | ||||
| 				boolean hasParam2 = false; | ||||
| 				data.append("data: {"); | ||||
| 				for (final Entry<String, List<ClassModel>> pathEntry : interfaceElement.multiPartParameters | ||||
| 						.entrySet()) { | ||||
| 					if (hasParam2) { | ||||
| 						data.append(", "); | ||||
| 					} | ||||
| 					hasParam2 = true; | ||||
| 					data.append(pathEntry.getKey()); | ||||
| 					data.append(": "); | ||||
| 					data.append(generateClassModelsTypescript(pathEntry.getValue(), dotGroup)); | ||||
| 				} | ||||
| 				data.append("}"); | ||||
| 			} | ||||
| 			data.append("): "); | ||||
| 			/* | ||||
| 			String tmp = DotClassElement.generateLocalModel( | ||||
| 					final String ModelName, | ||||
| 					final List<ClassModel> models, | ||||
| 					final DotClassElementGroup dotGroup) | ||||
| 					public static String generateClassModelsTypescript( | ||||
| 							final List<ClassModel> models, | ||||
| 							final DotClassElementGroup dotGroup, | ||||
| 							final Set<ClassModel> imports) throws IOException { | ||||
| 			*/ | ||||
| 			final String returnType = generateClassModelsTypescript(interfaceElement.returnTypes, dotGroup); | ||||
| 			data.append(returnType); | ||||
| 			final List<String> returnLinks = generateClassModelsLinks(interfaceElement.returnTypes, dotGroup); | ||||
| 			for (final String link : returnLinks) { | ||||
| 				outLinks.append("\t"); | ||||
| 				outLinks.append(element.name); | ||||
| 				outLinks.append(":"); | ||||
| 				outLinks.append(interfaceElement.name); | ||||
| 				outLinks.append(":e -> "); | ||||
| 				outLinks.append(link); | ||||
| 				outLinks.append(":NAME:w\n"); | ||||
| 			} | ||||
| 			data.append("</b>"); | ||||
| 			//data.append("<br align=\"left\"/>    "); | ||||
| 			data.append("</td></tr>\n\t\t\t\t\t\t\t<tr><td  align=\"left\">    "); | ||||
| 			/* | ||||
| 			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 { | ||||
| 					final String returnType = generateClassModelsTypescript(interfaceElement.returnTypes, dotGroup, | ||||
| 							imports, false); | ||||
| 					if (!"void".equals(returnType)) { | ||||
| 						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 DotClassElement retType = dotGroup.find(interfaceElement.returnTypes.get(0)); | ||||
| 				if (retType.dotCheckType != null) { | ||||
| 					data.append(", "); | ||||
| 					data.append(retType.dotCheckType); | ||||
| 					imports.add(interfaceElement.returnTypes.get(0)); | ||||
| 				} | ||||
| 			} | ||||
| 			*/ | ||||
| 			data.append("</td></tr>\n"); | ||||
| 		} | ||||
| 		/* | ||||
| 		data.append("\n}\n"); | ||||
|  | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
|  | ||||
| 		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 Set<String> finalImportSet = new TreeSet<>(); | ||||
|  | ||||
| 		for (final ClassModel model : imports) { | ||||
| 			final DotClassElement dotModel = dotGroup.find(model); | ||||
| 			if (dotModel.nativeType == DefinedPosition.NATIVE) { | ||||
| 				continue; | ||||
| 			} | ||||
| 			finalImportSet.add(dotModel.dotTypeName); | ||||
| 		} | ||||
| 		for (final ClassModel model : isImports) { | ||||
| 			final DotClassElement dotModel = dotGroup.find(model); | ||||
| 			if (dotModel.nativeType == DefinedPosition.NATIVE) { | ||||
| 				continue; | ||||
| 			} | ||||
| 			if (dotModel.dotCheckType != null) { | ||||
| 				finalImportSet.add(dotModel.dotCheckType); | ||||
| 			} | ||||
| 		} | ||||
| 		for (final ClassModel model : zodImports) { | ||||
| 			final DotClassElement dotModel = dotGroup.find(model); | ||||
| 			if (dotModel.nativeType == DefinedPosition.NATIVE) { | ||||
| 				continue; | ||||
| 			} | ||||
| 			finalImportSet.add("Zod" + dotModel.dotTypeName); | ||||
| 		} | ||||
| 		for (final ClassModel model : writeImports) { | ||||
| 			final DotClassElement dotModel = dotGroup.find(model); | ||||
| 			if (dotModel.nativeType == DefinedPosition.NATIVE) { | ||||
| 				continue; | ||||
| 			} | ||||
| 			finalImportSet.add(dotModel.dotTypeName + "Write"); | ||||
| 		} | ||||
|  | ||||
| 		if (finalImportSet.size() != 0) { | ||||
| 			out.append("import {"); | ||||
| 			for (final String elem : finalImportSet) { | ||||
| 				out.append("\n\t"); | ||||
| 				out.append(elem); | ||||
| 				out.append(","); | ||||
| 			} | ||||
| 			out.append("\n} from \"../model\";\n\n"); | ||||
| 		} | ||||
|  | ||||
| 		out.append(data.toString()); | ||||
| 		*/ | ||||
|  | ||||
| 		data.append(""" | ||||
| 									</table> | ||||
| 								</td> | ||||
| 							</tr> | ||||
| 						</table>> | ||||
| 					] | ||||
| 				"""); | ||||
| 		data.append(outLinks.toString()); | ||||
| 		return data.toString(); | ||||
| 	} | ||||
|  | ||||
| } | ||||
							
								
								
									
										485
									
								
								src/org/kar/archidata/externalRestApi/dot/DotClassElement.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										485
									
								
								src/org/kar/archidata/externalRestApi/dot/DotClassElement.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,485 @@ | ||||
| package org.kar.archidata.externalRestApi.dot; | ||||
|  | ||||
| import java.io.IOException; | ||||
| import java.util.List; | ||||
| import java.util.Map.Entry; | ||||
|  | ||||
| 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 DotClassElement { | ||||
| 	static final Logger LOGGER = LoggerFactory.getLogger(DotClassElement.class); | ||||
|  | ||||
| 	public enum DefinedPosition { | ||||
| 		NATIVE, // Native element of  dot language. | ||||
| 		BASIC, // basic wrapping for JAVA type. | ||||
| 		NORMAL // Normal Object to interpret. | ||||
| 	} | ||||
|  | ||||
| 	public List<ClassModel> models; | ||||
| 	public String zodName; | ||||
| 	public String dotTypeName; | ||||
| 	public String dotCheckType; | ||||
| 	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 DotClassElement(final List<ClassModel> model, final String zodName, final String dotTypeName, | ||||
| 			final String dotCheckType, final String declaration, final DefinedPosition nativeType) { | ||||
| 		this.models = model; | ||||
| 		this.zodName = zodName; | ||||
| 		this.dotTypeName = dotTypeName; | ||||
| 		this.declaration = declaration; | ||||
| 		this.nativeType = nativeType; | ||||
| 	} | ||||
|  | ||||
| 	public DotClassElement(final ClassModel model) { | ||||
| 		this.models = List.of(model); | ||||
| 		this.dotTypeName = model.getOriginClasses().getSimpleName(); | ||||
| 		this.declaration = null; | ||||
| 	} | ||||
|  | ||||
| 	public boolean isCompatible(final ClassModel model) { | ||||
| 		return this.models.contains(model); | ||||
| 	} | ||||
|  | ||||
| 	public String generateEnum(final ClassEnumModel model, final DotClassElementGroup dotGroup) throws IOException { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		out.append(""" | ||||
| 					%s [ | ||||
| 						shape=plain | ||||
| 						label=<<table color="#33FF33" border="2" cellborder="1" cellspacing="0" cellpadding="4"> | ||||
| 							<tr> | ||||
| 								<td port="NAME"><b>%s</b><br/>(ENUM)</td> | ||||
| 							</tr> | ||||
| 							<tr> | ||||
| 								<td> | ||||
| 									<table border="0" cellborder="0" cellspacing="0" > | ||||
| 				""".formatted(this.dotTypeName, this.dotTypeName)); | ||||
| 		final boolean first = true; | ||||
| 		for (final Entry<String, Object> elem : model.getListOfValues().entrySet()) { | ||||
| 			out.append("\t\t\t\t\t\t<tr><td  align=\"left\"><b> + "); | ||||
| 			out.append(elem.getKey()); | ||||
| 			out.append("</b> = "); | ||||
| 			if (elem.getValue() instanceof final Integer value) { | ||||
| 				out.append(value); | ||||
| 			} else { | ||||
| 				out.append("'"); | ||||
| 				out.append(elem.getValue()); | ||||
| 				out.append("'"); | ||||
| 			} | ||||
| 			out.append("</td></tr>\n"); | ||||
| 		} | ||||
| 		out.append(""" | ||||
| 									</table> | ||||
| 								</td> | ||||
| 							</tr> | ||||
| 						</table>> | ||||
| 					] | ||||
| 				"""); | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public String generateImporDot(final List<ClassModel> depModels, final DotClassElementGroup dotGroup) | ||||
| 			throws IOException { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		for (final ClassModel depModel : depModels) { | ||||
| 			final DotClassElement dotModel = dotGroup.find(depModel); | ||||
| 			if (dotModel.nativeType != DefinedPosition.NATIVE) { | ||||
| 				out.append("import {"); | ||||
| 				out.append(dotModel.zodName); | ||||
| 				out.append("} from \"./"); | ||||
| 				out.append(dotModel.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) { | ||||
| 		// Common checking element (apply to List, Map, ...) | ||||
| 		if (field.nullable()) { | ||||
| 			return ".optional()"; | ||||
| 		} | ||||
| 		if (field.notNull()) { | ||||
| 			return ""; | ||||
| 		} | ||||
| 		// Other object: | ||||
| 		if (field.model().getOriginClasses() == null || field.model().getOriginClasses().isPrimitive()) { | ||||
| 			return ""; | ||||
| 		} | ||||
| 		if (field.columnNotNull()) { | ||||
| 			return ""; | ||||
| 		} | ||||
| 		return ".optional()"; | ||||
| 	} | ||||
|  | ||||
| 	public String maxSizeZod(final FieldProperty field) { | ||||
| 		final StringBuilder builder = new StringBuilder(); | ||||
| 		final Class<?> clazz = field.model().getOriginClasses(); | ||||
| 		if (clazz == String.class) { | ||||
| 			if (field.sizeMin() > 0) { | ||||
| 				builder.append(".min("); | ||||
| 				builder.append(field.sizeMin()); | ||||
| 				builder.append(")"); | ||||
| 			} | ||||
| 			if (field.sizeMax() > 0) { | ||||
| 				builder.append(".max("); | ||||
| 				builder.append(field.sizeMax()); | ||||
| 				builder.append(")"); | ||||
| 			} | ||||
| 		} | ||||
| 		if (clazz == short.class || clazz == Short.class || clazz == int.class || clazz == Integer.class | ||||
| 				|| clazz == long.class || clazz == Long.class || clazz == float.class || clazz == Float.class | ||||
| 				|| clazz == double.class || clazz == Double.class) { | ||||
| 			if (field.min() != null && field.min() > 0) { | ||||
| 				builder.append(".min("); | ||||
| 				builder.append(field.min()); | ||||
| 				builder.append(")"); | ||||
| 			} | ||||
| 			if (field.max() != null && field.max() > 0) { | ||||
| 				builder.append(".max("); | ||||
| 				builder.append(field.max()); | ||||
| 				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(); | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public String convertHtml(final String data) { | ||||
| 		return data.replace("<", "<").replace(">", ">"); | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassModelTypescript(final ClassModel model, final DotClassElementGroup dotGroup) | ||||
| 			throws IOException { | ||||
| 		if (model instanceof ClassEnumModel) { | ||||
| 			final DotClassElement dotFieldModel = dotGroup.find(model); | ||||
| 			return dotFieldModel.dotTypeName; | ||||
| 		} else if (model instanceof ClassObjectModel) { | ||||
| 			final DotClassElement dotFieldModel = dotGroup.find(model); | ||||
| 			return dotFieldModel.dotTypeName; | ||||
| 		} else if (model instanceof final ClassListModel fieldListModel) { | ||||
| 			return generateDotList(fieldListModel, dotGroup); | ||||
| 		} else if (model instanceof final ClassMapModel fieldMapModel) { | ||||
| 			return generateDotMap(fieldMapModel, dotGroup); | ||||
| 		} | ||||
| 		throw new IOException("Impossible model:" + model); | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassModelTypescriptLink(final ClassModel model, final DotClassElementGroup dotGroup) | ||||
| 			throws IOException { | ||||
| 		if (model instanceof ClassEnumModel) { | ||||
| 			final DotClassElement dotFieldModel = dotGroup.find(model); | ||||
| 			return dotFieldModel.dotTypeName; | ||||
| 		} else if (model instanceof ClassObjectModel) { | ||||
| 			final DotClassElement dotFieldModel = dotGroup.find(model); | ||||
| 			if (dotFieldModel.nativeType == DefinedPosition.NORMAL) { | ||||
| 				return dotFieldModel.dotTypeName; | ||||
| 			} | ||||
| 		} else if (model instanceof final ClassListModel fieldListModel) { | ||||
| 			final String className = generateDotListClassName(fieldListModel, dotGroup); | ||||
| 			if (className != null) { | ||||
| 				return className; | ||||
| 			} | ||||
| 		} else if (model instanceof final ClassMapModel fieldMapModel) { | ||||
| 			final String className = generateDotMapClassName(fieldMapModel, dotGroup); | ||||
| 			if (className != null) { | ||||
| 				return className; | ||||
| 			} | ||||
| 		} | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	public String generateObject(final ClassObjectModel model, final DotClassElementGroup dotGroup) throws IOException { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		final StringBuilder outLinks = new StringBuilder(); | ||||
| 		out.append(""" | ||||
| 					%s [ | ||||
| 						shape=plain | ||||
| 						ranksep="2" | ||||
| 						label=<<table color="#000000" border="2" cellborder="1" cellspacing="0" cellpadding="4"> | ||||
| 							<tr> | ||||
| 								<td port="NAME"><b>%s</b></td> | ||||
| 							</tr> | ||||
| 							<tr> | ||||
| 								<td> | ||||
| 									<table border="0" cellborder="0" cellspacing="0" > | ||||
| 				""".formatted(this.dotTypeName, this.dotTypeName)); | ||||
| 		String inheritence = null; | ||||
| 		if (model.getExtendsClass() != null) { | ||||
| 			final ClassModel parentClass = model.getExtendsClass(); | ||||
| 			final DotClassElement dotParentModel = dotGroup.find(parentClass); | ||||
| 			inheritence = dotParentModel.dotTypeName; | ||||
| 		} | ||||
| 		if (model.getFields().size() == 0) { | ||||
| 			out.append("\t\t\t\t\t\t<tr><td> <i>(empty)</i> </td></tr>"); | ||||
| 		} | ||||
| 		for (final FieldProperty field : model.getFields()) { | ||||
| 			final ClassModel fieldModel = field.model(); | ||||
| 			if (field.comment() != null) { | ||||
| 				out.append("\t\t\t\t\t\t<tr><td  align=\"left\"><i> // "); | ||||
| 				out.append(convertHtml(field.comment())); | ||||
| 				out.append("</i></td></tr>\n"); | ||||
| 			} | ||||
| 			out.append("\t\t\t\t\t\t<tr><td  align=\"left\" port=\""); | ||||
| 			out.append(field.name()); | ||||
| 			out.append("\"><b> + "); | ||||
| 			out.append(field.name()); | ||||
| 			out.append("</b>: "); | ||||
|  | ||||
| 			out.append(generateClassModelTypescript(fieldModel, dotGroup)); | ||||
| 			final String remoteType = generateClassModelTypescriptLink(fieldModel, dotGroup); | ||||
| 			if (remoteType != null) { | ||||
| 				outLinks.append("\t"); | ||||
| 				outLinks.append(this.dotTypeName); | ||||
| 				outLinks.append(":"); | ||||
| 				outLinks.append(field.name()); | ||||
| 				outLinks.append(":e -> "); | ||||
| 				outLinks.append(remoteType); | ||||
| 				outLinks.append(":NAME:w\n"); | ||||
| 			} else if (field.linkClass() != null) { | ||||
| 				final String remoteLinkType = generateClassModelTypescriptLink(field.linkClass(), dotGroup); | ||||
| 				if (remoteLinkType != null) { | ||||
| 					outLinks.append("\t"); | ||||
| 					outLinks.append(this.dotTypeName); | ||||
| 					outLinks.append(":"); | ||||
| 					outLinks.append(field.name()); | ||||
| 					outLinks.append(":e -> "); | ||||
| 					outLinks.append(remoteLinkType); | ||||
| 					outLinks.append(":NAME:w\n"); | ||||
| 				} | ||||
| 			} | ||||
| 			out.append("</td></tr>\n"); | ||||
| 		} | ||||
| 		out.append(""" | ||||
| 									</table> | ||||
| 								</td> | ||||
| 							</tr> | ||||
| 						</table>> | ||||
| 					] | ||||
| 				"""); | ||||
| 		if (inheritence != null) { | ||||
| 			out.append("\tedge [dir=back arrowtail=empty arrowsize=2]\n"); | ||||
| 			out.append("\t"); | ||||
| 			out.append(inheritence); | ||||
| 			// heritage stop link on the "s" South | ||||
| 			out.append(":s -> "); | ||||
| 			out.append(this.dotTypeName); | ||||
| 			// heritage start link on the "n" North | ||||
| 			out.append(":n\n"); | ||||
| 		} | ||||
| 		if (!outLinks.isEmpty()) { | ||||
| 			out.append("\tedge [dir=back arrowtail=diamond arrowsize=2]\n"); | ||||
| 			//out.append("\tedge [arrowhead=diamond arrowsize=2]\n"); | ||||
| 			out.append(outLinks.toString()); | ||||
|  | ||||
| 		} | ||||
| 		return out.toString(); | ||||
|  | ||||
| 	} | ||||
|  | ||||
| 	private static String generateDotMap(final ClassMapModel model, final DotClassElementGroup dotGroup) { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		out.append("Map<"); | ||||
| 		if (model.keyModel instanceof final ClassListModel fieldListModel) { | ||||
| 			final String tmp = generateDotList(fieldListModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} else if (model.keyModel instanceof final ClassMapModel fieldMapModel) { | ||||
| 			final String tmp = generateDotMap(fieldMapModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} else if (model.keyModel instanceof final ClassObjectModel fieldObjectModel) { | ||||
| 			final String tmp = generateDotObject(fieldObjectModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} else if (model.keyModel instanceof final ClassEnumModel fieldEnumModel) { | ||||
| 			final String tmp = generateDotEnum(fieldEnumModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} | ||||
| 		out.append(", "); | ||||
| 		if (model.valueModel instanceof final ClassListModel fieldListModel) { | ||||
| 			final String tmp = generateDotList(fieldListModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} else if (model.valueModel instanceof final ClassMapModel fieldMapModel) { | ||||
| 			final String tmp = generateDotMap(fieldMapModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} else if (model.valueModel instanceof final ClassObjectModel fieldObjectModel) { | ||||
| 			final String tmp = generateDotObject(fieldObjectModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} else if (model.valueModel instanceof final ClassEnumModel fieldEnumModel) { | ||||
| 			final String tmp = generateDotEnum(fieldEnumModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} | ||||
| 		out.append(">"); | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	private static String generateDotEnum(final ClassEnumModel model, final DotClassElementGroup dotGroup) { | ||||
| 		final DotClassElement dotParentModel = dotGroup.find(model); | ||||
| 		return dotParentModel.dotTypeName; | ||||
| 	} | ||||
|  | ||||
| 	private static String generateDotObject(final ClassObjectModel model, final DotClassElementGroup dotGroup) { | ||||
| 		final DotClassElement dotParentModel = dotGroup.find(model); | ||||
| 		return dotParentModel.dotTypeName; | ||||
| 	} | ||||
|  | ||||
| 	private static String generateDotObjectClassName( | ||||
| 			final ClassObjectModel model, | ||||
| 			final DotClassElementGroup dotGroup) { | ||||
| 		final DotClassElement dotParentModel = dotGroup.find(model); | ||||
| 		if (dotParentModel.nativeType == DefinedPosition.NORMAL) { | ||||
| 			return dotParentModel.dotTypeName; | ||||
| 		} | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	private static String generateDotListClassName(final ClassListModel model, final DotClassElementGroup dotGroup) { | ||||
| 		if (model.valueModel instanceof final ClassListModel fieldListModel) { | ||||
| 			return generateDotListClassName(fieldListModel, dotGroup); | ||||
| 		} else if (model.valueModel instanceof final ClassMapModel fieldMapModel) { | ||||
| 			return generateDotMapClassName(fieldMapModel, dotGroup); | ||||
| 		} else if (model.valueModel instanceof final ClassObjectModel fieldObjectModel) { | ||||
| 			return generateDotObjectClassName(fieldObjectModel, dotGroup); | ||||
| 		} | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	private static String generateDotMapClassName(final ClassMapModel model, final DotClassElementGroup dotGroup) { | ||||
| 		if (model.valueModel instanceof final ClassListModel fieldListModel) { | ||||
| 			return generateDotListClassName(fieldListModel, dotGroup); | ||||
| 		} else if (model.valueModel instanceof final ClassMapModel fieldMapModel) { | ||||
| 			return generateDotMapClassName(fieldMapModel, dotGroup); | ||||
| 		} else if (model.valueModel instanceof final ClassObjectModel fieldObjectModel) { | ||||
| 			return generateDotObjectClassName(fieldObjectModel, dotGroup); | ||||
| 		} else if (model.valueModel instanceof final ClassEnumModel fieldEnumModel) { | ||||
| 			return generateDotEnum(fieldEnumModel, dotGroup); | ||||
| 		} | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| 	private static String generateDotList(final ClassListModel model, final DotClassElementGroup dotGroup) { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		out.append("List<"); | ||||
| 		if (model.valueModel instanceof final ClassListModel fieldListModel) { | ||||
| 			final String tmp = generateDotList(fieldListModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} else if (model.valueModel instanceof final ClassMapModel fieldMapModel) { | ||||
| 			final String tmp = generateDotMap(fieldMapModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} else if (model.valueModel instanceof final ClassObjectModel fieldObjectModel) { | ||||
| 			final String tmp = generateDotObject(fieldObjectModel, dotGroup); | ||||
| 			out.append(tmp); | ||||
| 		} | ||||
| 		out.append(">"); | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public String generateFile(final DotClassElementGroup dotGroup) 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) { | ||||
| 			// nothing to do___ data = generateBaseObject(); | ||||
| 		} else if (model instanceof final ClassEnumModel modelEnum) { | ||||
| 			data = generateEnum(modelEnum, dotGroup); | ||||
| 		} else if (model instanceof final ClassObjectModel modelObject) { | ||||
| 			data = generateObject(modelObject, dotGroup); | ||||
| 		} | ||||
| 		return data; | ||||
| 	} | ||||
|  | ||||
| 	private static String generateLocalModelBase(final ClassModel model, final DotClassElementGroup dotGroup) | ||||
| 			throws IOException { | ||||
| 		if (model instanceof final ClassObjectModel objectModel) { | ||||
| 			return generateDotObject(objectModel, dotGroup); | ||||
| 		} | ||||
| 		if (model instanceof final ClassEnumModel enumModel) { | ||||
| 			return generateDotEnum(enumModel, dotGroup); | ||||
| 		} | ||||
| 		if (model instanceof final ClassListModel listModel) { | ||||
| 			return generateDotList(listModel, dotGroup); | ||||
| 		} | ||||
| 		if (model instanceof final ClassMapModel mapModel) { | ||||
| 			return generateDotMap(mapModel, dotGroup); | ||||
| 		} | ||||
| 		return ""; | ||||
| 	} | ||||
|  | ||||
| 	public static String generateLocalModel( | ||||
| 			final String ModelName, | ||||
| 			final List<ClassModel> models, | ||||
| 			final DotClassElementGroup dotGroup) 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(); | ||||
| 		if (models.size() == 1) { | ||||
| 			out.append(generateLocalModelBase(models.get(0), dotGroup)); | ||||
| 		} else { | ||||
| 			out.append("Union<"); | ||||
| 			for (final ClassModel model : models) { | ||||
| 				out.append("\t"); | ||||
| 				out.append(generateLocalModelBase(models.get(0), dotGroup)); | ||||
| 				out.append(",\n"); | ||||
| 			} | ||||
| 			out.append(">"); | ||||
| 		} | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -0,0 +1,27 @@ | ||||
| package org.kar.archidata.externalRestApi.dot; | ||||
|  | ||||
| import java.util.List; | ||||
|  | ||||
| import org.kar.archidata.externalRestApi.model.ClassModel; | ||||
|  | ||||
| public class DotClassElementGroup { | ||||
| 	private final List<DotClassElement> dotElements; | ||||
|  | ||||
| 	public List<DotClassElement> getDotElements() { | ||||
| 		return this.dotElements; | ||||
| 	} | ||||
|  | ||||
| 	public DotClassElementGroup(final List<DotClassElement> tsElements) { | ||||
| 		this.dotElements = tsElements; | ||||
| 	} | ||||
|  | ||||
| 	public DotClassElement find(final ClassModel model) { | ||||
| 		for (final DotClassElement elem : this.dotElements) { | ||||
| 			if (elem.isCompatible(model)) { | ||||
| 				return elem; | ||||
| 			} | ||||
| 		} | ||||
| 		return null; | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -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); | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										176
									
								
								src/org/kar/archidata/externalRestApi/model/ApiModel.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										176
									
								
								src/org/kar/archidata/externalRestApi/model/ApiModel.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,176 @@ | ||||
| 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)); | ||||
| 				} | ||||
| 			} | ||||
| 			if (this.returnTypes.size() == 0) { | ||||
| 				this.produces.clear(); | ||||
| 			} | ||||
| 			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); | ||||
| 		} | ||||
| 		if (this.returnTypes.size() == 0) { | ||||
| 			this.produces.clear(); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	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) { | ||||
| 					final ClassModel modelGenerated = ClassModel.getModel(elem, previousModel); | ||||
| 					parameterModel.add(modelGenerated); | ||||
| 				} | ||||
| 			} 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) { | ||||
| 				if (!this.queries.containsKey(queryParam)) { | ||||
| 					this.queries.put(queryParam, parameterModel); | ||||
| 				} | ||||
| 			} else if (pathParam != null) { | ||||
| 				if (!this.parameters.containsKey(pathParam)) { | ||||
| 					this.parameters.put(pathParam, parameterModel); | ||||
| 				} | ||||
| 			} else if (formDataParam != null) { | ||||
| 				if (!this.multiPartParameters.containsKey(formDataParam)) { | ||||
| 					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); | ||||
| 		} | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										208
									
								
								src/org/kar/archidata/externalRestApi/model/ApiTool.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										208
									
								
								src/org/kar/archidata/externalRestApi/model/ApiTool.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,208 @@ | ||||
| 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 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; | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -0,0 +1,67 @@ | ||||
| package org.kar.archidata.externalRestApi.model; | ||||
|  | ||||
| import java.io.IOException; | ||||
| import java.lang.reflect.Method; | ||||
| import java.util.HashMap; | ||||
| import java.util.Map; | ||||
| import java.util.Set; | ||||
|  | ||||
| public class ClassEnumModel extends ClassModel { | ||||
|  | ||||
| 	protected ClassEnumModel(final Class<?> clazz) { | ||||
| 		this.originClasses = clazz; | ||||
| 		this.noWriteSpecificMode = true; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public String toString() { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		out.append("ClassEnumModel ["); | ||||
| 		out.append(this.originClasses.getCanonicalName()); | ||||
| 		out.append("]"); | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	final Map<String, Object> listOfValues = new HashMap<>(); | ||||
|  | ||||
| 	@Override | ||||
| 	public void analyze(final ModelGroup group) throws IOException { | ||||
| 		if (this.analyzeDone) { | ||||
| 			return; | ||||
| 		} | ||||
| 		this.analyzeDone = true; | ||||
| 		final Class<?> clazz = this.originClasses; | ||||
| 		final Object[] constants = clazz.getEnumConstants(); | ||||
|  | ||||
| 		// Try to get a get Value element to serialize: | ||||
| 		try { | ||||
| 			final Method getValueMethod = clazz.getMethod("getValue"); | ||||
| 			for (final Object constant : constants) { | ||||
| 				final String name = constant.toString(); | ||||
| 				final Object value = getValueMethod.invoke(constant); | ||||
| 				this.listOfValues.put(name, value); | ||||
| 			} | ||||
| 			return; | ||||
| 		} catch (final Exception e) { | ||||
| 			//e.printStackTrace(); | ||||
| 		} | ||||
|  | ||||
| 		for (final Object elem : constants) { | ||||
| 			this.listOfValues.put(elem.toString(), elem.toString()); | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	public Map<String, Object> getListOfValues() { | ||||
| 		return this.listOfValues; | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public Set<ClassModel> getAlls() { | ||||
| 		return Set.of(this); | ||||
| 	} | ||||
|  | ||||
| 	@Override | ||||
| 	public Set<ClassModel> getDependencyGroupModels() { | ||||
| 		return Set.of(this); | ||||
| 	} | ||||
| } | ||||
| @@ -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(); | ||||
| 	} | ||||
| } | ||||
| @@ -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; | ||||
| 	} | ||||
| } | ||||
							
								
								
									
										83
									
								
								src/org/kar/archidata/externalRestApi/model/ClassModel.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										83
									
								
								src/org/kar/archidata/externalRestApi/model/ClassModel.java
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,83 @@ | ||||
| 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 boolean noWriteSpecificMode = false; | ||||
| 	protected List<ClassModel> dependencyModels = new ArrayList<>(); | ||||
|  | ||||
| 	public Class<?> getOriginClasses() { | ||||
| 		return this.originClasses; | ||||
| 	} | ||||
|  | ||||
| 	public boolean isNoWriteSpecificMode() { | ||||
| 		return this.noWriteSpecificMode; | ||||
| 	} | ||||
|  | ||||
| 	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(); | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -0,0 +1,270 @@ | ||||
| package org.kar.archidata.externalRestApi.model; | ||||
|  | ||||
| import java.io.IOException; | ||||
| 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.kar.archidata.exception.DataAccessException; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import jakarta.persistence.ManyToMany; | ||||
| import jakarta.persistence.ManyToOne; | ||||
| import jakarta.persistence.OneToMany; | ||||
| import jakarta.validation.constraints.Size; | ||||
|  | ||||
| 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, | ||||
| 			ClassModel linkClass, // link class when use remote ID (ex: list<UUID>) | ||||
| 			String comment, | ||||
| 			int sizeMin, // String SizeMin | ||||
| 			int sizeMax, // String SizeMax | ||||
| 			Long min, // number min value | ||||
| 			Long max, // number max value | ||||
| 			Boolean readOnly, | ||||
| 			Boolean notNull, | ||||
| 			Boolean columnNotNull, | ||||
| 			Boolean nullable) { | ||||
|  | ||||
| 		public FieldProperty(final String name, final ClassModel model, final ClassModel linkClass, | ||||
| 				final String comment, final int sizeMin, final int sizeMax, final Long min, final Long max, | ||||
| 				final Boolean readOnly, final Boolean notNull, final Boolean columnNotNull, final Boolean nullable) { | ||||
| 			this.name = name; | ||||
| 			this.model = model; | ||||
| 			this.linkClass = linkClass; | ||||
| 			this.comment = comment; | ||||
| 			this.sizeMin = sizeMin; | ||||
| 			this.sizeMax = sizeMax; | ||||
| 			this.min = min; | ||||
| 			this.max = max; | ||||
| 			this.readOnly = readOnly; | ||||
| 			this.notNull = notNull; | ||||
| 			this.columnNotNull = columnNotNull; | ||||
| 			this.nullable = nullable; | ||||
|  | ||||
| 		} | ||||
|  | ||||
| 		private static int getStringMinSize(final Field field) throws DataAccessException { | ||||
| 			final Size size = AnnotationTools.getConstraintsSize(field); | ||||
| 			return size != null ? size.min() : 0; | ||||
| 		} | ||||
|  | ||||
| 		private static int getStringMaxSize(final Field field) throws DataAccessException { | ||||
| 			final Size size = AnnotationTools.getConstraintsSize(field); | ||||
| 			final int colomnLimitSize = AnnotationTools.getLimitSize(field); | ||||
| 			return size == null ? colomnLimitSize : colomnLimitSize < size.max() ? colomnLimitSize : size.max(); | ||||
| 		} | ||||
|  | ||||
| 		private static Class<?> getSubModelIfExist2(final Field field) { | ||||
| 			final ManyToOne manyToOne = AnnotationTools.getManyToOne(field); | ||||
| 			if (manyToOne != null) { | ||||
| 				if (manyToOne.targetEntity() != null && manyToOne.targetEntity() != void.class) { | ||||
| 					return manyToOne.targetEntity(); | ||||
| 				} | ||||
| 				return null; | ||||
| 			} | ||||
| 			final ManyToMany manyToMany = AnnotationTools.getManyToMany(field); | ||||
| 			if (manyToMany != null) { | ||||
| 				if (manyToMany.targetEntity() != null && manyToMany.targetEntity() != void.class) { | ||||
| 					return manyToMany.targetEntity(); | ||||
| 				} | ||||
| 				return null; | ||||
| 			} | ||||
| 			final OneToMany oneToMany = AnnotationTools.getOneToMany(field); | ||||
| 			if (oneToMany != null) { | ||||
| 				if (oneToMany.targetEntity() != null && oneToMany.targetEntity() != void.class) { | ||||
| 					return oneToMany.targetEntity(); | ||||
| 				} | ||||
| 				return null; | ||||
| 			} | ||||
| 			return null; | ||||
| 		} | ||||
|  | ||||
| 		private static ClassModel getSubModelIfExist(final Field field, final ModelGroup previous) throws IOException { | ||||
| 			final Class<?> tmp = getSubModelIfExist2(field); | ||||
| 			if (tmp == null) { | ||||
| 				return null; | ||||
| 			} | ||||
| 			return ClassModel.getModel(tmp, previous); | ||||
| 		} | ||||
|  | ||||
| 		public FieldProperty(final Field field, final ModelGroup previous) throws DataAccessException, IOException { | ||||
| 			this(field.getName(), // | ||||
| 					ClassModel.getModel(field.getGenericType(), previous), // | ||||
| 					getSubModelIfExist(field, previous), // | ||||
| 					AnnotationTools.getComment(field), // | ||||
| 					getStringMinSize(field), // | ||||
| 					getStringMaxSize(field), // | ||||
| 					AnnotationTools.getConstraintsMin(field), // | ||||
| 					AnnotationTools.getConstraintsMax(field), // | ||||
| 					AnnotationTools.getSchemaReadOnly(field), // | ||||
| 					AnnotationTools.getConstraintsNotNull(field), // | ||||
| 					AnnotationTools.getColumnNotNull(field), // | ||||
| 					AnnotationTools.getNullable(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.noWriteSpecificMode = AnnotationTools.getNoWriteSpecificMode(clazz); | ||||
| 		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; | ||||
| 	} | ||||
|  | ||||
| } | ||||
							
								
								
									
										53
									
								
								src/org/kar/archidata/externalRestApi/model/ModelGroup.java
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										53
									
								
								src/org/kar/archidata/externalRestApi/model/ModelGroup.java
									
									
									
									
									
										Normal 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; | ||||
| 	} | ||||
| } | ||||
| @@ -0,0 +1,5 @@ | ||||
| package org.kar.archidata.externalRestApi.model; | ||||
|  | ||||
| public enum RestTypeRequest { | ||||
| 	GET, POST, PUT, PATCH, DELETE | ||||
| } | ||||
| @@ -0,0 +1,443 @@ | ||||
| package org.kar.archidata.externalRestApi.typescript; | ||||
|  | ||||
| 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 java.util.TreeSet; | ||||
|  | ||||
| import org.kar.archidata.dataAccess.DataExport; | ||||
| 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.kar.archidata.externalRestApi.typescript.TsClassElement.DefinedPosition; | ||||
| 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 Set<ClassModel> importWrite) 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 Set<ClassModel> importWrite) throws IOException { | ||||
| 		final TsClassElement tsModel = tsGroup.find(model); | ||||
| 		if (tsModel.nativeType != DefinedPosition.NATIVE) { | ||||
| 			if (importWrite == null || tsModel.models.get(0).isNoWriteSpecificMode()) { | ||||
| 				imports.add(model); | ||||
| 			} else { | ||||
| 				importWrite.add(model); | ||||
| 			} | ||||
| 		} | ||||
| 		if (tsModel.nativeType != DefinedPosition.NORMAL) { | ||||
| 			return tsModel.tsTypeName; | ||||
| 		} | ||||
| 		if (importWrite != null && !tsModel.models.get(0).isNoWriteSpecificMode()) { | ||||
| 			return tsModel.tsTypeName + "Write"; | ||||
| 		} | ||||
| 		return tsModel.tsTypeName; | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassMapModelTypescript( | ||||
| 			final ClassMapModel model, | ||||
| 			final TsClassElementGroup tsGroup, | ||||
| 			final Set<ClassModel> imports, | ||||
| 			final Set<ClassModel> importWrite) throws IOException { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		out.append("{[key: "); | ||||
| 		out.append(generateClassModelTypescript(model.keyModel, tsGroup, imports, importWrite)); | ||||
| 		out.append("]: "); | ||||
| 		out.append(generateClassModelTypescript(model.valueModel, tsGroup, imports, importWrite)); | ||||
| 		out.append(";}"); | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassListModelTypescript( | ||||
| 			final ClassListModel model, | ||||
| 			final TsClassElementGroup tsGroup, | ||||
| 			final Set<ClassModel> imports, | ||||
| 			final Set<ClassModel> importWrite) throws IOException { | ||||
| 		final StringBuilder out = new StringBuilder(); | ||||
| 		out.append(generateClassModelTypescript(model.valueModel, tsGroup, imports, importWrite)); | ||||
| 		out.append("[]"); | ||||
| 		return out.toString(); | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassModelTypescript( | ||||
| 			final ClassModel model, | ||||
| 			final TsClassElementGroup tsGroup, | ||||
| 			final Set<ClassModel> imports, | ||||
| 			final Set<ClassModel> importWrite) throws IOException { | ||||
| 		if (model instanceof final ClassObjectModel objectModel) { | ||||
| 			return generateClassObjectModelTypescript(objectModel, tsGroup, imports, importWrite); | ||||
| 		} | ||||
| 		if (model instanceof final ClassListModel listModel) { | ||||
| 			return generateClassListModelTypescript(listModel, tsGroup, imports, importWrite); | ||||
| 		} | ||||
| 		if (model instanceof final ClassMapModel mapModel) { | ||||
| 			return generateClassMapModelTypescript(mapModel, tsGroup, imports, importWrite); | ||||
| 		} | ||||
| 		if (model instanceof final ClassEnumModel enumModel) { | ||||
| 			return generateClassEnumModelTypescript(enumModel, tsGroup, imports, importWrite); | ||||
| 		} | ||||
| 		throw new IOException("Impossible model:" + model); | ||||
| 	} | ||||
|  | ||||
| 	public static String generateClassModelsTypescript( | ||||
| 			final List<ClassModel> models, | ||||
| 			final TsClassElementGroup tsGroup, | ||||
| 			final Set<ClassModel> imports, | ||||
| 			final Set<ClassModel> importWrite) 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, importWrite); | ||||
| 			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\tcallbacks,"); | ||||
| 			} | ||||
| 			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, null)); | ||||
| 					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, null)); | ||||
| 					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, imports, | ||||
| 						writeImports)); | ||||
| 				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, imports, writeImports)); | ||||
| 					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\tcallbacks?: 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, | ||||
| 						null); | ||||
| 				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 { | ||||
| 					final String returnType = generateClassModelsTypescript(interfaceElement.returnTypes, tsGroup, | ||||
| 							imports, null); | ||||
| 					if (!"void".equals(returnType)) { | ||||
| 						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\tcallbacks,"); | ||||
| 			} | ||||
| 			data.append("\n\t\t}"); | ||||
| 			if (returnComplexModel != null) { | ||||
| 				data.append(", is"); | ||||
| 				data.append(returnModelNameIfComplex); | ||||
| 			} else { | ||||
| 				final TsClassElement retType = tsGroup.find(interfaceElement.returnTypes.get(0)); | ||||
| 				if (retType.tsCheckType != null) { | ||||
| 					data.append(", "); | ||||
| 					data.append(retType.tsCheckType); | ||||
| 					imports.add(interfaceElement.returnTypes.get(0)); | ||||
| 				} | ||||
| 			} | ||||
| 			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 Set<String> finalImportSet = new TreeSet<>(); | ||||
|  | ||||
| 		for (final ClassModel model : imports) { | ||||
| 			final TsClassElement tsModel = tsGroup.find(model); | ||||
| 			if (tsModel.nativeType == DefinedPosition.NATIVE) { | ||||
| 				continue; | ||||
| 			} | ||||
| 			finalImportSet.add(tsModel.tsTypeName); | ||||
| 		} | ||||
| 		for (final ClassModel model : isImports) { | ||||
| 			final TsClassElement tsModel = tsGroup.find(model); | ||||
| 			if (tsModel.nativeType == DefinedPosition.NATIVE) { | ||||
| 				continue; | ||||
| 			} | ||||
| 			if (tsModel.tsCheckType != null) { | ||||
| 				finalImportSet.add(tsModel.tsCheckType); | ||||
| 			} | ||||
| 		} | ||||
| 		for (final ClassModel model : zodImports) { | ||||
| 			final TsClassElement tsModel = tsGroup.find(model); | ||||
| 			if (tsModel.nativeType == DefinedPosition.NATIVE) { | ||||
| 				continue; | ||||
| 			} | ||||
| 			finalImportSet.add("Zod" + tsModel.tsTypeName); | ||||
| 		} | ||||
| 		for (final ClassModel model : writeImports) { | ||||
| 			final TsClassElement tsModel = tsGroup.find(model); | ||||
| 			if (tsModel.nativeType == DefinedPosition.NATIVE) { | ||||
| 				continue; | ||||
| 			} | ||||
| 			finalImportSet.add(tsModel.tsTypeName + "Write"); | ||||
| 		} | ||||
|  | ||||
| 		if (finalImportSet.size() != 0) { | ||||
| 			out.append("import {"); | ||||
| 			for (final String elem : finalImportSet) { | ||||
| 				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(); | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -0,0 +1,590 @@ | ||||
| package org.kar.archidata.externalRestApi.typescript; | ||||
|  | ||||
| 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 java.util.Map.Entry; | ||||
|  | ||||
| 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 Entry<String, Object> elem : model.getListOfValues().entrySet()) { | ||||
| 				if (!first) { | ||||
| 					out.append(",\n\t"); | ||||
| 				} else { | ||||
| 					out.append("\n\t"); | ||||
| 					first = false; | ||||
| 				} | ||||
| 				out.append("'"); | ||||
| 				out.append(elem.getKey()); | ||||
| 				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 Entry<String, Object> elem : model.getListOfValues().entrySet()) { | ||||
| 				if (!first) { | ||||
| 					out.append(",\n\t"); | ||||
| 				} else { | ||||
| 					out.append("\n\t"); | ||||
| 					first = false; | ||||
| 				} | ||||
| 				out.append(elem.getKey()); | ||||
| 				out.append(" = "); | ||||
| 				if (elem.getValue() instanceof final Integer value) { | ||||
| 					out.append(value); | ||||
| 				} else { | ||||
| 					out.append("'"); | ||||
| 					out.append(elem.getValue()); | ||||
| 					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); | ||||
| 				if (tsModel.nativeType == DefinedPosition.NORMAL && !(tsModel.models.get(0).isNoWriteSpecificMode())) { | ||||
| 					out.append(", "); | ||||
| 					out.append(tsModel.zodName); | ||||
| 					out.append("Write "); | ||||
| 				} | ||||
| 				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 boolean isOptionalTypeZod(final FieldProperty field) { | ||||
| 		// Common checking element (apply to List, Map, ...) | ||||
| 		if (field.nullable()) { | ||||
| 			return true; | ||||
| 		} | ||||
| 		if (field.notNull()) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		// Other object: | ||||
| 		if (field.model().getOriginClasses() == null || field.model().getOriginClasses().isPrimitive()) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		if (field.columnNotNull()) { | ||||
| 			return false; | ||||
| 		} | ||||
| 		return true; | ||||
| 	} | ||||
|  | ||||
| 	public String optionalTypeZod(final FieldProperty field) { | ||||
| 		// Common checking element (apply to List, Map, ...) | ||||
| 		if (isOptionalTypeZod(field)) { | ||||
| 			return ".optional()"; | ||||
| 		} | ||||
| 		return ""; | ||||
| 	} | ||||
|  | ||||
| 	public String optionalWriteTypeZod(final FieldProperty field) { | ||||
| 		// Common checking element (apply to List, Map, ...) | ||||
| 		if (isOptionalTypeZod(field)) { | ||||
| 			return ".nullable()"; | ||||
| 		} | ||||
| 		return ""; | ||||
| 	} | ||||
|  | ||||
| 	public String maxSizeZod(final FieldProperty field) { | ||||
| 		final StringBuilder builder = new StringBuilder(); | ||||
| 		final Class<?> clazz = field.model().getOriginClasses(); | ||||
| 		if (clazz == String.class) { | ||||
| 			if (field.sizeMin() > 0) { | ||||
| 				builder.append(".min("); | ||||
| 				builder.append(field.sizeMin()); | ||||
| 				builder.append(")"); | ||||
| 			} | ||||
| 			if (field.sizeMax() > 0) { | ||||
| 				builder.append(".max("); | ||||
| 				builder.append(field.sizeMax()); | ||||
| 				builder.append(")"); | ||||
| 			} | ||||
| 		} | ||||
| 		if (clazz == short.class || clazz == Short.class || clazz == int.class || clazz == Integer.class | ||||
| 				|| clazz == long.class || clazz == Long.class || clazz == float.class || clazz == Float.class | ||||
| 				|| clazz == double.class || clazz == Double.class) { | ||||
| 			if (field.min() != null && field.min() > 0) { | ||||
| 				builder.append(".min("); | ||||
| 				builder.append(field.min()); | ||||
| 				builder.append(")"); | ||||
| 			} | ||||
| 			if (field.max() != null && field.max() > 0) { | ||||
| 				builder.append(".max("); | ||||
| 				builder.append(field.max()); | ||||
| 				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"); | ||||
| 		// ------------------------------------------------------------------------ | ||||
| 		// -- Generate read mode | ||||
| 		// ------------------------------------------------------------------------ | ||||
| 		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("")); | ||||
| 		// check if we need to generate write mode : | ||||
| 		if (!model.isNoWriteSpecificMode()) { | ||||
| 			// ------------------------------------------------------------------------ | ||||
| 			// -- Generate write mode | ||||
| 			// ------------------------------------------------------------------------ | ||||
| 			//out.append(generateComment(model)); | ||||
| 			out.append("export const "); | ||||
| 			out.append(this.zodName); | ||||
| 			out.append("Write = "); | ||||
|  | ||||
| 			if (model.getExtendsClass() != null) { | ||||
| 				final ClassModel parentClass = model.getExtendsClass(); | ||||
| 				final TsClassElement tsParentModel = tsGroup.find(parentClass); | ||||
| 				out.append(tsParentModel.zodName); | ||||
| 				out.append("Write"); | ||||
| 				out.append(".extend({"); | ||||
| 			} else { | ||||
| 				out.append("zod.object({"); | ||||
| 			} | ||||
| 			out.append("\n"); | ||||
| 			for (final FieldProperty field : model.getFields()) { | ||||
| 				// remove all readOnly field | ||||
| 				if (field.readOnly()) { | ||||
| 					continue; | ||||
| 				} | ||||
| 				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(optionalWriteTypeZod(field)); | ||||
| 				// all write field are optional | ||||
| 				if (field.model() instanceof final ClassObjectModel plop) { | ||||
| 					if (!plop.isPrimitive()) { | ||||
| 						out.append(".optional()"); | ||||
| 					} | ||||
| 				} else { | ||||
| 					out.append(".optional()"); | ||||
| 				} | ||||
| 				out.append(",\n"); | ||||
| 			} | ||||
| 			out.append("\n});\n"); | ||||
| 			out.append(generateZodInfer(this.tsTypeName + "Write", this.zodName + "Write")); | ||||
| 			// Check only the input value ==> no need of the output | ||||
| 			out.append(generateExportCheckFunctionWrite("Write")); | ||||
| 			// 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"); | ||||
| 			*/ | ||||
| 		} | ||||
| 		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.createDirectories(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(); | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -0,0 +1,27 @@ | ||||
| package org.kar.archidata.externalRestApi.typescript; | ||||
|  | ||||
| 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; | ||||
| 	} | ||||
|  | ||||
| } | ||||
| @@ -14,6 +14,8 @@ import org.kar.archidata.migration.model.Migration; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
|  | ||||
| import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; | ||||
|  | ||||
| public class MigrationEngine { | ||||
| 	final static Logger LOGGER = LoggerFactory.getLogger(MigrationEngine.class); | ||||
|  | ||||
| @@ -103,6 +105,8 @@ public class MigrationEngine { | ||||
| 	/** Process the automatic migration of the system | ||||
| 	 * @param config SQL connection for the migration | ||||
| 	 * @throws IOException Error if access on the DB */ | ||||
| 	@SuppressFBWarnings({ "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING", | ||||
| 			"SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE" }) | ||||
| 	public void migrateErrorThrow(final DBConfig config) throws MigrationException { | ||||
| 		LOGGER.info("Execute migration ... [BEGIN]"); | ||||
| 		// check the integrity of the migrations: | ||||
| @@ -318,12 +322,12 @@ public class MigrationEngine { | ||||
| 		boolean find = false; | ||||
| 		for (int iii = this.datas.size() - 1; iii >= 0; iii--) { | ||||
| 			if (!find) { | ||||
| 				if (this.datas.get(iii).getName() == currentVersion.name) { | ||||
| 				if (this.datas.get(iii).getName().equals(currentVersion.name)) { | ||||
| 					find = true; | ||||
| 				} | ||||
| 				continue; | ||||
| 			} | ||||
| 			if (this.datas.get(iii).getName() == currentVersion.name) { | ||||
| 			if (this.datas.get(iii).getName().equals(currentVersion.name)) { | ||||
| 				break; | ||||
| 			} | ||||
| 			toApply.add(this.datas.get(iii)); | ||||
|   | ||||
| @@ -4,8 +4,8 @@ import org.kar.archidata.annotation.DataDeleted; | ||||
| import org.kar.archidata.annotation.DataNotRead; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.media.Schema; | ||||
| import jakarta.annotation.Nullable; | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.validation.constraints.NotNull; | ||||
| import jakarta.ws.rs.DefaultValue; | ||||
|  | ||||
| public class GenericDataSoftDelete extends GenericData { | ||||
| @@ -13,7 +13,7 @@ public class GenericDataSoftDelete extends GenericData { | ||||
| 	@Column(nullable = false) | ||||
| 	@DefaultValue("'0'") | ||||
| 	@DataDeleted | ||||
| 	@NotNull | ||||
| 	@Schema(description = "Deleted state", hidden = true, required = false, readOnly = true) | ||||
| 	@Nullable | ||||
| 	public Boolean deleted = null; | ||||
| } | ||||
|   | ||||
| @@ -9,23 +9,23 @@ import org.kar.archidata.annotation.UpdateTimestamp; | ||||
| import com.fasterxml.jackson.annotation.JsonFormat; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.media.Schema; | ||||
| import jakarta.annotation.Nullable; | ||||
| 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") | ||||
| 	@Nullable | ||||
| 	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; | ||||
| 	@Nullable | ||||
| 	public Date updatedAt = null; | ||||
| } | ||||
|   | ||||
| @@ -4,6 +4,7 @@ import java.sql.Timestamp; | ||||
|  | ||||
| import org.kar.archidata.annotation.DataIfNotExists; | ||||
|  | ||||
| import com.fasterxml.jackson.annotation.JsonFormat; | ||||
| import com.fasterxml.jackson.annotation.JsonInclude; | ||||
|  | ||||
| import jakarta.persistence.Column; | ||||
| @@ -18,6 +19,7 @@ public class GenericToken extends GenericDataSoftDelete { | ||||
| 	@Column(nullable = false, length = 0) | ||||
| 	public String name; | ||||
| 	@Column(nullable = false) | ||||
| 	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") | ||||
| 	public Timestamp endValidityTime = null; | ||||
| 	@Column(nullable = false, length = 0) | ||||
| 	public String token; | ||||
|   | ||||
| @@ -9,6 +9,10 @@ public class GetToken { | ||||
| 	@Column(length = -1, nullable = false) | ||||
| 	public String jwt; | ||||
|  | ||||
| 	public GetToken() { | ||||
|  | ||||
| 	} | ||||
|  | ||||
| 	public GetToken(final String jwt) { | ||||
| 		this.jwt = jwt; | ||||
| 	} | ||||
|   | ||||
| @@ -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; | ||||
| } | ||||
|   | ||||
| @@ -4,8 +4,8 @@ import org.kar.archidata.annotation.DataDeleted; | ||||
| import org.kar.archidata.annotation.DataNotRead; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.media.Schema; | ||||
| import jakarta.annotation.Nullable; | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.validation.constraints.NotNull; | ||||
| import jakarta.ws.rs.DefaultValue; | ||||
|  | ||||
| public class UUIDGenericDataSoftDelete extends UUIDGenericData { | ||||
| @@ -13,7 +13,7 @@ public class UUIDGenericDataSoftDelete extends UUIDGenericData { | ||||
| 	@Column(nullable = false) | ||||
| 	@DefaultValue("'0'") | ||||
| 	@DataDeleted | ||||
| 	@NotNull | ||||
| 	@Schema(description = "Deleted state", hidden = true, required = false, readOnly = true) | ||||
| 	@Nullable | ||||
| 	public Boolean deleted = null; | ||||
| } | ||||
|   | ||||
| @@ -16,14 +16,17 @@ CREATE TABLE `user` ( | ||||
|  | ||||
| import java.sql.Timestamp; | ||||
| import java.util.List; | ||||
| import java.util.UUID; | ||||
|  | ||||
| import org.kar.archidata.annotation.DataIfNotExists; | ||||
| import org.kar.archidata.annotation.DataJson; | ||||
|  | ||||
| import com.fasterxml.jackson.annotation.JsonFormat; | ||||
| import com.fasterxml.jackson.annotation.JsonInclude; | ||||
|  | ||||
| import io.swagger.v3.oas.annotations.media.Schema; | ||||
| import jakarta.annotation.Nullable; | ||||
| import jakarta.persistence.Column; | ||||
| import jakarta.persistence.FetchType; | ||||
| import jakarta.persistence.ManyToMany; | ||||
| import jakarta.persistence.Table; | ||||
| import jakarta.ws.rs.DefaultValue; | ||||
|  | ||||
| @@ -34,6 +37,7 @@ public class User extends GenericDataSoftDelete { | ||||
| 	@Column(length = 128) | ||||
| 	public String login = null; | ||||
|  | ||||
| 	@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") | ||||
| 	public Timestamp lastConnection = null; | ||||
| 	@DefaultValue("'0'") | ||||
| 	@Column(nullable = false) | ||||
| @@ -45,8 +49,10 @@ public class User extends GenericDataSoftDelete { | ||||
| 	@Column(nullable = false) | ||||
| 	public boolean removed = false; | ||||
|  | ||||
| 	@ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class) | ||||
| 	public List<Long> covers; | ||||
| 	@Schema(description = "List of Id of the specific covers") | ||||
| 	@DataJson(targetEntity = Data.class) | ||||
| 	@Nullable | ||||
| 	public List<UUID> covers; | ||||
|  | ||||
| 	@Override | ||||
| 	public String toString() { | ||||
|   | ||||
| @@ -22,7 +22,7 @@ public class UserByToken { | ||||
| 		final Object data = this.right.get(key); | ||||
| 		if (data instanceof final Boolean elem) { | ||||
| 			if (value instanceof final Boolean castVal) { | ||||
| 				if (elem == castVal) { | ||||
| 				if (elem.equals(castVal)) { | ||||
| 					return true; | ||||
| 				} | ||||
| 			} | ||||
| @@ -38,7 +38,7 @@ public class UserByToken { | ||||
| 		} | ||||
| 		if (data instanceof final Long elem) { | ||||
| 			if (value instanceof final Long castVal) { | ||||
| 				if (elem == castVal) { | ||||
| 				if (elem.equals(castVal)) { | ||||
| 					return true; | ||||
| 				} | ||||
| 			} | ||||
| @@ -46,7 +46,7 @@ public class UserByToken { | ||||
| 		} | ||||
| 		if (data instanceof final Double elem) { | ||||
| 			if (value instanceof final Double castVal) { | ||||
| 				if (elem == castVal) { | ||||
| 				if (elem.equals(castVal)) { | ||||
| 					return true; | ||||
| 				} | ||||
| 			} | ||||
|   | ||||
| @@ -22,6 +22,8 @@ import org.kar.archidata.dataAccess.QueryCondition; | ||||
| import org.kar.archidata.dataAccess.addOn.AddOnDataJson; | ||||
| import org.kar.archidata.dataAccess.options.Condition; | ||||
| import org.kar.archidata.dataAccess.options.ReadAllColumn; | ||||
| import org.kar.archidata.exception.FailException; | ||||
| import org.kar.archidata.exception.InputException; | ||||
| import org.kar.archidata.model.Data; | ||||
| import org.slf4j.Logger; | ||||
| import org.slf4j.LoggerFactory; | ||||
| @@ -214,25 +216,21 @@ public class DataTools { | ||||
| 		return data; | ||||
| 	} | ||||
|  | ||||
| 	public static <CLASS_TYPE, ID_TYPE> Response uploadCover( | ||||
| 	public static <CLASS_TYPE, ID_TYPE> void uploadCover( | ||||
| 			final Class<CLASS_TYPE> clazz, | ||||
| 			final ID_TYPE id, | ||||
| 			String fileName, | ||||
| 			final InputStream fileInputStream, | ||||
| 			final FormDataContentDisposition fileMetaData) { | ||||
| 		try { | ||||
| 			// correct input string stream : | ||||
| 			fileName = multipartCorrection(fileName); | ||||
|  | ||||
| 			final FormDataContentDisposition fileMetaData) throws Exception { | ||||
| 		// public NodeSmall uploadFile(final FormDataMultiPart form) { | ||||
| 		LOGGER.info("Upload media file: {}", fileMetaData); | ||||
| 		LOGGER.info("    - id: {}", id); | ||||
| 			LOGGER.info("    - file_name: ", fileName); | ||||
| 		LOGGER.info("    - file_name: {} ", fileMetaData.getFileName()); | ||||
| 		LOGGER.info("    - fileInputStream: {}", fileInputStream); | ||||
| 		LOGGER.info("    - fileMetaData: {}", fileMetaData); | ||||
| 		final CLASS_TYPE media = DataAccess.get(clazz, id); | ||||
| 		if (media == null) { | ||||
| 				return Response.notModified("Media Id does not exist or removed...").build(); | ||||
| 			throw new InputException(clazz.getCanonicalName(), | ||||
| 					"[" + id.toString() + "] Id does not exist or removed..."); | ||||
| 		} | ||||
|  | ||||
| 		final long tmpUID = getTmpDataId(); | ||||
| @@ -241,15 +239,15 @@ public class DataTools { | ||||
| 		if (data == null) { | ||||
| 			LOGGER.info("Need to add the data in the BDD ... "); | ||||
| 			try { | ||||
| 					data = createNewData(tmpUID, fileName, sha512); | ||||
| 				data = createNewData(tmpUID, fileMetaData.getFileName(), sha512); | ||||
| 			} catch (final IOException ex) { | ||||
| 				removeTemporaryFile(tmpUID); | ||||
| 					ex.printStackTrace(); | ||||
| 					return Response.notModified("can not create input media").build(); | ||||
| 				throw new FailException(Response.Status.NOT_MODIFIED, | ||||
| 						clazz.getCanonicalName() + "[" + id.toString() + "] can not create input media", ex); | ||||
| 			} catch (final SQLException ex) { | ||||
| 					ex.printStackTrace(); | ||||
| 				removeTemporaryFile(tmpUID); | ||||
| 					return Response.notModified("Error in SQL insertion ...").build(); | ||||
| 				throw new FailException(Response.Status.NOT_MODIFIED, | ||||
| 						clazz.getCanonicalName() + "[" + id.toString() + "] Error in SQL insertion", ex); | ||||
| 			} | ||||
| 		} else if (data.deleted) { | ||||
| 			LOGGER.error("Data already exist but deleted"); | ||||
| @@ -267,11 +265,5 @@ public class DataTools { | ||||
| 		} else { | ||||
| 			throw new IOException("Fail to add Cover can not detect type..."); | ||||
| 		} | ||||
| 			return Response.ok(DataAccess.get(clazz, id)).build(); | ||||
| 		} catch (final Exception ex) { | ||||
| 			System.out.println("Cat ann unexpected error ... "); | ||||
| 			ex.printStackTrace(); | ||||
| 		} | ||||
| 		return Response.serverError().build(); | ||||
| 	} | ||||
| } | ||||
|   | ||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user